From 5445b13f4e881bfac7d02cb5b8720f37f7ade401 Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Mon, 28 Aug 2023 11:14:57 -0400 Subject: [PATCH 01/84] empty files --- ipie/thermal/empty | 1 + ipie/thermal/propagation/empty | 1 + ipie/thermal/qmc/empty | 1 + ipie/thermal/trial/empty | 1 + ipie/thermal/walkers/empty | 1 + 5 files changed, 5 insertions(+) create mode 100644 ipie/thermal/empty create mode 100644 ipie/thermal/propagation/empty create mode 100644 ipie/thermal/qmc/empty create mode 100644 ipie/thermal/trial/empty create mode 100644 ipie/thermal/walkers/empty diff --git a/ipie/thermal/empty b/ipie/thermal/empty new file mode 100644 index 00000000..c6cac692 --- /dev/null +++ b/ipie/thermal/empty @@ -0,0 +1 @@ +empty diff --git a/ipie/thermal/propagation/empty b/ipie/thermal/propagation/empty new file mode 100644 index 00000000..c6cac692 --- /dev/null +++ b/ipie/thermal/propagation/empty @@ -0,0 +1 @@ +empty diff --git a/ipie/thermal/qmc/empty b/ipie/thermal/qmc/empty new file mode 100644 index 00000000..c6cac692 --- /dev/null +++ b/ipie/thermal/qmc/empty @@ -0,0 +1 @@ +empty diff --git a/ipie/thermal/trial/empty b/ipie/thermal/trial/empty new file mode 100644 index 00000000..c6cac692 --- /dev/null +++ b/ipie/thermal/trial/empty @@ -0,0 +1 @@ +empty diff --git a/ipie/thermal/walkers/empty b/ipie/thermal/walkers/empty new file mode 100644 index 00000000..c6cac692 --- /dev/null +++ b/ipie/thermal/walkers/empty @@ -0,0 +1 @@ +empty From 682cd3e703a03dc31a119a66157dd374328cb004 Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Mon, 28 Aug 2023 14:21:23 -0400 Subject: [PATCH 02/84] renaming empty to __init__.py --- ipie/thermal/{empty => __init__.py} | 0 ipie/thermal/propagation/{empty => __init__.py} | 0 ipie/thermal/qmc/{empty => __init__.py} | 0 ipie/thermal/trial/{empty => __init__.py} | 0 ipie/thermal/walkers/{empty => __init__.py} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename ipie/thermal/{empty => __init__.py} (100%) rename ipie/thermal/propagation/{empty => __init__.py} (100%) rename ipie/thermal/qmc/{empty => __init__.py} (100%) rename ipie/thermal/trial/{empty => __init__.py} (100%) rename ipie/thermal/walkers/{empty => __init__.py} (100%) diff --git a/ipie/thermal/empty b/ipie/thermal/__init__.py similarity index 100% rename from ipie/thermal/empty rename to ipie/thermal/__init__.py diff --git a/ipie/thermal/propagation/empty b/ipie/thermal/propagation/__init__.py similarity index 100% rename from ipie/thermal/propagation/empty rename to ipie/thermal/propagation/__init__.py diff --git a/ipie/thermal/qmc/empty b/ipie/thermal/qmc/__init__.py similarity index 100% rename from ipie/thermal/qmc/empty rename to ipie/thermal/qmc/__init__.py diff --git a/ipie/thermal/trial/empty b/ipie/thermal/trial/__init__.py similarity index 100% rename from ipie/thermal/trial/empty rename to ipie/thermal/trial/__init__.py diff --git a/ipie/thermal/walkers/empty b/ipie/thermal/walkers/__init__.py similarity index 100% rename from ipie/thermal/walkers/empty rename to ipie/thermal/walkers/__init__.py From 24109227f819a59419c77e85ca1c801ffd148214 Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Mon, 28 Aug 2023 23:29:19 -0400 Subject: [PATCH 03/84] adding ft_afqmc mpi test script --- ipie/qmc/tests/test_ft_mpi_integration.py | 121 ++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 ipie/qmc/tests/test_ft_mpi_integration.py diff --git a/ipie/qmc/tests/test_ft_mpi_integration.py b/ipie/qmc/tests/test_ft_mpi_integration.py new file mode 100644 index 00000000..411074f2 --- /dev/null +++ b/ipie/qmc/tests/test_ft_mpi_integration.py @@ -0,0 +1,121 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + +import json +import os +import sys +import tempfile +import uuid + +import numpy as np + +from ipie.analysis.extraction import extract_test_data_hdf5 +from ipie.config import MPI +from ipie.qmc.calc import get_driver, read_input + +_built_legacy = True + + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) +else: + test_id = None +test_id = comm.bcast(test_id, root=0) + +_data_dir = os.path.abspath(os.path.dirname(__file__)) + "/reference_data/" +_legacy_test_dirs = [ + "ft_4x4_hubbard_discrete", + "ft_ueg_ecut1.0_rs1.0", +] +_legacy_tests = [ + (_data_dir + d + "/input.json", _data_dir + d + "/reference.json") for d in _legacy_test_dirs +] + + +def compare_test_data(ref, test): + comparison = {} + for k, v in ref.items(): + if k == "sys_info": + continue + try: + comparison[k] = ( + np.array(ref[k]), + np.array(test[k]), + np.max(np.abs(np.array(ref[k]) - np.array(test[k]))) < 1e-10, + ) + except KeyError: + print(f"# Issue with test data key {k}") + return comparison + + +def run_test_system(input_file, benchmark_file, legacy_job=False): + comm = MPI.COMM_WORLD + input_dict = read_input(input_file, comm) + if input_dict["system"].get("integrals") is not None: + input_dict["system"]["integrals"] = input_file[:-10] + "afqmc.h5" + input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" + elif ("hamiltonian" in input_dict) and (input_dict["hamiltonian"].get("integrals") is not None): + input_dict["hamiltonian"]["integrals"] = input_file[:-10] + "afqmc.h5" + input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" + with tempfile.NamedTemporaryFile() as tmpf: + input_dict["estimators"]["filename"] = tmpf.name + if _built_legacy and legacy_job: + from ipie.legacy.qmc.calc import get_driver as get_legacy_driver + + input_dict["qmc"]["batched"] = False + afqmc = get_legacy_driver(input_dict, comm) + afqmc.run(comm=comm) + afqmc.finalise(comm) + else: + afqmc = get_driver(input_dict, comm) + afqmc.run(estimator_filename=tmpf.name) + afqmc.finalise() + if comm.rank == 0: + with open(benchmark_file, "r") as f: + ref_data = json.load(f) + skip_val = ref_data.get("extract_skip_value", 10) + test_data = extract_test_data_hdf5(tmpf.name, skip=skip_val) + comparison = compare_test_data(ref_data, test_data) + else: + comparison = None + comm.barrier() + comparison = comm.bcast(comparison) + return comparison + + +if __name__ == "__main__": + err_count = 0 + for test_name, (ind, outd) in zip(_legacy_test_dirs, _legacy_tests): + comparison = run_test_system(ind, outd, legacy_job=True) + local_err_count = 0 + if comm.rank == 0: + for k, v in comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f" *** FAILED *** : mismatch between benchmark and test run: {test_name}") + err_count += 1 + print(f"name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + else: + err_count = None + if local_err_count == 0 and comm.rank == 0: + print(f"*** PASSED : {test_name} ***") + err_count = comm.bcast(err_count) + sys.exit(err_count) From 4bb54057a52fe50e712f77776c9c9ac96d0deb52 Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Tue, 29 Aug 2023 12:05:13 -0400 Subject: [PATCH 04/84] creating estimators --- ipie/thermal/estimators/__init__.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 ipie/thermal/estimators/__init__.py diff --git a/ipie/thermal/estimators/__init__.py b/ipie/thermal/estimators/__init__.py new file mode 100644 index 00000000..e69de29b From a67b7598397a8e99b75d50bc67fd18ec2ee20b76 Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Tue, 29 Aug 2023 12:07:19 -0400 Subject: [PATCH 05/84] copying over relevant files for ft-afqmc --- ipie/thermal/estimators/thermal.py | 215 +++++++ ipie/thermal/propagation/__init__.py | 1 - ipie/thermal/propagation/continuous.py | 299 ++++++++++ ipie/thermal/propagation/generic.py | 167 ++++++ ipie/thermal/propagation/planewave.py | 723 ++++++++++++++++++++++++ ipie/thermal/qmc/__init__.py | 1 - ipie/thermal/qmc/thermal_afqmc.py | 382 +++++++++++++ ipie/thermal/trial/__init__.py | 1 - ipie/thermal/trial/chem_pot.py | 66 +++ ipie/thermal/trial/mean_field.py | 113 ++++ ipie/thermal/trial/onebody.py | 146 +++++ ipie/thermal/trial/utils.py | 39 ++ ipie/thermal/walkers/__init__.py | 1 - ipie/thermal/walkers/stack.py | 393 +++++++++++++ ipie/thermal/walkers/uhf_walkers.py | 738 +++++++++++++++++++++++++ 15 files changed, 3281 insertions(+), 4 deletions(-) create mode 100644 ipie/thermal/estimators/thermal.py create mode 100644 ipie/thermal/propagation/continuous.py create mode 100644 ipie/thermal/propagation/generic.py create mode 100644 ipie/thermal/propagation/planewave.py create mode 100644 ipie/thermal/qmc/thermal_afqmc.py create mode 100644 ipie/thermal/trial/chem_pot.py create mode 100644 ipie/thermal/trial/mean_field.py create mode 100644 ipie/thermal/trial/onebody.py create mode 100644 ipie/thermal/trial/utils.py create mode 100644 ipie/thermal/walkers/stack.py create mode 100644 ipie/thermal/walkers/uhf_walkers.py diff --git a/ipie/thermal/estimators/thermal.py b/ipie/thermal/estimators/thermal.py new file mode 100644 index 00000000..04526308 --- /dev/null +++ b/ipie/thermal/estimators/thermal.py @@ -0,0 +1,215 @@ +import numpy +import scipy.linalg + + +def fermi_factor(ek, beta, mu): + return 1.0 / (numpy.exp(beta * (ek - mu)) + 1.0) + + +def greens_function_unstable(A): + r"""Construct Green's function from density matrix. + + .. math:: + G_{ij} = \langle c_{i} c_j^{\dagger} \rangle \\ + = \left[\frac{1}{1+A}\right]_{ij} + + Parameters + ---------- + A : :class:`numpy.ndarray` + Density matrix (product of B matrices). + + Returns + ------- + G : :class:`numpy.ndarray` + Thermal Green's function. + """ + I = numpy.identity(A.shape[-1]) + return numpy.array([scipy.linalg.inv(I + A[0]), scipy.linalg.inv(I + A[1])]) + + +def greens_function(A): + r"""Construct Greens function from density matrix. + + .. math:: + G_{ij} = \langle c_{i} c_j^{\dagger} \rangle \\ + = \left[\frac{1}{1+A}\right]_{ij} + + Uses stable algorithm from White et al. (1988) + + Parameters + ---------- + A : :class:`numpy.ndarray` + Density matrix (product of B matrices). + + Returns + ------- + G : :class:`numpy.ndarray` + Thermal Green's function. + """ + G = numpy.zeros(A.shape, dtype=A.dtype) + (U1, S1, V1) = scipy.linalg.svd(A) + T = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) + (U2, S2, V2) = scipy.linalg.svd(T) + U3 = numpy.dot(U1, U2) + D3 = numpy.diag(1.0 / S2) + V3 = numpy.dot(V2, V1) + G = (V3.conj().T).dot(D3).dot(U3.conj().T) + return G + + +def inverse_greens_function(A): + """Inverse greens function from A""" + + Ginv = numpy.zeros(A.shape, dtype=A.dtype) + (U1, S1, V1) = scipy.linalg.svd(A) + T = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) + (U2, S2, V2) = scipy.linalg.svd(T) + U3 = numpy.dot(U1, U2) + D3 = numpy.diag(S2) + V3 = numpy.dot(V2, V1) + Ginv = (V3.conj().T).dot(D3).dot(U3.conj().T) + return Ginv + + +def inverse_greens_function_qr(A): + """Inverse greens function from A""" + + Ginv = numpy.zeros(A.shape, dtype=A.dtype) + + (U1, V1) = scipy.linalg.qr(A, pivoting=False) + V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0])) + T = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0]) + (U2, V2) = scipy.linalg.qr(T, pivoting=False) + U3 = numpy.dot(U1, U2) + V3 = numpy.dot(V2, V1) + Ginv = U3.dot(V3) + # (U1,S1,V1) = scipy.linalg.svd(A) + # T = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) + # (U2,S2,V2) = scipy.linalg.svd(T) + # U3 = numpy.dot(U1, U2) + # D3 = numpy.diag(S2) + # V3 = numpy.dot(V2, V1) + # Ginv = (V3.conj().T).dot(D3).dot(U3.conj().T) + return Ginv + + +def one_rdm(A): + r"""Compute one-particle reduced density matrix + + .. math:: + rho_{ij} = \langle c_{i}^{\dagger} c_{j} \rangle \\ + = 1 - G_{ji} + Parameters + ---------- + A : :class:`numpy.ndarray` + Density matrix (product of B matrices). + + Returns + ------- + P : :class:`numpy.ndarray` + Thermal 1RDM. + """ + I = numpy.identity(A.shape[-1]) + G = numpy.array([greens_function(A[0]), greens_function(A[1])]) + return numpy.array([I - G[0].T, I - G[1].T]) + + +def one_rdm_from_G(G): + r"""Compute one-particle reduced density matrix from Green's function. + + .. math:: + rho_{ij} = \langle c_{i}^{\dagger} c_{j} \rangle \\ + = 1 - G_{ji} + Parameters + ---------- + G : :class:`numpy.ndarray` + Thermal Green's function. + + Returns + ------- + P : :class:`numpy.ndarray` + Thermal 1RDM. + """ + I = numpy.identity(G.shape[-1]) + return numpy.array([I - G[0].T, I - G[1].T], dtype=numpy.complex128) + + +def particle_number(dmat): + """Compute average particle number. + + Parameters + ---------- + dmat : :class:`numpy.ndarray` + Thermal 1RDM. + + Returns + ------- + nav : float + Average particle number. + """ + nav = dmat[0].trace() + dmat[1].trace() + return nav + + +def one_rdm_stable(BT, num_slices): + nbasis = BT.shape[-1] + G = [] + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in + # stable way. Iteratively construct column pivoted QR decompositions + # (A = QDT) starting from the rightmost (product of) propagator(s). + (Q1, R1, P1) = scipy.linalg.qr(BT[spin], pivoting=True, check_finite=False) + # Form D matrices + D1 = numpy.diag(R1.diagonal()) + D1inv = numpy.diag(1.0 / R1.diagonal()) + T1 = numpy.einsum("ii,ij->ij", D1inv, R1) + # permute them + T1[:, P1] = T1[:, range(nbasis)] + + for i in range(0, num_slices - 1): + C2 = numpy.dot(numpy.dot(BT[spin], Q1), D1) + (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = numpy.diag(1.0 / R1.diagonal()) + D1 = numpy.diag(R1.diagonal()) + tmp = numpy.einsum("ii,ij->ij", D1inv, R1) + tmp[:, P1] = tmp[:, range(nbasis)] + T1 = numpy.dot(tmp, T1) + # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T + # Write D = Db^{-1} Ds + # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T + Db = numpy.zeros(BT[spin].shape, BT[spin].dtype) + Ds = numpy.zeros(BT[spin].shape, BT[spin].dtype) + for i in range(Db.shape[0]): + absDlcr = abs(Db[i, i]) + if absDlcr > 1.0: + Db[i, i] = 1.0 / absDlcr + Ds[i, i] = numpy.sign(D1[i, i]) + else: + Db[i, i] = 1.0 + Ds[i, i] = D1[i, i] + + T1inv = scipy.linalg.inv(T1, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("ii,ij->ij", Db, Q1.conj().T), T1inv) + Ds + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + G.append(numpy.dot(numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T))) + return one_rdm_from_G(numpy.array(G)) + + +def entropy(beta, mu, H): + assert numpy.linalg.norm(H[0] - H[1]) < 1e-12 + eigs, eigv = numpy.linalg.eigh(H[0]) + p_i = fermi_factor(eigs, beta, mu) + S = -2.0 * sum(p * numpy.log(p) + (1 - p) * numpy.log(1 - p) for p in p_i) + # muN = mu * numpy.eye(H[0].shape[-1], dtype=H[0].dtype) + # rho = numpy.array([scipy.linalg.expm(-beta*(H[0]-muN)), + # scipy.linalg.expm(-beta*(H[1]-muN))]) + # W = rho[0] + rho[1] + # W = W / W.trace() + # logW = -numpy.trace(scipy.linalg.logm(W)) + # S = -numpy.trace(numpy.dot(W,logW)) + return S diff --git a/ipie/thermal/propagation/__init__.py b/ipie/thermal/propagation/__init__.py index c6cac692..e69de29b 100644 --- a/ipie/thermal/propagation/__init__.py +++ b/ipie/thermal/propagation/__init__.py @@ -1 +0,0 @@ -empty diff --git a/ipie/thermal/propagation/continuous.py b/ipie/thermal/propagation/continuous.py new file mode 100644 index 00000000..a97c6dc4 --- /dev/null +++ b/ipie/thermal/propagation/continuous.py @@ -0,0 +1,299 @@ +import cmath +import math +import sys +import time + +import numpy +import scipy.sparse.linalg + +from ipie.legacy.estimators.thermal import inverse_greens_function_qr, one_rdm_from_G +from ipie.legacy.propagation.operations import kinetic_real +from ipie.legacy.thermal_propagation.generic import GenericContinuous +from ipie.legacy.thermal_propagation.hubbard import HubbardContinuous +from ipie.legacy.thermal_propagation.planewave import PlaneWave +from ipie.utils.linalg import exponentiate_matrix + + +class Continuous(object): + """Propagator for generic many-electron Hamiltonian. + + Uses continuous HS transformation for exponential of two body operator. + + Parameters + ---------- + options : dict + Propagator input options. + qmc : :class:`pie.qmc.options.QMCOpts` + QMC options. + system : :class:`pie.system.System` + System object. + trial : :class:`pie.trial_wavefunctioin.Trial` + Trial wavefunction object. + verbose : bool + If true print out more information during setup. + """ + + def __init__(self, options, qmc, system, hamiltonian, trial, verbose=False, lowrank=False): + if verbose: + print("# Parsing continuous propagator input options.") + print("# Using continuous Hubbar--Stratonovich transformations.") + + # Input options + self.hs_type = "continuous" + self.exp_nmax = options.get("expansion_order", 6) + + optimised = options.get("optimised", True) + # Derived Attributes + self.dt = qmc.dt + self.sqrt_dt = qmc.dt**0.5 + self.isqrt_dt = 1j * self.sqrt_dt + self.nfb_trig = 0 + self.lowrank = lowrank + + self.propagator = get_continuous_propagator( + system, hamiltonian, trial, qmc, options=options, verbose=verbose + ) + # Mean field shifted one-body propagator + self.mu = system.mu + self.propagator.construct_one_body_propagator(hamiltonian, qmc.dt) + + self.BH1 = self.propagator.BH1 + self.BT = trial.dmat + self.BTinv = trial.dmat_inv + self.BT_BP = None + + self.mf_const_fac = cmath.exp(-self.dt * self.propagator.mf_core) + self.nstblz = qmc.nstblz + + self.ebound = (2.0 / self.dt) ** 0.5 + self.mean_local_energy = 0 + self.free_projection = options.get("free_projection", False) + self.force_bias = options.get("force_bias", True) + if self.free_projection: + if verbose: + print("# Using free projection.") + print("# Setting force_bias to False with free projection.") + self.force_bias = options.get("force_bias", False) + self.propagate_walker = self.propagate_walker_free + else: + if verbose: + print("# Using phaseless approximation.") + if self.force_bias: + print(f"# Setting force bias to {self.force_bias!r}.") + self.propagate_walker = self.propagate_walker_phaseless + if verbose: + print("# Finished setting up propagator.") + + def two_body_propagator(self, walker, system, trial): + r"""Continuous Hubbard-Statonovich transformation. + + Parameters + ---------- + walker : :class:`pie.walker.Walker` walker object to be updated. On + output we have acted on phi by B_V(x). + system : :class:`pie.system.System` + System object. + trial : :class:`pie.trial_wavefunctioin.Trial` + Trial wavefunction object. + """ + # Normally distrubted auxiliary fields. + xi = numpy.random.normal(0.0, 1.0, system.nfields) + if self.force_bias: + P = one_rdm_from_G(walker.G) + xbar = self.propagator.construct_force_bias(system, P, trial) + else: + xbar = numpy.zeros(xi.shape, dtype=numpy.complex128) + + for i in range(system.nfields): + if numpy.absolute(xbar[i]) > 1.0: + # if self.nfb_trig < 10: + # print("# Rescaling force bias is triggered") + # print("# Warning will only be printed 10 times on root.") + self.nfb_trig += 1 + xbar[i] /= numpy.absolute(xbar[i]) + # Constant factor arising from shifting the propability distribution. + cfb = xi.dot(xbar) - 0.5 * xbar.dot(xbar) + xshifted = xi - xbar + # Constant factor arising from force bias and mean field shift + cmf = -self.sqrt_dt * xshifted.dot(self.propagator.mf_shift) + + # Operator terms contributing to propagator. + VHS = self.propagator.construct_VHS(system, xshifted) + + return (cmf, cfb, xshifted, VHS) + + def estimate_eshift(self, walker): + return 0.0 + + def exponentiate(self, VHS, debug=False): + """Apply exponential propagator of the HS transformation + Parameters + ---------- + system : + system class + phi : numpy array + a state + VHS : numpy array + HS transformation potential + Returns + ------- + phi : numpy array + Exp(VHS) * phi + """ + # JOONHO: exact exponential + # copy = numpy.copy(phi) + # phi = scipy.linalg.expm(VHS).dot(copy) + phi = numpy.identity(VHS.shape[0], dtype=numpy.complex128) + if debug: + copy = numpy.copy(phi) + c2 = scipy.linalg.expm(VHS).dot(copy) + + Temp = numpy.identity(VHS.shape[0], dtype=numpy.complex128) + + for n in range(1, self.exp_nmax + 1): + Temp = VHS.dot(Temp) / n + phi += Temp + if debug: + print(f"DIFF: {(c2 - phi).sum() / c2.size: 10.8e}") + return phi + + def propagate_walker_free(self, system, walker, trial, eshift=0): + r"""Free projection for continuous HS transformation. + + .. Warning:: + Currently not implemented. + + + Parameters + ---------- + walker : :class:`walker.Walker` + Walker object to be updated. on output we have acted on + :math:`|\phi_i\rangle` by :math:`B` and updated the weight + appropriately. Updates inplace. + state : :class:`state.State` + Simulation state. + """ + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, system, trial) + BV = self.exponentiate(VHS) + + B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) + B = numpy.array([self.BH1[0].dot(B[0]), self.BH1[1].dot(B[1])]) + + # Compute determinant ratio det(1+A')/det(1+A). + # 1. Current walker's green's function. + G = walker.greens_function(trial, inplace=False) + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function(trial, inplace=True) + # 3. Compute det(G/G') + M0 = [ + scipy.linalg.det(G[0], check_finite=False), + scipy.linalg.det(G[1], check_finite=False), + ] + Mnew = [ + scipy.linalg.det(walker.G[0], check_finite=False), + scipy.linalg.det(walker.G[1], check_finite=False), + ] + # Could save M0 rather than recompute. + try: + # Could save M0 rather than recompute. + oratio = (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) + walker.ot = 1.0 + # Constant terms are included in the walker's weight. + (magn, phase) = cmath.polar(cmath.exp(cmf + cfb) * oratio) + walker.weight *= magn + walker.phase *= cmath.exp(1j * phase) + except ZeroDivisionError: + walker.weight = 0.0 + + def propagate_walker_phaseless(self, system, walker, trial, eshift=0): + r"""Propagate walker using phaseless approximation. + + Uses importance sampling and the hybrid method. + + Parameters + ---------- + walker : :class:`walker.Walker` + Walker object to be updated. On output we have acted on phi with the + propagator B(x), and updated the weight appropriately. Updates + inplace. + system : :class:`pie.system.System` + System object. + trial : :class:`pie.trial_wavefunctioin.Trial` + Trial wavefunction object. + """ + + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, system, trial) + BV = self.exponentiate(VHS) + + B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) + B = numpy.array([self.BH1[0].dot(B[0]), self.BH1[1].dot(B[1])]) + + # Compute determinant ratio det(1+A')/det(1+A). + # 1. Current walker's green's function. + tix = walker.stack.ntime_slices + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function(None, slice_ix=tix, inplace=True) + # 3. Compute det(G/G') + M0 = walker.M0 + Mnew = [ + scipy.linalg.det(walker.G[0], check_finite=False), + scipy.linalg.det(walker.G[1], check_finite=False), + ] + try: + # Could save M0 rather than recompute. + oratio = (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) + # Might want to cap this at some point + hybrid_energy = cmath.log(oratio) + cfb + cmf + Q = cmath.exp(hybrid_energy) + expQ = self.mf_const_fac * Q + (magn, phase) = cmath.polar(expQ) + + if not math.isinf(magn): + # Determine cosine phase from Arg(det(1+A'(x))/det(1+A(x))). + # Note this doesn't include exponential factor from shifting + # propability distribution. + dtheta = cmath.phase(cmath.exp(hybrid_energy - cfb)) + cosine_fac = max(0, math.cos(dtheta)) + walker.weight *= magn * cosine_fac + walker.M0 = Mnew + else: + walker.weight = 0.0 + except ZeroDivisionError: + walker.weight = 0.0 + + +def get_continuous_propagator(system, hamiltonian, trial, qmc, options={}, verbose=False): + """Wrapper to select propagator class. + + Parameters + ---------- + options : dict + Propagator input options. + qmc : :class:`pie.qmc.QMCOpts` class + Trial wavefunction input options. + system : class + System class. + trial : class + Trial wavefunction object. + + Returns + ------- + propagator : class or None + Propagator object. + """ + if system.name == "UEG": + propagator = PlaneWave(system, hamiltonian, trial, qmc, options=options, verbose=verbose) + elif system.name == "Hubbard": + propagator = HubbardContinuous( + system, hamiltonian, trial, qmc, options=options, verbose=verbose + ) + elif system.name == "Generic": + propagator = GenericContinuous( + system, hamiltonian, trial, qmc, options=options, verbose=verbose + ) + else: + propagator = None + + return propagator diff --git a/ipie/thermal/propagation/generic.py b/ipie/thermal/propagation/generic.py new file mode 100644 index 00000000..7454b5df --- /dev/null +++ b/ipie/thermal/propagation/generic.py @@ -0,0 +1,167 @@ +import cmath +import math +import sys +import time + +import numpy +import scipy.sparse.linalg + +from ipie.legacy.estimators.thermal import inverse_greens_function_qr, one_rdm_from_G +from ipie.legacy.propagation.operations import kinetic_real +from ipie.utils.linalg import exponentiate_matrix + + +class GenericContinuous(object): + """Propagator for generic many-electron Hamiltonian. + + Uses continuous HS transformation for exponential of two body operator. + + Parameters + ---------- + options : dict + Propagator input options. + qmc : :class:`pie.qmc.options.QMCOpts` + QMC options. + system : :class:`pie.system.System` + System object. + trial : :class:`pie.trial_wavefunctioin.Trial` + Trial wavefunction object. + verbose : bool + If true print out more information during setup. + """ + + def __init__(self, system, hamiltonian, trial, qmc, options={}, verbose=False): + if verbose: + print("# Parsing continuous propagator input options.") + + # Input options + self.hs_type = "continuous" + self.free_projection = options.get("free_projection", False) + if verbose: + print("# Using phaseless approximation: %r" % (not self.free_projection)) + self.exp_nmax = options.get("expansion_order", 6) + self.force_bias = options.get("force_bias", True) + if self.free_projection: + if verbose: + print("# Setting force_bias to False with free projection.") + self.force_bias = False + else: + if verbose: + print(f"# Setting force bias to {self.force_bias!r}.") + + optimised = options.get("optimised", True) + if optimised: + self.construct_force_bias = self.construct_force_bias_fast + self.construct_VHS = self.construct_VHS_fast + else: + self.construct_force_bias = self.construct_force_bias_slow + self.construct_VHS = self.construct_VHS_slow + # Derived Attributes + self.dt = qmc.dt + self.sqrt_dt = qmc.dt**0.5 + self.isqrt_dt = 1j * self.sqrt_dt + self.nfb_trig = 0 + + P = one_rdm_from_G(trial.G) + # Mean field shifts (2,nchol_vec). + self.mf_shift = self.construct_mean_field_shift(hamiltonian, P) + if verbose: + print( + "# Absolute value of maximum component of mean field shift: " + "{:13.8e}.".format(numpy.max(numpy.abs(self.mf_shift))) + ) + + # Mean field shifted one-body propagator + self.mu = hamiltonian.mu + + self.BT = trial.dmat + self.BTinv = trial.dmat_inv + + # Constant core contribution modified by mean field shift. + self.mf_core = hamiltonian.ecore + 0.5 * numpy.dot(self.mf_shift, self.mf_shift) + self.nstblz = qmc.nstblz + + self.ebound = (2.0 / self.dt) ** 0.5 + self.mean_local_energy = 0 + if verbose: + print("# Finished setting up propagator.") + + def construct_mean_field_shift(self, system, P): + if system.sparse: + mf_shift = 1j * P[0].ravel() * system.chol_vecs + mf_shift += 1j * P[1].ravel() * system.chol_vecs + else: + mf_shift = 1j * numpy.einsum("lpq,spq->l", system.chol_vecs, P) + return mf_shift + + def construct_one_body_propagator(self, system, dt): + """Construct mean-field shifted one-body propagator. + + Parameters + ---------- + dt : float + Timestep. + chol_vecs : :class:`numpy.ndarray` + Cholesky vectors. + h1e_mod : :class:`numpy.ndarray` + One-body operator including factor from factorising two-body + Hamiltonian. + """ + if system.sparse: + nb = system.nbasis + shift = 1j * system.hs_pot.dot(self.mf_shift).reshape(nb, nb) + else: + shift = 1j * numpy.einsum("l,lpq->pq", self.mf_shift, system.hs_pot) + I = numpy.identity(system.nbasis, dtype=system.H1.dtype) + muN = self.mu * I + H1 = system.h1e_mod - numpy.array([shift + muN, shift + muN]) + + self.BH1 = numpy.array( + [scipy.linalg.expm(-0.5 * dt * H1[0]), scipy.linalg.expm(-0.5 * dt * H1[1])] + ) + + def construct_force_bias_slow(self, system, P, trial): + r"""Compute optimal force bias. + + Uses explicit expression. + + Parameters + ---------- + G: :class:`numpy.ndarray` + Walker's 1RDM: . + + Returns + ------- + xbar : :class:`numpy.ndarray` + Force bias. + """ + vbias = numpy.einsum("lpq,pq->l", system.hs_pot, P[0]) + vbias += numpy.einsum("lpq,pq->l", system.hs_pot, P[1]) + return -self.sqrt_dt * (1j * vbias - self.mf_shift) + + def construct_force_bias_fast(self, system, P, trial): + r"""Compute optimal force bias. + + Uses explicit expression. + + Parameters + ---------- + G: :class:`numpy.ndarray` + Walker's 1RDM: . + + Returns + ------- + xbar : :class:`numpy.ndarray` + Force bias. + """ + vbias = P[0].ravel() * system.hs_pot + vbias += P[1].ravel() * system.hs_pot + return -self.sqrt_dt * (1j * vbias - self.mf_shift) + + def construct_VHS_slow(self, system, shifted): + return self.isqrt_dt * numpy.einsum("l,lpq->pq", shifted, system.hs_pot) + + def construct_VHS_fast(self, system, xshifted): + VHS = system.hs_pot.dot(xshifted) + VHS = VHS.reshape(system.nbasis, system.nbasis) + return self.isqrt_dt * VHS diff --git a/ipie/thermal/propagation/planewave.py b/ipie/thermal/propagation/planewave.py new file mode 100644 index 00000000..8b258c38 --- /dev/null +++ b/ipie/thermal/propagation/planewave.py @@ -0,0 +1,723 @@ +import cmath +import math +import sys +import time + +import numpy +import scipy.sparse.linalg +from scipy.linalg import sqrtm + +from ipie.legacy.estimators.thermal import inverse_greens_function_qr, one_rdm_from_G +from ipie.legacy.propagation.operations import kinetic_real +from ipie.legacy.walkers.single_det import SingleDetWalker +from ipie.utils.linalg import exponentiate_matrix + + +class PlaneWave(object): + """PlaneWave class""" + + def __init__(self, system, hamiltonian, trial, qmc, options={}, verbose=False, lowrank=False): + self.verbose = verbose + if verbose: + print("# Parsing plane wave propagator input options.") + # Input options + self.hs_type = "plane_wave" + self.free_projection = options.get("free_projection", False) + self.optimised = options.get("optimised", True) + self.lowrank = lowrank + self.exp_nmax = options.get("expansion_order", 6) + self.nstblz = qmc.nstblz + self.fb_bound = options.get("fb_bound", 1.0) + # Derived Attributes + self.dt = qmc.dt + self.sqrt_dt = qmc.dt**0.5 + self.isqrt_dt = 1j * self.sqrt_dt + self.num_vplus = hamiltonian.nfields // 2 + self.mf_shift = self.construct_mf_shift(hamiltonian, trial) + if verbose: + print( + "# Absolute value of maximum component of mean field shift: " + "{:13.8e}.".format(numpy.max(numpy.abs(self.mf_shift))) + ) + if verbose: + print("# Number of fields = %i" % hamiltonian.nfields) + print(f"# Using lowrank propagation: {self.lowrank}") + + self.vbias = numpy.zeros(hamiltonian.nfields, dtype=numpy.complex128) + + # Constant core contribution modified by mean field shift. + mf_core = hamiltonian.ecore + + self.construct_one_body_propagator(hamiltonian, qmc.dt) + + self.BT = trial.dmat + self.BTinv = trial.dmat_inv + + self.mf_const_fac = 1 + + # todo : ? + self.BT_BP = self.BT + self.nstblz = qmc.nstblz + + self.ebound = (2.0 / self.dt) ** 0.5 + self.mean_local_energy = 0 + + # self.propagate_walker_phaseless = self.propagate_walker_phaseless_full_rank + if self.lowrank: + self.propagate_walker_free = self.propagate_walker_phaseless_low_rank + self.propagate_walker_phaseless = self.propagate_walker_phaseless_low_rank + else: + self.propagate_walker_free = self.propagate_walker_free_full_rank + self.propagate_walker_phaseless = self.propagate_walker_phaseless_full_rank + + if self.free_projection: + if verbose: + print("# Using free projection") + self.propagate_walker = self.propagate_walker_free + else: + if verbose: + print("# Using phaseless approximation") + self.propagate_walker = self.propagate_walker_phaseless + if verbose: + print("# Finished setting up propagator.") + self.nfb_trig = False + + def construct_mf_shift(self, hamiltonian, trial): + P = one_rdm_from_G(trial.G) + P = P.reshape(2, hamiltonian.nbasis * hamiltonian.nbasis) + mf_shift = numpy.zeros(hamiltonian.nfields, numpy.complex128) + mf_shift[: self.num_vplus] = P[0].T * hamiltonian.iA + P[1].T * hamiltonian.iA + mf_shift[self.num_vplus :] = P[0].T * hamiltonian.iB + P[1].T * hamiltonian.iB + return mf_shift + + def construct_one_body_propagator(self, hamiltonian, dt): + """Construct the one-body propagator Exp(-dt/2 H0) + Parameters + ---------- + hamiltonian : + hamiltonian class + dt : float + time-step + Returns + ------- + self.BH1 : numpy array + Exp(-dt/2 H0) + """ + H1 = hamiltonian.h1e_mod + I = numpy.identity(H1[0].shape[0], dtype=H1.dtype) + print(f"hamiltonian.mu = {hamiltonian.mu}") + # No spin dependence for the moment. + self.BH1 = numpy.array( + [ + scipy.linalg.expm(-0.5 * dt * H1[0] + 0.5 * dt * hamiltonian.mu * I), + scipy.linalg.expm(-0.5 * dt * H1[1] + 0.5 * dt * hamiltonian.mu * I), + ] + ) + + def two_body_potentials(self, hamiltonian, iq): + """Calculatate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q + Parameters + ---------- + hamiltonian : + hamiltonian class + q : float + a plane-wave vector + Returns + ------- + iA : numpy array + Eq.(13a) + iB : numpy array + Eq.(13b) + """ + rho_q = hamiltonian.density_operator(iq) + qscaled = hamiltonian.kfac * hamiltonian.qvecs[iq] + + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = math.pi / (hamiltonian.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + # JOONHO: include a factor of 1j + iA = 1j * factor * (rho_q + rho_q.getH()) + iB = -factor * (rho_q - rho_q.getH()) + return (iA, iB) + + def construct_force_bias(self, hamiltonian, G): + """Compute the force bias term as in Eq.(33) of DOI:10.1002/wcms.1364 + Parameters + ---------- + hamiltonian : + hamiltonian class + G : numpy array + Green's function + Returns + ------- + force bias : numpy array + -sqrt(dt) * vbias + """ + for i, qi in enumerate(hamiltonian.qvecs): + (iA, iB) = self.two_body_potentials(hamiltonian, i) + # Deal with spin more gracefully + self.vbias[i] = iA.dot(G[0]).diagonal().sum() + iA.dot(G[1]).diagonal().sum() + self.vbias[i + self.num_vplus] = ( + iB.dot(G[0]).diagonal().sum() + iB.dot(G[1]).diagonal().sum() + ) + return -self.sqrt_dt * self.vbias + + def construct_VHS_outofcore(self, hamiltonian, xshifted): + """Construct the one body potential from the HS transformation + Parameters + ---------- + hamiltonian : + hamiltonian class + xshifted : numpy array + shifited auxiliary field + Returns + ------- + VHS : numpy array + the HS potential + """ + VHS = numpy.zeros((hamiltonian.nbasis, hamiltonian.nbasis), dtype=numpy.complex128) + + for i, qi in enumerate(hamiltonian.qvecs): + (iA, iB) = self.two_body_potentials(hamiltonian, i) + VHS = VHS + (xshifted[i] * iA).todense() + VHS = VHS + (xshifted[i + self.num_vplus] * iB).todense() + return VHS * self.sqrt_dt + + def construct_VHS_incore(self, hamiltonian, xshifted): + """Construct the one body potential from the HS transformation + Parameters + ---------- + hamiltonian : + hamiltonian class + xshifted : numpy array + shifited auxiliary field + Returns + ------- + VHS : numpy array + the HS potential + """ + VHS = numpy.zeros((hamiltonian.nbasis, hamiltonian.nbasis), dtype=numpy.complex128) + VHS = ( + hamiltonian.iA * xshifted[: self.num_vplus] + + hamiltonian.iB * xshifted[self.num_vplus :] + ) + VHS = VHS.reshape(hamiltonian.nbasis, hamiltonian.nbasis) + return VHS * self.sqrt_dt + + def construct_force_bias_incore(self, hamiltonian, G): + """Compute the force bias term as in Eq.(33) of DOI:10.1002/wcms.1364 + Parameters + ---------- + hamiltonian : + hamiltonian class + G : numpy array + Green's function + Returns + ------- + force bias : numpy array + -sqrt(dt) * vbias + """ + Gvec = G.reshape(2, hamiltonian.nbasis * hamiltonian.nbasis) + self.vbias[: self.num_vplus] = Gvec[0].T * hamiltonian.iA + Gvec[1].T * hamiltonian.iA + self.vbias[self.num_vplus :] = Gvec[0].T * hamiltonian.iB + Gvec[1].T * hamiltonian.iB + return -self.sqrt_dt * self.vbias + + def propagate_greens_function(self, walker, B, Binv): + if walker.stack.time_slice < walker.stack.ntime_slices: + walker.G[0] = B[0].dot(walker.G[0]).dot(Binv[0]) + walker.G[1] = B[1].dot(walker.G[1]).dot(Binv[1]) + + def two_body_propagator(self, walker, hamiltonian, force_bias=True): + """It appliese the two-body propagator + Parameters + ---------- + walker : + walker class + hamiltonian : + hamiltonian class + fb : boolean + wheter to use force bias + Returns + ------- + cxf : float + the constant factor arises from mean-field shift (hard-coded for UEG for now) + cfb : float + the constant factor arises from the force-bias + xshifted : numpy array + shifited auxiliary field + """ + + # Normally distrubted auxiliary fields. + xi = numpy.random.normal(0.0, 1.0, hamiltonian.nfields) + + # Optimal force bias. + xbar = numpy.zeros(hamiltonian.nfields) + if force_bias: + rdm = one_rdm_from_G(walker.G) + xbar = self.construct_force_bias_incore(hamiltonian, rdm) + + for i in range(hamiltonian.nfields): + if numpy.absolute(xbar[i]) > self.fb_bound: + if not self.nfb_trig and self.verbose: + print("# Rescaling force bias is triggered.") + print("# Warning will only be printed once per thread.") + print(f"# Bound = {self.fb_bound}") + xb = (xbar[i].real, xbar[i].imag) + vb = abs(xbar[i]) / self.sqrt_dt + vb = (vb.real, vb.imag) + print("XBAR: (%f,%f)" % xb) + print(": (%f,%f)" % vb) + self.nfb_trig = True + walker.rescaled_fb = True + xbar[i] /= numpy.absolute(xbar[i]) + + xshifted = xi - xbar + + # Constant factors: Note they are not exponentiated. + # Constant factor arising from force bias and mean field shift + cmf = -self.sqrt_dt * xshifted.dot(self.mf_shift) + # Constant factor arising from shifting the propability distribution. + cfb = xi.dot(xbar) - 0.5 * xbar.dot(xbar) + + # print(xbar.dot(xbar)) + + # Operator terms contributing to propagator. + VHS = self.construct_VHS_incore(hamiltonian, xshifted) + + return (cmf, cfb, xshifted, VHS) + + def exponentiate(self, VHS, debug=False): + """Apply exponential propagator of the HS transformation + Parameters + ---------- + system : + system class + phi : numpy array + a state + VHS : numpy array + HS transformation potential + Returns + ------- + phi : numpy array + Exp(VHS) * phi + """ + # JOONHO: exact exponential + # copy = numpy.copy(phi) + # phi = scipy.linalg.expm(VHS).dot(copy) + phi = numpy.identity(VHS.shape[0], dtype=numpy.complex128) + if debug: + copy = numpy.copy(phi) + c2 = scipy.linalg.expm(VHS).dot(copy) + + Temp = numpy.identity(VHS.shape[0], dtype=numpy.complex128) + + for n in range(1, self.exp_nmax + 1): + Temp = VHS.dot(Temp) / n + phi += Temp + if debug: + print(f"DIFF: {(c2 - phi).sum() / c2.size: 10.8e}") + return phi + + def estimate_eshift(self, walker): + return 0.0 + + def propagate_walker_free_full_rank( + self, system, hamiltonian, walker, trial, eshift=0, force_bias=False + ): + """Free projection propagator + Parameters + ---------- + walker : + walker class + system : + system class + trial : + trial wavefunction class + Returns + ------- + """ + + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator( + walker, hamiltonian, force_bias=force_bias + ) + BV = self.exponentiate(VHS) # could use a power-series method to build this + + B = numpy.array( + [ + numpy.einsum("ij,jj->ij", BV, self.BH1[0]), + numpy.einsum("ij,jj->ij", BV, self.BH1[1]), + ] + ) + B = numpy.array( + [ + numpy.einsum("ii,ij->ij", self.BH1[0], B[0]), + numpy.einsum("ii,ij->ij", self.BH1[1], B[1]), + ] + ) + + # Compute determinant ratio det(1+A')/det(1+A). + if self.optimised: + icur = walker.stack.time_slice // walker.stack.stack_size + inext = (walker.stack.time_slice + 1) // walker.stack.stack_size + if walker.stack.counter == 0: + walker.compute_left_right(icur) + # 1. Current walker's green's function. + # Green's function that takes Left Right and Center + G = walker.greens_function_left_right_no_truncation(icur, inplace=False) + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function_left_right_no_truncation(icur, inplace=True) + else: + # Compute determinant ratio det(1+A')/det(1+A). + # 1. Current walker's green's function. + G = walker.greens_function(None, slice_ix=walker.stack.ntime_slices, inplace=False) + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function(None, slice_ix=walker.stack.ntime_slices, inplace=True) + + # 3. Compute det(G/G') + M0 = numpy.array( + [ + scipy.linalg.det(G[0], check_finite=False), + scipy.linalg.det(G[1], check_finite=False), + ] + ) + Mnew = numpy.array( + [ + scipy.linalg.det(walker.G[0], check_finite=False), + scipy.linalg.det(walker.G[1], check_finite=False), + ] + ) + + try: + # Could save M0 rather than recompute. + oratio = (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) + + walker.ot = 1.0 + # Constant terms are included in the walker's weight. + (magn, phase) = cmath.polar(cmath.exp(cmf + cfb) * oratio) + walker.weight *= magn + walker.phase *= cmath.exp(1j * phase) + except ZeroDivisionError: + walker.weight = 0.0 + + def propagate_walker_free_low_rank(self, system, walker, trial, eshift=0, force_bias=False): + """Free projection propagator + Parameters + ---------- + walker : + walker class + system : + system class + trial : + trial wavefunction class + Returns + ------- + """ + + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator( + walker, hamiltonian, force_bias=force_bias + ) + BV = self.exponentiate(VHS) # could use a power-series method to build this + + B = numpy.array( + [ + numpy.einsum("ij,jj->ij", BV, self.BH1[0]), + numpy.einsum("ij,jj->ij", BV, self.BH1[1]), + ] + ) + B = numpy.array( + [ + numpy.einsum("ii,ij->ij", self.BH1[0], B[0]), + numpy.einsum("ii,ij->ij", self.BH1[1], B[1]), + ] + ) + + # Compute determinant ratio det(1+A')/det(1+A). + if self.optimised: + icur = walker.stack.time_slice // walker.stack.stack_size + inext = (walker.stack.time_slice + 1) // walker.stack.stack_size + if walker.stack.counter == 0: + walker.compute_left_right(icur) + # 1. Current walker's green's function. + # Green's function that takes Left Right and Center + G = walker.greens_function_left_right_no_truncation(icur, inplace=False) + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function_left_right_no_truncation(icur, inplace=True) + else: + # Compute determinant ratio det(1+A')/det(1+A). + # 1. Current walker's green's function. + tix = walker.stack.ntime_slices + G = walker.greens_function(None, slice_ix=tix, inplace=False) + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function(None, slice_ix=tix, inplace=True) + + ovlp = numpy.asarray(walker.stack.ovlp).copy() + walker.stack.update_new(B) + ovlp_new = numpy.asarray(walker.stack.ovlp).copy() + walker.G = walker.stack.G.copy() + + try: + # Could save M0 rather than recompute. + oratio = (ovlp_new[0] * ovlp_new[1]) / (ovlp[0] * ovlp[1]) + + walker.ot = 1.0 + # Constant terms are included in the walker's weight. + (magn, phase) = cmath.polar(cmath.exp(cmf + cfb) * oratio) + walker.weight *= magn + walker.phase *= cmath.exp(1j * phase) + except ZeroDivisionError: + walker.weight = 0.0 + + def propagate_walker_phaseless_full_rank(self, hamiltonian, walker, trial, eshift=0): + # """Phaseless propagator + # Parameters + # ---------- + # walker : + # walker class + # system : + # system class + # trial : + # trial wavefunction class + # Returns + # ------- + # """ + + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, hamiltonian, True) + BV = self.exponentiate(VHS) # could use a power-series method to build this + + B = numpy.array( + [ + numpy.einsum("ij,jj->ij", BV, self.BH1[0]), + numpy.einsum("ij,jj->ij", BV, self.BH1[1]), + ] + ) + B = numpy.array( + [ + numpy.einsum("ii,ij->ij", self.BH1[0], B[0]), + numpy.einsum("ii,ij->ij", self.BH1[1], B[1]), + ] + ) + if self.optimised: + icur = walker.stack.time_slice // walker.stack.stack_size + inext = (walker.stack.time_slice + 1) // walker.stack.stack_size + if walker.stack.counter == 0: + walker.compute_left_right(icur) + # 1. Current walker's green's function. + # Green's function that takes Left Right and Center + # print("walker.stack.G (before) = ", walker.G) + G = walker.greens_function_left_right_no_truncation(icur, inplace=False) + # print("G (before) = ", G) + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function_left_right_no_truncation(icur, inplace=True) + # print("G (after) = ", walker.G) + else: + # Compute determinant ratio det(1+A')/det(1+A). + # 1. Current walker's green's function. + tix = walker.stack.ntime_slices + G = walker.greens_function(None, slice_ix=tix, inplace=False) + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function(None, slice_ix=tix, inplace=True) + + # 3. Compute det(G/G') + M0 = walker.M0 + Mnew = numpy.array( + [ + scipy.linalg.det(walker.G[0], check_finite=False), + scipy.linalg.det(walker.G[1], check_finite=False), + ] + ) + + # Could save M0 rather than recompute. + try: + oratio = (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) + # Might want to cap this at some point + hybrid_energy = cmath.log(oratio) + cfb + cmf + Q = cmath.exp(hybrid_energy) + expQ = self.mf_const_fac * Q + (magn, phase) = cmath.polar(expQ) + if not math.isinf(magn): + # Determine cosine phase from Arg(det(1+A'(x))/det(1+A(x))). + # Note this doesn't include exponential factor from shifting + # propability distribution. + dtheta = cmath.phase(cmath.exp(hybrid_energy - cfb)) + cosine_fac = max(0, math.cos(dtheta)) + walker.weight *= magn * cosine_fac + walker.M0 = Mnew + else: + walker.weight = 0.0 + except ZeroDivisionError: + walker.weight = 0.0 + + def propagate_walker_phaseless_low_rank(self, hamiltonian, walker, trial, eshift=0): + # """Phaseless propagator + # Parameters + # ---------- + # walker : + # walker class + # system : + # system class + # trial : + # trial wavefunction class + # Returns + # ------- + # """ + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, hamiltonian, True) + BV = self.exponentiate(VHS) # could use a power-series method to build this + + B = numpy.array( + [ + numpy.einsum("ij,jj->ij", BV, self.BH1[0]), + numpy.einsum("ij,jj->ij", BV, self.BH1[1]), + ] + ) + B = numpy.array( + [ + numpy.einsum("ii,ij->ij", self.BH1[0], B[0]), + numpy.einsum("ii,ij->ij", self.BH1[1], B[1]), + ] + ) + + icur = walker.stack.time_slice // walker.stack.stack_size + # + # local index within a stack = walker.stack.counter + # global stack index = icur + ovlp = numpy.asarray(walker.stack.ovlp).copy() + walker.stack.update_new(B) + ovlp_new = numpy.asarray(walker.stack.ovlp).copy() + walker.G = walker.stack.G.copy() + + # Could save M0 rather than recompute. + try: + oratio = (ovlp_new[0] * ovlp_new[1]) / (ovlp[0] * ovlp[1]) + # Might want to cap this at some point + hybrid_energy = cmath.log(oratio) + cfb + cmf + Q = cmath.exp(hybrid_energy) + expQ = self.mf_const_fac * Q + (magn, phase) = cmath.polar(expQ) + if not math.isinf(magn): + # Determine cosine phase from Arg(det(1+A'(x))/det(1+A(x))). + # Note this doesn't include exponential factor from shifting + # propability distribution. + dtheta = cmath.phase(cmath.exp(hybrid_energy - cfb)) + cosine_fac = max(0, math.cos(dtheta)) + walker.weight *= magn * cosine_fac + # walker.M0 = Mnew + walker.M0 = ovlp_new + else: + walker.weight = 0.0 + except ZeroDivisionError: + walker.weight = 0.0 + + def propagate_greens_function(self, walker): + if walker.stack.time_slice < walker.stack.ntime_slices: + walker.G[0] = self.BT[0].dot(walker.G[0]).dot(self.BTinv[0]) + walker.G[1] = self.BT[1].dot(walker.G[1]).dot(self.BTinv[1]) + + +def unit_test(): + import cProfile + + from ipie.estimators.pw_fft import local_energy_pw_fft + from ipie.legacy.estimators.ueg import local_energy_ueg + from ipie.legacy.qmc.options import QMCOpts + from ipie.legacy.systems.ueg import UEG + from ipie.legacy.trial_density_matrices.onebody import OneBody + from ipie.legacy.walkers.thermal import ThermalWalker + from ipie.qmc.comm import FakeComm + from ipie.systems.pw_fft import PW_FFT + + beta = 16.0 + dt = 0.005 + + # beta = 0.5 + # dt = 0.05 + + lowrank = True + # lowrank = False + + stack_size = 10 + + ecuts = [4.0, 8.0, 10.0, 12.0, 16.0, 21.0, 21.5, 32.0] + for ecut in ecuts: + inputs = { + "nup": 33, + "ndown": 33, + "thermal": True, + "beta": beta, + "rs": 1.0, + "ecut": ecut, + "dt": dt, + "nwalkers": 10, + "lowrank": lowrank, + "stack_size": stack_size, + } + + system = UEG(inputs, True) + + qmc = QMCOpts(inputs, system, True) + + comm = FakeComm() + + trial = OneBody(comm, system, beta, dt, options=inputs, verbose=True) + + propagator = PlaneWave(system, trial, qmc, inputs, True) + + walker = ThermalWalker( + {"stack_size": trial.stack_size, "low_rank": lowrank}, + system, + trial, + verbose=True, + ) + eshift = 0.0 + 0.0j + + numpy.random.seed(7) + + pr = cProfile.Profile() + pr.enable() + for ts in range(0, walker.num_slices): + propagator.propagate_walker_phaseless( + walker=walker, system=system, trial=trial, eshift=eshift + ) + + if lowrank: + system = PW_FFT(inputs, False) + sort_basis = numpy.argsort(numpy.diag(system.H1[0]), kind="mergesort") + inv_sort_basis = numpy.zeros_like(sort_basis) + + for i, idx in enumerate(sort_basis): + inv_sort_basis[idx] = i + + mT = walker.stack.mT + Ctrial = numpy.zeros((system.nbasis, walker.stack.mT * 2), dtype=numpy.complex128) + Ctrial[:, :mT] = walker.stack.CT[0][:, :mT] + Ctrial[:, mT:] = walker.stack.CT[1][:, :mT] + + P = one_rdm_from_G(walker.G) + # Ptmp = Ctrial[:,:mT].conj().dot(walker.stack.theta[0,:mT,:]) + + # Reorder to FFT + P[:, :, :] = P[:, inv_sort_basis, :] + P[:, :, :] = P[:, :, inv_sort_basis] + Theta = walker.stack.theta[:, :mT, :] + Theta[:, :, :] = Theta[:, :, inv_sort_basis] + Ctrial = Ctrial[inv_sort_basis, :] + + print(f"E = {local_energy_pw_fft(system, G=P, Ghalf=Theta, trial=Ctrial)}") + else: + P = one_rdm_from_G(walker.G) + print(numpy.diag(walker.G[0].real)) + print(f"weight = {walker.weight}") + print(f"E = {local_energy_ueg(system, P)}") + + pr.disable() + pr.print_stats(sort="tottime") + + +if __name__ == "__main__": + unit_test() diff --git a/ipie/thermal/qmc/__init__.py b/ipie/thermal/qmc/__init__.py index c6cac692..e69de29b 100644 --- a/ipie/thermal/qmc/__init__.py +++ b/ipie/thermal/qmc/__init__.py @@ -1 +0,0 @@ -empty diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py new file mode 100644 index 00000000..f4e60a9c --- /dev/null +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -0,0 +1,382 @@ +"""Driver to perform AFQMC calculation""" +import copy +import json +import sys +import time +import uuid +import warnings +from math import exp + +import h5py +import numpy + +from ipie.legacy.estimators.handler import Estimators +from ipie.legacy.estimators.local_energy import local_energy +from ipie.legacy.hamiltonians.utils import get_hamiltonian +from ipie.legacy.thermal_propagation.utils import get_propagator +from ipie.legacy.trial_density_matrices.utils import get_trial_density_matrix +from ipie.legacy.walkers.handler import Walkers +from ipie.legacy.qmc.options import QMCOpts +from ipie.qmc.utils import set_rng_seed +from ipie.legacy.systems.utils import get_system +from ipie.utils.io import get_input_value, to_json +from ipie.utils.misc import get_git_info, print_env_info +from ipie.utils.mpi import get_shared_comm + + +class ThermalAFQMC(object): + """AFQMC driver. + + Non-zero temperature AFQMC using open ended random walk. + + Parameters + ---------- + model : dict + Input parameters for model system. + qmc_opts : dict + Input options relating to qmc parameters. + estimates : dict + Input options relating to what estimator to calculate. + trial : dict + Input options relating to trial wavefunction. + propagator : dict + Input options relating to propagator. + parallel : bool + If true we are running in parallel. + verbose : bool + If true we print out additional setup information. + + Attributes + ---------- + uuid : string + Simulation state uuid. + sha1 : string + Git hash. + seed : int + RNG seed. This is set during initialisation in calc. + root : bool + If true we are on the root / master processor. + nprocs : int + Number of processors. + rank : int + Processor id. + cplx : bool + If true then most numpy arrays are complex valued. + init_time : float + Calculation initialisation (cpu) time. + init_time : float + Human readable initialisation time. + system : system object. + Container for model input options. + qmc : :class:`pie.state.QMCOpts` object. + Container for qmc input options. + trial : :class:`pie.trial_wavefunction.X' object + Trial wavefunction class. + propagators : :class:`pie.propagation.Projectors` object + Container for system specific propagation routines. + estimators : :class:`pie.estimators.Estimators` object + Estimator handler. + walk : :class:`pie.walkers.Walkers` object + Stores walkers which sample the partition function. + """ + + def __init__( + self, + comm, + options=None, + system=None, + hamiltonian=None, + trial=None, + parallel=False, + verbose=None, + ): + if verbose is not None: + self.verbosity = verbose + if comm.rank != 0: + self.verbosity = 0 + verbose = verbose > 0 and comm.rank == 0 + else: + self.verbosity = 0 + verbose = False + qmc_opts = get_input_value( + options, + "qmc", + default={}, + alias=["qmc_options"], + verbose=self.verbosity > 1, + ) + if qmc_opts.get("beta") is None: + print("Shouldn't call ThermalAFQMC without specifying beta") + exit() + # 1. Environment attributes + if comm.rank == 0: + self.uuid = str(uuid.uuid1()) + get_sha1 = options.get("get_sha1", True) + if get_sha1: + self.sha1, self.branch, self.local_mods = get_git_info() + else: + self.sha1 = "None" + if verbose: + self.sys_info = print_env_info( + self.sha1, self.branch, self.local_mods, self.uuid, comm.size + ) + # Hack - this is modified later if running in parallel on + # initialisation. + self.root = comm.rank == 0 + self.nprocs = comm.size + self.rank = comm.rank + self._init_time = time.time() + self.run_time = (time.asctime(),) + self.shared_comm = get_shared_comm(comm, verbose=verbose) + + # 2. Calculation objects. + sys_opts = options.get("system") + if system is not None: + self.system = system + else: + sys_opts = get_input_value( + options, + "system", + default={}, + alias=["model"], + verbose=self.verbosity > 1, + ) + sys_opts["thermal"] = True + self.system = get_system(sys_opts=sys_opts, verbose=verbose) + + if hamiltonian is not None: + self.hamiltonian = hamiltonian + else: + ham_opts = get_input_value( + options, "hamiltonian", default={}, verbose=self.verbosity > 1 + ) + # backward compatibility with previous code (to be removed) + for item in sys_opts.items(): + if item[0].lower() == "name" and "name" in ham_opts.keys(): + continue + ham_opts[item[0]] = item[1] + self.hamiltonian = get_hamiltonian( + self.system, ham_opts, verbose=verbose, comm=self.shared_comm + ) + + self.qmc = QMCOpts(qmc_opts, self.system, verbose) + self.qmc.rng_seed = set_rng_seed(self.qmc.rng_seed, comm) + self.qmc.ntime_slices = int(round(self.qmc.beta / self.qmc.dt)) + # Overide whatever's in the input file due to structure of FT algorithm. + self.qmc.nsteps = 1 + self.qmc.total_steps = self.qmc.nblocks + if verbose: + print("# Number of time slices = %i" % self.qmc.ntime_slices) + self.cplx = True + if trial is not None: + self.trial = trial + if verbose: + print( + "# Trial density matrix passed from input: {} ".format( + self.trial.__class__.__name__ + ) + ) + else: + trial_opts = get_input_value( + options, + "trial", + default={}, + alias=["trial_density"], + verbose=self.verbosity > 1, + ) + self.trial = get_trial_density_matrix( + self.system, + self.hamiltonian, + self.qmc.beta, + self.qmc.dt, + comm=comm, + options=trial_opts, + verbose=verbose, + ) + + self.qmc.ntot_walkers = self.qmc.nwalkers + # Number of walkers per core/rank. + self.qmc.nwalkers = int(self.qmc.nwalkers / comm.size) + # Total number of walkers. + self.qmc.ntot_walkers = self.qmc.nwalkers * self.nprocs + if self.qmc.nwalkers == 0: + if comm.rank == 0 and verbose: + print("# WARNING: Not enough walkers for selected core count.") + print( + "# There must be at least one walker per core set in the " + "input file." + ) + print("# Setting one walker per core.") + self.qmc.nwalkers = 1 + self.qmc.ntot_walkers = self.qmc.nwalkers * self.nprocs + wlk_opts = get_input_value( + options, + "walkers", + default={}, + alias=["walker", "walker_opts"], + verbose=self.verbosity > 1, + ) + self.walk = Walkers( + self.system, + self.hamiltonian, + self.trial, + self.qmc, + walker_opts=wlk_opts, + verbose=verbose, + ) + lowrank = self.walk.walkers[0].lowrank + prop_opts = get_input_value( + options, + "propagator", + default={}, + alias=["prop", "propagation"], + verbose=self.verbosity > 1, + ) + self.propagators = get_propagator( + prop_opts, + self.qmc, + self.system, + self.hamiltonian, + self.trial, + verbose=verbose, + lowrank=lowrank, + ) + + self.tsetup = time.time() - self._init_time + est_opts = get_input_value( + options, + "estimators", + default={}, + alias=["estimates"], + verbose=self.verbosity > 1, + ) + self.estimators = Estimators( + est_opts, + self.root, + self.qmc, + self.system, + self.hamiltonian, + self.trial, + self.propagators.BT_BP, + verbose, + ) + # stabilization frequency might be updated due to wrong user input + if self.qmc.nstblz != self.propagators.nstblz: + self.propagators.nstblz = self.qmc.nstblz + if comm.rank == 0: + json_string = to_json(self) + self.estimators.json_string = json_string + self.estimators.dump_metadata() + if verbose: + self.estimators.estimators["mixed"].print_key() + self.estimators.estimators["mixed"].print_header() + + def run(self, walk=None, comm=None, verbose=None): + """Perform AFQMC simulation on state object using open-ended random walk. + + Parameters + ---------- + state : :class:`pie.state.State` object + Model and qmc parameters. + walk: :class:`pie.walker.Walkers` object + Initial wavefunction / distribution of walkers. + comm : MPI communicator + """ + if walk is not None: + self.walk = walk + self.setup_timers() + # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) + (E_T, ke, pe) = local_energy( + self.system, self.hamiltonian, self.walk.walkers[0], self.trial + ) + # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) + # Calculate estimates for initial distribution of walkers. + self.estimators.estimators["mixed"].update( + self.qmc, + self.system, + self.hamiltonian, + self.trial, + self.walk, + 0, + self.propagators.free_projection, + ) + # Print out zeroth step for convenience. + self.estimators.estimators["mixed"].print_step(comm, self.nprocs, 0, 1) + + for step in range(1, self.qmc.total_steps + 1): + start_path = time.time() + for ts in range(0, self.qmc.ntime_slices): + if self.verbosity >= 2 and comm.rank == 0: + print(" # Timeslice %d of %d." % (ts, self.qmc.ntime_slices)) + start = time.time() + for w in self.walk.walkers: + self.propagators.propagate_walker(self.hamiltonian, w, ts, 0) + if (abs(w.weight) > w.total_weight * 0.10) and ts > 0: + w.weight = w.total_weight * 0.10 + self.tprop += time.time() - start + start = time.time() + if ts % self.qmc.npop_control == 0 and ts != 0: + self.walk.pop_control(comm) + self.tpopc += time.time() - start + self.tpath += time.time() - start_path + start = time.time() + self.estimators.update( + self.qmc, + self.system, + self.hamiltonian, + self.trial, + self.walk, + step, + self.propagators.free_projection, + ) + self.testim += time.time() - start + self.estimators.print_step( + comm, + self.nprocs, + step, + free_projection=self.propagators.free_projection, + ) + self.walk.reset(self.trial) + + def finalise(self, verbose): + """Tidy up. + + Parameters + ---------- + verbose : bool + If true print out some information to stdout. + """ + if self.root: + if verbose: + print(f"# End Time: {time.asctime()}") + print(f"# Running time : {time.time() - self._init_time:.6f} seconds") + print("# Timing breakdown (per processor, per path/slice):") + print(f"# - Setup: {self.tsetup:f} s") + nsteps = self.qmc.nsteps + nslice = nsteps * self.qmc.ntime_slices + npcon = nslice // self.qmc.npop_control + print(f"# - Path update: {self.tpath / nsteps:f} s") + print(f"# - Propagation: {self.tprop / nslice:f} s") + print(f"# - Estimators: {self.testim / nsteps:f} s") + print(f"# - Population control: {self.tpopc / npcon:f} s") + + def determine_dtype(self, propagator, system): + """Determine dtype for trial wavefunction and walkers. + + Parameters + ---------- + propagator : dict + Propagator input options. + system : object + System object. + """ + hs_type = propagator.get("hubbard_stratonovich", "discrete") + continuous = "continuous" in hs_type + twist = system.ktwist.all() is not None + return continuous or twist + + def setup_timers(self): + self.tpath = 0 + self.tprop = 0 + self.testim = 0 + self.tpopc = 0 diff --git a/ipie/thermal/trial/__init__.py b/ipie/thermal/trial/__init__.py index c6cac692..e69de29b 100644 --- a/ipie/thermal/trial/__init__.py +++ b/ipie/thermal/trial/__init__.py @@ -1 +0,0 @@ -empty diff --git a/ipie/thermal/trial/chem_pot.py b/ipie/thermal/trial/chem_pot.py new file mode 100644 index 00000000..f5f19aa7 --- /dev/null +++ b/ipie/thermal/trial/chem_pot.py @@ -0,0 +1,66 @@ +import numpy + +from ipie.legacy.estimators.thermal import one_rdm_stable, particle_number +from ipie.utils.io import format_fixed_width_floats, format_fixed_width_strings + + +def find_chemical_potential( + alt_convention, rho, beta, num_bins, target, deps=1e-6, max_it=1000, verbose=False +): + # Todo: some sort of generic starting point independent of + # system/temperature + dmu1 = dmu2 = 1 + mu1 = -1 + mu2 = 1 + sign = -1 if alt_convention else 1 + if verbose: + print(f"# Finding chemical potential to match = {target:13.8e}") + while numpy.sign(dmu1) * numpy.sign(dmu2) > 0: + rho1 = compute_rho(rho, mu1, beta, sign=sign) + dmat = one_rdm_stable(rho1, num_bins) + dmu1 = delta_nav(dmat, target) + rho2 = compute_rho(rho, mu2, beta, sign=sign) + dmat = one_rdm_stable(rho2, num_bins) + dmu2 = delta_nav(dmat, target) + if numpy.sign(dmu1) * numpy.sign(dmu2) < 0: + if verbose: + print(f"# Chemical potential lies within range of [{mu1:f},{mu2:f}]") + print(f"# delta_mu1 = {dmu1.real:f}, delta_mu2 = {dmu2.real:f}") + break + else: + mu1 -= 2 + mu2 += 2 + if verbose: + print(f"# Increasing chemical potential search to [{mu1:f},{mu2:f}]") + found_mu = False + if verbose: + print("# " + format_fixed_width_strings(["iteration", "mu", "Dmu", ""])) + for i in range(0, max_it): + mu = 0.5 * (mu1 + mu2) + rho_mu = compute_rho(rho, mu, beta, sign=sign) + dmat = one_rdm_stable(rho_mu, num_bins) + dmu = delta_nav(dmat, target).real + if verbose: + out = [i, mu, dmu, particle_number(dmat).real] + print("# " + format_fixed_width_floats(out)) + if abs(dmu) < deps: + found_mu = True + break + else: + if dmu * dmu1 > 0: + mu1 = mu + elif dmu * dmu2 > 0: + mu2 = mu + if found_mu: + return mu + else: + print("# Error chemical potential not found") + return None + + +def delta_nav(dm, nav): + return particle_number(dm) - nav + + +def compute_rho(rho, mu, beta, sign=1): + return numpy.einsum("ijk,k->ijk", rho, numpy.exp(sign * beta * mu * numpy.ones(rho.shape[-1]))) diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py new file mode 100644 index 00000000..46c01bb4 --- /dev/null +++ b/ipie/thermal/trial/mean_field.py @@ -0,0 +1,113 @@ +import numpy +import scipy.linalg + +from ipie.legacy.estimators.fock import fock_matrix +from ipie.legacy.estimators.local_energy import local_energy +from ipie.legacy.estimators.thermal import entropy, greens_function, one_rdm_stable, particle_number +from ipie.legacy.trial_density_matrices.chem_pot import compute_rho, find_chemical_potential +from ipie.legacy.trial_density_matrices.onebody import OneBody + + +class MeanField(OneBody): + def __init__(self, system, hamiltonian, beta, dt, options={}, H1=None, verbose=False): + OneBody.__init__( + self, system, hamiltonian, beta, dt, options=options, H1=H1, verbose=verbose + ) + if verbose: + print(" # Building THF density matrix.") + self.alpha = options.get("alpha", 0.75) + self.max_scf_it = options.get("max_scf_it", self.max_it) + self.max_macro_it = options.get("max_macro_it", self.max_it) + self.find_mu = options.get("find_mu", True) + self.P, HMF, self.mu = self.thermal_hartree_fock(hamiltonian, beta) + muN = self.mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) + self.dmat = numpy.array( + [ + scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN)), + ] + ) + self.dmat_inv = numpy.array( + [ + scipy.linalg.inv(self.dmat[0], check_finite=False), + scipy.linalg.inv(self.dmat[1], check_finite=False), + ] + ) + self.G = numpy.array([greens_function(self.dmat[0]), greens_function(self.dmat[1])]) + self.nav = particle_number(self.P).real + + def thermal_hartree_fock(self, system, beta): + dt = self.dtau + mu_old = self.mu + P = self.P.copy() + if self.verbose: + print("# Determining Thermal Hartree--Fock Density Matrix.") + for it in range(self.max_macro_it): + if self.verbose: + print(f"# Macro iteration: {it}") + HMF = self.scf(system, beta, mu_old, P) + rho = numpy.array([scipy.linalg.expm(-dt * HMF[0]), scipy.linalg.expm(-dt * HMF[1])]) + if self.find_mu: + mu = find_chemical_potential( + system, + rho, + dt, + self.num_bins, + self.nav, + deps=self.deps, + max_it=self.max_it, + verbose=self.verbose, + ) + else: + mu = self.mu + rho_mu = compute_rho(rho, mu_old, dt) + P = one_rdm_stable(rho_mu, self.num_bins) + dmu = abs(mu - mu_old) + if self.verbose: + print(f"# New mu: {mu:13.8e} Old mu: {mu_old:13.8e} Dmu: {dmu:13.8e}") + if dmu < self.deps: + break + mu_old = mu + return P, HMF, mu + + def scf(self, system, beta, mu, P): + # 1. Compute HMF + HMF = fock_matrix(system, P) + dt = self.dtau + muN = mu * numpy.eye(system.nbasis, dtype=self.G.dtype) + rho = numpy.array( + [ + scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN)), + ] + ) + Pold = one_rdm_stable(rho, self.num_bins) + if self.verbose: + print(" # Running Thermal SCF.") + for it in range(self.max_scf_it): + HMF = fock_matrix(system, Pold) + rho = numpy.array( + [ + scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN)), + ] + ) + Pnew = (1 - self.alpha) * one_rdm_stable(rho, self.num_bins) + self.alpha * Pold + change = numpy.linalg.norm(Pnew - Pold) + if change < self.deps: + break + if self.verbose: + N = particle_number(P).real + E = local_energy(system, P)[0].real + S = entropy(beta, mu, HMF) + omega = E - mu * N - 1.0 / beta * S + print( + " # Iteration: {:4d} dP: {:13.8e} Omega: {:13.8e}".format( + it, change, omega.real + ) + ) + Pold = Pnew.copy() + if self.verbose: + N = particle_number(P).real + print(f" # Average particle number: {N:13.8e}") + return HMF diff --git a/ipie/thermal/trial/onebody.py b/ipie/thermal/trial/onebody.py new file mode 100644 index 00000000..9d262336 --- /dev/null +++ b/ipie/thermal/trial/onebody.py @@ -0,0 +1,146 @@ +import math +import sys + +import numpy +import scipy.linalg + +from ipie.legacy.estimators.local_energy import local_energy +from ipie.legacy.estimators.thermal import ( + greens_function, + one_rdm, + one_rdm_from_G, + one_rdm_stable, + particle_number, +) +from ipie.legacy.trial_density_matrices.chem_pot import compute_rho, find_chemical_potential +from ipie.utils.misc import update_stack + + +class OneBody(object): + def __init__( + self, + system, + hamiltonian, + beta, + dt, + options={}, + nav=None, + H1=None, + verbose=False, + ): + self.name = "thermal" + self.verbose = verbose + if H1 is None: + try: + self.H1 = hamiltonian.H1 + except AttributeError: + self.H1 = hamiltonian.h1e + else: + self.H1 = H1 + + if verbose: + print("# Building OneBody density matrix.") + print(f"# beta in OneBody: {beta}") + print(f"# dt in OneBody: {dt}") + + dmat_up = scipy.linalg.expm(-dt * (self.H1[0])) + dmat_down = scipy.linalg.expm(-dt * (self.H1[1])) + self.dmat = numpy.array([dmat_up, dmat_down]) + cond = numpy.linalg.cond(self.dmat[0]) + if verbose: + print(f"# condition number of BT: {cond: 10e}") + + if nav is not None: + self.nav = nav + else: + self.nav = options.get("nav", None) + if self.nav is None: + self.nav = system.nup + system.ndown + if verbose: + print(f"# Target average electron number: {self.nav}") + + self.max_it = options.get("max_it", 1000) + self.deps = options.get("threshold", 1e-6) + self.mu = options.get("mu", None) + + self.num_slices = int(beta / dt) + self.stack_size = options.get("stack_size", None) + + if self.stack_size == None: + if verbose: + print("# Estimating stack size from BT.") + eigs, ev = scipy.linalg.eigh(self.dmat[0]) + emax = numpy.max(eigs) + emin = numpy.min(eigs) + self.cond = numpy.linalg.cond(self.dmat[0]) + # We will end up multiplying many BTs together. Can roughly determine + # safe stack size from condition number of BT as the condition number of + # the product will scale roughly as cond(BT)^(number of products). + # We can determine a conservative stack size by requiring that the + # condition number of the product does not exceed 1e3. + self.stack_size = min(self.num_slices, int(3.0 / numpy.log10(self.cond))) + if verbose: + print( + "# Initial stack size, # of slices: {}, {}".format( + self.stack_size, self.num_slices + ) + ) + + # adjust stack size + self.stack_size = update_stack(self.stack_size, self.num_slices, verbose=verbose) + self.num_bins = int(beta / (self.stack_size * dt)) + + if verbose: + print(f"# Number of stacks: {self.num_bins}") + + sign = 1 + if hamiltonian._alt_convention: + if verbose: + print("# Using alternate sign convention for chemical potential.") + sign = -1 + dtau = self.stack_size * dt + self.dtau = dtau + + if self.mu is None: + self.rho = numpy.array( + [ + scipy.linalg.expm(-dtau * (self.H1[0])), + scipy.linalg.expm(-dtau * (self.H1[1])), + ] + ) + self.mu = find_chemical_potential( + hamiltonian._alt_convention, + self.rho, + dtau, + self.num_bins, + self.nav, + deps=self.deps, + max_it=self.max_it, + verbose=verbose, + ) + else: + self.rho = numpy.array( + [ + scipy.linalg.expm(-dtau * (self.H1[0])), + scipy.linalg.expm(-dtau * (self.H1[1])), + ] + ) + + if self.verbose: + print(f"# Chemical potential in trial density matrix: {self.mu: .10e}") + + self.P = one_rdm_stable(compute_rho(self.rho, self.mu, dtau, sign=sign), self.num_bins) + self.nav = particle_number(self.P).real + if self.verbose: + print(f"# Average particle number in trial density matrix: {self.nav}") + self.dmat = compute_rho(self.dmat, self.mu, dt, sign=sign) + self.dmat_inv = numpy.array( + [ + scipy.linalg.inv(self.dmat[0], check_finite=False), + scipy.linalg.inv(self.dmat[1], check_finite=False), + ] + ) + + self.G = numpy.array([greens_function(self.dmat[0]), greens_function(self.dmat[1])]) + self.error = False + self.init = numpy.array([0]) diff --git a/ipie/thermal/trial/utils.py b/ipie/thermal/trial/utils.py new file mode 100644 index 00000000..9ca857a2 --- /dev/null +++ b/ipie/thermal/trial/utils.py @@ -0,0 +1,39 @@ +from ipie.legacy.trial_density_matrices.mean_field import MeanField +from ipie.legacy.trial_density_matrices.onebody import OneBody + + +def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=None, verbose=False): + """Wrapper to select trial wavefunction class. + + Parameters + ---------- + + Returns + ------- + trial : class or None + Trial density matrix class. + """ + trial_type = options.get("name", "one_body") + if comm is None or comm.rank == 0: + if trial_type == "one_body_mod": + trial = OneBody( + system, + hamiltonian, + beta, + dt, + options=options, + H1=hamiltonian.h1e_mod, + verbose=verbose, + ) + elif trial_type == "one_body": + trial = OneBody(system, hamiltonian, beta, dt, options=options, verbose=verbose) + elif trial_type == "thermal_hartree_fock": + trial = MeanField(system, hamiltonian, beta, dt, options=options, verbose=verbose) + else: + trial = None + else: + trial = None + if comm is not None: + trial = comm.bcast(trial) + + return trial diff --git a/ipie/thermal/walkers/__init__.py b/ipie/thermal/walkers/__init__.py index c6cac692..e69de29b 100644 --- a/ipie/thermal/walkers/__init__.py +++ b/ipie/thermal/walkers/__init__.py @@ -1 +0,0 @@ -empty diff --git a/ipie/thermal/walkers/stack.py b/ipie/thermal/walkers/stack.py new file mode 100644 index 00000000..3550570d --- /dev/null +++ b/ipie/thermal/walkers/stack.py @@ -0,0 +1,393 @@ +import numpy +import scipy.linalg + +from ipie.utils.misc import get_numeric_names + +class PropagatorStack: + def __init__( + self, + stack_size, + ntime_slices, + nbasis, + dtype, + BT=None, + BTinv=None, + diagonal=False, + averaging=False, + lowrank=True, + thresh=1e-6, + ): + self.time_slice = 0 + self.stack_size = stack_size + self.ntime_slices = ntime_slices + self.nbins = ntime_slices // self.stack_size + self.diagonal_trial = diagonal + self.averaging = averaging + self.thresh = thresh + + self.lowrank = lowrank + self.ovlp = numpy.asarray([1.0, 1.0]) + + if self.lowrank: + assert diagonal + + self.reortho = 1 + + if self.nbins * self.stack_size < self.ntime_slices: + print("stack_size must divide the total path length") + assert self.nbins * self.stack_size == self.ntime_slices + + self.nbasis = nbasis + self.dtype = dtype + self.BT = BT + self.BTinv = BTinv + self.counter = 0 + self.block = 0 + + self.stack = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) + self.left = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) + self.right = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) + + self.G = numpy.asarray( + [numpy.eye(self.nbasis, dtype=dtype), numpy.eye(self.nbasis, dtype=dtype)] + ) + + if self.lowrank: + self.update_new = self.update_low_rank + else: + self.update_new = self.update_full_rank + + # Global block matrix + if self.lowrank: + self.Ql = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + self.Dl = numpy.zeros(shape=(2, nbasis), dtype=dtype) + self.Tl = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + + self.Qr = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + self.Dr = numpy.zeros(shape=(2, nbasis), dtype=dtype) + self.Tr = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + + self.CT = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + self.theta = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + self.mT = nbasis + + self.buff_names, self.buff_size = get_numeric_names(self.__dict__) + # set all entries to be the identity matrix + self.reset() + + def get(self, ix): + return self.stack[ix] + + def get_buffer(self): + s = 0 + buff = numpy.zeros(self.buff_size, dtype=numpy.complex128) + for d in self.buff_names: + data = self.__dict__[d] + if isinstance(data, (numpy.ndarray)): + buff[s : s + data.size] = data.ravel() + s += data.size + else: + buff[s : s + 1] = data + s += 1 + return buff + + def set_buffer(self, buff): + s = 0 + for d in self.buff_names: + data = self.__dict__[d] + if isinstance(data, numpy.ndarray): + self.__dict__[d] = buff[s : s + data.size].reshape(data.shape).copy() + dsize = data.size + else: + if isinstance(self.__dict__[d], int): + self.__dict__[d] = int(buff[s].real) + elif isinstance(self.__dict__[d], float): + self.__dict__[d] = float(buff[s].real) + else: + self.__dict__[d] = buff[s] + dsize = 1 + s += dsize + + def set_all(self, BT): + # Diagonal = True assumes BT is diagonal and left is also diagonal + if self.diagonal_trial: + for i in range(0, self.ntime_slices): + ix = i // self.stack_size # bin index + # Commenting out these two. It is only useful for Hubbard + self.left[ix, 0] = numpy.diag( + numpy.multiply(BT[0].diagonal(), self.left[ix, 0].diagonal()) + ) + self.left[ix, 1] = numpy.diag( + numpy.multiply(BT[1].diagonal(), self.left[ix, 1].diagonal()) + ) + self.stack[ix, 0] = self.left[ix, 0].copy() + self.stack[ix, 1] = self.left[ix, 1].copy() + else: + for i in range(0, self.ntime_slices): + ix = i // self.stack_size # bin index + self.left[ix, 0] = numpy.dot(BT[0], self.left[ix, 0]) + self.left[ix, 1] = numpy.dot(BT[1], self.left[ix, 1]) + self.stack[ix, 0] = self.left[ix, 0].copy() + self.stack[ix, 1] = self.left[ix, 1].copy() + + if self.lowrank: + self.initialize_left() + for s in [0, 1]: + self.Qr[s] = numpy.identity(self.nbasis, dtype=self.dtype) + self.Dr[s] = numpy.ones(self.nbasis, dtype=self.dtype) + self.Tr[s] = numpy.identity(self.nbasis, dtype=self.dtype) + + def reset(self): + self.time_slice = 0 + self.block = 0 + for i in range(0, self.nbins): + self.stack[i, 0] = numpy.identity(self.nbasis, dtype=self.dtype) + self.stack[i, 1] = numpy.identity(self.nbasis, dtype=self.dtype) + self.right[i, 0] = numpy.identity(self.nbasis, dtype=self.dtype) + self.right[i, 1] = numpy.identity(self.nbasis, dtype=self.dtype) + self.left[i, 0] = numpy.identity(self.nbasis, dtype=self.dtype) + self.left[i, 1] = numpy.identity(self.nbasis, dtype=self.dtype) + + if self.lowrank: + for s in [0, 1]: + self.Qr[s] = numpy.identity(self.nbasis, dtype=self.dtype) + self.Dr[s] = numpy.ones(self.nbasis, dtype=self.dtype) + self.Tr[s] = numpy.identity(self.nbasis, dtype=self.dtype) + + # Form BT product for i = 1, ..., nslices - 1 (i.e., skip i = 0) + # \TODO add non-diagonal version of this + def initialize_left(self): + assert self.diagonal_trial + for spin in [0, 1]: + # We will assume that B matrices are all diagonal for left.... + # B = self.stack[1] + B = self.stack[0] + self.Dl[spin] = B[spin].diagonal() + self.Ql[spin] = numpy.identity(B[spin].shape[0]) + self.Tl[spin] = numpy.identity(B[spin].shape[0]) + + # for ix in range(2, self.nbins): + for ix in range(1, self.nbins): + B = self.stack[ix] + C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) + self.Dl[spin] = C2 + + def update(self, B): + if self.counter == 0: + self.stack[self.block, 0] = numpy.identity(B.shape[-1], dtype=B.dtype) + self.stack[self.block, 1] = numpy.identity(B.shape[-1], dtype=B.dtype) + self.stack[self.block, 0] = B[0].dot(self.stack[self.block, 0]) + self.stack[self.block, 1] = B[1].dot(self.stack[self.block, 1]) + self.time_slice = self.time_slice + 1 + self.block = self.time_slice // self.stack_size + self.counter = (self.counter + 1) % self.stack_size + + def update_full_rank(self, B): + # Diagonal = True assumes BT is diagonal and left is also diagonal + if self.counter == 0: + self.right[self.block, 0] = numpy.identity(B.shape[-1], dtype=B.dtype) + self.right[self.block, 1] = numpy.identity(B.shape[-1], dtype=B.dtype) + + if self.diagonal_trial: + self.left[self.block, 0] = numpy.diag( + numpy.multiply(self.left[self.block, 0].diagonal(), self.BTinv[0].diagonal()) + ) + self.left[self.block, 1] = numpy.diag( + numpy.multiply(self.left[self.block, 1].diagonal(), self.BTinv[1].diagonal()) + ) + else: + self.left[self.block, 0] = self.left[self.block, 0].dot(self.BTinv[0]) + self.left[self.block, 1] = self.left[self.block, 1].dot(self.BTinv[1]) + + self.right[self.block, 0] = B[0].dot(self.right[self.block, 0]) + self.right[self.block, 1] = B[1].dot(self.right[self.block, 1]) + + if self.diagonal_trial: + self.stack[self.block, 0] = numpy.einsum( + "ii,ij->ij", self.left[self.block, 0], self.right[self.block, 0] + ) + self.stack[self.block, 1] = numpy.einsum( + "ii,ij->ij", self.left[self.block, 1], self.right[self.block, 1] + ) + else: + self.stack[self.block, 0] = self.left[self.block, 0].dot(self.right[self.block, 0]) + self.stack[self.block, 1] = self.left[self.block, 1].dot(self.right[self.block, 1]) + + self.time_slice = self.time_slice + 1 # Count the time slice + self.block = self.time_slice // self.stack_size # move to the next block if necessary + self.counter = (self.counter + 1) % self.stack_size # Counting within a stack + + def update_low_rank(self, B): + assert not self.averaging + # Diagonal = True assumes BT is diagonal and left is also diagonal + assert self.diagonal_trial + + if self.counter == 0: + for s in [0, 1]: + self.Tl[s] = self.left[self.block, s] + + mR = B.shape[-1] # initial mR + mL = B.shape[-1] # initial mR + mT = B.shape[-1] # initial mR + next_block = (self.time_slice + 1) // self.stack_size # move to the next block if necessary + # print("next_block", next_block) + # print("self.block", self.block) + if next_block > self.block: # Do QR and update here? + for s in [0, 1]: + mR = len(self.Dr[s][numpy.abs(self.Dr[s]) > self.thresh]) + self.Dl[s] = numpy.einsum("i,ii->i", self.Dl[s], self.BTinv[s]) + mL = len(self.Dl[s][numpy.abs(self.Dl[s]) > self.thresh]) + + self.Qr[s][:, :mR] = B[s].dot(self.Qr[s][:, :mR]) # N x mR + self.Qr[s][:, mR:] = 0.0 + + Ccr = numpy.einsum("ij,j->ij", self.Qr[s][:, :mR], self.Dr[s][:mR]) # N x mR + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) + Dlcr = Rlcr[:mR, :mR].diagonal() # mR + + self.Dr[s][:mR] = Dlcr + self.Dr[s][mR:] = 0.0 + self.Qr[s] = Qlcr + + Dinv = 1.0 / Dlcr # mR + tmp = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :mR]) # mR, mR x mR -> mR x mR + tmp[:, Plcr] = tmp[:, range(mR)] + Tlcr = numpy.dot(tmp, self.Tr[s][:mR, :]) # mR x N + + self.Tr[s][:mR, :] = Tlcr + + # assume left stack is all diagonal (i.e., QDT = diagonal -> Q and T are identity) + Clcr = numpy.einsum( + "i,ij->ij", + self.Dl[s][:mL], + numpy.einsum("ij,j->ij", Qlcr[:mL, :mR], Dlcr[:mR]), + ) # mL x mR + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr( + Clcr, pivoting=True, check_finite=False + ) # mL x mL, min(mL,mR) x min(mL,mR), mR x mR + Dlcr = Rlcr.diagonal()[: min(mL, mR)] + Dinv = 1.0 / Dlcr + + mT = len(Dlcr[numpy.abs(Dlcr) > self.thresh]) + + assert mT <= mL and mT <= mR + + tmp = numpy.einsum("i,ij->ij", Dinv[:mT], Rlcr[:mT, :]) + tmp[:, Plcr] = tmp[:, range(mR)] # mT x mR + Tlcr = numpy.dot(tmp, Tlcr) # mT x N + + Db = numpy.zeros(mT, B[s].dtype) + Ds = numpy.zeros(mT, B[s].dtype) + for i in range(mT): + absDlcr = abs(Dlcr[i]) + if absDlcr > 1.0: + Db[i] = 1.0 / absDlcr + Ds[i] = numpy.sign(Dlcr[i]) + else: + Db[i] = 1.0 + Ds[i] = Dlcr[i] + Dbinv = 1.0 / Db + + TQ = Tlcr[:, :mL].dot(Qlcr[:mL, :mT]) # mT x mT + TQinv = scipy.linalg.inv(TQ, check_finite=False) + tmp = numpy.einsum("ij,j->ij", TQinv, Db) + numpy.diag(Ds) # mT x mT + + M = numpy.einsum("ij,j->ij", tmp, Dbinv).dot(TQ) + # self.ovlp[s] = 1.0 / scipy.linalg.det(M, check_finite=False) + self.ovlp[s] = scipy.linalg.det(M, check_finite=False) + + tmp = scipy.linalg.inv(tmp, check_finite=False) + A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv)) # mT x mT + Qlcr_pad = numpy.zeros((self.nbasis, self.nbasis), dtype=B[s].dtype) + Qlcr_pad[:mL, :mT] = Qlcr[:, :mT] + + # self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - Qlcr_pad[:,:mT].dot(numpy.diag(Dlcr[:mT])).dot(A).dot(Tlcr) + + self.CT[s][:, :] = 0.0 + self.CT[s][:, :mT] = (A.dot(Tlcr)).T.conj() + self.theta[s][:, :] = 0.0 + self.theta[s][:mT, :] = Qlcr_pad[:, :mT].dot(numpy.diag(Dlcr[:mT])).T + # self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.CT[s][:,:mT].dot(self.theta[s][:mT,:]) + self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.theta[s][:mT, :].T.dot( + self.CT[s][:, :mT].T.conj() + ) + # self.CT[s][:,:mT] = self.CT[s][:,:mT].conj() + + # print("# mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) + else: # don't do QR and just update + for s in [0, 1]: + mR = len(self.Dr[s][numpy.abs(self.Dr[s]) > self.thresh]) + + self.Dl[s] = numpy.einsum("i,ii->i", self.Dl[s], self.BTinv[s]) + mL = len(self.Dl[s][numpy.abs(self.Dl[s]) > self.thresh]) + + self.Qr[s][:, :mR] = B[s].dot(self.Qr[s][:, :mR]) # N x mR + self.Qr[s][:, mR:] = 0.0 + + Ccr = numpy.einsum("ij,j->ij", self.Qr[s][:, :mR], self.Dr[s][:mR]) # N x mR + Clcr = numpy.einsum("i,ij->ij", self.Dl[s][:mL], Ccr[:mL, :mR]) # mL x mR + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr( + Clcr, pivoting=True, check_finite=False + ) # mL x mL, min(mL,mR) x min(mL,mR), mR x mR + Dlcr = Rlcr.diagonal()[: min(mL, mR)] + Dinv = 1.0 / Dlcr + + mT = len(Dlcr[numpy.abs(Dlcr) > self.thresh]) + + assert mT <= mL and mT <= mR + + tmp = numpy.einsum("i,ij->ij", Dinv[:mT], Rlcr[:mT, :]) + tmp[:, Plcr] = tmp[:, range(mR)] # mT x mR + Tlcr = numpy.dot(tmp, self.Tr[s][:mR, :]) # mT x N + + Db = numpy.zeros(mT, B[s].dtype) + Ds = numpy.zeros(mT, B[s].dtype) + for i in range(mT): + absDlcr = abs(Dlcr[i]) + if absDlcr > 1.0: + Db[i] = 1.0 / absDlcr + Ds[i] = numpy.sign(Dlcr[i]) + else: + Db[i] = 1.0 + Ds[i] = Dlcr[i] + Dbinv = 1.0 / Db + + TQ = Tlcr[:, :mL].dot(Qlcr[:mL, :mT]) # mT x mT + TQinv = scipy.linalg.inv(TQ, check_finite=False) + tmp = numpy.einsum("ij,j->ij", TQinv, Db) + numpy.diag(Ds) # mT x mT + + M = numpy.einsum("ij,j->ij", tmp, Dbinv).dot(TQ) + # self.ovlp[s] = 1.0 / scipy.linalg.det(M, check_finite=False) + self.ovlp[s] = scipy.linalg.det(M, check_finite=False) + + tmp = scipy.linalg.inv(tmp, check_finite=False) + A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv)) # mT x mT + Qlcr_pad = numpy.zeros((self.nbasis, self.nbasis), dtype=B[s].dtype) + Qlcr_pad[:mL, :mT] = Qlcr[:, :mT] + + # self.CT[s][:,:] = 0.0 + # self.CT[s][:,:mT] = Qlcr_pad[:,:mT].dot(numpy.diag(Dlcr[:mT])) + # self.theta[s][:,:] = 0.0 + # self.theta[s][:mT,:] = A.dot(Tlcr) + # self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.CT[s][:,:mT].dot(self.theta[s][:mT,:]) + # self.CT[s][:,:mT] = self.CT[s][:,:mT].conj() + self.CT[s][:, :] = 0.0 + self.CT[s][:, :mT] = (A.dot(Tlcr)).T.conj() + self.theta[s][:, :] = 0.0 + self.theta[s][:mT, :] = Qlcr_pad[:, :mT].dot(numpy.diag(Dlcr[:mT])).T + # self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.CT[s][:,:mT].dot(self.theta[s][:mT,:]) + self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.theta[s][:mT, :].T.dot( + self.CT[s][:, :mT].T.conj() + ) + + # self.CT = numpy.zeros(shape=(2, nbasis, nbasis),dtype=dtype) + # self.theta = numpy.zeros(shape=(2, nbasis, nbasis),dtype=dtype) + # print("# mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) + + # print("ovlp = {}".format(self.ovlp)) + self.mT = mT + self.time_slice = self.time_slice + 1 # Count the time slice + self.block = self.time_slice // self.stack_size # move to the next block if necessary + self.counter = (self.counter + 1) % self.stack_size # Counting within a stack diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py new file mode 100644 index 00000000..1a512ab7 --- /dev/null +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -0,0 +1,738 @@ +import cmath +import copy + +import numpy +import scipy.linalg + +from ipie.legacy.estimators.local_energy import local_energy_G +from ipie.legacy.estimators.thermal import greens_function, one_rdm_from_G, particle_number +from ipie.legacy.walkers.stack import PropagatorStack +from ipie.legacy.walkers.walker import Walker +from ipie.utils.linalg import regularise_matrix_inverse +from ipie.utils.misc import get_numeric_names, update_stack + + +class ThermalWalker(Walker): + def __init__(self, system, hamiltonian, trial, walker_opts={}, verbose=False): + Walker.__init__(self, system, hamiltonian, trial, walker_opts=walker_opts) + self.name = "ThermalWalker" + self.num_slices = trial.num_slices + dtype = numpy.complex128 + self.G = numpy.zeros(trial.dmat.shape, dtype=dtype) + self.Ghalf = None + self.nbasis = trial.dmat[0].shape[0] + self.stack_size = walker_opts.get("stack_size", None) + max_diff_diag = numpy.linalg.norm((numpy.diag(trial.dmat[0].diagonal()) - trial.dmat[0])) + if max_diff_diag < 1e-10: + self.diagonal_trial = True + if verbose: + print("# Trial density matrix is diagonal.") + else: + self.diagonal_trial = False + if verbose: + print("# Trial density matrix is not diagonal.") + + if self.stack_size == None: + self.stack_size = trial.stack_size + if (self.num_slices // self.stack_size) * self.stack_size != self.num_slices: + if verbose: + print("# Input stack size does not divide number of slices.") + self.stack_size = update_stack(self.stack_size, self.num_slices, verbose) + if self.stack_size > trial.stack_size: + if verbose: + print( + "# Walker stack size differs from that estimated from " "trial density matrix." + ) + print(f"# Be careful. cond(BT)**stack_size: {trial.cond ** self.stack_size:10.3e}.") + self.stack_length = self.num_slices // self.stack_size + if verbose: + print(f"# Walker stack size: {self.stack_size}") + + self.lowrank = walker_opts.get("low_rank", False) + self.lowrank_thresh = walker_opts.get("low_rank_thresh", 1e-6) + if verbose: + print(f"# Using low rank trick: {self.lowrank}") + self.stack = PropagatorStack( + self.stack_size, + trial.num_slices, + trial.dmat.shape[-1], + dtype, + trial.dmat, + trial.dmat_inv, + diagonal=self.diagonal_trial, + lowrank=self.lowrank, + thresh=self.lowrank_thresh, + ) + + # Initialise all propagators to the trial density matrix. + self.stack.set_all(trial.dmat) + self.greens_function_qr_strat(trial) + self.stack.G = self.G + self.M0 = numpy.array( + [ + scipy.linalg.det(self.G[0], check_finite=False), + scipy.linalg.det(self.G[1], check_finite=False), + ] + ) + self.stack.ovlp = numpy.array([1.0 / self.M0[0], 1.0 / self.M0[1]]) + + # # temporary storage for stacks... + I = numpy.identity(hamiltonian.nbasis, dtype=dtype) + One = numpy.ones(hamiltonian.nbasis, dtype=dtype) + self.Tl = numpy.array([I, I]) + self.Ql = numpy.array([I, I]) + self.Dl = numpy.array([One, One]) + self.Tr = numpy.array([I, I]) + self.Qr = numpy.array([I, I]) + self.Dr = numpy.array([One, One]) + + self.hybrid_energy = 0.0 + if verbose: + # def local_energy(self, system, two_rdm=None): + P = one_rdm_from_G(self.G) + eloc = local_energy_G(system, hamiltonian, self, P) + nav = particle_number(P) + print("# Initial walker energy: {} {} {}".format(*eloc)) + print(f"# Initial walker electron number: {nav}") + # self.buff_names = ['weight', 'G', 'unscaled_weight', 'phase', 'Tl', + # 'Ql', 'Dl', 'Tr', 'Qr', 'Dr', 'M0'] + self.buff_names, self.buff_size = get_numeric_names(self.__dict__) + # self.buff_size = (self.G.size+3+self.Tl.size+2+ + # self.Ql.size+self.Dl.size+self.Tr.size+self.Qr.size + # +self.Dr.size) + + def greens_function(self, trial, slice_ix=None, inplace=True): + if self.lowrank: + return self.stack.G + else: + return self.greens_function_qr_strat(trial, slice_ix=slice_ix, inplace=inplace) + + def greens_function_svd(self, trial, slice_ix=None, inplace=True): + if slice_ix == None: + slice_ix = self.stack.time_slice + bin_ix = slice_ix // self.stack.stack_size + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + if inplace: + G = None + else: + G = numpy.zeros(self.G.shape, self.G.dtype) + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} + # in stable way. Iteratively construct SVD decompositions starting + # from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + (U1, S1, V1) = scipy.linalg.svd(B[spin]) + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + T1 = numpy.dot(B[spin], U1) + # todo optimise + T2 = numpy.dot(T1, numpy.diag(S1)) + (U1, S1, V) = scipy.linalg.svd(T2) + V1 = numpy.dot(V, V1) + A = numpy.dot(U1.dot(numpy.diag(S1)), V1) + # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. + # Care needs to be taken when adding the identity matrix. + T3 = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) + (U2, S2, V2) = scipy.linalg.svd(T3) + U3 = numpy.dot(U1, U2) + D3 = numpy.diag(1.0 / S2) + V3 = numpy.dot(V2, V1) + # G(l) = (U3 S2 V3)^{-1} + # = V3^{\dagger} D3 U3^{\dagger} + if inplace: + # self.G[spin] = (V3inv).dot(U3.conj().T) + self.G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) + else: + # G[spin] = (V3inv).dot(U3.conj().T) + G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) + return G + + def greens_function_qr(self, trial, slice_ix=None, inplace=True): + if slice_ix == None: + slice_ix = self.stack.time_slice + + bin_ix = slice_ix // self.stack.stack_size + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} + # in stable way. Iteratively construct SVD decompositions starting + # from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + (U1, V1) = scipy.linalg.qr(B[spin], pivoting=False, check_finite=False) + + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + T1 = numpy.dot(B[spin], U1) + (U1, V) = scipy.linalg.qr(T1, pivoting=False, check_finite=False) + V1 = numpy.dot(V, V1) + + # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. + # Care needs to be taken when adding the identity matrix. + V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0])) + + T3 = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0]) + (U2, V2) = scipy.linalg.qr(T3, pivoting=False, check_finite=False) + + U3 = numpy.dot(U1, U2) + V3 = numpy.dot(V2, V1) + V3inv = scipy.linalg.solve_triangular(V3, numpy.identity(V3.shape[0])) + # G(l) = (U3 S2 V3)^{-1} + # = V3^{\dagger} D3 U3^{\dagger} + if inplace: + self.G[spin] = (V3inv).dot(U3.conj().T) + else: + G[spin] = (V3inv).dot(U3.conj().T) + return G + + def compute_left_right(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # right bit + # B(right) ... B(1) + if center_ix > 0: + # print ("center_ix > 0") + B = self.stack.get(0) + (self.Qr[spin], R1, P1) = scipy.linalg.qr( + B[spin], pivoting=True, check_finite=False + ) + # Form D matrices + self.Dr[spin] = R1.diagonal() + D1inv = 1.0 / R1.diagonal() + self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) + # now permute them + self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] + + for ix in range(1, center_ix): + B = self.stack.get(ix) + C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) + (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = 1.0 / R1.diagonal() + self.Dr[spin] = R1.diagonal() + # smarter permutation + # D^{-1} * R + tmp = numpy.einsum("i,ij->ij", D1inv, R1) + # D^{-1} * R * P^T + tmp[:, P1] = tmp[:, range(self.nbasis)] + # D^{-1} * R * P^T * T + self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) + + # left bit + # B(l) ... B(left) + if center_ix < self.stack.nbins - 1: + # print("center_ix < self.stack.nbins-1 first") + # We will assume that B matrices are all diagonal for left.... + B = self.stack.get(center_ix + 1) + self.Dl[spin] = B[spin].diagonal() + D1inv = 1.0 / B[spin].diagonal() + self.Ql[spin] = numpy.identity(B[spin].shape[0]) + self.Tl[spin] = numpy.identity(B[spin].shape[0]) + + for ix in range(center_ix + 2, self.stack.nbins): + # print("center_ix < self.stack.nbins-1 first inner loop") + B = self.stack.get(ix) + C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) + self.Dl[spin] = C2 + + def compute_right(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # right bit + # B(right) ... B(1) + if center_ix > 0: + # print ("center_ix > 0") + B = self.stack.get(0) + (self.Qr[spin], R1, P1) = scipy.linalg.qr( + B[spin], pivoting=True, check_finite=False + ) + # Form D matrices + self.Dr[spin] = R1.diagonal() + D1inv = 1.0 / R1.diagonal() + self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) + # now permute them + self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] + + for ix in range(1, center_ix): + B = self.stack.get(ix) + C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) + (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = 1.0 / R1.diagonal() + self.Dr[spin] = R1.diagonal() + # smarter permutation + # D^{-1} * R + tmp = numpy.einsum("i,ij->ij", D1inv, R1) + # D^{-1} * R * P^T + tmp[:, P1] = tmp[:, range(self.nbasis)] + # D^{-1} * R * P^T * T + self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) + + def compute_left(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # left bit + # B(l) ... B(left) + if center_ix < self.stack.nbins - 1: + # print("center_ix < self.stack.nbins-1 first") + # We will assume that B matrices are all diagonal for left.... + B = self.stack.get(center_ix + 1) + self.Dl[spin] = B[spin].diagonal() + self.Ql[spin] = numpy.identity(B[spin].shape[0]) + self.Tl[spin] = numpy.identity(B[spin].shape[0]) + + for ix in range(center_ix + 2, self.stack.nbins): + # print("center_ix < self.stack.nbins-1 first inner loop") + B = self.stack.get(ix) + C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) + self.Dl[spin] = C2.diagonal() + + def greens_function_left_right(self, center_ix, inplace=False, thresh=1e-6): + assert self.diagonal_trial + + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + mL = self.G.shape[1] + mR = self.G.shape[1] + mT = self.G.shape[1] + + Bc = self.stack.get(center_ix) + + nbsf = Bc.shape[1] + + # It goes to right to left and we sample (I + L*B*R) in the end + for spin in [0, 1]: + if center_ix > 0: # there exists right bit + mR = len(self.Dr[spin][numpy.abs(self.Dr[spin]) > thresh]) + + Ccr = numpy.einsum( + "ij,j->ij", + numpy.dot(Bc[spin], self.Qr[spin][:, :mR]), + self.Dr[spin][:mR], + ) # N x mR + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) + Dlcr = Rlcr[:mR, :mR].diagonal() # mR + Dinv = 1.0 / Dlcr # mR + tmp = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :mR]) # mR, mR x mR -> mR x mR + tmp[:, Plcr] = tmp[:, range(mR)] + Tlcr = numpy.dot(tmp, self.Tr[spin][:mR, :]) # mR x N + else: + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) + # Form D matrices + Dlcr = Rlcr.diagonal() + + mR = len(Dlcr[numpy.abs(Dlcr) > thresh]) + + Dinv = 1.0 / Rlcr.diagonal() + Tlcr = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :]) # mR x N + Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] # mR x N + + if center_ix < self.stack.nbins - 1: # there exists left bit + # assume left stack is all diagonal (i.e., QDT = diagonal -> Q and T are identity) + Clcr = numpy.einsum( + "i,ij->ij", + self.Dl[spin], + numpy.einsum("ij,j->ij", Qlcr[:, :mR], Dlcr[:mR]), + ) # N x mR + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr( + Clcr, pivoting=True, check_finite=False + ) # N x N, mR x mR + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Dlcr + + mT = len(Dlcr[numpy.abs(Dlcr) > thresh]) + + tmp = numpy.einsum("i,ij->ij", Dinv[:mT], Rlcr[:mT, :]) + tmp[:, Plcr] = tmp[:, range(mR)] # mT x mR + Tlcr = numpy.dot(tmp, Tlcr) # mT x N + else: + mT = mR + + # D = Ds Db^{-1} + Db = numpy.zeros(mT, Bc[spin].dtype) + Ds = numpy.zeros(mT, Bc[spin].dtype) + for i in range(mT): + absDlcr = abs(Dlcr[i]) + if absDlcr > 1.0: + Db[i] = 1.0 / absDlcr + Ds[i] = numpy.sign(Dlcr[i]) + else: + Db[i] = 1.0 + Ds[i] = Dlcr[i] + + if mT == nbsf: # No need for Woodbury + T1inv = scipy.linalg.inv(Tlcr, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), + numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), + ) + # return # This seems to change the answer WHY?? + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), + numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), + ) + else: # Use Woodbury + TQ = Tlcr.dot(Qlcr[:, :mT]) + TQinv = scipy.linalg.inv(TQ, check_finite=False) + tmp = scipy.linalg.inv( + numpy.einsum("ij,j->ij", TQinv, Db) + numpy.diag(Ds), + check_finite=False, + ) + A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv)) + if inplace: + self.G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( + numpy.diag(Dlcr[:mT]) + ).dot(A).dot(Tlcr) + else: + G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( + numpy.diag(Dlcr[:mT]) + ).dot(A).dot(Tlcr) + # print(mR,mT,nbsf) + # print("ref: mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) + return G + + def greens_function_left_right_no_truncation(self, center_ix, inplace=False): + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + Bc = self.stack.get(center_ix) + for spin in [0, 1]: + if center_ix > 0: # there exists right bit + # print("center_ix > 0 second") + Ccr = numpy.einsum("ij,j->ij", numpy.dot(Bc[spin], self.Qr[spin]), self.Dr[spin]) + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) + tmp[:, Plcr] = tmp[:, range(self.nbasis)] + Tlcr = numpy.dot(tmp, self.Tr[spin]) + else: + # print("center_ix > 0 else second") + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) + # Form D matrices + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + Tlcr = numpy.einsum("i,ij->ij", Dinv, Rlcr) + Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] + + if center_ix < self.stack.nbins - 1: # there exists left bit + # print("center_ix < self.stack.nbins-1 second") + # assume left stack is all diagonal + Clcr = numpy.einsum("i,ij->ij", self.Dl[spin], numpy.einsum("ij,j->ij", Qlcr, Dlcr)) + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Clcr, pivoting=True, check_finite=False) + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + + tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) + tmp[:, Plcr] = tmp[:, range(self.nbasis)] + Tlcr = numpy.dot(tmp, Tlcr) + + # print("Dlcr = {}".format(Dlcr)) + + # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T + # Write D = Db^{-1} Ds + # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T + Db = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) + Ds = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) + for i in range(Db.shape[0]): + absDlcr = abs(Dlcr[i]) + if absDlcr > 1.0: + Db[i] = 1.0 / absDlcr + Ds[i] = numpy.sign(Dlcr[i]) + else: + Db[i] = 1.0 + Ds[i] = Dlcr[i] + + T1inv = scipy.linalg.inv(Tlcr, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) + ) + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) + ) + return G + + def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + if slice_ix == None: + slice_ix = self.stack.time_slice + + bin_ix = slice_ix // self.stack.stack_size + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in + # stable way. Iteratively construct column pivoted QR decompositions + # (A = QDT) starting from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + + (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) + # Form D matrices + D1 = numpy.diag(R1.diagonal()) + D1inv = numpy.diag(1.0 / R1.diagonal()) + T1 = numpy.einsum("ii,ij->ij", D1inv, R1) + # permute them + T1[:, P1] = T1[:, range(self.nbasis)] + + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) + (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = numpy.diag(1.0 / R1.diagonal()) + D1 = numpy.diag(R1.diagonal()) + tmp = numpy.einsum("ii,ij->ij", D1inv, R1) + tmp[:, P1] = tmp[:, range(self.nbasis)] + T1 = numpy.dot(tmp, T1) + + # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T + # Write D = Db^{-1} Ds + # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T + Db = numpy.zeros(B[spin].shape, B[spin].dtype) + Ds = numpy.zeros(B[spin].shape, B[spin].dtype) + for i in range(Db.shape[0]): + absDlcr = abs(Db[i, i]) + if absDlcr > 1.0: + Db[i, i] = 1.0 / absDlcr + Ds[i, i] = numpy.sign(D1[i, i]) + else: + Db[i, i] = 1.0 + Ds[i, i] = D1[i, i] + + T1inv = scipy.linalg.inv(T1, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("ii,ij->ij", Db, Q1.conj().T), T1inv) + Ds + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) + ) + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) + ) + return G + + +# def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): +# def local_energy(self, system, two_rdm=None): +# rdm = one_rdm_from_G(self.G) +# return local_energy_G(system, hamiltonian, self, rdm) + + +def unit_test(): + from ipie.legacy.systems.ueg import UEG + from ipie.legacy.thermal_propagation.planewave import PlaneWave + from ipie.legacy.trial_density_matrices.onebody import OneBody + from ipie.legacy.qmc.options import QMCOpts + + inputs = { + "nup": 1, + "ndown": 1, + "rs": 1.0, + "ecut": 0.5, + "name": "one_body", + "mu": 1.94046021, + "beta": 0.5, + "dt": 0.05, + "optimised": True, + } + beta = inputs["beta"] + dt = inputs["dt"] + + system = UEG(inputs, verbose=False) + + qmc = QMCOpts(inputs, system, True) + trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False) + + walker = ThermalWalker(inputs, system, trial, True) + # walker.greens_function(trial) + E, T, V = walker.local_energy(system) + numpy.random.seed(0) + inputs["optimised"] = False + propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) + + propagator.propagate_walker_free(system, walker, trial, False) + + Gold = walker.G[0].copy() + + system = UEG(inputs, verbose=False) + + qmc = QMCOpts(inputs, system, verbose=False) + trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False) + + propagator = PlaneWave(inputs, qmc, system, trial, True) + walker = ThermalWalker(inputs, system, trial, verbose=False) + # walker.greens_function(trial) + E, T, V = walker.local_energy(system) + numpy.random.seed(0) + inputs["optimised"] = True + propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) + + propagator.propagate_walker_free(system, walker, trial, False) + + Gnew = walker.G[0].copy() + + assert scipy.linalg.norm(Gold[:, 0] - Gnew[:, 0]) < 1e-10 + + inputs["stack_size"] = 1 + walker = ThermalWalker(inputs, system, trial, verbose=False) + numpy.random.seed(0) + propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) + for i in range(0, 5): + propagator.propagate_walker(system, walker, trial) + Gs1 = walker.G[0].copy() + for ts in range(walker.stack_length): + walker.greens_function(trial, slice_ix=ts * walker.stack_size) + E, T, V = walker.local_energy(system) + # print(E) + + inputs["stack_size"] = 5 + walker = ThermalWalker(inputs, system, trial, verbose=False) + numpy.random.seed(0) + propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) + for i in range(0, 5): + propagator.propagate_walker(system, walker, trial) + Gs5 = walker.G[0].copy() + for ts in range(walker.stack_length): + walker.greens_function(trial, slice_ix=ts * walker.stack_size) + E, T, V = walker.local_energy(system) + # print(E) + assert numpy.linalg.norm(Gs1 - Gs5) < 1e-10 + + N = 5 + A = numpy.random.rand(N, N) + Q, R, P = scipy.linalg.qr(A, pivoting=True) + + #### test permutation start + # Pmat = numpy.zeros((N,N)) + # for i in range (N): + # Pmat[P[i],i] = 1 + # print(P) + # tmp = Q.dot(R)#.dot(Pmat.T) + # print(tmp) + # print("==================") + # tmp2 = tmp.dot(Pmat.T) + # print(tmp2) + # print("==================") + # tmp[:,P] = tmp [:,range(N)] + # print(tmp) + #### test permutation end + + B = numpy.random.rand(N, N) + (Q1, R1, P1) = scipy.linalg.qr(B, pivoting=True, check_finite=False) + # Form permutation matrix + P1mat = numpy.zeros(B.shape, B.dtype) + P1mat[P1, range(len(P1))] = 1.0 + # Form D matrices + D1 = numpy.diag(R1.diagonal()) + D1inv = numpy.diag(1.0 / R1.diagonal()) + T1 = numpy.dot(numpy.dot(D1inv, R1), P1mat.T) + + assert numpy.linalg.norm(B - numpy.einsum("ij,jj->ij", Q1, D1).dot(T1)) < 1e-10 + + # tmp[:,:] = tmp[:,P] + # print(A - tmp) + # print(Q * Q.T) + # print(R) + + # Test walker green's function. + from ipie.legacy.estimators.hubbard import local_energy_hubbard + from ipie.legacy.estimators.thermal import greens_function, one_rdm_from_G + from ipie.legacy.hamiltonians.hubbard import Hubbard + + sys_dict = { + "name": "Hubbard", + "nx": 4, + "ny": 4, + "nup": 7, + "ndown": 7, + "U": 4, + "t": 1, + } + system = Hubbard(sys_dict) + beta = 4 + mu = 1 + trial = OneBody({"mu": mu}, system, beta, dt, verbose=True) + + dt = 0.05 + num_slices = int(beta / dt) + + eref = 0 + for ek in system.eks: + eref += 2 * ek * 1.0 / (numpy.exp(beta * (ek - mu)) + 1) + walker = ThermalWalker({"stack_size": 1}, system, trial) + Gs1 = walker.G[0].copy() + rdm = one_rdm_from_G(walker.G) + ekin = local_energy_hubbard(system, rdm)[1] + try: + assert abs(eref - ekin) < 1e-8 + except AssertionError: + print(f"Error in kinetic energy check. Ref: {eref:13.8e} Calc:{ekin:13.8e}") + walker = ThermalWalker({"stack_size": 10}, system, trial) + rdm = one_rdm_from_G(walker.G) + ekin = local_energy_hubbard(system, rdm)[1] + try: + assert abs(eref - ekin) < 1e-8 + except AssertionError: + print( + "Error in kinetic energy check. Ref: %13.10e Calc: %13.10e" + " Error: %13.8e" % (eref.real, ekin.real, abs(eref - ekin)) + ) + for ts in range(walker.stack_length): + walker.greens_function(trial, slice_ix=ts * walker.stack_size) + assert numpy.linalg.norm(Gs1 - walker.G[0]) < 1e-10 + + +if __name__ == "__main__": + unit_test() From 2fa376277fe4f1c5426bc4574f26ce75f4b8a5fd Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Tue, 29 Aug 2023 18:07:50 -0400 Subject: [PATCH 06/84] add test without using mpi. qmc/tests/test_ft_integration.py --- .../reference_nompi.json | 1 + .../ft_ueg_ecut1.0_rs1.0/reference_nompi.json | 1 + ipie/qmc/tests/test_ft_integration.py | 117 ++++++++++++++++++ 3 files changed, 119 insertions(+) create mode 100644 ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json create mode 100644 ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json create mode 100644 ipie/qmc/tests/test_ft_integration.py diff --git a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json new file mode 100644 index 00000000..0fbf7b3e --- /dev/null +++ b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json @@ -0,0 +1 @@ +{"WeightFactor": [32.0, 44.98645457011622], "Weight": [32.0, 43.034282083027925], "ENumer": [152.0047418107588, 20.184762894579933], "EDenom": [32.0, 43.034282083027925], "ETotal": [4.750148181586212, 0.4690391454802612], "E1Body": [-7.499853241434117, -7.214851781729806], "E2Body": [12.250001423020322, 7.683890927210067], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154442, 13.233641168838517], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "a67b7598397a8e99b75d50bc67fd18ec2ee20b76-dirty", "numpy": {"version": "1.24.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}, "mpi4py": {"version": "3.1.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/mpi4py", "mpicc": "/sw/spack/delta-2022-03/apps/openmpi/4.1.4-gcc-11.2.0-7ooytax/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json new file mode 100644 index 00000000..553a1533 --- /dev/null +++ b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json @@ -0,0 +1 @@ +{"WeightFactor": [32.0, 47.79071285048463], "Weight": [32.0, 31.999999999999996], "ENumer": [853.4128425513711, 986.9792326724249], "EDenom": [32.0, 31.999999999999996], "ETotal": [26.669151329730347, 30.843101021013286], "E1Body": [28.374994808285724, 33.221059734849845], "E2Body": [-1.7058434785553744, -2.3779587138365548], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209661, 16.377795476555466], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "a67b7598397a8e99b75d50bc67fd18ec2ee20b76-dirty", "numpy": {"version": "1.24.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}, "mpi4py": {"version": "3.1.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/mpi4py", "mpicc": "/sw/spack/delta-2022-03/apps/openmpi/4.1.4-gcc-11.2.0-7ooytax/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/qmc/tests/test_ft_integration.py b/ipie/qmc/tests/test_ft_integration.py new file mode 100644 index 00000000..17000af3 --- /dev/null +++ b/ipie/qmc/tests/test_ft_integration.py @@ -0,0 +1,117 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + +import json +import os +import sys +import tempfile +import uuid + +import numpy as np + +from ipie.analysis.extraction import extract_test_data_hdf5 +from ipie.config import MPI +from ipie.qmc.calc import get_driver, read_input + +_built_legacy = True + + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) +else: + test_id = None +test_id = comm.bcast(test_id, root=0) + +_data_dir = os.path.abspath(os.path.dirname(__file__)) + "/reference_data/" +_legacy_test_dirs = [ + "ft_4x4_hubbard_discrete", + "ft_ueg_ecut1.0_rs1.0", +] + + +_legacy_tests = [ + (_data_dir + d + "/input.json", _data_dir + d + "/reference_nompi.json") for d in _legacy_test_dirs +] + + +def compare_test_data(ref, test): + comparison = {} + for k, v in ref.items(): + if k == "sys_info": + continue + try: + comparison[k] = ( + np.array(ref[k]), + np.array(test[k]), + np.max(np.abs(np.array(ref[k]) - np.array(test[k]))) < 1e-10, + ) + except KeyError: + print(f"# Issue with test data key {k}") + return comparison + + +def run_test_system(input_file, benchmark_file, legacy_job=False): + comm = MPI.COMM_WORLD + input_dict = read_input(input_file, comm) + if input_dict["system"].get("integrals") is not None: + input_dict["system"]["integrals"] = input_file[:-10] + "afqmc.h5" + input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" + elif ("hamiltonian" in input_dict) and (input_dict["hamiltonian"].get("integrals") is not None): + input_dict["hamiltonian"]["integrals"] = input_file[:-10] + "afqmc.h5" + input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" + with tempfile.NamedTemporaryFile() as tmpf: + input_dict["estimators"]["filename"] = tmpf.name + if _built_legacy and legacy_job: + from ipie.legacy.qmc.calc import get_driver as get_legacy_driver + + input_dict["qmc"]["batched"] = False + afqmc = get_legacy_driver(input_dict, comm) + afqmc.run(comm=comm) + afqmc.finalise(comm) + else: + print('here') + afqmc = get_driver(input_dict, comm) + afqmc.run(estimator_filename=tmpf.name) + afqmc.finalise() + with open(benchmark_file, "r") as f: + ref_data = json.load(f) + skip_val = ref_data.get("extract_skip_value", 10) + test_data = extract_test_data_hdf5(tmpf.name, skip=skip_val) + comparison = compare_test_data(ref_data, test_data) + + return comparison + + +if __name__ == "__main__": + err_count = 0 + for test_name, (ind, outd) in zip(_legacy_test_dirs, _legacy_tests): + comparison = run_test_system(ind, outd, legacy_job=True) + local_err_count = 0 + for k, v in comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f" *** FAILED *** : mismatch between benchmark and test run: {test_name}") + err_count += 1 + print(f"name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + if local_err_count == 0: + print(f"*** PASSED : {test_name} ***") + err_count = comm.bcast(err_count) + sys.exit(err_count) From 98c4982e359304affc5f27b3fd0fe2ea01befc96 Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Tue, 29 Aug 2023 22:14:52 -0400 Subject: [PATCH 07/84] revise; 32 to 1 walker reference. thermal folder is legacy free clean up thermal, add some files needed from legacy, will remove later clean up thermal --- ipie/legacy/hamiltonians/utils.py | 6 +- ipie/thermal/__init__.py | 2 +- ipie/thermal/estimators/fock.py | 15 + ipie/thermal/estimators/generic.py | 511 ++++++++++++ ipie/thermal/estimators/handler.py | 135 ++++ ipie/thermal/estimators/hubbard.py | 159 ++++ ipie/thermal/estimators/local_energy.py | 131 ++++ ipie/thermal/estimators/mixed.py | 485 ++++++++++++ ipie/thermal/estimators/pw_fft.py | 345 ++++++++ ipie/thermal/estimators/ueg.py | 290 +++++++ ipie/thermal/estimators/ueg_kernels.pyx | 169 ++++ ipie/thermal/estimators/utils.py | 318 ++++++++ ipie/thermal/hamiltonians/_generic.py | 320 ++++++++ ipie/thermal/hamiltonians/hubbard.py | 400 ++++++++++ ipie/thermal/hamiltonians/ueg.py | 481 ++++++++++++ ipie/thermal/hamiltonians/utils.py | 53 ++ ipie/thermal/propagation/continuous.py | 12 +- ipie/thermal/propagation/generic.py | 9 +- ipie/thermal/propagation/hubbard.py | 271 +++++++ ipie/thermal/propagation/planewave.py | 7 +- ipie/thermal/propagation/utils.py | 70 ++ ipie/thermal/qmc/calc.py | 33 + ipie/thermal/qmc/options.py | 150 ++++ ipie/thermal/qmc/thermal_afqmc.py | 24 +- ipie/thermal/system/hubbard_holstein.py | 505 ++++++++++++ ipie/thermal/system/ueg.py | 98 +++ ipie/thermal/system/utils.py | 45 ++ ipie/thermal/tests/__init__.py | 16 + .../ft_4x4_hubbard_discrete/input.json | 32 + .../ft_4x4_hubbard_discrete/reference.json | 1 + .../reference_1walker.json | 1 + .../reference_nompi.json | 1 + .../ft_ueg_ecut1.0_rs1.0/input.json | 32 + .../ft_ueg_ecut1.0_rs1.0/reference.json | 1 + .../reference_1walker.json | 1 + .../ft_ueg_ecut1.0_rs1.0/reference_nompi.json | 1 + ipie/thermal/tests/test_ft_integration.py | 116 +++ ipie/thermal/trial/chem_pot.py | 2 +- ipie/thermal/trial/mean_field.py | 10 +- ipie/thermal/trial/onebody.py | 9 +- ipie/thermal/trial/utils.py | 4 +- ipie/thermal/walkers/handler.py | 429 ++++++++++ ipie/thermal/walkers/stack.py | 1 + ipie/thermal/walkers/thermal.py | 734 ++++++++++++++++++ ipie/thermal/walkers/uhf_walkers.py | 14 +- ipie/thermal/walkers/walker.py | 135 ++++ setup.py | 6 + 47 files changed, 6525 insertions(+), 65 deletions(-) create mode 100644 ipie/thermal/estimators/fock.py create mode 100644 ipie/thermal/estimators/generic.py create mode 100644 ipie/thermal/estimators/handler.py create mode 100644 ipie/thermal/estimators/hubbard.py create mode 100644 ipie/thermal/estimators/local_energy.py create mode 100644 ipie/thermal/estimators/mixed.py create mode 100644 ipie/thermal/estimators/pw_fft.py create mode 100644 ipie/thermal/estimators/ueg.py create mode 100644 ipie/thermal/estimators/ueg_kernels.pyx create mode 100644 ipie/thermal/estimators/utils.py create mode 100644 ipie/thermal/hamiltonians/_generic.py create mode 100644 ipie/thermal/hamiltonians/hubbard.py create mode 100644 ipie/thermal/hamiltonians/ueg.py create mode 100644 ipie/thermal/hamiltonians/utils.py create mode 100644 ipie/thermal/propagation/hubbard.py create mode 100644 ipie/thermal/propagation/utils.py create mode 100644 ipie/thermal/qmc/calc.py create mode 100644 ipie/thermal/qmc/options.py create mode 100644 ipie/thermal/system/hubbard_holstein.py create mode 100644 ipie/thermal/system/ueg.py create mode 100644 ipie/thermal/system/utils.py create mode 100644 ipie/thermal/tests/__init__.py create mode 100644 ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/input.json create mode 100644 ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference.json create mode 100644 ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_1walker.json create mode 100644 ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json create mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json create mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json create mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_1walker.json create mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json create mode 100644 ipie/thermal/tests/test_ft_integration.py create mode 100644 ipie/thermal/walkers/handler.py create mode 100644 ipie/thermal/walkers/thermal.py create mode 100644 ipie/thermal/walkers/walker.py diff --git a/ipie/legacy/hamiltonians/utils.py b/ipie/legacy/hamiltonians/utils.py index 670d0f84..34f03935 100644 --- a/ipie/legacy/hamiltonians/utils.py +++ b/ipie/legacy/hamiltonians/utils.py @@ -2,9 +2,9 @@ import time from ipie.hamiltonians.utils import get_generic_integrals -from ipie.legacy.hamiltonians._generic import Generic -from ipie.legacy.hamiltonians.hubbard import Hubbard -from ipie.legacy.hamiltonians.ueg import UEG +from ipie.thermal.hamiltonians._generic import Generic +from ipie.thermal.hamiltonians.hubbard import Hubbard +from ipie.thermal.hamiltonians.ueg import UEG def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): diff --git a/ipie/thermal/__init__.py b/ipie/thermal/__init__.py index c6cac692..8b137891 100644 --- a/ipie/thermal/__init__.py +++ b/ipie/thermal/__init__.py @@ -1 +1 @@ -empty + diff --git a/ipie/thermal/estimators/fock.py b/ipie/thermal/estimators/fock.py new file mode 100644 index 00000000..676cf89f --- /dev/null +++ b/ipie/thermal/estimators/fock.py @@ -0,0 +1,15 @@ +from ipie.estimators.generic import fock_generic +from ipie.thermal.estimators.hubbard import fock_hubbard +from ipie.thermal.estimators.ueg import fock_ueg + + +def fock_matrix(system, G): + if system.name == "UEG": + return fock_ueg(system, G) + elif system.name == "Generic": + return fock_generic(system, G) + elif system.name == "Hubbard": + return fock_hubbard(system, G) + else: + print(f"# Fock matrix not implemented for {system.name}") + return None diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py new file mode 100644 index 00000000..8dc3c627 --- /dev/null +++ b/ipie/thermal/estimators/generic.py @@ -0,0 +1,511 @@ + +import numpy + +from ipie.utils.misc import is_cupy + + +def local_energy_generic_pno( + system, + G, + Ghalf=None, + eri=None, + C0=None, + ecoul0=None, + exxa0=None, + exxb0=None, + UVT=None, +): + na = system.nup + nb = system.ndown + M = system.nbasis + + UVT_aa = UVT[0] + UVT_bb = UVT[1] + UVT_ab = UVT[2] + + Ga, Gb = Ghalf[0], Ghalf[1] + + # Element wise multiplication. + e1b = numpy.sum(system.H1[0] * G[0]) + numpy.sum(system.H1[1] * G[1]) + + eJaa = 0.0 + eKaa = 0.0 + + if len(C0.shape) == 3: + CT = C0[0, :, :].T + else: + CT = C0[:, :].T + + GTa = CT[:na, :] # hard-coded to do single slater + GTb = CT[na:, :] # hard-coded to do single slater + + for (i, j), (U, VT) in zip(system.ij_list_aa, UVT_aa): + if i == j: + c = 0.5 + else: + c = 1.0 + + theta_i = Ga[i, :] + theta_j = Ga[j, :] + + thetaT_i = GTa[i, :] + thetaT_j = GTa[j, :] + + thetaU = numpy.einsum("p,pk->k", theta_i, U) + thetaV = numpy.einsum("p,kp->k", theta_j, VT) + + thetaTU = numpy.einsum("p,pk->k", thetaT_i, U) + thetaTV = numpy.einsum("p,kp->k", thetaT_j, VT) + + eJaa += c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) + + thetaU = numpy.einsum("p,pk->k", theta_j, U) + thetaV = numpy.einsum("p,kp->k", theta_i, VT) + thetaTU = numpy.einsum("p,pk->k", thetaT_j, U) + thetaTV = numpy.einsum("p,kp->k", thetaT_i, VT) + eKaa -= c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) + + eJbb = 0.0 + eKbb = 0.0 + + for (i, j), (U, VT) in zip(system.ij_list_bb, UVT_bb): + if i == j: + c = 0.5 + else: + c = 1.0 + + theta_i = Gb[i, :] + theta_j = Gb[j, :] + thetaT_i = GTb[i, :] + thetaT_j = GTb[j, :] + + thetaU = numpy.einsum("p,pk->k", theta_i, U) + thetaV = numpy.einsum("p,kp->k", theta_j, VT) + thetaTU = numpy.einsum("p,pk->k", thetaT_i, U) + thetaTV = numpy.einsum("p,kp->k", thetaT_j, VT) + eJbb += c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) + + thetaU = numpy.einsum("p,pk->k", theta_j, U) + thetaV = numpy.einsum("p,kp->k", theta_i, VT) + thetaTU = numpy.einsum("p,pk->k", thetaT_j, U) + thetaTV = numpy.einsum("p,kp->k", thetaT_i, VT) + eKbb -= c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) + + eJab = 0.0 + for (i, j), (U, VT) in zip(system.ij_list_ab, UVT_ab): + theta_i = Ga[i, :] + theta_j = Gb[j, :] + thetaT_i = GTa[i, :] + thetaT_j = GTb[j, :] + thetaU = numpy.einsum("p,pk->k", theta_i, U) + thetaV = numpy.einsum("p,kp->k", theta_j, VT) + thetaTU = numpy.einsum("p,pk->k", thetaT_i, U) + thetaTV = numpy.einsum("p,kp->k", thetaT_j, VT) + eJab += numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV) + + e2b = 0.5 * (ecoul0 - exxa0 - exxb0) + eJaa + eJbb + eJab + eKaa + eKbb + + return (e1b + e2b + system.ecore, e1b + system.ecore, e2b) + + +def _exx_compute_batch(rchol_a, rchol_b, GaT_stacked, GbT_stacked, lwalker): + """ + Internal function for computing exchange two-electron integral energy + of batched walkers. The stacked batching ends up being about 30% faster + than simple loop over walkers. + + Parameters + ---------- + rchol_a: :class:`numpy.ndarray` + alpha-spin half-rotated cholesky vectors that are (naux, nalpha, nbasis) + rchol_b: :class:`numpy.ndarray` + beta-spin half-rotated cholesky vectors that are (naux, nbeta, nbasis) + GaT_stacked: :class:`numpy.ndarray` + alpha-spin half-rotated Greens function of size (nbasis, nalpha * nwalker) + GbT_stacked: :class:`numpy.ndarray` + beta-spin half-rotated Greens function of size (nbasis, nbeta * nwalker) + Returns + ------- + exx: numpy.ndarary + vector of exchange contributions for each walker + """ + naux = rchol_a.shape[0] + nbasis = GaT_stacked.shape[0] + nalpha = GaT_stacked.shape[1] // lwalker + nbeta = GbT_stacked.shape[1] // lwalker + + exx_vec_a = numpy.zeros(lwalker, dtype=numpy.complex128) + exx_vec_b = numpy.zeros(lwalker, dtype=numpy.complex128) + + # Ta = numpy.zeros((nalpha, nalpha * lwalker), dtype=numpy.complex128) + # Tb = numpy.zeros((nbeta, nbeta * lwalker), dtype=numpy.complex128) + + # Writing this way so in the future we can vmap of naux index of rchol_a + for x in range(naux): + rmi_a = rchol_a[x].reshape((nalpha, nbasis)) # can we get rid of this? + Ta = rmi_a.dot(GaT_stacked) # (na, na x nwalker) + # Ta = rmi_a.real.dot(GaT_stacked.real) + 1j * rmi_a.real.dot(GaT_stacked.imag) + rmi_b = rchol_b[x].reshape((nbeta, nbasis)) + Tb = rmi_b.dot(GbT_stacked) # (nb, nb x nwalker) + # Tb = rmi_b.real.dot(GbT_stacked.real) + 1j * rmi_b.real.dot(GbT_stacked.imag) + Ta = Ta.reshape((nalpha, lwalker, nalpha)) # reshape into 3-tensor for tdot + Tb = Tb.reshape((nbeta, lwalker, nbeta)) + exx_vec_a += numpy.einsum("ikj,jki->k", Ta, Ta, optimize=True) + exx_vec_b += numpy.einsum("ikj,jki->k", Tb, Tb, optimize=True) + return exx_vec_b + exx_vec_a + + +def local_energy_generic_cholesky_opt_batched( + system, + ham, + Ga_batch: numpy.ndarray, + Gb_batch: numpy.ndarray, + Ghalfa_batch: numpy.ndarray, + Ghalfb_batch: numpy.ndarray, + rchola: numpy.ndarray, + rcholb: numpy.ndarray, +): + r"""Calculate local for generic two-body hamiltonian. + + This uses the cholesky decomposed two-electron integrals. and batched + walkers. The intended use is CPU batching where walker G functions are + stacked so we can use gemm on bigger arrays. + + Parameters + ---------- + system : :class:`Generic` + System information for Generic. + ham : :class:`Abinitio` + Contains necessary hamiltonian information + Ga_batched : :class:`numpy.ndarray` + alpha-spin Walker's "green's function" 3-tensor (nwalker, nbasis, nbasis) + Gb_batched : :class:`numpy.ndarray` + beta-spin Walker's "green's function" 3-tensor (nwalker, nbasis, nbasis) + Ghalfa_batched : :class:`numpy.ndarray` + alpha-spin Walker's half-rotated "green's function" 3-tensor (nwalker, nalpha, nbasis) + Ghalfb_batched : :class:`numpy.ndarray` + beta-spin Walker's half-rotated "green's function" 3-tensor (nwalker, nbeta, nbasis) + rchola : :class:`numpy.ndarray` + alpha-spin trial's half-rotated choleksy vectors (naux, nalpha * nbasis) + rcholb : :class:`numpy.ndarray` + beta-spin trial's half-rotated choleksy vectors (naux, nbeta * nbasis) + + Returns + ------- + (E, T, V): tuple of vectors + vectors of Local, kinetic and potential energies for each walker + """ + # Element wise multiplication. + nwalker = Ga_batch.shape[0] + e1_vec = numpy.zeros(nwalker, dtype=numpy.complex128) + ecoul_vec = numpy.zeros(nwalker, dtype=numpy.complex128) + # simple loop because this part isn't the slow bit + for widx in range(nwalker): + e1b = numpy.sum(ham.H1[0] * Ga_batch[widx]) + numpy.sum(ham.H1[1] * Gb_batch[widx]) + e1_vec[widx] = e1b + nalpha, nbeta = system.nup, system.ndown + nbasis = ham.nbasis + if rchola is not None: + naux = rchola.shape[0] + + Xa = rchola.dot(Ghalfa_batch[widx].ravel()) + Xb = rcholb.dot(Ghalfb_batch[widx].ravel()) + ecoul = numpy.dot(Xa, Xa) + ecoul += numpy.dot(Xb, Xb) + ecoul += 2 * numpy.dot(Xa, Xb) + ecoul_vec[widx] = ecoul + + # transpose batch of walkers as exx prep + GhalfaT_stacked = numpy.hstack([*Ghalfa_batch.transpose((0, 2, 1)).copy()]) + GhalfbT_stacked = numpy.hstack([*Ghalfb_batch.transpose((0, 2, 1)).copy()]) + # call batched exx computation + exx_vec = _exx_compute_batch( + rchol_a=rchola, + rchol_b=rcholb, + GaT_stacked=GhalfaT_stacked, + GbT_stacked=GhalfbT_stacked, + lwalker=nwalker, + ) + e2b_vec = 0.5 * (ecoul_vec - exx_vec) + + return (e1_vec + e2b_vec + ham.ecore, e1_vec + ham.ecore, e2b_vec) + + +def local_energy_generic_cholesky(system, ham, G, Ghalf=None): + r"""Calculate local for generic two-body hamiltonian. + + This uses the cholesky decomposed two-electron integrals. + + Parameters + ---------- + system : :class:`Generic` + generic system information + ham : :class:`Generic` + ab-initio hamiltonian information + G : :class:`numpy.ndarray` + Walker's "green's function" + + Returns + ------- + (E, T, V): tuple + Local, kinetic and potential energies. + """ + # Element wise multiplication. + e1b = numpy.sum(ham.H1[0] * G[0]) + numpy.sum(ham.H1[1] * G[1]) + nalpha, nbeta = system.nup, system.ndown + nbasis = ham.nbasis + nchol = ham.nchol + Ga, Gb = G[0], G[1] + + # Xa = numpy.dot(ham.chol_vecs, Ga.ravel()) + # Xb = numpy.dot(ham.chol_vecs, Gb.ravel()) + + if numpy.isrealobj(ham.chol_vecs): + # Xa = ham.chol_vecs.T.dot(Ga.real.ravel()) + 1.j * ham.chol_vecs.dot(Ga.imag.ravel()) + # Xb = ham.chol_vecs.T.dot(Gb.real.ravel()) + 1.j * ham.chol_vecs.dot(Gb.imag.ravel()) + Xa = ham.chol_vecs.T.dot(Ga.real.ravel()) + 1.0j * ham.chol_vecs.T.dot(Ga.imag.ravel()) + Xb = ham.chol_vecs.T.dot(Gb.real.ravel()) + 1.0j * ham.chol_vecs.T.dot(Gb.imag.ravel()) + else: + Xa = ham.chol_vecs.T.dot(Ga.ravel()) + Xb = ham.chol_vecs.T.dot(Gb.ravel()) + + ecoul = numpy.dot(Xa, Xa) + ecoul += numpy.dot(Xb, Xb) + ecoul += 2 * numpy.dot(Xa, Xb) + + # T[l,k,n] = \sum_i L[i,k,n] G[i,l] + # exx = \sum_{nlk} T[l,k,n] T[k,l,n] + # cv = ham.chol_vecs.T.reshape((nbasis,nbasis,-1)) + # Ta = numpy.tensordot(Ga, cv, axes=((0),(0))) + # exxa = numpy.tensordot(Ta, Ta, axes=((0,1,2),(1,0,2))) + # Tb = numpy.tensordot(Gb, cv, axes=((0),(0))) + # exxb = numpy.tensordot(Tb, Tb, axes=((0,1,2),(1,0,2))) + # exx = exxa + exxb + # e2b = 0.5 * (ecoul - exx) + + T = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) + + GaT = Ga.T.copy() + GbT = Gb.T.copy() + + exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta + if numpy.isrealobj(ham.chol_vecs): + for x in range(nchol): # write a cython function that calls blas for this. + Lmn = ham.chol_vecs[:, x].reshape((nbasis, nbasis)) + T[:, :].real = GaT.real.dot(Lmn) + T[:, :].imag = GaT.imag.dot(Lmn) + exx += numpy.trace(T.dot(T)) + T[:, :].real = GbT.real.dot(Lmn) + T[:, :].imag = GbT.imag.dot(Lmn) + exx += numpy.trace(T.dot(T)) + else: + for x in range(nchol): # write a cython function that calls blas for this. + Lmn = ham.chol_vecs[:, x].reshape((nbasis, nbasis)) + T[:, :] = GaT.dot(Lmn) + exx += numpy.trace(T.dot(T)) + T[:, :] = GbT.dot(Lmn) + exx += numpy.trace(T.dot(T)) + + e2b = 0.5 * (ecoul - exx) + + return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) + + +def local_energy_generic_cholesky_opt_stochastic( + system, G, nsamples, Ghalf, rchol=None, C0=None, ecoul0=None, exxa0=None, exxb0=None +): + r"""Calculate local for generic two-body hamiltonian. + This uses the cholesky decomposed two-electron integrals. + Parameters + ---------- + system : :class:`hubbard` + System information for the hubbard model. + G : :class:`numpy.ndarray` + Walker's "green's function" + Returns + ------- + (E, T, V): tuple + Local, kinetic and potential energies. + """ + # import cProfile + # pr = cProfile.Profile() + # pr.enable() + + if type(C0) == numpy.ndarray: + control = True + else: + control = False + + # Element wise multiplication. + e1b = numpy.sum(system.H1[0] * G[0]) + numpy.sum(system.H1[1] * G[1]) + if rchol is None: + rchol = system.rchol + nalpha, nbeta = system.nup, system.ndown + nbasis = system.nbasis + Ga, Gb = Ghalf[0], Ghalf[1] + Xa = rchol[0].T.dot(Ga.ravel()) + Xb = rchol[1].T.dot(Gb.ravel()) + ecoul = numpy.dot(Xa, Xa) + ecoul += numpy.dot(Xb, Xb) + ecoul += 2 * numpy.dot(Xa, Xb) + if system.sparse: + rchol_a, rchol_b = [rchol[0].toarray(), rchol[1].toarray()] + else: + rchol_a, rchol_b = rchol[0], rchol[1] + + # T_{abn} = \sum_k Theta_{ak} LL_{ak,n} + # LL_{ak,n} = \sum_i L_{ik,n} A^*_{ia} + + naux = rchol_a.shape[-1] + + theta = numpy.zeros((naux, nsamples), dtype=numpy.int64) + for i in range(nsamples): + theta[:, i] = 2 * numpy.random.randint(0, 2, size=(naux)) - 1 + + if control: + ra = rchol_a.dot(theta).T * numpy.sqrt(1.0 / nsamples) + rb = rchol_b.dot(theta).T * numpy.sqrt(1.0 / nsamples) + + Ta0 = numpy.zeros((nsamples, nalpha, nalpha), dtype=rchol_a.dtype) + Tb0 = numpy.zeros((nsamples, nbeta, nbeta), dtype=rchol_b.dtype) + + Ta = numpy.zeros((nsamples, nalpha, nalpha), dtype=rchol_a.dtype) + Tb = numpy.zeros((nsamples, nbeta, nbeta), dtype=rchol_b.dtype) + + G0aT = C0[:, : system.nup] + G0bT = C0[:, system.nup :] + + GaT = Ga.T + GbT = Gb.T + + for x in range(nsamples): + rmi_a = ra[x].reshape((nalpha, nbasis)) + rmi_b = rb[x].reshape((nbeta, nbasis)) + + Ta0[x] = rmi_a.dot(G0aT) + Tb0[x] = rmi_b.dot(G0bT) + Ta[x] = rmi_a.dot(GaT) + Tb[x] = rmi_b.dot(GbT) + + exxa_hf = numpy.tensordot(Ta0, Ta0, axes=((0, 1, 2), (0, 2, 1))) + exxb_hf = numpy.tensordot(Tb0, Tb0, axes=((0, 1, 2), (0, 2, 1))) + + exxa_corr = numpy.tensordot(Ta, Ta, axes=((0, 1, 2), (0, 2, 1))) + exxb_corr = numpy.tensordot(Tb, Tb, axes=((0, 1, 2), (0, 2, 1))) + + exxa = exxa0 + (exxa_corr - exxa_hf) + exxb = exxb0 + (exxb_corr - exxb_hf) + + else: + rchol_a = rchol_a.reshape((nalpha, nbasis, naux)) + rchol_b = rchol_b.reshape((nbeta, nbasis, naux)) + + ra = numpy.einsum("ipX,Xs->ips", rchol_a, theta, optimize=True) * numpy.sqrt(1.0 / nsamples) + Gra = numpy.einsum("kq,lqx->lkx", Ga, ra, optimize=True) + exxa = numpy.tensordot(Gra, Gra, axes=((0, 1, 2), (1, 0, 2))) + + rb = numpy.einsum("ipX,Xs->ips", rchol_b, theta, optimize=True) * numpy.sqrt(1.0 / nsamples) + Grb = numpy.einsum("kq,lqx->lkx", Gb, rb, optimize=True) + exxb = numpy.tensordot(Grb, Grb, axes=((0, 1, 2), (1, 0, 2))) + + exx = exxa + exxb + e2b = 0.5 * (ecoul - exx) + + # pr.disable() + # pr.print_stats(sort='tottime') + + return (e1b + e2b + system.ecore, e1b + system.ecore, e2b) + + +def local_energy_generic_cholesky_opt(system, ham, Ga, Gb, Ghalfa, Ghalfb, rchola, rcholb): + r"""Calculate local for generic two-body hamiltonian. + + This uses the cholesky decomposed two-electron integrals. + + Parameters + ---------- + system : :class:`Generic` + System information for Generic. + ham : :class:`Abinitio` + Contains necessary hamiltonian information + G : :class:`numpy.ndarray` + Walker's "green's function" + Ghalf : :class:`numpy.ndarray` + Walker's half-rotated "green's function" shape is nocc x nbasis + rchol : :class:`numpy.ndarray` + trial's half-rotated choleksy vectors + + Returns + ------- + (E, T, V): tuple + Local, kinetic and potential energies. + """ + # Element wise multiplication. + if is_cupy( + rchola + ): # if even one array is a cupy array we should assume the rest is done with cupy + import cupy + + assert cupy.is_available() + array = cupy.array + zeros = cupy.zeros + sum = cupy.sum + dot = cupy.dot + trace = cupy.trace + einsum = cupy.einsum + isrealobj = cupy.isrealobj + else: + array = numpy.array + zeros = numpy.zeros + einsum = numpy.einsum + trace = numpy.trace + sum = numpy.sum + dot = numpy.dot + isrealobj = numpy.isrealobj + + complex128 = numpy.complex128 + + e1b = sum(ham.H1[0] * Ga) + sum(ham.H1[1] * Gb) + nalpha, nbeta = system.nup, system.ndown + nbasis = ham.nbasis + if rchola is not None: + naux = rchola.shape[0] + + if isrealobj(rchola) and isrealobj(rcholb): + Xa = rchola.dot(Ghalfa.real.ravel()) + 1.0j * rchola.dot(Ghalfa.imag.ravel()) + Xb = rcholb.dot(Ghalfb.real.ravel()) + 1.0j * rcholb.dot(Ghalfb.imag.ravel()) + else: + Xa = rchola.dot(Ghalfa.ravel()) + Xb = rcholb.dot(Ghalfb.ravel()) + + ecoul = dot(Xa, Xa) + ecoul += dot(Xb, Xb) + ecoul += 2 * dot(Xa, Xb) + + GhalfaT = Ghalfa.T.copy() # nbasis x nocc + GhalfbT = Ghalfb.T.copy() + + Ta = zeros((nalpha, nalpha), dtype=complex128) + Tb = zeros((nbeta, nbeta), dtype=complex128) + + exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta + if isrealobj(rchola) and isrealobj(rcholb): + for x in range(naux): # write a cython function that calls blas for this. + rmi_a = rchola[x].reshape((nalpha, nbasis)) + rmi_b = rcholb[x].reshape((nbeta, nbasis)) + Ta[:, :].real = rmi_a.dot(GhalfaT.real) + Ta[:, :].imag = rmi_a.dot(GhalfaT.imag) # this is a (nalpha, nalpha) + Tb[:, :].real = rmi_b.dot(GhalfbT.real) + Tb[:, :].imag = rmi_b.dot(GhalfbT.imag) # this is (nbeta, nbeta) + exx += trace(Ta.dot(Ta)) + trace(Tb.dot(Tb)) + else: + for x in range(naux): # write a cython function that calls blas for this. + rmi_a = rchola[x].reshape((nalpha, nbasis)) + rmi_b = rcholb[x].reshape((nbeta, nbasis)) + Ta[:, :] = rmi_a.dot(GhalfaT) # this is a (nalpha, nalpha) + Tb[:, :] = rmi_b.dot(GhalfbT) # this is (nbeta, nbeta) + exx += trace(Ta.dot(Ta)) + trace(Tb.dot(Tb)) + + e2b = 0.5 * (ecoul - exx) + + return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) diff --git a/ipie/thermal/estimators/handler.py b/ipie/thermal/estimators/handler.py new file mode 100644 index 00000000..ca46df0c --- /dev/null +++ b/ipie/thermal/estimators/handler.py @@ -0,0 +1,135 @@ +"""Routines and classes for estimation of observables.""" + +from __future__ import print_function + +import os +import h5py +import numpy + +from ipie.thermal.estimators.mixed import Mixed + + +class Estimators(object): + """Container for qmc estimates of observables. + + Parameters + ---------- + estimates : dict + input options detailing which estimators to calculate. By default only + mixed estimates will be calculated. + root : bool + True if on root/master processor. + qmc : :class:`ipie.state.QMCOpts` object. + Container for qmc input options. + system : :class:`ipie.hubbard.Hubbard` / system object in general. + Container for model input options. + trial : :class:`ipie.trial_wavefunction.X' object + Trial wavefunction class. + BT2 : :class:`numpy.ndarray` + One body propagator. + verbose : bool + If true we print out additional setup information. + + Attributes + ---------- + h5f : :class:`h5py.File` + Output file object. + estimates : dict + Dictionary of estimator objects. + back_propagation : bool + True if doing back propagation, specified in estimates dict. + nbp : int + Number of back propagation steps. + nprop_tot : int + Total number of auxiliary field configurations we store / use for back + propagation and itcf calculation. + calc_itcf : bool + True if calculating imaginary time correlation functions (ITCFs). + """ + + def __init__(self, estimates, root, qmc, system, hamiltonian, trial, BT2, verbose=False): + if verbose: + print("# Setting up estimator object.") + if root: + self.index = estimates.get("index", 0) + self.filename = estimates.get("filename", None) + self.basename = estimates.get("basename", "estimates") + if self.filename is None: + overwrite = estimates.get("overwrite", True) + self.filename = self.basename + f".{self.index}.h5" + while os.path.isfile(self.filename) and not overwrite: + self.index = int(self.filename.split(".")[1]) + self.index = self.index + 1 + self.filename = self.basename + f".{self.index}.h5" + with h5py.File(self.filename, "w") as fh5: + pass + if verbose: + print(f"# Writing estimator data to {self.filename}.") + else: + self.filename = None + # Sub-members: + # 1. Back-propagation + mixed = estimates.get("mixed", {}) + self.estimators = {} + dtype = complex + self.estimators["mixed"] = Mixed( + mixed, system, hamiltonian, root, self.filename, qmc, trial, dtype + ) + self.nprop_tot = None + self.nbp = None + # 2. Imaginary time correlation functions. + if verbose: + print("# Finished settting up estimator object.") + + def reset(self, root): + if root: + self.increment_file_number() + self.dump_metadata() + for k, e in self.estimators.items(): + e.setup_output(self.filename) + + def dump_metadata(self): + with h5py.File(self.filename, "a") as fh5: + fh5["metadata"] = self.json_string + + def increment_file_number(self): + self.index = self.index + 1 + self.filename = self.basename + f".{self.index}.h5" + + def print_step(self, comm, nprocs, step, nsteps=None, free_projection=False): + """Print QMC estimates. + + Parameters + ---------- + comm : + MPI communicator. + nprocs : int + Number of processors. + step : int + Current iteration number. + nmeasure : int + Number of steps between measurements. + """ + for k, e in self.estimators.items(): + e.print_step(comm, nprocs, step, nsteps=nsteps, free_projection=free_projection) + + def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=False): + """Update estimators + + Parameters + ---------- + system : system object in general. + Container for model input options. + qmc : :class:`ipie.state.QMCOpts` object. + Container for qmc input options. + trial : :class:`ipie.trial_wavefunction.X' object + Trial wavefunction class. + psi : :class:`ipie.legacy.walkers.Walkers` object + CPMC wavefunction. + step : int + Current simulation step + free_projection : bool + True if doing free projection. + """ + for k, e in self.estimators.items(): + e.update(qmc, system, hamiltonian, trial, psi, step, free_projection) diff --git a/ipie/thermal/estimators/hubbard.py b/ipie/thermal/estimators/hubbard.py new file mode 100644 index 00000000..8223067e --- /dev/null +++ b/ipie/thermal/estimators/hubbard.py @@ -0,0 +1,159 @@ +import numpy + +def local_energy_hubbard_holstein(ham, G, X, Lap, Ghalf=None): + r"""Calculate local energy of walker for the Hubbard-Hostein model. + + Parameters + ---------- + ham : :class:`HubbardHolstein` + ham information for the HubbardHolstein model. + G : :class:`numpy.ndarray` + Walker's "Green's function" + X : :class:`numpy.ndarray` + Walker's phonon coordinate + + Returns + ------- + (E_L(phi), T, V): tuple + Local, kinetic and potential energies of given walker phi. + """ + ke = numpy.sum(ham.T[0] * G[0] + ham.T[1] * G[1]) + + if ham.symmetric: + pe = -0.5 * ham.U * (G[0].trace() + G[1].trace()) + + pe = ham.U * numpy.dot(G[0].diagonal(), G[1].diagonal()) + + pe_ph = 0.5 * ham.w0**2 * ham.m * numpy.sum(X * X) + + ke_ph = -0.5 * numpy.sum(Lap) / ham.m - 0.5 * ham.w0 * ham.nbasis + + rho = G[0].diagonal() + G[1].diagonal() + e_eph = -ham.g * numpy.sqrt(ham.m * ham.w0 * 2.0) * numpy.dot(rho, X) + + etot = ke + pe + pe_ph + ke_ph + e_eph + + Eph = ke_ph + pe_ph + Eel = ke + pe + Eeb = e_eph + + return (etot, ke + pe, ke_ph + pe_ph + e_eph) + + +def local_energy_hubbard(ham, G, Ghalf=None): + r"""Calculate local energy of walker for the Hubbard model. + + Parameters + ---------- + ham : :class:`Hubbard` + ham information for the Hubbard model. + G : :class:`numpy.ndarray` + Walker's "Green's function" + + Returns + ------- + (E_L(phi), T, V): tuple + Local, kinetic and potential energies of given walker phi. + """ + ke = numpy.sum(ham.T[0] * G[0] + ham.T[1] * G[1]) + # Todo: Stupid + if ham.symmetric: + pe = -0.5 * ham.U * (G[0].trace() + G[1].trace()) + pe = ham.U * numpy.dot(G[0].diagonal(), G[1].diagonal()) + + return (ke + pe, ke, pe) + + +def local_energy_hubbard_ghf(ham, Gi, weights, denom): + """Calculate local energy of GHF walker for the Hubbard model. + + Parameters + ---------- + ham : :class:`Hubbard` + ham information for the Hubbard model. + Gi : :class:`numpy.ndarray` + Array of Walker's "Green's function" + denom : float + Overlap of trial wavefunction with walker. + + Returns + ------- + (E_L(phi), T, V): tuple + Local, kinetic and potential energies of given walker phi. + """ + ke = numpy.einsum("i,ikl,kl->", weights, Gi, ham.Text) / denom + # numpy.diagonal returns a view so there should be no overhead in creating + # temporary arrays. + guu = numpy.diagonal(Gi[:, : ham.nbasis, : ham.nbasis], axis1=1, axis2=2) + gdd = numpy.diagonal(Gi[:, ham.nbasis :, ham.nbasis :], axis1=1, axis2=2) + gud = numpy.diagonal(Gi[:, ham.nbasis :, : ham.nbasis], axis1=1, axis2=2) + gdu = numpy.diagonal(Gi[:, : ham.nbasis, ham.nbasis :], axis1=1, axis2=2) + gdiag = guu * gdd - gud * gdu + pe = ham.U * numpy.einsum("j,jk->", weights, gdiag) / denom + return (ke + pe, ke, pe) + + +def local_energy_hubbard_ghf_full(ham, GAB, weights): + r"""Calculate local energy of GHF walker for the Hubbard model. + + Parameters + ---------- + ham : :class:`Hubbard` + ham information for the Hubbard model. + GAB : :class:`numpy.ndarray` + Matrix of Green's functions for different SDs A and B. + weights : :class:`numpy.ndarray` + Components of overlap of trial wavefunction with walker. + + Returns + ------- + (E_L, T, V): tuple + Local, kinetic and potential energies of given walker phi. + """ + denom = numpy.sum(weights) + ke = numpy.einsum("ij,ijkl,kl->", weights, GAB, ham.Text) / denom + # numpy.diagonal returns a view so there should be no overhead in creating + # temporary arrays. + guu = numpy.diagonal(GAB[:, :, : ham.nbasis, : ham.nbasis], axis1=2, axis2=3) + gdd = numpy.diagonal(GAB[:, :, ham.nbasis :, ham.nbasis :], axis1=2, axis2=3) + gud = numpy.diagonal(GAB[:, :, ham.nbasis :, : ham.nbasis], axis1=2, axis2=3) + gdu = numpy.diagonal(GAB[:, :, : ham.nbasis, ham.nbasis :], axis1=2, axis2=3) + gdiag = guu * gdd - gud * gdu + pe = ham.U * numpy.einsum("ij,ijk->", weights, gdiag) / denom + return (ke + pe, ke, pe) + + +def local_energy_multi_det(ham, Gi, weights): + """Calculate local energy of GHF walker for the Hubbard model. + + Parameters + ---------- + ham : :class:`Hubbard` + ham information for the Hubbard model. + Gi : :class:`numpy.ndarray` + Array of Walker's "Green's function" + weights : :class:`numpy.ndarray` + Components of overlap of trial wavefunction with walker. + + Returns + ------- + (E_L(phi), T, V): tuple + Local, kinetic and potential energies of given walker phi. + """ + denom = numpy.sum(weights) + ke = numpy.einsum("i,ikl,kl->", weights, Gi, ham.Text) / denom + # numpy.diagonal returns a view so there should be no overhead in creating + # temporary arrays. + guu = numpy.diagonal(Gi[:, :, : ham.nup], axis1=1, axis2=2) + gdd = numpy.diagonal(Gi[:, :, ham.nup :], axis1=1, axis2=2) + pe = ham.U * numpy.einsum("j,jk->", weights, guu * gdd) / denom + return (ke + pe, ke, pe) + + +def fock_hubbard(ham, P): + """Hubbard Fock Matrix + F_{ij} = T_{ij} + U(nid + niu)_{ij} + """ + niu = numpy.diag(P[0].diagonal()) + nid = numpy.diag(P[1].diagonal()) + return ham.T + ham.U * numpy.array([nid, niu]) diff --git a/ipie/thermal/estimators/local_energy.py b/ipie/thermal/estimators/local_energy.py new file mode 100644 index 00000000..c3b19fd4 --- /dev/null +++ b/ipie/thermal/estimators/local_energy.py @@ -0,0 +1,131 @@ +import numpy + +try: + from ipie.thermal.estimators.pw_fft import local_energy_pw_fft + from ipie.thermal.estimators.ueg import local_energy_ueg +except ImportError as e: + print(e) +from ipie.estimators.generic import local_energy_generic_opt +from ipie.thermal.estimators.generic import ( + local_energy_generic_cholesky, + local_energy_generic_cholesky_opt, + local_energy_generic_cholesky_opt_stochastic, + local_energy_generic_pno, +) +from ipie.thermal.estimators.hubbard import ( + local_energy_hubbard, + local_energy_hubbard_ghf, + local_energy_hubbard_holstein, +) +from ipie.thermal.estimators.thermal import one_rdm_from_G + + +def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): + assert len(G) == 2 + ghf = G[0].shape[-1] == 2 * hamiltonian.nbasis + # unfortunate interfacial problem for the HH model + if hamiltonian.name == "Hubbard": + if ghf: + return local_energy_hubbard_ghf(hamiltonian, G) + else: + return local_energy_hubbard(hamiltonian, G) + elif hamiltonian.name == "HubbardHolstein": + return local_energy_hubbard_holstein(hamiltonian, G, X, Lap, Ghalf) + elif hamiltonian.name == "PW_FFT": + return local_energy_pw_fft(system, G, Ghalf) + elif hamiltonian.name == "UEG": + return local_energy_ueg(system, hamiltonian, G) + else: + if Ghalf is not None: + if hamiltonian.stochastic_ri and hamiltonian.control_variate: + return local_energy_generic_cholesky_opt_stochastic( + system, + G, + nsamples=hamiltonian.nsamples, + Ghalf=Ghalf, + rchol=trial._rchol, + C0=trial.psi, + ecoul0=trial.ecoul0, + exxa0=trial.exxa0, + exxb0=trial.exxb0, + ) + elif hamiltonian.stochastic_ri and not hamiltonian.control_variate: + return local_energy_generic_cholesky_opt_stochastic( + system, + G, + nsamples=hamiltonian.nsamples, + Ghalf=Ghalf, + rchol=trial._rchol, + ) + elif hamiltonian.exact_eri and not hamiltonian.pno: + return local_energy_generic_opt(system, G, Ghalf=Ghalf, eri=trial._eri) + elif hamiltonian.pno: + assert hamiltonian.exact_eri and hamiltonian.control_variate + return local_energy_generic_pno( + system, + G, + Ghalf=Ghalf, + eri=trial._eri, + C0=trial.C0, + ecoul0=trial.ecoul0, + exxa0=trial.exxa0, + exxb0=trial.exxb0, + UVT=trial.UVT, + ) + else: + return local_energy_generic_cholesky_opt( + system, + hamiltonian, + Ga=G[0], + Gb=G[1], + Ghalfa=Ghalf[0], + Ghalfb=Ghalf[1], + rchola=trial._rchola, + rcholb=trial._rcholb, + ) + else: + return local_energy_generic_cholesky(system, hamiltonian, G) + + +# TODO: should pass hamiltonian here and make it work for all possible types +# this is a generic local_energy handler. So many possible combinations of local energy strategies... +def local_energy(system, hamiltonian, walker, trial): + if walker.name == "MultiDetWalker": + if hamiltonian.name == "HubbardHolstein": + return local_energy_multi_det_hh( + system, walker.Gi, walker.weights, walker.X, walker.Lapi + ) + else: + return local_energy_multi_det(system, hamiltonian, trial, walker.Gi, walker.weights) + elif walker.name == "ThermalWalker": + return local_energy_G(system, hamiltonian, trial, one_rdm_from_G(walker.G), None) + else: + if hamiltonian.name == "HubbardHolstein": + return local_energy_G( + system, hamiltonian, trial, walker.G, walker.Ghalf, walker.X, walker.Lap + ) + else: + return local_energy_G(system, hamiltonian, trial, walker.G, walker.Ghalf) + + +def local_energy_multi_det(system, hamiltonian, trial, Gi, weights): + weight = 0 + energies = 0 + denom = 0 + for idet, (w, G) in enumerate(zip(weights, Gi)): + energies += w * numpy.array(local_energy_G(system, hamiltonian, trial, G)) + denom += w + return tuple(energies / denom) + + +def local_energy_multi_det_hh(system, Gi, weights, X, Lapi): + weight = 0 + energies = 0 + denom = 0 + for w, G, Lap in zip(weights, Gi, Lapi): + # construct "local" green's functions for each component of A + energies += w * numpy.array(local_energy_hubbard_holstein(system, G, X, Lap, Ghalf=None)) + denom += w + return tuple(energies / denom) + + diff --git a/ipie/thermal/estimators/mixed.py b/ipie/thermal/estimators/mixed.py new file mode 100644 index 00000000..bd772330 --- /dev/null +++ b/ipie/thermal/estimators/mixed.py @@ -0,0 +1,485 @@ +import h5py +import numpy + +try: + from ipie.config import MPI + + mpi_sum = MPI.SUM +except ImportError: + mpi_sum = None +import time + +from ipie.estimators.greens_function import greens_function +from ipie.estimators.local_energy_batch import local_energy_batch +from ipie.estimators.utils import H5EstimatorHelper +from ipie.thermal.estimators.local_energy import local_energy +from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number +from ipie.utils.io import format_fixed_width_floats, format_fixed_width_strings +from ipie.utils.misc import dotdict, is_cupy + + +class Mixed(object): + """Class for computing mixed estimates. + + Parameters + ---------- + mixed : dict + Input options for mixed estimates. + root : bool + True if on root/master processor. + qmc : :class:`ipie.state.QMCOpts` object. + Container for qmc input options. + trial : :class:`ipie.trial_wavefunction.X' object + Trial wavefunction class. + dtype : complex or float + Output type. + + Attributes + ---------- + nmeasure : int + Max number of measurements. + nreg : int + Number of regular estimates (exluding iteration). + G : :class:`numpy.ndarray` + One-particle RDM. + estimates : :class:`numpy.ndarray` + Store for mixed estimates per processor. + global_estimates : :class:`numpy.ndarray` + Store for mixed estimates accross all processors. + names : :class:`ipie.estimators.EstimEnum` + Enum for locating estimates in estimates array. + header : int + Output header. + key : dict + Explanation of output. + output : :class:`ipie.estimators.H5EstimatorHelper` + Class for outputting data to HDF5 group. + output : :class:`ipie.estimators.H5EstimatorHelper` + Class for outputting rdm data to HDF5 group. + """ + + def __init__(self, mixed_opts, system, hamiltonian, root, filename, qmc, trial, dtype): + self.average_gf = mixed_opts.get("average_gf", False) + self.eval_energy = mixed_opts.get("evaluate_energy", True) + self.calc_one_rdm = mixed_opts.get("one_rdm", False) + self.calc_two_rdm = mixed_opts.get("two_rdm", None) + self.energy_eval_freq = mixed_opts.get("energy_eval_freq", None) + if self.energy_eval_freq is None: + self.energy_eval_freq = qmc.nsteps + self.verbose = mixed_opts.get("verbose", True) + # number of steps per block + self.nsteps = qmc.nsteps + self.header = [ + "Iteration", + "WeightFactor", + "Weight", + "ENumer", + "EDenom", + "ETotal", + "E1Body", + "E2Body", + "EHybrid", + "Overlap", + ] + if qmc.beta is not None: + self.thermal = True + self.header.append("Nav") + else: + self.thermal = False + self.header.append("Time") + self.nreg = len(self.header[1:]) + self.dtype = dtype + self.G = numpy.zeros((2, hamiltonian.nbasis, hamiltonian.nbasis), dtype) + if self.calc_one_rdm: + dms_size = self.G.size + else: + dms_size = 0 + self.eshift = numpy.array([0, 0]) + # Abuse of language for the moment. Only accumulates S(k) for UEG. + # This works only for finite temperature so temporarily disabled + # TODO: Add functionality to accumulate 2RDM? + if self.calc_two_rdm is not None: + if self.calc_two_rdm == "structure_factor": + two_rdm_shape = ( + 2, + 2, + len(hamiltonian.qvecs), + ) + self.two_rdm = numpy.zeros(two_rdm_shape, dtype=numpy.complex128) + dms_size += self.two_rdm.size + else: + self.two_rdm = None + + if qmc.gpu: + import cupy + + self.estimates = cupy.zeros(self.nreg + dms_size, dtype=dtype) + self.names = get_estimator_enum(self.thermal) + self.estimates[self.names.time] = time.time() + # self.global_estimates = cupy.zeros(self.nreg+dms_size, + # dtype=dtype) + else: + self.estimates = numpy.zeros(self.nreg + dms_size, dtype=dtype) + self.names = get_estimator_enum(self.thermal) + self.estimates[self.names.time] = time.time() + self.global_estimates = numpy.zeros(self.nreg + dms_size, dtype=dtype) + self.key = { + "Iteration": "Simulation iteration. iteration*dt = tau.", + "WeightFactor": "Rescaling Factor from population control.", + "Weight": "Total walker weight.", + "E_num": "Numerator for projected energy estimator.", + "E_denom": "Denominator for projected energy estimator.", + "ETotal": "Projected energy estimator.", + "E1Body": "Mixed one-body energy estimator.", + "E2Body": "Mixed two-body energy estimator.", + "EHybrid": "Hybrid energy.", + "Overlap": "Walker average overlap.", + "Nav": "Average number of electrons.", + "Time": "Time per processor to complete one iteration.", + } + if root: + self.setup_output(filename) + + def update_batch( + self, qmc, system, hamiltonian, trial, walker_batch, step, free_projection=False + ): + """Update mixed estimates for walkers. + + Parameters + ---------- + qmc : :class:`ipie.state.QMCOpts` object. + Container for qmc input options. + system : system object. + Container for model input options. + hamiltonian : hamiltonian object. + Container for hamiltonian input options. + trial : :class:`ipie.trial_wavefunction.X' object + Trial wavefunction class. + psi : :class:`ipie.legacy.walkers.Walkers` object + CPMC wavefunction. + step : int + Current simulation step + free_projection : bool + True if doing free projection. + """ + assert free_projection == False + assert self.thermal == False + if is_cupy( + walker_batch.weight + ): # if even one array is a cupy array we should assume the rest is done with cupy + import cupy + + assert cupy.is_available() + array = cupy.array + zeros = cupy.zeros + sum = cupy.sum + abs = cupy.abs + else: + array = numpy.array + zeros = numpy.zeros + sum = numpy.sum + abs = numpy.abs + + # When using importance sampling we only need to know the current + # walkers weight as well as the local energy, the walker's overlap + # with the trial wavefunction is not needed. + if step % self.energy_eval_freq == 0: + greens_function(walker_batch, trial) + if self.eval_energy: + energy = local_energy_batch(system, hamiltonian, walker_batch, trial) + else: + energy = zeros(walker_batch.nwalkers, 3, dtype=numpy.complex128) + self.estimates[self.names.enumer] += sum(walker_batch.weight * energy[:, 0].real) + self.estimates[self.names.e1b : self.names.e2b + 1] += array( + [ + sum(walker_batch.weight * energy[:, 1].real), + sum(walker_batch.weight * energy[:, 2].real), + ] + ) + self.estimates[self.names.edenom] += sum(walker_batch.weight) + + self.estimates[self.names.uweight] += sum(walker_batch.unscaled_weight) + self.estimates[self.names.weight] += sum(walker_batch.weight) + self.estimates[self.names.ovlp] += sum(walker_batch.weight * abs(walker_batch.ovlp)) + self.estimates[self.names.ehyb] += sum(walker_batch.weight * walker_batch.hybrid_energy) + + if self.calc_one_rdm: + start = self.names.time + 1 + end = self.names.time + 1 + w.G.size + self.estimates[start:end] += w.weight * w.G.flatten().real + if self.calc_two_rdm is not None: + start = end + end = end + self.two_rdm.size + self.estimates[start:end] += w.weight * self.two_rdm.flatten().real + + def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=False): + """Update mixed estimates for walkers. + + Parameters + ---------- + qmc : :class:`ipie.state.QMCOpts` object. + Container for qmc input options. + system : system object. + Container for model input options. + hamiltonian : hamiltonian object. + Container for hamiltonian input options. + trial : :class:`ipie.trial_wavefunction.X' object + Trial wavefunction class. + psi : :class:`ipie.legacy.walkers.Walkers` object + CPMC wavefunction. + step : int + Current simulation step + free_projection : bool + True if doing free projection. + """ + if free_projection: + for i, w in enumerate(psi.walkers): + # For T > 0 w.ot = 1 always. + wfac = w.weight * w.ot * w.phase # * numpy.exp(w.log_detR-w.log_detR_shift) + if step % self.energy_eval_freq == 0: + w.greens_function(trial) + if self.eval_energy: + if self.thermal: + E, T, V = local_energy(system, hamiltonian, w, trial) + else: + E, T, V = local_energy( + system, + hamiltonian, + w, + rchol=trial._rchol, + eri=trial._eri, + ) + else: + E, T, V = 0, 0, 0 + self.estimates[self.names.enumer] += wfac * E + self.estimates[self.names.e1b : self.names.e2b + 1] += wfac * numpy.array( + [T, V] + ) + self.estimates[self.names.edenom] += wfac + if self.thermal: + nav = particle_number(one_rdm_from_G(w.G)) + self.estimates[self.names.nav] += wfac * nav + self.estimates[self.names.uweight] += w.unscaled_weight + self.estimates[self.names.weight] += wfac + self.estimates[self.names.ehyb] += wfac * w.hybrid_energy + self.estimates[self.names.ovlp] += w.weight * abs(w.ot) + else: + # When using importance sampling we only need to know the current + # walkers weight as well as the local energy, the walker's overlap + # with the trial wavefunction is not needed. + for i, w in enumerate(psi.walkers): + if self.thermal: + if self.average_gf: + E_sum = 0 + T_sum = 0 + V_sum = 0 + nav = 0 + for ts in range(w.stack_length): + w.greens_function(trial, slice_ix=ts * w.stack_size) + E, T, V = local_energy(system, hamiltonian, w, trial) + E_sum += E + T_sum += T + V_sum += V + nav += particle_number(one_rdm_from_G(w.G)) + self.estimates[self.names.nav] += w.weight * nav / w.stack_length + self.estimates[self.names.enumer] += w.weight * E_sum.real / w.stack_length + self.estimates[self.names.e1b : self.names.e2b + 1] += ( + w.weight * numpy.array([T_sum, V_sum]).real / w.stack_length + ) + else: + w.greens_function(trial) + E, T, V = local_energy(system, hamiltonian, w, trial) + nav = particle_number(one_rdm_from_G(w.G)) + self.estimates[self.names.nav] += w.weight * nav + self.estimates[self.names.enumer] += w.weight * E.real + self.estimates[self.names.e1b : self.names.e2b + 1] += ( + w.weight * numpy.array([T, V]).real + ) + self.estimates[self.names.edenom] += w.weight + else: + if step % self.energy_eval_freq == 0: + w.greens_function(trial) + if self.eval_energy: + E, T, V = local_energy(system, hamiltonian, w, trial) + else: + E, T, V = 0, 0, 0 + + self.estimates[self.names.enumer] += w.weight * w.le_oratio * E.real + self.estimates[self.names.e1b : self.names.e2b + 1] += ( + w.weight * w.le_oratio * numpy.array([T, V]).real + ) + self.estimates[self.names.edenom] += w.weight * w.le_oratio + + self.estimates[self.names.uweight] += w.unscaled_weight + self.estimates[self.names.weight] += w.weight + self.estimates[self.names.ovlp] += w.weight * abs(w.ot) + self.estimates[self.names.ehyb] += w.weight * w.hybrid_energy + if self.calc_one_rdm: + start = self.names.time + 1 + end = self.names.time + 1 + w.G.size + self.estimates[start:end] += w.weight * w.G.flatten().real + if self.calc_two_rdm is not None: + start = end + end = end + self.two_rdm.size + self.estimates[start:end] += w.weight * self.two_rdm.flatten().real + + def print_step(self, comm, nprocs, step, nsteps=None, free_projection=False): + """Print mixed estimates to file. + + This reduces estimates arrays over processors. On return estimates + arrays are zerod. + + Parameters + ---------- + comm : + MPI communicator. + nprocs : int + Number of processors. + step : int + Current iteration number. + nmeasure : int + Number of steps between measurements. + """ + if is_cupy( + self.estimates + ): # if even one array is a cupy array we should assume the rest is done with cupy + import cupy + + assert cupy.is_available() + array = cupy.asnumpy + else: + array = numpy.array + + if step % self.nsteps != 0: + return + if nsteps is None: + nsteps = self.nsteps + es = array(self.estimates) + ns = self.names + es[ns.time] = (time.time() - es[ns.time]) / nprocs + es[ns.uweight : ns.weight + 1] /= nsteps + es[ns.ehyb : ns.time + 1] /= nsteps + comm.Reduce(es, self.global_estimates, op=mpi_sum) + gs = self.global_estimates + if comm.rank == 0: + gs[ns.eproj] = gs[ns.enumer] + gs[ns.eproj : ns.e2b + 1] = gs[ns.eproj : ns.e2b + 1] / gs[ns.edenom] + gs[ns.ehyb] /= gs[ns.weight] + gs[ns.ovlp] /= gs[ns.weight] + eshift = numpy.array([gs[ns.ehyb], gs[ns.eproj]]) + else: + eshift = numpy.array([0, 0]) + if self.thermal and comm.rank == 0: + gs[ns.nav] = gs[ns.nav] / gs[ns.weight] + eshift = comm.bcast(eshift, root=0) + self.eshift = eshift + if comm.rank == 0: + if self.verbose: + print(format_fixed_width_floats([step] + list(gs[: ns.time + 1].real))) + self.output.push([step] + list(gs[: ns.time + 1]), "energies") + if self.calc_one_rdm: + start = self.nreg + end = self.nreg + self.G.size + rdm = gs[start:end].reshape(self.G.shape) / nsteps + self.output.push(rdm / gs[ns.weight], "one_rdm") + if self.calc_two_rdm: + start = self.nreg + self.G.size + rdm = gs[start:].reshape(self.two_rdm.shape) / nsteps + self.output.push(rdm / gs[ns.weight], "two_rdm") + self.output.increment() + self.zero() + + def print_key(self, eol="", encode=False): + """Print out information about what the estimates are. + + Parameters + ---------- + eol : string, optional + String to append to output, e.g., Default : ''. + encode : bool + In True encode output to be utf-8. + """ + header = ( + eol + + "# Explanation of output column headers:\n" + + "# -------------------------------------" + + eol + ) + if encode: + header = header.encode("utf-8") + print(header) + for k, v in self.key.items(): + s = f"# {k} : {v}" + eol + if encode: + s = s.encode("utf-8") + print(s) + + def print_header(self, eol="", encode=False): + r"""Print out header for estimators + + Parameters + ---------- + eol : string, optional + String to append to output, Default : ''. + encode : bool + In True encode output to be utf-8. + + Returns + ------- + None + """ + s = format_fixed_width_strings(self.header) + eol + if encode: + s = s.encode("utf-8") + print(s) + + def get_shift(self, hybrid=True): + """get hybrid shift. + + parameters + ---------- + hybrid : bool + true if using hybrid propgation + returns + ------- + eshift : float + walker averaged hybrid energy. + """ + if hybrid: + return self.eshift[0].real + else: + return self.eshift[1].real + + def zero(self): + """Zero (in the appropriate sense) various estimator arrays.""" + self.estimates[:] = 0 + self.global_estimates[:] = 0 + self.estimates[self.names.time] = time.time() + + def setup_output(self, filename): + with h5py.File(filename, "a") as fh5: + fh5["basic/headers"] = numpy.array(self.header).astype("S") + self.output = H5EstimatorHelper(filename, "basic") + + +def get_estimator_enum(thermal=False): + keys = [ + "uweight", + "weight", + "enumer", + "edenom", + "eproj", + "e1b", + "e2b", + "ehyb", + "ovlp", + ] + if thermal: + keys.append("nav") + keys.append("time") + enum = {} + for v, k in enumerate(keys): + enum[k] = v + return dotdict(enum) + + diff --git a/ipie/thermal/estimators/pw_fft.py b/ipie/thermal/estimators/pw_fft.py new file mode 100644 index 00000000..d61a5749 --- /dev/null +++ b/ipie/thermal/estimators/pw_fft.py @@ -0,0 +1,345 @@ +try: + from ipie.thermal.estimators.ueg_kernels import exchange_greens_function_per_qvec +except ImportError: + pass + +try: + from ipie.thermal.estimators.ueg_kernels import exchange_greens_function_fft +except ImportError: + pass + +import itertools + +import numpy + +from ipie.thermal.estimators.utils import convolve + + +def local_energy_pw_fft(system, G, Ghalf, trial, two_rdm=None): + """Local energy computation for uniform electron gas + Parameters + ---------- + system : + system class + G : + Green's function + Returns + ------- + etot : float + total energy + ke : float + kinetic energy + pe : float + potential energy + """ + assert Ghalf[0].shape[0] + Ghalf[1].shape[0] == trial.shape[1] + + nocca = Ghalf[0].shape[0] + noccb = Ghalf[1].shape[0] + # CTdagger = numpy.array([numpy.array(system.trial[:,0:system.nup],dtype=numpy.complex128).T.conj(), + # numpy.array(system.trial[:,system.nup:],dtype=numpy.complex128).T.conj()]) + + CTdagger = numpy.array( + [ + numpy.array(trial[:, 0:nocca], dtype=numpy.complex128).T.conj(), + numpy.array(trial[:, nocca:], dtype=numpy.complex128).T.conj(), + ] + ) + + # ke = numpy.einsum('sij,sji->', system.H1, G) # Wrong convention (correct Joonho convention) + # ke = numpy.einsum('sij,sij->', system.H1, G) # Correct ipie convention + if system.diagH1: + ke = numpy.einsum("sii,sii->", system.H1, G) + else: + ke = numpy.einsum("sij,sij->", system.H1, G) + + nq = numpy.shape(system.qvecs)[0] + + nocc = [nocca, noccb] + + nqgrid = numpy.prod(system.qmesh) + ngrid = numpy.prod(system.mesh) + + Gkpq = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) + Gpmq = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) + + for s in [0, 1]: + for i in range(nocc[s]): + ################################### + Gh_i = Ghalf[s][i, ::-1] + CTdagger_i = CTdagger[s][i, :] + + Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + + Gh_i_cube[system.gmap] = Gh_i + CTdagger_i_cube[system.gmap] = CTdagger_i + + # \sum_G CT(G-Q) theta(G) + lQ_i_cube = convolve(CTdagger_i_cube, Gh_i_cube, system.mesh)[::-1] + Gpmq[s] += lQ_i_cube[system.qmap] + + # ################################################################ + + Gh_i = Ghalf[s][i, :] + CTdagger_i = CTdagger[s][i, :][::-1] + + Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + + Gh_i_cube[system.gmap] = Gh_i + CTdagger_i_cube[system.gmap] = CTdagger_i + + # \sum_G CT(G+Q) theta(G) + lQ_i_cube = convolve(Gh_i_cube, CTdagger_i_cube, system.mesh)[::-1] + Gkpq[s] += lQ_i_cube[system.qmap] + + Gprod = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) + for s in [0, 1]: + Gprod[s] = exchange_greens_function_fft( + nocc[s], + system.nbasis, + numpy.array(system.mesh), + numpy.array(system.qmesh), + numpy.array(system.gmap), + numpy.array(system.qmap), + CTdagger[s], + Ghalf[s], + ) + + if two_rdm is None: + two_rdm = numpy.zeros((2, 2, len(system.qvecs)), dtype=numpy.complex128) + two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] + essa = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[0, 0]) + + two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] + essb = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[1, 1]) + + two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) + two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) + eos = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[0, 1]) + ( + 1.0 / (2.0 * system.vol) + ) * system.vqvec.dot(two_rdm[1, 0]) + pe = essa + essb + eos + + return (ke + pe, ke, pe) + + +def local_energy_pw_fft_no_cython(system, G, Ghalf, two_rdm=None): + """Local energy computation for uniform electron gas + Parameters + ---------- + system : + system class + G : + Green's function + Returns + ------- + etot : float + total energy + ke : float + kinetic energy + pe : float + potential energy + """ + + CTdagger = numpy.array( + [ + numpy.array(system.trial[:, 0 : system.nup], dtype=numpy.complex128).T.conj(), + numpy.array(system.trial[:, system.nup :], dtype=numpy.complex128).T.conj(), + ] + ) + + # ke = numpy.einsum('sij,sji->', system.H1, G) # Wrong convention (correct Joonho convention) + ke = numpy.einsum("sij,sij->", system.H1, G) # Correct ipie convention + + ne = [system.nup, system.ndown] + nq = numpy.shape(system.qvecs)[0] + + nocc = [system.nup, system.ndown] + nqgrid = numpy.prod(system.qmesh) + ngrid = numpy.prod(system.mesh) + + Gkpq = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) + Gpmq = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) + + for s in [0, 1]: + for i in range(nocc[s]): + ################################### + Gh_i = numpy.flip(Ghalf[s][i, :]) + CTdagger_i = CTdagger[s][i, :] + + Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + + Gh_i_cube[system.gmap] = Gh_i + CTdagger_i_cube[system.gmap] = CTdagger_i + + # \sum_G CT(G-Q) theta(G) + lQ_i_cube = numpy.flip(convolve(CTdagger_i_cube, Gh_i_cube, system.mesh)) + Gpmq[s] += lQ_i_cube[system.qmap] + + # ################################################################ + + Gh_i = Ghalf[s][i, :] + CTdagger_i = numpy.flip(CTdagger[s][i, :]) + + Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + + Gh_i_cube[system.gmap] = Gh_i + CTdagger_i_cube[system.gmap] = CTdagger_i + + # \sum_G CT(G+Q) theta(G) + lQ_i_cube = numpy.flip(convolve(Gh_i_cube, CTdagger_i_cube, system.mesh)) + Gkpq[s] += lQ_i_cube[system.qmap] + + Gprod = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) + + for s in [0, 1]: + for i, j in itertools.product(range(nocc[s]), range(nocc[s])): + ################################### + Gh_i = numpy.flip(Ghalf[s][i, :]) + CTdagger_j = CTdagger[s][j, :] + + Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + CTdagger_j_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + + Gh_i_cube[system.gmap] = Gh_i + CTdagger_j_cube[system.gmap] = CTdagger_j + + # \sum_G CT(G-Q) theta(G) + lQ_ji_cube = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, system.mesh)) + lQ_ji_fft = lQ_ji_cube[system.qmap] + + # ################################################################ + + Gh_j = Ghalf[s][j, :] + CTdagger_i = numpy.flip(CTdagger[s][i, :]) + + Gh_j_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) + + Gh_j_cube[system.gmap] = Gh_j + CTdagger_i_cube[system.gmap] = CTdagger_i + + # \sum_G CT(G+Q) theta(G) + lQ_ij_cube = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, system.mesh)) + lQ_ij_fft = lQ_ij_cube[system.qmap] + + Gprod[s] += lQ_ji_fft * lQ_ij_fft + + if two_rdm is None: + two_rdm = numpy.zeros((2, 2, len(system.qvecs)), dtype=numpy.complex128) + two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] + essa = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[0, 0]) + + two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] + essb = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[1, 1]) + + two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) + two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) + eos = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[0, 1]) + ( + 1.0 / (2.0 * system.vol) + ) * system.vqvec.dot(two_rdm[1, 0]) + pe = essa + essb + eos + + return (ke + pe, ke, pe) + + +def unit_test(): + import cProfile + + import numpy as np + + from ipie.legacy.estimators.greens_function import gab_mod + from ipie.legacy.estimators.ueg import local_energy_ueg + from ipie.legacy.systems.ueg import UEG + from ipie.systems.pw_fft import PW_FFT + from ipie.utils.testing import get_random_wavefunction + + # ecuts = [128.0] + # ecuts = [128.0] + ecuts = [2.0] + # ecuts = [2.0, 4.0, 8.0, 16.0, 32.0, 64.0] + + for ecut in ecuts: + inputs = { + "nup": 27, + "ndown": 27, + "rs": 1.0, + "ecut": ecut, + "skip_cholesky": True, + } + + system = PW_FFT(inputs, False) + print(f"ecut = {ecut}, nbsf = {system.nbasis}") + np.random.seed(7) + + rpsi = numpy.random.rand(system.nbasis, system.nup + system.ndown) + zpsi = numpy.random.rand(system.nbasis, system.nup + system.ndown) + system.trial = rpsi + 1.0j * zpsi + + Ca = np.array(system.trial[:, 0 : system.nup], dtype=np.complex128) + Cb = np.array(system.trial[:, system.nup :], dtype=np.complex128) + + (G_a, Ghalf_a) = gab_mod(Ca, Ca) + (G_b, Ghalf_b) = gab_mod(Cb, Cb) + + G = np.array([G_a, G_b]) + Ghalf = np.array([Ghalf_a, Ghalf_b]) + + pr = cProfile.Profile() + pr.enable() + + etot, ekin, epot = local_energy_pw_fft(system, G=G, Ghalf=Ghalf, trial=system.trial) + pr.disable() + pr.print_stats(sort="tottime") + print(f"ERHF = {etot}, {ekin}, {epot}") + # ERHF = (55.724777391549715-1.5180081474352112e-14j), (68.06317599174015-2.2316276597217335e-14j), (-12.33839860019044+7.136195122865225e-15j) + + # start = time.time() + # etot, ekin, epot = local_energy_pw_fft_no_cython(system, G=G, Ghalf=Ghalf) + # print("ERHF = {}, {}, {}".format(etot, ekin, epot)) + # end = time.time() + # print("FFT w/o Cython local energy (s): {}".format(end - start)) + + # # pr = cProfile.Profile() + # # pr.enable() + # system2 = UEG(inputs, False) + # print ("ecut = {}, nbsf = {}".format(ecut, system2.nbasis)) + # # pr.disable() + # # pr.print_stats(sort='tottime') + # nbsf = system2.nbasis + # Pa = np.zeros([nbsf,nbsf],dtype = np.complex128) + # Pb = np.zeros([nbsf,nbsf],dtype = np.complex128) + # na = system2.nup + # nb = system2.ndown + # for i in range(na): + # Pa[i,i] = 1.0 + # for i in range(nb): + # Pb[i,i] = 1.0 + # P = np.array([Pa, Pb]) + + # start = time.time() + # pr = cProfile.Profile() + # pr.enable() + # etot, ekin, epot = local_energy_ueg(system2, G=P) + # pr.disable() + # pr.print_stats(sort='tottime') + # print("ERHF = {}, {}, {}".format(etot, ekin, epot)) + # end = time.time() + # print("Usual local energy (s): {}".format(end - start)) + + # print(Greorder[0]) + # print(G[0]) + + # print(numpy.diag(system.H1[0])[sort_basis]) + # print(system2.H1) + + +# ERHF = (13.603557335564197+0j), (15.692780148560848+0j), (-2.0892228129966512+0j) #(7e,7e) + + +if __name__ == "__main__": + unit_test() diff --git a/ipie/thermal/estimators/ueg.py b/ipie/thermal/estimators/ueg.py new file mode 100644 index 00000000..9906fc9d --- /dev/null +++ b/ipie/thermal/estimators/ueg.py @@ -0,0 +1,290 @@ + +import numpy + +from ipie.thermal.estimators.ueg_kernels import ( + build_J_opt, + build_K_opt, + coulomb_greens_function_per_qvec, + exchange_greens_function_per_qvec, +) + + +def exchange_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gprod, G): + for iq in range(nq): + for idxkpq, i in zip(kpq[iq], kpq_i[iq]): + for idxpmq, j in zip(pmq[iq], pmq_i[iq]): + Gprod[iq] += G[j, idxkpq] * G[i, idxpmq] + + +def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): + for iq in range(nq): + for idxkpq, i in zip(kpq[iq], kpq_i[iq]): + Gkpq[iq] += G[i, idxkpq] + for idxpmq, i in zip(pmq[iq], pmq_i[iq]): + Gpmq[iq] += G[i, idxpmq] + + +def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): + """Local energy computation for uniform electron gas + Parameters + ---------- + system : + system class + ham : + hamiltonian class + G : + Green's function + Returns + ------- + etot : float + total energy + ke : float + kinetic energy + pe : float + potential energy + """ + if ham.diagH1: + ke = numpy.einsum("sii,sii->", ham.H1, G) + else: + ke = numpy.einsum("sij,sij->", ham.H1, G) + + Gkpq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + Gpmq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + Gprod = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + + ne = [system.nup, system.ndown] + nq = numpy.shape(ham.qvecs)[0] + + for s in [0, 1]: + # exchange_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i,ham.ipmq_pmq, Gprod[s],G[s]) + # coulomb_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i, ham.ipmq_pmq,Gkpq[s], Gpmq[s],G[s]) + for iq in range(nq): + Gkpq[s, iq], Gpmq[s, iq] = coulomb_greens_function_per_qvec( + ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] + ) + Gprod[s, iq] = exchange_greens_function_per_qvec( + ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] + ) + + if two_rdm is None: + two_rdm = numpy.zeros((2, 2, len(ham.qvecs)), dtype=numpy.complex128) + two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] + essa = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 0]) + + two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] + essb = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[1, 1]) + + two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) + two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) + eos = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 1]) + ( + 1.0 / (2.0 * ham.vol) + ) * ham.vqvec.dot(two_rdm[1, 0]) + + pe = essa + essb + eos + + return (ke + pe, ke, pe) + + +# JHLFML +def build_J(system, Gpmq, Gkpq): + J = [ + numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), + numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), + ] + + for iq, q in enumerate(system.qvecs): + for idxi, i in enumerate(system.basis): + for idxj, j in enumerate(system.basis): + jpq = j + q + idxjpq = system.lookup_basis(jpq) + if (idxjpq is not None) and (idxjpq == idxi): + J[0][idxj, idxi] += ( + (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + ) + + for iq, q in enumerate(system.qvecs): + for idxi, i in enumerate(system.basis): + for idxj, j in enumerate(system.basis): + jpq = j - q + idxjmq = system.lookup_basis(jpq) + if (idxjmq is not None) and (idxjmq == idxi): + J[0][idxj, idxi] += ( + (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + ) + + J[1] = J[0] + + return J + + +def build_K(system, G): + K = numpy.zeros((2, system.nbasis, system.nbasis), dtype=numpy.complex128) + for s in [0, 1]: + for iq in range(len(system.vqvec)): + for idxjmq, idxj in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): + for idxkpq, idxk in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): + K[s, idxj, idxkpq] += ( + -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjmq, idxk] + ) + for iq in range(len(system.vqvec)): + for idxjpq, idxj in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): + for idxpmq, idxp in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): + K[s, idxj, idxpmq] += ( + -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjpq, idxp] + ) + return K + + +def fock_ueg(ham, G): + """Fock matrix computation for uniform electron gas + + Parameters + ---------- + ham : :class`ipie.legacy.hamiltonians.ueg` + UEG hamiltonian class. + G : :class:`numpy.ndarray` + Green's function. + Returns + ------- + F : :class:`numpy.ndarray` + Fock matrix (2, nbasis, nbasis). + """ + nbsf = ham.nbasis + nq = len(ham.qvecs) + assert nq == len(ham.vqvec) + + Fock = numpy.zeros((2, nbsf, nbsf), dtype=numpy.complex128) + Gkpq = numpy.zeros((2, nq), dtype=numpy.complex128) + Gpmq = numpy.zeros((2, nq), dtype=numpy.complex128) + + for s in [0, 1]: + coulomb_greens_function( + nq, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + Gkpq[s], + Gpmq[s], + G[s], + ) + + J = build_J_opt( + nq, + ham.vqvec, + ham.vol, + ham.nbasis, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + Gkpq, + Gpmq, + ) + + K = build_K_opt( + nq, + ham.vqvec, + ham.vol, + ham.nbasis, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + G, + ) + + for s in [0, 1]: + Fock[s] = ham.H1[s] + J[s] + K[s] + + return Fock + + +def unit_test(): + import numpy as np + + from ipie.legacy.systems.ueg import UEG + + inputs = {"nup": 7, "ndown": 7, "rs": 1.0, "ecut": 2.0} + system = UEG(inputs, True) + nbsf = system.nbasis + Pa = np.zeros([nbsf, nbsf], dtype=np.complex128) + Pb = np.zeros([nbsf, nbsf], dtype=np.complex128) + na = system.nup + nb = system.ndown + for i in range(na): + Pa[i, i] = 1.0 + for i in range(nb): + Pb[i, i] = 1.0 + P = np.array([Pa, Pb]) + etot, ekin, epot = local_energy_ueg(system, G=P) + print(f"ERHF = {etot}, {ekin}, {epot}") + + from ipie.legacy.estimators.greens_function import gab + from ipie.utils.linalg import exponentiate_matrix, reortho + + # numpy.random.seed() + rCa = numpy.random.randn(nbsf, na) + zCa = numpy.random.randn(nbsf, na) + rCb = numpy.random.randn(nbsf, nb) + zCb = numpy.random.randn(nbsf, nb) + + Ca = rCa + 1j * zCa + Cb = rCb + 1j * zCb + + Ca, detR = reortho(Ca) + Cb, detR = reortho(Cb) + # S = print(Ca.dot(Cb.T)) + # print(S) + # exit() + Ca = numpy.array(Ca, dtype=numpy.complex128) + Cb = numpy.array(Cb, dtype=numpy.complex128) + P = [gab(Ca, Ca), gab(Cb, Cb)] + # diff = P[0] - P[1] + # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) + + # solver = lib.diis.DIIS() + + # dt = 0.1 + # for i in range(100): + # # Compute Fock matrix + # Fock = fock_ueg(system, G=P) + # # Compute DIIS Errvec + # PFmFPa = P[0].dot(Fock[0]) - Fock[0].dot(P[0]) + # PFmFPb = P[1].dot(Fock[1]) - Fock[1].dot(P[1]) + # errvec = numpy.append(numpy.reshape(PFmFPa, nbsf*nbsf),numpy.reshape(PFmFPb, nbsf*nbsf)) + # RMS = np.sqrt(np.dot(errvec, errvec)) + # print ("{} {} {}".format(i,numpy.real(local_energy_ueg(system, P)), numpy.real(RMS))) + # # Form Fockvec + # Fock[0] = numpy.array(Fock[0]) + # Fock[1] = numpy.array(Fock[1]) + # Fockvec = numpy.append(numpy.reshape(Fock[0],nbsf*nbsf), numpy.reshape(Fock[1],nbsf*nbsf)) + # # Extrapolate Fockvec + # # Fockvec = solver.update(Fockvec, xerr=errvec) + + # # Apply Propagator + # Fock = numpy.reshape(Fockvec, (2, nbsf, nbsf)) + # ea, Ca = numpy.linalg.eig(Fock[0]) + # eb, Cb = numpy.linalg.eig(Fock[1]) + # sort_perm = ea.argsort() + # ea.sort() + # Ca = Ca[:, sort_perm] + # sort_perm = eb.argsort() + # eb.sort() + # Cb = Cb[:, sort_perm] + + # Ca = Ca[:,:na] + # Cb = Cb[:,:nb] + # Ca, detR = reortho(Ca) + # Cb, detR = reortho(Cb) + + # P = [gab(Ca, Ca), gab(Cb, Cb)] + # # expF = [exponentiate_matrix(-dt*Fock[0]), exponentiate_matrix(-dt*Fock[1])] + # # Ca = expF[0].dot(Ca) + # # Cb = expF[1].dot(Cb) + # # diff = P[0] - P[1] + # # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) + + +if __name__ == "__main__": + unit_test() diff --git a/ipie/thermal/estimators/ueg_kernels.pyx b/ipie/thermal/estimators/ueg_kernels.pyx new file mode 100644 index 00000000..9c7a25de --- /dev/null +++ b/ipie/thermal/estimators/ueg_kernels.pyx @@ -0,0 +1,169 @@ +import numpy + +cimport numpy + +import itertools +import math + +from ipie.thermal.estimators.utils import convolve + +DTYPE_CX = numpy.complex128 +DTYPE = numpy.float64 + + +def vq(numpy.ndarray q): + assert(q.shape[0] == 3) + cdef double q2 = numpy.dot(q, q) + if (q2 < 1e-10): + return 0.0 + else: + return 4*math.pi / q2 + +def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): + """ Add a diagonal term of two-body Hamiltonian to the one-body term + Parameters + ---------- + T : float + one-body Hamiltonian (i.e. kinetic energy) + Returns + ------- + h1e_mod: float + modified one-body Hamiltonian + """ + + cdef size_t nbsf = basis.shape[0] + cdef numpy.ndarray h1e_mod = T.copy() + cdef double fac = 1.0 / (2.0 * vol) + + for (i, ki) in enumerate(basis): + for (j, kj) in enumerate(basis): + if i != j: + q = kfac * (ki - kj) + h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) + return h1e_mod + +def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): + + cdef int nq = kpq_i.shape[0] + + cdef int idxkpq, idxpmq, i, j, iq + + cdef double complex Gkpq = 0.0 + cdef double complex Gpmq = 0.0 + + for (idxkpq,i) in zip(kpq,kpq_i): + Gkpq += G[i,idxkpq] + for (idxpmq,i) in zip(pmq,pmq_i): + Gpmq += G[i,idxpmq] + + return Gkpq, Gpmq + +def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): + + cdef int nkpq = kpq_i.shape[0] + cdef int npmq = pmq_i.shape[0] + + cdef double complex Gprod = 0.0 + + cdef int idxkpq, idxpmq, i, j + + for inkpq in range(nkpq): + idxkpq = kpq[inkpq] + i = kpq_i[inkpq] + for jnpmq in range(npmq): + idxpmq = pmq[jnpmq] + j = pmq_i[jnpmq] + Gprod += G[j,idxkpq]*G[i,idxpmq] + + return Gprod + +def exchange_greens_function_fft (long nocc, long nbsf, + long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, + double complex[:,:] CTdagger, double complex[:,:] Ghalf): + + assert (mesh.shape[0] == 3) + assert (qmesh.shape[0] == 3) + assert (Ghalf.shape[0] == nocc) + assert (Ghalf.shape[1] == nbsf) + assert (CTdagger.shape[0] == nocc) + assert (CTdagger.shape[1] == nbsf) + + cdef long ngrid = numpy.prod(mesh) + cdef long nqgrid = numpy.prod(qmesh) + + cdef long nq = qmap.shape[0] + cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) + + cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) + cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) + + for i in range(nocc): + for j in range(nocc): + Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) + CTdagger_j = numpy.asarray(CTdagger[j,:]) + + Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + Gh_i_cube[gmap] = Gh_i + CTdagger_j_cube[gmap] = CTdagger_j + + lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] + + Gh_j = numpy.asarray(Ghalf[j,:]) + CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) + + Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + Gh_j_cube[gmap] = Gh_j + CTdagger_i_cube[gmap] = CTdagger_i + + lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] + + Gprod += lQ_ji*lQ_ij + + return Gprod + +def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, + list kpq, list pmq_i, list pmq, + double complex[:,:] Gkpq, double complex[:,:] Gpmq): + + cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) + cdef int i, j + for iq in range(nq): + for i, j in zip(pmq_i[iq], pmq[iq]): + J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + for i, j in zip(kpq_i[iq], kpq[iq]): + J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + + J[1] = J[0] + + return J + +def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, + list kpq, list pmq_i, list pmq, + double complex[:,:,:] G): + + cdef numpy.ndarray K = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) + cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp + + for s in range(2): + for iq in range(nq): + for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): + for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): + K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] + return K diff --git a/ipie/thermal/estimators/utils.py b/ipie/thermal/estimators/utils.py new file mode 100644 index 00000000..8665fe0b --- /dev/null +++ b/ipie/thermal/estimators/utils.py @@ -0,0 +1,318 @@ + +try: + import pyfftw +except ImportError: + pass +import numpy +import scipy + +try: + from scipy.fft._helper import _init_nd_shape_and_axes, next_fast_len +except ModuleNotFoundError: + pass + + +# Stolen from scipy +def scipy_fftconvolve(in1, in2, mesh1=None, mesh2=None, mode="full", axes=None): + """Convolve two N-dimensional arrays using FFT. + Convolve `in1` and `in2` using the fast Fourier transform method, with + the output size determined by the `mode` argument. + This is generally much faster than `convolve` for large arrays (n > ~500), + but can be slower when only a few output values are needed, and can only + output float arrays (int or object array inputs will be cast to float). + As of v0.19, `convolve` automatically chooses this method or the direct + method based on an estimation of which is faster. + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + axis : tuple, optional + axes : int or array_like of ints or None, optional + Axes over which to compute the convolution. + The default is over all axes. + Returns + ------- + out : array + An N-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + """ + + if not mesh1 == None: + in1 = in1.reshape(mesh1) + if not mesh2 == None: + in2 = in2.reshape(mesh2) + + in1 = numpy.asarray(in1) + in2 = numpy.asarray(in2) + noaxes = axes is None + + if in1.ndim == in2.ndim == 0: # scalar inputs + return in1 * in2 + elif in1.ndim != in2.ndim: + raise ValueError("in1 and in2 should have the same dimensionality") + elif in1.size == 0 or in2.size == 0: # empty arrays + return numpy.array([]) + + _, axes = _init_nd_shape_and_axes_sorted(in1, shape=None, axes=axes) + + if not noaxes and not axes.size: + raise ValueError("when provided, axes cannot be empty") + + if noaxes: + other_axes = numpy.array([], dtype=numpy.intc) + else: + other_axes = numpy.setdiff1d(numpy.arange(in1.ndim), axes) + + s1 = numpy.array(in1.shape) + s2 = numpy.array(in2.shape) + + if not numpy.all( + (s1[other_axes] == s2[other_axes]) | (s1[other_axes] == 1) | (s2[other_axes] == 1) + ): + raise ValueError(f"incompatible shapes for in1 and in2: {in1.shape} and {in2.shape}") + + complex_result = numpy.issubdtype(in1.dtype, numpy.complexfloating) or numpy.issubdtype( + in2.dtype, numpy.complexfloating + ) + shape = numpy.maximum(s1, s2) + shape[axes] = s1[axes] + s2[axes] - 1 + + # Check that input sizes are compatible with 'valid' mode + if scipy.signal.signaltools._inputs_swap_needed(mode, s1, s2): + # Convolution is commutative; order doesn't have any effect on output + in1, s1, in2, s2 = in2, s2, in1, s1 + + # Speed up FFT by padding to optimal size for FFTPACK + fshape = [next_fast_len(d) for d in shape[axes]] + fslice = tuple([slice(sz) for sz in shape]) + + # Pre-1.9 NumPy FFT routines are not threadsafe. For older NumPys, make + # sure we only call rfftn/irfftn from one thread at a time. + + # If we're here, it's either because we need a complex result, or we + # failed to acquire _rfft_lock (meaning rfftn isn't threadsafe and + # is already in use by another thread). In either case, use the + # (threadsafe but slower) SciPy complex-FFT routines instead. + sp1 = numpy.fft.fftn(in1, fshape, axes=axes) + sp2 = numpy.fft.fftn(in2, fshape, axes=axes) + ret = numpy.fft.ifftn(sp1 * sp2, axes=axes)[fslice].copy() + + if not complex_result: + ret = ret.real + + if mode == "full": + return ret + elif mode == "same": + return scipy.signal.signaltools._centered(ret, s1) + elif mode == "valid": + shape_valid = shape.copy() + shape_valid[axes] = s1[axes] - s2[axes] + 1 + return scipy.signal.signaltools._centered(ret, shape_valid) + else: + raise ValueError("acceptable mode flags are 'valid'," " 'same', or 'full'") + + +def convolve(f, g, mesh, backend=numpy.fft): + f_ = f.reshape(*mesh) + g_ = g.reshape(*mesh) + shape = numpy.maximum(f_.shape, g_.shape) + min_shape = numpy.array(f_.shape) + numpy.array(g_.shape) - 1 + + nqtot = numpy.prod(min_shape) + fshape = [next_fast_len(d) for d in min_shape] + + finv = backend.ifftn(f_, s=fshape) + ginv = backend.ifftn(g_, s=fshape) + fginv = finv * ginv + fq = backend.fftn(fginv).copy().ravel() + fq = fq.reshape(fshape) + fq = fq[: min_shape[0], : min_shape[1], : min_shape[2]] + fq = fq.reshape(nqtot) * numpy.prod(fshape) + return fq + + +# Stolen from scipy +def scipy_fftconvolve(in1, in2, mesh1=None, mesh2=None, mode="full", axes=None): + """Convolve two N-dimensional arrays using FFT. + Convolve `in1` and `in2` using the fast Fourier transform method, with + the output size determined by the `mode` argument. + This is generally much faster than `convolve` for large arrays (n > ~500), + but can be slower when only a few output values are needed, and can only + output float arrays (int or object array inputs will be cast to float). + As of v0.19, `convolve` automatically chooses this method or the direct + method based on an estimation of which is faster. + Parameters + ---------- + in1 : array_like + First input. + in2 : array_like + Second input. Should have the same number of dimensions as `in1`. + mode : str {'full', 'valid', 'same'}, optional + A string indicating the size of the output: + ``full`` + The output is the full discrete linear convolution + of the inputs. (Default) + ``valid`` + The output consists only of those elements that do not + rely on the zero-padding. In 'valid' mode, either `in1` or `in2` + must be at least as large as the other in every dimension. + ``same`` + The output is the same size as `in1`, centered + with respect to the 'full' output. + axis : tuple, optional + axes : int or array_like of ints or None, optional + Axes over which to compute the convolution. + The default is over all axes. + Returns + ------- + out : array + An N-dimensional array containing a subset of the discrete linear + convolution of `in1` with `in2`. + """ + + if not mesh1 == None: + in1 = in1.reshape(mesh1) + if not mesh2 == None: + in2 = in2.reshape(mesh2) + + in1 = numpy.asarray(in1) + in2 = numpy.asarray(in2) + noaxes = axes is None + + if in1.ndim == in2.ndim == 0: # scalar inputs + return in1 * in2 + elif in1.ndim != in2.ndim: + raise ValueError("in1 and in2 should have the same dimensionality") + elif in1.size == 0 or in2.size == 0: # empty arrays + return numpy.array([]) + + _, axes = _init_nd_shape_and_axes_sorted(in1, shape=None, axes=axes) + + if not noaxes and not axes.size: + raise ValueError("when provided, axes cannot be empty") + + if noaxes: + other_axes = numpy.array([], dtype=numpy.intc) + else: + other_axes = numpy.setdiff1d(numpy.arange(in1.ndim), axes) + + s1 = numpy.array(in1.shape) + s2 = numpy.array(in2.shape) + + if not numpy.all( + (s1[other_axes] == s2[other_axes]) | (s1[other_axes] == 1) | (s2[other_axes] == 1) + ): + raise ValueError(f"incompatible shapes for in1 and in2: {in1.shape} and {in2.shape}") + + complex_result = numpy.issubdtype(in1.dtype, numpy.complexfloating) or numpy.issubdtype( + in2.dtype, numpy.complexfloating + ) + shape = numpy.maximum(s1, s2) + shape[axes] = s1[axes] + s2[axes] - 1 + + # Check that input sizes are compatible with 'valid' mode + if scipy.signal.signaltools._inputs_swap_needed(mode, s1, s2): + # Convolution is commutative; order doesn't have any effect on output + in1, s1, in2, s2 = in2, s2, in1, s1 + + # Speed up FFT by padding to optimal size for FFTPACK + fshape = [next_fast_len(d) for d in shape[axes]] + fslice = tuple([slice(sz) for sz in shape]) + + # Pre-1.9 NumPy FFT routines are not threadsafe. For older NumPys, make + # sure we only call rfftn/irfftn from one thread at a time. + + # If we're here, it's either because we need a complex result, or we + # failed to acquire _rfft_lock (meaning rfftn isn't threadsafe and + # is already in use by another thread). In either case, use the + # (threadsafe but slower) SciPy complex-FFT routines instead. + sp1 = numpy.fft.fftn(in1, fshape, axes=axes) + sp2 = numpy.fft.fftn(in2, fshape, axes=axes) + ret = numpy.fft.ifftn(sp1 * sp2, axes=axes)[fslice].copy() + + if not complex_result: + ret = ret.real + + if mode == "full": + return ret + elif mode == "same": + return scipy.signal.signaltools._centered(ret, s1) + elif mode == "valid": + shape_valid = shape.copy() + shape_valid[axes] = s1[axes] - s2[axes] + 1 + return scipy.signal.signaltools._centered(ret, shape_valid) + else: + raise ValueError("acceptable mode flags are 'valid'," " 'same', or 'full'") + + +def convolve(f, g, mesh, backend=numpy.fft): + f_ = f.reshape(*mesh) + g_ = g.reshape(*mesh) + shape = numpy.maximum(f_.shape, g_.shape) + min_shape = numpy.array(f_.shape) + numpy.array(g_.shape) - 1 + + nqtot = numpy.prod(min_shape) + fshape = [next_fast_len(d) for d in min_shape] + + finv = backend.ifftn(f_, s=fshape) + ginv = backend.ifftn(g_, s=fshape) + fginv = finv * ginv + fq = backend.fftn(fginv).copy().ravel() + fq = fq.reshape(fshape) + fq = fq[: min_shape[0], : min_shape[1], : min_shape[2]] + fq = fq.reshape(nqtot) * numpy.prod(fshape) + return fq + + +def _init_nd_shape_and_axes_sorted(x, shape, axes): + """Handle and sort shape and axes arguments for n-dimensional transforms. + + This is identical to `_init_nd_shape_and_axes`, except the axes are + returned in sorted order and the shape is reordered to match. + + Parameters + ---------- + x : array_like + The input array. + shape : int or array_like of ints or None + The shape of the result. If both `shape` and `axes` (see below) are + None, `shape` is ``x.shape``; if `shape` is None but `axes` is + not None, then `shape` is ``scipy.take(x.shape, axes, axis=0)``. + If `shape` is -1, the size of the corresponding dimension of `x` is + used. + axes : int or array_like of ints or None + Axes along which the calculation is computed. + The default is over all axes. + Negative indices are automatically converted to their positive + counterpart. + + Returns + ------- + shape : array + The shape of the result. It is a 1D integer array. + axes : array + The shape of the result. It is a 1D integer array. + + """ + noaxes = axes is None + shape, axes = _init_nd_shape_and_axes(x, shape, axes) + + if not noaxes: + shape = shape[axes.argsort()] + axes.sort() + + return shape, axes diff --git a/ipie/thermal/hamiltonians/_generic.py b/ipie/thermal/hamiltonians/_generic.py new file mode 100644 index 00000000..e361deb5 --- /dev/null +++ b/ipie/thermal/hamiltonians/_generic.py @@ -0,0 +1,320 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + +import numpy + +array = numpy.array +zeros = numpy.zeros +einsum = numpy.einsum +isrealobj = numpy.isrealobj + + +from ipie.utils.io import ( + from_qmcpack_dense, + from_qmcpack_sparse, + write_hamiltonian, + read_hamiltonian, +) + + +class Generic(object): + """Ab-initio Hamiltonian. + + Can be created by either passing the one and two electron integrals directly + or initialised from integrals stored in QMCPACK hdf5 format. If initialising + from file the `inputs' optional dictionary should be populated. + + Parameters + ---------- + h1e : :class:`numpy.ndarray' + One-electron integrals. Optional. Default: None. + chol : :class:`numpy.ndarray' + Factorized 2-electron integrals (L_{ik,n}) of shape (nbasis^2, nchol). + Optional. Default: None. + ecore : float + Core energy. + options : dict + Input options defined below. + integrals : string + Path to file containing one- and two-electron integrals in QMCPACK + format. + verbose : bool + Print extra information. + + Attributes + ---------- + H1 : :class:`numpy.ndarray` + One-body part of the Hamiltonian. Spin-dependent by default. + ecore : float + Core contribution to the total energy. + h1e_mod : :class:`numpy.ndarray` + Modified one-body Hamiltonian. + chol_vecs : :class:`numpy.ndarray` + Cholesky vectors. [M^2, nchol] + nchol : int + Number of cholesky vectors. + nfields : int + Number of auxiliary fields required. + sparse_cutoff : float + Screen out integrals below this threshold. Optional. Default 0. + cplx_chol : bool + Force setting of interpretation of cholesky decomposition. Optional. + Default False, i.e. real/complex factorization determined from cholesky + integrals. + """ + + def __init__( + self, + h1e, + chol, + ecore, + h1e_mod=None, + chol_packed=None, + options={}, + verbose=False, + write_ints=False, + ): + if verbose: + print("# Parsing input options for hamiltonians.Generic.") + self.name = "Generic" + self.verbose = verbose + self.exact_eri = options.get("exact_eri", False) + self.mixed_precision = options.get("mixed_precision", False) + self.density_diff = options.get("density_diff", False) + self.symmetry = options.get("symmetry", True) + self.chunked = False # chunking disabled by default + + self.ecore = ecore + self.chol_vecs = chol # [M^2, nchol] + self.chol = self.chol_vecs + + if self.symmetry: + self.chol_packed = chol_packed + nbsf = h1e.shape[1] + self.sym_idx = numpy.triu_indices(nbsf) + self.sym_idx_i = self.sym_idx[0].copy() + self.sym_idx_j = self.sym_idx[1].copy() + else: + self.chol_packed = None # [M*(M+1)/2, nchol] if used + self.sym_idx = None + + # unncessary booleans for legacy compatibility + self.control_variate = False + self.stochastic_ri = False + self.pno = False + + if self.mixed_precision: + if not self.density_diff: + self.density_diff = True + if self.verbose: + print("# density_diff is switched on for more stable mixed precision") + if self.symmetry: + self.chol_packed = self.chol_packed.astype(numpy.float32) + else: + self.chol_vecs = self.chol_vecs.astype(numpy.float32) # [M^2, nchol] + + if self.exact_eri: + if self.verbose: + print("# exact_eri is used for the local energy evaluation") + + if self.density_diff: + if self.verbose: + print("# density_diff is used for the force bias and the local energy evaluation") + + if self.mixed_precision: + if self.verbose: + print("# mixed_precision is used for the propagation") + + if isrealobj(self.chol_vecs.dtype): + if verbose: + print("# Found real Choleksy integrals.") + self.cplx_chol = False + else: + if verbose: + print("# Found complex Cholesky integrals.") + self.cplx_chol = True + + self.H1 = array(h1e) + self.nbasis = h1e.shape[-1] + + mem = self.chol_vecs.nbytes / (1024.0**3) + self.sparse = False + if verbose: + print("# Number of orbitals: %d" % self.nbasis) + print(f"# Approximate memory required by Cholesky vectors {mem:f} GB") + self.nchol = self.chol_vecs.shape[-1] + if h1e_mod is not None: + self.h1e_mod = h1e_mod + else: + h1e_mod = zeros(self.H1.shape, dtype=self.H1.dtype) + construct_h1e_mod(self.chol_vecs, self.H1, h1e_mod) + self.h1e_mod = h1e_mod + + # For consistency + self.vol = 1.0 + self.nfields = self.nchol + + if verbose: + print("# Number of Cholesky vectors: %d" % (self.nchol)) + print("# Number of fields: %d" % (self.nfields)) + if write_ints: + self.write_integrals() + if verbose: + print("# Finished setting up hamiltonians.Generic object.") + + def hijkl(self, i, j, k, l): + ik = i * self.nbasis + k + jl = j * self.nbasis + l + return numpy.dot(self.chol_vecs[ik], self.chol_vecs[jl]) + + def write_integrals(self, nelec, filename="hamil.h5"): + write_hamiltonian( + self.H1[0], + self.chol_vecs.T.reshape((self.nchol, self.nbasis, self.nbasis)), + self.ecore, + filename=filename, + ) + + def chunk(self, handler, verbose=False): + self.chunked = True # Boolean to indicate that chunked cholesky is available + + chol_idxs = [i for i in range(self.nchol)] + self.chol_idxs_chunk = handler.scatter_group(chol_idxs) + + if self.symmetry: + # if handler.srank == 0: # creating copies for every rank = 0!!!! + self.chol_packed = self.chol_packed.T.copy() # [chol, M^2] + handler.comm.barrier() + + self.chol_packed_chunk = handler.scatter_group(self.chol_packed) # distribute over chol + + # if handler.srank == 0: + self.chol_packed = self.chol_packed.T.copy() # [M^2, chol] + handler.comm.barrier() + + self.chol_packed_chunk = self.chol_packed_chunk.T.copy() # [M^2, chol_chunk] + + tot_size = handler.allreduce_group(self.chol_packed_chunk.size) + + assert self.chol_packed.size == tot_size + else: + # if handler.comm.rank == 0: + self.chol_vecs = self.chol_vecs.T.copy() # [chol, M^2] + handler.comm.barrier() + + self.chol_vecs_chunk = handler.scatter_group(self.chol_vecs) # distribute over chol + + # if handler.comm.rank == 0: + self.chol_vecs = self.chol_vecs.T.copy() # [M^2, chol] + handler.comm.barrier() + + self.chol_vecs_chunk = self.chol_vecs_chunk.T.copy() # [M^2, chol_chunk] + + tot_size = handler.allreduce_group(self.chol_vecs_chunk.size) + assert self.chol_vecs.size == tot_size + + # This function casts relevant member variables into cupy arrays + # Keeping this specific for the moment as too much logic. + # A sign it should be split up.. + def cast_to_cupy(self, verbose=False): + import cupy + + size = self.H1.size + self.h1e_mod.size + if self.chunked: + if self.symmetry: + size += self.chol_packed_chunk.size + else: + size += self.chol_vecs_chunk.size + else: + if self.symmetry: + size += self.chol_packed.size + else: + size += self.chol_vecs.size + + if self.symmetry: + size += self.sym_idx_i.size + size += self.sym_idx_j.size + + if verbose: + expected_bytes = size * 8.0 # float64 + print( + "# hamiltonians.generic: expected to allocate {:4.3f} GB".format( + expected_bytes / 1024**3 + ) + ) + + self.H1 = cupy.asarray(self.H1) + self.h1e_mod = cupy.asarray(self.h1e_mod) + if self.symmetry: + self.sym_idx_i = cupy.asarray(self.sym_idx_i) + self.sym_idx_j = cupy.asarray(self.sym_idx_j) + + if self.chunked: + if self.symmetry: + self.chol_packed_chunk = cupy.asarray(self.chol_packed_chunk) + else: + self.chol_vecs_chunk = cupy.asarray(self.chol_vecs_chunk) + else: + if self.symmetry: + self.chol_packed = cupy.asarray(self.chol_packed) + else: + self.chol_vecs = cupy.asarray(self.chol_vecs) + + free_bytes, total_bytes = cupy.cuda.Device().mem_info + used_bytes = total_bytes - free_bytes + if verbose: + print( + "# hamiltonians.Generic: using {:4.3f} GB out of {:4.3f} GB memory on GPU".format( + used_bytes / 1024**3, total_bytes / 1024**3 + ) + ) + + +def read_integrals(integral_file): + try: + (h1e, schol_vecs, ecore, nbasis, nup, ndown) = from_qmcpack_sparse(integral_file) + chol_vecs = schol_vecs.toarray() + return h1e, chol_vecs, ecore + except KeyError: + pass + try: + (h1e, chol_vecs, ecore, nbasis, nup, ndown) = from_qmcpack_dense(integral_file) + return h1e, chol_vecs, ecore + except KeyError: + pass + try: + (h1e, chol_vecs, ecore) = read_hamiltonian(integral_file) + naux = chol_vecs.shape[0] + nbsf = chol_vecs.shape[-1] + return h1e, chol_vecs.T.reshape((nbsf, nbsf, naux)), ecore + except KeyError: + return None + + +def construct_h1e_mod(chol, h1e, h1e_mod): + # Subtract one-body bit following reordering of 2-body operators. + # Eqn (17) of [Motta17]_ + nbasis = h1e.shape[-1] + nchol = chol.shape[-1] + chol_view = chol.reshape((nbasis, nbasis * nchol)) + # assert chol_view.__array_interface__['data'][0] == chol.__array_interface__['data'][0] + v0 = 0.5 * numpy.dot( + chol_view, chol_view.T + ) # einsum('ikn,jkn->ij', chol_3, chol_3, optimize=True) + h1e_mod[0, :, :] = h1e[0] - v0 + h1e_mod[1, :, :] = h1e[1] - v0 diff --git a/ipie/thermal/hamiltonians/hubbard.py b/ipie/thermal/hamiltonians/hubbard.py new file mode 100644 index 00000000..a5cb638d --- /dev/null +++ b/ipie/thermal/hamiltonians/hubbard.py @@ -0,0 +1,400 @@ +"""Hubbard model specific classes and methods""" + +from math import cos, pi + +import numpy +import scipy.linalg + +from ipie.thermal.system.hubbard_holstein import kinetic +from ipie.utils.io import fcidump_header + + +class Hubbard(object): + """Hubbard model system class. + + 1 and 2 case with nearest neighbour hopping. + + Parameters + ---------- + options : dict + dictionary of system input options. + + Attributes + ---------- + t : float + Hopping parameter. + U : float + Hubbard U interaction strength. + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + nbasis : int + Number of single-particle basis functions. + T : numpy.array + Hopping matrix + gamma : numpy.array + Super matrix (not currently implemented). + """ + + def __init__(self, options, verbose=False): + if verbose: + print("# Parsing input options.") + # for backward compatibility + self.mixed_precision = False + self.chunked = False + self.t = options.get("t", 1.0) + self.U = options["U"] + self.nx = options["nx"] + self.ny = options["ny"] + self.ktwist = numpy.array(options.get("ktwist")) + self.control_variate = False + self.symmetric = options.get("symmetric", False) + self.sparse = False + if self.symmetric: + # An unusual convention for the sign of the chemical potential is + # used in Phys. Rev. B 99, 045108 (2018) + # Symmetric uses the symmetric form of the hubbard model and will + # also change the sign of the chemical potential in the density + # matrix. + self._alt_convention = True + else: + self._alt_convention = False + + self.ypbc = options.get("ypbc", True) + self.xpbc = options.get("xpbc", True) + + self.nbasis = self.nx * self.ny + self.nactive = self.nbasis + self.nfv = 0 + self.ncore = 0 + (self.kpoints, self.kc, self.eks) = kpoints(self.t, self.nx, self.ny) + self.pinning = options.get("pinning_fields", False) + self._opt = True + if verbose: + print("# Setting up one-body operator.") + if self.pinning: + if verbose: + print("# Using pinning field.") + self.T = kinetic_pinning_alt(self.t, self.nbasis, self.nx, self.ny) + else: + self.T = kinetic( + self.t, + self.nbasis, + self.nx, + self.ny, + self.ktwist, + xpbc=self.xpbc, + ypbc=self.ypbc, + ) + self.H1 = self.T + self.Text = scipy.linalg.block_diag(self.T[0], self.T[1]) + self.P = transform_matrix(self.nbasis, self.kpoints, self.kc, self.nx, self.ny) + self.mu = options.get("mu", None) + # For interface consistency. + self.ecore = 0.0 + # Number of field configurations per walker. + self.nfields = self.nbasis + self.name = "Hubbard" + if verbose: + print("# Finished setting up Hubbard system object.") + # "Volume" to define density. + self.vol = self.nx * self.ny + self.construct_h1e_mod() + self.control_variate = False + + def fcidump(self, nup, ndown, to_string=False): + """Dump 1- and 2-electron integrals to file. + + Parameters + ---------- + to_string : bool + Return fcidump as string. Default print to stdout. + """ + header = fcidump_header(nup + ndown, self.nbasis, nup - ndown) + for i in range(1, self.nbasis + 1): + if self.T.dtype == complex: + fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" + line = fmt.format(self.U.real, self.U.imag, i, i, i, i) + else: + fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" + line = fmt.format(self.U, i, i, i, i) + header += line + for i in range(0, self.nbasis): + for j in range(i + 1, self.nbasis): + integral = self.T[0][i, j] + if abs(integral) > 1e-8: + if self.T.dtype == complex: + fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" + line = fmt.format(integral.real, integral.imag, i + 1, j + 1, 0, 0) + else: + fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" + line = fmt.format(integral, i + 1, j + 1, 0, 0) + header += line + if self.T.dtype == complex: + fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" + header += fmt.format(0, 0, 0, 0, 0, 0) + else: + fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" + header += fmt.format(0, 0, 0, 0, 0) + if to_string: + print(header) + else: + return header + + def construct_h1e_mod(self): + # Subtract one-body bit following reordering of 2-body operators. + # Eqn (17) of [Motta17]_ + if not self.symmetric: + v0 = 0.5 * self.U * numpy.eye(self.nbasis) + self.h1e_mod = numpy.array([self.H1[0] - v0, self.H1[1] - v0]) + else: + self.h1e_mod = self.H1 + + def hijkl(self, i, j, k, l): + # (ik|jl) + if i == j == k == l: + return self.U + else: + return 0.0 + + +def transform_matrix(nbasis, kpoints, kc, nx, ny): + U = numpy.zeros(shape=(nbasis, nbasis), dtype=complex) + for i, k_i in enumerate(kpoints): + for j in range(0, nbasis): + r_j = decode_basis(nx, ny, j) + U[i, j] = numpy.exp(1j * numpy.dot(kc * k_i, r_j)) + + return U + + +def kinetic_pinning(t, nbasis, nx, ny): + r"""Kinetic part of the Hamiltonian in our one-electron basis. + + Adds pinning fields as outlined in [Qin16]_. This forces periodic boundary + conditions along x and open boundary conditions along y. Pinning fields are + applied in the y direction as: + + .. math:: + \nu_{i\uparrow} = -\nu_{i\downarrow} = (-1)^{i_x+i_y}\nu_0, + + for :math:`i_y=1,L_y` and :math:`\nu_0=t/4`. + + Parameters + ---------- + t : float + Hopping parameter + nbasis : int + Number of one-electron basis functions. + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + + Returns + ------- + T : numpy.array + Hopping Hamiltonian matrix. + """ + + Tup = numpy.zeros((nbasis, nbasis)) + Tdown = numpy.zeros((nbasis, nbasis)) + nu0 = 0.25 * t + + for i in range(0, nbasis): + # pinning field along y. + xy1 = decode_basis(nx, ny, i) + if xy1[1] == 0 or xy1[1] == ny - 1: + Tup[i, i] += (-1.0) ** (xy1[0] + xy1[1]) * nu0 + Tdown[i, i] += (-1.0) ** (xy1[0] + xy1[1] + 1) * nu0 + for j in range(i + 1, nbasis): + xy2 = decode_basis(nx, ny, j) + dij = abs(xy1 - xy2) + if sum(dij) == 1: + Tup[i, j] = Tdown[i, j] = -t + # periodic bcs in x. + if (dij == [nx - 1, 0]).all(): + Tup[i, j] += -t + Tdown[i, j] += -t + + return numpy.array([Tup + numpy.triu(Tup, 1).T, Tdown + numpy.triu(Tdown, 1).T]) + + +def kinetic_pinning_alt(t, nbasis, nx, ny): + r"""Kinetic part of the Hamiltonian in our one-electron basis. + + Adds pinning fields as outlined in [Qin16]_. This forces periodic boundary + conditions along x and open boundary conditions along y. Pinning fields are + applied in the y direction as: + + .. math:: + \nu_{i\uparrow} = -\nu_{i\downarrow} = (-1)^{i_x+i_y}\nu_0, + + for :math:`i_y=1,L_y` and :math:`\nu_0=t/4`. + + Parameters + ---------- + t : float + Hopping parameter + nbasis : int + Number of one-electron basis functions. + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + + Returns + ------- + T : numpy.array + Hopping Hamiltonian matrix. + """ + + Tup = numpy.zeros((nbasis, nbasis)) + Tdown = numpy.zeros((nbasis, nbasis)) + h = 0.1 * t + + for i in range(0, nbasis): + # pinning field along y direction when i_x = 0. + xy1 = decode_basis(nx, ny, i) + if xy1[0] == 0: + Tup[i, i] += (-1.0) ** (xy1[1]) * h + Tdown[i, i] += (-1.0) ** (xy1[1] + 1) * h + for j in range(i + 1, nbasis): + xy2 = decode_basis(nx, ny, j) + dij = abs(xy1 - xy2) + if sum(dij) == 1: + Tup[i, j] = Tdown[i, j] = -t + # periodic bcs in y. + if (dij == [0, ny - 1]).all(): + Tup[i, j] += -t + Tdown[i, j] += -t + + return numpy.array([Tup + numpy.triu(Tup, 1).T, Tdown + numpy.triu(Tdown, 1).T]) + + +def decode_basis(nx, ny, i): + """Return cartesian lattice coordinates from basis index. + + Consider a 3x3 lattice then we index lattice sites like:: + + (0,2) (1,2) (2,2) 6 7 8 + (0,1) (1,1) (2,1) -> 3 4 5 + (0,0) (1,0) (2,0) 0 1 2 + + i.e., i = i_x + n_x * i_y, and i_x = i%n_x, i_y = i//nx. + + Parameters + ---------- + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + i : int + Basis index (same for up and down spins). + """ + if ny == 1: + return numpy.array([i % nx]) + else: + return numpy.array([i % nx, i // nx]) + + +def encode_basis(i, j, nx): + """Encode 2d index to one dimensional index. + + See decode basis for layout. + + Parameters + ---------- + i : int + x coordinate. + j : int + y coordinate + nx : int + Number of x lattice sites. + + Returns + ------- + ix : int + basis index. + """ + return i + j * nx + + +def _super_matrix(U, nbasis): + """Construct super-matrix from v_{ijkl}""" + + +def kpoints(t, nx, ny): + """Construct kpoints for system. + + Parameters + ---------- + t : float + Hopping amplitude. + nx : int + Number of x lattice sites. + nx : int + Number of y lattice sites. + + Returns + ------- + kp : numpy array + System kpoints Note these are not sorted according to eigenvalue energy + but rather so as to conform with numpys default kpoint indexing for FFTs. + kfac : float + Kpoint scaling factor (2pi/L). + eigs : numpy array + Single particle eigenvalues associated with kp. + """ + kp = [] + eigs = [] + if ny == 1: + kfac = numpy.array([2.0 * pi / nx]) + for n in range(0, nx): + kp.append(numpy.array([n])) + eigs.append(ek(t, n, kfac, ny)) + else: + kfac = numpy.array([2.0 * pi / nx, 2.0 * pi / ny]) + for n in range(0, nx): + for m in range(0, ny): + k = numpy.array([n, m]) + kp.append(k) + eigs.append(ek(t, k, kfac, ny)) + + eigs = numpy.array(eigs) + kp = numpy.array(kp) + return (kp, kfac, eigs) + + +def ek(t, k, kc, ny): + """Calculate single-particle energies. + + Parameters + ---------- + t : float + Hopping amplitude. + k : numpy array + Kpoint. + kc : float + Scaling factor. + ny : int + Number of y lattice points. + """ + if ny == 1: + e = -2.0 * t * cos(kc * k) + else: + e = -2.0 * t * (cos(kc[0] * k[0]) + cos(kc[1] * k[1])) + + return e + + +def get_strip(cfunc, cfunc_err, ix, nx, ny, stag=False): + iy = [i for i in range(ny)] + idx = [encode_basis(ix, i, nx) for i in iy] + if stag: + c = [((-1) ** (ix + i)) * cfunc[ib] for (i, ib) in zip(iy, idx)] + else: + c = [cfunc[ib] for ib in idx] + cerr = [cfunc_err[ib] for ib in idx] + return c, cerr diff --git a/ipie/thermal/hamiltonians/ueg.py b/ipie/thermal/hamiltonians/ueg.py new file mode 100644 index 00000000..5ddbb6ba --- /dev/null +++ b/ipie/thermal/hamiltonians/ueg.py @@ -0,0 +1,481 @@ +import math + +import numpy +import scipy.linalg +import scipy.sparse + +from ipie.utils.io import write_qmcpack_sparse + + +class UEG(object): + """UEG system class (integrals read from fcidump) + Parameters + ---------- + nup : int + Number of up electrons. + ndown : int + Number of down electrons. + rs : float + Density parameter. + ecut : float + Scaled cutoff energy. + ktwist : :class:`numpy.ndarray` + Twist vector. + verbose : bool + Print extra information. + Attributes + ---------- + T : :class:`numpy.ndarray` + One-body part of the Hamiltonian. This is diagonal in plane wave basis. + ecore : float + Madelung contribution to the total energy. + h1e_mod : :class:`numpy.ndarray` + Modified one-body Hamiltonian. + nfields : int + Number of field configurations per walker for back propagation. + basis : :class:`numpy.ndarray` + Basis vectors within a cutoff. + kfac : float + Scale factor (2pi/L). + """ + + def __init__(self, system, options, verbose=False): + if verbose: + print("# Parsing input options.") + self.name = "UEG" + self.mu = options.get("mu", None) + if self.mu is not None: + print(f"# mu: {self.mu:6.4e}") + self._alt_convention = options.get("alt_convention", False) + self.sparse = True + + # core energy + self.ecore = 0.5 * system.ne * self.madelung(system) + self.diagH1 = True + + skip_cholesky = options.get("skip_cholesky", False) + + self.kfac = system.kfac + self.vol = system.vol + # Single particle eigenvalues and corresponding kvectors + (self.sp_eigv, self.basis, self.nmax) = self.sp_energies( + system.ktwist, system.kfac, system.ecut + ) + + self.shifted_nmax = 2 * self.nmax + self.imax_sq = numpy.dot(self.basis[-1], self.basis[-1]) + self.create_lookup_table() + for i, k in enumerate(self.basis): + assert i == self.lookup_basis(k) + + # Number of plane waves. + self.nbasis = len(self.sp_eigv) + self.nactive = self.nbasis + self.ncore = 0 + self.nfv = 0 + self.mo_coeff = None + # Allowed momentum transfers (4*ecut) + (eigs, qvecs, self.qnmax) = self.sp_energies(system.ktwist, system.kfac, 4 * system.ecut) + # Omit Q = 0 term. + self.qvecs = numpy.copy(qvecs[1:]) + self.vqvec = numpy.array([self.vq(system.kfac * q) for q in self.qvecs]) + # Number of momentum transfer vectors / auxiliary fields. + # Can reduce by symmetry but be stupid for the moment. + self.nchol = len(self.qvecs) + self.nfields = 2 * len(self.qvecs) + if verbose: + print(f"# Number of plane waves: {self.nbasis:d}") + print(f"# Number of Cholesky vectors: {self.nchol:d}.") + # For consistency with frozen core molecular code. + self.orbs = None + self.frozen_core = False + T = numpy.diag(self.sp_eigv) + self.H1 = numpy.array([T, T]) # Making alpha and beta + + if skip_cholesky == False: + h1e_mod = self.mod_one_body(T, system) + self.h1e_mod = numpy.array([h1e_mod, h1e_mod]) + self.orbs = None + self._opt = True + + nlimit = system.nup + + if system.thermal: + nlimit = self.nbasis + + self.ikpq_i = [] + self.ikpq_kpq = [] + for iq, q in enumerate(self.qvecs): + idxkpq_list_i = [] + idxkpq_list_kpq = [] + for i, k in enumerate(self.basis[0:nlimit]): + kpq = k + q + idxkpq = self.lookup_basis(kpq) + if idxkpq is not None: + idxkpq_list_i += [i] + idxkpq_list_kpq += [idxkpq] + self.ikpq_i += [idxkpq_list_i] + self.ikpq_kpq += [idxkpq_list_kpq] + + self.ipmq_i = [] + self.ipmq_pmq = [] + for iq, q in enumerate(self.qvecs): + idxpmq_list_i = [] + idxpmq_list_pmq = [] + for i, p in enumerate(self.basis[0:nlimit]): + pmq = p - q + idxpmq = self.lookup_basis(pmq) + if idxpmq is not None: + idxpmq_list_i += [i] + idxpmq_list_pmq += [idxpmq] + self.ipmq_i += [idxpmq_list_i] + self.ipmq_pmq += [idxpmq_list_pmq] + + for iq, q in enumerate(self.qvecs): + self.ikpq_i[iq] = numpy.array(self.ikpq_i[iq], dtype=numpy.int64) + self.ikpq_kpq[iq] = numpy.array(self.ikpq_kpq[iq], dtype=numpy.int64) + self.ipmq_i[iq] = numpy.array(self.ipmq_i[iq], dtype=numpy.int64) + self.ipmq_pmq[iq] = numpy.array(self.ipmq_pmq[iq], dtype=numpy.int64) + + if skip_cholesky == False: + if verbose: + print("# Constructing two-body potentials incore.") + (self.chol_vecs, self.iA, self.iB) = self.two_body_potentials_incore() + write_ints = options.get("write_integrals", False) + if write_ints: + self.write_integrals(system) + if verbose: + print( + "# Approximate memory required for " + "two-body potentials: {:13.8e} GB.".format((3 * self.iA.nnz * 16 / (1024**3))) + ) + print("# Finished constructing two-body potentials.") + print("# Finished setting up UEG system object.") + + def sp_energies(self, ks, kfac, ecut): + """Calculate the allowed kvectors and resulting single particle eigenvalues (basically kinetic energy) + which can fit in the sphere in kspace determined by ecut. + Parameters + ---------- + kfac : float + kspace grid spacing. + ecut : float + energy cutoff. + Returns + ------- + spval : :class:`numpy.ndarray` + Array containing sorted single particle eigenvalues. + kval : :class:`numpy.ndarray` + Array containing basis vectors, sorted according to their + corresponding single-particle energy. + """ + + # Scaled Units to match with HANDE. + # So ecut is measured in units of 1/kfac^2. + nmax = int(math.ceil(numpy.sqrt((2 * ecut)))) + + spval = [] + vec = [] + kval = [] + + for ni in range(-nmax, nmax + 1): + for nj in range(-nmax, nmax + 1): + for nk in range(-nmax, nmax + 1): + spe = 0.5 * (ni**2 + nj**2 + nk**2) + if spe <= ecut: + kijk = [ni, nj, nk] + kval.append(kijk) + # Reintroduce 2 \pi / L factor. + ek = 0.5 * numpy.dot(numpy.array(kijk) + ks, numpy.array(kijk) + ks) + spval.append(kfac**2 * ek) + + # Sort the arrays in terms of increasing energy. + spval = numpy.array(spval) + ix = numpy.argsort(spval, kind="mergesort") + spval = spval[ix] + kval = numpy.array(kval)[ix] + + return (spval, kval, nmax) + + def create_lookup_table(self): + basis_ix = [] + for k in self.basis: + basis_ix.append(self.map_basis_to_index(k)) + self.lookup = numpy.zeros(max(basis_ix) + 1, dtype=int) + for i, b in enumerate(basis_ix): + self.lookup[b] = i + self.max_ix = max(basis_ix) + + def lookup_basis(self, vec): + if numpy.dot(vec, vec) <= self.imax_sq: + ix = self.map_basis_to_index(vec) + if ix >= len(self.lookup): + ib = None + else: + ib = self.lookup[ix] + return ib + else: + ib = None + + def map_basis_to_index(self, k): + return ( + (k[0] + self.nmax) + + self.shifted_nmax * (k[1] + self.nmax) + + self.shifted_nmax * self.shifted_nmax * (k[2] + self.nmax) + ) + + def madelung(self, system): + """Use expression in Schoof et al. (PhysRevLett.115.130402) for the + Madelung contribution to the total energy fitted to L.M. Fraser et al. + Phys. Rev. B 53, 1814. + Parameters + ---------- + rs : float + Wigner-Seitz radius. + ne : int + Number of electrons. + Returns + ------- + v_M: float + Madelung potential (in Hartrees). + """ + c1 = -2.837297 + c2 = (3.0 / (4.0 * math.pi)) ** (1.0 / 3.0) + return c1 * c2 / (system.ne ** (1.0 / 3.0) * system.rs) + + def vq(self, q): + """The typical 3D Coulomb kernel + Parameters + ---------- + q : float + a plane-wave vector + Returns + ------- + v_M: float + 3D Coulomb kernel (in Hartrees) + """ + return 4 * math.pi / numpy.dot(q, q) + + def mod_one_body(self, T, system): + """Add a diagonal term of two-body Hamiltonian to the one-body term + Parameters + ---------- + T : float + one-body Hamiltonian (i.e. kinetic energy) + Returns + ------- + h1e_mod: float + modified one-body Hamiltonian + """ + h1e_mod = numpy.copy(T) + + fac = 1.0 / (2.0 * system.vol) + for i, ki in enumerate(self.basis): + for j, kj in enumerate(self.basis): + if i != j: + q = self.kfac * (ki - kj) + h1e_mod[i, i] = h1e_mod[i, i] - fac * self.vq(q) + return h1e_mod + + def density_operator(self, iq): + """Density operator as defined in Eq.(6) of PRB(75)245123 + Parameters + ---------- + q : float + a plane-wave vector + Returns + ------- + rho_q: float + density operator + """ + nnz = self.rho_ikpq_kpq[iq].shape[0] # Number of non-zeros + ones = numpy.ones((nnz), dtype=numpy.complex128) + rho_q = scipy.sparse.csc_matrix( + (ones, (self.rho_ikpq_kpq[iq], self.rho_ikpq_i[iq])), + shape=(self.nbasis, self.nbasis), + dtype=numpy.complex128, + ) + return rho_q + + def scaled_density_operator_incore(self, transpose): + """Density operator as defined in Eq.(6) of PRB(75)245123 + Parameters + ---------- + q : float + a plane-wave vector + Returns + ------- + rho_q: float + density operator + """ + rho_ikpq_i = [] + rho_ikpq_kpq = [] + for iq, q in enumerate(self.qvecs): + idxkpq_list_i = [] + idxkpq_list_kpq = [] + for i, k in enumerate(self.basis): + kpq = k + q + idxkpq = self.lookup_basis(kpq) + if idxkpq is not None: + idxkpq_list_i += [i] + idxkpq_list_kpq += [idxkpq] + rho_ikpq_i += [idxkpq_list_i] + rho_ikpq_kpq += [idxkpq_list_kpq] + + for iq, q in enumerate(self.qvecs): + rho_ikpq_i[iq] = numpy.array(rho_ikpq_i[iq], dtype=numpy.int64) + rho_ikpq_kpq[iq] = numpy.array(rho_ikpq_kpq[iq], dtype=numpy.int64) + + nq = len(self.qvecs) + nnz = 0 + for iq in range(nq): + nnz += rho_ikpq_kpq[iq].shape[0] + + col_index = [] + row_index = [] + + values = [] + + if transpose: + for iq in range(nq): + qscaled = self.kfac * self.qvecs[iq] + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = math.pi / (self.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + for innz, kpq in enumerate(rho_ikpq_kpq[iq]): + row_index += [rho_ikpq_kpq[iq][innz] + rho_ikpq_i[iq][innz] * self.nbasis] + col_index += [iq] + values += [factor] + else: + for iq in range(nq): + qscaled = self.kfac * self.qvecs[iq] + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = math.pi / (self.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + for innz, kpq in enumerate(rho_ikpq_kpq[iq]): + row_index += [rho_ikpq_kpq[iq][innz] * self.nbasis + rho_ikpq_i[iq][innz]] + col_index += [iq] + values += [factor] + + rho_q = scipy.sparse.csc_matrix( + (values, (row_index, col_index)), + shape=(self.nbasis * self.nbasis, nq), + dtype=numpy.complex128, + ) + + return rho_q + + def two_body_potentials_incore(self): + """Calculatate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q + Parameters + ---------- + system : + system class + q : float + a plane-wave vector + Returns + ------- + iA : numpy array + Eq.(13a) + iB : numpy array + Eq.(13b) + """ + # qscaled = self.kfac * self.qvecs + + # # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + + rho_q = self.scaled_density_operator_incore(False) + rho_qH = self.scaled_density_operator_incore(True) + + iA = 1j * (rho_q + rho_qH) + iB = -(rho_q - rho_qH) + + return (rho_q, iA, iB) + + def write_integrals(self, system, filename="hamil.h5"): + write_qmcpack_sparse( + self.H1[0], + 2 * self.chol_vecs.toarray(), + system.nelec, + self.nbasis, + enuc=0.0, + filename=filename, + ) + + def hijkl(self, i, j, k, l): + """Compute = (ik|jl) = 1/Omega * 4pi/(kk-ki)**2 + + Checks for momentum conservation k_i + k_j = k_k + k_k, or + k_k - k_i = k_j - k_l. + + Parameters + ---------- + i, j, k, l : int + Orbital indices for integral (ik|jl) = . + + Returns + ------- + integral : float + (ik|jl) + """ + q1 = self.basis[k] - self.basis[i] + q2 = self.basis[j] - self.basis[l] + if numpy.dot(q1, q1) > 1e-12 and numpy.dot(q1 - q2, q1 - q2) < 1e-12: + return 1.0 / self.vol * self.vq(self.kfac * q1) + else: + return 0.0 + + def compute_real_transformation(self): + U22 = numpy.zeros((2, 2), dtype=numpy.complex128) + U22[0, 0] = 1.0 / numpy.sqrt(2.0) + U22[0, 1] = 1.0 / numpy.sqrt(2.0) + U22[1, 0] = -1.0j / numpy.sqrt(2.0) + U22[1, 1] = 1.0j / numpy.sqrt(2.0) + + U = numpy.zeros((self.nbasis, self.nbasis), dtype=numpy.complex128) + + for i, b in enumerate(self.basis): + if numpy.sum(b * b) == 0: + U[i, i] = 1.0 + else: + mb = -b + diff = numpy.einsum("ij->i", (self.basis - mb) ** 2) + idx = numpy.argwhere(diff == 0) + assert idx.ravel().shape[0] == 1 + if i < idx: + idx = idx.ravel()[0] + U[i, i] = U22[0, 0] + U[i, idx] = U22[0, 1] + U[idx, i] = U22[1, 0] + U[idx, idx] = U22[1, 1] + else: + continue + + U = U.T.copy() + return U + + def eri_4(self): + eri_chol = 4 * self.chol_vecs.dot(self.chol_vecs.T) + eri_chol = ( + eri_chol.toarray().reshape((self.nbasis, self.nbasis, self.nbasis, self.nbasis)).real + ) + eri_chol = eri_chol.transpose(0, 1, 3, 2) + return eri_chol + + # Compute 8-fold symmetric integrals. Useful for running standard quantum chemistry methods + def eri_8(self): + eri = self.eri_4() + U = self.compute_real_transformation() + + eri0 = numpy.einsum("mp,mnls->pnls", U.conj(), eri, optimize=True) + eri1 = numpy.einsum("nq,pnls->pqls", U, eri0, optimize=True) + eri2 = numpy.einsum("lr,pqls->pqrs", U.conj(), eri1, optimize=True) + eri3 = numpy.einsum("st,pqrs->pqrt", U, eri2, optimize=True).real + + return eri3 + + +if __name__ == "__main__": + unit_test() diff --git a/ipie/thermal/hamiltonians/utils.py b/ipie/thermal/hamiltonians/utils.py new file mode 100644 index 00000000..34f03935 --- /dev/null +++ b/ipie/thermal/hamiltonians/utils.py @@ -0,0 +1,53 @@ +import sys +import time + +from ipie.hamiltonians.utils import get_generic_integrals +from ipie.thermal.hamiltonians._generic import Generic +from ipie.thermal.hamiltonians.hubbard import Hubbard +from ipie.thermal.hamiltonians.ueg import UEG + + +def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): + """Wrapper to select hamiltonian class + + Parameters + ---------- + ham_opts : dict + Hamiltonian input options. + verbose : bool + Output verbosity. + + Returns + ------- + ham : object + Hamiltonian class. + """ + if ham_opts["name"] == "Hubbard": + ham = Hubbard(ham_opts, verbose) + elif ham_opts["name"] == "UEG": + ham = UEG(system, ham_opts, verbose) + elif ham_opts["name"] == "Generic": + filename = ham_opts.get("integrals", None) + if filename is None: + if comm.rank == 0: + print("# Error: integrals not specfied.") + sys.exit() + start = time.time() + hcore, chol, h1e_mod, enuc = get_generic_integrals(filename, comm=comm, verbose=verbose) + if verbose: + print(f"# Time to read integrals: {time.time() - start:.6f}") + ham = Generic( + h1e=hcore, + chol=chol, + ecore=enuc, + h1e_mod=h1e_mod, + options=ham_opts, + verbose=verbose, + ) + else: + if comm.rank == 0: + print(f"# Error: unrecognized hamiltonian name {ham_opts['name']}.") + sys.exit() + ham = None + + return ham diff --git a/ipie/thermal/propagation/continuous.py b/ipie/thermal/propagation/continuous.py index a97c6dc4..74c3ad9b 100644 --- a/ipie/thermal/propagation/continuous.py +++ b/ipie/thermal/propagation/continuous.py @@ -1,17 +1,13 @@ import cmath import math -import sys -import time import numpy import scipy.sparse.linalg -from ipie.legacy.estimators.thermal import inverse_greens_function_qr, one_rdm_from_G -from ipie.legacy.propagation.operations import kinetic_real -from ipie.legacy.thermal_propagation.generic import GenericContinuous -from ipie.legacy.thermal_propagation.hubbard import HubbardContinuous -from ipie.legacy.thermal_propagation.planewave import PlaneWave -from ipie.utils.linalg import exponentiate_matrix +from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.thermal.propagation.generic import GenericContinuous +from ipie.thermal.propagation.hubbard import HubbardContinuous +from ipie.thermal.propagation.planewave import PlaneWave class Continuous(object): diff --git a/ipie/thermal/propagation/generic.py b/ipie/thermal/propagation/generic.py index 7454b5df..c88870a2 100644 --- a/ipie/thermal/propagation/generic.py +++ b/ipie/thermal/propagation/generic.py @@ -1,14 +1,9 @@ -import cmath -import math -import sys -import time import numpy import scipy.sparse.linalg -from ipie.legacy.estimators.thermal import inverse_greens_function_qr, one_rdm_from_G -from ipie.legacy.propagation.operations import kinetic_real -from ipie.utils.linalg import exponentiate_matrix +from ipie.legacy.estimators.thermal import one_rdm_from_G + class GenericContinuous(object): diff --git a/ipie/thermal/propagation/hubbard.py b/ipie/thermal/propagation/hubbard.py new file mode 100644 index 00000000..daea5e92 --- /dev/null +++ b/ipie/thermal/propagation/hubbard.py @@ -0,0 +1,271 @@ +import cmath + +import numpy +import scipy.linalg + +from ipie.thermal.estimators.thermal import one_rdm_from_G + + +class ThermalDiscrete(object): + def __init__(self, ham, trial, qmc, options={}, verbose=False, lowrank=False): + if verbose: + print("# Parsing discrete propagator input options.") + print("# Using continuous Hubbar--Stratonovich transformations.") + self.free_projection = options.get("free_projection", False) + self.nstblz = qmc.nstblz + self.hs_type = "discrete" + self.charge_decomp = options.get("charge_decomposition", False) + if verbose: + if self.charge_decomp: + print("# Using charge decomposition.") + else: + print("# Using spin decomposition.") + # [field,spin] + if self.charge_decomp: + self.gamma = numpy.arccosh(numpy.exp(-0.5 * qmc.dt * ham.U + 0j)) + self.auxf = numpy.array( + [ + [numpy.exp(self.gamma), numpy.exp(self.gamma)], + [numpy.exp(-self.gamma), numpy.exp(-self.gamma)], + ] + ) + # e^{-gamma x} + self.aux_wfac = numpy.exp(0.5 * qmc.dt * ham.U) * numpy.array( + [numpy.exp(-self.gamma), numpy.exp(self.gamma)] + ) + else: + self.gamma = numpy.arccosh(numpy.exp(0.5 * qmc.dt * ham.U)) + self.auxf = numpy.array( + [ + [numpy.exp(self.gamma), numpy.exp(-self.gamma)], + [numpy.exp(-self.gamma), numpy.exp(self.gamma)], + ] + ) + self.aux_wfac = numpy.array([1.0, 1.0]) + if not ham.symmetric: + self.auxf = self.auxf * numpy.exp(-0.5 * qmc.dt * ham.U) + # Account for potential shift in chemical potential + sign = 1 if ham._alt_convention else -1 + self.dmu = sign * (ham.mu - trial.mu) + self.auxf *= numpy.exp(-qmc.dt * (self.dmu)) + if abs(self.dmu) > 1e-16: + self._mu = trial.mu + if verbose: + print(f"# Chemical potential shift (mu_T-mu): {-sign * self.dmu}") + else: + self._mu = ham.mu + self.delta = self.auxf - 1 + dt = qmc.dt + dmat_up = scipy.linalg.expm(-dt * (ham.H1[0])) + dmat_down = scipy.linalg.expm(-dt * (ham.H1[1])) + dmat = numpy.array([dmat_up, dmat_down]) + self.construct_one_body_propagator(ham, self._mu, dt) + self.BT_BP = None + self.BT = trial.dmat + self.BT_inv = trial.dmat_inv + if self.charge_decomp: + dtype = numpy.complex128 + else: + dtype = trial.dmat.dtype + self.BV = numpy.zeros((2, trial.dmat.shape[-1]), dtype=dtype) + if self.free_projection: + self.propagate_walker = self.propagate_walker_free + else: + self.propagate_walker = self.propagate_walker_constrained + + def construct_one_body_propagator(self, ham, mu, dt): + """Construct the one-body propagator Exp(-dt/2 H0) + Parameters + ---------- + ham : + ham class + dt : float + time-step + Returns + ------- + self.BH1 : numpy array + Exp(-dt H0) + """ + H1 = ham.H1 + I = numpy.identity(H1[0].shape[0], dtype=H1.dtype) + # No spin dependence for the moment. + sign = 1 if ham._alt_convention else -1 + self.BH1 = numpy.array( + [ + scipy.linalg.expm(-dt * (H1[0] + sign * mu * I)), + scipy.linalg.expm(-dt * (H1[1] + sign * mu * I)), + ] + ) + + def update_greens_function_simple(self, walker, time_slice): + walker.construct_greens_function_stable(time_slice) + + def update_greens_function(self, walker, i, xi): + for spin in [0, 1]: + g = walker.G[spin, :, i] + gbar = -walker.G[spin, i, :] + gbar[i] += 1 + denom = 1 + (1 - g[i]) * self.delta[xi, spin] + walker.G[spin] = ( + walker.G[spin] - self.delta[xi, spin] * numpy.einsum("i,j->ij", g, gbar) / denom + ) + + def propagate_greens_function(self, walker): + if walker.stack.time_slice < walker.stack.ntime_slices: + walker.G[0] = self.BT[0].dot(walker.G[0]).dot(self.BT_inv[0]) + walker.G[1] = self.BT[1].dot(walker.G[1]).dot(self.BT_inv[1]) + + def calculate_overlap_ratio(self, walker, i): + R1_up = 1 + (1 - walker.G[0, i, i]) * self.delta[0, 0] + R1_dn = 1 + (1 - walker.G[1, i, i]) * self.delta[0, 1] + R2_up = 1 + (1 - walker.G[0, i, i]) * self.delta[1, 0] + R2_dn = 1 + (1 - walker.G[1, i, i]) * self.delta[1, 1] + return 0.5 * numpy.array([R1_up * R1_dn, R2_up * R2_dn]) + + def estimate_eshift(self, walker): + oratio = self.calculate_overlap_ratio(walker, 0) + return sum(oratio) + + def propagate_walker_constrained(self, system, walker, time_slice, eshift=0): + for i in range(0, system.nbasis): + probs = self.calculate_overlap_ratio(walker, i) + phaseless_ratio = numpy.maximum(probs.real, [0, 0]) + norm = sum(phaseless_ratio) + r = numpy.random.random() + if norm > 0: + walker.weight = walker.weight * norm * numpy.exp(eshift) + # if walker.weight > walker.total_weight * 0.10: + # walker.weight = walker.total_weight * 0.10 + if r < phaseless_ratio[0] / norm: + xi = 0 + else: + xi = 1 + self.update_greens_function(walker, i, xi) + self.BV[0, i] = self.auxf[xi, 0] + self.BV[1, i] = self.auxf[xi, 1] + else: + walker.weight = 0 + B = numpy.einsum("ki,kij->kij", self.BV, self.BH1) + walker.stack.update(B) + # Need to recompute Green's function from scratch before we propagate it + # to the next time slice due to stack structure. + if walker.stack.time_slice % self.nstblz == 0: + walker.greens_function(None, walker.stack.time_slice - 1) + self.propagate_greens_function(walker) + + def propagate_walker_free(self, system, walker, time_slice, eshift): + fields = numpy.random.randint(0, 2, system.nbasis) + self.BV[0] = numpy.array([self.auxf[xi, 0] for xi in fields]) + self.BV[1] = numpy.array([self.auxf[xi, 1] for xi in fields]) + # Vsii Tsij + B = numpy.einsum("ki,kij->kij", self.BV, self.BH1) + wfac = 1.0 + 0j + for xi in fields: + wfac *= self.aux_wfac[xi] + # Compute determinant ratio det(1+A')/det(1+A). + # 1. Current walker's green's function. + G = walker.greens_function(None, slice_ix=walker.stack.ntime_slices, inplace=False) + # 2. Compute updated green's function. + walker.stack.update_new(B) + walker.greens_function(None, slice_ix=walker.stack.ntime_slices, inplace=True) + + # 3. Compute det(G/G') + M0 = numpy.array( + [ + scipy.linalg.det(G[0], check_finite=False), + scipy.linalg.det(G[1], check_finite=False), + ] + ) + Mnew = numpy.array( + [ + scipy.linalg.det(walker.G[0], check_finite=False), + scipy.linalg.det(walker.G[1], check_finite=False), + ] + ) + try: + # Could save M0 rather than recompute. + oratio = wfac * (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) + + walker.ot = 1.0 + # Constant terms are included in the walker's weight. + (magn, phase) = cmath.polar(oratio) + walker.weight *= magn + walker.phase *= cmath.exp(1j * phase) + except ZeroDivisionError: + walker.weight = 0.0 + # Need to recompute Green's function from scratch before we propagate it + # to the next time slice due to stack structure. + + +class HubbardContinuous(object): + """Propagator for continuous HS transformation, specialised for Hubbard model. + + Parameters + ---------- + options : dict + Propagator input options. + qmc : :class:`pie.qmc.options.QMCOpts` + QMC options. + system : :class:`pie.system.System` + System object. + trial : :class:`pie.trial_wavefunctioin.Trial` + Trial wavefunction object. + verbose : bool + If true print out more information during setup. + """ + + def __init__(self, system, trial, qmc, options={}, verbose=False): + if verbose: + print("# Parsing continuous propagator input options.") + self.hs_type = "hubbard_continuous" + self.free_projection = options.get("free_projection", False) + self.ffts = options.get("ffts", False) + self.nstblz = qmc.nstblz + self.btk = numpy.exp(-0.5 * qmc.dt * system.eks) + model = system.__class__.__name__ + self.dt = qmc.dt + self.iu_fac = 1j * system.U**0.5 + self.sqrt_dt = qmc.dt**0.5 + self.isqrt_dt = 1j * self.sqrt_dt + # optimal mean-field shift for the hubbard model + P = one_rdm_from_G(trial.G) + # Mean field shifts (2,nchol_vec). + self.mf_shift = self.construct_mean_field_shift(system, P) + if verbose: + print( + "# Absolute value of maximum component of mean field shift: " + "{:13.8e}.".format(numpy.max(numpy.abs(self.mf_shift))) + ) + self.mf_core = 0.5 * numpy.dot(self.mf_shift, self.mf_shift) + # if self.ffts: + # self.kinetic = kinetic_kspace + # else: + # self.kinetic = kinetic_real + if verbose: + print("# Finished propagator input options.") + + def construct_one_body_propagator(self, system, dt): + # \sum_gamma v_MF^{gamma} v^{\gamma} + vi1b = self.iu_fac * numpy.diag(self.mf_shift) + I = numpy.identity(system.H1[0].shape[0], dtype=system.H1.dtype) + muN = system.mu * I + sign = 1 if system._alt_convention else -1 + H1 = system.h1e_mod - numpy.array([vi1b - sign * muN, vi1b - sign * muN]) + self.BH1 = numpy.array( + [scipy.linalg.expm(-0.5 * dt * H1[0]), scipy.linalg.expm(-0.5 * dt * H1[1])] + ) + + def construct_mean_field_shift(self, system, P): + # i sqrt{U} < n_{iup} + n_{idn} >_MF + return self.iu_fac * (numpy.diag(P[0]) + numpy.diag(P[1])) + + def construct_force_bias(self, system, P, trial): + # i sqrt{U} < n_{iup} + n_{idn} > - mf_shift + vbias = self.iu_fac * (numpy.diag(P[0]) + numpy.diag(P[1])) + return -self.sqrt_dt * (vbias - self.mf_shift) + + def construct_VHS(self, system, shifted): + # Note factor of i included in v_i + # B_V(x-\bar{x}) = e^{\sqrt{dt}*(x-\bar{x})\hat{v}_i} + # v_i = n_{iu} + n_{id} + return numpy.diag(self.sqrt_dt * self.iu_fac * shifted) diff --git a/ipie/thermal/propagation/planewave.py b/ipie/thermal/propagation/planewave.py index 8b258c38..ed68f95a 100644 --- a/ipie/thermal/propagation/planewave.py +++ b/ipie/thermal/propagation/planewave.py @@ -1,16 +1,11 @@ import cmath import math -import sys -import time import numpy import scipy.sparse.linalg from scipy.linalg import sqrtm -from ipie.legacy.estimators.thermal import inverse_greens_function_qr, one_rdm_from_G -from ipie.legacy.propagation.operations import kinetic_real -from ipie.legacy.walkers.single_det import SingleDetWalker -from ipie.utils.linalg import exponentiate_matrix +from ipie.thermal.estimators.thermal import one_rdm_from_G class PlaneWave(object): diff --git a/ipie/thermal/propagation/utils.py b/ipie/thermal/propagation/utils.py new file mode 100644 index 00000000..2a8ad1c2 --- /dev/null +++ b/ipie/thermal/propagation/utils.py @@ -0,0 +1,70 @@ +"""Routines for performing propagation of a walker""" + +from ipie.thermal.propagation.continuous import Continuous +from ipie.thermal.propagation.hubbard import ThermalDiscrete +from ipie.thermal.propagation.planewave import PlaneWave + + +def get_propagator(options, qmc, system, hamiltonian, trial, verbose=False, lowrank=False): + """Wrapper to select propagator class. + + Parameters + ---------- + options : dict + Propagator input options. + qmc : :class:`pie.qmc.QMCOpts` class + Trial wavefunction input options. + system : class + System class. + trial : class + Trial wavefunction object. + + Returns + ------- + propagator : class or None + Propagator object. + """ + if hamiltonian.name == "Hubbard": + hs_type = options.get("hubbard_stratonovich", "discrete") + if hs_type == "discrete": + propagator = ThermalDiscrete( + hamiltonian, + trial, + qmc, + options=options, + verbose=verbose, + lowrank=lowrank, + ) + else: + propagator = Continuous( + options, + qmc, + system, + hamiltonian, + trial, + verbose=verbose, + lowrank=lowrank, + ) + else: + if hamiltonian.name == "UEG": + propagator = PlaneWave( + system, + hamiltonian, + trial, + qmc, + options=options, + verbose=verbose, + lowrank=lowrank, + ) + else: + propagator = Continuous( + options, + qmc, + system, + hamiltonian, + trial, + verbose=verbose, + lowrank=lowrank, + ) + + return propagator diff --git a/ipie/thermal/qmc/calc.py b/ipie/thermal/qmc/calc.py new file mode 100644 index 00000000..caed1997 --- /dev/null +++ b/ipie/thermal/qmc/calc.py @@ -0,0 +1,33 @@ +"""Helper Routines for setting up a calculation""" +# todo : handle more gracefully. + +try: + import mpi4py + + mpi4py.rc.recv_mprobe = False + from ipie.config import MPI + + # import dill + # MPI.pickle.__init__(dill.dumps, dill.loads) + parallel = True +except ImportError: + parallel = False +from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC +from ipie.utils.io import get_input_value + + +def get_driver(options, comm): + verbosity = options.get("verbosity", 1) + qmc_opts = get_input_value(options, "qmc", default={}, alias=["qmc_options"]) + beta = get_input_value(qmc_opts, "beta", default=None) + batched = get_input_value(qmc_opts, "batched", default=True) # , + # verbose=verbosity) + if beta is not None: + afqmc = ThermalAFQMC(comm, options=options, parallel=comm.size > 1, verbose=verbosity) + else: + raise NotImplementedError + + return afqmc + + + diff --git a/ipie/thermal/qmc/options.py b/ipie/thermal/qmc/options.py new file mode 100644 index 00000000..a17072bc --- /dev/null +++ b/ipie/thermal/qmc/options.py @@ -0,0 +1,150 @@ + +from ipie.utils.io import get_input_value + + +def convert_from_reduced_unit(system, qmc_opts, verbose=False): + if system.name == "UEG": + TF = system.ef # Fermi temeprature + if verbose: + print(f"# Fermi Temperature: {TF:13.8e}") + print(f"# beta in reduced unit: {qmc_opts['beta']:13.8e}") + print(f"# dt in reduced unit: {qmc_opts['dt']:13.8e}") + dt = qmc_opts["dt"] # original dt + beta = qmc_opts["beta"] # original dt + scaled_dt = dt / TF # converting to Hartree ^ -1 + scaled_beta = beta / TF # converting to Hartree ^ -1 + if verbose: + print(f"# beta in Hartree^-1: {scaled_beta:13.8e}") + print(f"# dt in Hartree^-1: {scaled_dt:13.8e}") + return scaled_dt, scaled_beta + + +class QMCOpts(object): + r"""Input options and certain constants / parameters derived from them. + + Initialised from a dict containing the following options, not all of which + are required. + + Parameters + ---------- + method : string + Which auxiliary field method are we using? Currently only CPMC is + implemented. + nwalkers : int + Number of walkers to propagate in a simulation. + dt : float + Timestep. + nsteps : int + Number of steps per block. + nmeasure : int + Frequency of energy measurements. + nstblz : int + Frequency of Gram-Schmidt orthogonalisation steps. + npop_control : int + Frequency of population control. + temp : float + Temperature. Currently not used. + nequilibrate : int + Number of steps used for equilibration phase. Only used to fix local + energy bound when using phaseless approximation. + importance_sampling : boolean + Are we using importance sampling. Default True. + hubbard_statonovich : string + Which hubbard stratonovich transformation are we using. Currently the + options are: + + - discrete : Use the discrete Hirsch spin transformation. + - opt_continuous : Use the continuous transformation for the Hubbard + model. + - generic : Use the generic transformation. To be used with Generic + system class. + + ffts : boolean + Use FFTS to diagonalise the kinetic energy propagator? Default False. + This may speed things up for larger lattices. + + Attributes + ---------- + cplx : boolean + Do we require complex wavefunctions? + mf_shift : float + Mean field shift for continuous Hubbard-Stratonovich transformation. + iut_fac : complex float + Stores i*(U*dt)**0.5 for continuous Hubbard-Stratonovich transformation. + ut_fac : float + Stores (U*dt) for continuous Hubbard-Stratonovich transformation. + mf_nsq : float + Stores M * mf_shift for continuous Hubbard-Stratonovich transformation. + local_energy_bound : float + Energy pound for continuous Hubbard-Stratonovich transformation. + mean_local_energy : float + Estimate for mean energy for continuous Hubbard-Stratonovich transformation. + """ + + def __init__(self, inputs, system, verbose=False): + self.nwalkers = get_input_value( + inputs, "num_walkers", default=10, alias=["nwalkers"], verbose=verbose + ) + self.nwalkers_per_task = get_input_value( + inputs, + "num_walkers", + default=None, + alias=["nwalkers_per_task"], + verbose=verbose, + ) + if self.nwalkers_per_task is not None: + self.nwalkers = None + self.dt = get_input_value(inputs, "timestep", default=0.005, alias=["dt"], verbose=verbose) + self.batched = get_input_value(inputs, "batched", default=True, verbose=verbose) + self.gpu = get_input_value(inputs, "gpu", default=False, verbose=verbose) + self.nsteps = get_input_value( + inputs, "num_steps", default=10, alias=["nsteps", "steps"], verbose=verbose + ) + self.nblocks = get_input_value( + inputs, + "blocks", + default=1000, + alias=["num_blocks", "nblocks"], + verbose=verbose, + ) + self.total_steps = self.nsteps * self.nblocks + self.nstblz = get_input_value( + inputs, + "stabilise_freq", + default=5, + alias=["nstabilise", "reortho"], + verbose=verbose, + ) + self.npop_control = get_input_value( + inputs, + "pop_control_freq", + default=5, + alias=["npop_control", "pop_control"], + verbose=verbose, + ) + self.eqlb_time = get_input_value( + inputs, + "equilibration_time", + default=2.0, + alias=["tau_eqlb"], + verbose=verbose, + ) + self.neqlb = int(self.eqlb_time / self.dt) + self.beta = get_input_value(inputs, "beta", default=None, verbose=verbose) + self.scaled_temp = get_input_value( + inputs, + "scaled_temperature", + default=False, + alias=["reduced_temperature"], + verbose=verbose, + ) + if self.scaled_temp: + self.beta_scaled = self.beta + self.dt, self.beta = convert_from_reduced_unit(system, inputs, verbose) + self.rng_seed = get_input_value( + inputs, + "rng_seed", + default=None, + alias=["random_seed", "seed"], + verbose=verbose, + ) diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index f4e60a9c..78e703ed 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -1,24 +1,16 @@ """Driver to perform AFQMC calculation""" -import copy -import json -import sys import time import uuid -import warnings -from math import exp -import h5py -import numpy - -from ipie.legacy.estimators.handler import Estimators -from ipie.legacy.estimators.local_energy import local_energy -from ipie.legacy.hamiltonians.utils import get_hamiltonian -from ipie.legacy.thermal_propagation.utils import get_propagator -from ipie.legacy.trial_density_matrices.utils import get_trial_density_matrix -from ipie.legacy.walkers.handler import Walkers -from ipie.legacy.qmc.options import QMCOpts +from ipie.thermal.estimators.handler import Estimators +from ipie.thermal.estimators.local_energy import local_energy +from ipie.thermal.hamiltonians.utils import get_hamiltonian +from ipie.thermal.propagation.utils import get_propagator +from ipie.thermal.trial.utils import get_trial_density_matrix +from ipie.thermal.walkers.handler import Walkers +from ipie.thermal.qmc.options import QMCOpts from ipie.qmc.utils import set_rng_seed -from ipie.legacy.systems.utils import get_system +from ipie.thermal.system.utils import get_system from ipie.utils.io import get_input_value, to_json from ipie.utils.misc import get_git_info, print_env_info from ipie.utils.mpi import get_shared_comm diff --git a/ipie/thermal/system/hubbard_holstein.py b/ipie/thermal/system/hubbard_holstein.py new file mode 100644 index 00000000..134c646c --- /dev/null +++ b/ipie/thermal/system/hubbard_holstein.py @@ -0,0 +1,505 @@ +"""Hubbard model specific classes and methods""" + +import cmath +from math import cos, pi, sqrt + +import numpy +import scipy.linalg + +from ipie.utils.io import fcidump_header + + +class HubbardHolstein(object): + """HubbardHolstein model system class. + + 1 and 2 case with nearest neighbour hopping. + + Parameters + ---------- + inputs : dict + dictionary of system input options. + + Attributes + ---------- + nup : int + Number of up electrons. + ndown : int + Number of down electrons. + ne : int + Number of electrons. + t : float + Hopping parameter. + U : float + Hubbard U interaction strength. + g : float + Holstein coupling strength + lmbda : float + Polaron formation energy + w0 : float + Frequency w0 + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + nbasis : int + Number of single-particle basis functions. + T : numpy.array + Hopping matrix + """ + + def __init__(self, inputs, verbose=False): + if verbose: + print("# Parsing input options.") + self.nup = inputs.get("nup") + self.ndown = inputs.get("ndown") + self.ne = self.nup + self.ndown + self.nelec = (self.nup, self.ndown) + + self.control_variate = False + + self.t = inputs.get("t", 1.0) + self.lmbda = inputs.get("lambda", 1.0) + self.w0 = inputs.get("w0", 1.0) + self.m = inputs.get("m", 1.0 / self.w0) # mass + + self.U = inputs["U"] + self.nx = inputs["nx"] + self.ny = inputs["ny"] + self.ktwist = numpy.array(inputs.get("ktwist")) + self.symmetric = inputs.get("symmetric", False) + + self.ypbc = inputs.get("ypbc", True) + self.xpbc = inputs.get("xpbc", True) + + self.control_variate = False + + if self.symmetric: + # An unusual convention for the sign of the chemical potential is + # used in Phys. Rev. B 99, 045108 (2018) + # Symmetric uses the symmetric form of the hubbard model and will + # also change the sign of the chemical potential in the density + # matrix. + self._alt_convention = True + else: + self._alt_convention = False + self.nbasis = self.nx * self.ny + + # This depends on the dimension of the system hard-coded to do 1D + d = 2 + if self.nx == 1 or self.ny == 1: # 1d + d = 1 + + self.g = inputs.get("g", None) + + if self.g == None: + # This is assuming self.m = 1 / self.w0 + # to include mass see 10.1103/PhysRevLett.97.056402 + self.g = sqrt(float(d) * 2.0 * self.lmbda * self.t * self.w0) + + if verbose: + print(f"# d = {d}") + print(f"# nx, ny = {self.nx},{self.ny}") + print(f"# nbasis = {self.nbasis}") + print(f"# t, U = {self.t}, {self.U}") + print(f"# m, w0, g, lambda = {self.m}, {self.w0}, {self.g}, {self.lmbda}") + + self.lang_firsov = inputs.get("lang_firsov", False) + self.gamma_lf = 0.0 + if self.lang_firsov: + self.gamma_lf = self.g * numpy.sqrt(2.0 / (self.m * self.w0**3)) + self.Ueff = ( + self.U + + self.gamma_lf**2 * self.m * self.w0**2 + - 2.0 * self.g * self.gamma_lf * numpy.sqrt(2.0 * self.m * self.w0) + ) + print(f"# gamma_lf = {self.gamma_lf}") + print(f"# Ueff = {self.Ueff}") + + self.nactive = self.nbasis + self.nfv = 0 + self.ncore = 0 + (self.kpoints, self.kc, self.eks) = kpoints(self.t, self.nx, self.ny) + self.pinning = inputs.get("pinning_fields", False) + self._opt = True + if verbose: + print("# Setting up one-body operator.") + if self.pinning: + if verbose: + print("# Using pinning field.") + self.T = kinetic_pinning_alt(self.t, self.nbasis, self.nx, self.ny) + else: + self.T = kinetic( + self.t, + self.nbasis, + self.nx, + self.ny, + self.ktwist, + xpbc=self.xpbc, + ypbc=self.ypbc, + ) + self.H1 = self.T + self.Text = scipy.linalg.block_diag(self.T[0], self.T[1]) + self.P = transform_matrix(self.nbasis, self.kpoints, self.kc, self.nx, self.ny) + self.mu = inputs.get("mu", None) + # For interface consistency. + self.ecore = 0.0 + # Number of field configurations per walker. + self.nfields = self.nbasis + self.name = "HubbardHolstein" + if verbose: + print("# Finished setting up Hubbard-Holstein system object.") + # "Volume" to define density. + self.vol = self.nx * self.ny + self.construct_h1e_mod() + + def fcidump(self, to_string=False): + """Dump 1- and 2-electron integrals to file. + + Parameters + ---------- + to_string : bool + Return fcidump as string. Default print to stdout. + """ + header = fcidump_header(self.ne, self.nbasis, self.nup - self.ndown) + for i in range(1, self.nbasis + 1): + if self.T.dtype == complex: + fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" + line = fmt.format(self.U.real, self.U.imag, i, i, i, i) + else: + fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" + line = fmt.format(self.U, i, i, i, i) + header += line + for i in range(0, self.nbasis): + for j in range(i + 1, self.nbasis): + integral = self.T[0][i, j] + if abs(integral) > 1e-8: + if self.T.dtype == complex: + fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" + line = fmt.format(integral.real, integral.imag, i + 1, j + 1, 0, 0) + else: + fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" + line = fmt.format(integral, i + 1, j + 1, 0, 0) + header += line + if self.T.dtype == complex: + fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" + header += fmt.format(0, 0, 0, 0, 0, 0) + else: + fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" + header += fmt.format(0, 0, 0, 0, 0) + if to_string: + print(header) + else: + return header + + def hijkl(self, i, j, k, l): + if i == k and j == l and i == j: + return self.U + else: + return 0.0 + + def construct_h1e_mod(self): + # Subtract one-body bit following reordering of 2-body operators. + # Eqn (17) of [Motta17]_ + if not self.symmetric: + v0 = 0.5 * self.U * numpy.eye(self.nbasis) + self.h1e_mod = numpy.array([self.H1[0] - v0, self.H1[1] - v0]) + else: + self.h1e_mod = self.H1 + + +def transform_matrix(nbasis, kpoints, kc, nx, ny): + U = numpy.zeros(shape=(nbasis, nbasis), dtype=complex) + for i, k_i in enumerate(kpoints): + for j in range(0, nbasis): + r_j = decode_basis(nx, ny, j) + U[i, j] = numpy.exp(1j * numpy.dot(kc * k_i, r_j)) + + return U + + +def kinetic(t, nbasis, nx, ny, ks, xpbc=True, ypbc=True): + """Kinetic part of the Hamiltonian in our one-electron basis. + + Parameters + ---------- + t : float + Hopping parameter + nbasis : int + Number of one-electron basis functions. + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + + Returns + ------- + T : numpy.array + Hopping Hamiltonian matrix. + """ + + if ks.all() is None: + T = numpy.zeros((nbasis, nbasis), dtype=float) + else: + T = numpy.zeros((nbasis, nbasis), dtype=complex) + + for i in range(0, nbasis): + xy1 = decode_basis(nx, ny, i) + for j in range(i + 1, nbasis): + xy2 = decode_basis(nx, ny, j) + dij = abs(xy1 - xy2) + if sum(dij) == 1: + T[i, j] = -t + # Take care of periodic boundary conditions + # there should be a less stupid way of doing this. + if ny == 1 and dij == [nx - 1] and xpbc: + if ks.all() is not None: + phase = cmath.exp(1j * numpy.dot(cmath.pi * ks, [1])) + else: + phase = 1.0 + T[i, j] += -t * phase + elif (dij == [nx - 1, 0]).all() and xpbc: + if ks.all() is not None: + phase = cmath.exp(1j * numpy.dot(cmath.pi * ks, [1, 0])) + else: + phase = 1.0 + T[i, j] += -t * phase + elif (dij == [0, ny - 1]).all() and ypbc: + if ks.all() is not None: + phase = cmath.exp(1j * numpy.dot(cmath.pi * ks, [0, 1])) + else: + phase = 1.0 + T[i, j] += -t * phase + + # This only works because the diagonal of T is zero. + return numpy.array([T + T.conj().T, T + T.conj().T]) + + +def kinetic_pinning(t, nbasis, nx, ny): + r"""Kinetic part of the Hamiltonian in our one-electron basis. + + Adds pinning fields as outlined in [Qin16]_. This forces periodic boundary + conditions along x and open boundary conditions along y. Pinning fields are + applied in the y direction as: + + .. math:: + \nu_{i\uparrow} = -\nu_{i\downarrow} = (-1)^{i_x+i_y}\nu_0, + + for :math:`i_y=1,L_y` and :math:`\nu_0=t/4`. + + Parameters + ---------- + t : float + Hopping parameter + nbasis : int + Number of one-electron basis functions. + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + + Returns + ------- + T : numpy.array + Hopping Hamiltonian matrix. + """ + + Tup = numpy.zeros((nbasis, nbasis)) + Tdown = numpy.zeros((nbasis, nbasis)) + nu0 = 0.25 * t + + for i in range(0, nbasis): + # pinning field along y. + xy1 = decode_basis(nx, ny, i) + if xy1[1] == 0 or xy1[1] == ny - 1: + Tup[i, i] += (-1.0) ** (xy1[0] + xy1[1]) * nu0 + Tdown[i, i] += (-1.0) ** (xy1[0] + xy1[1] + 1) * nu0 + for j in range(i + 1, nbasis): + xy2 = decode_basis(nx, ny, j) + dij = abs(xy1 - xy2) + if sum(dij) == 1: + Tup[i, j] = Tdown[i, j] = -t + # periodic bcs in x. + if (dij == [nx - 1, 0]).all(): + Tup[i, j] += -t + Tdown[i, j] += -t + + return numpy.array([Tup + numpy.triu(Tup, 1).T, Tdown + numpy.triu(Tdown, 1).T]) + + +def kinetic_pinning_alt(t, nbasis, nx, ny): + r"""Kinetic part of the Hamiltonian in our one-electron basis. + + Adds pinning fields as outlined in [Qin16]_. This forces periodic boundary + conditions along x and open boundary conditions along y. Pinning fields are + applied in the y direction as: + + .. math:: + \nu_{i\uparrow} = -\nu_{i\downarrow} = (-1)^{i_x+i_y}\nu_0, + + for :math:`i_y=1,L_y` and :math:`\nu_0=t/4`. + + Parameters + ---------- + t : float + Hopping parameter + nbasis : int + Number of one-electron basis functions. + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + + Returns + ------- + T : numpy.array + Hopping Hamiltonian matrix. + """ + + Tup = numpy.zeros((nbasis, nbasis)) + Tdown = numpy.zeros((nbasis, nbasis)) + h = 0.1 * t + + for i in range(0, nbasis): + # pinning field along y direction when i_x = 0. + xy1 = decode_basis(nx, ny, i) + if xy1[0] == 0: + Tup[i, i] += (-1.0) ** (xy1[1]) * h + Tdown[i, i] += (-1.0) ** (xy1[1] + 1) * h + for j in range(i + 1, nbasis): + xy2 = decode_basis(nx, ny, j) + dij = abs(xy1 - xy2) + if sum(dij) == 1: + Tup[i, j] = Tdown[i, j] = -t + # periodic bcs in y. + if (dij == [0, ny - 1]).all(): + Tup[i, j] += -t + Tdown[i, j] += -t + + return numpy.array([Tup + numpy.triu(Tup, 1).T, Tdown + numpy.triu(Tdown, 1).T]) + + +def decode_basis(nx, ny, i): + """Return cartesian lattice coordinates from basis index. + + Consider a 3x3 lattice then we index lattice sites like:: + + (0,2) (1,2) (2,2) 6 7 8 + (0,1) (1,1) (2,1) -> 3 4 5 + (0,0) (1,0) (2,0) 0 1 2 + + i.e., i = i_x + n_x * i_y, and i_x = i%n_x, i_y = i//nx. + + Parameters + ---------- + nx : int + Number of x lattice sites. + ny : int + Number of y lattice sites. + i : int + Basis index (same for up and down spins). + """ + if ny == 1: + return numpy.array([i % nx]) + else: + return numpy.array([i % nx, i // nx]) + + +def encode_basis(i, j, nx): + """Encode 2d index to one dimensional index. + + See decode basis for layout. + + Parameters + ---------- + i : int + x coordinate. + j : int + y coordinate + nx : int + Number of x lattice sites. + + Returns + ------- + ix : int + basis index. + """ + return i + j * nx + + +def _super_matrix(U, nbasis): + """Construct super-matrix from v_{ijkl}""" + + +def kpoints(t, nx, ny): + """Construct kpoints for system. + + Parameters + ---------- + t : float + Hopping amplitude. + nx : int + Number of x lattice sites. + nx : int + Number of y lattice sites. + + Returns + ------- + kp : numpy array + System kpoints Note these are not sorted according to eigenvalue energy + but rather so as to conform with numpys default kpoint indexing for FFTs. + kfac : float + Kpoint scaling factor (2pi/L). + eigs : numpy array + Single particle eigenvalues associated with kp. + """ + kp = [] + eigs = [] + if ny == 1: + kfac = numpy.array([2.0 * pi / nx]) + for n in range(0, nx): + kp.append(numpy.array([n])) + eigs.append(ek(t, n, kfac, ny)) + else: + kfac = numpy.array([2.0 * pi / nx, 2.0 * pi / ny]) + for n in range(0, nx): + for m in range(0, ny): + k = numpy.array([n, m]) + kp.append(k) + eigs.append(ek(t, k, kfac, ny)) + + eigs = numpy.array(eigs) + kp = numpy.array(kp) + return (kp, kfac, eigs) + + +def ek(t, k, kc, ny): + """Calculate single-particle energies. + + Parameters + ---------- + t : float + Hopping amplitude. + k : numpy array + Kpoint. + kc : float + Scaling factor. + ny : int + Number of y lattice points. + """ + if ny == 1: + e = -2.0 * t * cos(kc * k) + else: + e = -2.0 * t * (cos(kc[0] * k[0]) + cos(kc[1] * k[1])) + + return e + + +def get_strip(cfunc, cfunc_err, ix, nx, ny, stag=False): + iy = [i for i in range(ny)] + idx = [encode_basis(ix, i, nx) for i in iy] + if stag: + c = [((-1) ** (ix + i)) * cfunc[ib] for (i, ib) in zip(iy, idx)] + else: + c = [cfunc[ib] for ib in idx] + cerr = [cfunc_err[ib] for ib in idx] + return c, cerr diff --git a/ipie/thermal/system/ueg.py b/ipie/thermal/system/ueg.py new file mode 100644 index 00000000..493d4917 --- /dev/null +++ b/ipie/thermal/system/ueg.py @@ -0,0 +1,98 @@ +import math +import numpy + + + +class UEG(object): + """UEG system class (integrals read from fcidump) + Parameters + ---------- + nup : int + Number of up electrons. + ndown : int + Number of down electrons. + rs : float + Density parameter. + ecut : float + Scaled cutoff energy. + ktwist : :class:`numpy.ndarray` + Twist vector. + verbose : bool + Print extra information. + Attributes + ---------- + T : :class:`numpy.ndarray` + One-body part of the Hamiltonian. This is diagonal in plane wave basis. + ecore : float + Madelung contribution to the total energy. + h1e_mod : :class:`numpy.ndarray` + Modified one-body Hamiltonian. + nfields : int + Number of field configurations per walker for back propagation. + basis : :class:`numpy.ndarray` + Basis vectors within a cutoff. + kfac : float + Scale factor (2pi/L). + """ + + def __init__(self, options, verbose=False): + if verbose: + print("# Parsing input options for systems.UEG.") + self.name = "UEG" + self.nup = options.get("nup") + self.ndown = options.get("ndown") + self.nelec = (self.nup, self.ndown) + self.rs = options.get("rs") + self.ecut = options.get("ecut") + self.ktwist = numpy.array(options.get("ktwist", [0, 0, 0])).reshape(3) + self.control_variate = False + self.mu = options.get("mu", None) + if verbose: + print(f"# Number of spin-up electrons: {self.nup:d}") + print(f"# Number of spin-down electrons: {self.ndown:d}") + print(f"# rs: {self.rs:6.4e}") + if self.mu is not None: + print(f"# mu: {self.mu:6.4e}") + + self.thermal = options.get("thermal", False) + if self.thermal and verbose: + print("# Thermal UEG activated") + self._alt_convention = options.get("alt_convention", False) + self.sparse = True + + # total # of electrons + self.ne = self.nup + self.ndown + # spin polarisation + self.zeta = (self.nup - self.ndown) / self.ne + # Density. + self.rho = ((4.0 * math.pi) / 3.0 * self.rs**3.0) ** (-1.0) + # Box Length. + self.L = self.rs * (4.0 * self.ne * math.pi / 3.0) ** (1 / 3.0) + # Volume + self.vol = self.L**3.0 + # k-space grid spacing. + # self.kfac = 2*math.pi/self.L + self.kfac = 2 * math.pi / self.L + # Fermi Wavevector (infinite system). + self.kf = (3 * (self.zeta + 1) * math.pi**2 * self.ne / self.L**3) ** (1 / 3.0) + # Fermi energy (inifinite systems). + self.ef = 0.5 * self.kf**2 + if verbose: + print(f"# Spin polarisation (zeta): {self.zeta:6.4e}") + print(f"# Electron density (rho): {self.rho:13.8e}") + print(f"# Box Length (L): {self.L:13.8e}") + print(f"# Volume: {self.vol:13.8e}") + print(f"# k-space factor (2pi/L): {self.kfac:13.8e}") + + +def unit_test(): + from numpy import linalg as LA + + from ipie.estimators import ci as pieci + + options = {"nup": 2, "ndown": 2, "rs": 1.0, "thermal": True, "ecut": 3} + system = UEG(options, True) + + +if __name__ == "__main__": + unit_test() diff --git a/ipie/thermal/system/utils.py b/ipie/thermal/system/utils.py new file mode 100644 index 00000000..d5fdafa9 --- /dev/null +++ b/ipie/thermal/system/utils.py @@ -0,0 +1,45 @@ +import sys + + +from ipie.thermal.system.ueg import UEG +from ipie.systems.generic import Generic + + +def get_system(sys_opts=None, verbose=0, comm=None): + """Wrapper to select system class + + Parameters + ---------- + sys_opts : dict + System input options. + verbose : bool + Output verbosity. + + Returns + ------- + system : object + System class. + """ + if not ("name" in sys_opts): + sys_opts["name"] = "Generic" + + if sys_opts["name"] == "UEG": + system = UEG(sys_opts, verbose) + elif ( + sys_opts["name"] == "Hubbard" + or sys_opts["name"] == "HubbardHolstein" + or sys_opts["name"] == "Generic" + ): + nup, ndown = sys_opts.get("nup"), sys_opts.get("ndown") + if nup is None or ndown is None: + if comm.rank == 0: + print("# Error: Number of electrons not specified.") + sys.exit() + nelec = (nup, ndown) + system = Generic(nelec, verbose) + else: + if comm.rank == 0: + print(f"# Error: unrecognized system name {sys_opts['name']}.") + sys.exit() + + return system diff --git a/ipie/thermal/tests/__init__.py b/ipie/thermal/tests/__init__.py new file mode 100644 index 00000000..32298b95 --- /dev/null +++ b/ipie/thermal/tests/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Author: Joonho Lee +# diff --git a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/input.json b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/input.json new file mode 100644 index 00000000..5e6ab9ef --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/input.json @@ -0,0 +1,32 @@ +{ + "system": { + "name": "Hubbard", + "nx": 4, + "ny": 4, + "nup": 7, + "ndown": 7, + "mu": 0.1, + "U": 4 + }, + "qmc": { + "dt": 0.01, + "nwalkers": 1, + "blocks": 10, + "nsteps": 10, + "rng_seed": 7, + "beta": 0.25, + "pop_control_freq": 5, + "stabilise_freq": 10, + "batched": false + }, + "trial": { + "name": "one_body" + }, + "walkers": { + "pop_control": "comb" + }, + "propagator": { + "hubbard_stratonovich": "discrete" + }, + "estimators": {} +} diff --git a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference.json b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference.json new file mode 100644 index 00000000..904b376c --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference.json @@ -0,0 +1 @@ +{"WeightFactor": [32.0, 44.98447572409485], "Weight": [32.0, 42.93486118721573], "ENumer": [152.0047418107582, 24.59220437157029], "EDenom": [32.0, 42.93486118721573], "ETotal": [4.7501481815861935, 0.5727794079579522], "E1Body": [-7.499853241434115, -7.179410491868211], "E2Body": [12.250001423020308, 7.752189899826164], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154433, 13.205553548235017], "sys_info": {"nranks": 4, "branch": "develop", "sha1": "5de52c915d59fc1e026bb3b42812f6daa4d1010b", "numpy": {"version": "1.18.4", "path": "/usr/local/lib/python3.7/site-packages/numpy", "BLAS": {"lib": "openblas openblas", "path": "/usr/local/lib"}}, "scipy": {"version": "1.4.1", "path": "/usr/local/lib/python3.7/site-packages/scipy"}, "h5py": {"version": "2.10.0", "path": "/usr/local/lib/python3.7/site-packages/h5py"}, "mpi4py": {"version": "3.0.1", "path": "/usr/local/lib/python3.7/site-packages/mpi4py", "mpicc": "/usr/local/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_1walker.json b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_1walker.json new file mode 100644 index 00000000..11509601 --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_1walker.json @@ -0,0 +1 @@ +{"WeightFactor": [1.0, 1.0], "Weight": [1.0, 0.1], "ENumer": [4.750148181586211, 0.004372991515192037], "EDenom": [1.0, 0.1], "ETotal": [4.750148181586211, 0.04372991515192037], "E1Body": [-7.499853241434114, -7.797076838398823], "E2Body": [12.250001423020326, 7.840806753550744], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154449, 13.195457786831575], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "3e25fb5948014be236679907b176cb8087863e3e-dirty", "numpy": {"version": "1.24.4", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json new file mode 100644 index 00000000..0fbf7b3e --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json @@ -0,0 +1 @@ +{"WeightFactor": [32.0, 44.98645457011622], "Weight": [32.0, 43.034282083027925], "ENumer": [152.0047418107588, 20.184762894579933], "EDenom": [32.0, 43.034282083027925], "ETotal": [4.750148181586212, 0.4690391454802612], "E1Body": [-7.499853241434117, -7.214851781729806], "E2Body": [12.250001423020322, 7.683890927210067], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154442, 13.233641168838517], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "a67b7598397a8e99b75d50bc67fd18ec2ee20b76-dirty", "numpy": {"version": "1.24.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}, "mpi4py": {"version": "3.1.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/mpi4py", "mpicc": "/sw/spack/delta-2022-03/apps/openmpi/4.1.4-gcc-11.2.0-7ooytax/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json new file mode 100644 index 00000000..7f7aa195 --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json @@ -0,0 +1,32 @@ +{ + "system": { + "name": "UEG", + "nup": 7, + "ndown": 7, + "rs": 1.0, + "mu": -1.0, + "ecut": 1.0 + }, + "qmc": { + "dt": 0.01, + "nwalkers": 1, + "blocks": 10, + "nsteps": 10, + "beta": 0.1, + "rng_seed": 7, + "pop_control_freq": 1, + "stabilise_freq": 10, + "batched": false + }, + "trial": { + "name": "one_body" + }, + "walkers": { + "population_control": "pair_branch" + }, + "estimators": { + "mixed": { + "one_rdm": true + } + } +} diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json new file mode 100644 index 00000000..c278179f --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json @@ -0,0 +1 @@ +{"WeightFactor": [32.0, 47.94831398616111], "Weight": [32.0, 31.999999999999996], "ENumer": [853.4128425513718, 986.7912119123343], "EDenom": [32.0, 31.999999999999996], "ETotal": [26.66915132973037, 30.837225372260455], "E1Body": [28.374994808285745, 33.21707786343164], "E2Body": [-1.705843478555375, -2.379852491171182], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209672, 16.375812925843057], "sys_info": {"nranks": 4, "branch": "hubbard_updates", "sha1": "618262bc7511a252e2f2bb3f23cc96fa4e8b9eb5", "numpy": {"version": "1.18.4", "path": "/usr/local/lib/python3.7/site-packages/numpy", "BLAS": {"lib": "openblas openblas", "path": "/usr/local/lib"}}, "scipy": {"version": "1.4.1", "path": "/usr/local/lib/python3.7/site-packages/scipy"}, "h5py": {"version": "2.10.0", "path": "/usr/local/lib/python3.7/site-packages/h5py"}, "mpi4py": {"version": "3.0.1", "path": "/usr/local/lib/python3.7/site-packages/mpi4py", "mpicc": "/usr/local/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_1walker.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_1walker.json new file mode 100644 index 00000000..46a6ca8f --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_1walker.json @@ -0,0 +1 @@ +{"WeightFactor": [1.0, 1.0], "Weight": [1.0, 0.1], "ENumer": [26.669151329730372, 3.0880611634447632], "EDenom": [1.0, 0.1], "ETotal": [26.669151329730372, 30.880611634447632], "E1Body": [28.374994808285745, 33.2449965368494], "E2Body": [-1.7058434785553742, -2.364384902401771], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209672, 16.388846234869657], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "3e25fb5948014be236679907b176cb8087863e3e-dirty", "numpy": {"version": "1.24.4", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json new file mode 100644 index 00000000..553a1533 --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json @@ -0,0 +1 @@ +{"WeightFactor": [32.0, 47.79071285048463], "Weight": [32.0, 31.999999999999996], "ENumer": [853.4128425513711, 986.9792326724249], "EDenom": [32.0, 31.999999999999996], "ETotal": [26.669151329730347, 30.843101021013286], "E1Body": [28.374994808285724, 33.221059734849845], "E2Body": [-1.7058434785553744, -2.3779587138365548], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209661, 16.377795476555466], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "a67b7598397a8e99b75d50bc67fd18ec2ee20b76-dirty", "numpy": {"version": "1.24.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}, "mpi4py": {"version": "3.1.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/mpi4py", "mpicc": "/sw/spack/delta-2022-03/apps/openmpi/4.1.4-gcc-11.2.0-7ooytax/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/test_ft_integration.py b/ipie/thermal/tests/test_ft_integration.py new file mode 100644 index 00000000..e51bc99d --- /dev/null +++ b/ipie/thermal/tests/test_ft_integration.py @@ -0,0 +1,116 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + +import json +import os +import sys +import tempfile +import uuid + +import numpy as np + +from ipie.analysis.extraction import extract_test_data_hdf5 +from ipie.config import MPI +from ipie.qmc.calc import get_driver, read_input + +_built_legacy = True + + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) +else: + test_id = None +test_id = comm.bcast(test_id, root=0) + +_data_dir = os.path.abspath(os.path.dirname(__file__)) + "/reference_data/" +_legacy_test_dirs = [ + "ft_4x4_hubbard_discrete", + "ft_ueg_ecut1.0_rs1.0", +] + + +_legacy_tests = [ + (_data_dir + d + "/input.json", _data_dir + d + "/reference_1walker.json") for d in _legacy_test_dirs +] + + +def compare_test_data(ref, test): + comparison = {} + for k, v in ref.items(): + if k == "sys_info": + continue + try: + comparison[k] = ( + np.array(ref[k]), + np.array(test[k]), + np.max(np.abs(np.array(ref[k]) - np.array(test[k]))) < 1e-10, + ) + except KeyError: + print(f"# Issue with test data key {k}") + return comparison + + +def run_test_system(input_file, benchmark_file, legacy_job=False): + comm = MPI.COMM_WORLD + input_dict = read_input(input_file, comm) + if input_dict["system"].get("integrals") is not None: + input_dict["system"]["integrals"] = input_file[:-10] + "afqmc.h5" + input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" + elif ("hamiltonian" in input_dict) and (input_dict["hamiltonian"].get("integrals") is not None): + input_dict["hamiltonian"]["integrals"] = input_file[:-10] + "afqmc.h5" + input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" + with tempfile.NamedTemporaryFile() as tmpf: + input_dict["estimators"]["filename"] = tmpf.name + if _built_legacy and legacy_job: + from ipie.thermal.qmc.calc import get_driver as get_legacy_driver + + input_dict["qmc"]["batched"] = False + afqmc = get_legacy_driver(input_dict, comm) + afqmc.run(comm=comm) + afqmc.finalise(comm) + else: + afqmc = get_driver(input_dict, comm) + afqmc.run(estimator_filename=tmpf.name) + afqmc.finalise() + with open(benchmark_file, "r") as f: + ref_data = json.load(f) + skip_val = ref_data.get("extract_skip_value", 10) + test_data = extract_test_data_hdf5(tmpf.name, skip=skip_val) + comparison = compare_test_data(ref_data, test_data) + + return comparison + + +if __name__ == "__main__": + err_count = 0 + for test_name, (ind, outd) in zip(_legacy_test_dirs, _legacy_tests): + comparison = run_test_system(ind, outd, legacy_job=True) + local_err_count = 0 + for k, v in comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f" *** FAILED *** : mismatch between benchmark and test run: {test_name}") + err_count += 1 + print(f"name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + if local_err_count == 0: + print(f"*** PASSED : {test_name} ***") + err_count = comm.bcast(err_count) + sys.exit(err_count) diff --git a/ipie/thermal/trial/chem_pot.py b/ipie/thermal/trial/chem_pot.py index f5f19aa7..29946327 100644 --- a/ipie/thermal/trial/chem_pot.py +++ b/ipie/thermal/trial/chem_pot.py @@ -1,6 +1,6 @@ import numpy -from ipie.legacy.estimators.thermal import one_rdm_stable, particle_number +from ipie.thermal.estimators.thermal import one_rdm_stable, particle_number from ipie.utils.io import format_fixed_width_floats, format_fixed_width_strings diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index 46c01bb4..94b3026c 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -1,11 +1,11 @@ import numpy import scipy.linalg -from ipie.legacy.estimators.fock import fock_matrix -from ipie.legacy.estimators.local_energy import local_energy -from ipie.legacy.estimators.thermal import entropy, greens_function, one_rdm_stable, particle_number -from ipie.legacy.trial_density_matrices.chem_pot import compute_rho, find_chemical_potential -from ipie.legacy.trial_density_matrices.onebody import OneBody +from ipie.thermal.estimators.fock import fock_matrix +from ipie.thermal.estimators.local_energy import local_energy +from ipie.thermal.estimators.thermal import entropy, greens_function, one_rdm_stable, particle_number +from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential +from ipie.thermal.trial.onebody import OneBody class MeanField(OneBody): diff --git a/ipie/thermal/trial/onebody.py b/ipie/thermal/trial/onebody.py index 9d262336..f349c945 100644 --- a/ipie/thermal/trial/onebody.py +++ b/ipie/thermal/trial/onebody.py @@ -1,18 +1,13 @@ -import math -import sys import numpy import scipy.linalg -from ipie.legacy.estimators.local_energy import local_energy -from ipie.legacy.estimators.thermal import ( +from ipie.thermal.estimators.thermal import ( greens_function, - one_rdm, - one_rdm_from_G, one_rdm_stable, particle_number, ) -from ipie.legacy.trial_density_matrices.chem_pot import compute_rho, find_chemical_potential +from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.utils.misc import update_stack diff --git a/ipie/thermal/trial/utils.py b/ipie/thermal/trial/utils.py index 9ca857a2..f0e8b71b 100644 --- a/ipie/thermal/trial/utils.py +++ b/ipie/thermal/trial/utils.py @@ -1,5 +1,5 @@ -from ipie.legacy.trial_density_matrices.mean_field import MeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.trial.onebody import OneBody def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=None, verbose=False): diff --git a/ipie/thermal/walkers/handler.py b/ipie/thermal/walkers/handler.py new file mode 100644 index 00000000..35e985be --- /dev/null +++ b/ipie/thermal/walkers/handler.py @@ -0,0 +1,429 @@ +import cmath +import sys +import time + +import h5py +import numpy + +from ipie.thermal.walkers.thermal import ThermalWalker +from ipie.utils.io import get_input_value +from ipie.utils.misc import update_stack + + +class Walkers(object): + """Container for groups of walkers which make up a wavefunction. + + Parameters + ---------- + system : object + System object. + trial : object + Trial wavefunction object. + nwalkers : int + Number of walkers to initialise. + nprop_tot : int + Total number of propagators to store for back propagation + itcf. + nbp : int + Number of back propagation steps. + """ + + def __init__( + self, + system, + hamiltonian, + trial, + qmc, + walker_opts={}, + verbose=False, + comm=None, + nprop_tot=None, + nbp=None, + ): + self.nwalkers = qmc.nwalkers + self.ntot_walkers = qmc.ntot_walkers + self.write_freq = walker_opts.get("write_freq", 0) + self.write_file = walker_opts.get("write_file", "restart.h5") + self.use_log_shift = walker_opts.get("use_log_shift", False) + self.shift_counter = 1 + self.read_file = walker_opts.get("read_file", None) + if comm is None: + rank = 0 + else: + rank = comm.rank + if verbose: + print("# Setting up walkers.handler.Walkers.") + print(f"# qmc.nwalkers = {self.nwalkers}") + print(f"# qmc.ntot_walkers = {self.ntot_walkers}") + + if trial.name in ["MultiSlater", "coherent_state"]: + print(trial.name) + raise NotImplementedError + elif trial.name == "thermal": + self.walker_type = "thermal" + self.walkers = [ + ThermalWalker( + system, + hamiltonian, + trial, + walker_opts=walker_opts, + verbose=(verbose and w == 0), + ) + for w in range(qmc.nwalkers) + ] + self.buff_size = self.walkers[0].buff_size + self.walkers[0].stack.buff_size + self.walker_buffer = numpy.zeros(self.buff_size, dtype=numpy.complex128) + stack_size = self.walkers[0].stack_size + if hamiltonian.name == "Hubbard": + if stack_size % qmc.nstblz != 0 or qmc.nstblz < stack_size: + if verbose: + print("# Stabilisation frequency is not commensurate " "with stack size.") + print("# Determining a better value.") + if qmc.nstblz < stack_size: + qmc.nstblz = stack_size + if verbose: + print(f"# Updated stabilization frequency: {qmc.nstblz}") + else: + qmc.nstblz = update_stack( + qmc.nstblz, stack_size, name="nstblz", verbose=verbose + ) + else: + raise NotImplementedError + if hamiltonian.name == "Generic" or system.name == "UEG": + dtype = complex + else: + dtype = int + self.pcont_method = get_input_value( + walker_opts, + "population_control", + alias=["pop_control"], + default="pair_branch", + verbose=verbose, + ) + self.min_weight = walker_opts.get("min_weight", 0.1) + self.max_weight = walker_opts.get("max_weight", 4.0) + if verbose: + print(f"# Using {self.pcont_method} population control algorithm.") + mem = float(self.walker_buffer.nbytes) / (1024.0**3) + print(f"# Buffer size for communication: {mem:13.8e} GB") + if mem > 2.0: + # TODO: FDM FIX THIS + print(" # Warning: Walker buffer size > 2GB. May run into MPI" "issues.") + if not self.walker_type == "thermal": + walker_size = 3 + self.walkers[0].phi.size + if self.write_freq > 0: + self.write_restart = True + self.dsets = [] + with h5py.File(self.write_file, "w", driver="mpio", comm=comm) as fh5: + for i in range(self.ntot_walkers): + fh5.create_dataset("walker_%d" % i, (walker_size,), dtype=numpy.complex128) + + else: + self.write_restart = False + if self.read_file is not None: + if verbose: + print(f"# Reading walkers from {self.read_file} file series.") + self.read_walkers(comm) + self.target_weight = qmc.ntot_walkers + self.nw = qmc.nwalkers + self.set_total_weight(qmc.ntot_walkers) + + if verbose: + print("# Finish setting up walkers.handler.Walkers.") + + def orthogonalise(self, trial, free_projection): + """Orthogonalise all walkers. + + Parameters + ---------- + trial : object + Trial wavefunction object. + free_projection : bool + True if doing free projection. + """ + for w in self.walkers: + detR = w.reortho(trial) + if free_projection: + (magn, dtheta) = cmath.polar(detR) + w.weight *= magn + w.phase *= cmath.exp(1j * dtheta) + + + def copy_historic_wfn(self): + """Copy current wavefunction to psi_n for next back propagation step.""" + for i, w in enumerate(self.walkers): + numpy.copyto(self.walkers[i].phi_old, self.walkers[i].phi) + + def copy_bp_wfn(self, phi_bp): + """Copy back propagated wavefunction. + + Parameters + ---------- + phi_bp : object + list of walker objects containing back propagated walkers. + """ + for i, (w, wbp) in enumerate(zip(self.walkers, phi_bp)): + numpy.copyto(self.walkers[i].phi_bp, wbp.phi) + + def copy_init_wfn(self): + """Copy current wavefunction to initial wavefunction. + + The definition of the initial wavefunction depends on whether we are + calculating an ITCF or not. + """ + for i, w in enumerate(self.walkers): + numpy.copyto(self.walkers[i].phi_right, self.walkers[i].phi) + + def pop_control(self, comm): + if self.ntot_walkers == 1: + return + if self.use_log_shift: + self.update_log_ovlp(comm) + weights = numpy.array([abs(w.weight) for w in self.walkers]) + global_weights = numpy.empty(len(weights) * comm.size) + comm.Allgather(weights, global_weights) + total_weight = sum(global_weights) + # Rescale weights to combat exponential decay/growth. + scale = total_weight / self.target_weight + if total_weight < 1e-8: + if comm.rank == 0: + print(f"# Warning: Total weight is {total_weight:13.8e}: ") + print("# Something is seriously wrong.") + sys.exit() + self.set_total_weight(total_weight) + # Todo: Just standardise information we want to send between routines. + for w in self.walkers: + w.unscaled_weight = w.weight + w.weight = w.weight / scale + if self.pcont_method == "comb": + global_weights = global_weights / scale + self.comb(comm, global_weights) + elif self.pcont_method == "pair_branch": + self.pair_branch(comm) + else: + if comm.rank == 0: + print("Unknown population control method.") + + def comb(self, comm, weights): + """Apply the comb method of population control / branching. + + See Booth & Gubernatis PRE 80, 046704 (2009). + + Parameters + ---------- + comm : MPI communicator + """ + # Need make a copy to since the elements in psi are only references to + # walker objects in memory. We don't want future changes in a given + # element of psi having unintended consequences. + # todo : add phase to walker for free projection + if comm.rank == 0: + parent_ix = numpy.zeros(len(weights), dtype="i") + else: + parent_ix = numpy.empty(len(weights), dtype="i") + if comm.rank == 0: + total_weight = sum(weights) + cprobs = numpy.cumsum(weights) + r = numpy.random.random() + comb = [ + (i + r) * (total_weight / self.target_weight) for i in range(self.target_weight) + ] + iw = 0 + ic = 0 + while ic < len(comb): + if comb[ic] < cprobs[iw]: + parent_ix[iw] += 1 + ic += 1 + else: + iw += 1 + data = {"ix": parent_ix} + else: + data = None + + data = comm.bcast(data, root=0) + parent_ix = data["ix"] + # Keep total weight saved for capping purposes. + # where returns a tuple (array,), selecting first element. + kill = numpy.where(parent_ix == 0)[0] + clone = numpy.where(parent_ix > 1)[0] + reqs = [] + walker_buffers = [] + # First initiate non-blocking sends of walkers. + comm.barrier() + for i, (c, k) in enumerate(zip(clone, kill)): + # Sending from current processor? + if c // self.nw == comm.rank: + # Location of walker to clone in local list. + clone_pos = c % self.nw + # copying walker data to intermediate buffer to avoid issues + # with accessing walker data during send. Might not be + # necessary. + dest_proc = k // self.nw + # with h5py.File('before_{}.h5'.format(comm.rank), 'a') as fh5: + # fh5['walker_{}_{}_{}'.format(c,k,dest_proc)] = self.walkers[clone_pos].get_buffer() + buff = self.walkers[clone_pos].get_buffer() + reqs.append(comm.Isend(buff, dest=dest_proc, tag=i)) + # Now receive walkers on processors where walkers are to be killed. + for i, (c, k) in enumerate(zip(clone, kill)): + # Receiving to current processor? + if k // self.nw == comm.rank: + # Processor we are receiving from. + source_proc = c // self.nw + # Location of walker to kill in local list of walkers. + kill_pos = k % self.nw + comm.Recv(self.walker_buffer, source=source_proc, tag=i) + # with h5py.File('walkers_recv.h5', 'w') as fh5: + # fh5['walk_{}'.format(k)] = self.walker_buffer.copy() + self.walkers[kill_pos].set_buffer(self.walker_buffer) + # with h5py.File('after_{}.h5'.format(comm.rank), 'a') as fh5: + # fh5['walker_{}_{}_{}'.format(c,k,comm.rank)] = self.walkers[kill_pos].get_buffer() + # Complete non-blocking send. + for rs in reqs: + rs.wait() + # Necessary? + # if len(kill) > 0 or len(clone) > 0: + # sys.exit() + comm.Barrier() + # Reset walker weight. + # TODO: check this. + for w in self.walkers: + w.weight = 1.0 + + def pair_branch(self, comm): + walker_info = [[abs(w.weight), 1, comm.rank, comm.rank] for w in self.walkers] + glob_inf = comm.gather(walker_info, root=0) + # Want same random number seed used on all processors + if comm.rank == 0: + # Rescale weights. + glob_inf = numpy.array([item for sub in glob_inf for item in sub]) + total_weight = sum(w[0] for w in glob_inf) + sort = numpy.argsort(glob_inf[:, 0], kind="mergesort") + isort = numpy.argsort(sort, kind="mergesort") + glob_inf = glob_inf[sort] + s = 0 + e = len(glob_inf) - 1 + tags = [] + isend = 0 + while s < e: + if glob_inf[s][0] < self.min_weight or glob_inf[e][0] > self.max_weight: + # sum of paired walker weights + wab = glob_inf[s][0] + glob_inf[e][0] + r = numpy.random.rand() + if r < glob_inf[e][0] / wab: + # clone large weight walker + glob_inf[e][0] = 0.5 * wab + glob_inf[e][1] = 2 + # Processor we will send duplicated walker to + glob_inf[e][3] = glob_inf[s][2] + send = glob_inf[s][2] + # Kill small weight walker + glob_inf[s][0] = 0.0 + glob_inf[s][1] = 0 + glob_inf[s][3] = glob_inf[e][2] + else: + # clone small weight walker + glob_inf[s][0] = 0.5 * wab + glob_inf[s][1] = 2 + # Processor we will send duplicated walker to + glob_inf[s][3] = glob_inf[e][2] + send = glob_inf[e][2] + # Kill small weight walker + glob_inf[e][0] = 0.0 + glob_inf[e][1] = 0 + glob_inf[e][3] = glob_inf[s][2] + tags.append([send]) + s += 1 + e -= 1 + else: + break + nw = self.nwalkers + glob_inf = glob_inf[isort].reshape((comm.size, nw, 4)) + else: + data = None + total_weight = 0 + data = comm.scatter(glob_inf, root=0) + # Keep total weight saved for capping purposes. + walker_buffers = [] + reqs = [] + for iw, walker in enumerate(data): + if walker[1] > 1: + tag = int(comm.rank * len(walker_info) + walker[3]) + self.walkers[iw].weight = walker[0] + buff = self.walkers[iw].get_buffer() + reqs.append(comm.Isend(buff, dest=int(round(walker[3])), tag=tag)) + for iw, walker in enumerate(data): + if walker[1] == 0: + tag = int(walker[3] * len(walker_info) + comm.rank) + comm.Recv(self.walker_buffer, source=int(round(walker[3])), tag=tag) + self.walkers[iw].set_buffer(self.walker_buffer) + for r in reqs: + r.wait() + + def recompute_greens_function(self, trial, time_slice=None): + for w in self.walkers: + w.greens_function(trial, time_slice) + + def set_total_weight(self, total_weight): + for w in self.walkers: + w.total_weight = total_weight + w.old_total_weight = w.total_weight + + def reset(self, trial): + for w in self.walkers: + w.stack.reset() + w.stack.set_all(trial.dmat) + w.greens_function(trial) + w.weight = 1.0 + w.phase = 1.0 + 0.0j + + def get_write_buffer(self, i): + w = self.walkers[i] + buff = numpy.concatenate([[w.weight], [w.phase], [w.ot], w.phi.ravel()]) + return buff + + def set_walker_from_buffer(self, i, buff): + w = self.walkers[i] + w.weight = buff[0] + w.phase = buff[1] + w.ot = buff[2] + w.phi = buff[3:].reshape(self.walkers[i].phi.shape) + + def write_walkers(self, comm): + start = time.time() + with h5py.File(self.write_file, "r+", driver="mpio", comm=comm) as fh5: + for i, w in enumerate(self.walkers): + ix = i + self.nwalkers * comm.rank + buff = self.get_write_buffer(i) + fh5["walker_%d" % ix][:] = self.get_write_buffer(i) + if comm.rank == 0: + print(" # Writing walkers to file.") + print(f" # Time to write restart: {time.time() - start:13.8e} s") + + def update_log_ovlp(self, comm): + send = numpy.zeros(3, dtype=numpy.complex128) + # Overlap log factor + send[0] = sum(abs(w.ot) for w in self.walkers) + # Det R log factor + send[1] = sum(abs(w.detR) for w in self.walkers) + send[2] = sum(abs(w.log_detR) for w in self.walkers) + global_av = numpy.zeros(3, dtype=numpy.complex128) + comm.Allreduce(send, global_av) + log_shift = numpy.log(global_av[0] / self.ntot_walkers) + detR_shift = numpy.log(global_av[1] / self.ntot_walkers) + log_detR_shift = global_av[2] / self.ntot_walkers + # w.log_shift = -0.5 + n = self.shift_counter + nm1 = self.shift_counter - 1 + for w in self.walkers: + w.log_shift = (w.log_shift * nm1 + log_shift) / n + w.log_detR_shift = (w.log_detR_shift * nm1 + log_detR_shift) / n + w.detR_shift = (w.detR_shift * nm1 + detR_shift) / n + self.shift_counter += 1 + + def read_walkers(self, comm): + with h5py.File(self.read_file, "r") as fh5: + for i, w in enumerate(self.walkers): + try: + ix = i + self.nwalkers * comm.rank + self.set_walker_from_buffer(i, fh5["walker_%d" % ix][:]) + except KeyError: + print(f" # Could not read walker data from: {self.read_file}") diff --git a/ipie/thermal/walkers/stack.py b/ipie/thermal/walkers/stack.py index 3550570d..3fbd38cd 100644 --- a/ipie/thermal/walkers/stack.py +++ b/ipie/thermal/walkers/stack.py @@ -3,6 +3,7 @@ from ipie.utils.misc import get_numeric_names + class PropagatorStack: def __init__( self, diff --git a/ipie/thermal/walkers/thermal.py b/ipie/thermal/walkers/thermal.py new file mode 100644 index 00000000..6b68e101 --- /dev/null +++ b/ipie/thermal/walkers/thermal.py @@ -0,0 +1,734 @@ +import numpy +import scipy.linalg + +from ipie.thermal.estimators.local_energy import local_energy_G +from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number +from ipie.thermal.walkers.stack import PropagatorStack +from ipie.thermal.walkers.walker import Walker +from ipie.utils.misc import get_numeric_names, update_stack + + +class ThermalWalker(Walker): + def __init__(self, system, hamiltonian, trial, walker_opts={}, verbose=False): + Walker.__init__(self, system, hamiltonian, trial, walker_opts=walker_opts) + self.name = "ThermalWalker" + self.num_slices = trial.num_slices + dtype = numpy.complex128 + self.G = numpy.zeros(trial.dmat.shape, dtype=dtype) + self.Ghalf = None + self.nbasis = trial.dmat[0].shape[0] + self.stack_size = walker_opts.get("stack_size", None) + max_diff_diag = numpy.linalg.norm((numpy.diag(trial.dmat[0].diagonal()) - trial.dmat[0])) + if max_diff_diag < 1e-10: + self.diagonal_trial = True + if verbose: + print("# Trial density matrix is diagonal.") + else: + self.diagonal_trial = False + if verbose: + print("# Trial density matrix is not diagonal.") + + if self.stack_size == None: + self.stack_size = trial.stack_size + if (self.num_slices // self.stack_size) * self.stack_size != self.num_slices: + if verbose: + print("# Input stack size does not divide number of slices.") + self.stack_size = update_stack(self.stack_size, self.num_slices, verbose) + if self.stack_size > trial.stack_size: + if verbose: + print( + "# Walker stack size differs from that estimated from " "trial density matrix." + ) + print(f"# Be careful. cond(BT)**stack_size: {trial.cond ** self.stack_size:10.3e}.") + self.stack_length = self.num_slices // self.stack_size + if verbose: + print(f"# Walker stack size: {self.stack_size}") + + self.lowrank = walker_opts.get("low_rank", False) + self.lowrank_thresh = walker_opts.get("low_rank_thresh", 1e-6) + if verbose: + print(f"# Using low rank trick: {self.lowrank}") + self.stack = PropagatorStack( + self.stack_size, + trial.num_slices, + trial.dmat.shape[-1], + dtype, + trial.dmat, + trial.dmat_inv, + diagonal=self.diagonal_trial, + lowrank=self.lowrank, + thresh=self.lowrank_thresh, + ) + + # Initialise all propagators to the trial density matrix. + self.stack.set_all(trial.dmat) + self.greens_function_qr_strat(trial) + self.stack.G = self.G + self.M0 = numpy.array( + [ + scipy.linalg.det(self.G[0], check_finite=False), + scipy.linalg.det(self.G[1], check_finite=False), + ] + ) + self.stack.ovlp = numpy.array([1.0 / self.M0[0], 1.0 / self.M0[1]]) + + # # temporary storage for stacks... + I = numpy.identity(hamiltonian.nbasis, dtype=dtype) + One = numpy.ones(hamiltonian.nbasis, dtype=dtype) + self.Tl = numpy.array([I, I]) + self.Ql = numpy.array([I, I]) + self.Dl = numpy.array([One, One]) + self.Tr = numpy.array([I, I]) + self.Qr = numpy.array([I, I]) + self.Dr = numpy.array([One, One]) + + self.hybrid_energy = 0.0 + if verbose: + # def local_energy(self, system, two_rdm=None): + P = one_rdm_from_G(self.G) + eloc = local_energy_G(system, hamiltonian, self, P) + nav = particle_number(P) + print("# Initial walker energy: {} {} {}".format(*eloc)) + print(f"# Initial walker electron number: {nav}") + # self.buff_names = ['weight', 'G', 'unscaled_weight', 'phase', 'Tl', + # 'Ql', 'Dl', 'Tr', 'Qr', 'Dr', 'M0'] + self.buff_names, self.buff_size = get_numeric_names(self.__dict__) + # self.buff_size = (self.G.size+3+self.Tl.size+2+ + # self.Ql.size+self.Dl.size+self.Tr.size+self.Qr.size + # +self.Dr.size) + + def greens_function(self, trial, slice_ix=None, inplace=True): + if self.lowrank: + return self.stack.G + else: + return self.greens_function_qr_strat(trial, slice_ix=slice_ix, inplace=inplace) + + def greens_function_svd(self, trial, slice_ix=None, inplace=True): + if slice_ix == None: + slice_ix = self.stack.time_slice + bin_ix = slice_ix // self.stack.stack_size + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + if inplace: + G = None + else: + G = numpy.zeros(self.G.shape, self.G.dtype) + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} + # in stable way. Iteratively construct SVD decompositions starting + # from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + (U1, S1, V1) = scipy.linalg.svd(B[spin]) + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + T1 = numpy.dot(B[spin], U1) + # todo optimise + T2 = numpy.dot(T1, numpy.diag(S1)) + (U1, S1, V) = scipy.linalg.svd(T2) + V1 = numpy.dot(V, V1) + A = numpy.dot(U1.dot(numpy.diag(S1)), V1) + # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. + # Care needs to be taken when adding the identity matrix. + T3 = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) + (U2, S2, V2) = scipy.linalg.svd(T3) + U3 = numpy.dot(U1, U2) + D3 = numpy.diag(1.0 / S2) + V3 = numpy.dot(V2, V1) + # G(l) = (U3 S2 V3)^{-1} + # = V3^{\dagger} D3 U3^{\dagger} + if inplace: + # self.G[spin] = (V3inv).dot(U3.conj().T) + self.G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) + else: + # G[spin] = (V3inv).dot(U3.conj().T) + G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) + return G + + def greens_function_qr(self, trial, slice_ix=None, inplace=True): + if slice_ix == None: + slice_ix = self.stack.time_slice + + bin_ix = slice_ix // self.stack.stack_size + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} + # in stable way. Iteratively construct SVD decompositions starting + # from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + (U1, V1) = scipy.linalg.qr(B[spin], pivoting=False, check_finite=False) + + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + T1 = numpy.dot(B[spin], U1) + (U1, V) = scipy.linalg.qr(T1, pivoting=False, check_finite=False) + V1 = numpy.dot(V, V1) + + # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. + # Care needs to be taken when adding the identity matrix. + V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0])) + + T3 = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0]) + (U2, V2) = scipy.linalg.qr(T3, pivoting=False, check_finite=False) + + U3 = numpy.dot(U1, U2) + V3 = numpy.dot(V2, V1) + V3inv = scipy.linalg.solve_triangular(V3, numpy.identity(V3.shape[0])) + # G(l) = (U3 S2 V3)^{-1} + # = V3^{\dagger} D3 U3^{\dagger} + if inplace: + self.G[spin] = (V3inv).dot(U3.conj().T) + else: + G[spin] = (V3inv).dot(U3.conj().T) + return G + + def compute_left_right(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # right bit + # B(right) ... B(1) + if center_ix > 0: + # print ("center_ix > 0") + B = self.stack.get(0) + (self.Qr[spin], R1, P1) = scipy.linalg.qr( + B[spin], pivoting=True, check_finite=False + ) + # Form D matrices + self.Dr[spin] = R1.diagonal() + D1inv = 1.0 / R1.diagonal() + self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) + # now permute them + self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] + + for ix in range(1, center_ix): + B = self.stack.get(ix) + C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) + (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = 1.0 / R1.diagonal() + self.Dr[spin] = R1.diagonal() + # smarter permutation + # D^{-1} * R + tmp = numpy.einsum("i,ij->ij", D1inv, R1) + # D^{-1} * R * P^T + tmp[:, P1] = tmp[:, range(self.nbasis)] + # D^{-1} * R * P^T * T + self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) + + # left bit + # B(l) ... B(left) + if center_ix < self.stack.nbins - 1: + # print("center_ix < self.stack.nbins-1 first") + # We will assume that B matrices are all diagonal for left.... + B = self.stack.get(center_ix + 1) + self.Dl[spin] = B[spin].diagonal() + D1inv = 1.0 / B[spin].diagonal() + self.Ql[spin] = numpy.identity(B[spin].shape[0]) + self.Tl[spin] = numpy.identity(B[spin].shape[0]) + + for ix in range(center_ix + 2, self.stack.nbins): + # print("center_ix < self.stack.nbins-1 first inner loop") + B = self.stack.get(ix) + C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) + self.Dl[spin] = C2 + + def compute_right(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # right bit + # B(right) ... B(1) + if center_ix > 0: + # print ("center_ix > 0") + B = self.stack.get(0) + (self.Qr[spin], R1, P1) = scipy.linalg.qr( + B[spin], pivoting=True, check_finite=False + ) + # Form D matrices + self.Dr[spin] = R1.diagonal() + D1inv = 1.0 / R1.diagonal() + self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) + # now permute them + self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] + + for ix in range(1, center_ix): + B = self.stack.get(ix) + C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) + (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = 1.0 / R1.diagonal() + self.Dr[spin] = R1.diagonal() + # smarter permutation + # D^{-1} * R + tmp = numpy.einsum("i,ij->ij", D1inv, R1) + # D^{-1} * R * P^T + tmp[:, P1] = tmp[:, range(self.nbasis)] + # D^{-1} * R * P^T * T + self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) + + def compute_left(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # left bit + # B(l) ... B(left) + if center_ix < self.stack.nbins - 1: + # print("center_ix < self.stack.nbins-1 first") + # We will assume that B matrices are all diagonal for left.... + B = self.stack.get(center_ix + 1) + self.Dl[spin] = B[spin].diagonal() + self.Ql[spin] = numpy.identity(B[spin].shape[0]) + self.Tl[spin] = numpy.identity(B[spin].shape[0]) + + for ix in range(center_ix + 2, self.stack.nbins): + # print("center_ix < self.stack.nbins-1 first inner loop") + B = self.stack.get(ix) + C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) + self.Dl[spin] = C2.diagonal() + + def greens_function_left_right(self, center_ix, inplace=False, thresh=1e-6): + assert self.diagonal_trial + + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + mL = self.G.shape[1] + mR = self.G.shape[1] + mT = self.G.shape[1] + + Bc = self.stack.get(center_ix) + + nbsf = Bc.shape[1] + + # It goes to right to left and we sample (I + L*B*R) in the end + for spin in [0, 1]: + if center_ix > 0: # there exists right bit + mR = len(self.Dr[spin][numpy.abs(self.Dr[spin]) > thresh]) + + Ccr = numpy.einsum( + "ij,j->ij", + numpy.dot(Bc[spin], self.Qr[spin][:, :mR]), + self.Dr[spin][:mR], + ) # N x mR + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) + Dlcr = Rlcr[:mR, :mR].diagonal() # mR + Dinv = 1.0 / Dlcr # mR + tmp = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :mR]) # mR, mR x mR -> mR x mR + tmp[:, Plcr] = tmp[:, range(mR)] + Tlcr = numpy.dot(tmp, self.Tr[spin][:mR, :]) # mR x N + else: + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) + # Form D matrices + Dlcr = Rlcr.diagonal() + + mR = len(Dlcr[numpy.abs(Dlcr) > thresh]) + + Dinv = 1.0 / Rlcr.diagonal() + Tlcr = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :]) # mR x N + Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] # mR x N + + if center_ix < self.stack.nbins - 1: # there exists left bit + # assume left stack is all diagonal (i.e., QDT = diagonal -> Q and T are identity) + Clcr = numpy.einsum( + "i,ij->ij", + self.Dl[spin], + numpy.einsum("ij,j->ij", Qlcr[:, :mR], Dlcr[:mR]), + ) # N x mR + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr( + Clcr, pivoting=True, check_finite=False + ) # N x N, mR x mR + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Dlcr + + mT = len(Dlcr[numpy.abs(Dlcr) > thresh]) + + tmp = numpy.einsum("i,ij->ij", Dinv[:mT], Rlcr[:mT, :]) + tmp[:, Plcr] = tmp[:, range(mR)] # mT x mR + Tlcr = numpy.dot(tmp, Tlcr) # mT x N + else: + mT = mR + + # D = Ds Db^{-1} + Db = numpy.zeros(mT, Bc[spin].dtype) + Ds = numpy.zeros(mT, Bc[spin].dtype) + for i in range(mT): + absDlcr = abs(Dlcr[i]) + if absDlcr > 1.0: + Db[i] = 1.0 / absDlcr + Ds[i] = numpy.sign(Dlcr[i]) + else: + Db[i] = 1.0 + Ds[i] = Dlcr[i] + + if mT == nbsf: # No need for Woodbury + T1inv = scipy.linalg.inv(Tlcr, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), + numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), + ) + # return # This seems to change the answer WHY?? + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), + numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), + ) + else: # Use Woodbury + TQ = Tlcr.dot(Qlcr[:, :mT]) + TQinv = scipy.linalg.inv(TQ, check_finite=False) + tmp = scipy.linalg.inv( + numpy.einsum("ij,j->ij", TQinv, Db) + numpy.diag(Ds), + check_finite=False, + ) + A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv)) + if inplace: + self.G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( + numpy.diag(Dlcr[:mT]) + ).dot(A).dot(Tlcr) + else: + G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( + numpy.diag(Dlcr[:mT]) + ).dot(A).dot(Tlcr) + # print(mR,mT,nbsf) + # print("ref: mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) + return G + + def greens_function_left_right_no_truncation(self, center_ix, inplace=False): + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + Bc = self.stack.get(center_ix) + for spin in [0, 1]: + if center_ix > 0: # there exists right bit + # print("center_ix > 0 second") + Ccr = numpy.einsum("ij,j->ij", numpy.dot(Bc[spin], self.Qr[spin]), self.Dr[spin]) + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) + tmp[:, Plcr] = tmp[:, range(self.nbasis)] + Tlcr = numpy.dot(tmp, self.Tr[spin]) + else: + # print("center_ix > 0 else second") + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) + # Form D matrices + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + Tlcr = numpy.einsum("i,ij->ij", Dinv, Rlcr) + Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] + + if center_ix < self.stack.nbins - 1: # there exists left bit + # print("center_ix < self.stack.nbins-1 second") + # assume left stack is all diagonal + Clcr = numpy.einsum("i,ij->ij", self.Dl[spin], numpy.einsum("ij,j->ij", Qlcr, Dlcr)) + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Clcr, pivoting=True, check_finite=False) + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + + tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) + tmp[:, Plcr] = tmp[:, range(self.nbasis)] + Tlcr = numpy.dot(tmp, Tlcr) + + # print("Dlcr = {}".format(Dlcr)) + + # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T + # Write D = Db^{-1} Ds + # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T + Db = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) + Ds = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) + for i in range(Db.shape[0]): + absDlcr = abs(Dlcr[i]) + if absDlcr > 1.0: + Db[i] = 1.0 / absDlcr + Ds[i] = numpy.sign(Dlcr[i]) + else: + Db[i] = 1.0 + Ds[i] = Dlcr[i] + + T1inv = scipy.linalg.inv(Tlcr, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) + ) + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) + ) + return G + + def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + if slice_ix == None: + slice_ix = self.stack.time_slice + + bin_ix = slice_ix // self.stack.stack_size + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in + # stable way. Iteratively construct column pivoted QR decompositions + # (A = QDT) starting from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + + (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) + # Form D matrices + D1 = numpy.diag(R1.diagonal()) + D1inv = numpy.diag(1.0 / R1.diagonal()) + T1 = numpy.einsum("ii,ij->ij", D1inv, R1) + # permute them + T1[:, P1] = T1[:, range(self.nbasis)] + + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) + (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = numpy.diag(1.0 / R1.diagonal()) + D1 = numpy.diag(R1.diagonal()) + tmp = numpy.einsum("ii,ij->ij", D1inv, R1) + tmp[:, P1] = tmp[:, range(self.nbasis)] + T1 = numpy.dot(tmp, T1) + + # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T + # Write D = Db^{-1} Ds + # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T + Db = numpy.zeros(B[spin].shape, B[spin].dtype) + Ds = numpy.zeros(B[spin].shape, B[spin].dtype) + for i in range(Db.shape[0]): + absDlcr = abs(Db[i, i]) + if absDlcr > 1.0: + Db[i, i] = 1.0 / absDlcr + Ds[i, i] = numpy.sign(D1[i, i]) + else: + Db[i, i] = 1.0 + Ds[i, i] = D1[i, i] + + T1inv = scipy.linalg.inv(T1, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("ii,ij->ij", Db, Q1.conj().T), T1inv) + Ds + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) + ) + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) + ) + return G + + +# def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): +# def local_energy(self, system, two_rdm=None): +# rdm = one_rdm_from_G(self.G) +# return local_energy_G(system, hamiltonian, self, rdm) + + +def unit_test(): + from ipie.thermal.system.ueg import UEG + from ipie.thermal.propagation.planewave import PlaneWave + from ipie.thermal.trial.onebody import OneBody + from ipie.thermal.qmc.options import QMCOpts + + inputs = { + "nup": 1, + "ndown": 1, + "rs": 1.0, + "ecut": 0.5, + "name": "one_body", + "mu": 1.94046021, + "beta": 0.5, + "dt": 0.05, + "optimised": True, + } + beta = inputs["beta"] + dt = inputs["dt"] + + system = UEG(inputs, verbose=False) + + qmc = QMCOpts(inputs, system, True) + trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False) + + walker = ThermalWalker(inputs, system, trial, True) + # walker.greens_function(trial) + E, T, V = walker.local_energy(system) + numpy.random.seed(0) + inputs["optimised"] = False + propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) + + propagator.propagate_walker_free(system, walker, trial, False) + + Gold = walker.G[0].copy() + + system = UEG(inputs, verbose=False) + + qmc = QMCOpts(inputs, system, verbose=False) + trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False) + + propagator = PlaneWave(inputs, qmc, system, trial, True) + walker = ThermalWalker(inputs, system, trial, verbose=False) + # walker.greens_function(trial) + E, T, V = walker.local_energy(system) + numpy.random.seed(0) + inputs["optimised"] = True + propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) + + propagator.propagate_walker_free(system, walker, trial, False) + + Gnew = walker.G[0].copy() + + assert scipy.linalg.norm(Gold[:, 0] - Gnew[:, 0]) < 1e-10 + + inputs["stack_size"] = 1 + walker = ThermalWalker(inputs, system, trial, verbose=False) + numpy.random.seed(0) + propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) + for i in range(0, 5): + propagator.propagate_walker(system, walker, trial) + Gs1 = walker.G[0].copy() + for ts in range(walker.stack_length): + walker.greens_function(trial, slice_ix=ts * walker.stack_size) + E, T, V = walker.local_energy(system) + # print(E) + + inputs["stack_size"] = 5 + walker = ThermalWalker(inputs, system, trial, verbose=False) + numpy.random.seed(0) + propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) + for i in range(0, 5): + propagator.propagate_walker(system, walker, trial) + Gs5 = walker.G[0].copy() + for ts in range(walker.stack_length): + walker.greens_function(trial, slice_ix=ts * walker.stack_size) + E, T, V = walker.local_energy(system) + # print(E) + assert numpy.linalg.norm(Gs1 - Gs5) < 1e-10 + + N = 5 + A = numpy.random.rand(N, N) + Q, R, P = scipy.linalg.qr(A, pivoting=True) + + #### test permutation start + # Pmat = numpy.zeros((N,N)) + # for i in range (N): + # Pmat[P[i],i] = 1 + # print(P) + # tmp = Q.dot(R)#.dot(Pmat.T) + # print(tmp) + # print("==================") + # tmp2 = tmp.dot(Pmat.T) + # print(tmp2) + # print("==================") + # tmp[:,P] = tmp [:,range(N)] + # print(tmp) + #### test permutation end + + B = numpy.random.rand(N, N) + (Q1, R1, P1) = scipy.linalg.qr(B, pivoting=True, check_finite=False) + # Form permutation matrix + P1mat = numpy.zeros(B.shape, B.dtype) + P1mat[P1, range(len(P1))] = 1.0 + # Form D matrices + D1 = numpy.diag(R1.diagonal()) + D1inv = numpy.diag(1.0 / R1.diagonal()) + T1 = numpy.dot(numpy.dot(D1inv, R1), P1mat.T) + + assert numpy.linalg.norm(B - numpy.einsum("ij,jj->ij", Q1, D1).dot(T1)) < 1e-10 + + # tmp[:,:] = tmp[:,P] + # print(A - tmp) + # print(Q * Q.T) + # print(R) + + # Test walker green's function. + from ipie.thermal.estimators.hubbard import local_energy_hubbard + from ipie.thermal.estimators.thermal import one_rdm_from_G + from ipie.thermal.hamiltonians.hubbard import Hubbard + + sys_dict = { + "name": "Hubbard", + "nx": 4, + "ny": 4, + "nup": 7, + "ndown": 7, + "U": 4, + "t": 1, + } + system = Hubbard(sys_dict) + beta = 4 + mu = 1 + trial = OneBody({"mu": mu}, system, beta, dt, verbose=True) + + dt = 0.05 + num_slices = int(beta / dt) + + eref = 0 + for ek in system.eks: + eref += 2 * ek * 1.0 / (numpy.exp(beta * (ek - mu)) + 1) + walker = ThermalWalker({"stack_size": 1}, system, trial) + Gs1 = walker.G[0].copy() + rdm = one_rdm_from_G(walker.G) + ekin = local_energy_hubbard(system, rdm)[1] + try: + assert abs(eref - ekin) < 1e-8 + except AssertionError: + print(f"Error in kinetic energy check. Ref: {eref:13.8e} Calc:{ekin:13.8e}") + walker = ThermalWalker({"stack_size": 10}, system, trial) + rdm = one_rdm_from_G(walker.G) + ekin = local_energy_hubbard(system, rdm)[1] + try: + assert abs(eref - ekin) < 1e-8 + except AssertionError: + print( + "Error in kinetic energy check. Ref: %13.10e Calc: %13.10e" + " Error: %13.8e" % (eref.real, ekin.real, abs(eref - ekin)) + ) + for ts in range(walker.stack_length): + walker.greens_function(trial, slice_ix=ts * walker.stack_size) + assert numpy.linalg.norm(Gs1 - walker.G[0]) < 1e-10 + + +if __name__ == "__main__": + unit_test() diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index 1a512ab7..b1d357fc 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -1,14 +1,10 @@ -import cmath -import copy - import numpy import scipy.linalg -from ipie.legacy.estimators.local_energy import local_energy_G -from ipie.legacy.estimators.thermal import greens_function, one_rdm_from_G, particle_number -from ipie.legacy.walkers.stack import PropagatorStack -from ipie.legacy.walkers.walker import Walker -from ipie.utils.linalg import regularise_matrix_inverse +from ipie.thermal.estimators.local_energy import local_energy_G +from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number +from ipie.thermal.walkers.stack import PropagatorStack +from ipie.thermal.walkers.walker import Walker from ipie.utils.misc import get_numeric_names, update_stack @@ -688,7 +684,7 @@ def unit_test(): # Test walker green's function. from ipie.legacy.estimators.hubbard import local_energy_hubbard - from ipie.legacy.estimators.thermal import greens_function, one_rdm_from_G + from ipie.legacy.estimators.thermal import one_rdm_from_G from ipie.legacy.hamiltonians.hubbard import Hubbard sys_dict = { diff --git a/ipie/thermal/walkers/walker.py b/ipie/thermal/walkers/walker.py new file mode 100644 index 00000000..60ad312e --- /dev/null +++ b/ipie/thermal/walkers/walker.py @@ -0,0 +1,135 @@ +import numpy + +class Walker(object): + """Walker base class. + + Parameters + ---------- + system : object + System object. + trial : object + Trial wavefunction object. + options : dict + Input options + index : int + Element of trial wavefunction to initalise walker to. + nprop_tot : int + Number of back propagation steps (including imaginary time correlation + functions.) + nbp : int + Number of back propagation steps. + """ + + def __init__( + self, + system, + hamiltonian, + trial, + walker_opts={}, + index=0, + nprop_tot=None, + nbp=None, + ): + self.weight = walker_opts.get("weight", 1.0) + self.unscaled_weight = self.weight + self.phase = 1 + 0j + self.alive = 1 + self.phi = numpy.array(trial.init.copy(), dtype=numpy.complex128) + self.nup = system.nup + self.ndown = system.ndown + self.total_weight = 0.0 + self.ot = 1.0 + self.ovlp = 1.0 + # self.E_L = local_energy(system, self.G, self.Gmod, trail._rchol)[0].real + self.E_L = 0.0 + self.eloc = 0.0 + # walkers overlap at time tau before backpropagation occurs + self.ot_bp = 1.0 + # walkers weight at time tau before backpropagation occurs + self.weight_bp = self.weight + # Historic wavefunction for back propagation. + self.phi_old = self.phi.copy() + self.hybrid_energy = 0.0 + # Historic wavefunction for ITCF. + self.phi_right = self.phi.copy() + self.weights = numpy.array( + [1.0] + ) # This is going to be for MSD trial... (should be named a lot better than this) + self.detR = 1.0 + self.detR_shift = 0.0 + self.log_detR = 0.0 + self.log_shift = 0.0 + self.log_detR_shift = 0.0 + # Number of propagators to store for back propagation / ITCF. + self.field_configs = None + self.stack = None + + def get_buffer(self): + """Get walker buffer for MPI communication + + Returns + ------- + buff : dict + Relevant walker information for population control. + """ + s = 0 + buff = numpy.zeros(self.buff_size, dtype=numpy.complex128) + for d in self.buff_names: + data = self.__dict__[d] + if isinstance(data, (numpy.ndarray)): + buff[s : s + data.size] = data.ravel() + s += data.size + elif isinstance(data, list): + for l in data: + if isinstance(l, (numpy.ndarray)): + buff[s : s + l.size] = l.ravel() + s += l.size + elif isinstance(l, (int, float, complex)): + buff[s : s + 1] = l + s += 1 + else: + buff[s : s + 1] = data + s += 1 + if self.field_configs is not None: + stack_buff = self.field_configs.get_buffer() + return numpy.concatenate((buff, stack_buff)) + elif self.stack is not None: + stack_buff = self.stack.get_buffer() + return numpy.concatenate((buff, stack_buff)) + else: + return buff + + def set_buffer(self, buff): + """Set walker buffer following MPI communication + + Parameters + ------- + buff : dict + Relevant walker information for population control. + """ + s = 0 + for d in self.buff_names: + data = self.__dict__[d] + if isinstance(data, numpy.ndarray): + self.__dict__[d] = buff[s : s + data.size].reshape(data.shape).copy() + s += data.size + elif isinstance(data, list): + for ix, l in enumerate(data): + if isinstance(l, (numpy.ndarray)): + self.__dict__[d][ix] = buff[s : s + l.size].reshape(l.shape).copy() + s += l.size + elif isinstance(l, (int, float, complex)): + self.__dict__[d][ix] = buff[s] + s += 1 + else: + if isinstance(self.__dict__[d], int): + self.__dict__[d] = int(buff[s].real) + elif isinstance(self.__dict__[d], float): + self.__dict__[d] = buff[s].real + else: + self.__dict__[d] = buff[s] + s += 1 + if self.field_configs is not None: + self.field_configs.set_buffer(buff[self.buff_size :]) + if self.stack is not None: + self.stack.set_buffer(buff[self.buff_size :]) diff --git a/setup.py b/setup.py index d67e8eb0..33c5b757 100644 --- a/setup.py +++ b/setup.py @@ -22,6 +22,12 @@ extra_compile_args=["-O3"], include_dirs=[numpy.get_include()], ), + Extension( + "ipie.thermal.estimators.ueg_kernels", + ["ipie/thermal/estimators/ueg_kernels.pyx"], + extra_compile_args=["-O3"], + include_dirs=[numpy.get_include()], + ), ] cythonized_extension = cythonize( extensions, From 8919abf50c2c8eb0603b23927e7b1f9645342df6 Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Wed, 30 Aug 2023 11:01:49 -0400 Subject: [PATCH 08/84] removing hubbard-related routines in ft-afqmc --- ipie/thermal/hamiltonians/hubbard.py | 400 ----------------- ipie/thermal/hamiltonians/utils.py | 5 +- ipie/thermal/propagation/continuous.py | 5 - ipie/thermal/propagation/hubbard.py | 271 ------------ ipie/thermal/propagation/utils.py | 61 +-- ipie/thermal/system/hubbard_holstein.py | 505 ---------------------- ipie/thermal/tests/test_ft_integration.py | 2 +- 7 files changed, 21 insertions(+), 1228 deletions(-) delete mode 100644 ipie/thermal/hamiltonians/hubbard.py delete mode 100644 ipie/thermal/propagation/hubbard.py delete mode 100644 ipie/thermal/system/hubbard_holstein.py diff --git a/ipie/thermal/hamiltonians/hubbard.py b/ipie/thermal/hamiltonians/hubbard.py deleted file mode 100644 index a5cb638d..00000000 --- a/ipie/thermal/hamiltonians/hubbard.py +++ /dev/null @@ -1,400 +0,0 @@ -"""Hubbard model specific classes and methods""" - -from math import cos, pi - -import numpy -import scipy.linalg - -from ipie.thermal.system.hubbard_holstein import kinetic -from ipie.utils.io import fcidump_header - - -class Hubbard(object): - """Hubbard model system class. - - 1 and 2 case with nearest neighbour hopping. - - Parameters - ---------- - options : dict - dictionary of system input options. - - Attributes - ---------- - t : float - Hopping parameter. - U : float - Hubbard U interaction strength. - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - nbasis : int - Number of single-particle basis functions. - T : numpy.array - Hopping matrix - gamma : numpy.array - Super matrix (not currently implemented). - """ - - def __init__(self, options, verbose=False): - if verbose: - print("# Parsing input options.") - # for backward compatibility - self.mixed_precision = False - self.chunked = False - self.t = options.get("t", 1.0) - self.U = options["U"] - self.nx = options["nx"] - self.ny = options["ny"] - self.ktwist = numpy.array(options.get("ktwist")) - self.control_variate = False - self.symmetric = options.get("symmetric", False) - self.sparse = False - if self.symmetric: - # An unusual convention for the sign of the chemical potential is - # used in Phys. Rev. B 99, 045108 (2018) - # Symmetric uses the symmetric form of the hubbard model and will - # also change the sign of the chemical potential in the density - # matrix. - self._alt_convention = True - else: - self._alt_convention = False - - self.ypbc = options.get("ypbc", True) - self.xpbc = options.get("xpbc", True) - - self.nbasis = self.nx * self.ny - self.nactive = self.nbasis - self.nfv = 0 - self.ncore = 0 - (self.kpoints, self.kc, self.eks) = kpoints(self.t, self.nx, self.ny) - self.pinning = options.get("pinning_fields", False) - self._opt = True - if verbose: - print("# Setting up one-body operator.") - if self.pinning: - if verbose: - print("# Using pinning field.") - self.T = kinetic_pinning_alt(self.t, self.nbasis, self.nx, self.ny) - else: - self.T = kinetic( - self.t, - self.nbasis, - self.nx, - self.ny, - self.ktwist, - xpbc=self.xpbc, - ypbc=self.ypbc, - ) - self.H1 = self.T - self.Text = scipy.linalg.block_diag(self.T[0], self.T[1]) - self.P = transform_matrix(self.nbasis, self.kpoints, self.kc, self.nx, self.ny) - self.mu = options.get("mu", None) - # For interface consistency. - self.ecore = 0.0 - # Number of field configurations per walker. - self.nfields = self.nbasis - self.name = "Hubbard" - if verbose: - print("# Finished setting up Hubbard system object.") - # "Volume" to define density. - self.vol = self.nx * self.ny - self.construct_h1e_mod() - self.control_variate = False - - def fcidump(self, nup, ndown, to_string=False): - """Dump 1- and 2-electron integrals to file. - - Parameters - ---------- - to_string : bool - Return fcidump as string. Default print to stdout. - """ - header = fcidump_header(nup + ndown, self.nbasis, nup - ndown) - for i in range(1, self.nbasis + 1): - if self.T.dtype == complex: - fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" - line = fmt.format(self.U.real, self.U.imag, i, i, i, i) - else: - fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" - line = fmt.format(self.U, i, i, i, i) - header += line - for i in range(0, self.nbasis): - for j in range(i + 1, self.nbasis): - integral = self.T[0][i, j] - if abs(integral) > 1e-8: - if self.T.dtype == complex: - fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" - line = fmt.format(integral.real, integral.imag, i + 1, j + 1, 0, 0) - else: - fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" - line = fmt.format(integral, i + 1, j + 1, 0, 0) - header += line - if self.T.dtype == complex: - fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" - header += fmt.format(0, 0, 0, 0, 0, 0) - else: - fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" - header += fmt.format(0, 0, 0, 0, 0) - if to_string: - print(header) - else: - return header - - def construct_h1e_mod(self): - # Subtract one-body bit following reordering of 2-body operators. - # Eqn (17) of [Motta17]_ - if not self.symmetric: - v0 = 0.5 * self.U * numpy.eye(self.nbasis) - self.h1e_mod = numpy.array([self.H1[0] - v0, self.H1[1] - v0]) - else: - self.h1e_mod = self.H1 - - def hijkl(self, i, j, k, l): - # (ik|jl) - if i == j == k == l: - return self.U - else: - return 0.0 - - -def transform_matrix(nbasis, kpoints, kc, nx, ny): - U = numpy.zeros(shape=(nbasis, nbasis), dtype=complex) - for i, k_i in enumerate(kpoints): - for j in range(0, nbasis): - r_j = decode_basis(nx, ny, j) - U[i, j] = numpy.exp(1j * numpy.dot(kc * k_i, r_j)) - - return U - - -def kinetic_pinning(t, nbasis, nx, ny): - r"""Kinetic part of the Hamiltonian in our one-electron basis. - - Adds pinning fields as outlined in [Qin16]_. This forces periodic boundary - conditions along x and open boundary conditions along y. Pinning fields are - applied in the y direction as: - - .. math:: - \nu_{i\uparrow} = -\nu_{i\downarrow} = (-1)^{i_x+i_y}\nu_0, - - for :math:`i_y=1,L_y` and :math:`\nu_0=t/4`. - - Parameters - ---------- - t : float - Hopping parameter - nbasis : int - Number of one-electron basis functions. - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - - Returns - ------- - T : numpy.array - Hopping Hamiltonian matrix. - """ - - Tup = numpy.zeros((nbasis, nbasis)) - Tdown = numpy.zeros((nbasis, nbasis)) - nu0 = 0.25 * t - - for i in range(0, nbasis): - # pinning field along y. - xy1 = decode_basis(nx, ny, i) - if xy1[1] == 0 or xy1[1] == ny - 1: - Tup[i, i] += (-1.0) ** (xy1[0] + xy1[1]) * nu0 - Tdown[i, i] += (-1.0) ** (xy1[0] + xy1[1] + 1) * nu0 - for j in range(i + 1, nbasis): - xy2 = decode_basis(nx, ny, j) - dij = abs(xy1 - xy2) - if sum(dij) == 1: - Tup[i, j] = Tdown[i, j] = -t - # periodic bcs in x. - if (dij == [nx - 1, 0]).all(): - Tup[i, j] += -t - Tdown[i, j] += -t - - return numpy.array([Tup + numpy.triu(Tup, 1).T, Tdown + numpy.triu(Tdown, 1).T]) - - -def kinetic_pinning_alt(t, nbasis, nx, ny): - r"""Kinetic part of the Hamiltonian in our one-electron basis. - - Adds pinning fields as outlined in [Qin16]_. This forces periodic boundary - conditions along x and open boundary conditions along y. Pinning fields are - applied in the y direction as: - - .. math:: - \nu_{i\uparrow} = -\nu_{i\downarrow} = (-1)^{i_x+i_y}\nu_0, - - for :math:`i_y=1,L_y` and :math:`\nu_0=t/4`. - - Parameters - ---------- - t : float - Hopping parameter - nbasis : int - Number of one-electron basis functions. - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - - Returns - ------- - T : numpy.array - Hopping Hamiltonian matrix. - """ - - Tup = numpy.zeros((nbasis, nbasis)) - Tdown = numpy.zeros((nbasis, nbasis)) - h = 0.1 * t - - for i in range(0, nbasis): - # pinning field along y direction when i_x = 0. - xy1 = decode_basis(nx, ny, i) - if xy1[0] == 0: - Tup[i, i] += (-1.0) ** (xy1[1]) * h - Tdown[i, i] += (-1.0) ** (xy1[1] + 1) * h - for j in range(i + 1, nbasis): - xy2 = decode_basis(nx, ny, j) - dij = abs(xy1 - xy2) - if sum(dij) == 1: - Tup[i, j] = Tdown[i, j] = -t - # periodic bcs in y. - if (dij == [0, ny - 1]).all(): - Tup[i, j] += -t - Tdown[i, j] += -t - - return numpy.array([Tup + numpy.triu(Tup, 1).T, Tdown + numpy.triu(Tdown, 1).T]) - - -def decode_basis(nx, ny, i): - """Return cartesian lattice coordinates from basis index. - - Consider a 3x3 lattice then we index lattice sites like:: - - (0,2) (1,2) (2,2) 6 7 8 - (0,1) (1,1) (2,1) -> 3 4 5 - (0,0) (1,0) (2,0) 0 1 2 - - i.e., i = i_x + n_x * i_y, and i_x = i%n_x, i_y = i//nx. - - Parameters - ---------- - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - i : int - Basis index (same for up and down spins). - """ - if ny == 1: - return numpy.array([i % nx]) - else: - return numpy.array([i % nx, i // nx]) - - -def encode_basis(i, j, nx): - """Encode 2d index to one dimensional index. - - See decode basis for layout. - - Parameters - ---------- - i : int - x coordinate. - j : int - y coordinate - nx : int - Number of x lattice sites. - - Returns - ------- - ix : int - basis index. - """ - return i + j * nx - - -def _super_matrix(U, nbasis): - """Construct super-matrix from v_{ijkl}""" - - -def kpoints(t, nx, ny): - """Construct kpoints for system. - - Parameters - ---------- - t : float - Hopping amplitude. - nx : int - Number of x lattice sites. - nx : int - Number of y lattice sites. - - Returns - ------- - kp : numpy array - System kpoints Note these are not sorted according to eigenvalue energy - but rather so as to conform with numpys default kpoint indexing for FFTs. - kfac : float - Kpoint scaling factor (2pi/L). - eigs : numpy array - Single particle eigenvalues associated with kp. - """ - kp = [] - eigs = [] - if ny == 1: - kfac = numpy.array([2.0 * pi / nx]) - for n in range(0, nx): - kp.append(numpy.array([n])) - eigs.append(ek(t, n, kfac, ny)) - else: - kfac = numpy.array([2.0 * pi / nx, 2.0 * pi / ny]) - for n in range(0, nx): - for m in range(0, ny): - k = numpy.array([n, m]) - kp.append(k) - eigs.append(ek(t, k, kfac, ny)) - - eigs = numpy.array(eigs) - kp = numpy.array(kp) - return (kp, kfac, eigs) - - -def ek(t, k, kc, ny): - """Calculate single-particle energies. - - Parameters - ---------- - t : float - Hopping amplitude. - k : numpy array - Kpoint. - kc : float - Scaling factor. - ny : int - Number of y lattice points. - """ - if ny == 1: - e = -2.0 * t * cos(kc * k) - else: - e = -2.0 * t * (cos(kc[0] * k[0]) + cos(kc[1] * k[1])) - - return e - - -def get_strip(cfunc, cfunc_err, ix, nx, ny, stag=False): - iy = [i for i in range(ny)] - idx = [encode_basis(ix, i, nx) for i in iy] - if stag: - c = [((-1) ** (ix + i)) * cfunc[ib] for (i, ib) in zip(iy, idx)] - else: - c = [cfunc[ib] for ib in idx] - cerr = [cfunc_err[ib] for ib in idx] - return c, cerr diff --git a/ipie/thermal/hamiltonians/utils.py b/ipie/thermal/hamiltonians/utils.py index 34f03935..42186c24 100644 --- a/ipie/thermal/hamiltonians/utils.py +++ b/ipie/thermal/hamiltonians/utils.py @@ -3,7 +3,6 @@ from ipie.hamiltonians.utils import get_generic_integrals from ipie.thermal.hamiltonians._generic import Generic -from ipie.thermal.hamiltonians.hubbard import Hubbard from ipie.thermal.hamiltonians.ueg import UEG @@ -22,9 +21,7 @@ def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): ham : object Hamiltonian class. """ - if ham_opts["name"] == "Hubbard": - ham = Hubbard(ham_opts, verbose) - elif ham_opts["name"] == "UEG": + if ham_opts["name"] == "UEG": ham = UEG(system, ham_opts, verbose) elif ham_opts["name"] == "Generic": filename = ham_opts.get("integrals", None) diff --git a/ipie/thermal/propagation/continuous.py b/ipie/thermal/propagation/continuous.py index 74c3ad9b..d534cc13 100644 --- a/ipie/thermal/propagation/continuous.py +++ b/ipie/thermal/propagation/continuous.py @@ -6,7 +6,6 @@ from ipie.thermal.estimators.thermal import one_rdm_from_G from ipie.thermal.propagation.generic import GenericContinuous -from ipie.thermal.propagation.hubbard import HubbardContinuous from ipie.thermal.propagation.planewave import PlaneWave @@ -281,10 +280,6 @@ def get_continuous_propagator(system, hamiltonian, trial, qmc, options={}, verbo """ if system.name == "UEG": propagator = PlaneWave(system, hamiltonian, trial, qmc, options=options, verbose=verbose) - elif system.name == "Hubbard": - propagator = HubbardContinuous( - system, hamiltonian, trial, qmc, options=options, verbose=verbose - ) elif system.name == "Generic": propagator = GenericContinuous( system, hamiltonian, trial, qmc, options=options, verbose=verbose diff --git a/ipie/thermal/propagation/hubbard.py b/ipie/thermal/propagation/hubbard.py deleted file mode 100644 index daea5e92..00000000 --- a/ipie/thermal/propagation/hubbard.py +++ /dev/null @@ -1,271 +0,0 @@ -import cmath - -import numpy -import scipy.linalg - -from ipie.thermal.estimators.thermal import one_rdm_from_G - - -class ThermalDiscrete(object): - def __init__(self, ham, trial, qmc, options={}, verbose=False, lowrank=False): - if verbose: - print("# Parsing discrete propagator input options.") - print("# Using continuous Hubbar--Stratonovich transformations.") - self.free_projection = options.get("free_projection", False) - self.nstblz = qmc.nstblz - self.hs_type = "discrete" - self.charge_decomp = options.get("charge_decomposition", False) - if verbose: - if self.charge_decomp: - print("# Using charge decomposition.") - else: - print("# Using spin decomposition.") - # [field,spin] - if self.charge_decomp: - self.gamma = numpy.arccosh(numpy.exp(-0.5 * qmc.dt * ham.U + 0j)) - self.auxf = numpy.array( - [ - [numpy.exp(self.gamma), numpy.exp(self.gamma)], - [numpy.exp(-self.gamma), numpy.exp(-self.gamma)], - ] - ) - # e^{-gamma x} - self.aux_wfac = numpy.exp(0.5 * qmc.dt * ham.U) * numpy.array( - [numpy.exp(-self.gamma), numpy.exp(self.gamma)] - ) - else: - self.gamma = numpy.arccosh(numpy.exp(0.5 * qmc.dt * ham.U)) - self.auxf = numpy.array( - [ - [numpy.exp(self.gamma), numpy.exp(-self.gamma)], - [numpy.exp(-self.gamma), numpy.exp(self.gamma)], - ] - ) - self.aux_wfac = numpy.array([1.0, 1.0]) - if not ham.symmetric: - self.auxf = self.auxf * numpy.exp(-0.5 * qmc.dt * ham.U) - # Account for potential shift in chemical potential - sign = 1 if ham._alt_convention else -1 - self.dmu = sign * (ham.mu - trial.mu) - self.auxf *= numpy.exp(-qmc.dt * (self.dmu)) - if abs(self.dmu) > 1e-16: - self._mu = trial.mu - if verbose: - print(f"# Chemical potential shift (mu_T-mu): {-sign * self.dmu}") - else: - self._mu = ham.mu - self.delta = self.auxf - 1 - dt = qmc.dt - dmat_up = scipy.linalg.expm(-dt * (ham.H1[0])) - dmat_down = scipy.linalg.expm(-dt * (ham.H1[1])) - dmat = numpy.array([dmat_up, dmat_down]) - self.construct_one_body_propagator(ham, self._mu, dt) - self.BT_BP = None - self.BT = trial.dmat - self.BT_inv = trial.dmat_inv - if self.charge_decomp: - dtype = numpy.complex128 - else: - dtype = trial.dmat.dtype - self.BV = numpy.zeros((2, trial.dmat.shape[-1]), dtype=dtype) - if self.free_projection: - self.propagate_walker = self.propagate_walker_free - else: - self.propagate_walker = self.propagate_walker_constrained - - def construct_one_body_propagator(self, ham, mu, dt): - """Construct the one-body propagator Exp(-dt/2 H0) - Parameters - ---------- - ham : - ham class - dt : float - time-step - Returns - ------- - self.BH1 : numpy array - Exp(-dt H0) - """ - H1 = ham.H1 - I = numpy.identity(H1[0].shape[0], dtype=H1.dtype) - # No spin dependence for the moment. - sign = 1 if ham._alt_convention else -1 - self.BH1 = numpy.array( - [ - scipy.linalg.expm(-dt * (H1[0] + sign * mu * I)), - scipy.linalg.expm(-dt * (H1[1] + sign * mu * I)), - ] - ) - - def update_greens_function_simple(self, walker, time_slice): - walker.construct_greens_function_stable(time_slice) - - def update_greens_function(self, walker, i, xi): - for spin in [0, 1]: - g = walker.G[spin, :, i] - gbar = -walker.G[spin, i, :] - gbar[i] += 1 - denom = 1 + (1 - g[i]) * self.delta[xi, spin] - walker.G[spin] = ( - walker.G[spin] - self.delta[xi, spin] * numpy.einsum("i,j->ij", g, gbar) / denom - ) - - def propagate_greens_function(self, walker): - if walker.stack.time_slice < walker.stack.ntime_slices: - walker.G[0] = self.BT[0].dot(walker.G[0]).dot(self.BT_inv[0]) - walker.G[1] = self.BT[1].dot(walker.G[1]).dot(self.BT_inv[1]) - - def calculate_overlap_ratio(self, walker, i): - R1_up = 1 + (1 - walker.G[0, i, i]) * self.delta[0, 0] - R1_dn = 1 + (1 - walker.G[1, i, i]) * self.delta[0, 1] - R2_up = 1 + (1 - walker.G[0, i, i]) * self.delta[1, 0] - R2_dn = 1 + (1 - walker.G[1, i, i]) * self.delta[1, 1] - return 0.5 * numpy.array([R1_up * R1_dn, R2_up * R2_dn]) - - def estimate_eshift(self, walker): - oratio = self.calculate_overlap_ratio(walker, 0) - return sum(oratio) - - def propagate_walker_constrained(self, system, walker, time_slice, eshift=0): - for i in range(0, system.nbasis): - probs = self.calculate_overlap_ratio(walker, i) - phaseless_ratio = numpy.maximum(probs.real, [0, 0]) - norm = sum(phaseless_ratio) - r = numpy.random.random() - if norm > 0: - walker.weight = walker.weight * norm * numpy.exp(eshift) - # if walker.weight > walker.total_weight * 0.10: - # walker.weight = walker.total_weight * 0.10 - if r < phaseless_ratio[0] / norm: - xi = 0 - else: - xi = 1 - self.update_greens_function(walker, i, xi) - self.BV[0, i] = self.auxf[xi, 0] - self.BV[1, i] = self.auxf[xi, 1] - else: - walker.weight = 0 - B = numpy.einsum("ki,kij->kij", self.BV, self.BH1) - walker.stack.update(B) - # Need to recompute Green's function from scratch before we propagate it - # to the next time slice due to stack structure. - if walker.stack.time_slice % self.nstblz == 0: - walker.greens_function(None, walker.stack.time_slice - 1) - self.propagate_greens_function(walker) - - def propagate_walker_free(self, system, walker, time_slice, eshift): - fields = numpy.random.randint(0, 2, system.nbasis) - self.BV[0] = numpy.array([self.auxf[xi, 0] for xi in fields]) - self.BV[1] = numpy.array([self.auxf[xi, 1] for xi in fields]) - # Vsii Tsij - B = numpy.einsum("ki,kij->kij", self.BV, self.BH1) - wfac = 1.0 + 0j - for xi in fields: - wfac *= self.aux_wfac[xi] - # Compute determinant ratio det(1+A')/det(1+A). - # 1. Current walker's green's function. - G = walker.greens_function(None, slice_ix=walker.stack.ntime_slices, inplace=False) - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function(None, slice_ix=walker.stack.ntime_slices, inplace=True) - - # 3. Compute det(G/G') - M0 = numpy.array( - [ - scipy.linalg.det(G[0], check_finite=False), - scipy.linalg.det(G[1], check_finite=False), - ] - ) - Mnew = numpy.array( - [ - scipy.linalg.det(walker.G[0], check_finite=False), - scipy.linalg.det(walker.G[1], check_finite=False), - ] - ) - try: - # Could save M0 rather than recompute. - oratio = wfac * (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) - - walker.ot = 1.0 - # Constant terms are included in the walker's weight. - (magn, phase) = cmath.polar(oratio) - walker.weight *= magn - walker.phase *= cmath.exp(1j * phase) - except ZeroDivisionError: - walker.weight = 0.0 - # Need to recompute Green's function from scratch before we propagate it - # to the next time slice due to stack structure. - - -class HubbardContinuous(object): - """Propagator for continuous HS transformation, specialised for Hubbard model. - - Parameters - ---------- - options : dict - Propagator input options. - qmc : :class:`pie.qmc.options.QMCOpts` - QMC options. - system : :class:`pie.system.System` - System object. - trial : :class:`pie.trial_wavefunctioin.Trial` - Trial wavefunction object. - verbose : bool - If true print out more information during setup. - """ - - def __init__(self, system, trial, qmc, options={}, verbose=False): - if verbose: - print("# Parsing continuous propagator input options.") - self.hs_type = "hubbard_continuous" - self.free_projection = options.get("free_projection", False) - self.ffts = options.get("ffts", False) - self.nstblz = qmc.nstblz - self.btk = numpy.exp(-0.5 * qmc.dt * system.eks) - model = system.__class__.__name__ - self.dt = qmc.dt - self.iu_fac = 1j * system.U**0.5 - self.sqrt_dt = qmc.dt**0.5 - self.isqrt_dt = 1j * self.sqrt_dt - # optimal mean-field shift for the hubbard model - P = one_rdm_from_G(trial.G) - # Mean field shifts (2,nchol_vec). - self.mf_shift = self.construct_mean_field_shift(system, P) - if verbose: - print( - "# Absolute value of maximum component of mean field shift: " - "{:13.8e}.".format(numpy.max(numpy.abs(self.mf_shift))) - ) - self.mf_core = 0.5 * numpy.dot(self.mf_shift, self.mf_shift) - # if self.ffts: - # self.kinetic = kinetic_kspace - # else: - # self.kinetic = kinetic_real - if verbose: - print("# Finished propagator input options.") - - def construct_one_body_propagator(self, system, dt): - # \sum_gamma v_MF^{gamma} v^{\gamma} - vi1b = self.iu_fac * numpy.diag(self.mf_shift) - I = numpy.identity(system.H1[0].shape[0], dtype=system.H1.dtype) - muN = system.mu * I - sign = 1 if system._alt_convention else -1 - H1 = system.h1e_mod - numpy.array([vi1b - sign * muN, vi1b - sign * muN]) - self.BH1 = numpy.array( - [scipy.linalg.expm(-0.5 * dt * H1[0]), scipy.linalg.expm(-0.5 * dt * H1[1])] - ) - - def construct_mean_field_shift(self, system, P): - # i sqrt{U} < n_{iup} + n_{idn} >_MF - return self.iu_fac * (numpy.diag(P[0]) + numpy.diag(P[1])) - - def construct_force_bias(self, system, P, trial): - # i sqrt{U} < n_{iup} + n_{idn} > - mf_shift - vbias = self.iu_fac * (numpy.diag(P[0]) + numpy.diag(P[1])) - return -self.sqrt_dt * (vbias - self.mf_shift) - - def construct_VHS(self, system, shifted): - # Note factor of i included in v_i - # B_V(x-\bar{x}) = e^{\sqrt{dt}*(x-\bar{x})\hat{v}_i} - # v_i = n_{iu} + n_{id} - return numpy.diag(self.sqrt_dt * self.iu_fac * shifted) diff --git a/ipie/thermal/propagation/utils.py b/ipie/thermal/propagation/utils.py index 2a8ad1c2..59959cbd 100644 --- a/ipie/thermal/propagation/utils.py +++ b/ipie/thermal/propagation/utils.py @@ -1,7 +1,6 @@ """Routines for performing propagation of a walker""" from ipie.thermal.propagation.continuous import Continuous -from ipie.thermal.propagation.hubbard import ThermalDiscrete from ipie.thermal.propagation.planewave import PlaneWave @@ -24,47 +23,25 @@ def get_propagator(options, qmc, system, hamiltonian, trial, verbose=False, lowr propagator : class or None Propagator object. """ - if hamiltonian.name == "Hubbard": - hs_type = options.get("hubbard_stratonovich", "discrete") - if hs_type == "discrete": - propagator = ThermalDiscrete( - hamiltonian, - trial, - qmc, - options=options, - verbose=verbose, - lowrank=lowrank, - ) - else: - propagator = Continuous( - options, - qmc, - system, - hamiltonian, - trial, - verbose=verbose, - lowrank=lowrank, - ) + if hamiltonian.name == "UEG": + propagator = PlaneWave( + system, + hamiltonian, + trial, + qmc, + options=options, + verbose=verbose, + lowrank=lowrank, + ) else: - if hamiltonian.name == "UEG": - propagator = PlaneWave( - system, - hamiltonian, - trial, - qmc, - options=options, - verbose=verbose, - lowrank=lowrank, - ) - else: - propagator = Continuous( - options, - qmc, - system, - hamiltonian, - trial, - verbose=verbose, - lowrank=lowrank, - ) + propagator = Continuous( + options, + qmc, + system, + hamiltonian, + trial, + verbose=verbose, + lowrank=lowrank, + ) return propagator diff --git a/ipie/thermal/system/hubbard_holstein.py b/ipie/thermal/system/hubbard_holstein.py deleted file mode 100644 index 134c646c..00000000 --- a/ipie/thermal/system/hubbard_holstein.py +++ /dev/null @@ -1,505 +0,0 @@ -"""Hubbard model specific classes and methods""" - -import cmath -from math import cos, pi, sqrt - -import numpy -import scipy.linalg - -from ipie.utils.io import fcidump_header - - -class HubbardHolstein(object): - """HubbardHolstein model system class. - - 1 and 2 case with nearest neighbour hopping. - - Parameters - ---------- - inputs : dict - dictionary of system input options. - - Attributes - ---------- - nup : int - Number of up electrons. - ndown : int - Number of down electrons. - ne : int - Number of electrons. - t : float - Hopping parameter. - U : float - Hubbard U interaction strength. - g : float - Holstein coupling strength - lmbda : float - Polaron formation energy - w0 : float - Frequency w0 - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - nbasis : int - Number of single-particle basis functions. - T : numpy.array - Hopping matrix - """ - - def __init__(self, inputs, verbose=False): - if verbose: - print("# Parsing input options.") - self.nup = inputs.get("nup") - self.ndown = inputs.get("ndown") - self.ne = self.nup + self.ndown - self.nelec = (self.nup, self.ndown) - - self.control_variate = False - - self.t = inputs.get("t", 1.0) - self.lmbda = inputs.get("lambda", 1.0) - self.w0 = inputs.get("w0", 1.0) - self.m = inputs.get("m", 1.0 / self.w0) # mass - - self.U = inputs["U"] - self.nx = inputs["nx"] - self.ny = inputs["ny"] - self.ktwist = numpy.array(inputs.get("ktwist")) - self.symmetric = inputs.get("symmetric", False) - - self.ypbc = inputs.get("ypbc", True) - self.xpbc = inputs.get("xpbc", True) - - self.control_variate = False - - if self.symmetric: - # An unusual convention for the sign of the chemical potential is - # used in Phys. Rev. B 99, 045108 (2018) - # Symmetric uses the symmetric form of the hubbard model and will - # also change the sign of the chemical potential in the density - # matrix. - self._alt_convention = True - else: - self._alt_convention = False - self.nbasis = self.nx * self.ny - - # This depends on the dimension of the system hard-coded to do 1D - d = 2 - if self.nx == 1 or self.ny == 1: # 1d - d = 1 - - self.g = inputs.get("g", None) - - if self.g == None: - # This is assuming self.m = 1 / self.w0 - # to include mass see 10.1103/PhysRevLett.97.056402 - self.g = sqrt(float(d) * 2.0 * self.lmbda * self.t * self.w0) - - if verbose: - print(f"# d = {d}") - print(f"# nx, ny = {self.nx},{self.ny}") - print(f"# nbasis = {self.nbasis}") - print(f"# t, U = {self.t}, {self.U}") - print(f"# m, w0, g, lambda = {self.m}, {self.w0}, {self.g}, {self.lmbda}") - - self.lang_firsov = inputs.get("lang_firsov", False) - self.gamma_lf = 0.0 - if self.lang_firsov: - self.gamma_lf = self.g * numpy.sqrt(2.0 / (self.m * self.w0**3)) - self.Ueff = ( - self.U - + self.gamma_lf**2 * self.m * self.w0**2 - - 2.0 * self.g * self.gamma_lf * numpy.sqrt(2.0 * self.m * self.w0) - ) - print(f"# gamma_lf = {self.gamma_lf}") - print(f"# Ueff = {self.Ueff}") - - self.nactive = self.nbasis - self.nfv = 0 - self.ncore = 0 - (self.kpoints, self.kc, self.eks) = kpoints(self.t, self.nx, self.ny) - self.pinning = inputs.get("pinning_fields", False) - self._opt = True - if verbose: - print("# Setting up one-body operator.") - if self.pinning: - if verbose: - print("# Using pinning field.") - self.T = kinetic_pinning_alt(self.t, self.nbasis, self.nx, self.ny) - else: - self.T = kinetic( - self.t, - self.nbasis, - self.nx, - self.ny, - self.ktwist, - xpbc=self.xpbc, - ypbc=self.ypbc, - ) - self.H1 = self.T - self.Text = scipy.linalg.block_diag(self.T[0], self.T[1]) - self.P = transform_matrix(self.nbasis, self.kpoints, self.kc, self.nx, self.ny) - self.mu = inputs.get("mu", None) - # For interface consistency. - self.ecore = 0.0 - # Number of field configurations per walker. - self.nfields = self.nbasis - self.name = "HubbardHolstein" - if verbose: - print("# Finished setting up Hubbard-Holstein system object.") - # "Volume" to define density. - self.vol = self.nx * self.ny - self.construct_h1e_mod() - - def fcidump(self, to_string=False): - """Dump 1- and 2-electron integrals to file. - - Parameters - ---------- - to_string : bool - Return fcidump as string. Default print to stdout. - """ - header = fcidump_header(self.ne, self.nbasis, self.nup - self.ndown) - for i in range(1, self.nbasis + 1): - if self.T.dtype == complex: - fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" - line = fmt.format(self.U.real, self.U.imag, i, i, i, i) - else: - fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" - line = fmt.format(self.U, i, i, i, i) - header += line - for i in range(0, self.nbasis): - for j in range(i + 1, self.nbasis): - integral = self.T[0][i, j] - if abs(integral) > 1e-8: - if self.T.dtype == complex: - fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" - line = fmt.format(integral.real, integral.imag, i + 1, j + 1, 0, 0) - else: - fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" - line = fmt.format(integral, i + 1, j + 1, 0, 0) - header += line - if self.T.dtype == complex: - fmt = "({: 10.8e}, {: 10.8e}) {:>3d} {:>3d} {:>3d} {:>3d}\n" - header += fmt.format(0, 0, 0, 0, 0, 0) - else: - fmt = "{: 10.8e} {:>3d} {:>3d} {:>3d} {:>3d}\n" - header += fmt.format(0, 0, 0, 0, 0) - if to_string: - print(header) - else: - return header - - def hijkl(self, i, j, k, l): - if i == k and j == l and i == j: - return self.U - else: - return 0.0 - - def construct_h1e_mod(self): - # Subtract one-body bit following reordering of 2-body operators. - # Eqn (17) of [Motta17]_ - if not self.symmetric: - v0 = 0.5 * self.U * numpy.eye(self.nbasis) - self.h1e_mod = numpy.array([self.H1[0] - v0, self.H1[1] - v0]) - else: - self.h1e_mod = self.H1 - - -def transform_matrix(nbasis, kpoints, kc, nx, ny): - U = numpy.zeros(shape=(nbasis, nbasis), dtype=complex) - for i, k_i in enumerate(kpoints): - for j in range(0, nbasis): - r_j = decode_basis(nx, ny, j) - U[i, j] = numpy.exp(1j * numpy.dot(kc * k_i, r_j)) - - return U - - -def kinetic(t, nbasis, nx, ny, ks, xpbc=True, ypbc=True): - """Kinetic part of the Hamiltonian in our one-electron basis. - - Parameters - ---------- - t : float - Hopping parameter - nbasis : int - Number of one-electron basis functions. - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - - Returns - ------- - T : numpy.array - Hopping Hamiltonian matrix. - """ - - if ks.all() is None: - T = numpy.zeros((nbasis, nbasis), dtype=float) - else: - T = numpy.zeros((nbasis, nbasis), dtype=complex) - - for i in range(0, nbasis): - xy1 = decode_basis(nx, ny, i) - for j in range(i + 1, nbasis): - xy2 = decode_basis(nx, ny, j) - dij = abs(xy1 - xy2) - if sum(dij) == 1: - T[i, j] = -t - # Take care of periodic boundary conditions - # there should be a less stupid way of doing this. - if ny == 1 and dij == [nx - 1] and xpbc: - if ks.all() is not None: - phase = cmath.exp(1j * numpy.dot(cmath.pi * ks, [1])) - else: - phase = 1.0 - T[i, j] += -t * phase - elif (dij == [nx - 1, 0]).all() and xpbc: - if ks.all() is not None: - phase = cmath.exp(1j * numpy.dot(cmath.pi * ks, [1, 0])) - else: - phase = 1.0 - T[i, j] += -t * phase - elif (dij == [0, ny - 1]).all() and ypbc: - if ks.all() is not None: - phase = cmath.exp(1j * numpy.dot(cmath.pi * ks, [0, 1])) - else: - phase = 1.0 - T[i, j] += -t * phase - - # This only works because the diagonal of T is zero. - return numpy.array([T + T.conj().T, T + T.conj().T]) - - -def kinetic_pinning(t, nbasis, nx, ny): - r"""Kinetic part of the Hamiltonian in our one-electron basis. - - Adds pinning fields as outlined in [Qin16]_. This forces periodic boundary - conditions along x and open boundary conditions along y. Pinning fields are - applied in the y direction as: - - .. math:: - \nu_{i\uparrow} = -\nu_{i\downarrow} = (-1)^{i_x+i_y}\nu_0, - - for :math:`i_y=1,L_y` and :math:`\nu_0=t/4`. - - Parameters - ---------- - t : float - Hopping parameter - nbasis : int - Number of one-electron basis functions. - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - - Returns - ------- - T : numpy.array - Hopping Hamiltonian matrix. - """ - - Tup = numpy.zeros((nbasis, nbasis)) - Tdown = numpy.zeros((nbasis, nbasis)) - nu0 = 0.25 * t - - for i in range(0, nbasis): - # pinning field along y. - xy1 = decode_basis(nx, ny, i) - if xy1[1] == 0 or xy1[1] == ny - 1: - Tup[i, i] += (-1.0) ** (xy1[0] + xy1[1]) * nu0 - Tdown[i, i] += (-1.0) ** (xy1[0] + xy1[1] + 1) * nu0 - for j in range(i + 1, nbasis): - xy2 = decode_basis(nx, ny, j) - dij = abs(xy1 - xy2) - if sum(dij) == 1: - Tup[i, j] = Tdown[i, j] = -t - # periodic bcs in x. - if (dij == [nx - 1, 0]).all(): - Tup[i, j] += -t - Tdown[i, j] += -t - - return numpy.array([Tup + numpy.triu(Tup, 1).T, Tdown + numpy.triu(Tdown, 1).T]) - - -def kinetic_pinning_alt(t, nbasis, nx, ny): - r"""Kinetic part of the Hamiltonian in our one-electron basis. - - Adds pinning fields as outlined in [Qin16]_. This forces periodic boundary - conditions along x and open boundary conditions along y. Pinning fields are - applied in the y direction as: - - .. math:: - \nu_{i\uparrow} = -\nu_{i\downarrow} = (-1)^{i_x+i_y}\nu_0, - - for :math:`i_y=1,L_y` and :math:`\nu_0=t/4`. - - Parameters - ---------- - t : float - Hopping parameter - nbasis : int - Number of one-electron basis functions. - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - - Returns - ------- - T : numpy.array - Hopping Hamiltonian matrix. - """ - - Tup = numpy.zeros((nbasis, nbasis)) - Tdown = numpy.zeros((nbasis, nbasis)) - h = 0.1 * t - - for i in range(0, nbasis): - # pinning field along y direction when i_x = 0. - xy1 = decode_basis(nx, ny, i) - if xy1[0] == 0: - Tup[i, i] += (-1.0) ** (xy1[1]) * h - Tdown[i, i] += (-1.0) ** (xy1[1] + 1) * h - for j in range(i + 1, nbasis): - xy2 = decode_basis(nx, ny, j) - dij = abs(xy1 - xy2) - if sum(dij) == 1: - Tup[i, j] = Tdown[i, j] = -t - # periodic bcs in y. - if (dij == [0, ny - 1]).all(): - Tup[i, j] += -t - Tdown[i, j] += -t - - return numpy.array([Tup + numpy.triu(Tup, 1).T, Tdown + numpy.triu(Tdown, 1).T]) - - -def decode_basis(nx, ny, i): - """Return cartesian lattice coordinates from basis index. - - Consider a 3x3 lattice then we index lattice sites like:: - - (0,2) (1,2) (2,2) 6 7 8 - (0,1) (1,1) (2,1) -> 3 4 5 - (0,0) (1,0) (2,0) 0 1 2 - - i.e., i = i_x + n_x * i_y, and i_x = i%n_x, i_y = i//nx. - - Parameters - ---------- - nx : int - Number of x lattice sites. - ny : int - Number of y lattice sites. - i : int - Basis index (same for up and down spins). - """ - if ny == 1: - return numpy.array([i % nx]) - else: - return numpy.array([i % nx, i // nx]) - - -def encode_basis(i, j, nx): - """Encode 2d index to one dimensional index. - - See decode basis for layout. - - Parameters - ---------- - i : int - x coordinate. - j : int - y coordinate - nx : int - Number of x lattice sites. - - Returns - ------- - ix : int - basis index. - """ - return i + j * nx - - -def _super_matrix(U, nbasis): - """Construct super-matrix from v_{ijkl}""" - - -def kpoints(t, nx, ny): - """Construct kpoints for system. - - Parameters - ---------- - t : float - Hopping amplitude. - nx : int - Number of x lattice sites. - nx : int - Number of y lattice sites. - - Returns - ------- - kp : numpy array - System kpoints Note these are not sorted according to eigenvalue energy - but rather so as to conform with numpys default kpoint indexing for FFTs. - kfac : float - Kpoint scaling factor (2pi/L). - eigs : numpy array - Single particle eigenvalues associated with kp. - """ - kp = [] - eigs = [] - if ny == 1: - kfac = numpy.array([2.0 * pi / nx]) - for n in range(0, nx): - kp.append(numpy.array([n])) - eigs.append(ek(t, n, kfac, ny)) - else: - kfac = numpy.array([2.0 * pi / nx, 2.0 * pi / ny]) - for n in range(0, nx): - for m in range(0, ny): - k = numpy.array([n, m]) - kp.append(k) - eigs.append(ek(t, k, kfac, ny)) - - eigs = numpy.array(eigs) - kp = numpy.array(kp) - return (kp, kfac, eigs) - - -def ek(t, k, kc, ny): - """Calculate single-particle energies. - - Parameters - ---------- - t : float - Hopping amplitude. - k : numpy array - Kpoint. - kc : float - Scaling factor. - ny : int - Number of y lattice points. - """ - if ny == 1: - e = -2.0 * t * cos(kc * k) - else: - e = -2.0 * t * (cos(kc[0] * k[0]) + cos(kc[1] * k[1])) - - return e - - -def get_strip(cfunc, cfunc_err, ix, nx, ny, stag=False): - iy = [i for i in range(ny)] - idx = [encode_basis(ix, i, nx) for i in iy] - if stag: - c = [((-1) ** (ix + i)) * cfunc[ib] for (i, ib) in zip(iy, idx)] - else: - c = [cfunc[ib] for ib in idx] - cerr = [cfunc_err[ib] for ib in idx] - return c, cerr diff --git a/ipie/thermal/tests/test_ft_integration.py b/ipie/thermal/tests/test_ft_integration.py index e51bc99d..390573c1 100644 --- a/ipie/thermal/tests/test_ft_integration.py +++ b/ipie/thermal/tests/test_ft_integration.py @@ -42,7 +42,7 @@ _data_dir = os.path.abspath(os.path.dirname(__file__)) + "/reference_data/" _legacy_test_dirs = [ - "ft_4x4_hubbard_discrete", + #"ft_4x4_hubbard_discrete", "ft_ueg_ecut1.0_rs1.0", ] From 2c17e28b65e318ee1de31ff0a5aedcc2b0f9aa55 Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Wed, 30 Aug 2023 16:37:43 -0400 Subject: [PATCH 09/84] remove thermal.qmc.options --- ipie/qmc/options.py | 6 ++ ipie/thermal/estimators/mixed.py | 15 +-- ipie/thermal/qmc/thermal_afqmc.py | 4 +- ipie/thermal/walkers/thermal.py | 167 ------------------------------ 4 files changed, 11 insertions(+), 181 deletions(-) diff --git a/ipie/qmc/options.py b/ipie/qmc/options.py index 44c52474..7a2be293 100644 --- a/ipie/qmc/options.py +++ b/ipie/qmc/options.py @@ -148,6 +148,12 @@ def __init__(self, inputs={}, verbose=False): alias=["random_seed", "seed"], verbose=verbose, ) + self.beta = get_input_value( + inputs, + "beta", + default=None, + verbose=verbose, + ) def __str__(self, verbose=0): _str = "" diff --git a/ipie/thermal/estimators/mixed.py b/ipie/thermal/estimators/mixed.py index bd772330..06284866 100644 --- a/ipie/thermal/estimators/mixed.py +++ b/ipie/thermal/estimators/mixed.py @@ -110,18 +110,9 @@ def __init__(self, mixed_opts, system, hamiltonian, root, filename, qmc, trial, else: self.two_rdm = None - if qmc.gpu: - import cupy - - self.estimates = cupy.zeros(self.nreg + dms_size, dtype=dtype) - self.names = get_estimator_enum(self.thermal) - self.estimates[self.names.time] = time.time() - # self.global_estimates = cupy.zeros(self.nreg+dms_size, - # dtype=dtype) - else: - self.estimates = numpy.zeros(self.nreg + dms_size, dtype=dtype) - self.names = get_estimator_enum(self.thermal) - self.estimates[self.names.time] = time.time() + self.estimates = numpy.zeros(self.nreg + dms_size, dtype=dtype) + self.names = get_estimator_enum(self.thermal) + self.estimates[self.names.time] = time.time() self.global_estimates = numpy.zeros(self.nreg + dms_size, dtype=dtype) self.key = { "Iteration": "Simulation iteration. iteration*dt = tau.", diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index 78e703ed..2b68c801 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -8,7 +8,7 @@ from ipie.thermal.propagation.utils import get_propagator from ipie.thermal.trial.utils import get_trial_density_matrix from ipie.thermal.walkers.handler import Walkers -from ipie.thermal.qmc.options import QMCOpts +from ipie.qmc.options import QMCOpts from ipie.qmc.utils import set_rng_seed from ipie.thermal.system.utils import get_system from ipie.utils.io import get_input_value, to_json @@ -151,7 +151,7 @@ def __init__( self.system, ham_opts, verbose=verbose, comm=self.shared_comm ) - self.qmc = QMCOpts(qmc_opts, self.system, verbose) + self.qmc = QMCOpts(qmc_opts, verbose) self.qmc.rng_seed = set_rng_seed(self.qmc.rng_seed, comm) self.qmc.ntime_slices = int(round(self.qmc.beta / self.qmc.dt)) # Overide whatever's in the input file due to structure of FT algorithm. diff --git a/ipie/thermal/walkers/thermal.py b/ipie/thermal/walkers/thermal.py index 6b68e101..3a3a57a9 100644 --- a/ipie/thermal/walkers/thermal.py +++ b/ipie/thermal/walkers/thermal.py @@ -565,170 +565,3 @@ def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): # rdm = one_rdm_from_G(self.G) # return local_energy_G(system, hamiltonian, self, rdm) - -def unit_test(): - from ipie.thermal.system.ueg import UEG - from ipie.thermal.propagation.planewave import PlaneWave - from ipie.thermal.trial.onebody import OneBody - from ipie.thermal.qmc.options import QMCOpts - - inputs = { - "nup": 1, - "ndown": 1, - "rs": 1.0, - "ecut": 0.5, - "name": "one_body", - "mu": 1.94046021, - "beta": 0.5, - "dt": 0.05, - "optimised": True, - } - beta = inputs["beta"] - dt = inputs["dt"] - - system = UEG(inputs, verbose=False) - - qmc = QMCOpts(inputs, system, True) - trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False) - - walker = ThermalWalker(inputs, system, trial, True) - # walker.greens_function(trial) - E, T, V = walker.local_energy(system) - numpy.random.seed(0) - inputs["optimised"] = False - propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) - - propagator.propagate_walker_free(system, walker, trial, False) - - Gold = walker.G[0].copy() - - system = UEG(inputs, verbose=False) - - qmc = QMCOpts(inputs, system, verbose=False) - trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False) - - propagator = PlaneWave(inputs, qmc, system, trial, True) - walker = ThermalWalker(inputs, system, trial, verbose=False) - # walker.greens_function(trial) - E, T, V = walker.local_energy(system) - numpy.random.seed(0) - inputs["optimised"] = True - propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) - - propagator.propagate_walker_free(system, walker, trial, False) - - Gnew = walker.G[0].copy() - - assert scipy.linalg.norm(Gold[:, 0] - Gnew[:, 0]) < 1e-10 - - inputs["stack_size"] = 1 - walker = ThermalWalker(inputs, system, trial, verbose=False) - numpy.random.seed(0) - propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) - for i in range(0, 5): - propagator.propagate_walker(system, walker, trial) - Gs1 = walker.G[0].copy() - for ts in range(walker.stack_length): - walker.greens_function(trial, slice_ix=ts * walker.stack_size) - E, T, V = walker.local_energy(system) - # print(E) - - inputs["stack_size"] = 5 - walker = ThermalWalker(inputs, system, trial, verbose=False) - numpy.random.seed(0) - propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) - for i in range(0, 5): - propagator.propagate_walker(system, walker, trial) - Gs5 = walker.G[0].copy() - for ts in range(walker.stack_length): - walker.greens_function(trial, slice_ix=ts * walker.stack_size) - E, T, V = walker.local_energy(system) - # print(E) - assert numpy.linalg.norm(Gs1 - Gs5) < 1e-10 - - N = 5 - A = numpy.random.rand(N, N) - Q, R, P = scipy.linalg.qr(A, pivoting=True) - - #### test permutation start - # Pmat = numpy.zeros((N,N)) - # for i in range (N): - # Pmat[P[i],i] = 1 - # print(P) - # tmp = Q.dot(R)#.dot(Pmat.T) - # print(tmp) - # print("==================") - # tmp2 = tmp.dot(Pmat.T) - # print(tmp2) - # print("==================") - # tmp[:,P] = tmp [:,range(N)] - # print(tmp) - #### test permutation end - - B = numpy.random.rand(N, N) - (Q1, R1, P1) = scipy.linalg.qr(B, pivoting=True, check_finite=False) - # Form permutation matrix - P1mat = numpy.zeros(B.shape, B.dtype) - P1mat[P1, range(len(P1))] = 1.0 - # Form D matrices - D1 = numpy.diag(R1.diagonal()) - D1inv = numpy.diag(1.0 / R1.diagonal()) - T1 = numpy.dot(numpy.dot(D1inv, R1), P1mat.T) - - assert numpy.linalg.norm(B - numpy.einsum("ij,jj->ij", Q1, D1).dot(T1)) < 1e-10 - - # tmp[:,:] = tmp[:,P] - # print(A - tmp) - # print(Q * Q.T) - # print(R) - - # Test walker green's function. - from ipie.thermal.estimators.hubbard import local_energy_hubbard - from ipie.thermal.estimators.thermal import one_rdm_from_G - from ipie.thermal.hamiltonians.hubbard import Hubbard - - sys_dict = { - "name": "Hubbard", - "nx": 4, - "ny": 4, - "nup": 7, - "ndown": 7, - "U": 4, - "t": 1, - } - system = Hubbard(sys_dict) - beta = 4 - mu = 1 - trial = OneBody({"mu": mu}, system, beta, dt, verbose=True) - - dt = 0.05 - num_slices = int(beta / dt) - - eref = 0 - for ek in system.eks: - eref += 2 * ek * 1.0 / (numpy.exp(beta * (ek - mu)) + 1) - walker = ThermalWalker({"stack_size": 1}, system, trial) - Gs1 = walker.G[0].copy() - rdm = one_rdm_from_G(walker.G) - ekin = local_energy_hubbard(system, rdm)[1] - try: - assert abs(eref - ekin) < 1e-8 - except AssertionError: - print(f"Error in kinetic energy check. Ref: {eref:13.8e} Calc:{ekin:13.8e}") - walker = ThermalWalker({"stack_size": 10}, system, trial) - rdm = one_rdm_from_G(walker.G) - ekin = local_energy_hubbard(system, rdm)[1] - try: - assert abs(eref - ekin) < 1e-8 - except AssertionError: - print( - "Error in kinetic energy check. Ref: %13.10e Calc: %13.10e" - " Error: %13.8e" % (eref.real, ekin.real, abs(eref - ekin)) - ) - for ts in range(walker.stack_length): - walker.greens_function(trial, slice_ix=ts * walker.stack_size) - assert numpy.linalg.norm(Gs1 - walker.G[0]) < 1e-10 - - -if __name__ == "__main__": - unit_test() From 3810288894f9f7a178d6ef4eccc5979d68d9fd67 Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Wed, 30 Aug 2023 16:39:02 -0400 Subject: [PATCH 10/84] recover code in legacy that was mistakely modified --- ipie/legacy/hamiltonians/utils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ipie/legacy/hamiltonians/utils.py b/ipie/legacy/hamiltonians/utils.py index 34f03935..670d0f84 100644 --- a/ipie/legacy/hamiltonians/utils.py +++ b/ipie/legacy/hamiltonians/utils.py @@ -2,9 +2,9 @@ import time from ipie.hamiltonians.utils import get_generic_integrals -from ipie.thermal.hamiltonians._generic import Generic -from ipie.thermal.hamiltonians.hubbard import Hubbard -from ipie.thermal.hamiltonians.ueg import UEG +from ipie.legacy.hamiltonians._generic import Generic +from ipie.legacy.hamiltonians.hubbard import Hubbard +from ipie.legacy.hamiltonians.ueg import UEG def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): From 3bccf5e4f7dfc81a91c327ab95f20d62bdb18d29 Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Wed, 30 Aug 2023 17:01:36 -0400 Subject: [PATCH 11/84] remove thermal.qmc.options --- ipie/thermal/qmc/options.py | 150 ------------------------------------ 1 file changed, 150 deletions(-) delete mode 100644 ipie/thermal/qmc/options.py diff --git a/ipie/thermal/qmc/options.py b/ipie/thermal/qmc/options.py deleted file mode 100644 index a17072bc..00000000 --- a/ipie/thermal/qmc/options.py +++ /dev/null @@ -1,150 +0,0 @@ - -from ipie.utils.io import get_input_value - - -def convert_from_reduced_unit(system, qmc_opts, verbose=False): - if system.name == "UEG": - TF = system.ef # Fermi temeprature - if verbose: - print(f"# Fermi Temperature: {TF:13.8e}") - print(f"# beta in reduced unit: {qmc_opts['beta']:13.8e}") - print(f"# dt in reduced unit: {qmc_opts['dt']:13.8e}") - dt = qmc_opts["dt"] # original dt - beta = qmc_opts["beta"] # original dt - scaled_dt = dt / TF # converting to Hartree ^ -1 - scaled_beta = beta / TF # converting to Hartree ^ -1 - if verbose: - print(f"# beta in Hartree^-1: {scaled_beta:13.8e}") - print(f"# dt in Hartree^-1: {scaled_dt:13.8e}") - return scaled_dt, scaled_beta - - -class QMCOpts(object): - r"""Input options and certain constants / parameters derived from them. - - Initialised from a dict containing the following options, not all of which - are required. - - Parameters - ---------- - method : string - Which auxiliary field method are we using? Currently only CPMC is - implemented. - nwalkers : int - Number of walkers to propagate in a simulation. - dt : float - Timestep. - nsteps : int - Number of steps per block. - nmeasure : int - Frequency of energy measurements. - nstblz : int - Frequency of Gram-Schmidt orthogonalisation steps. - npop_control : int - Frequency of population control. - temp : float - Temperature. Currently not used. - nequilibrate : int - Number of steps used for equilibration phase. Only used to fix local - energy bound when using phaseless approximation. - importance_sampling : boolean - Are we using importance sampling. Default True. - hubbard_statonovich : string - Which hubbard stratonovich transformation are we using. Currently the - options are: - - - discrete : Use the discrete Hirsch spin transformation. - - opt_continuous : Use the continuous transformation for the Hubbard - model. - - generic : Use the generic transformation. To be used with Generic - system class. - - ffts : boolean - Use FFTS to diagonalise the kinetic energy propagator? Default False. - This may speed things up for larger lattices. - - Attributes - ---------- - cplx : boolean - Do we require complex wavefunctions? - mf_shift : float - Mean field shift for continuous Hubbard-Stratonovich transformation. - iut_fac : complex float - Stores i*(U*dt)**0.5 for continuous Hubbard-Stratonovich transformation. - ut_fac : float - Stores (U*dt) for continuous Hubbard-Stratonovich transformation. - mf_nsq : float - Stores M * mf_shift for continuous Hubbard-Stratonovich transformation. - local_energy_bound : float - Energy pound for continuous Hubbard-Stratonovich transformation. - mean_local_energy : float - Estimate for mean energy for continuous Hubbard-Stratonovich transformation. - """ - - def __init__(self, inputs, system, verbose=False): - self.nwalkers = get_input_value( - inputs, "num_walkers", default=10, alias=["nwalkers"], verbose=verbose - ) - self.nwalkers_per_task = get_input_value( - inputs, - "num_walkers", - default=None, - alias=["nwalkers_per_task"], - verbose=verbose, - ) - if self.nwalkers_per_task is not None: - self.nwalkers = None - self.dt = get_input_value(inputs, "timestep", default=0.005, alias=["dt"], verbose=verbose) - self.batched = get_input_value(inputs, "batched", default=True, verbose=verbose) - self.gpu = get_input_value(inputs, "gpu", default=False, verbose=verbose) - self.nsteps = get_input_value( - inputs, "num_steps", default=10, alias=["nsteps", "steps"], verbose=verbose - ) - self.nblocks = get_input_value( - inputs, - "blocks", - default=1000, - alias=["num_blocks", "nblocks"], - verbose=verbose, - ) - self.total_steps = self.nsteps * self.nblocks - self.nstblz = get_input_value( - inputs, - "stabilise_freq", - default=5, - alias=["nstabilise", "reortho"], - verbose=verbose, - ) - self.npop_control = get_input_value( - inputs, - "pop_control_freq", - default=5, - alias=["npop_control", "pop_control"], - verbose=verbose, - ) - self.eqlb_time = get_input_value( - inputs, - "equilibration_time", - default=2.0, - alias=["tau_eqlb"], - verbose=verbose, - ) - self.neqlb = int(self.eqlb_time / self.dt) - self.beta = get_input_value(inputs, "beta", default=None, verbose=verbose) - self.scaled_temp = get_input_value( - inputs, - "scaled_temperature", - default=False, - alias=["reduced_temperature"], - verbose=verbose, - ) - if self.scaled_temp: - self.beta_scaled = self.beta - self.dt, self.beta = convert_from_reduced_unit(system, inputs, verbose) - self.rng_seed = get_input_value( - inputs, - "rng_seed", - default=None, - alias=["random_seed", "seed"], - verbose=verbose, - ) From 46dd6e97ab7889abb86271d066eba4315952716d Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 30 Aug 2023 17:21:27 -0400 Subject: [PATCH 12/84] Removed thermal/walkers/thermal.py since it duplicates thermal/walkers/uhf_walkers.py. Removed thermal/hamiltonians/ and thermal/systems/directories. Added ueg to 0T hamiltonians/ and systems/ directories. --- ipie/hamiltonians/__init__.py | 1 + ipie/hamiltonians/tests/ueg_test.py | 73 +++ ipie/{thermal => }/hamiltonians/ueg.py | 0 ipie/hamiltonians/utils.py | 10 + ipie/systems/__init__.py | 1 + ipie/systems/tests/test_ueg.py | 143 ++++++ ipie/{thermal/system => systems}/ueg.py | 2 - ipie/systems/utils.py | 8 + ipie/thermal/hamiltonians/_generic.py | 320 ------------- ipie/thermal/hamiltonians/utils.py | 50 --- ipie/thermal/propagation/planewave.py | 4 +- ipie/thermal/qmc/thermal_afqmc.py | 4 +- ipie/thermal/system/utils.py | 45 -- ipie/thermal/walkers/handler.py | 2 +- ipie/thermal/walkers/thermal.py | 567 ------------------------ ipie/thermal/walkers/uhf_walkers.py | 168 ------- 16 files changed, 241 insertions(+), 1157 deletions(-) create mode 100644 ipie/hamiltonians/tests/ueg_test.py rename ipie/{thermal => }/hamiltonians/ueg.py (100%) create mode 100644 ipie/systems/tests/test_ueg.py rename ipie/{thermal/system => systems}/ueg.py (99%) delete mode 100644 ipie/thermal/hamiltonians/_generic.py delete mode 100644 ipie/thermal/hamiltonians/utils.py delete mode 100644 ipie/thermal/system/utils.py delete mode 100644 ipie/thermal/walkers/thermal.py diff --git a/ipie/hamiltonians/__init__.py b/ipie/hamiltonians/__init__.py index c2aa068f..db8dba3f 100644 --- a/ipie/hamiltonians/__init__.py +++ b/ipie/hamiltonians/__init__.py @@ -18,3 +18,4 @@ from .generic_base import GenericBase from .generic import Generic +from .ueg import UEG diff --git a/ipie/hamiltonians/tests/ueg_test.py b/ipie/hamiltonians/tests/ueg_test.py new file mode 100644 index 00000000..4755807f --- /dev/null +++ b/ipie/hamiltonians/tests/ueg_test.py @@ -0,0 +1,73 @@ +import pytest +import numpy +from ipie.utils.linalg import modified_cholesky +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol + +# TODO: write UEG test + +@pytest.mark.unit +def test_real_modified_cholesky(): + numpy.random.seed(7) + nmo = 13 + nelec = (4, 3) + # ERI is already in the right form for cholesky decomposition + _, _, _, eri = generate_hamiltonian(nmo, nelec, cplx=False, sym=8) + + eri = eri.reshape((nmo**2, nmo**2)).T + chol = modified_cholesky(eri, tol=1e-8, verbose=False, cmax=30) + nchol = chol.shape[0] + + chol = chol.reshape((nchol, nmo**2)) + eri_chol = chol.T @ chol.conj() + numpy.testing.assert_allclose(eri_chol, eri, atol=1e-8) + + +@pytest.mark.unit +def test_complex_modified_cholesky(): + numpy.random.seed(7) + nmo = 13 + nelec = (4, 3) + # ERI is already in the right form for cholesky decomposition + _, _, _, eri = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) + + eri = eri.transpose((0, 1, 3, 2)) + eri = eri.reshape((nmo**2, nmo**2)) + chol = modified_cholesky(eri, tol=1e-8, verbose=False, cmax=30) + nchol = chol.shape[0] + + chol = modified_cholesky(eri, tol=1e-8, verbose=False, cmax=30) + nchol = chol.shape[0] + + chol = chol.reshape((nchol, nmo**2)) + eri_chol = chol.T @ chol.conj() + numpy.testing.assert_allclose(eri_chol, eri, atol=1e-8) + + +@pytest.mark.unit +def test_complex_hamiltonian(): + numpy.random.seed(7) + nmo = 13 + nelec = (4, 3) + h1e, chol, nuc, eri = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) + nchol = chol.shape[0] + chol = chol.reshape((nchol, nmo**2)).T.copy() + ham = GenericComplexChol(numpy.array([h1e, h1e], dtype=h1e.dtype), chol, nuc, verbose=True) + + +@pytest.mark.unit +def test_real_hamiltonian(): + numpy.random.seed(7) + nmo = 13 + nelec = (4, 3) + h1e, chol, nuc, eri = generate_hamiltonian(nmo, nelec, cplx=False, sym=8) + nchol = chol.shape[0] + chol = chol.reshape((nchol, nmo**2)).T.copy() + ham = GenericRealChol(numpy.array([h1e, h1e], dtype=h1e.dtype), chol, nuc, verbose=True) + + +if __name__ == "__main__": + test_real_modified_cholesky() + test_complex_modified_cholesky() + test_complex_hamiltonian() + test_real_hamiltonian() diff --git a/ipie/thermal/hamiltonians/ueg.py b/ipie/hamiltonians/ueg.py similarity index 100% rename from ipie/thermal/hamiltonians/ueg.py rename to ipie/hamiltonians/ueg.py diff --git a/ipie/hamiltonians/utils.py b/ipie/hamiltonians/utils.py index 6c7e7b4f..ca033852 100644 --- a/ipie/hamiltonians/utils.py +++ b/ipie/hamiltonians/utils.py @@ -22,7 +22,9 @@ import numpy from ipie.systems.generic import Generic as SysGeneric +from ipie.systems.ueg import UEG as SysUEG from ipie.hamiltonians.generic import Generic, construct_h1e_mod, read_integrals +from ipie.hamiltonians.ueg import UEG from ipie.utils.io import get_input_value from ipie.utils.mpi import get_shared_array, have_shared_mem from ipie.utils.pack_numba import pack_cholesky @@ -98,6 +100,14 @@ def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): ecore=enuc, verbose=verbose, ) + + elif isinstance(system, SysUEG): + ham = UEG( + system, + ham_opts, + verbose=verbose, + ) + else: if comm.rank == 0: print(f"# Error: unrecognized hamiltonian name {ham_opts['name']}.") diff --git a/ipie/systems/__init__.py b/ipie/systems/__init__.py index 7c4485e6..cccf70de 100644 --- a/ipie/systems/__init__.py +++ b/ipie/systems/__init__.py @@ -17,3 +17,4 @@ # from .generic import Generic +from .ueg import UEG diff --git a/ipie/systems/tests/test_ueg.py b/ipie/systems/tests/test_ueg.py new file mode 100644 index 00000000..86adfa30 --- /dev/null +++ b/ipie/systems/tests/test_ueg.py @@ -0,0 +1,143 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + +# TODO: write UEG test + +import os +import tempfile + +import numpy +import pytest + +from ipie.config import MPI +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.hamiltonians.utils import get_generic_integrals +from ipie.systems.generic import Generic +from ipie.utils.testing import generate_hamiltonian + + +@pytest.mark.unit +def test_real(): + numpy.random.seed(7) + nmo = 17 + nelec = (4, 3) + h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) + sys = Generic(nelec=nelec) + ham = HamGeneric( + h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nmo * nmo)).T.copy(), + ecore=enuc, + ) + assert sys.nup == 4 + assert sys.ndown == 3 + assert numpy.trace(h1e) == pytest.approx(9.38462274882365) + + +@pytest.mark.unit +def test_complex(): + numpy.random.seed(7) + nmo = 17 + nelec = (5, 3) + h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) + sys = Generic(nelec=nelec) + ham = HamGeneric( + h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nmo * nmo)).T.copy(), + ecore=enuc, + ) + assert sys.nup == 5 + assert sys.ndown == 3 + assert ham.nbasis == 17 + + +# @pytest.mark.unit +# def test_write(): +# numpy.random.seed(7) +# nmo = 13 +# nelec = (4, 3) +# h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) +# sys = Generic(nelec=nelec) +# ham = HamGeneric( +# h1e=numpy.array([h1e, h1e]), +# chol=chol.reshape((-1, nmo * nmo)).T.copy(), +# ecore=enuc, +# ) +# ham.write_integrals(nelec, filename="hamil.test_write.h5") + + +@pytest.mark.unit +def test_read(): + numpy.random.seed(7) + nmo = 13 + nelec = (4, 3) + h1e_, chol_, enuc_, eri_ = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) + from ipie.utils.io import write_qmcpack_dense + + chol_ = chol_.reshape((-1, nmo * nmo)).T.copy() + with tempfile.NamedTemporaryFile() as tmpf: + filename = tmpf.name + write_qmcpack_dense(h1e_, chol_, nelec, nmo, enuc=enuc_, filename=filename, real_chol=False) + nup, ndown = nelec + comm = None + hcore, chol, h1e_mod, enuc = get_generic_integrals(filename, comm=comm, verbose=False) + sys = Generic(nelec=nelec) + ham = HamGeneric(h1e=hcore, chol=chol, ecore=enuc) + assert ham.ecore == pytest.approx(0.4392816555570978) + assert ham.chol.shape == chol_.shape # now two are transposed + assert len(ham.H1.shape) == 3 + assert numpy.linalg.norm(ham.H1[0] - h1e_) == pytest.approx(0.0) + assert numpy.linalg.norm(ham.chol - chol_) == pytest.approx(0.0) # now two are transposed + + +@pytest.mark.unit +def test_shmem(): + numpy.random.seed(7) + nmo = 13 + nelec = (4, 3) + comm = MPI.COMM_WORLD + h1e_, chol_, enuc_, eri_ = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) + from ipie.utils.io import write_qmcpack_dense + + with tempfile.NamedTemporaryFile() as tmpf: + chol_ = chol_.reshape((-1, nmo * nmo)).T.copy() + filename = tmpf.name + write_qmcpack_dense(h1e_, chol_, nelec, nmo, enuc=enuc_, filename=filename, real_chol=False) + from ipie.utils.mpi import get_shared_comm + + shared_comm = get_shared_comm(comm, verbose=True) + hcore, chol, _, enuc = get_generic_integrals(filename, comm=shared_comm, verbose=False) + # system = Generic(h1e=hcore, chol=chol, ecore=enuc, + # h1e_mod=h1e_mod, nelec=nelec, + # verbose=False) + # print("hcore.shape = ", hcore.shape) + sys = Generic(nelec=nelec) + ham = HamGeneric(h1e=hcore, chol=chol.copy(), ecore=enuc) + + assert ham.ecore == pytest.approx(0.4392816555570978) + assert ham.chol.shape == chol_.shape # now two are transposed + assert len(ham.H1.shape) == 3 + assert numpy.linalg.norm(ham.H1[0] - h1e_) == pytest.approx(0.0) + assert numpy.linalg.norm(ham.chol - chol_) == pytest.approx(0.0) # now two are transposed + + +if __name__ == "__main__": + test_real() + test_complex() + # test_write() + test_read() + test_shmem() diff --git a/ipie/thermal/system/ueg.py b/ipie/systems/ueg.py similarity index 99% rename from ipie/thermal/system/ueg.py rename to ipie/systems/ueg.py index 493d4917..4162ded3 100644 --- a/ipie/thermal/system/ueg.py +++ b/ipie/systems/ueg.py @@ -1,8 +1,6 @@ import math import numpy - - class UEG(object): """UEG system class (integrals read from fcidump) Parameters diff --git a/ipie/systems/utils.py b/ipie/systems/utils.py index d1fe1912..6425d871 100644 --- a/ipie/systems/utils.py +++ b/ipie/systems/utils.py @@ -19,6 +19,7 @@ import sys from ipie.systems.generic import Generic +from ipie.systems.ueg import UEG def get_system(sys_opts=None, verbose=0, comm=None): @@ -38,17 +39,24 @@ def get_system(sys_opts=None, verbose=0, comm=None): """ assert sys_opts is not None sys_type = sys_opts.get("name") + if sys_type is None or sys_type == "Generic": nup, ndown = sys_opts.get("nup"), sys_opts.get("ndown") if nup is None or ndown is None: if comm.rank == 0: print("# Error: Number of electrons not specified.") sys.exit() + nelec = (nup, ndown) system = Generic(nelec, verbose) + + elif sys_type == "UEG": + system = UEG(sys_opts, verbose) + else: if comm.rank == 0: print(f"# Error: unrecognized system name {sys_type}.") + raise ValueError return system diff --git a/ipie/thermal/hamiltonians/_generic.py b/ipie/thermal/hamiltonians/_generic.py deleted file mode 100644 index e361deb5..00000000 --- a/ipie/thermal/hamiltonians/_generic.py +++ /dev/null @@ -1,320 +0,0 @@ -# Copyright 2022 The ipie Developers. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Authors: Fionn Malone -# Joonho Lee -# - -import numpy - -array = numpy.array -zeros = numpy.zeros -einsum = numpy.einsum -isrealobj = numpy.isrealobj - - -from ipie.utils.io import ( - from_qmcpack_dense, - from_qmcpack_sparse, - write_hamiltonian, - read_hamiltonian, -) - - -class Generic(object): - """Ab-initio Hamiltonian. - - Can be created by either passing the one and two electron integrals directly - or initialised from integrals stored in QMCPACK hdf5 format. If initialising - from file the `inputs' optional dictionary should be populated. - - Parameters - ---------- - h1e : :class:`numpy.ndarray' - One-electron integrals. Optional. Default: None. - chol : :class:`numpy.ndarray' - Factorized 2-electron integrals (L_{ik,n}) of shape (nbasis^2, nchol). - Optional. Default: None. - ecore : float - Core energy. - options : dict - Input options defined below. - integrals : string - Path to file containing one- and two-electron integrals in QMCPACK - format. - verbose : bool - Print extra information. - - Attributes - ---------- - H1 : :class:`numpy.ndarray` - One-body part of the Hamiltonian. Spin-dependent by default. - ecore : float - Core contribution to the total energy. - h1e_mod : :class:`numpy.ndarray` - Modified one-body Hamiltonian. - chol_vecs : :class:`numpy.ndarray` - Cholesky vectors. [M^2, nchol] - nchol : int - Number of cholesky vectors. - nfields : int - Number of auxiliary fields required. - sparse_cutoff : float - Screen out integrals below this threshold. Optional. Default 0. - cplx_chol : bool - Force setting of interpretation of cholesky decomposition. Optional. - Default False, i.e. real/complex factorization determined from cholesky - integrals. - """ - - def __init__( - self, - h1e, - chol, - ecore, - h1e_mod=None, - chol_packed=None, - options={}, - verbose=False, - write_ints=False, - ): - if verbose: - print("# Parsing input options for hamiltonians.Generic.") - self.name = "Generic" - self.verbose = verbose - self.exact_eri = options.get("exact_eri", False) - self.mixed_precision = options.get("mixed_precision", False) - self.density_diff = options.get("density_diff", False) - self.symmetry = options.get("symmetry", True) - self.chunked = False # chunking disabled by default - - self.ecore = ecore - self.chol_vecs = chol # [M^2, nchol] - self.chol = self.chol_vecs - - if self.symmetry: - self.chol_packed = chol_packed - nbsf = h1e.shape[1] - self.sym_idx = numpy.triu_indices(nbsf) - self.sym_idx_i = self.sym_idx[0].copy() - self.sym_idx_j = self.sym_idx[1].copy() - else: - self.chol_packed = None # [M*(M+1)/2, nchol] if used - self.sym_idx = None - - # unncessary booleans for legacy compatibility - self.control_variate = False - self.stochastic_ri = False - self.pno = False - - if self.mixed_precision: - if not self.density_diff: - self.density_diff = True - if self.verbose: - print("# density_diff is switched on for more stable mixed precision") - if self.symmetry: - self.chol_packed = self.chol_packed.astype(numpy.float32) - else: - self.chol_vecs = self.chol_vecs.astype(numpy.float32) # [M^2, nchol] - - if self.exact_eri: - if self.verbose: - print("# exact_eri is used for the local energy evaluation") - - if self.density_diff: - if self.verbose: - print("# density_diff is used for the force bias and the local energy evaluation") - - if self.mixed_precision: - if self.verbose: - print("# mixed_precision is used for the propagation") - - if isrealobj(self.chol_vecs.dtype): - if verbose: - print("# Found real Choleksy integrals.") - self.cplx_chol = False - else: - if verbose: - print("# Found complex Cholesky integrals.") - self.cplx_chol = True - - self.H1 = array(h1e) - self.nbasis = h1e.shape[-1] - - mem = self.chol_vecs.nbytes / (1024.0**3) - self.sparse = False - if verbose: - print("# Number of orbitals: %d" % self.nbasis) - print(f"# Approximate memory required by Cholesky vectors {mem:f} GB") - self.nchol = self.chol_vecs.shape[-1] - if h1e_mod is not None: - self.h1e_mod = h1e_mod - else: - h1e_mod = zeros(self.H1.shape, dtype=self.H1.dtype) - construct_h1e_mod(self.chol_vecs, self.H1, h1e_mod) - self.h1e_mod = h1e_mod - - # For consistency - self.vol = 1.0 - self.nfields = self.nchol - - if verbose: - print("# Number of Cholesky vectors: %d" % (self.nchol)) - print("# Number of fields: %d" % (self.nfields)) - if write_ints: - self.write_integrals() - if verbose: - print("# Finished setting up hamiltonians.Generic object.") - - def hijkl(self, i, j, k, l): - ik = i * self.nbasis + k - jl = j * self.nbasis + l - return numpy.dot(self.chol_vecs[ik], self.chol_vecs[jl]) - - def write_integrals(self, nelec, filename="hamil.h5"): - write_hamiltonian( - self.H1[0], - self.chol_vecs.T.reshape((self.nchol, self.nbasis, self.nbasis)), - self.ecore, - filename=filename, - ) - - def chunk(self, handler, verbose=False): - self.chunked = True # Boolean to indicate that chunked cholesky is available - - chol_idxs = [i for i in range(self.nchol)] - self.chol_idxs_chunk = handler.scatter_group(chol_idxs) - - if self.symmetry: - # if handler.srank == 0: # creating copies for every rank = 0!!!! - self.chol_packed = self.chol_packed.T.copy() # [chol, M^2] - handler.comm.barrier() - - self.chol_packed_chunk = handler.scatter_group(self.chol_packed) # distribute over chol - - # if handler.srank == 0: - self.chol_packed = self.chol_packed.T.copy() # [M^2, chol] - handler.comm.barrier() - - self.chol_packed_chunk = self.chol_packed_chunk.T.copy() # [M^2, chol_chunk] - - tot_size = handler.allreduce_group(self.chol_packed_chunk.size) - - assert self.chol_packed.size == tot_size - else: - # if handler.comm.rank == 0: - self.chol_vecs = self.chol_vecs.T.copy() # [chol, M^2] - handler.comm.barrier() - - self.chol_vecs_chunk = handler.scatter_group(self.chol_vecs) # distribute over chol - - # if handler.comm.rank == 0: - self.chol_vecs = self.chol_vecs.T.copy() # [M^2, chol] - handler.comm.barrier() - - self.chol_vecs_chunk = self.chol_vecs_chunk.T.copy() # [M^2, chol_chunk] - - tot_size = handler.allreduce_group(self.chol_vecs_chunk.size) - assert self.chol_vecs.size == tot_size - - # This function casts relevant member variables into cupy arrays - # Keeping this specific for the moment as too much logic. - # A sign it should be split up.. - def cast_to_cupy(self, verbose=False): - import cupy - - size = self.H1.size + self.h1e_mod.size - if self.chunked: - if self.symmetry: - size += self.chol_packed_chunk.size - else: - size += self.chol_vecs_chunk.size - else: - if self.symmetry: - size += self.chol_packed.size - else: - size += self.chol_vecs.size - - if self.symmetry: - size += self.sym_idx_i.size - size += self.sym_idx_j.size - - if verbose: - expected_bytes = size * 8.0 # float64 - print( - "# hamiltonians.generic: expected to allocate {:4.3f} GB".format( - expected_bytes / 1024**3 - ) - ) - - self.H1 = cupy.asarray(self.H1) - self.h1e_mod = cupy.asarray(self.h1e_mod) - if self.symmetry: - self.sym_idx_i = cupy.asarray(self.sym_idx_i) - self.sym_idx_j = cupy.asarray(self.sym_idx_j) - - if self.chunked: - if self.symmetry: - self.chol_packed_chunk = cupy.asarray(self.chol_packed_chunk) - else: - self.chol_vecs_chunk = cupy.asarray(self.chol_vecs_chunk) - else: - if self.symmetry: - self.chol_packed = cupy.asarray(self.chol_packed) - else: - self.chol_vecs = cupy.asarray(self.chol_vecs) - - free_bytes, total_bytes = cupy.cuda.Device().mem_info - used_bytes = total_bytes - free_bytes - if verbose: - print( - "# hamiltonians.Generic: using {:4.3f} GB out of {:4.3f} GB memory on GPU".format( - used_bytes / 1024**3, total_bytes / 1024**3 - ) - ) - - -def read_integrals(integral_file): - try: - (h1e, schol_vecs, ecore, nbasis, nup, ndown) = from_qmcpack_sparse(integral_file) - chol_vecs = schol_vecs.toarray() - return h1e, chol_vecs, ecore - except KeyError: - pass - try: - (h1e, chol_vecs, ecore, nbasis, nup, ndown) = from_qmcpack_dense(integral_file) - return h1e, chol_vecs, ecore - except KeyError: - pass - try: - (h1e, chol_vecs, ecore) = read_hamiltonian(integral_file) - naux = chol_vecs.shape[0] - nbsf = chol_vecs.shape[-1] - return h1e, chol_vecs.T.reshape((nbsf, nbsf, naux)), ecore - except KeyError: - return None - - -def construct_h1e_mod(chol, h1e, h1e_mod): - # Subtract one-body bit following reordering of 2-body operators. - # Eqn (17) of [Motta17]_ - nbasis = h1e.shape[-1] - nchol = chol.shape[-1] - chol_view = chol.reshape((nbasis, nbasis * nchol)) - # assert chol_view.__array_interface__['data'][0] == chol.__array_interface__['data'][0] - v0 = 0.5 * numpy.dot( - chol_view, chol_view.T - ) # einsum('ikn,jkn->ij', chol_3, chol_3, optimize=True) - h1e_mod[0, :, :] = h1e[0] - v0 - h1e_mod[1, :, :] = h1e[1] - v0 diff --git a/ipie/thermal/hamiltonians/utils.py b/ipie/thermal/hamiltonians/utils.py deleted file mode 100644 index 42186c24..00000000 --- a/ipie/thermal/hamiltonians/utils.py +++ /dev/null @@ -1,50 +0,0 @@ -import sys -import time - -from ipie.hamiltonians.utils import get_generic_integrals -from ipie.thermal.hamiltonians._generic import Generic -from ipie.thermal.hamiltonians.ueg import UEG - - -def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): - """Wrapper to select hamiltonian class - - Parameters - ---------- - ham_opts : dict - Hamiltonian input options. - verbose : bool - Output verbosity. - - Returns - ------- - ham : object - Hamiltonian class. - """ - if ham_opts["name"] == "UEG": - ham = UEG(system, ham_opts, verbose) - elif ham_opts["name"] == "Generic": - filename = ham_opts.get("integrals", None) - if filename is None: - if comm.rank == 0: - print("# Error: integrals not specfied.") - sys.exit() - start = time.time() - hcore, chol, h1e_mod, enuc = get_generic_integrals(filename, comm=comm, verbose=verbose) - if verbose: - print(f"# Time to read integrals: {time.time() - start:.6f}") - ham = Generic( - h1e=hcore, - chol=chol, - ecore=enuc, - h1e_mod=h1e_mod, - options=ham_opts, - verbose=verbose, - ) - else: - if comm.rank == 0: - print(f"# Error: unrecognized hamiltonian name {ham_opts['name']}.") - sys.exit() - ham = None - - return ham diff --git a/ipie/thermal/propagation/planewave.py b/ipie/thermal/propagation/planewave.py index ed68f95a..d8e330b9 100644 --- a/ipie/thermal/propagation/planewave.py +++ b/ipie/thermal/propagation/planewave.py @@ -618,14 +618,14 @@ def propagate_greens_function(self, walker): def unit_test(): import cProfile - from ipie.estimators.pw_fft import local_energy_pw_fft + from ipie.legacy.estimators.pw_fft import local_energy_pw_fft from ipie.legacy.estimators.ueg import local_energy_ueg from ipie.legacy.qmc.options import QMCOpts from ipie.legacy.systems.ueg import UEG from ipie.legacy.trial_density_matrices.onebody import OneBody from ipie.legacy.walkers.thermal import ThermalWalker from ipie.qmc.comm import FakeComm - from ipie.systems.pw_fft import PW_FFT + from ipie.legacy.systems.pw_fft import PW_FFT beta = 16.0 dt = 0.005 diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index 2b68c801..98603264 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -4,13 +4,13 @@ from ipie.thermal.estimators.handler import Estimators from ipie.thermal.estimators.local_energy import local_energy -from ipie.thermal.hamiltonians.utils import get_hamiltonian +from ipie.hamiltonians.utils import get_hamiltonian from ipie.thermal.propagation.utils import get_propagator from ipie.thermal.trial.utils import get_trial_density_matrix from ipie.thermal.walkers.handler import Walkers from ipie.qmc.options import QMCOpts from ipie.qmc.utils import set_rng_seed -from ipie.thermal.system.utils import get_system +from ipie.systems.utils import get_system from ipie.utils.io import get_input_value, to_json from ipie.utils.misc import get_git_info, print_env_info from ipie.utils.mpi import get_shared_comm diff --git a/ipie/thermal/system/utils.py b/ipie/thermal/system/utils.py deleted file mode 100644 index d5fdafa9..00000000 --- a/ipie/thermal/system/utils.py +++ /dev/null @@ -1,45 +0,0 @@ -import sys - - -from ipie.thermal.system.ueg import UEG -from ipie.systems.generic import Generic - - -def get_system(sys_opts=None, verbose=0, comm=None): - """Wrapper to select system class - - Parameters - ---------- - sys_opts : dict - System input options. - verbose : bool - Output verbosity. - - Returns - ------- - system : object - System class. - """ - if not ("name" in sys_opts): - sys_opts["name"] = "Generic" - - if sys_opts["name"] == "UEG": - system = UEG(sys_opts, verbose) - elif ( - sys_opts["name"] == "Hubbard" - or sys_opts["name"] == "HubbardHolstein" - or sys_opts["name"] == "Generic" - ): - nup, ndown = sys_opts.get("nup"), sys_opts.get("ndown") - if nup is None or ndown is None: - if comm.rank == 0: - print("# Error: Number of electrons not specified.") - sys.exit() - nelec = (nup, ndown) - system = Generic(nelec, verbose) - else: - if comm.rank == 0: - print(f"# Error: unrecognized system name {sys_opts['name']}.") - sys.exit() - - return system diff --git a/ipie/thermal/walkers/handler.py b/ipie/thermal/walkers/handler.py index 35e985be..c247cdd7 100644 --- a/ipie/thermal/walkers/handler.py +++ b/ipie/thermal/walkers/handler.py @@ -5,7 +5,7 @@ import h5py import numpy -from ipie.thermal.walkers.thermal import ThermalWalker +from ipie.thermal.walkers.uhf_walkers import ThermalWalker from ipie.utils.io import get_input_value from ipie.utils.misc import update_stack diff --git a/ipie/thermal/walkers/thermal.py b/ipie/thermal/walkers/thermal.py deleted file mode 100644 index 3a3a57a9..00000000 --- a/ipie/thermal/walkers/thermal.py +++ /dev/null @@ -1,567 +0,0 @@ -import numpy -import scipy.linalg - -from ipie.thermal.estimators.local_energy import local_energy_G -from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number -from ipie.thermal.walkers.stack import PropagatorStack -from ipie.thermal.walkers.walker import Walker -from ipie.utils.misc import get_numeric_names, update_stack - - -class ThermalWalker(Walker): - def __init__(self, system, hamiltonian, trial, walker_opts={}, verbose=False): - Walker.__init__(self, system, hamiltonian, trial, walker_opts=walker_opts) - self.name = "ThermalWalker" - self.num_slices = trial.num_slices - dtype = numpy.complex128 - self.G = numpy.zeros(trial.dmat.shape, dtype=dtype) - self.Ghalf = None - self.nbasis = trial.dmat[0].shape[0] - self.stack_size = walker_opts.get("stack_size", None) - max_diff_diag = numpy.linalg.norm((numpy.diag(trial.dmat[0].diagonal()) - trial.dmat[0])) - if max_diff_diag < 1e-10: - self.diagonal_trial = True - if verbose: - print("# Trial density matrix is diagonal.") - else: - self.diagonal_trial = False - if verbose: - print("# Trial density matrix is not diagonal.") - - if self.stack_size == None: - self.stack_size = trial.stack_size - if (self.num_slices // self.stack_size) * self.stack_size != self.num_slices: - if verbose: - print("# Input stack size does not divide number of slices.") - self.stack_size = update_stack(self.stack_size, self.num_slices, verbose) - if self.stack_size > trial.stack_size: - if verbose: - print( - "# Walker stack size differs from that estimated from " "trial density matrix." - ) - print(f"# Be careful. cond(BT)**stack_size: {trial.cond ** self.stack_size:10.3e}.") - self.stack_length = self.num_slices // self.stack_size - if verbose: - print(f"# Walker stack size: {self.stack_size}") - - self.lowrank = walker_opts.get("low_rank", False) - self.lowrank_thresh = walker_opts.get("low_rank_thresh", 1e-6) - if verbose: - print(f"# Using low rank trick: {self.lowrank}") - self.stack = PropagatorStack( - self.stack_size, - trial.num_slices, - trial.dmat.shape[-1], - dtype, - trial.dmat, - trial.dmat_inv, - diagonal=self.diagonal_trial, - lowrank=self.lowrank, - thresh=self.lowrank_thresh, - ) - - # Initialise all propagators to the trial density matrix. - self.stack.set_all(trial.dmat) - self.greens_function_qr_strat(trial) - self.stack.G = self.G - self.M0 = numpy.array( - [ - scipy.linalg.det(self.G[0], check_finite=False), - scipy.linalg.det(self.G[1], check_finite=False), - ] - ) - self.stack.ovlp = numpy.array([1.0 / self.M0[0], 1.0 / self.M0[1]]) - - # # temporary storage for stacks... - I = numpy.identity(hamiltonian.nbasis, dtype=dtype) - One = numpy.ones(hamiltonian.nbasis, dtype=dtype) - self.Tl = numpy.array([I, I]) - self.Ql = numpy.array([I, I]) - self.Dl = numpy.array([One, One]) - self.Tr = numpy.array([I, I]) - self.Qr = numpy.array([I, I]) - self.Dr = numpy.array([One, One]) - - self.hybrid_energy = 0.0 - if verbose: - # def local_energy(self, system, two_rdm=None): - P = one_rdm_from_G(self.G) - eloc = local_energy_G(system, hamiltonian, self, P) - nav = particle_number(P) - print("# Initial walker energy: {} {} {}".format(*eloc)) - print(f"# Initial walker electron number: {nav}") - # self.buff_names = ['weight', 'G', 'unscaled_weight', 'phase', 'Tl', - # 'Ql', 'Dl', 'Tr', 'Qr', 'Dr', 'M0'] - self.buff_names, self.buff_size = get_numeric_names(self.__dict__) - # self.buff_size = (self.G.size+3+self.Tl.size+2+ - # self.Ql.size+self.Dl.size+self.Tr.size+self.Qr.size - # +self.Dr.size) - - def greens_function(self, trial, slice_ix=None, inplace=True): - if self.lowrank: - return self.stack.G - else: - return self.greens_function_qr_strat(trial, slice_ix=slice_ix, inplace=inplace) - - def greens_function_svd(self, trial, slice_ix=None, inplace=True): - if slice_ix == None: - slice_ix = self.stack.time_slice - bin_ix = slice_ix // self.stack.stack_size - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == self.stack.nbins: - bin_ix = -1 - if inplace: - G = None - else: - G = numpy.zeros(self.G.shape, self.G.dtype) - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} - # in stable way. Iteratively construct SVD decompositions starting - # from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) - (U1, S1, V1) = scipy.linalg.svd(B[spin]) - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) - T1 = numpy.dot(B[spin], U1) - # todo optimise - T2 = numpy.dot(T1, numpy.diag(S1)) - (U1, S1, V) = scipy.linalg.svd(T2) - V1 = numpy.dot(V, V1) - A = numpy.dot(U1.dot(numpy.diag(S1)), V1) - # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. - # Care needs to be taken when adding the identity matrix. - T3 = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) - (U2, S2, V2) = scipy.linalg.svd(T3) - U3 = numpy.dot(U1, U2) - D3 = numpy.diag(1.0 / S2) - V3 = numpy.dot(V2, V1) - # G(l) = (U3 S2 V3)^{-1} - # = V3^{\dagger} D3 U3^{\dagger} - if inplace: - # self.G[spin] = (V3inv).dot(U3.conj().T) - self.G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) - else: - # G[spin] = (V3inv).dot(U3.conj().T) - G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) - return G - - def greens_function_qr(self, trial, slice_ix=None, inplace=True): - if slice_ix == None: - slice_ix = self.stack.time_slice - - bin_ix = slice_ix // self.stack.stack_size - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == self.stack.nbins: - bin_ix = -1 - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} - # in stable way. Iteratively construct SVD decompositions starting - # from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) - (U1, V1) = scipy.linalg.qr(B[spin], pivoting=False, check_finite=False) - - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) - T1 = numpy.dot(B[spin], U1) - (U1, V) = scipy.linalg.qr(T1, pivoting=False, check_finite=False) - V1 = numpy.dot(V, V1) - - # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. - # Care needs to be taken when adding the identity matrix. - V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0])) - - T3 = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0]) - (U2, V2) = scipy.linalg.qr(T3, pivoting=False, check_finite=False) - - U3 = numpy.dot(U1, U2) - V3 = numpy.dot(V2, V1) - V3inv = scipy.linalg.solve_triangular(V3, numpy.identity(V3.shape[0])) - # G(l) = (U3 S2 V3)^{-1} - # = V3^{\dagger} D3 U3^{\dagger} - if inplace: - self.G[spin] = (V3inv).dot(U3.conj().T) - else: - G[spin] = (V3inv).dot(U3.conj().T) - return G - - def compute_left_right(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # right bit - # B(right) ... B(1) - if center_ix > 0: - # print ("center_ix > 0") - B = self.stack.get(0) - (self.Qr[spin], R1, P1) = scipy.linalg.qr( - B[spin], pivoting=True, check_finite=False - ) - # Form D matrices - self.Dr[spin] = R1.diagonal() - D1inv = 1.0 / R1.diagonal() - self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) - # now permute them - self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] - - for ix in range(1, center_ix): - B = self.stack.get(ix) - C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) - (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = 1.0 / R1.diagonal() - self.Dr[spin] = R1.diagonal() - # smarter permutation - # D^{-1} * R - tmp = numpy.einsum("i,ij->ij", D1inv, R1) - # D^{-1} * R * P^T - tmp[:, P1] = tmp[:, range(self.nbasis)] - # D^{-1} * R * P^T * T - self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) - - # left bit - # B(l) ... B(left) - if center_ix < self.stack.nbins - 1: - # print("center_ix < self.stack.nbins-1 first") - # We will assume that B matrices are all diagonal for left.... - B = self.stack.get(center_ix + 1) - self.Dl[spin] = B[spin].diagonal() - D1inv = 1.0 / B[spin].diagonal() - self.Ql[spin] = numpy.identity(B[spin].shape[0]) - self.Tl[spin] = numpy.identity(B[spin].shape[0]) - - for ix in range(center_ix + 2, self.stack.nbins): - # print("center_ix < self.stack.nbins-1 first inner loop") - B = self.stack.get(ix) - C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) - self.Dl[spin] = C2 - - def compute_right(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # right bit - # B(right) ... B(1) - if center_ix > 0: - # print ("center_ix > 0") - B = self.stack.get(0) - (self.Qr[spin], R1, P1) = scipy.linalg.qr( - B[spin], pivoting=True, check_finite=False - ) - # Form D matrices - self.Dr[spin] = R1.diagonal() - D1inv = 1.0 / R1.diagonal() - self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) - # now permute them - self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] - - for ix in range(1, center_ix): - B = self.stack.get(ix) - C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) - (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = 1.0 / R1.diagonal() - self.Dr[spin] = R1.diagonal() - # smarter permutation - # D^{-1} * R - tmp = numpy.einsum("i,ij->ij", D1inv, R1) - # D^{-1} * R * P^T - tmp[:, P1] = tmp[:, range(self.nbasis)] - # D^{-1} * R * P^T * T - self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) - - def compute_left(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # left bit - # B(l) ... B(left) - if center_ix < self.stack.nbins - 1: - # print("center_ix < self.stack.nbins-1 first") - # We will assume that B matrices are all diagonal for left.... - B = self.stack.get(center_ix + 1) - self.Dl[spin] = B[spin].diagonal() - self.Ql[spin] = numpy.identity(B[spin].shape[0]) - self.Tl[spin] = numpy.identity(B[spin].shape[0]) - - for ix in range(center_ix + 2, self.stack.nbins): - # print("center_ix < self.stack.nbins-1 first inner loop") - B = self.stack.get(ix) - C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) - self.Dl[spin] = C2.diagonal() - - def greens_function_left_right(self, center_ix, inplace=False, thresh=1e-6): - assert self.diagonal_trial - - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - - mL = self.G.shape[1] - mR = self.G.shape[1] - mT = self.G.shape[1] - - Bc = self.stack.get(center_ix) - - nbsf = Bc.shape[1] - - # It goes to right to left and we sample (I + L*B*R) in the end - for spin in [0, 1]: - if center_ix > 0: # there exists right bit - mR = len(self.Dr[spin][numpy.abs(self.Dr[spin]) > thresh]) - - Ccr = numpy.einsum( - "ij,j->ij", - numpy.dot(Bc[spin], self.Qr[spin][:, :mR]), - self.Dr[spin][:mR], - ) # N x mR - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) - Dlcr = Rlcr[:mR, :mR].diagonal() # mR - Dinv = 1.0 / Dlcr # mR - tmp = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :mR]) # mR, mR x mR -> mR x mR - tmp[:, Plcr] = tmp[:, range(mR)] - Tlcr = numpy.dot(tmp, self.Tr[spin][:mR, :]) # mR x N - else: - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) - # Form D matrices - Dlcr = Rlcr.diagonal() - - mR = len(Dlcr[numpy.abs(Dlcr) > thresh]) - - Dinv = 1.0 / Rlcr.diagonal() - Tlcr = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :]) # mR x N - Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] # mR x N - - if center_ix < self.stack.nbins - 1: # there exists left bit - # assume left stack is all diagonal (i.e., QDT = diagonal -> Q and T are identity) - Clcr = numpy.einsum( - "i,ij->ij", - self.Dl[spin], - numpy.einsum("ij,j->ij", Qlcr[:, :mR], Dlcr[:mR]), - ) # N x mR - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr( - Clcr, pivoting=True, check_finite=False - ) # N x N, mR x mR - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Dlcr - - mT = len(Dlcr[numpy.abs(Dlcr) > thresh]) - - tmp = numpy.einsum("i,ij->ij", Dinv[:mT], Rlcr[:mT, :]) - tmp[:, Plcr] = tmp[:, range(mR)] # mT x mR - Tlcr = numpy.dot(tmp, Tlcr) # mT x N - else: - mT = mR - - # D = Ds Db^{-1} - Db = numpy.zeros(mT, Bc[spin].dtype) - Ds = numpy.zeros(mT, Bc[spin].dtype) - for i in range(mT): - absDlcr = abs(Dlcr[i]) - if absDlcr > 1.0: - Db[i] = 1.0 / absDlcr - Ds[i] = numpy.sign(Dlcr[i]) - else: - Db[i] = 1.0 - Ds[i] = Dlcr[i] - - if mT == nbsf: # No need for Woodbury - T1inv = scipy.linalg.inv(Tlcr, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) - Cinv = scipy.linalg.inv(C, check_finite=False) - - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), - numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), - ) - # return # This seems to change the answer WHY?? - else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), - numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), - ) - else: # Use Woodbury - TQ = Tlcr.dot(Qlcr[:, :mT]) - TQinv = scipy.linalg.inv(TQ, check_finite=False) - tmp = scipy.linalg.inv( - numpy.einsum("ij,j->ij", TQinv, Db) + numpy.diag(Ds), - check_finite=False, - ) - A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv)) - if inplace: - self.G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( - numpy.diag(Dlcr[:mT]) - ).dot(A).dot(Tlcr) - else: - G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( - numpy.diag(Dlcr[:mT]) - ).dot(A).dot(Tlcr) - # print(mR,mT,nbsf) - # print("ref: mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) - return G - - def greens_function_left_right_no_truncation(self, center_ix, inplace=False): - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - - Bc = self.stack.get(center_ix) - for spin in [0, 1]: - if center_ix > 0: # there exists right bit - # print("center_ix > 0 second") - Ccr = numpy.einsum("ij,j->ij", numpy.dot(Bc[spin], self.Qr[spin]), self.Dr[spin]) - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) - tmp[:, Plcr] = tmp[:, range(self.nbasis)] - Tlcr = numpy.dot(tmp, self.Tr[spin]) - else: - # print("center_ix > 0 else second") - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) - # Form D matrices - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - Tlcr = numpy.einsum("i,ij->ij", Dinv, Rlcr) - Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] - - if center_ix < self.stack.nbins - 1: # there exists left bit - # print("center_ix < self.stack.nbins-1 second") - # assume left stack is all diagonal - Clcr = numpy.einsum("i,ij->ij", self.Dl[spin], numpy.einsum("ij,j->ij", Qlcr, Dlcr)) - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Clcr, pivoting=True, check_finite=False) - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - - tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) - tmp[:, Plcr] = tmp[:, range(self.nbasis)] - Tlcr = numpy.dot(tmp, Tlcr) - - # print("Dlcr = {}".format(Dlcr)) - - # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T - # Write D = Db^{-1} Ds - # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T - Db = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) - Ds = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) - for i in range(Db.shape[0]): - absDlcr = abs(Dlcr[i]) - if absDlcr > 1.0: - Db[i] = 1.0 / absDlcr - Ds[i] = numpy.sign(Dlcr[i]) - else: - Db[i] = 1.0 - Ds[i] = Dlcr[i] - - T1inv = scipy.linalg.inv(Tlcr, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) - Cinv = scipy.linalg.inv(C, check_finite=False) - - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) - ) - else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) - ) - return G - - def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - if slice_ix == None: - slice_ix = self.stack.time_slice - - bin_ix = slice_ix // self.stack.stack_size - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == self.stack.nbins: - bin_ix = -1 - - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in - # stable way. Iteratively construct column pivoted QR decompositions - # (A = QDT) starting from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) - - (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) - # Form D matrices - D1 = numpy.diag(R1.diagonal()) - D1inv = numpy.diag(1.0 / R1.diagonal()) - T1 = numpy.einsum("ii,ij->ij", D1inv, R1) - # permute them - T1[:, P1] = T1[:, range(self.nbasis)] - - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) - C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) - (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = numpy.diag(1.0 / R1.diagonal()) - D1 = numpy.diag(R1.diagonal()) - tmp = numpy.einsum("ii,ij->ij", D1inv, R1) - tmp[:, P1] = tmp[:, range(self.nbasis)] - T1 = numpy.dot(tmp, T1) - - # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T - # Write D = Db^{-1} Ds - # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T - Db = numpy.zeros(B[spin].shape, B[spin].dtype) - Ds = numpy.zeros(B[spin].shape, B[spin].dtype) - for i in range(Db.shape[0]): - absDlcr = abs(Db[i, i]) - if absDlcr > 1.0: - Db[i, i] = 1.0 / absDlcr - Ds[i, i] = numpy.sign(D1[i, i]) - else: - Db[i, i] = 1.0 - Ds[i, i] = D1[i, i] - - T1inv = scipy.linalg.inv(T1, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("ii,ij->ij", Db, Q1.conj().T), T1inv) + Ds - Cinv = scipy.linalg.inv(C, check_finite=False) - - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) - ) - else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) - ) - return G - - -# def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): -# def local_energy(self, system, two_rdm=None): -# rdm = one_rdm_from_G(self.G) -# return local_energy_G(system, hamiltonian, self, rdm) - diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index b1d357fc..286924ae 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -564,171 +564,3 @@ def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): # def local_energy(self, system, two_rdm=None): # rdm = one_rdm_from_G(self.G) # return local_energy_G(system, hamiltonian, self, rdm) - - -def unit_test(): - from ipie.legacy.systems.ueg import UEG - from ipie.legacy.thermal_propagation.planewave import PlaneWave - from ipie.legacy.trial_density_matrices.onebody import OneBody - from ipie.legacy.qmc.options import QMCOpts - - inputs = { - "nup": 1, - "ndown": 1, - "rs": 1.0, - "ecut": 0.5, - "name": "one_body", - "mu": 1.94046021, - "beta": 0.5, - "dt": 0.05, - "optimised": True, - } - beta = inputs["beta"] - dt = inputs["dt"] - - system = UEG(inputs, verbose=False) - - qmc = QMCOpts(inputs, system, True) - trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False) - - walker = ThermalWalker(inputs, system, trial, True) - # walker.greens_function(trial) - E, T, V = walker.local_energy(system) - numpy.random.seed(0) - inputs["optimised"] = False - propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) - - propagator.propagate_walker_free(system, walker, trial, False) - - Gold = walker.G[0].copy() - - system = UEG(inputs, verbose=False) - - qmc = QMCOpts(inputs, system, verbose=False) - trial = OneBody(inputs, system, beta, dt, system.H1, verbose=False) - - propagator = PlaneWave(inputs, qmc, system, trial, True) - walker = ThermalWalker(inputs, system, trial, verbose=False) - # walker.greens_function(trial) - E, T, V = walker.local_energy(system) - numpy.random.seed(0) - inputs["optimised"] = True - propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) - - propagator.propagate_walker_free(system, walker, trial, False) - - Gnew = walker.G[0].copy() - - assert scipy.linalg.norm(Gold[:, 0] - Gnew[:, 0]) < 1e-10 - - inputs["stack_size"] = 1 - walker = ThermalWalker(inputs, system, trial, verbose=False) - numpy.random.seed(0) - propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) - for i in range(0, 5): - propagator.propagate_walker(system, walker, trial) - Gs1 = walker.G[0].copy() - for ts in range(walker.stack_length): - walker.greens_function(trial, slice_ix=ts * walker.stack_size) - E, T, V = walker.local_energy(system) - # print(E) - - inputs["stack_size"] = 5 - walker = ThermalWalker(inputs, system, trial, verbose=False) - numpy.random.seed(0) - propagator = PlaneWave(inputs, qmc, system, trial, verbose=False) - for i in range(0, 5): - propagator.propagate_walker(system, walker, trial) - Gs5 = walker.G[0].copy() - for ts in range(walker.stack_length): - walker.greens_function(trial, slice_ix=ts * walker.stack_size) - E, T, V = walker.local_energy(system) - # print(E) - assert numpy.linalg.norm(Gs1 - Gs5) < 1e-10 - - N = 5 - A = numpy.random.rand(N, N) - Q, R, P = scipy.linalg.qr(A, pivoting=True) - - #### test permutation start - # Pmat = numpy.zeros((N,N)) - # for i in range (N): - # Pmat[P[i],i] = 1 - # print(P) - # tmp = Q.dot(R)#.dot(Pmat.T) - # print(tmp) - # print("==================") - # tmp2 = tmp.dot(Pmat.T) - # print(tmp2) - # print("==================") - # tmp[:,P] = tmp [:,range(N)] - # print(tmp) - #### test permutation end - - B = numpy.random.rand(N, N) - (Q1, R1, P1) = scipy.linalg.qr(B, pivoting=True, check_finite=False) - # Form permutation matrix - P1mat = numpy.zeros(B.shape, B.dtype) - P1mat[P1, range(len(P1))] = 1.0 - # Form D matrices - D1 = numpy.diag(R1.diagonal()) - D1inv = numpy.diag(1.0 / R1.diagonal()) - T1 = numpy.dot(numpy.dot(D1inv, R1), P1mat.T) - - assert numpy.linalg.norm(B - numpy.einsum("ij,jj->ij", Q1, D1).dot(T1)) < 1e-10 - - # tmp[:,:] = tmp[:,P] - # print(A - tmp) - # print(Q * Q.T) - # print(R) - - # Test walker green's function. - from ipie.legacy.estimators.hubbard import local_energy_hubbard - from ipie.legacy.estimators.thermal import one_rdm_from_G - from ipie.legacy.hamiltonians.hubbard import Hubbard - - sys_dict = { - "name": "Hubbard", - "nx": 4, - "ny": 4, - "nup": 7, - "ndown": 7, - "U": 4, - "t": 1, - } - system = Hubbard(sys_dict) - beta = 4 - mu = 1 - trial = OneBody({"mu": mu}, system, beta, dt, verbose=True) - - dt = 0.05 - num_slices = int(beta / dt) - - eref = 0 - for ek in system.eks: - eref += 2 * ek * 1.0 / (numpy.exp(beta * (ek - mu)) + 1) - walker = ThermalWalker({"stack_size": 1}, system, trial) - Gs1 = walker.G[0].copy() - rdm = one_rdm_from_G(walker.G) - ekin = local_energy_hubbard(system, rdm)[1] - try: - assert abs(eref - ekin) < 1e-8 - except AssertionError: - print(f"Error in kinetic energy check. Ref: {eref:13.8e} Calc:{ekin:13.8e}") - walker = ThermalWalker({"stack_size": 10}, system, trial) - rdm = one_rdm_from_G(walker.G) - ekin = local_energy_hubbard(system, rdm)[1] - try: - assert abs(eref - ekin) < 1e-8 - except AssertionError: - print( - "Error in kinetic energy check. Ref: %13.10e Calc: %13.10e" - " Error: %13.8e" % (eref.real, ekin.real, abs(eref - ekin)) - ) - for ts in range(walker.stack_length): - walker.greens_function(trial, slice_ix=ts * walker.stack_size) - assert numpy.linalg.norm(Gs1 - walker.G[0]) < 1e-10 - - -if __name__ == "__main__": - unit_test() From 7006a8a4e52ce585c7d3f41d16ab657ff3c99d4a Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Wed, 30 Aug 2023 17:37:23 -0400 Subject: [PATCH 13/84] test_thermal_walkers.py --- .../walkers/tests/test_thermal_walkers.py | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 ipie/thermal/walkers/tests/test_thermal_walkers.py diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py new file mode 100644 index 00000000..e71a8622 --- /dev/null +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -0,0 +1,42 @@ +import numpy +import pytest + +from ipie.legacy.hamiltonians.ueg import UEG as HamUEG +from ipie.legacy.propagation.planewave import PlaneWave +from ipie.legacy.systems.ueg import UEG +from ipie.legacy.trial_wavefunction.multi_slater import MultiSlater +from ipie.legacy.walkers.single_det import SingleDetWalker +from ipie.utils.misc import dotdict + + +@pytest.mark.unit +def test_pw(): + print("Joonho") + options = {"rs": 2, "nup": 7, "ndown": 7, "ecut": 2, "write_integrals": False} + system = UEG(options=options) + ham = HamUEG(system, options=options) + occ = numpy.eye(ham.nbasis)[:, : system.nup] + wfn = numpy.zeros((1, ham.nbasis, system.nup + system.ndown), dtype=numpy.complex128) + wfn[0, :, : system.nup] = occ + wfn[0, :, system.nup :] = occ + coeffs = numpy.array([1 + 0j]) + trial = MultiSlater(system, ham, (coeffs, wfn)) + trial.psi = trial.psi[0] + qmc = dotdict({"dt": 0.005, "nstblz": 5}) + prop = PlaneWave(system, ham, trial, qmc) + walker = SingleDetWalker(system, ham, trial) + numpy.random.seed(7) + a = numpy.random.rand(ham.nbasis * (system.nup + system.ndown)) + b = numpy.random.rand(ham.nbasis * (system.nup + system.ndown)) + wfn = (a + 1j * b).reshape((ham.nbasis, system.nup + system.ndown)) + walker.phi = wfn.copy() + walker.greens_function(trial) + # fb = prop.construct_force_bias_slow(system, walker, trial) + fb = prop.construct_force_bias(ham, walker, trial) + assert numpy.linalg.norm(fb) == pytest.approx(0.16660828645573392) + xi = numpy.random.rand(ham.nfields) + vhs = prop.construct_VHS(ham, xi - fb) + assert numpy.linalg.norm(vhs) == pytest.approx(0.1467322554815581) + +test_pw() + From 78eaa7e8ccfcf5181b9b213ce6cb2fc9f645ea12 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 30 Aug 2023 18:09:14 -0400 Subject: [PATCH 14/84] Update hamiltonian/ueg.py and systems/ueg.py unit tests. --- ipie/hamiltonians/tests/ueg_test.py | 103 +++++++++----------- ipie/hamiltonians/ueg.py | 6 +- ipie/systems/tests/test_ueg.py | 140 ++++++---------------------- ipie/systems/ueg.py | 1 - 4 files changed, 76 insertions(+), 174 deletions(-) diff --git a/ipie/hamiltonians/tests/ueg_test.py b/ipie/hamiltonians/tests/ueg_test.py index 4755807f..453a2fdd 100644 --- a/ipie/hamiltonians/tests/ueg_test.py +++ b/ipie/hamiltonians/tests/ueg_test.py @@ -1,73 +1,56 @@ import pytest import numpy -from ipie.utils.linalg import modified_cholesky -from ipie.utils.testing import generate_hamiltonian -from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol -# TODO: write UEG test - -@pytest.mark.unit -def test_real_modified_cholesky(): - numpy.random.seed(7) - nmo = 13 - nelec = (4, 3) - # ERI is already in the right form for cholesky decomposition - _, _, _, eri = generate_hamiltonian(nmo, nelec, cplx=False, sym=8) - - eri = eri.reshape((nmo**2, nmo**2)).T - chol = modified_cholesky(eri, tol=1e-8, verbose=False, cmax=30) - nchol = chol.shape[0] - - chol = chol.reshape((nchol, nmo**2)) - eri_chol = chol.T @ chol.conj() - numpy.testing.assert_allclose(eri_chol, eri, atol=1e-8) - - -@pytest.mark.unit -def test_complex_modified_cholesky(): - numpy.random.seed(7) - nmo = 13 - nelec = (4, 3) - # ERI is already in the right form for cholesky decomposition - _, _, _, eri = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) - - eri = eri.transpose((0, 1, 3, 2)) - eri = eri.reshape((nmo**2, nmo**2)) - chol = modified_cholesky(eri, tol=1e-8, verbose=False, cmax=30) - nchol = chol.shape[0] - - chol = modified_cholesky(eri, tol=1e-8, verbose=False, cmax=30) - nchol = chol.shape[0] - - chol = chol.reshape((nchol, nmo**2)) - eri_chol = chol.T @ chol.conj() - numpy.testing.assert_allclose(eri_chol, eri, atol=1e-8) +from ipie.systems.ueg import UEG as SysUEG +from ipie.hamiltonians.ueg import UEG +# TODO: write UEG test @pytest.mark.unit -def test_complex_hamiltonian(): +def test_hamiltonian(): numpy.random.seed(7) - nmo = 13 - nelec = (4, 3) - h1e, chol, nuc, eri = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) - nchol = chol.shape[0] - chol = chol.reshape((nchol, nmo**2)).T.copy() - ham = GenericComplexChol(numpy.array([h1e, h1e], dtype=h1e.dtype), chol, nuc, verbose=True) - + nup = 7 + ndown = 5 + ne = nup + ndown + rs = 1. + mu = -1. + ecut = 1. + sys_opts = { + "nup": nup, + "ndown": ndown, + "rs": rs, + "mu": mu, + "ecut": ecut + } + ham_opts = {} # Default + sys = SysUEG(sys_opts) + ham = UEG(sys, ham_opts, verbose=True) + assert hasattr(ham, "h1e_mod") == True @pytest.mark.unit -def test_real_hamiltonian(): +def test_skip_cholesky(): numpy.random.seed(7) - nmo = 13 - nelec = (4, 3) - h1e, chol, nuc, eri = generate_hamiltonian(nmo, nelec, cplx=False, sym=8) - nchol = chol.shape[0] - chol = chol.reshape((nchol, nmo**2)).T.copy() - ham = GenericRealChol(numpy.array([h1e, h1e], dtype=h1e.dtype), chol, nuc, verbose=True) + nup = 7 + ndown = 5 + ne = nup + ndown + rs = 1. + mu = -1. + ecut = 1. + sys_opts = { + "nup": nup, + "ndown": ndown, + "rs": rs, + "mu": mu, + "ecut": ecut + } + ham_opts = { + "skip_cholesky": True + } + sys = SysUEG(sys_opts) + ham = UEG(sys, ham_opts, verbose=True) + assert hasattr(ham, "h1e_mod") == False if __name__ == "__main__": - test_real_modified_cholesky() - test_complex_modified_cholesky() - test_complex_hamiltonian() - test_real_hamiltonian() + test_hamiltonian() + test_skip_cholesky() diff --git a/ipie/hamiltonians/ueg.py b/ipie/hamiltonians/ueg.py index 5ddbb6ba..ad46e4ee 100644 --- a/ipie/hamiltonians/ueg.py +++ b/ipie/hamiltonians/ueg.py @@ -43,10 +43,8 @@ def __init__(self, system, options, verbose=False): if verbose: print("# Parsing input options.") self.name = "UEG" - self.mu = options.get("mu", None) - if self.mu is not None: - print(f"# mu: {self.mu:6.4e}") - self._alt_convention = options.get("alt_convention", False) + self.mu = system.mu + self._alt_convention = system._alt_convention self.sparse = True # core energy diff --git a/ipie/systems/tests/test_ueg.py b/ipie/systems/tests/test_ueg.py index 86adfa30..922eba7b 100644 --- a/ipie/systems/tests/test_ueg.py +++ b/ipie/systems/tests/test_ueg.py @@ -21,123 +21,45 @@ import os import tempfile +import math import numpy import pytest from ipie.config import MPI -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.hamiltonians.utils import get_generic_integrals -from ipie.systems.generic import Generic -from ipie.utils.testing import generate_hamiltonian +from ipie.systems.ueg import UEG @pytest.mark.unit -def test_real(): +def test_ueg(): numpy.random.seed(7) - nmo = 17 - nelec = (4, 3) - h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - sys = Generic(nelec=nelec) - ham = HamGeneric( - h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nmo * nmo)).T.copy(), - ecore=enuc, - ) - assert sys.nup == 4 - assert sys.ndown == 3 - assert numpy.trace(h1e) == pytest.approx(9.38462274882365) - - -@pytest.mark.unit -def test_complex(): - numpy.random.seed(7) - nmo = 17 - nelec = (5, 3) - h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) - sys = Generic(nelec=nelec) - ham = HamGeneric( - h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nmo * nmo)).T.copy(), - ecore=enuc, - ) - assert sys.nup == 5 - assert sys.ndown == 3 - assert ham.nbasis == 17 - - -# @pytest.mark.unit -# def test_write(): -# numpy.random.seed(7) -# nmo = 13 -# nelec = (4, 3) -# h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) -# sys = Generic(nelec=nelec) -# ham = HamGeneric( -# h1e=numpy.array([h1e, h1e]), -# chol=chol.reshape((-1, nmo * nmo)).T.copy(), -# ecore=enuc, -# ) -# ham.write_integrals(nelec, filename="hamil.test_write.h5") - - -@pytest.mark.unit -def test_read(): - numpy.random.seed(7) - nmo = 13 - nelec = (4, 3) - h1e_, chol_, enuc_, eri_ = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) - from ipie.utils.io import write_qmcpack_dense - - chol_ = chol_.reshape((-1, nmo * nmo)).T.copy() - with tempfile.NamedTemporaryFile() as tmpf: - filename = tmpf.name - write_qmcpack_dense(h1e_, chol_, nelec, nmo, enuc=enuc_, filename=filename, real_chol=False) - nup, ndown = nelec - comm = None - hcore, chol, h1e_mod, enuc = get_generic_integrals(filename, comm=comm, verbose=False) - sys = Generic(nelec=nelec) - ham = HamGeneric(h1e=hcore, chol=chol, ecore=enuc) - assert ham.ecore == pytest.approx(0.4392816555570978) - assert ham.chol.shape == chol_.shape # now two are transposed - assert len(ham.H1.shape) == 3 - assert numpy.linalg.norm(ham.H1[0] - h1e_) == pytest.approx(0.0) - assert numpy.linalg.norm(ham.chol - chol_) == pytest.approx(0.0) # now two are transposed - - -@pytest.mark.unit -def test_shmem(): - numpy.random.seed(7) - nmo = 13 - nelec = (4, 3) - comm = MPI.COMM_WORLD - h1e_, chol_, enuc_, eri_ = generate_hamiltonian(nmo, nelec, cplx=True, sym=4) - from ipie.utils.io import write_qmcpack_dense - - with tempfile.NamedTemporaryFile() as tmpf: - chol_ = chol_.reshape((-1, nmo * nmo)).T.copy() - filename = tmpf.name - write_qmcpack_dense(h1e_, chol_, nelec, nmo, enuc=enuc_, filename=filename, real_chol=False) - from ipie.utils.mpi import get_shared_comm - - shared_comm = get_shared_comm(comm, verbose=True) - hcore, chol, _, enuc = get_generic_integrals(filename, comm=shared_comm, verbose=False) - # system = Generic(h1e=hcore, chol=chol, ecore=enuc, - # h1e_mod=h1e_mod, nelec=nelec, - # verbose=False) - # print("hcore.shape = ", hcore.shape) - sys = Generic(nelec=nelec) - ham = HamGeneric(h1e=hcore, chol=chol.copy(), ecore=enuc) - - assert ham.ecore == pytest.approx(0.4392816555570978) - assert ham.chol.shape == chol_.shape # now two are transposed - assert len(ham.H1.shape) == 3 - assert numpy.linalg.norm(ham.H1[0] - h1e_) == pytest.approx(0.0) - assert numpy.linalg.norm(ham.chol - chol_) == pytest.approx(0.0) # now two are transposed + nup = 7 + ndown = 5 + ne = nup + ndown + rs = 1. + mu = -1. + ecut = 1. + sys_opts = { + "nup": nup, + "ndown": ndown, + "rs": rs, + "mu": mu, + "ecut": ecut + } + sys = UEG(sys_opts, verbose=True) + assert sys.nup == nup + assert sys.ndown == ndown + assert sys.rs == rs + assert sys.mu == mu + assert sys.ecut == ecut + assert sys.ne == nup + ndown + assert sys.zeta == (nup - ndown) / ne + assert sys.rho == ((4.0 * math.pi) / 3.0 * rs**3.0)**(-1.0) + assert sys.L == rs * (4.0 * ne * math.pi / 3.0) ** (1.0 / 3.0) + assert sys.vol == sys.L**3.0 + assert sys.kfac == 2 * math.pi / sys.L + assert sys.kf == (3 * (sys.zeta + 1) * math.pi**2 * ne / sys.L**3) ** (1.0 / 3.0) + assert sys.ef == 0.5 * sys.kf**2 if __name__ == "__main__": - test_real() - test_complex() - # test_write() - test_read() - test_shmem() + test_ueg() diff --git a/ipie/systems/ueg.py b/ipie/systems/ueg.py index 4162ded3..454d3693 100644 --- a/ipie/systems/ueg.py +++ b/ipie/systems/ueg.py @@ -69,7 +69,6 @@ def __init__(self, options, verbose=False): # Volume self.vol = self.L**3.0 # k-space grid spacing. - # self.kfac = 2*math.pi/self.L self.kfac = 2 * math.pi / self.L # Fermi Wavevector (infinite system). self.kf = (3 * (self.zeta + 1) * math.pi**2 * self.ne / self.L**3) ** (1 / 3.0) From 0443bbfa505d6c864ec0e9f9bb7f2020dd6ba0f0 Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Wed, 30 Aug 2023 18:47:27 -0400 Subject: [PATCH 15/84] add a ft qmc example for generic system: tests/example_generic.py --- ipie/hamiltonians/utils.py | 7 ++ ipie/systems/utils.py | 2 + ipie/thermal/propagation/generic.py | 11 +-- ipie/thermal/tests/example_generic.py | 96 +++++++++++++++++++++++++++ 4 files changed, 112 insertions(+), 4 deletions(-) create mode 100644 ipie/thermal/tests/example_generic.py diff --git a/ipie/hamiltonians/utils.py b/ipie/hamiltonians/utils.py index ca033852..37bd2f9d 100644 --- a/ipie/hamiltonians/utils.py +++ b/ipie/hamiltonians/utils.py @@ -100,6 +100,13 @@ def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): ecore=enuc, verbose=verbose, ) + ham._alt_convention = ham_opts["_alt_convention"] + ham.sparse = ham_opts["sparse"] + ham.name = ham_opts["name"] + ham.hs_pot = chol.T.reshape(nchol, nbsf, nbsf) + ham.chol_vecs = chol + ham.mu = ham_opts["mu"] + elif isinstance(system, SysUEG): ham = UEG( diff --git a/ipie/systems/utils.py b/ipie/systems/utils.py index 6425d871..b0de9ef4 100644 --- a/ipie/systems/utils.py +++ b/ipie/systems/utils.py @@ -49,6 +49,8 @@ def get_system(sys_opts=None, verbose=0, comm=None): nelec = (nup, ndown) system = Generic(nelec, verbose) + system.mu = sys_opts["mu"] + elif sys_type == "UEG": system = UEG(sys_opts, verbose) diff --git a/ipie/thermal/propagation/generic.py b/ipie/thermal/propagation/generic.py index c88870a2..34927332 100644 --- a/ipie/thermal/propagation/generic.py +++ b/ipie/thermal/propagation/generic.py @@ -86,7 +86,8 @@ def construct_mean_field_shift(self, system, P): mf_shift = 1j * P[0].ravel() * system.chol_vecs mf_shift += 1j * P[1].ravel() * system.chol_vecs else: - mf_shift = 1j * numpy.einsum("lpq,spq->l", system.chol_vecs, P) + # mf_shift = 1j * numpy.einsum("lpq,spq->l", system.chol_vecs, P) + mf_shift = 1j * numpy.einsum("lpq,spq->l", system.hs_pot, P) return mf_shift def construct_one_body_propagator(self, system, dt): @@ -149,14 +150,16 @@ def construct_force_bias_fast(self, system, P, trial): xbar : :class:`numpy.ndarray` Force bias. """ - vbias = P[0].ravel() * system.hs_pot - vbias += P[1].ravel() * system.hs_pot + # vbias = P[0].ravel() * system.hs_pot + # vbias += P[1].ravel() * system.hs_pot + vbias = system.chol_vecs.T.dot(P[0].ravel()) + vbias += system.chol_vecs.T.dot(P[1].ravel()) return -self.sqrt_dt * (1j * vbias - self.mf_shift) def construct_VHS_slow(self, system, shifted): return self.isqrt_dt * numpy.einsum("l,lpq->pq", shifted, system.hs_pot) def construct_VHS_fast(self, system, xshifted): - VHS = system.hs_pot.dot(xshifted) + VHS = system.chol_vecs.dot(xshifted) VHS = VHS.reshape(system.nbasis, system.nbasis) return self.isqrt_dt * VHS diff --git a/ipie/thermal/tests/example_generic.py b/ipie/thermal/tests/example_generic.py new file mode 100644 index 00000000..432283d9 --- /dev/null +++ b/ipie/thermal/tests/example_generic.py @@ -0,0 +1,96 @@ +from ipie.systems.generic import Generic +from pyscf import gto, scf, lo +from ipie.utils.from_pyscf import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC +import numpy +import mpi4py.MPI as MPI +import h5py + +comm = MPI.COMM_WORLD + +nocca = 5 +noccb = 5 +nelec = nocca + noccb +r0 = 1.75 +mol = gto.M( + atom=[("H", i * r0, 0, 0) for i in range(nelec)], + basis='sto-6g', + unit='Bohr', + verbose=5 +) + +mf = scf.UHF(mol).run() +mf.chkfile = 'scf.chk' + +mo1 = mf.stability()[0] +dm1 = mf.make_rdm1(mo1, mf.mo_occ) +mf = mf.run(dm1) +mf.stability(return_status=True) + +s1e = mol.intor("int1e_ovlp_sph") +ao_coeff = lo.orth.lowdin(s1e) + +system = Generic(nelec=mol.nelec) + +integrals = generate_hamiltonian( + mol, + mf.mo_coeff, + mf.get_hcore(), + ao_coeff, + ortho_ao=True, + chol_cut=1.e-8 + ) + +num_chol = integrals.chol.shape[1] +num_basis = integrals.nbasis + +with h5py.File("generic_integrals.h5", "w") as fa: + fa["hcore"] = integrals.H1[0] + fa["LXmn"] = integrals.chol.T.reshape(num_chol, num_basis, num_basis) + fa["e0"] = integrals.ecore + +mu = -10.0 + +options = { + "qmc": { + "dt": 0.01, + "nwalkers": 1, + "blocks": 10, + "nsteps": 10, + "beta": 0.1, + "rng_seed": 7, + "pop_control_freq": 1, + "stabilise_freq": 10, + "batched": False + }, + "walkers": { + "population_control": "pair_branch" + }, + "estimators": { + "mixed": { + "one_rdm": True + } + }, + "trial": { + "name": "thermal_hartree_fock" + }, + "hamiltonian": { + "name": "Generic", + "integrals": "generic_integrals.h5", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + "system": { + "name": "Generic", + "nup": nocca, + "ndown": noccb, + "mu": mu + } +} + + +afqmc = ThermalAFQMC(comm, options) +afqmc.run(comm=comm) +afqmc.finalise(comm) \ No newline at end of file From bda0cb3a5e423f8de9472f1f243ddf165868171b Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Wed, 30 Aug 2023 21:33:58 -0400 Subject: [PATCH 16/84] removing rest files of Hubbard in thermal code --- ipie/thermal/estimators/fock.py | 3 +- ipie/thermal/estimators/hubbard.py | 159 ----------- ipie/thermal/estimators/local_energy.py | 51 +--- ipie/thermal/estimators/pw_fft.py | 345 ------------------------ 4 files changed, 5 insertions(+), 553 deletions(-) delete mode 100644 ipie/thermal/estimators/hubbard.py delete mode 100644 ipie/thermal/estimators/pw_fft.py diff --git a/ipie/thermal/estimators/fock.py b/ipie/thermal/estimators/fock.py index 676cf89f..2330ad2e 100644 --- a/ipie/thermal/estimators/fock.py +++ b/ipie/thermal/estimators/fock.py @@ -1,5 +1,4 @@ from ipie.estimators.generic import fock_generic -from ipie.thermal.estimators.hubbard import fock_hubbard from ipie.thermal.estimators.ueg import fock_ueg @@ -9,7 +8,7 @@ def fock_matrix(system, G): elif system.name == "Generic": return fock_generic(system, G) elif system.name == "Hubbard": - return fock_hubbard(system, G) + raise NotImplementedError else: print(f"# Fock matrix not implemented for {system.name}") return None diff --git a/ipie/thermal/estimators/hubbard.py b/ipie/thermal/estimators/hubbard.py deleted file mode 100644 index 8223067e..00000000 --- a/ipie/thermal/estimators/hubbard.py +++ /dev/null @@ -1,159 +0,0 @@ -import numpy - -def local_energy_hubbard_holstein(ham, G, X, Lap, Ghalf=None): - r"""Calculate local energy of walker for the Hubbard-Hostein model. - - Parameters - ---------- - ham : :class:`HubbardHolstein` - ham information for the HubbardHolstein model. - G : :class:`numpy.ndarray` - Walker's "Green's function" - X : :class:`numpy.ndarray` - Walker's phonon coordinate - - Returns - ------- - (E_L(phi), T, V): tuple - Local, kinetic and potential energies of given walker phi. - """ - ke = numpy.sum(ham.T[0] * G[0] + ham.T[1] * G[1]) - - if ham.symmetric: - pe = -0.5 * ham.U * (G[0].trace() + G[1].trace()) - - pe = ham.U * numpy.dot(G[0].diagonal(), G[1].diagonal()) - - pe_ph = 0.5 * ham.w0**2 * ham.m * numpy.sum(X * X) - - ke_ph = -0.5 * numpy.sum(Lap) / ham.m - 0.5 * ham.w0 * ham.nbasis - - rho = G[0].diagonal() + G[1].diagonal() - e_eph = -ham.g * numpy.sqrt(ham.m * ham.w0 * 2.0) * numpy.dot(rho, X) - - etot = ke + pe + pe_ph + ke_ph + e_eph - - Eph = ke_ph + pe_ph - Eel = ke + pe - Eeb = e_eph - - return (etot, ke + pe, ke_ph + pe_ph + e_eph) - - -def local_energy_hubbard(ham, G, Ghalf=None): - r"""Calculate local energy of walker for the Hubbard model. - - Parameters - ---------- - ham : :class:`Hubbard` - ham information for the Hubbard model. - G : :class:`numpy.ndarray` - Walker's "Green's function" - - Returns - ------- - (E_L(phi), T, V): tuple - Local, kinetic and potential energies of given walker phi. - """ - ke = numpy.sum(ham.T[0] * G[0] + ham.T[1] * G[1]) - # Todo: Stupid - if ham.symmetric: - pe = -0.5 * ham.U * (G[0].trace() + G[1].trace()) - pe = ham.U * numpy.dot(G[0].diagonal(), G[1].diagonal()) - - return (ke + pe, ke, pe) - - -def local_energy_hubbard_ghf(ham, Gi, weights, denom): - """Calculate local energy of GHF walker for the Hubbard model. - - Parameters - ---------- - ham : :class:`Hubbard` - ham information for the Hubbard model. - Gi : :class:`numpy.ndarray` - Array of Walker's "Green's function" - denom : float - Overlap of trial wavefunction with walker. - - Returns - ------- - (E_L(phi), T, V): tuple - Local, kinetic and potential energies of given walker phi. - """ - ke = numpy.einsum("i,ikl,kl->", weights, Gi, ham.Text) / denom - # numpy.diagonal returns a view so there should be no overhead in creating - # temporary arrays. - guu = numpy.diagonal(Gi[:, : ham.nbasis, : ham.nbasis], axis1=1, axis2=2) - gdd = numpy.diagonal(Gi[:, ham.nbasis :, ham.nbasis :], axis1=1, axis2=2) - gud = numpy.diagonal(Gi[:, ham.nbasis :, : ham.nbasis], axis1=1, axis2=2) - gdu = numpy.diagonal(Gi[:, : ham.nbasis, ham.nbasis :], axis1=1, axis2=2) - gdiag = guu * gdd - gud * gdu - pe = ham.U * numpy.einsum("j,jk->", weights, gdiag) / denom - return (ke + pe, ke, pe) - - -def local_energy_hubbard_ghf_full(ham, GAB, weights): - r"""Calculate local energy of GHF walker for the Hubbard model. - - Parameters - ---------- - ham : :class:`Hubbard` - ham information for the Hubbard model. - GAB : :class:`numpy.ndarray` - Matrix of Green's functions for different SDs A and B. - weights : :class:`numpy.ndarray` - Components of overlap of trial wavefunction with walker. - - Returns - ------- - (E_L, T, V): tuple - Local, kinetic and potential energies of given walker phi. - """ - denom = numpy.sum(weights) - ke = numpy.einsum("ij,ijkl,kl->", weights, GAB, ham.Text) / denom - # numpy.diagonal returns a view so there should be no overhead in creating - # temporary arrays. - guu = numpy.diagonal(GAB[:, :, : ham.nbasis, : ham.nbasis], axis1=2, axis2=3) - gdd = numpy.diagonal(GAB[:, :, ham.nbasis :, ham.nbasis :], axis1=2, axis2=3) - gud = numpy.diagonal(GAB[:, :, ham.nbasis :, : ham.nbasis], axis1=2, axis2=3) - gdu = numpy.diagonal(GAB[:, :, : ham.nbasis, ham.nbasis :], axis1=2, axis2=3) - gdiag = guu * gdd - gud * gdu - pe = ham.U * numpy.einsum("ij,ijk->", weights, gdiag) / denom - return (ke + pe, ke, pe) - - -def local_energy_multi_det(ham, Gi, weights): - """Calculate local energy of GHF walker for the Hubbard model. - - Parameters - ---------- - ham : :class:`Hubbard` - ham information for the Hubbard model. - Gi : :class:`numpy.ndarray` - Array of Walker's "Green's function" - weights : :class:`numpy.ndarray` - Components of overlap of trial wavefunction with walker. - - Returns - ------- - (E_L(phi), T, V): tuple - Local, kinetic and potential energies of given walker phi. - """ - denom = numpy.sum(weights) - ke = numpy.einsum("i,ikl,kl->", weights, Gi, ham.Text) / denom - # numpy.diagonal returns a view so there should be no overhead in creating - # temporary arrays. - guu = numpy.diagonal(Gi[:, :, : ham.nup], axis1=1, axis2=2) - gdd = numpy.diagonal(Gi[:, :, ham.nup :], axis1=1, axis2=2) - pe = ham.U * numpy.einsum("j,jk->", weights, guu * gdd) / denom - return (ke + pe, ke, pe) - - -def fock_hubbard(ham, P): - """Hubbard Fock Matrix - F_{ij} = T_{ij} + U(nid + niu)_{ij} - """ - niu = numpy.diag(P[0].diagonal()) - nid = numpy.diag(P[1].diagonal()) - return ham.T + ham.U * numpy.array([nid, niu]) diff --git a/ipie/thermal/estimators/local_energy.py b/ipie/thermal/estimators/local_energy.py index c3b19fd4..9d8d6d57 100644 --- a/ipie/thermal/estimators/local_energy.py +++ b/ipie/thermal/estimators/local_energy.py @@ -1,7 +1,5 @@ -import numpy try: - from ipie.thermal.estimators.pw_fft import local_energy_pw_fft from ipie.thermal.estimators.ueg import local_energy_ueg except ImportError as e: print(e) @@ -12,11 +10,6 @@ local_energy_generic_cholesky_opt_stochastic, local_energy_generic_pno, ) -from ipie.thermal.estimators.hubbard import ( - local_energy_hubbard, - local_energy_hubbard_ghf, - local_energy_hubbard_holstein, -) from ipie.thermal.estimators.thermal import one_rdm_from_G @@ -24,15 +17,8 @@ def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): assert len(G) == 2 ghf = G[0].shape[-1] == 2 * hamiltonian.nbasis # unfortunate interfacial problem for the HH model - if hamiltonian.name == "Hubbard": - if ghf: - return local_energy_hubbard_ghf(hamiltonian, G) - else: - return local_energy_hubbard(hamiltonian, G) - elif hamiltonian.name == "HubbardHolstein": - return local_energy_hubbard_holstein(hamiltonian, G, X, Lap, Ghalf) - elif hamiltonian.name == "PW_FFT": - return local_energy_pw_fft(system, G, Ghalf) + if hamiltonian.name in ["Hubbard", "HubbardHolstein", "PW_FFT"]: + raise NotImplementedError elif hamiltonian.name == "UEG": return local_energy_ueg(system, hamiltonian, G) else: @@ -91,41 +77,12 @@ def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): # this is a generic local_energy handler. So many possible combinations of local energy strategies... def local_energy(system, hamiltonian, walker, trial): if walker.name == "MultiDetWalker": - if hamiltonian.name == "HubbardHolstein": - return local_energy_multi_det_hh( - system, walker.Gi, walker.weights, walker.X, walker.Lapi - ) - else: - return local_energy_multi_det(system, hamiltonian, trial, walker.Gi, walker.weights) + raise NotImplementedError elif walker.name == "ThermalWalker": return local_energy_G(system, hamiltonian, trial, one_rdm_from_G(walker.G), None) else: if hamiltonian.name == "HubbardHolstein": - return local_energy_G( - system, hamiltonian, trial, walker.G, walker.Ghalf, walker.X, walker.Lap - ) + raise NotImplementedError else: return local_energy_G(system, hamiltonian, trial, walker.G, walker.Ghalf) - -def local_energy_multi_det(system, hamiltonian, trial, Gi, weights): - weight = 0 - energies = 0 - denom = 0 - for idet, (w, G) in enumerate(zip(weights, Gi)): - energies += w * numpy.array(local_energy_G(system, hamiltonian, trial, G)) - denom += w - return tuple(energies / denom) - - -def local_energy_multi_det_hh(system, Gi, weights, X, Lapi): - weight = 0 - energies = 0 - denom = 0 - for w, G, Lap in zip(weights, Gi, Lapi): - # construct "local" green's functions for each component of A - energies += w * numpy.array(local_energy_hubbard_holstein(system, G, X, Lap, Ghalf=None)) - denom += w - return tuple(energies / denom) - - diff --git a/ipie/thermal/estimators/pw_fft.py b/ipie/thermal/estimators/pw_fft.py deleted file mode 100644 index d61a5749..00000000 --- a/ipie/thermal/estimators/pw_fft.py +++ /dev/null @@ -1,345 +0,0 @@ -try: - from ipie.thermal.estimators.ueg_kernels import exchange_greens_function_per_qvec -except ImportError: - pass - -try: - from ipie.thermal.estimators.ueg_kernels import exchange_greens_function_fft -except ImportError: - pass - -import itertools - -import numpy - -from ipie.thermal.estimators.utils import convolve - - -def local_energy_pw_fft(system, G, Ghalf, trial, two_rdm=None): - """Local energy computation for uniform electron gas - Parameters - ---------- - system : - system class - G : - Green's function - Returns - ------- - etot : float - total energy - ke : float - kinetic energy - pe : float - potential energy - """ - assert Ghalf[0].shape[0] + Ghalf[1].shape[0] == trial.shape[1] - - nocca = Ghalf[0].shape[0] - noccb = Ghalf[1].shape[0] - # CTdagger = numpy.array([numpy.array(system.trial[:,0:system.nup],dtype=numpy.complex128).T.conj(), - # numpy.array(system.trial[:,system.nup:],dtype=numpy.complex128).T.conj()]) - - CTdagger = numpy.array( - [ - numpy.array(trial[:, 0:nocca], dtype=numpy.complex128).T.conj(), - numpy.array(trial[:, nocca:], dtype=numpy.complex128).T.conj(), - ] - ) - - # ke = numpy.einsum('sij,sji->', system.H1, G) # Wrong convention (correct Joonho convention) - # ke = numpy.einsum('sij,sij->', system.H1, G) # Correct ipie convention - if system.diagH1: - ke = numpy.einsum("sii,sii->", system.H1, G) - else: - ke = numpy.einsum("sij,sij->", system.H1, G) - - nq = numpy.shape(system.qvecs)[0] - - nocc = [nocca, noccb] - - nqgrid = numpy.prod(system.qmesh) - ngrid = numpy.prod(system.mesh) - - Gkpq = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) - Gpmq = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) - - for s in [0, 1]: - for i in range(nocc[s]): - ################################### - Gh_i = Ghalf[s][i, ::-1] - CTdagger_i = CTdagger[s][i, :] - - Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - - Gh_i_cube[system.gmap] = Gh_i - CTdagger_i_cube[system.gmap] = CTdagger_i - - # \sum_G CT(G-Q) theta(G) - lQ_i_cube = convolve(CTdagger_i_cube, Gh_i_cube, system.mesh)[::-1] - Gpmq[s] += lQ_i_cube[system.qmap] - - # ################################################################ - - Gh_i = Ghalf[s][i, :] - CTdagger_i = CTdagger[s][i, :][::-1] - - Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - - Gh_i_cube[system.gmap] = Gh_i - CTdagger_i_cube[system.gmap] = CTdagger_i - - # \sum_G CT(G+Q) theta(G) - lQ_i_cube = convolve(Gh_i_cube, CTdagger_i_cube, system.mesh)[::-1] - Gkpq[s] += lQ_i_cube[system.qmap] - - Gprod = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) - for s in [0, 1]: - Gprod[s] = exchange_greens_function_fft( - nocc[s], - system.nbasis, - numpy.array(system.mesh), - numpy.array(system.qmesh), - numpy.array(system.gmap), - numpy.array(system.qmap), - CTdagger[s], - Ghalf[s], - ) - - if two_rdm is None: - two_rdm = numpy.zeros((2, 2, len(system.qvecs)), dtype=numpy.complex128) - two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] - essa = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[0, 0]) - - two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] - essb = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[1, 1]) - - two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) - two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) - eos = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[0, 1]) + ( - 1.0 / (2.0 * system.vol) - ) * system.vqvec.dot(two_rdm[1, 0]) - pe = essa + essb + eos - - return (ke + pe, ke, pe) - - -def local_energy_pw_fft_no_cython(system, G, Ghalf, two_rdm=None): - """Local energy computation for uniform electron gas - Parameters - ---------- - system : - system class - G : - Green's function - Returns - ------- - etot : float - total energy - ke : float - kinetic energy - pe : float - potential energy - """ - - CTdagger = numpy.array( - [ - numpy.array(system.trial[:, 0 : system.nup], dtype=numpy.complex128).T.conj(), - numpy.array(system.trial[:, system.nup :], dtype=numpy.complex128).T.conj(), - ] - ) - - # ke = numpy.einsum('sij,sji->', system.H1, G) # Wrong convention (correct Joonho convention) - ke = numpy.einsum("sij,sij->", system.H1, G) # Correct ipie convention - - ne = [system.nup, system.ndown] - nq = numpy.shape(system.qvecs)[0] - - nocc = [system.nup, system.ndown] - nqgrid = numpy.prod(system.qmesh) - ngrid = numpy.prod(system.mesh) - - Gkpq = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) - Gpmq = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) - - for s in [0, 1]: - for i in range(nocc[s]): - ################################### - Gh_i = numpy.flip(Ghalf[s][i, :]) - CTdagger_i = CTdagger[s][i, :] - - Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - - Gh_i_cube[system.gmap] = Gh_i - CTdagger_i_cube[system.gmap] = CTdagger_i - - # \sum_G CT(G-Q) theta(G) - lQ_i_cube = numpy.flip(convolve(CTdagger_i_cube, Gh_i_cube, system.mesh)) - Gpmq[s] += lQ_i_cube[system.qmap] - - # ################################################################ - - Gh_i = Ghalf[s][i, :] - CTdagger_i = numpy.flip(CTdagger[s][i, :]) - - Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - - Gh_i_cube[system.gmap] = Gh_i - CTdagger_i_cube[system.gmap] = CTdagger_i - - # \sum_G CT(G+Q) theta(G) - lQ_i_cube = numpy.flip(convolve(Gh_i_cube, CTdagger_i_cube, system.mesh)) - Gkpq[s] += lQ_i_cube[system.qmap] - - Gprod = numpy.zeros((2, len(system.qvecs)), dtype=numpy.complex128) - - for s in [0, 1]: - for i, j in itertools.product(range(nocc[s]), range(nocc[s])): - ################################### - Gh_i = numpy.flip(Ghalf[s][i, :]) - CTdagger_j = CTdagger[s][j, :] - - Gh_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - CTdagger_j_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - - Gh_i_cube[system.gmap] = Gh_i - CTdagger_j_cube[system.gmap] = CTdagger_j - - # \sum_G CT(G-Q) theta(G) - lQ_ji_cube = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, system.mesh)) - lQ_ji_fft = lQ_ji_cube[system.qmap] - - # ################################################################ - - Gh_j = Ghalf[s][j, :] - CTdagger_i = numpy.flip(CTdagger[s][i, :]) - - Gh_j_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - CTdagger_i_cube = numpy.zeros(ngrid, dtype=numpy.complex128) - - Gh_j_cube[system.gmap] = Gh_j - CTdagger_i_cube[system.gmap] = CTdagger_i - - # \sum_G CT(G+Q) theta(G) - lQ_ij_cube = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, system.mesh)) - lQ_ij_fft = lQ_ij_cube[system.qmap] - - Gprod[s] += lQ_ji_fft * lQ_ij_fft - - if two_rdm is None: - two_rdm = numpy.zeros((2, 2, len(system.qvecs)), dtype=numpy.complex128) - two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] - essa = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[0, 0]) - - two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] - essb = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[1, 1]) - - two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) - two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) - eos = (1.0 / (2.0 * system.vol)) * system.vqvec.dot(two_rdm[0, 1]) + ( - 1.0 / (2.0 * system.vol) - ) * system.vqvec.dot(two_rdm[1, 0]) - pe = essa + essb + eos - - return (ke + pe, ke, pe) - - -def unit_test(): - import cProfile - - import numpy as np - - from ipie.legacy.estimators.greens_function import gab_mod - from ipie.legacy.estimators.ueg import local_energy_ueg - from ipie.legacy.systems.ueg import UEG - from ipie.systems.pw_fft import PW_FFT - from ipie.utils.testing import get_random_wavefunction - - # ecuts = [128.0] - # ecuts = [128.0] - ecuts = [2.0] - # ecuts = [2.0, 4.0, 8.0, 16.0, 32.0, 64.0] - - for ecut in ecuts: - inputs = { - "nup": 27, - "ndown": 27, - "rs": 1.0, - "ecut": ecut, - "skip_cholesky": True, - } - - system = PW_FFT(inputs, False) - print(f"ecut = {ecut}, nbsf = {system.nbasis}") - np.random.seed(7) - - rpsi = numpy.random.rand(system.nbasis, system.nup + system.ndown) - zpsi = numpy.random.rand(system.nbasis, system.nup + system.ndown) - system.trial = rpsi + 1.0j * zpsi - - Ca = np.array(system.trial[:, 0 : system.nup], dtype=np.complex128) - Cb = np.array(system.trial[:, system.nup :], dtype=np.complex128) - - (G_a, Ghalf_a) = gab_mod(Ca, Ca) - (G_b, Ghalf_b) = gab_mod(Cb, Cb) - - G = np.array([G_a, G_b]) - Ghalf = np.array([Ghalf_a, Ghalf_b]) - - pr = cProfile.Profile() - pr.enable() - - etot, ekin, epot = local_energy_pw_fft(system, G=G, Ghalf=Ghalf, trial=system.trial) - pr.disable() - pr.print_stats(sort="tottime") - print(f"ERHF = {etot}, {ekin}, {epot}") - # ERHF = (55.724777391549715-1.5180081474352112e-14j), (68.06317599174015-2.2316276597217335e-14j), (-12.33839860019044+7.136195122865225e-15j) - - # start = time.time() - # etot, ekin, epot = local_energy_pw_fft_no_cython(system, G=G, Ghalf=Ghalf) - # print("ERHF = {}, {}, {}".format(etot, ekin, epot)) - # end = time.time() - # print("FFT w/o Cython local energy (s): {}".format(end - start)) - - # # pr = cProfile.Profile() - # # pr.enable() - # system2 = UEG(inputs, False) - # print ("ecut = {}, nbsf = {}".format(ecut, system2.nbasis)) - # # pr.disable() - # # pr.print_stats(sort='tottime') - # nbsf = system2.nbasis - # Pa = np.zeros([nbsf,nbsf],dtype = np.complex128) - # Pb = np.zeros([nbsf,nbsf],dtype = np.complex128) - # na = system2.nup - # nb = system2.ndown - # for i in range(na): - # Pa[i,i] = 1.0 - # for i in range(nb): - # Pb[i,i] = 1.0 - # P = np.array([Pa, Pb]) - - # start = time.time() - # pr = cProfile.Profile() - # pr.enable() - # etot, ekin, epot = local_energy_ueg(system2, G=P) - # pr.disable() - # pr.print_stats(sort='tottime') - # print("ERHF = {}, {}, {}".format(etot, ekin, epot)) - # end = time.time() - # print("Usual local energy (s): {}".format(end - start)) - - # print(Greorder[0]) - # print(G[0]) - - # print(numpy.diag(system.H1[0])[sort_basis]) - # print(system2.H1) - - -# ERHF = (13.603557335564197+0j), (15.692780148560848+0j), (-2.0892228129966512+0j) #(7e,7e) - - -if __name__ == "__main__": - unit_test() From 389d4817bae203b06ba1f96ab220f5728dc19baf Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Wed, 30 Aug 2023 21:51:13 -0400 Subject: [PATCH 17/84] clean up walker handler, remove qmc.calc file clean up walker handler, remove qmc.calc file.. --- ipie/thermal/qmc/calc.py | 33 ---------------- ipie/thermal/tests/test_ft_integration.py | 11 ++---- ipie/thermal/walkers/handler.py | 46 ----------------------- 3 files changed, 4 insertions(+), 86 deletions(-) delete mode 100644 ipie/thermal/qmc/calc.py diff --git a/ipie/thermal/qmc/calc.py b/ipie/thermal/qmc/calc.py deleted file mode 100644 index caed1997..00000000 --- a/ipie/thermal/qmc/calc.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Helper Routines for setting up a calculation""" -# todo : handle more gracefully. - -try: - import mpi4py - - mpi4py.rc.recv_mprobe = False - from ipie.config import MPI - - # import dill - # MPI.pickle.__init__(dill.dumps, dill.loads) - parallel = True -except ImportError: - parallel = False -from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC -from ipie.utils.io import get_input_value - - -def get_driver(options, comm): - verbosity = options.get("verbosity", 1) - qmc_opts = get_input_value(options, "qmc", default={}, alias=["qmc_options"]) - beta = get_input_value(qmc_opts, "beta", default=None) - batched = get_input_value(qmc_opts, "batched", default=True) # , - # verbose=verbosity) - if beta is not None: - afqmc = ThermalAFQMC(comm, options=options, parallel=comm.size > 1, verbose=verbosity) - else: - raise NotImplementedError - - return afqmc - - - diff --git a/ipie/thermal/tests/test_ft_integration.py b/ipie/thermal/tests/test_ft_integration.py index 390573c1..d74128d4 100644 --- a/ipie/thermal/tests/test_ft_integration.py +++ b/ipie/thermal/tests/test_ft_integration.py @@ -27,6 +27,8 @@ from ipie.analysis.extraction import extract_test_data_hdf5 from ipie.config import MPI from ipie.qmc.calc import get_driver, read_input +from ipie.utils.io import get_input_value +from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC _built_legacy = True @@ -80,16 +82,11 @@ def run_test_system(input_file, benchmark_file, legacy_job=False): with tempfile.NamedTemporaryFile() as tmpf: input_dict["estimators"]["filename"] = tmpf.name if _built_legacy and legacy_job: - from ipie.thermal.qmc.calc import get_driver as get_legacy_driver - input_dict["qmc"]["batched"] = False - afqmc = get_legacy_driver(input_dict, comm) + verbosity = input_dict.get("verbosity", 1) + afqmc = ThermalAFQMC(comm, options=input_dict, parallel=comm.size > 1, verbose=verbosity) afqmc.run(comm=comm) afqmc.finalise(comm) - else: - afqmc = get_driver(input_dict, comm) - afqmc.run(estimator_filename=tmpf.name) - afqmc.finalise() with open(benchmark_file, "r") as f: ref_data = json.load(f) skip_val = ref_data.get("extract_skip_value", 10) diff --git a/ipie/thermal/walkers/handler.py b/ipie/thermal/walkers/handler.py index c247cdd7..9559cf1e 100644 --- a/ipie/thermal/walkers/handler.py +++ b/ipie/thermal/walkers/handler.py @@ -130,48 +130,6 @@ def __init__( if verbose: print("# Finish setting up walkers.handler.Walkers.") - def orthogonalise(self, trial, free_projection): - """Orthogonalise all walkers. - - Parameters - ---------- - trial : object - Trial wavefunction object. - free_projection : bool - True if doing free projection. - """ - for w in self.walkers: - detR = w.reortho(trial) - if free_projection: - (magn, dtheta) = cmath.polar(detR) - w.weight *= magn - w.phase *= cmath.exp(1j * dtheta) - - - def copy_historic_wfn(self): - """Copy current wavefunction to psi_n for next back propagation step.""" - for i, w in enumerate(self.walkers): - numpy.copyto(self.walkers[i].phi_old, self.walkers[i].phi) - - def copy_bp_wfn(self, phi_bp): - """Copy back propagated wavefunction. - - Parameters - ---------- - phi_bp : object - list of walker objects containing back propagated walkers. - """ - for i, (w, wbp) in enumerate(zip(self.walkers, phi_bp)): - numpy.copyto(self.walkers[i].phi_bp, wbp.phi) - - def copy_init_wfn(self): - """Copy current wavefunction to initial wavefunction. - - The definition of the initial wavefunction depends on whether we are - calculating an ITCF or not. - """ - for i, w in enumerate(self.walkers): - numpy.copyto(self.walkers[i].phi_right, self.walkers[i].phi) def pop_control(self, comm): if self.ntot_walkers == 1: @@ -358,10 +316,6 @@ def pair_branch(self, comm): for r in reqs: r.wait() - def recompute_greens_function(self, trial, time_slice=None): - for w in self.walkers: - w.greens_function(trial, time_slice) - def set_total_weight(self, total_weight): for w in self.walkers: w.total_weight = total_weight From 6146d6a41d5cbaba50e44ff9f4e666bf32bd5cc0 Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Thu, 31 Aug 2023 09:39:01 -0400 Subject: [PATCH 18/84] thermal walker test update --- .../walkers/tests/test_thermal_walkers.py | 42 ++++++------------- ipie/thermal/walkers/uhf_walkers.py | 4 +- 2 files changed, 14 insertions(+), 32 deletions(-) diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py index e71a8622..287618f0 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -2,41 +2,23 @@ import pytest from ipie.legacy.hamiltonians.ueg import UEG as HamUEG -from ipie.legacy.propagation.planewave import PlaneWave from ipie.legacy.systems.ueg import UEG -from ipie.legacy.trial_wavefunction.multi_slater import MultiSlater -from ipie.legacy.walkers.single_det import SingleDetWalker -from ipie.utils.misc import dotdict +from ipie.thermal.trial.onebody import OneBody +from ipie.thermal.walkers.thermal import ThermalWalker @pytest.mark.unit -def test_pw(): - print("Joonho") +def test_thermal_walkers(): options = {"rs": 2, "nup": 7, "ndown": 7, "ecut": 2, "write_integrals": False} system = UEG(options=options) - ham = HamUEG(system, options=options) - occ = numpy.eye(ham.nbasis)[:, : system.nup] - wfn = numpy.zeros((1, ham.nbasis, system.nup + system.ndown), dtype=numpy.complex128) - wfn[0, :, : system.nup] = occ - wfn[0, :, system.nup :] = occ - coeffs = numpy.array([1 + 0j]) - trial = MultiSlater(system, ham, (coeffs, wfn)) - trial.psi = trial.psi[0] - qmc = dotdict({"dt": 0.005, "nstblz": 5}) - prop = PlaneWave(system, ham, trial, qmc) - walker = SingleDetWalker(system, ham, trial) - numpy.random.seed(7) - a = numpy.random.rand(ham.nbasis * (system.nup + system.ndown)) - b = numpy.random.rand(ham.nbasis * (system.nup + system.ndown)) - wfn = (a + 1j * b).reshape((ham.nbasis, system.nup + system.ndown)) - walker.phi = wfn.copy() - walker.greens_function(trial) - # fb = prop.construct_force_bias_slow(system, walker, trial) - fb = prop.construct_force_bias(ham, walker, trial) - assert numpy.linalg.norm(fb) == pytest.approx(0.16660828645573392) - xi = numpy.random.rand(ham.nfields) - vhs = prop.construct_VHS(ham, xi - fb) - assert numpy.linalg.norm(vhs) == pytest.approx(0.1467322554815581) + hamiltonian = HamUEG(system, options=options) -test_pw() + beta = 1 + trial = OneBody(system, hamiltonian, beta, 0.05) + nwalkers = 10 + walkers = [ThermalWalker(system, hamiltonian, trial, verbose=i == 0) for i in range(nwalkers)] + + +if __name__ == "__main__": + test_thermal_walkers() diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index 286924ae..eb8d921a 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -4,11 +4,11 @@ from ipie.thermal.estimators.local_energy import local_energy_G from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number from ipie.thermal.walkers.stack import PropagatorStack -from ipie.thermal.walkers.walker import Walker from ipie.utils.misc import get_numeric_names, update_stack +from ipie.walkers.base_walkers import Walker -class ThermalWalker(Walker): +class ThermalWalker(BaseWalkers): def __init__(self, system, hamiltonian, trial, walker_opts={}, verbose=False): Walker.__init__(self, system, hamiltonian, trial, walker_opts=walker_opts) self.name = "ThermalWalker" From 1b692e035185e64c3b6f0cf54afcf91886c481eb Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Thu, 31 Aug 2023 15:39:29 -0400 Subject: [PATCH 19/84] add generic reference json --- .../tests/reference_data/generic_ref.json | 1 + .../{example_generic.py => test_generic.py} | 39 +++++++++++++++++-- ipie/thermal/trial/mean_field.py | 10 ----- ipie/thermal/walkers/uhf_walkers.py | 5 ++- 4 files changed, 40 insertions(+), 15 deletions(-) create mode 100644 ipie/thermal/tests/reference_data/generic_ref.json rename ipie/thermal/tests/{example_generic.py => test_generic.py} (58%) diff --git a/ipie/thermal/tests/reference_data/generic_ref.json b/ipie/thermal/tests/reference_data/generic_ref.json new file mode 100644 index 00000000..d042dba9 --- /dev/null +++ b/ipie/thermal/tests/reference_data/generic_ref.json @@ -0,0 +1 @@ +{"WeightFactor": [1.0, 1.0], "Weight": [1.0, 0.00031475080684714826], "ENumer": [0.12706480956961563, 0.00057748930951224], "EDenom": [1.0, 0.00031475080684714826], "ETotal": [0.12706480956961563, 1.834750847176334], "E1Body": [-12.035567865348977, -1.6611431481738972], "E2Body": [12.162632674918592, 3.495893995350231], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [9.864020634242591, 5.424380018458521]} \ No newline at end of file diff --git a/ipie/thermal/tests/example_generic.py b/ipie/thermal/tests/test_generic.py similarity index 58% rename from ipie/thermal/tests/example_generic.py rename to ipie/thermal/tests/test_generic.py index 432283d9..f9982b34 100644 --- a/ipie/thermal/tests/example_generic.py +++ b/ipie/thermal/tests/test_generic.py @@ -91,6 +91,39 @@ } -afqmc = ThermalAFQMC(comm, options) -afqmc.run(comm=comm) -afqmc.finalise(comm) \ No newline at end of file +def compare_test_data(ref, test): + comparison = {} + for k, v in ref.items(): + if k == "sys_info": + continue + try: + comparison[k] = ( + numpy.array(ref[k]), + numpy.array(test[k]), + numpy.max(numpy.abs(numpy.array(ref[k]) - numpy.array(test[k]))) < 1e-10, + ) + except KeyError: + print(f"# Issue with test data key {k}") + return comparison + +test_name = "generic" +import tempfile +import json +from ipie.analysis.extraction import extract_test_data_hdf5 +with tempfile.NamedTemporaryFile() as tmpf: + options["estimators"]["filename"] = tmpf.name + afqmc = ThermalAFQMC(comm, options=options, parallel=comm.size > 1, verbose=1) + afqmc.run(comm=comm) + afqmc.finalise(comm) + test_data = extract_test_data_hdf5(tmpf.name) + with open("reference_data/generic_ref.json", "r") as fa: + ref_data = json.load(fa) + comparison = compare_test_data(ref_data, test_data) + local_err_count = 0 + for k, v in comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f" *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f"name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0] - v[1]}\n") + if local_err_count == 0: + print(f"*** PASSED : {test_name} ***") diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index 94b3026c..bd0ab8c7 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -96,16 +96,6 @@ def scf(self, system, beta, mu, P): change = numpy.linalg.norm(Pnew - Pold) if change < self.deps: break - if self.verbose: - N = particle_number(P).real - E = local_energy(system, P)[0].real - S = entropy(beta, mu, HMF) - omega = E - mu * N - 1.0 / beta * S - print( - " # Iteration: {:4d} dP: {:13.8e} Omega: {:13.8e}".format( - it, change, omega.real - ) - ) Pold = Pnew.copy() if self.verbose: N = particle_number(P).real diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index eb8d921a..0e22086d 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -5,10 +5,11 @@ from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number from ipie.thermal.walkers.stack import PropagatorStack from ipie.utils.misc import get_numeric_names, update_stack -from ipie.walkers.base_walkers import Walker +from ipie.walkers.base_walkers import BaseWalkers +from ipie.thermal.walkers.walker import Walker -class ThermalWalker(BaseWalkers): +class ThermalWalker(Walker): def __init__(self, system, hamiltonian, trial, walker_opts={}, verbose=False): Walker.__init__(self, system, hamiltonian, trial, walker_opts=walker_opts) self.name = "ThermalWalker" From 3fe8a611833b83ed5f7bb14d3c9be8a793e82b40 Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Fri, 1 Sep 2023 14:40:04 -0400 Subject: [PATCH 20/84] updating thermal walker cleanup --- .../propagation/tests/test_planewave.py | 2 -- ipie/systems/utils.py | 2 +- .../walkers/tests/test_thermal_walkers.py | 2 +- ipie/thermal/walkers/uhf_walkers.py | 23 +++++++++++++------ 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/ipie/legacy/propagation/tests/test_planewave.py b/ipie/legacy/propagation/tests/test_planewave.py index e05b2604..ed12be56 100644 --- a/ipie/legacy/propagation/tests/test_planewave.py +++ b/ipie/legacy/propagation/tests/test_planewave.py @@ -1,5 +1,3 @@ -import os - import numpy import pytest diff --git a/ipie/systems/utils.py b/ipie/systems/utils.py index b0de9ef4..55049f08 100644 --- a/ipie/systems/utils.py +++ b/ipie/systems/utils.py @@ -49,7 +49,7 @@ def get_system(sys_opts=None, verbose=0, comm=None): nelec = (nup, ndown) system = Generic(nelec, verbose) - system.mu = sys_opts["mu"] + #system.mu = sys_opts["mu"] elif sys_type == "UEG": diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py index 287618f0..7c47c42c 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -4,7 +4,7 @@ from ipie.legacy.hamiltonians.ueg import UEG as HamUEG from ipie.legacy.systems.ueg import UEG from ipie.thermal.trial.onebody import OneBody -from ipie.thermal.walkers.thermal import ThermalWalker +from ipie.legacy.walkers.thermal import ThermalWalker @pytest.mark.unit diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index eb8d921a..f781ea0e 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -5,13 +5,22 @@ from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number from ipie.thermal.walkers.stack import PropagatorStack from ipie.utils.misc import get_numeric_names, update_stack -from ipie.walkers.base_walkers import Walker - - -class ThermalWalker(BaseWalkers): - def __init__(self, system, hamiltonian, trial, walker_opts={}, verbose=False): - Walker.__init__(self, system, hamiltonian, trial, walker_opts=walker_opts) - self.name = "ThermalWalker" +from ipie.walkers.base_walkers import BaseWalkers + + +class ThermalWalkers(BaseWalkers): + # def __init__(self, system, hamiltonian, trial, walker_opts={}, verbose=False): + def __init__( + self, + initial_walker: numpy.ndarray, + nup: int, + ndown: int, + nbasis: int, + nwalkers: int, + mpi_handler=None, + verbose: bool = False, + ): + super().__init__(self, system, hamiltonian, trial, walker_opts=walker_opts) self.num_slices = trial.num_slices dtype = numpy.complex128 self.G = numpy.zeros(trial.dmat.shape, dtype=dtype) From 4c1e2c64fc859549a38883d26b8e1e8c36d3fd3c Mon Sep 17 00:00:00 2001 From: Tong Jiang Date: Fri, 1 Sep 2023 17:41:20 -0400 Subject: [PATCH 21/84] cleanup ThermalAFQMC class for only Generic case, by inheriting ZT AFQMC class --- ipie/thermal/propagation/continuous.py | 2 +- ipie/thermal/qmc/thermal_afqmc_clean.py | 193 ++++++++++++++++++ .../tests/reference_data/generic_integrals.h5 | Bin 0 -> 30056 bytes ipie/thermal/tests/test_generic.py | 110 +++++++--- ipie/thermal/walkers/handler.py | 13 -- 5 files changed, 276 insertions(+), 42 deletions(-) create mode 100644 ipie/thermal/qmc/thermal_afqmc_clean.py create mode 100644 ipie/thermal/tests/reference_data/generic_integrals.h5 diff --git a/ipie/thermal/propagation/continuous.py b/ipie/thermal/propagation/continuous.py index d534cc13..cfd43a43 100644 --- a/ipie/thermal/propagation/continuous.py +++ b/ipie/thermal/propagation/continuous.py @@ -49,7 +49,7 @@ def __init__(self, options, qmc, system, hamiltonian, trial, verbose=False, lowr system, hamiltonian, trial, qmc, options=options, verbose=verbose ) # Mean field shifted one-body propagator - self.mu = system.mu + self.mu = hamiltonian.mu self.propagator.construct_one_body_propagator(hamiltonian, qmc.dt) self.BH1 = self.propagator.BH1 diff --git a/ipie/thermal/qmc/thermal_afqmc_clean.py b/ipie/thermal/qmc/thermal_afqmc_clean.py new file mode 100644 index 00000000..65ac114d --- /dev/null +++ b/ipie/thermal/qmc/thermal_afqmc_clean.py @@ -0,0 +1,193 @@ +"""Driver to perform AFQMC calculation""" +import time +import uuid +from ipie.thermal.propagation.utils import get_propagator +from ipie.thermal.walkers.handler import Walkers +from ipie.qmc.options import QMCOpts +from ipie.qmc.utils import set_rng_seed +from ipie.utils.misc import get_git_info, print_env_info +from ipie.qmc.afqmc import AFQMC +from ipie.qmc.options import QMCParams +from ipie.systems.generic import Generic +from ipie.utils.mpi import MPIHandler + + +## This is now only applicable to the Generic case! +## See test_generic.py for example. + +class ThermalAFQMC(AFQMC): + def __init__( + self, + num_elec, + mu, + beta, + hamiltonian, + trial, + num_walkers: int = 100, + seed: int = None, + num_steps_per_block: int = 25, + num_blocks: int = 100, + timestep: float = 0.005, + stabilize_freq=5, + pop_control_freq=5, + verbose=True, + ): + + mpi_handler = MPIHandler() + comm = mpi_handler.comm + params = QMCParams( + num_walkers=num_walkers, + total_num_walkers=num_walkers * comm.size, + num_blocks=num_blocks, + num_steps_per_block=num_steps_per_block, + timestep=timestep, + num_stblz=stabilize_freq, + pop_control_freq=pop_control_freq, + rng_seed=seed, + ) + + system = Generic(num_elec, verbose) + system.mu = mu + + qmc = QMCOpts() # should be removed later after walker is cleaned up + qmc.nwalkers = num_walkers + qmc.ntot_walkers = num_walkers * comm.size + qmc.beta = beta + qmc.total_steps = num_blocks + qmc.nsteps = 1 + qmc.ntime_slices = int(round(beta / timestep)) + qmc.rng_seed = set_rng_seed(seed, comm) + qmc.dt = timestep + + if comm.rank == 0: + self.uuid = str(uuid.uuid1()) + get_sha1 = True + if get_sha1: + self.sha1, self.branch, self.local_mods = get_git_info() + else: + self.sha1 = "None" + if verbose: + self.sys_info = print_env_info( + self.sha1, self.branch, self.local_mods, self.uuid, comm.size + ) + + self.qmc = qmc + self.qmc.nstblz = 10 + self.qmc.npop_control = 1 + + wlk_opts = {} # should be removed later after walker is cleaned up + walkers = Walkers( + system, + hamiltonian, + trial, + qmc, + walker_opts=wlk_opts, + verbose=verbose) + + prop_opts = {} # should be removed later after walker is cleaned up + + propagator = get_propagator( + prop_opts, + qmc, + system, + hamiltonian, + trial, + verbose=verbose + ) + self.propagators = propagator + self.root = True + + super().__init__(system, hamiltonian, trial, walkers, propagator, params, verbose) + + def run(self, walkers=None, comm=None, verbose=None): + """Perform AFQMC simulation on state object using open-ended random walk. + + Parameters + ---------- + state : :class:`pie.state.State` object + Model and qmc parameters. + walk: :class:`pie.walker.Walkers` object + Initial wavefunction / distribution of walkers. + comm : MPI communicator + """ + if walkers is not None: + self.walkers = walkers + self.setup_timers() + # Calculate estimates for initial distribution of walkers. + self.estimators.estimators["mixed"].update( + self.qmc, + self.system, + self.hamiltonian, + self.trial, + self.walkers, + 0, + self.propagators.free_projection, + ) + # Print out zeroth step for convenience. + self.estimators.estimators["mixed"].print_step(comm, comm.size, 0, 1) + + for step in range(1, self.qmc.total_steps + 1): + start_path = time.time() + for ts in range(0, self.qmc.ntime_slices): + if self.verbosity >= 2 and comm.rank == 0: + print(" # Timeslice %d of %d." % (ts, self.qmc.ntime_slices)) + start = time.time() + for w in self.walkers.walkers: + self.propagators.propagate_walker(self.hamiltonian, w, ts, 0) + if (abs(w.weight) > w.total_weight * 0.10) and ts > 0: + w.weight = w.total_weight * 0.10 + self.tprop += time.time() - start + start = time.time() + if ts % self.qmc.npop_control == 0 and ts != 0: + self.walkers.pop_control(comm) + self.tpopc += time.time() - start + self.tpath += time.time() - start_path + start = time.time() + self.estimators.update( + self.qmc, + self.system, + self.hamiltonian, + self.trial, + self.walkers, + step, + self.propagators.free_projection, + ) + self.testim += time.time() - start + self.estimators.print_step( + comm, + comm.size, + step, + free_projection=self.propagators.free_projection, + ) + self.walkers.reset(self.trial) + + def finalise(self, verbose): + """Tidy up. + + Parameters + ---------- + verbose : bool + If true print out some information to stdout. + """ + pass + + def determine_dtype(self, propagator, system): + """Determine dtype for trial wavefunction and walkers. + + Parameters + ---------- + propagator : dict + Propagator input options. + system : object + System object. + """ + hs_type = propagator.get("hubbard_stratonovich", "discrete") + continuous = "continuous" in hs_type + twist = system.ktwist.all() is not None + return continuous or twist + + def setup_timers(self): + self.tpath = 0 + self.tprop = 0 + self.testim = 0 + self.tpopc = 0 diff --git a/ipie/thermal/tests/reference_data/generic_integrals.h5 b/ipie/thermal/tests/reference_data/generic_integrals.h5 new file mode 100644 index 0000000000000000000000000000000000000000..cd0fa383c3589e3ac847d0d975ef0f1c73bbf214 GIT binary patch literal 30056 zcmeF32{4!K|L<+dQVPiu*_TRolI6baOCf7fWXTrF79|Olr9z<;?Z_TNWV}v_FmN=gKx}P(1{%6jA&YYPuXU?4S{ANPw)%*Q=f4+A;&-is+PfKSj0~Z6uKmX9t zQP5CqC*J+{n|1OZS3mSU|9<@MkK2*&P?B#W$+sC)=p9OmfBr{7!9jjMGs*vtpJ#5W ztxd7Wuel8^yBBB=#1;zj9E%nCb|MQv5 ze1HPot{R0LBZb^LHHxrl<9q-4aVjbVq$6J`)Rg3>Q}B_Wi9Vl#;=;f0{2zI1W^_c0 zl7jlbJ|!+}`p;wh`?`;${m(z|-`DkjZ2O=8tp9s|^uNC=beWVJ!~gS-09oxn-qru; z`~TPPjE@ohQfhAGFG;>}{ck_~-~7>k?*m-~vO%$NasR8YBRleUu75A=-y-+_edqt_ zw*{J~_HyHYVaZ#@Xe+yqF#g*5-Ii}f00tyavC7_q)BUA-4b6c-tl=4mNVJ1eQFl{{ z0yV)S&C?C_n?&K@sY=!W3Pz9|MZ4%fK8yd$dEU^vOSgxz>hjgCR};EAVV>EWTu!kP zVBP6CN zZztKSoXo>da{5Aw0xC3Vs=}@EUyn3&LiNjcyFwL9K-{gfmptneVKm7d>mc(ULmt{l zKT2e;Kr&Ad$>}`nzWaJAO_hbPN2)nuMQ{j&`^*3ijba5Nk403FC#L~ zzno!`n@avV0j$VF^atcOW*Y6LMD8_7dVWauh$4GkAoJWOId!B54$_O3Iod7hBD#lk za`!LfUO}X1ACh~U>}5yh`FE#PayK1vM+0)#QSyGilDqF9_ZlEQ8<2i{$X*zk$B^V? zlXq4@-fu2>hkoS!u#vmZkbC{>`5NixG1<$A%=2G484d+ucv= zZ!n6NbKAr1pW)02h?C!SpW5T<2%rEBI|6>k!n2IEm{)&mahVp> ztB}k?L2@3~nfE&0e+TMM&>YjaZwF)d{0^7a0pMIv;>*AH#bEDh&N0^CTYza{HEnms zJU*20z|MSc8^#)f{5&9g^*NzDK_tidz0qvzhdR`>`oC!v~<}Fbko@B&H`fQ(Ao>>m4 zco|!KspO!?1p8O%6&9f8i$yBOF5>#+?keP7sibGiHRNZPKkB73jq(`pMjXDvMkVW# z5}>vi>yv#-6jInZFho?BV@c%w6qCCTlY7mQp6ybQpM0_x-4x1m{|Dmy)VNVjQ&|Kk zFu5F!FPniRd53A_{j8F^pS*|m@?k}udrFa?DnHbVA_L{2&_bN60WS;ps}+D#;%iOJ z&K__o-9O2sRvW1LfB51P(2hG_jTljSu@!tAZ!s$Oo53|hoQ6#YpJ8kgn^&uBDlqG) z-8Ub_LcHv=N2mNiIo1|0(pN|I6qn0DoCmfqqt9wR1MT#|eJ2adf!OWns-z`x$b8NH zwJ=}+*cpdsS!XkGQRab@HLr$nc4dP@sb_~Vb9Py!-+u=1p~Nc+`=nQ$m5xRab?yln^MH-5hmSZ@rrexd-Q3Cc=iCxyOQ8Rh6vPY zRB|6P-~$XtSih9-PGk9~Mhz`85R)xoMFrP=6yV!!H`Hq~2j$UF zwE|bq)PPar*03SLFoo&rNya}(`8poI34B0c|Z zKz=yMUQ9<(oKVSjZ$oml@cc=JwFC*mHj`VYb z>@`B>IY4si>bk}Htw%sem`nj+h^{P6L@;q%o zoM%dNa}K+{g6q*sFV7iYgPY%ux@!x`gFeYT_&f9vurGda?&+7qus0jG^hlKfdJMKY zw6;4z;>yv?6Ey4iP~HGV*r!j}$tTZBByw^5MdI^Qvsn+Z;d;b*AQko|#iAT&;JV7X zcWR_){-;pKvS`@K;M>FE<9RJ0G5`IBO3QweR*wYimNP za}k3Jt9+ojYJz%~0wpy4Yq96vxj{^v>}5&jaUwZG(NaCi`oqA?^l-Xu%?)^Oj3#2U z-xYXKddHf%s6EImVc|`UKL|Ur*E32OIY24bFw<4TAGitWCxq;^^&HCMY=Sr{<-e;6 z=;pvlIyWWGEjM8&|F*%~bY_6fB}Y5W(j1=JRafJgbO89rtHD1jY|w=CoJIQaAbSOo zdF1F3$0>J-+2zJCILi0E=zdQu%&#cB+AQn={<<-53x8z-c~uXYrUyuY7;-N+(sKss z$A;|XAc*p4lbr8Tr-~}q+5tRkZ#|vi3v;bw_V#G&f~_fEC#6cn;g)=~yA!#W5a~Ib z^ixXq>L&ACBRTs|o^_GER||xy{tPGks)ERV?a7*ADG*NHk6<6#{VTaw7wNf;^uyqe zdM%tldGf0f$IjDVcRjoS%rU-sWFVvqa>+ZS`iAbujNCn&+-rpNY)tymBYW9>LV4^M z5Qmr6`{C1)OHi?7c;KtkNjRgnBVeje9cZ_z?EgE(2XiDYDsM^`10&Re!3@VXL6yq7 zQlDZPxRY=5$H!HxSS?fd;M~jz-m{J2o(^9LesuAY=Uwk)j8z?R>Q_{9Rh46b(mk`} zNEu6T*7mHwE`<)1z!e$XH3UF@hD6h+U1H$Lk`0gd#BP|Q@F<3#o(43rW8ooJda-lt zjK8g_Yw+*yQJ!Lw6VzVaQ=swyuzxpfDOhs>4ibHJj-J9m8x#h}RUL+GZ#Lh#{S5=D zyE3oOE%QS!KjU|J${+mvb_PmHj}gpI67@2+LwQn3&QCn^%F^EuKzX?@;mAFGFnV{q zWJjMXI3x7aDVoU|a@5xhy6*x&>kODV26ll_{#li_A}aWi^utT`YL!BH<^m8Ww!S%5 zBQzFTYQ1g9YIT8K<6~p%Iv#+a-WWQIG`M$Z~uBjoM{Bt ztRMi^*C`u()xHk9osEh;OHKp7sqdl!Qp&I_HOz)xd?(2NT_v0~_Y3d3>|;L4--$hb z@ipbw#RB|91j=K%hB)|#)9ZdIv!KK9mj;7i5VXz%mOJCsfv)lO(NR`AXwD;bOY*cP z(7xZJWg;a6Uk4mw`xLnuJeW&$m$jV0E684TWS&?f#Oc|YdB}KA4@fR*6bes^hIS3l zwfSBI0+!JaS9sO!;PFi(35?MIgqASq4%hR+>Fw59vmWah$64g(3)$<@OO)qd&SqJE zk%Qw8VN`DJHREbCIQXGue`bY#b~t?l}Wc^O~4p2iV^S<&3SUi%;oZy-HCCjFcw zd+j6hbY>yWa*^tnV{fj*BCjQ7`XfGI;N$SYKe_raKC7gAwn7Zlt(-bCuSW}ccc8s~ zke*#gKSLv^*Y5Wy&pvO&X}d8eMiR^@q;fnaX=N-KR0A2F;J7mE~}qfVOq-GTizCK&fy0i8Gi5ys$kc*(yU9hPW;q&mLq2LA|W@i=EwgCJ*wn zdoSw6`V-|*vqzlPgFE`CNAJV>xdXkKr*6T`gZ*x)T~^Saz98rFiWgw1eO2uISOZpS zXm1K+Vgp&EXED-G6WMDYndb({xm)NF%niH1QPx6BnHSUo@m zc|U@ZX!nogUa6$#{iGiQvX?!X=Ml;AR7<`S>Q@NYXbd)|`T2wS4s?ffN74O=$)Mf0 z_oKbUHIe5WdgMnu67_N>^ZeL^I5Vtzvz`GSpa%E8tUH_wFHHK}TT%@Ksb5k(&c2O? zSLi~ImTNkK6yLvRc8aUQlwF4HR?m3>Yr==$cTZ75S)=7$b>bt~W$LIj=a3p)PqQUr z^++=2FpW4#C#ds-cZ>u3@p9>-whln6o*}pM(FMSe(7&?+cY-`$%eJO%(gr_2F;&I} z3&Rsl`my2hbRe=U;qA5OGx$r(h}~_S4OkkPhjAEjIJ@8b%SmLy)vkfmtxVBSy?@4r zGR6~}4A6TQpRWn!lncwZ-sJ3Q-%>&)(czpUWy4si{(W7CV2Edsz21^}(nyXS zXU!NrTM^t|?5p`X{XF>fc<_3zpe5WE4fgUL1>l=S@hy3JUU=oT!sk1V>ljbRx30z4 z19&#+$C2zc(1-FEksMWn)R>np8-ETQNjzHq>=>Zy%{)G)ssNi)F?$!v?ZDne@?+qo zFL;L0srS;EO;|4J*@*Pxb^-O8d4lr%9z~o@JayV1{{(`<6ZX3YZ0GJaQate!FBECfEk zyI4jW+=01bMf+;4K4JRg?vKd5-nAmnb)=sWve$|b%9E&vI4=6z&-8qhh3|OMEZcX> z0=WR>I$jXoruWm#-NFv5eyLyP z;SdE6{v36D7gL3aSzkzS>Y2c<@AqAi2&=@0`zl+lP5N+8^DBILBaQg^OT$})3v=+r zh+ysn%?2#cGybrtYcjTP32`1;+>Yl9l7`IBzEoL+%7Xy@(`jC%bTB0ScJWfn1ZJ=l zR3-Lj1rxI>?kU5+Vx4qs*Tw+-bajl6!ProeFS9-?dIobw6nT>utE?bP%-VR%I>mNP;!5b*u7+ zOdzqfFu;C?^y-17(d;TJ`{@D-Ft_X6UakI;~L z@hK6g_{eFmQU(ClF0(feB?aRk=asZwq_xeS8UigXpl;@#d|K>SO za`M`;w;eaS2sEer<40zq;hYH5Z19;&;K#+D_IJbf;8-x)U78W?1&Wbpj&sP5OEKzo ziOkbMas@pg0%WgNGLP3u z#2H}@TG;-547h%}Dv`Au1Wd>~tR?Sfg4}%{xtA;H*_HJ3g6vgK=Ar0E9B(zQ`)@~c zp+FSx<93^!fOhEG(5CVgoUY|&7sV-V__l>YpYyaL*rUWat|-I-emULcWF1|E_`3$%4+`ui|Do)) z*$Qqy=awhRrvVQrn`K42YJs1vpSyfBc|ntrB<0ovJ$P&!`wczod~5)oYojO%#}(eA zJeN-+4(__;@z{Ge;21k$Lfv`+WO^@zYJEEk?q)pvsaWm>=Scmd_y^T10We@3pRun?j&2yG}2vxLe2BIfb3ha^!_5P;8O>1Y^UxJo~s6bH7QuA?B)idq-ROePbAsvG?~W- zAkNU2w%TV5<6!b)kg0n3LC_=k!D(l}B{2ItUb>3?6s+{xF_kQ<4&EO^dsUI1-AF%k zWUmM^kBtlBWH=uWxbrOshR81Yc6voYzdc!Fv|ZL9;XTC>zbKsxX8Wmp+qhN3SzWXPbZNS}uzDRZtX{aJ;>sk%AgI9q?>v`PY@Sq;# zxv?JknIU@(ka_e;j#d4Qdm2nv0JCqOK$U6$C^lDh_`$9XZ=D>V3p5u1<Lqdv<^jT_gPvxZ1UKbCHLFiKXgO714hVXEwhWai4nt>5jdcYs5UkFYdBq3cGdTlX>2Ug3Tg;*{WXR5H%fi zri%m_{gYUJ=<_o`p%Kr@Soaiw7g{Qyu4AQ^ERL-MbxCP3yjpR)3 zIZDx(cL^pnbNW~~7(?D7!&1Iqg5d6I#PJ!+5!`M0`io1O%PR$tv(;Ng7?hb7R`U$hiTqHyPu>*dl_9to`qW@2|vE_sMl&`9Fb?66yo@I z8A{|`l!upoeNP#TMPSYZ;7Z^B=?#DC)?Y_+p?e%&)^87^)`MLW7^`cxuc{XVv zj*`F+rEl?jp}51-3+IFQK$Zx)!;|Uge!N}L?(`Ks#9qtPoP=j*&H=)Y+__ky7llIu zktg#k;#e}M+b(Nwhh|c-5jSURF@3f|OTVa3n4G`F-a)ll%xJN`RQc>XOwdN!nuRL| z7fUX^03N-HT52Z2M68ZRH6z?Y8bOwTY-fF{qUY z{}CDBl3FyE*T@Ykdak;Kn~mUaELC(nH(qzuq1zo4H(t-eVP{6WHl7o;!pM(h6Y90* z@{q`5Xn{B}$YV7tDYeV-f3#WkEnwK%ZL1AkVhi$j>i!)JsAhGEzx0}*lSKKh48GKGeY?3TDwN{N{~T$ijxuNmszf&=f-oQ_ty`>k!=y+ zU{tq%|HgC8WXEgq<&EbhBRAUJUI6WdeL|k8jv_x#@=-53Zj?uW7#!|9k`OHAs54CjGd@qh2>+P@WNzb6<4774OD#IPi99 z4BU9W=QN=^Ol3j$(;J6&54?u<5+gmooj`tuSx~Q89h66p-gkN9_YKCK!FSZy zMPX2Clh3|+Gq9iO-L{RdMS{BD-ruq?SA$oNeUue=s0G7S=g-?M{KeoK@6|sKCh>gc zLkrQ?jTp0xpTyj&EWA!^OTk)4IF^%)I8N3-RCAI;;Ml>}Z;DF7LB!}a=1bOR0Nkw3 zr}M!H2wnQl=V`?aukJ76E2h~Dvaax7vOGJDCzxl+E(*TGehAUhwymb&bId4@kuu_Z zgJ8gNA_CY78yi2JPlOZJbf+X8!{EfV1x>yNd0^9J&UWVq4-9yr(=#Ja0Z!_lQ?M`` z#%Y4*#-oeMu%QLiD{lhjp%6u!(~mDarcFtQrcZCDt5Q~gtDyz8nJ2>F-qR&}cB(l8 z$FTQfi$8SX^cOyzU0Pz`v4Z4ng|JP~=qU0NK#O{9CG%vHoTlrwOnK4iaBFaVPT0OA z=wg0~-fPVRyo|JKy}seKTJw9<(tAN5NpYSkoyo3quUK@h;n#e((ox_oz z*l^VAiZ;rldKhtDvBvDzy1NTRu&c03@mhjzE{9Z8+O2SlB)XpjQ?$E{9@^{GSL8WN z1Nkv|j(P!hlt*kA;ymfOqxC542z;E?l601P7oZkJcgR5APv2#ym$1h}QJFa`^VqTK)tO)K zhp-E=SGAJ-M{$e#aSpD`ZQ zz4>}=?b^_@)UW=V-%*g2bRZ}Bpe4*0+?O4`LlagGx99_FJs2gJEo1P725{R{|Juj@ z5qFC~er`9TUXm&(PcTHB)Vbl0+JzzTHiegeK*q*%!o)ggsPGIZoD~^3xz!n%%krgY zD)YnCS8(Cao*68y4tZ{nMt*w9UZxLGp7SIpa)fX4@y4G?CC*XbGGYg&nWvWIC{e%n?ARR# z>b2H~RQ|d{K1FngPesuEnB!=7EiJUypK#=vA|;XVqq2f}?I!bZYak9!%bncom$X4^ zjH|Hrk~y3yz#gm&TmkJ8qOVWoT!-F{*OSNIngP>rip0%B63}#y6$b@78z`&3m+UzH z6CbyKyYunYE^JMK&SuBA*SP0vpWAAp_pqJ$h;!w4VtK7lKHR;4M`zNNgGRjf}qhWFRN62XxHmhvEao=QJXktXJnRM^OBB+051g zY&#%lXQ}v+`|DU+Uhmq>&rkTK?t501^OacQUF4@K1NC~xi1Hj!N1V1HMRr3vb0~Im z=?wRf8;}-qv9XX-fjd;VV&cEDfjdvEwAC7yafcY|@w}-H?3fJl%$SP&2r!^tGqosB zb`;|5T2#z8jj)BOdrFw?)x-eB-p(jC`Q6|G|C>v)M>;WGu1?P&)k-X)3GF3)A9)V< zLVjlQQ7>;{lqZZ8al8Y=)py&{03O4-g0$01xI^AC?t5Ybm~X@Ly1dX&_|wy9_lVbM zuS{FyndTkx6QhrMvF}28-e0XHI2HQ>ZF)47pyyE6wKYCnz_&?FbFW4;Zi%7$2~I(~ zM|GgR!m^QPwG8AZ_D2=b%Ujfv$b)}E9LDdA47LxI;oF@T4vDr?g2Onv!{%4$eyljr z?(2hSuManoXM+*s$K5}T=ta@SLFDnNI8SiA#VzYrXD!#(#a{ig7>4zZdXK56jUsymfyj|zNW%(u)ASYb`eud0zw zK``qg+{blT6nHL)m8!h?gNF$9@MV;}$HvNQMSuLv#uLAyJi;#!CoW%E-Qbfge3EIS zoe<>)oS#rXD!eNUuKM)EYMs`CF|yQlvHH5O@3~z3{2mSvsdWC`diXc|`M2$7FYju` zk}slO97jyA{x-r+3Kxw$& zOjIe^loF(DnTS-a`HaWkLVmO|Q7;gR^4uml2TMP+yC&WS%XR$xo2Bl+hWy=h)@ETa zXSqlE+tH)o!75BonHGf|YG&=%ztVs{U*y^BJ@RwI5A}M_hw{w7MI7prMYQ${=}^u~ zwS7ju94K@53R`4F!`HXyvRk-a!8G+XTr5u;UN%O1RX8EfEmFwOsyOPE`vT>e@ z2Dg1G!?s-vUYKm{#7YOU%Eg+~FsZguccI~Ytd?u(t!&;qT=PhVa`ZwX_DvRXLf%&x z%Op|&4<gu0jE|OZtHUPG zl9c&@>VZE#F_UE&jqnxwwu4gd9`ztYD;$-_Ud;s-Q+=cRBCWyn`zB(L0 za~Pgvq6~3yPyz0?4;O3rlws4w#%AAYU{o2UqrxjmqN4C z8Tv50!1zOY8ap`Pf;12amII>7IgTm30uw? z13!$bM9bS5M1C8&f4NTczd%^GjQsmAXQ?ydCYedo7gk+`1r3_+d^)y>=|3JiF}>$DUbl z5_OCh@qFbo;gdT~cWNp^HUXa*o^WplbrWE zy!293^Put8RqMYsp`b?(-C=kwx*ww-X!k#JXs?)Tzz4t_V@z^<=`O!L z*y#;_y}TCvJ?$J&JHtU0f0zOcB%P1Jw`~IQEt~p8=;!f*A8zGO?W!@3CgjFt`(*H5zsieppr}iCzp2D9-~{#NlwYZ^=rY$24u9p54B@j2++ml74I0 zP8e`&XH@#QB$zdPU2DFN2L^?`kDB(Sg8RzerJcIB@#h$0xrXZQU%1j_$Wb5mW^Cpf zHLF*39$sUeFZlCjG`1xhae6FtohNeyLC;kHgPPz2GqutTU|5B} z+1Wx5Cfx^5v6~!VsURa=ar+!z5L{fBD%g%Oo<`gqS5Y3$O2l#D-?q}=qz;~qew^{m zHHNP(jSOBf8G+@DoGvWh8HCbX=KgrB03Gl5_^KPwgLINR*NpOJYNKAGy(o|V0OC;h zv#Q1j9D>URCR>ssu7CzRjmZMRDEN0<#?@O*c3=l1;vP&wc~9yf4-$8gAGtEr>%bwD zN5B|y@)rMQ9(K!vd=oF4dg{x-BPYadd4ck_YakE8#mKJ)>G>h)$CB*DPUZ<8N1XB> zhCh}}Wi@0k!s8`x{l!rSOaURn%5xez%i6ZXdWDOf}XQd%% z=bM+%?!#G#JAM!4eMI`nA4I+26O?CS9dSM{Xb^XXeaR*6*W(1bLmg+t9cw^&pJ^ix zr%BHyIml1k7IY5@9VidaBH~PZMz0G~o@cT0_e=o&i85Z>i*6A2H9KFecNP3$Uhoj! zd~)OK-07{-HonfJ`tc#3kY60|+@>w5^H-KI`hK|{rldZ+V9O($(%Ti-n@_nx64^=k zcU{EEjHB?l9_a{zb(oGh?)8Oq$K8LW@A3sBZu>8=S!+W(V;}cE=k5bG_O>-?^^0!V!J`wE0o48|3n@q|vj9O2H=1UUJOpkieS)n`vY(tw%n`=6^rM)1h7i=x?#Lzr5`kkhrNwfHeMajjz~ zpJOu7$dCI))T@W*F_9;HHl5%+-}8cfP?Qz0#DBGWe1QdO?my$ay78R3l3%FwY2)iW ztxEd&)qhN2>3m7|46ZifN7Iq#QG4X)H#_RJd$$IWC&&hIF6R`?9dBa-C0gdOhDN&~ zO~G}qA1tCk$=kc|z7`dHIjr@K=i384{0pi|;WtMeU3=tJIN^+$9+*orQ(J5R(uVy{dd1W%0(K*!W9x}kd#syrAO8440baMc)oW`&5%%m{qPbL{Y9=RN?Ea6v9zf}@}i z|3>D~I2Jj2)xPZW8lGv%cVSwC4a6&T)_-`uga_)(>Ll=uU_DK#16)Owc(>-y9yXWP z*x1o=!4{dfczsgAtIduTSSf7}ktd$!8o_DrD%61`OG`-wd6T`2^I3cO1- zq1{cg&|YcU$a5DH@?)cj zdhs!!Je)j;bK^d%OL&AM`0AnS7!cqFDcaE;Ui3rv6JCXOPgX{IIUGQqrS>8}j|)++ z%U&o?F+buQd1Uh}Il%-BiE2JOwLF8}`I+WTm`_o>)OOejnbxa)!-8~?$ zuAu;)Eo2SP_p-rZ*_{5M0}I%(GqwRo7TfSERWWz=#l6J*@@@BL?YV{fW#tka+r7p& zGmxZ41Gc_Q1TMdC$x_Uzot_vrS<4H6WVwz3J>B zJIG3V4HQNwftywxC0Ip@O zo(Aka2_N1i`9cZ#%`EJczF<4;AOD?V8(-J-s<1-&o&X3b+!v{qxe0nu2EI2qIf8|G zBR|p@>UEX{<++uKI66Q2@{_Xd0Yj_T&!Y7c(D03TJspiAc(`dK^H<3nev?J}$npGP z>~>}K_;go2ZqR}}e@sDs{321WdI6N@nHS=mk$#liv!V&!#GjeA-@y-`q+qv3bm-t{ zPzdGZk$J4NprgA&wi++nj`osRzDRhkAG=EU+4K1~(Tkf4) zQbeze=vPD@iUtk6e>gu6qzhJRT*XrZbLXS@yzypkDXrf647|`Y#aY4&QWjzb)n65safV!(6we8>hQ0+<4HZ1oM`9seg!ntLI^Q9c;+uxR+P;N zOB{q=2RkJhn~W2##yl*u_VM z_Q1iVS+??lFQj7F`Dw?-bE0``zly-d^GBsf&jC|`OdTEHEJiqe#2~G(A+*gJa4bYw1@?Aoc9R_yaAns5*1>Mh)cU8phSNEX3 z%oUL5shh};KM(4aqH9UyQL#ZBj_^?%#*N=Mwm6u=$=!wc>lMM@&!u}YX-1*9!L;A- zZ`LzcTy!@9Dz>L%&1I$dd8H3+A6u#5lbcK`H1R*M)uq@P_RURr;vvV&wW3cj$9*5W z(m#aYN~;*bk(Xbi@`E?=;#C+maXh`zz))7d?r-c80PV)qbvayKDPLGVP)_jw9vK~wUA`q*Dw zqVir<+5rhrIQP-rmQn{gS8Frx_EQ8}YTK@IWi!E@l6gXoNu$`*nq2>pceS`KE$X#$ z-I2(X^|XTE+#9WNii^|)R&o#7nr~Y}tx`&2XJ7 zzG@r1%C!81VQmhZ%e+JQk?&C^dj0XZPvptGi8y;V1z*>+}qA4u1|_*3^y zD2QXH>=M#3hr0)&-mNX|1D@FPM>hnw!YDiBxs_`d;b(-Ylj!xc3FS%ri#U!?6yv(3(DdU3v*EZSH02OXxq)2U*!^cc7$3JoO6R6T2Gv;K+FvdCjM|o zIQxu^6U0h`U*DWAybO{C`-I{u7h`Ckr}uPRMngNci{tgH)g7;K=RYB9xxxvU!5!3V zNfG6te}p(DI(&Lbw{<~IJOBE19W|h36ZqTgku5ab<(t8KQwBsc`{v94+y?6=E#_`* zS;S(3r^6^TTJa*~0>Y1d2kPb2xRb~;u+B$t*sf{6<6csPnMS{dZ~WB;42dGLEKCX$%yHuE5kYhHmm+o}|N zs5rqF|BD`!=qT1E@J-{4wEN6fif1s#1J~|zuUF$YvRH_{T%IG(j>fTspL5GTM6dKB zl;_fiaf0J~YXPrPUc}QY7#YuUFJo4U$G-;uW`>h*DLqg7jbJf;O2qDk`gX)#p3f!; z&pyzH@N=Pen&?F(Cq?90N!vY(PAK9v;lv?-)Yk25s^m(-r|3vYgxSx10 zw7b>yVq!1Xx5%@~AP?cE*nKb2>yE?;BF~hO8o?QE1sxBoNAN@E>l&#XUt`a6(H$0F zMfcNP5lrkZWQO)~JdHflRwF+?U#W>+>-5)%JP9h_2#!taYYtV-7~ID1o!JvbKV0D^ z2Q9l)47TL$`N7pC7vJ(_?y2|VT5K%5aDnw*6#ns&I>%6dFFy8aJG1*j4(8SJ-gDc} zMEt&}>~B7)d~A8$a?m*_6sO8Er6)Md2lX}Y+{Sz9Xe%j?-^MC_4^NiFBx9xKnkv~c zMHu`2;`UC46)e7dMU15_7`^L_r!1@(+KWzwCSh% z!39i!ah5TJvj(5tJW2Gb5OtmUC(oAtbb_<_%k+(E3m#B#z^df5uq>=D>y^x{KMdaH zow4=|;DZl+J-2+jLjguE@r_>ZV}^0NsBEjkMzM6kbixlWn>x|U#~S5nkw6@}_3b^) z)}o-;hax2YxGZG1EQn&`-45#K&7|d=zT>AxzRyxdNq~g0_Eqtab-a8Dc`n&gLimwO zDJOdE6YL}MBvVikoUGT&;zE}N0GIyiJR|)cI7GcUAYSX^955x^xb+rO^q2-$?{WVMe5 zfs;9VUpa*uL1*qZV)u*c*2G?3a+8GTTS>^z+drt+yF(~XzBA&avwYI|P-zJy9=Kg_ z)Nq8$%CnPrwmf*iitZ8$vFPM!;02 z$}2`#2rdkuJFK%n_v0}&L+q~olakoWJPdjMXn_3GUq`*Jw9F8BcJbB_oSz4Uu$#(D zSZR)z;xk%Ld@Gh0YWN`%qd0#&_I#ot)<444>*imFvjuwCtrgc|ie>^gpH$Gp$H~96 za~uY+`v%nsWihWe{vJ0shcWj=?4fZ&l2^Vzp4pfe_75lEqW^U2mIt_O_fzr5x2o~q zAk#DBhkgW?rkwu-aA3O~-5pwXHDB?{s5j`YsP1dWEK(IBpCdJUz>i zKQ9Pgh;8GUyGH>9g<}%cxQ4O6>reL;mg2aPxGB+VOMWqtr|FUj!Ff6ck|lBs!PgNz z4kOD`kVfpd=}o#z;9hCxA#rPC*j-TMp2of(1ggd?!}+c7NIZvo%KS8@P!~Y>5n{+D zddVMkC-PjA)+ac&3J-0Jl8ynh$mECO8{9O8q?W`5`HjD)(eBod&9nHTnEhPqVk7pd zv~D7);XSUYjXXO)Mt(X>P_Oe0C=buqX9VX>?~O|HY(rqn>mhyXs4#2|n;Psswup&I z@?=s4Bw&kUOxfc<3o#lww3ooJ0^vDI82M4Vf_i0m+$Zv!ZgnF#){`-7?0Tyh=upG9 z9WTIbuKo4B*Yg2qJpZS{!gm}K8Gb|Tes@3G>qj0F;knKb`7y6HA$n2W=pyno+j}bi z!;w=cGkkaOCH`FC?X-_+IcB)8Lg)9_X1wb#x*w6qoy6|NmC?jroL`~|&pk)Y2|sZ1 zeAYj`G#jyV|Kzcx0|e*r!_qeb2cP3<67GGkO)@bJ0d$8Idgy*EY|-vFEYMzmf@=uR zhm|M^KZ+@TiC$E(1w@|DMMwJo;V>vT{|;A+!^c8XE}u4plA$ zc+v+`{<2o|565g;E>YZi1#gc7iQ5#If$p;-HHy#nL(4&<=DtN)Fzm+OgPOBF}G&yuxVZAfaKilpe?)!v? zj8Uv}^;Kf!`$Zmp=YNcE`fEh^N!nvV^t$M>g~&tugpc3|Ul>_<&oGZ)d~_^C-~J0W zJQX&UU%PpFb-fi$sKnZqpM z8G2qM{K)J)K=fKa7)0c`xX+Z})ZWR-D4eOoh1VFBly!iT2U{_%Wa4>RE>cxMdJ>sM%Z-9LGb(EOK@ z&O03IJq+VUhm=`LNLKbSB7}V3WMzbsGC~yItc+3_B_Uf%h@z~NgAkSReeKl{8QGDM zmFvHjV@B4EdMB zUfBJ$5-aT0+nxoU>C_iZ2|vTFDqFq8W*mt;Z|)AU5S%J?l@r?wV(^QsL`N%qDQufO z;xcS&iL8vmt{tj&#t)|^)hmbZA@0oXR^{YWyibW-D1Y?{s`lkwtdEYv#xABZkKf)$ zK}=y}|wZxZi zNX*G(Sbn@3Yut@L{5AAF8WL&qQy415(>+P4BBn3V!^D%usgEAw$z%Wd5qW;}?TREg zhVF_EL1iznA@!NGg=ma?CnpvaKlfsLQ_Y#tvRO1uZ|hJy-i^Kf$l6}_Y(bvC68hX~ z8*$c)=C_&7g=l5KSBvNsrknwJO8qM{2u`(Nz7WeZ3ZAhs%}ZJMip;z6L%b7aF+I0H zYTX4IQcJcmtAE)7uKl*XyKiG;^Er_G!|zXj#Y`*wUkN{?G(YH-HDSI){)4&3yqk9@493bLYU13>4aTN*Qz9^C;#=ICw@X z4&cWw;Ux5$(V{?}_>0mz368t_qAu0P8T=W={my8mA?>Z7iB4GKqeQS?R~-E%M{;vz zDrP>rhoZkE340kr$kc)RN%{T(cBh%jfxXhN%Y)~HwC&*M zNW2jA!uRVSk8gnra7H}hbhGqFaksqJRK=%f*GtaiL?LPjQFLbb7#u5F!vD1U# z{C?KaNSOE;-XEO=37L(CRCno zyq(yPf#067yb#%D&jI(p=N;Tco~52VX@bLPsKtA-+MYkc(mCP34WG?TuG4fl- zv$M0MOZ>Y?wM`~x)_bKWLINzG4ZT%Kj1MtzH+24jycO)X!2@;nPw=B2Y6HE}=-)t| zJ#(YL8PMwPPNAox#J^Mia#)>%B=Pb*aP7n|Ltd*SPw-&3|1tR0R(=E@7g$~3^Sq+= z@O8B8r{VihwIpzg_YDKr+G-tM$IYW2UYEwp1#;|}T!viHN4EAF(WHUg#aw03W6**b zdRax90{4;E+!p8Hp9_SC1C&+p!sVnY3J~|;e|2m3X3B;Ku~(?A19%qywdFn5 zhYWd{`>G*Noc9QDxOCjbiQNKK737E=zc+;O5WDKSZtbkl$_u+!H*ax2O>NypmY*AV zm@apKUK}_J@{CgP$`Tx}AXN?G&am~EKXG@@G!DWY2A-XT`$>1Jhuwwawmh6K+VY!d zKLLKyZL8oOwh2z|C-QvgxOtc0L>Mh;R&M@W=uyAWH~6BDxK5hPyRmy=_VX9=Uy6sK zJFdg2D7Hp#YS)3{8sHBB2QI=K5#^tBgajIE72~pOI(*< z8=i?0aE(b^M1sOD)Fz?ZDQ3Ye+G@EU(6OAPk87b{(J%4FiTyN^1m{cepWnkr+Hnt0RzNWA=KIcq zk_^rbuv4NKD#gY~G9)TJzOupwHj0sye#IyrL)=1=;MvEj68t3neGz&IQ$!$7zuZ&c z9BZ7`Fq2!rR2PEI@X9lg>L&uupRyI9kfY5$lKT&nIu}}8862o70ld1fSA~uQc(!=M z2Ywz1YCtb3(E!LZ!l?%wxz6pPp*<^j&)<)AWd?ST%=h2c<=MwgQJz1Zo_~H6_2rhs z?mnR-u$Mz@6nHkMRRKQ=F=fze(Z(6_Tv4O~POjOQch0*dY#RM<*Hq>TD)X|qDqB#8 zH?~Q^{g^T>!0rzfDX`ZX69qhfY32k!@|Vs)FR@U4$P=r)1333*o7D#n4C4gBsAzZ2 z5~SuA4tE%OD**0?bfg+~uU~D2y}0U*gJ;v+Ch#-=ay^ac<<%ACN#v<|JqjGh%E6eo z){%Hu$8NDZrz0_AOM1K(YY8&2lnd|AsKd$sW?XuFdK7tV8B%K#P9Zqgb{mbp-#3gWR?5N`D9DOz$E$56SOwX6a>(a1e^Z$N$czWrIP_D*=b~y0KkjBT#4e7_% zadJ)L3rEj3wE5>;R^e#Z{4+76Ty%CNN#2i{XM{-AYmRxW@L)zP5_uPi#u$T65KX}#+tOq|~ z)-16^FRewDBMWnDUfL-u;X9mZOZ!~O8to`u~}{oEw6 zmxd#oGT}K`rU3jf%g3D~dSz=={U-8g?by-qVw00DurRjou_RL0xzM>zeFWj-@?xqo zrnr@QuHTq+7ir(r3=i;nfG;tOv5+aJVREsa#38N+Tx+S&v@^I zUbXw-F+{l~^1UFq0kjep%IdP&XGM-h4c{ICH|fw)h|KzJ+4v#g3UJTi*s8frd?$WxOzFFv@Z zG}MGL>W$?hw*SWZ!Zr-Phg*>39UtnN(o|e&!3};?-7hW>y?z^3UMBJw1T8-zIA?|t z)tvBK?0AdbMzXORIoZn%1Lsm`8P~|82+KlH|)?>q|(1b=gPqH7kXQX~?ob`a3%5R;!*G zQ-r^EYQSC&dMx01|5_*bDLAMbO7v>#GKM@kL*IdO&~G>{?fxLPj+HEm(VIpVPo5V2 z>y7ctc+dFcQ?W>hP7ik1`@@Z*sX1HA@6{0DjVyI8*=IJVQvhTQwQ zaL6Ubk)m$}XqIc&HD$>t?BYm*`#D+G1iQxy+@L-l0(*rpYJz8n zh(ry-&zJQR&xu~Cbm){ zLWFtxPc-A2BXfkCk)nT6q3E9*o9~B}V3M0RU&8&1?bJ)S4V_Im^=Blv7^~?nCNtJO zM7bY#Bcj*q{Wu!bEUv}Xt{)RRb z#|b}HB{a~>Z1Ec8dDr7zL2w+Jn59>K_TkvC z<7D=fpGe90$C0L{cQ_;}^XA_C1f)~4FOWP~g)h~M_eQGcpwF@a;JHft7Wj#$mWEz; zd}|@k;ptl76klU_X|TT?n@&5d?%wtqy)QbcFqRd~o1$ z;V5n19jv3j2X_BVZwz}KN2TD|#ZWVV@Iy99@g#cPxEahu 1, verbose=1) + estimators = Estimators( + options["estimators"], + comm.rank == 0, + qmc, + system, + hamiltonian, + trial, + None + ) + afqmc.estimators = estimators + if comm.rank == 0: + json_string = to_json(afqmc) + afqmc.estimators.json_string = json_string + afqmc.estimators.dump_metadata() + afqmc.estimators.estimators["mixed"].print_key() + afqmc.estimators.estimators["mixed"].print_header() afqmc.run(comm=comm) afqmc.finalise(comm) test_data = extract_test_data_hdf5(tmpf.name) diff --git a/ipie/thermal/walkers/handler.py b/ipie/thermal/walkers/handler.py index 9559cf1e..4d488954 100644 --- a/ipie/thermal/walkers/handler.py +++ b/ipie/thermal/walkers/handler.py @@ -73,19 +73,6 @@ def __init__( self.buff_size = self.walkers[0].buff_size + self.walkers[0].stack.buff_size self.walker_buffer = numpy.zeros(self.buff_size, dtype=numpy.complex128) stack_size = self.walkers[0].stack_size - if hamiltonian.name == "Hubbard": - if stack_size % qmc.nstblz != 0 or qmc.nstblz < stack_size: - if verbose: - print("# Stabilisation frequency is not commensurate " "with stack size.") - print("# Determining a better value.") - if qmc.nstblz < stack_size: - qmc.nstblz = stack_size - if verbose: - print(f"# Updated stabilization frequency: {qmc.nstblz}") - else: - qmc.nstblz = update_stack( - qmc.nstblz, stack_size, name="nstblz", verbose=verbose - ) else: raise NotImplementedError if hamiltonian.name == "Generic" or system.name == "UEG": From 5054bbd3d3a6d15db6ac9b74ba007182512cd153 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 7 Sep 2023 22:30:34 -0400 Subject: [PATCH 22/84] Add UEG calculation as example. Fixed trial energy calculation for complex integrals. --- ipie/estimators/generic.py | 59 +++++++++++++++++---------- ipie/hamiltonians/generic.py | 2 +- ipie/hamiltonians/ueg.py | 42 ++++++++++++------- ipie/trial_wavefunction/single_det.py | 9 ++-- ipie/utils/testing.py | 31 ++++++++++---- 5 files changed, 94 insertions(+), 49 deletions(-) diff --git a/ipie/estimators/generic.py b/ipie/estimators/generic.py index 6f69d085..ce0d3167 100644 --- a/ipie/estimators/generic.py +++ b/ipie/estimators/generic.py @@ -257,7 +257,18 @@ def exx_kernel_rchol_real(rchol, Ghalf): @jit(nopython=True, fastmath=True) -def exx_kernel_rchol_complex(rchol, Ghalf): +def ecoul_kernel_rchol_complex(rchola, rcholb, rcholbara, rcholbarb, Ghalfa, Ghalfb): + X1 = rchola.dot(Ghalfa.ravel()) + X1 += rcholb.dot(Ghalfb.ravel()) + X2 = rcholbara.dot(Ghalfa.ravel()) + X2 += rcholbarb.dot(Ghalfb.ravel()) + ecoul = xp.dot(X1, X2) + ecoul *= 0.5 + return ecoul + + +@jit(nopython=True, fastmath=True) +def exx_kernel_rchol_complex(rchol, rcholbar, Ghalf): """Compute exchange contribution for complex rchol. Parameters @@ -270,22 +281,24 @@ def exx_kernel_rchol_complex(rchol, Ghalf): Returns ------- exx : :class:`numpy.ndarray` - exchange contribution for given green's function. + exchange contribution for all walkers. """ naux = rchol.shape[0] nocc = Ghalf.shape[0] - nbasis = Ghalf.shape[1] - - exx = 0 + 0j - GhalfT = Ghalf.T.copy() + nbsf = Ghalf.shape[1] + T1 = xp.zeros((nocc, nocc), dtype=numpy.complex128) + T2 = xp.zeros((nocc, nocc), dtype=numpy.complex128) + exx = 0. + 0.j # Fix this with gpu env for jx in range(naux): - rmi = rchol[jx].reshape((nocc, nbasis)) - T = rmi.dot(GhalfT) - exx += numpy.dot(T.ravel(), T.T.ravel()) + rcholx = rchol[jx].reshape(nocc, nbsf) + rcholbarx = rcholbar[jx].reshape(nocc, nbsf) + T1 = rcholx.dot(Ghalf.T) + T2 = rcholbarx.dot(Ghalf.T) + exx += xp.dot(T1.ravel(), T2.T.ravel()) + exx *= 0.5 return exx - def cholesky_jk_ghf(chol, G): nbasis = G.shape[0] // 2 @@ -322,13 +335,11 @@ def cholesky_jk_ghf(chol, G): return 0.5 * ecoul, -0.5 * exx # JK energy -def half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial): +def half_rotated_cholesky_jk(Ghalfa, Ghalfb, trial): """Compute exchange and coulomb contributions via jitted kernels. Parameters ---------- - system : :class:`Generic` - System information for Generic. Ghalfa : :class:`numpy.ndarray` Walker's half-rotated "green's function" shape is nalpha x nbasis Ghalfa : :class:`numpy.ndarray` @@ -343,7 +354,6 @@ def half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial): exx : :class:`numpy.ndarray` Exchange energy. """ - rchola = trial._rchola rcholb = trial._rcholb @@ -351,19 +361,24 @@ def half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial): if xp.isrealobj(rchola) and xp.isrealobj(rcholb): Xa = rchola.dot(Ghalfa.real.ravel()) + 1.0j * rchola.dot(Ghalfa.imag.ravel()) Xb = rcholb.dot(Ghalfb.real.ravel()) + 1.0j * rcholb.dot(Ghalfb.imag.ravel()) + ecoul = xp.dot(Xa, Xa) + ecoul += xp.dot(Xb, Xb) + ecoul += 2 * xp.dot(Xa, Xb) else: - Xa = rchola.dot(Ghalfa.ravel()) - Xb = rcholb.dot(Ghalfb.ravel()) + rcholbara = trial._rcholbara + rcholbarb = trial._rcholbarb + ecoul = 2.0 * ecoul_kernel_rchol_complex( + rchola, rcholb, rcholbara, rcholbarb, Ghalfa, Ghalfb + ) - ecoul = xp.dot(Xa, Xa) - ecoul += xp.dot(Xb, Xb) - ecoul += 2 * xp.dot(Xa, Xb) - exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta if xp.isrealobj(rchola) and xp.isrealobj(rcholb): exx = exx_kernel_rchol_real(rchola, Ghalfa) + exx_kernel_rchol_real(rcholb, Ghalfb) else: - exx = exx_kernel_rchol_complex(rchola, Ghalfa) + exx_kernel_rchol_complex(rcholb, Ghalfb) - + rcholbara = trial._rcholbara + rcholbarb = trial._rcholbarb + exx = exx_kernel_rchol_complex(rchola, rcholbara, Ghalfa) + exx += exx_kernel_rchol_complex(rcholb, rcholbarb, Ghalfb) + exx *= 2.0 synchronize() return 0.5 * ecoul, -0.5 * exx # JK energy diff --git a/ipie/hamiltonians/generic.py b/ipie/hamiltonians/generic.py index 44ed4043..95466dd0 100644 --- a/ipie/hamiltonians/generic.py +++ b/ipie/hamiltonians/generic.py @@ -29,7 +29,7 @@ def construct_h1e_mod(chol, h1e, h1e_mod): # Subtract one-body bit following reordering of 2-body operators. - # Eqn (17) of [Motta17]_ + # Eqn (17) of [Motta17]. nbasis = h1e.shape[-1] nchol = chol.shape[-1] chol_view = chol.reshape((nbasis, nbasis * nchol)) diff --git a/ipie/hamiltonians/ueg.py b/ipie/hamiltonians/ueg.py index ad46e4ee..3097319a 100644 --- a/ipie/hamiltonians/ueg.py +++ b/ipie/hamiltonians/ueg.py @@ -43,21 +43,23 @@ def __init__(self, system, options, verbose=False): if verbose: print("# Parsing input options.") self.name = "UEG" + + # Inherit from system. self.mu = system.mu + self.kfac = system.kfac + self.vol = system.vol self._alt_convention = system._alt_convention + self.sparse = True + skip_cholesky = options.get("skip_cholesky", False) - # core energy + # Core energy self.ecore = 0.5 * system.ne * self.madelung(system) self.diagH1 = True - skip_cholesky = options.get("skip_cholesky", False) - - self.kfac = system.kfac - self.vol = system.vol - # Single particle eigenvalues and corresponding kvectors + # Get plane wave basis vectors and corresponding eigenvalues. (self.sp_eigv, self.basis, self.nmax) = self.sp_energies( - system.ktwist, system.kfac, system.ecut + system.ktwist, self.kfac, system.ecut ) self.shifted_nmax = 2 * self.nmax @@ -72,11 +74,14 @@ def __init__(self, system, options, verbose=False): self.ncore = 0 self.nfv = 0 self.mo_coeff = None - # Allowed momentum transfers (4*ecut) - (eigs, qvecs, self.qnmax) = self.sp_energies(system.ktwist, system.kfac, 4 * system.ecut) + + # Allowed momentum transfers (4*ecut). + (eigs, qvecs, self.qnmax) = self.sp_energies(system.ktwist, self.kfac, 4 * system.ecut) + # Omit Q = 0 term. self.qvecs = numpy.copy(qvecs[1:]) - self.vqvec = numpy.array([self.vq(system.kfac * q) for q in self.qvecs]) + self.vqvec = numpy.array([self.vq(self.kfac * q) for q in self.qvecs]) + # Number of momentum transfer vectors / auxiliary fields. # Can reduce by symmetry but be stupid for the moment. self.nchol = len(self.qvecs) @@ -84,6 +89,7 @@ def __init__(self, system, options, verbose=False): if verbose: print(f"# Number of plane waves: {self.nbasis:d}") print(f"# Number of Cholesky vectors: {self.nchol:d}.") + # For consistency with frozen core molecular code. self.orbs = None self.frozen_core = False @@ -93,14 +99,15 @@ def __init__(self, system, options, verbose=False): if skip_cholesky == False: h1e_mod = self.mod_one_body(T, system) self.h1e_mod = numpy.array([h1e_mod, h1e_mod]) + self.orbs = None self._opt = True nlimit = system.nup - if system.thermal: nlimit = self.nbasis + # Get arrays of plane wave basis vectors connected by momentum transfers Q. self.ikpq_i = [] self.ikpq_kpq = [] for iq, q in enumerate(self.qvecs): @@ -114,7 +121,7 @@ def __init__(self, system, options, verbose=False): idxkpq_list_kpq += [idxkpq] self.ikpq_i += [idxkpq_list_i] self.ikpq_kpq += [idxkpq_list_kpq] - + self.ipmq_i = [] self.ipmq_pmq = [] for iq, q in enumerate(self.qvecs): @@ -138,10 +145,13 @@ def __init__(self, system, options, verbose=False): if skip_cholesky == False: if verbose: print("# Constructing two-body potentials incore.") + (self.chol_vecs, self.iA, self.iB) = self.two_body_potentials_incore() write_ints = options.get("write_integrals", False) + if write_ints: self.write_integrals(system) + if verbose: print( "# Approximate memory required for " @@ -255,7 +265,8 @@ def vq(self, q): return 4 * math.pi / numpy.dot(q, q) def mod_one_body(self, T, system): - """Add a diagonal term of two-body Hamiltonian to the one-body term + """Absorb the diagonal term of the two-body Hamiltonian to the one-body term. + Essentially adding the third term in Eq.(11b) of Phys. Rev. B 75, 245123. Parameters ---------- T : float @@ -276,7 +287,7 @@ def mod_one_body(self, T, system): return h1e_mod def density_operator(self, iq): - """Density operator as defined in Eq.(6) of PRB(75)245123 + """Density operator as defined in Eq.(6) of Phys. Rev. B 75, 245123. Parameters ---------- q : float @@ -366,7 +377,8 @@ def scaled_density_operator_incore(self, transpose): return rho_q def two_body_potentials_incore(self): - """Calculatate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q + """Calculate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q + Parameters ---------- system : diff --git a/ipie/trial_wavefunction/single_det.py b/ipie/trial_wavefunction/single_det.py index 28e592b5..bfbaa940 100644 --- a/ipie/trial_wavefunction/single_det.py +++ b/ipie/trial_wavefunction/single_det.py @@ -35,10 +35,10 @@ def __init__(self, wavefunction, num_elec, num_basis, verbose=False): self.num_elec = num_elec self._num_dets = 1 self._max_num_dets = 1 - imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) - if imag_norm <= 1e-8: + #imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) + #if imag_norm <= 1e-8: # print("# making trial wavefunction MO coefficient real") - self.psi = numpy.array(self.psi.real, dtype=numpy.float64) + #self.psi = numpy.array(self.psi.real, dtype=numpy.float64) self.psi0a = self.psi[:, : self.nalpha] self.psi0b = self.psi[:, self.nalpha :] @@ -65,12 +65,13 @@ def calculate_energy(self, system, hamiltonian) -> numpy.ndarray: + hamiltonian.ecore ) self.ej, self.ek = half_rotated_cholesky_jk( - system, self.Ghalf[0], self.Ghalf[1], trial=self + self.Ghalf[0], self.Ghalf[1], trial=self ) self.e2b = self.ej + self.ek self.energy = self.e1b + self.e2b if self.verbose: + print("# (Ej, Ek) = {}, {}".format(self.ej, self.ek)) print( "# (E, E1B, E2B): (%13.8e, %13.8e, %13.8e)" % (self.energy.real, self.e1b.real, self.e2b.real) diff --git a/ipie/utils/testing.py b/ipie/utils/testing.py index 7e83875b..c5fe3013 100644 --- a/ipie/utils/testing.py +++ b/ipie/utils/testing.py @@ -21,6 +21,8 @@ from typing import Tuple, Union import numpy +import scipy.sparse +import scipy.stats from ipie.hamiltonians import Generic as HamGeneric from ipie.propagation.phaseless_generic import PhaselessBase, PhaselessGeneric @@ -44,13 +46,28 @@ from ipie.walkers.walkers_dispatch import UHFWalkersTrial -def generate_hamiltonian(nmo, nelec, cplx=False, sym=8, tol=1e-3): - h1e = numpy.random.random((nmo, nmo)) - if cplx: - h1e = h1e + 1j * numpy.random.random((nmo, nmo)) - eri = numpy.random.normal(scale=0.01, size=(nmo, nmo, nmo, nmo)) - if cplx: - eri = eri + 1j * numpy.random.normal(scale=0.01, size=(nmo, nmo, nmo, nmo)) +def generate_hamiltonian(nmo, nelec, cplx=False, sym=8, sparse=False, tol=1e-3): + h1e, eri = None, None + if sparse: + h1e = scipy.sparse.random(nmo, nmo).toarray() + if cplx: + h1e = h1e + 1j * scipy.sparse.random(nmo, nmo).toarray() + + rvs = scipy.stats.norm(scale=0.01).rvs + eri = scipy.sparse.random(nmo**2, nmo**2, data_rvs=rvs).toarray() + if cplx: + eri = eri + 1j * scipy.sparse.random(nmo**2, nmo**2, data_rvs=rvs).toarray() + eri = eri.reshape((nmo, nmo, nmo, nmo)) + + else: + h1e = numpy.random.random((nmo, nmo)) + if cplx: + h1e = h1e + 1j * numpy.random.random((nmo, nmo)) + + eri = numpy.random.normal(scale=0.01, size=(nmo, nmo, nmo, nmo)) + if cplx: + eri = eri + 1j * numpy.random.normal(scale=0.01, size=(nmo, nmo, nmo, nmo)) + # Restore symmetry to the integrals. if sym >= 4: # (ik|jl) = (jl|ik) From f39f066225cade83c847b67052d4817d2ee54840 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 9 Sep 2023 15:56:34 -0400 Subject: [PATCH 23/84] Removed system-dependence in thermal/trial/. Renamed `system` -> `hamiltonian` in thermal/estimators/ files. --- ipie/thermal/estimators/fock.py | 16 ++++----- ipie/thermal/estimators/generic.py | 53 +++++++++++++----------------- ipie/thermal/tests/test_generic.py | 2 +- ipie/thermal/trial/mean_field.py | 21 ++++++------ ipie/thermal/trial/onebody.py | 4 +-- ipie/thermal/trial/utils.py | 8 ++--- 6 files changed, 47 insertions(+), 57 deletions(-) diff --git a/ipie/thermal/estimators/fock.py b/ipie/thermal/estimators/fock.py index 2330ad2e..63f493b0 100644 --- a/ipie/thermal/estimators/fock.py +++ b/ipie/thermal/estimators/fock.py @@ -1,14 +1,12 @@ -from ipie.estimators.generic import fock_generic +from ipie.thermal.estimators.generic import fock_generic from ipie.thermal.estimators.ueg import fock_ueg -def fock_matrix(system, G): - if system.name == "UEG": - return fock_ueg(system, G) - elif system.name == "Generic": - return fock_generic(system, G) - elif system.name == "Hubbard": - raise NotImplementedError +def fock_matrix(hamiltonian, G): + if hamiltonian.name == "UEG": + return fock_ueg(hamiltonian, G) + elif hamiltonian.name == "Generic": + return fock_generic(hamiltonian, G) else: - print(f"# Fock matrix not implemented for {system.name}") + print(f"# Fock matrix not implemented for {hamiltonian.name}") return None diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py index 8dc3c627..a30a5b7a 100644 --- a/ipie/thermal/estimators/generic.py +++ b/ipie/thermal/estimators/generic.py @@ -156,7 +156,6 @@ def _exx_compute_batch(rchol_a, rchol_b, GaT_stacked, GbT_stacked, lwalker): def local_energy_generic_cholesky_opt_batched( - system, ham, Ga_batch: numpy.ndarray, Gb_batch: numpy.ndarray, @@ -173,8 +172,6 @@ def local_energy_generic_cholesky_opt_batched( Parameters ---------- - system : :class:`Generic` - System information for Generic. ham : :class:`Abinitio` Contains necessary hamiltonian information Ga_batched : :class:`numpy.ndarray` @@ -203,7 +200,6 @@ def local_energy_generic_cholesky_opt_batched( for widx in range(nwalker): e1b = numpy.sum(ham.H1[0] * Ga_batch[widx]) + numpy.sum(ham.H1[1] * Gb_batch[widx]) e1_vec[widx] = e1b - nalpha, nbeta = system.nup, system.ndown nbasis = ham.nbasis if rchola is not None: naux = rchola.shape[0] @@ -238,12 +234,12 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): Parameters ---------- - system : :class:`Generic` - generic system information ham : :class:`Generic` ab-initio hamiltonian information G : :class:`numpy.ndarray` Walker's "green's function" + Ghalf : :class:`numpy.ndarray` + Walker's "half-rotated" "green's function" Returns ------- @@ -252,46 +248,30 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): """ # Element wise multiplication. e1b = numpy.sum(ham.H1[0] * G[0]) + numpy.sum(ham.H1[1] * G[1]) - nalpha, nbeta = system.nup, system.ndown nbasis = ham.nbasis nchol = ham.nchol Ga, Gb = G[0], G[1] - # Xa = numpy.dot(ham.chol_vecs, Ga.ravel()) - # Xb = numpy.dot(ham.chol_vecs, Gb.ravel()) - - if numpy.isrealobj(ham.chol_vecs): - # Xa = ham.chol_vecs.T.dot(Ga.real.ravel()) + 1.j * ham.chol_vecs.dot(Ga.imag.ravel()) - # Xb = ham.chol_vecs.T.dot(Gb.real.ravel()) + 1.j * ham.chol_vecs.dot(Gb.imag.ravel()) - Xa = ham.chol_vecs.T.dot(Ga.real.ravel()) + 1.0j * ham.chol_vecs.T.dot(Ga.imag.ravel()) - Xb = ham.chol_vecs.T.dot(Gb.real.ravel()) + 1.0j * ham.chol_vecs.T.dot(Gb.imag.ravel()) + if numpy.isrealobj(ham.chol): + Xa = ham.chol.T.dot(Ga.real.ravel()) + 1.0j * ham.chol.T.dot(Ga.imag.ravel()) + Xb = ham.chol.T.dot(Gb.real.ravel()) + 1.0j * ham.chol.T.dot(Gb.imag.ravel()) else: - Xa = ham.chol_vecs.T.dot(Ga.ravel()) - Xb = ham.chol_vecs.T.dot(Gb.ravel()) + Xa = ham.chol.T.dot(Ga.ravel()) + Xb = ham.chol.T.dot(Gb.ravel()) ecoul = numpy.dot(Xa, Xa) ecoul += numpy.dot(Xb, Xb) ecoul += 2 * numpy.dot(Xa, Xb) - # T[l,k,n] = \sum_i L[i,k,n] G[i,l] - # exx = \sum_{nlk} T[l,k,n] T[k,l,n] - # cv = ham.chol_vecs.T.reshape((nbasis,nbasis,-1)) - # Ta = numpy.tensordot(Ga, cv, axes=((0),(0))) - # exxa = numpy.tensordot(Ta, Ta, axes=((0,1,2),(1,0,2))) - # Tb = numpy.tensordot(Gb, cv, axes=((0),(0))) - # exxb = numpy.tensordot(Tb, Tb, axes=((0,1,2),(1,0,2))) - # exx = exxa + exxb - # e2b = 0.5 * (ecoul - exx) - T = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) GaT = Ga.T.copy() GbT = Gb.T.copy() exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - if numpy.isrealobj(ham.chol_vecs): + if numpy.isrealobj(ham.chol): for x in range(nchol): # write a cython function that calls blas for this. - Lmn = ham.chol_vecs[:, x].reshape((nbasis, nbasis)) + Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) T[:, :].real = GaT.real.dot(Lmn) T[:, :].imag = GaT.imag.dot(Lmn) exx += numpy.trace(T.dot(T)) @@ -300,7 +280,7 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): exx += numpy.trace(T.dot(T)) else: for x in range(nchol): # write a cython function that calls blas for this. - Lmn = ham.chol_vecs[:, x].reshape((nbasis, nbasis)) + Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) T[:, :] = GaT.dot(Lmn) exx += numpy.trace(T.dot(T)) T[:, :] = GbT.dot(Lmn) @@ -509,3 +489,16 @@ def local_energy_generic_cholesky_opt(system, ham, Ga, Gb, Ghalfa, Ghalfb, rchol e2b = 0.5 * (ecoul - exx) return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) + +def fock_generic(hamiltonian, P): + nbasis = hamiltonian.nbasis + nchol = hamiltonian.nchol + hs_pot = hamiltonian.chol.T.reshape(nchol, nbasis, nbasis) + if hamiltonian.sparse: + mf_shift = 1j * P[0].ravel() * hs_pot + mf_shift += 1j * P[1].ravel() * hs_pot + VMF = 1j * hs_pot.dot(mf_shift).reshape(nbasis, nbasis) + else: + mf_shift = 1j * numpy.einsum("lpq,spq->l", hs_pot, P) + VMF = 1j * numpy.einsum("lpq,l->pq", hs_pot, mf_shift) + return hamiltonian.h1e_mod - VMF diff --git a/ipie/thermal/tests/test_generic.py b/ipie/thermal/tests/test_generic.py index 31f054e6..b81e4b19 100644 --- a/ipie/thermal/tests/test_generic.py +++ b/ipie/thermal/tests/test_generic.py @@ -124,7 +124,7 @@ def compare_test_data(ref, test): system = Generic(mol.nelec) system.mu = mu hamiltonian = get_hamiltonian(system, options["hamiltonian"]) -trial = get_trial_density_matrix(system, hamiltonian, beta, dt, comm=comm, options=options["trial"]) +trial = get_trial_density_matrix(hamiltonian, mol.nelec, beta, dt, comm=comm, options=options["trial"]) qmc = QMCOpts() # should be removed later after walker is cleaned up qmc.nwalkers = num_walkers diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index bd0ab8c7..c9e03b8a 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -2,16 +2,15 @@ import scipy.linalg from ipie.thermal.estimators.fock import fock_matrix -from ipie.thermal.estimators.local_energy import local_energy -from ipie.thermal.estimators.thermal import entropy, greens_function, one_rdm_stable, particle_number +from ipie.thermal.estimators.thermal import greens_function, one_rdm_stable, particle_number from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.thermal.trial.onebody import OneBody class MeanField(OneBody): - def __init__(self, system, hamiltonian, beta, dt, options={}, H1=None, verbose=False): + def __init__(self, hamiltonian, nelec, beta, dt, options={}, H1=None, verbose=False): OneBody.__init__( - self, system, hamiltonian, beta, dt, options=options, H1=H1, verbose=verbose + self, hamiltonian, nelec, beta, dt, options=options, H1=H1, verbose=verbose ) if verbose: print(" # Building THF density matrix.") @@ -36,7 +35,7 @@ def __init__(self, system, hamiltonian, beta, dt, options={}, H1=None, verbose=F self.G = numpy.array([greens_function(self.dmat[0]), greens_function(self.dmat[1])]) self.nav = particle_number(self.P).real - def thermal_hartree_fock(self, system, beta): + def thermal_hartree_fock(self, hamiltonian, beta): dt = self.dtau mu_old = self.mu P = self.P.copy() @@ -45,11 +44,11 @@ def thermal_hartree_fock(self, system, beta): for it in range(self.max_macro_it): if self.verbose: print(f"# Macro iteration: {it}") - HMF = self.scf(system, beta, mu_old, P) + HMF = self.scf(hamiltonian, beta, mu_old, P) rho = numpy.array([scipy.linalg.expm(-dt * HMF[0]), scipy.linalg.expm(-dt * HMF[1])]) if self.find_mu: mu = find_chemical_potential( - system, + hamiltonian._alt_convention, rho, dt, self.num_bins, @@ -70,11 +69,11 @@ def thermal_hartree_fock(self, system, beta): mu_old = mu return P, HMF, mu - def scf(self, system, beta, mu, P): + def scf(self, hamiltonian, beta, mu, P): # 1. Compute HMF - HMF = fock_matrix(system, P) + HMF = fock_matrix(hamiltonian, P) dt = self.dtau - muN = mu * numpy.eye(system.nbasis, dtype=self.G.dtype) + muN = mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) rho = numpy.array( [ scipy.linalg.expm(-dt * (HMF[0] - muN)), @@ -85,7 +84,7 @@ def scf(self, system, beta, mu, P): if self.verbose: print(" # Running Thermal SCF.") for it in range(self.max_scf_it): - HMF = fock_matrix(system, Pold) + HMF = fock_matrix(hamiltonian, Pold) rho = numpy.array( [ scipy.linalg.expm(-dt * (HMF[0] - muN)), diff --git a/ipie/thermal/trial/onebody.py b/ipie/thermal/trial/onebody.py index f349c945..2962cbd5 100644 --- a/ipie/thermal/trial/onebody.py +++ b/ipie/thermal/trial/onebody.py @@ -14,8 +14,8 @@ class OneBody(object): def __init__( self, - system, hamiltonian, + nelec, beta, dt, options={}, @@ -50,7 +50,7 @@ def __init__( else: self.nav = options.get("nav", None) if self.nav is None: - self.nav = system.nup + system.ndown + self.nav = nelec[0] + nelec[1] if verbose: print(f"# Target average electron number: {self.nav}") diff --git a/ipie/thermal/trial/utils.py b/ipie/thermal/trial/utils.py index f0e8b71b..b474af53 100644 --- a/ipie/thermal/trial/utils.py +++ b/ipie/thermal/trial/utils.py @@ -2,7 +2,7 @@ from ipie.thermal.trial.onebody import OneBody -def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=None, verbose=False): +def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, comm=None, verbose=False): """Wrapper to select trial wavefunction class. Parameters @@ -17,8 +17,8 @@ def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=Non if comm is None or comm.rank == 0: if trial_type == "one_body_mod": trial = OneBody( - system, hamiltonian, + nelec, beta, dt, options=options, @@ -26,9 +26,9 @@ def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=Non verbose=verbose, ) elif trial_type == "one_body": - trial = OneBody(system, hamiltonian, beta, dt, options=options, verbose=verbose) + trial = OneBody(hamiltonian, nelec, beta, dt, options=options, verbose=verbose) elif trial_type == "thermal_hartree_fock": - trial = MeanField(system, hamiltonian, beta, dt, options=options, verbose=verbose) + trial = MeanField(hamiltonian, nelec, beta, dt, options=options, verbose=verbose) else: trial = None else: From ffa0ca39295d9d5a88998443b80918c96ba8bbd6 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 9 Sep 2023 15:56:34 -0400 Subject: [PATCH 24/84] Removed system-dependence in thermal/trial/. Renamed `system` -> `hamiltonian` in thermal/trial/ files. --- ipie/thermal/estimators/fock.py | 16 ++++----- ipie/thermal/estimators/generic.py | 53 +++++++++++++----------------- ipie/thermal/tests/test_generic.py | 2 +- ipie/thermal/trial/mean_field.py | 21 ++++++------ ipie/thermal/trial/onebody.py | 4 +-- ipie/thermal/trial/utils.py | 8 ++--- 6 files changed, 47 insertions(+), 57 deletions(-) diff --git a/ipie/thermal/estimators/fock.py b/ipie/thermal/estimators/fock.py index 2330ad2e..63f493b0 100644 --- a/ipie/thermal/estimators/fock.py +++ b/ipie/thermal/estimators/fock.py @@ -1,14 +1,12 @@ -from ipie.estimators.generic import fock_generic +from ipie.thermal.estimators.generic import fock_generic from ipie.thermal.estimators.ueg import fock_ueg -def fock_matrix(system, G): - if system.name == "UEG": - return fock_ueg(system, G) - elif system.name == "Generic": - return fock_generic(system, G) - elif system.name == "Hubbard": - raise NotImplementedError +def fock_matrix(hamiltonian, G): + if hamiltonian.name == "UEG": + return fock_ueg(hamiltonian, G) + elif hamiltonian.name == "Generic": + return fock_generic(hamiltonian, G) else: - print(f"# Fock matrix not implemented for {system.name}") + print(f"# Fock matrix not implemented for {hamiltonian.name}") return None diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py index 8dc3c627..a30a5b7a 100644 --- a/ipie/thermal/estimators/generic.py +++ b/ipie/thermal/estimators/generic.py @@ -156,7 +156,6 @@ def _exx_compute_batch(rchol_a, rchol_b, GaT_stacked, GbT_stacked, lwalker): def local_energy_generic_cholesky_opt_batched( - system, ham, Ga_batch: numpy.ndarray, Gb_batch: numpy.ndarray, @@ -173,8 +172,6 @@ def local_energy_generic_cholesky_opt_batched( Parameters ---------- - system : :class:`Generic` - System information for Generic. ham : :class:`Abinitio` Contains necessary hamiltonian information Ga_batched : :class:`numpy.ndarray` @@ -203,7 +200,6 @@ def local_energy_generic_cholesky_opt_batched( for widx in range(nwalker): e1b = numpy.sum(ham.H1[0] * Ga_batch[widx]) + numpy.sum(ham.H1[1] * Gb_batch[widx]) e1_vec[widx] = e1b - nalpha, nbeta = system.nup, system.ndown nbasis = ham.nbasis if rchola is not None: naux = rchola.shape[0] @@ -238,12 +234,12 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): Parameters ---------- - system : :class:`Generic` - generic system information ham : :class:`Generic` ab-initio hamiltonian information G : :class:`numpy.ndarray` Walker's "green's function" + Ghalf : :class:`numpy.ndarray` + Walker's "half-rotated" "green's function" Returns ------- @@ -252,46 +248,30 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): """ # Element wise multiplication. e1b = numpy.sum(ham.H1[0] * G[0]) + numpy.sum(ham.H1[1] * G[1]) - nalpha, nbeta = system.nup, system.ndown nbasis = ham.nbasis nchol = ham.nchol Ga, Gb = G[0], G[1] - # Xa = numpy.dot(ham.chol_vecs, Ga.ravel()) - # Xb = numpy.dot(ham.chol_vecs, Gb.ravel()) - - if numpy.isrealobj(ham.chol_vecs): - # Xa = ham.chol_vecs.T.dot(Ga.real.ravel()) + 1.j * ham.chol_vecs.dot(Ga.imag.ravel()) - # Xb = ham.chol_vecs.T.dot(Gb.real.ravel()) + 1.j * ham.chol_vecs.dot(Gb.imag.ravel()) - Xa = ham.chol_vecs.T.dot(Ga.real.ravel()) + 1.0j * ham.chol_vecs.T.dot(Ga.imag.ravel()) - Xb = ham.chol_vecs.T.dot(Gb.real.ravel()) + 1.0j * ham.chol_vecs.T.dot(Gb.imag.ravel()) + if numpy.isrealobj(ham.chol): + Xa = ham.chol.T.dot(Ga.real.ravel()) + 1.0j * ham.chol.T.dot(Ga.imag.ravel()) + Xb = ham.chol.T.dot(Gb.real.ravel()) + 1.0j * ham.chol.T.dot(Gb.imag.ravel()) else: - Xa = ham.chol_vecs.T.dot(Ga.ravel()) - Xb = ham.chol_vecs.T.dot(Gb.ravel()) + Xa = ham.chol.T.dot(Ga.ravel()) + Xb = ham.chol.T.dot(Gb.ravel()) ecoul = numpy.dot(Xa, Xa) ecoul += numpy.dot(Xb, Xb) ecoul += 2 * numpy.dot(Xa, Xb) - # T[l,k,n] = \sum_i L[i,k,n] G[i,l] - # exx = \sum_{nlk} T[l,k,n] T[k,l,n] - # cv = ham.chol_vecs.T.reshape((nbasis,nbasis,-1)) - # Ta = numpy.tensordot(Ga, cv, axes=((0),(0))) - # exxa = numpy.tensordot(Ta, Ta, axes=((0,1,2),(1,0,2))) - # Tb = numpy.tensordot(Gb, cv, axes=((0),(0))) - # exxb = numpy.tensordot(Tb, Tb, axes=((0,1,2),(1,0,2))) - # exx = exxa + exxb - # e2b = 0.5 * (ecoul - exx) - T = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) GaT = Ga.T.copy() GbT = Gb.T.copy() exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - if numpy.isrealobj(ham.chol_vecs): + if numpy.isrealobj(ham.chol): for x in range(nchol): # write a cython function that calls blas for this. - Lmn = ham.chol_vecs[:, x].reshape((nbasis, nbasis)) + Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) T[:, :].real = GaT.real.dot(Lmn) T[:, :].imag = GaT.imag.dot(Lmn) exx += numpy.trace(T.dot(T)) @@ -300,7 +280,7 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): exx += numpy.trace(T.dot(T)) else: for x in range(nchol): # write a cython function that calls blas for this. - Lmn = ham.chol_vecs[:, x].reshape((nbasis, nbasis)) + Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) T[:, :] = GaT.dot(Lmn) exx += numpy.trace(T.dot(T)) T[:, :] = GbT.dot(Lmn) @@ -509,3 +489,16 @@ def local_energy_generic_cholesky_opt(system, ham, Ga, Gb, Ghalfa, Ghalfb, rchol e2b = 0.5 * (ecoul - exx) return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) + +def fock_generic(hamiltonian, P): + nbasis = hamiltonian.nbasis + nchol = hamiltonian.nchol + hs_pot = hamiltonian.chol.T.reshape(nchol, nbasis, nbasis) + if hamiltonian.sparse: + mf_shift = 1j * P[0].ravel() * hs_pot + mf_shift += 1j * P[1].ravel() * hs_pot + VMF = 1j * hs_pot.dot(mf_shift).reshape(nbasis, nbasis) + else: + mf_shift = 1j * numpy.einsum("lpq,spq->l", hs_pot, P) + VMF = 1j * numpy.einsum("lpq,l->pq", hs_pot, mf_shift) + return hamiltonian.h1e_mod - VMF diff --git a/ipie/thermal/tests/test_generic.py b/ipie/thermal/tests/test_generic.py index 31f054e6..b81e4b19 100644 --- a/ipie/thermal/tests/test_generic.py +++ b/ipie/thermal/tests/test_generic.py @@ -124,7 +124,7 @@ def compare_test_data(ref, test): system = Generic(mol.nelec) system.mu = mu hamiltonian = get_hamiltonian(system, options["hamiltonian"]) -trial = get_trial_density_matrix(system, hamiltonian, beta, dt, comm=comm, options=options["trial"]) +trial = get_trial_density_matrix(hamiltonian, mol.nelec, beta, dt, comm=comm, options=options["trial"]) qmc = QMCOpts() # should be removed later after walker is cleaned up qmc.nwalkers = num_walkers diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index bd0ab8c7..c9e03b8a 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -2,16 +2,15 @@ import scipy.linalg from ipie.thermal.estimators.fock import fock_matrix -from ipie.thermal.estimators.local_energy import local_energy -from ipie.thermal.estimators.thermal import entropy, greens_function, one_rdm_stable, particle_number +from ipie.thermal.estimators.thermal import greens_function, one_rdm_stable, particle_number from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.thermal.trial.onebody import OneBody class MeanField(OneBody): - def __init__(self, system, hamiltonian, beta, dt, options={}, H1=None, verbose=False): + def __init__(self, hamiltonian, nelec, beta, dt, options={}, H1=None, verbose=False): OneBody.__init__( - self, system, hamiltonian, beta, dt, options=options, H1=H1, verbose=verbose + self, hamiltonian, nelec, beta, dt, options=options, H1=H1, verbose=verbose ) if verbose: print(" # Building THF density matrix.") @@ -36,7 +35,7 @@ def __init__(self, system, hamiltonian, beta, dt, options={}, H1=None, verbose=F self.G = numpy.array([greens_function(self.dmat[0]), greens_function(self.dmat[1])]) self.nav = particle_number(self.P).real - def thermal_hartree_fock(self, system, beta): + def thermal_hartree_fock(self, hamiltonian, beta): dt = self.dtau mu_old = self.mu P = self.P.copy() @@ -45,11 +44,11 @@ def thermal_hartree_fock(self, system, beta): for it in range(self.max_macro_it): if self.verbose: print(f"# Macro iteration: {it}") - HMF = self.scf(system, beta, mu_old, P) + HMF = self.scf(hamiltonian, beta, mu_old, P) rho = numpy.array([scipy.linalg.expm(-dt * HMF[0]), scipy.linalg.expm(-dt * HMF[1])]) if self.find_mu: mu = find_chemical_potential( - system, + hamiltonian._alt_convention, rho, dt, self.num_bins, @@ -70,11 +69,11 @@ def thermal_hartree_fock(self, system, beta): mu_old = mu return P, HMF, mu - def scf(self, system, beta, mu, P): + def scf(self, hamiltonian, beta, mu, P): # 1. Compute HMF - HMF = fock_matrix(system, P) + HMF = fock_matrix(hamiltonian, P) dt = self.dtau - muN = mu * numpy.eye(system.nbasis, dtype=self.G.dtype) + muN = mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) rho = numpy.array( [ scipy.linalg.expm(-dt * (HMF[0] - muN)), @@ -85,7 +84,7 @@ def scf(self, system, beta, mu, P): if self.verbose: print(" # Running Thermal SCF.") for it in range(self.max_scf_it): - HMF = fock_matrix(system, Pold) + HMF = fock_matrix(hamiltonian, Pold) rho = numpy.array( [ scipy.linalg.expm(-dt * (HMF[0] - muN)), diff --git a/ipie/thermal/trial/onebody.py b/ipie/thermal/trial/onebody.py index f349c945..2962cbd5 100644 --- a/ipie/thermal/trial/onebody.py +++ b/ipie/thermal/trial/onebody.py @@ -14,8 +14,8 @@ class OneBody(object): def __init__( self, - system, hamiltonian, + nelec, beta, dt, options={}, @@ -50,7 +50,7 @@ def __init__( else: self.nav = options.get("nav", None) if self.nav is None: - self.nav = system.nup + system.ndown + self.nav = nelec[0] + nelec[1] if verbose: print(f"# Target average electron number: {self.nav}") diff --git a/ipie/thermal/trial/utils.py b/ipie/thermal/trial/utils.py index f0e8b71b..b474af53 100644 --- a/ipie/thermal/trial/utils.py +++ b/ipie/thermal/trial/utils.py @@ -2,7 +2,7 @@ from ipie.thermal.trial.onebody import OneBody -def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=None, verbose=False): +def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, comm=None, verbose=False): """Wrapper to select trial wavefunction class. Parameters @@ -17,8 +17,8 @@ def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=Non if comm is None or comm.rank == 0: if trial_type == "one_body_mod": trial = OneBody( - system, hamiltonian, + nelec, beta, dt, options=options, @@ -26,9 +26,9 @@ def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=Non verbose=verbose, ) elif trial_type == "one_body": - trial = OneBody(system, hamiltonian, beta, dt, options=options, verbose=verbose) + trial = OneBody(hamiltonian, nelec, beta, dt, options=options, verbose=verbose) elif trial_type == "thermal_hartree_fock": - trial = MeanField(system, hamiltonian, beta, dt, options=options, verbose=verbose) + trial = MeanField(hamiltonian, nelec, beta, dt, options=options, verbose=verbose) else: trial = None else: From a2c2281f1d883260d3d974082a188f7543885f64 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 9 Sep 2023 16:07:47 -0400 Subject: [PATCH 25/84] Readd `system` argument for compatibility. --- ipie/thermal/estimators/generic.py | 1 + 1 file changed, 1 insertion(+) diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py index a30a5b7a..edd3cbe5 100644 --- a/ipie/thermal/estimators/generic.py +++ b/ipie/thermal/estimators/generic.py @@ -156,6 +156,7 @@ def _exx_compute_batch(rchol_a, rchol_b, GaT_stacked, GbT_stacked, lwalker): def local_energy_generic_cholesky_opt_batched( + system, ham, Ga_batch: numpy.ndarray, Gb_batch: numpy.ndarray, From 64356f1d59af4e6586621b48940e5a34c0ea3602 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 9 Sep 2023 19:51:28 -0400 Subject: [PATCH 26/84] Remove system-dependency in thermal/estimators. --- ipie/hamiltonians/utils.py | 2 +- .../estimators/{handler.py => estimators.py} | 12 +- ipie/thermal/estimators/generic.py | 80 ++++++--- ipie/thermal/estimators/local_energy.py | 40 +++-- ipie/thermal/estimators/mixed.py | 161 +++++++++--------- ipie/thermal/estimators/ueg.py | 7 +- ipie/thermal/qmc/thermal_afqmc.py | 9 +- ipie/thermal/qmc/thermal_afqmc_clean.py | 2 - ipie/thermal/tests/test_generic.py | 6 +- ipie/thermal/trial/onebody.py | 5 +- 10 files changed, 169 insertions(+), 155 deletions(-) rename ipie/thermal/estimators/{handler.py => estimators.py} (88%) diff --git a/ipie/hamiltonians/utils.py b/ipie/hamiltonians/utils.py index 37bd2f9d..b3a0e503 100644 --- a/ipie/hamiltonians/utils.py +++ b/ipie/hamiltonians/utils.py @@ -100,6 +100,7 @@ def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): ecore=enuc, verbose=verbose, ) + ham._alt_convention = ham_opts["_alt_convention"] ham.sparse = ham_opts["sparse"] ham.name = ham_opts["name"] @@ -107,7 +108,6 @@ def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): ham.chol_vecs = chol ham.mu = ham_opts["mu"] - elif isinstance(system, SysUEG): ham = UEG( system, diff --git a/ipie/thermal/estimators/handler.py b/ipie/thermal/estimators/estimators.py similarity index 88% rename from ipie/thermal/estimators/handler.py rename to ipie/thermal/estimators/estimators.py index ca46df0c..065f5f7c 100644 --- a/ipie/thermal/estimators/handler.py +++ b/ipie/thermal/estimators/estimators.py @@ -21,8 +21,6 @@ class Estimators(object): True if on root/master processor. qmc : :class:`ipie.state.QMCOpts` object. Container for qmc input options. - system : :class:`ipie.hubbard.Hubbard` / system object in general. - Container for model input options. trial : :class:`ipie.trial_wavefunction.X' object Trial wavefunction class. BT2 : :class:`numpy.ndarray` @@ -47,7 +45,7 @@ class Estimators(object): True if calculating imaginary time correlation functions (ITCFs). """ - def __init__(self, estimates, root, qmc, system, hamiltonian, trial, BT2, verbose=False): + def __init__(self, estimates, root, qmc, hamiltonian, trial, BT2, verbose=False): if verbose: print("# Setting up estimator object.") if root: @@ -73,7 +71,7 @@ def __init__(self, estimates, root, qmc, system, hamiltonian, trial, BT2, verbos self.estimators = {} dtype = complex self.estimators["mixed"] = Mixed( - mixed, system, hamiltonian, root, self.filename, qmc, trial, dtype + mixed, hamiltonian, root, self.filename, qmc, trial, dtype ) self.nprop_tot = None self.nbp = None @@ -113,13 +111,11 @@ def print_step(self, comm, nprocs, step, nsteps=None, free_projection=False): for k, e in self.estimators.items(): e.print_step(comm, nprocs, step, nsteps=nsteps, free_projection=free_projection) - def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=False): + def update(self, qmc, hamiltonian, trial, psi, step, free_projection=False): """Update estimators Parameters ---------- - system : system object in general. - Container for model input options. qmc : :class:`ipie.state.QMCOpts` object. Container for qmc input options. trial : :class:`ipie.trial_wavefunction.X' object @@ -132,4 +128,4 @@ def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=Fal True if doing free projection. """ for k, e in self.estimators.items(): - e.update(qmc, system, hamiltonian, trial, psi, step, free_projection) + e.update(qmc, hamiltonian, trial, psi, step, free_projection) diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py index a30a5b7a..3033daf9 100644 --- a/ipie/thermal/estimators/generic.py +++ b/ipie/thermal/estimators/generic.py @@ -5,7 +5,8 @@ def local_energy_generic_pno( - system, + hamiltonian, + nelec, G, Ghalf=None, eri=None, @@ -15,9 +16,8 @@ def local_energy_generic_pno( exxb0=None, UVT=None, ): - na = system.nup - nb = system.ndown - M = system.nbasis + na, nb = nelec + M = hamiltonian.nbasis UVT_aa = UVT[0] UVT_bb = UVT[1] @@ -26,7 +26,7 @@ def local_energy_generic_pno( Ga, Gb = Ghalf[0], Ghalf[1] # Element wise multiplication. - e1b = numpy.sum(system.H1[0] * G[0]) + numpy.sum(system.H1[1] * G[1]) + e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) eJaa = 0.0 eKaa = 0.0 @@ -39,7 +39,7 @@ def local_energy_generic_pno( GTa = CT[:na, :] # hard-coded to do single slater GTb = CT[na:, :] # hard-coded to do single slater - for (i, j), (U, VT) in zip(system.ij_list_aa, UVT_aa): + for (i, j), (U, VT) in zip(hamiltonian.ij_list_aa, UVT_aa): if i == j: c = 0.5 else: @@ -68,7 +68,7 @@ def local_energy_generic_pno( eJbb = 0.0 eKbb = 0.0 - for (i, j), (U, VT) in zip(system.ij_list_bb, UVT_bb): + for (i, j), (U, VT) in zip(hamiltonian.ij_list_bb, UVT_bb): if i == j: c = 0.5 else: @@ -92,7 +92,7 @@ def local_energy_generic_pno( eKbb -= c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) eJab = 0.0 - for (i, j), (U, VT) in zip(system.ij_list_ab, UVT_ab): + for (i, j), (U, VT) in zip(hamiltonian.ij_list_ab, UVT_ab): theta_i = Ga[i, :] theta_j = Gb[j, :] thetaT_i = GTa[i, :] @@ -104,8 +104,7 @@ def local_energy_generic_pno( eJab += numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV) e2b = 0.5 * (ecoul0 - exxa0 - exxb0) + eJaa + eJbb + eJab + eKaa + eKbb - - return (e1b + e2b + system.ecore, e1b + system.ecore, e2b) + return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) def _exx_compute_batch(rchol_a, rchol_b, GaT_stacked, GbT_stacked, lwalker): @@ -223,11 +222,10 @@ def local_energy_generic_cholesky_opt_batched( lwalker=nwalker, ) e2b_vec = 0.5 * (ecoul_vec - exx_vec) - return (e1_vec + e2b_vec + ham.ecore, e1_vec + ham.ecore, e2b_vec) -def local_energy_generic_cholesky(system, ham, G, Ghalf=None): +def local_energy_generic_cholesky(ham, G, Ghalf=None): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. @@ -287,19 +285,16 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): exx += numpy.trace(T.dot(T)) e2b = 0.5 * (ecoul - exx) - return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) def local_energy_generic_cholesky_opt_stochastic( - system, G, nsamples, Ghalf, rchol=None, C0=None, ecoul0=None, exxa0=None, exxb0=None + hamiltonian, nelec, nsamples, G, Ghalf=None, rchol=None, C0=None, ecoul0=None, exxa0=None, exxb0=None ): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. Parameters ---------- - system : :class:`hubbard` - System information for the hubbard model. G : :class:`numpy.ndarray` Walker's "green's function" Returns @@ -317,18 +312,18 @@ def local_energy_generic_cholesky_opt_stochastic( control = False # Element wise multiplication. - e1b = numpy.sum(system.H1[0] * G[0]) + numpy.sum(system.H1[1] * G[1]) + e1b = numpy.sum(hamilltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) if rchol is None: - rchol = system.rchol - nalpha, nbeta = system.nup, system.ndown - nbasis = system.nbasis + rchol = hamiltonian.rchol + nalpha, nbeta = nelec + nbasis = hamiltonian.nbasis Ga, Gb = Ghalf[0], Ghalf[1] Xa = rchol[0].T.dot(Ga.ravel()) Xb = rchol[1].T.dot(Gb.ravel()) ecoul = numpy.dot(Xa, Xa) ecoul += numpy.dot(Xb, Xb) ecoul += 2 * numpy.dot(Xa, Xb) - if system.sparse: + if hamiltonian.sparse: rchol_a, rchol_b = [rchol[0].toarray(), rchol[1].toarray()] else: rchol_a, rchol_b = rchol[0], rchol[1] @@ -352,8 +347,8 @@ def local_energy_generic_cholesky_opt_stochastic( Ta = numpy.zeros((nsamples, nalpha, nalpha), dtype=rchol_a.dtype) Tb = numpy.zeros((nsamples, nbeta, nbeta), dtype=rchol_b.dtype) - G0aT = C0[:, : system.nup] - G0bT = C0[:, system.nup :] + G0aT = C0[:, :nalpha] + G0bT = C0[:, nalpha:] GaT = Ga.T GbT = Gb.T @@ -394,18 +389,16 @@ def local_energy_generic_cholesky_opt_stochastic( # pr.disable() # pr.print_stats(sort='tottime') - return (e1b + e2b + system.ecore, e1b + system.ecore, e2b) + return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) -def local_energy_generic_cholesky_opt(system, ham, Ga, Gb, Ghalfa, Ghalfb, rchola, rcholb): +def local_energy_generic_cholesky_opt(ham, nelec, Ga, Gb, Ghalfa=None, Ghalfb=None, rchola=None, rcholb=None): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. Parameters ---------- - system : :class:`Generic` - System information for Generic. ham : :class:`Abinitio` Contains necessary hamiltonian information G : :class:`numpy.ndarray` @@ -446,8 +439,9 @@ def local_energy_generic_cholesky_opt(system, ham, Ga, Gb, Ghalfa, Ghalfb, rchol complex128 = numpy.complex128 e1b = sum(ham.H1[0] * Ga) + sum(ham.H1[1] * Gb) - nalpha, nbeta = system.nup, system.ndown + nalpha, nbeta = nelec nbasis = ham.nbasis + if rchola is not None: naux = rchola.shape[0] @@ -490,6 +484,36 @@ def local_energy_generic_cholesky_opt(system, ham, Ga, Gb, Ghalfa, Ghalfb, rchol return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) + +# FDM: deprecated remove? +def local_energy_generic_opt(hamiltonian, nelec, G, Ghalf=None, eri=None): + """Compute local energy using half-rotated eri tensor.""" + na, nb = nelec + M = hamiltonian.nbasis + assert eri is not None + + vipjq_aa = eri[0, : na**2 * M**2].reshape((na, M, na, M)) + vipjq_bb = eri[0, na**2 * M**2 : na**2 * M**2 + nb**2 * M**2].reshape( + (nb, M, nb, M) + ) + vipjq_ab = eri[0, na**2 * M**2 + nb**2 * M**2 :].reshape((na, M, nb, M)) + + Ga, Gb = Ghalf[0], Ghalf[1] + # Element wise multiplication. + e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) + # Coulomb + eJaa = 0.5 * numpy.einsum("irjs,ir,js", vipjq_aa, Ga, Ga) + eJbb = 0.5 * numpy.einsum("irjs,ir,js", vipjq_bb, Gb, Gb) + eJab = numpy.einsum("irjs,ir,js", vipjq_ab, Ga, Gb) + + eKaa = -0.5 * numpy.einsum("irjs,is,jr", vipjq_aa, Ga, Ga) + eKbb = -0.5 * numpy.einsum("irjs,is,jr", vipjq_bb, Gb, Gb) + + e2b = eJaa + eJbb + eJab + eKaa + eKbb + + return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) + + def fock_generic(hamiltonian, P): nbasis = hamiltonian.nbasis nchol = hamiltonian.nchol diff --git a/ipie/thermal/estimators/local_energy.py b/ipie/thermal/estimators/local_energy.py index 9d8d6d57..8003fbb9 100644 --- a/ipie/thermal/estimators/local_energy.py +++ b/ipie/thermal/estimators/local_energy.py @@ -3,7 +3,7 @@ from ipie.thermal.estimators.ueg import local_energy_ueg except ImportError as e: print(e) -from ipie.estimators.generic import local_energy_generic_opt +from ipie.thermal.estimators.generic import local_energy_generic_opt from ipie.thermal.estimators.generic import ( local_energy_generic_cholesky, local_energy_generic_cholesky_opt, @@ -13,21 +13,22 @@ from ipie.thermal.estimators.thermal import one_rdm_from_G -def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): +def local_energy_G(hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): assert len(G) == 2 ghf = G[0].shape[-1] == 2 * hamiltonian.nbasis # unfortunate interfacial problem for the HH model if hamiltonian.name in ["Hubbard", "HubbardHolstein", "PW_FFT"]: raise NotImplementedError elif hamiltonian.name == "UEG": - return local_energy_ueg(system, hamiltonian, G) + return local_energy_ueg(hamiltonian, G) else: if Ghalf is not None: if hamiltonian.stochastic_ri and hamiltonian.control_variate: return local_energy_generic_cholesky_opt_stochastic( - system, + hamiltonian, + trial.nelec, + hamiltonian.nsamples, G, - nsamples=hamiltonian.nsamples, Ghalf=Ghalf, rchol=trial._rchol, C0=trial.psi, @@ -37,18 +38,25 @@ def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): ) elif hamiltonian.stochastic_ri and not hamiltonian.control_variate: return local_energy_generic_cholesky_opt_stochastic( - system, + hamiltonian, + trial.nelec, + hamiltonian.nsamples, G, - nsamples=hamiltonian.nsamples, Ghalf=Ghalf, rchol=trial._rchol, ) elif hamiltonian.exact_eri and not hamiltonian.pno: - return local_energy_generic_opt(system, G, Ghalf=Ghalf, eri=trial._eri) + return local_energy_generic_opt( + hamiltonian, + trial.nelec, + G, + Ghalf=Ghalf, + eri=trial._eri) elif hamiltonian.pno: assert hamiltonian.exact_eri and hamiltonian.control_variate return local_energy_generic_pno( - system, + hamiltonian, + trial.nelec, G, Ghalf=Ghalf, eri=trial._eri, @@ -60,29 +68,29 @@ def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): ) else: return local_energy_generic_cholesky_opt( - system, hamiltonian, - Ga=G[0], - Gb=G[1], + trial.nelec, + G[0], + G[1], Ghalfa=Ghalf[0], Ghalfb=Ghalf[1], rchola=trial._rchola, rcholb=trial._rcholb, ) else: - return local_energy_generic_cholesky(system, hamiltonian, G) + return local_energy_generic_cholesky(hamiltonian, G) # TODO: should pass hamiltonian here and make it work for all possible types # this is a generic local_energy handler. So many possible combinations of local energy strategies... -def local_energy(system, hamiltonian, walker, trial): +def local_energy(hamiltonian, walker, trial): if walker.name == "MultiDetWalker": raise NotImplementedError elif walker.name == "ThermalWalker": - return local_energy_G(system, hamiltonian, trial, one_rdm_from_G(walker.G), None) + return local_energy_G(hamiltonian, trial, one_rdm_from_G(walker.G), None) else: if hamiltonian.name == "HubbardHolstein": raise NotImplementedError else: - return local_energy_G(system, hamiltonian, trial, walker.G, walker.Ghalf) + return local_energy_G(hamiltonian, trial, walker.G, walker.Ghalf) diff --git a/ipie/thermal/estimators/mixed.py b/ipie/thermal/estimators/mixed.py index 06284866..5f641c52 100644 --- a/ipie/thermal/estimators/mixed.py +++ b/ipie/thermal/estimators/mixed.py @@ -10,7 +10,7 @@ import time from ipie.estimators.greens_function import greens_function -from ipie.estimators.local_energy_batch import local_energy_batch +#from ipie.estimators.local_energy_batch import local_energy_batch from ipie.estimators.utils import H5EstimatorHelper from ipie.thermal.estimators.local_energy import local_energy from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number @@ -58,7 +58,7 @@ class Mixed(object): Class for outputting rdm data to HDF5 group. """ - def __init__(self, mixed_opts, system, hamiltonian, root, filename, qmc, trial, dtype): + def __init__(self, mixed_opts, hamiltonian, root, filename, qmc, trial, dtype): self.average_gf = mixed_opts.get("average_gf", False) self.eval_energy = mixed_opts.get("evaluate_energy", True) self.calc_one_rdm = mixed_opts.get("one_rdm", False) @@ -131,87 +131,87 @@ def __init__(self, mixed_opts, system, hamiltonian, root, filename, qmc, trial, if root: self.setup_output(filename) - def update_batch( - self, qmc, system, hamiltonian, trial, walker_batch, step, free_projection=False - ): - """Update mixed estimates for walkers. - - Parameters - ---------- - qmc : :class:`ipie.state.QMCOpts` object. - Container for qmc input options. - system : system object. - Container for model input options. - hamiltonian : hamiltonian object. - Container for hamiltonian input options. - trial : :class:`ipie.trial_wavefunction.X' object - Trial wavefunction class. - psi : :class:`ipie.legacy.walkers.Walkers` object - CPMC wavefunction. - step : int - Current simulation step - free_projection : bool - True if doing free projection. - """ - assert free_projection == False - assert self.thermal == False - if is_cupy( - walker_batch.weight - ): # if even one array is a cupy array we should assume the rest is done with cupy - import cupy - - assert cupy.is_available() - array = cupy.array - zeros = cupy.zeros - sum = cupy.sum - abs = cupy.abs - else: - array = numpy.array - zeros = numpy.zeros - sum = numpy.sum - abs = numpy.abs - - # When using importance sampling we only need to know the current - # walkers weight as well as the local energy, the walker's overlap - # with the trial wavefunction is not needed. - if step % self.energy_eval_freq == 0: - greens_function(walker_batch, trial) - if self.eval_energy: - energy = local_energy_batch(system, hamiltonian, walker_batch, trial) - else: - energy = zeros(walker_batch.nwalkers, 3, dtype=numpy.complex128) - self.estimates[self.names.enumer] += sum(walker_batch.weight * energy[:, 0].real) - self.estimates[self.names.e1b : self.names.e2b + 1] += array( - [ - sum(walker_batch.weight * energy[:, 1].real), - sum(walker_batch.weight * energy[:, 2].real), - ] - ) - self.estimates[self.names.edenom] += sum(walker_batch.weight) - - self.estimates[self.names.uweight] += sum(walker_batch.unscaled_weight) - self.estimates[self.names.weight] += sum(walker_batch.weight) - self.estimates[self.names.ovlp] += sum(walker_batch.weight * abs(walker_batch.ovlp)) - self.estimates[self.names.ehyb] += sum(walker_batch.weight * walker_batch.hybrid_energy) - - if self.calc_one_rdm: - start = self.names.time + 1 - end = self.names.time + 1 + w.G.size - self.estimates[start:end] += w.weight * w.G.flatten().real - if self.calc_two_rdm is not None: - start = end - end = end + self.two_rdm.size - self.estimates[start:end] += w.weight * self.two_rdm.flatten().real - def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=False): +# def update_batch( +# self, qmc, system, hamiltonian, trial, walker_batch, step, free_projection=False +# ): +# """Update mixed estimates for walkers. +# +# Parameters +# ---------- +# qmc : :class:`ipie.state.QMCOpts` object. +# Container for qmc input options. +# system : system object. +# Container for model input options. +# hamiltonian : hamiltonian object. +# Container for hamiltonian input options. +# trial : :class:`ipie.trial_wavefunction.X' object +# Trial wavefunction class. +# psi : :class:`ipie.legacy.walkers.Walkers` object +# CPMC wavefunction. +# step : int +# Current simulation step +# free_projection : bool +# True if doing free projection. +# """ +# assert free_projection == False +# assert self.thermal == False +# if is_cupy( +# walker_batch.weight +# ): # if even one array is a cupy array we should assume the rest is done with cupy +# import cupy +# +# assert cupy.is_available() +# array = cupy.array +# zeros = cupy.zeros +# sum = cupy.sum +# abs = cupy.abs +# else: +# array = numpy.array +# zeros = numpy.zeros +# sum = numpy.sum +# abs = numpy.abs +# +# # When using importance sampling we only need to know the current +# # walkers weight as well as the local energy, the walker's overlap +# # with the trial wavefunction is not needed. +# if step % self.energy_eval_freq == 0: +# greens_function(walker_batch, trial) +# if self.eval_energy: +# energy = local_energy_batch(system, hamiltonian, walker_batch, trial) +# else: +# energy = zeros(walker_batch.nwalkers, 3, dtype=numpy.complex128) +# self.estimates[self.names.enumer] += sum(walker_batch.weight * energy[:, 0].real) +# self.estimates[self.names.e1b : self.names.e2b + 1] += array( +# [ +# sum(walker_batch.weight * energy[:, 1].real), +# sum(walker_batch.weight * energy[:, 2].real), +# ] +# ) +# self.estimates[self.names.edenom] += sum(walker_batch.weight) +# +# self.estimates[self.names.uweight] += sum(walker_batch.unscaled_weight) +# self.estimates[self.names.weight] += sum(walker_batch.weight) +# self.estimates[self.names.ovlp] += sum(walker_batch.weight * abs(walker_batch.ovlp)) +# self.estimates[self.names.ehyb] += sum(walker_batch.weight * walker_batch.hybrid_energy) +# +# if self.calc_one_rdm: +# start = self.names.time + 1 +# end = self.names.time + 1 + w.G.size +# self.estimates[start:end] += w.weight * w.G.flatten().real +# if self.calc_two_rdm is not None: +# start = end +# end = end + self.two_rdm.size +# self.estimates[start:end] += w.weight * self.two_rdm.flatten().real + + + def update(self, qmc, hamiltonian, trial, psi, step, free_projection=False): """Update mixed estimates for walkers. Parameters ---------- qmc : :class:`ipie.state.QMCOpts` object. Container for qmc input options. - system : system object. - Container for model input options. hamiltonian : hamiltonian object. Container for hamiltonian input options. trial : :class:`ipie.trial_wavefunction.X' object @@ -231,10 +231,9 @@ def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=Fal w.greens_function(trial) if self.eval_energy: if self.thermal: - E, T, V = local_energy(system, hamiltonian, w, trial) + E, T, V = local_energy(hamiltonian, w, trial) else: E, T, V = local_energy( - system, hamiltonian, w, rchol=trial._rchol, @@ -267,7 +266,7 @@ def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=Fal nav = 0 for ts in range(w.stack_length): w.greens_function(trial, slice_ix=ts * w.stack_size) - E, T, V = local_energy(system, hamiltonian, w, trial) + E, T, V = local_energy(hamiltonian, w, trial) E_sum += E T_sum += T V_sum += V @@ -279,7 +278,7 @@ def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=Fal ) else: w.greens_function(trial) - E, T, V = local_energy(system, hamiltonian, w, trial) + E, T, V = local_energy(hamiltonian, w, trial) nav = particle_number(one_rdm_from_G(w.G)) self.estimates[self.names.nav] += w.weight * nav self.estimates[self.names.enumer] += w.weight * E.real @@ -291,7 +290,7 @@ def update(self, qmc, system, hamiltonian, trial, psi, step, free_projection=Fal if step % self.energy_eval_freq == 0: w.greens_function(trial) if self.eval_energy: - E, T, V = local_energy(system, hamiltonian, w, trial) + E, T, V = local_energy(hamiltonian, w, trial) else: E, T, V = 0, 0, 0 diff --git a/ipie/thermal/estimators/ueg.py b/ipie/thermal/estimators/ueg.py index 9906fc9d..802c5e05 100644 --- a/ipie/thermal/estimators/ueg.py +++ b/ipie/thermal/estimators/ueg.py @@ -24,12 +24,10 @@ def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): Gpmq[iq] += G[i, idxpmq] -def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): +def local_energy_ueg(ham, G, Ghalf=None, two_rdm=None): """Local energy computation for uniform electron gas Parameters ---------- - system : - system class ham : hamiltonian class G : @@ -51,8 +49,6 @@ def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): Gkpq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) Gpmq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) Gprod = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - - ne = [system.nup, system.ndown] nq = numpy.shape(ham.qvecs)[0] for s in [0, 1]: @@ -81,7 +77,6 @@ def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): ) * ham.vqvec.dot(two_rdm[1, 0]) pe = essa + essb + eos - return (ke + pe, ke, pe) diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index 98603264..987a76d2 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -2,7 +2,7 @@ import time import uuid -from ipie.thermal.estimators.handler import Estimators +from ipie.thermal.estimators.estimators import Estimators from ipie.thermal.estimators.local_energy import local_energy from ipie.hamiltonians.utils import get_hamiltonian from ipie.thermal.propagation.utils import get_propagator @@ -177,9 +177,6 @@ def __init__( verbose=self.verbosity > 1, ) self.trial = get_trial_density_matrix( - self.system, - self.hamiltonian, - self.qmc.beta, self.qmc.dt, comm=comm, options=trial_opts, @@ -279,13 +276,12 @@ def run(self, walk=None, comm=None, verbose=None): self.setup_timers() # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) (E_T, ke, pe) = local_energy( - self.system, self.hamiltonian, self.walk.walkers[0], self.trial + self.hamiltonian, self.walk.walkers[0], self.trial ) # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) # Calculate estimates for initial distribution of walkers. self.estimators.estimators["mixed"].update( self.qmc, - self.system, self.hamiltonian, self.trial, self.walk, @@ -314,7 +310,6 @@ def run(self, walk=None, comm=None, verbose=None): start = time.time() self.estimators.update( self.qmc, - self.system, self.hamiltonian, self.trial, self.walk, diff --git a/ipie/thermal/qmc/thermal_afqmc_clean.py b/ipie/thermal/qmc/thermal_afqmc_clean.py index 65ac114d..c4aace74 100644 --- a/ipie/thermal/qmc/thermal_afqmc_clean.py +++ b/ipie/thermal/qmc/thermal_afqmc_clean.py @@ -116,7 +116,6 @@ def run(self, walkers=None, comm=None, verbose=None): # Calculate estimates for initial distribution of walkers. self.estimators.estimators["mixed"].update( self.qmc, - self.system, self.hamiltonian, self.trial, self.walkers, @@ -145,7 +144,6 @@ def run(self, walkers=None, comm=None, verbose=None): start = time.time() self.estimators.update( self.qmc, - self.system, self.hamiltonian, self.trial, self.walkers, diff --git a/ipie/thermal/tests/test_generic.py b/ipie/thermal/tests/test_generic.py index b81e4b19..63b672a1 100644 --- a/ipie/thermal/tests/test_generic.py +++ b/ipie/thermal/tests/test_generic.py @@ -5,7 +5,7 @@ import numpy import mpi4py.MPI as MPI import h5py -from ipie.thermal.estimators.handler import Estimators +from ipie.thermal.estimators.estimators import Estimators from ipie.qmc.options import QMCOpts from ipie.utils.io import to_json @@ -53,8 +53,6 @@ num_chol = Lxmn.shape[0] num_basis = Lxmn.shape[1] -system = Generic(nelec=mol.nelec) - mu = -10.0 beta = 0.1 dt = 0.01 @@ -121,6 +119,7 @@ def compare_test_data(ref, test): from ipie.thermal.qmc.thermal_afqmc_clean import ThermalAFQMC from ipie.hamiltonians.utils import get_hamiltonian + system = Generic(mol.nelec) system.mu = mu hamiltonian = get_hamiltonian(system, options["hamiltonian"]) @@ -155,7 +154,6 @@ def compare_test_data(ref, test): options["estimators"], comm.rank == 0, qmc, - system, hamiltonian, trial, None diff --git a/ipie/thermal/trial/onebody.py b/ipie/thermal/trial/onebody.py index 2962cbd5..97539156 100644 --- a/ipie/thermal/trial/onebody.py +++ b/ipie/thermal/trial/onebody.py @@ -44,13 +44,14 @@ def __init__( cond = numpy.linalg.cond(self.dmat[0]) if verbose: print(f"# condition number of BT: {cond: 10e}") - + + self.nelec = nelec if nav is not None: self.nav = nav else: self.nav = options.get("nav", None) if self.nav is None: - self.nav = nelec[0] + nelec[1] + self.nav = numpy.sum(nelec) if verbose: print(f"# Target average electron number: {self.nav}") From f36f21f38dbc021b0f149498bf4157b5f7b6687f Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 9 Sep 2023 19:55:24 -0400 Subject: [PATCH 27/84] Misspelling --- ipie/thermal/estimators/generic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py index 3033daf9..e4362824 100644 --- a/ipie/thermal/estimators/generic.py +++ b/ipie/thermal/estimators/generic.py @@ -312,7 +312,7 @@ def local_energy_generic_cholesky_opt_stochastic( control = False # Element wise multiplication. - e1b = numpy.sum(hamilltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) + e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) if rchol is None: rchol = hamiltonian.rchol nalpha, nbeta = nelec From 8a7ab90418fdeb0552d927f651bd903f7c108926 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Mon, 2 Oct 2023 11:17:55 -0400 Subject: [PATCH 28/84] updates to walkers --- ipie/thermal/estimators/generic.py | 48 +- ipie/thermal/propagation/generic.py | 2 +- ipie/thermal/trial/mean_field.py | 1 - .../thermal/trial/{onebody.py => one_body.py} | 16 +- ipie/thermal/walkers/handler.py | 4 +- ipie/thermal/walkers/stack.py | 45 +- .../walkers/tests/test_thermal_walkers.py | 23 +- ipie/thermal/walkers/uhf_walkers.py | 115 ++-- ipie/thermal/walkers/uhf_walkers2.py | 593 ++++++++++++++++++ 9 files changed, 726 insertions(+), 121 deletions(-) rename ipie/thermal/trial/{onebody.py => one_body.py} (90%) create mode 100644 ipie/thermal/walkers/uhf_walkers2.py diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py index e4362824..f8513ae2 100644 --- a/ipie/thermal/estimators/generic.py +++ b/ipie/thermal/estimators/generic.py @@ -155,7 +155,7 @@ def _exx_compute_batch(rchol_a, rchol_b, GaT_stacked, GbT_stacked, lwalker): def local_energy_generic_cholesky_opt_batched( - ham, + hamiltonian, Ga_batch: numpy.ndarray, Gb_batch: numpy.ndarray, Ghalfa_batch: numpy.ndarray, @@ -171,7 +171,7 @@ def local_energy_generic_cholesky_opt_batched( Parameters ---------- - ham : :class:`Abinitio` + hamiltonian : :class:`Abinitio` Contains necessary hamiltonian information Ga_batched : :class:`numpy.ndarray` alpha-spin Walker's "green's function" 3-tensor (nwalker, nbasis, nbasis) @@ -197,9 +197,9 @@ def local_energy_generic_cholesky_opt_batched( ecoul_vec = numpy.zeros(nwalker, dtype=numpy.complex128) # simple loop because this part isn't the slow bit for widx in range(nwalker): - e1b = numpy.sum(ham.H1[0] * Ga_batch[widx]) + numpy.sum(ham.H1[1] * Gb_batch[widx]) + e1b = numpy.sum(hamiltonian.H1[0] * Ga_batch[widx]) + numpy.sum(hamiltonian.H1[1] * Gb_batch[widx]) e1_vec[widx] = e1b - nbasis = ham.nbasis + nbasis = hamiltonian.nbasis if rchola is not None: naux = rchola.shape[0] @@ -222,17 +222,17 @@ def local_energy_generic_cholesky_opt_batched( lwalker=nwalker, ) e2b_vec = 0.5 * (ecoul_vec - exx_vec) - return (e1_vec + e2b_vec + ham.ecore, e1_vec + ham.ecore, e2b_vec) + return (e1_vec + e2b_vec + hamiltonian.ecore, e1_vec + hamiltonian.ecore, e2b_vec) -def local_energy_generic_cholesky(ham, G, Ghalf=None): +def local_energy_generic_cholesky(hamiltonian, G, Ghalf=None): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. Parameters ---------- - ham : :class:`Generic` + hamiltonian : :class:`Generic` ab-initio hamiltonian information G : :class:`numpy.ndarray` Walker's "green's function" @@ -245,17 +245,17 @@ def local_energy_generic_cholesky(ham, G, Ghalf=None): Local, kinetic and potential energies. """ # Element wise multiplication. - e1b = numpy.sum(ham.H1[0] * G[0]) + numpy.sum(ham.H1[1] * G[1]) - nbasis = ham.nbasis - nchol = ham.nchol + e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) + nbasis = hamiltonian.nbasis + nchol = hamiltonian.nchol Ga, Gb = G[0], G[1] - if numpy.isrealobj(ham.chol): - Xa = ham.chol.T.dot(Ga.real.ravel()) + 1.0j * ham.chol.T.dot(Ga.imag.ravel()) - Xb = ham.chol.T.dot(Gb.real.ravel()) + 1.0j * ham.chol.T.dot(Gb.imag.ravel()) + if numpy.isrealobj(hamiltonian.chol): + Xa = hamiltonian.chol.T.dot(Ga.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Ga.imag.ravel()) + Xb = hamiltonian.chol.T.dot(Gb.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Gb.imag.ravel()) else: - Xa = ham.chol.T.dot(Ga.ravel()) - Xb = ham.chol.T.dot(Gb.ravel()) + Xa = hamiltonian.chol.T.dot(Ga.ravel()) + Xb = hamiltonian.chol.T.dot(Gb.ravel()) ecoul = numpy.dot(Xa, Xa) ecoul += numpy.dot(Xb, Xb) @@ -267,9 +267,9 @@ def local_energy_generic_cholesky(ham, G, Ghalf=None): GbT = Gb.T.copy() exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - if numpy.isrealobj(ham.chol): + if numpy.isrealobj(hamiltonian.chol): for x in range(nchol): # write a cython function that calls blas for this. - Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) + Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) T[:, :].real = GaT.real.dot(Lmn) T[:, :].imag = GaT.imag.dot(Lmn) exx += numpy.trace(T.dot(T)) @@ -278,14 +278,14 @@ def local_energy_generic_cholesky(ham, G, Ghalf=None): exx += numpy.trace(T.dot(T)) else: for x in range(nchol): # write a cython function that calls blas for this. - Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) + Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) T[:, :] = GaT.dot(Lmn) exx += numpy.trace(T.dot(T)) T[:, :] = GbT.dot(Lmn) exx += numpy.trace(T.dot(T)) e2b = 0.5 * (ecoul - exx) - return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) + return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) def local_energy_generic_cholesky_opt_stochastic( @@ -392,14 +392,14 @@ def local_energy_generic_cholesky_opt_stochastic( return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) -def local_energy_generic_cholesky_opt(ham, nelec, Ga, Gb, Ghalfa=None, Ghalfb=None, rchola=None, rcholb=None): +def local_energy_generic_cholesky_opt(hamiltonian, nelec, Ga, Gb, Ghalfa=None, Ghalfb=None, rchola=None, rcholb=None): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. Parameters ---------- - ham : :class:`Abinitio` + hamiltonian : :class:`Abinitio` Contains necessary hamiltonian information G : :class:`numpy.ndarray` Walker's "green's function" @@ -438,9 +438,9 @@ def local_energy_generic_cholesky_opt(ham, nelec, Ga, Gb, Ghalfa=None, Ghalfb=No complex128 = numpy.complex128 - e1b = sum(ham.H1[0] * Ga) + sum(ham.H1[1] * Gb) + e1b = sum(hamiltonian.H1[0] * Ga) + sum(hamiltonian.H1[1] * Gb) nalpha, nbeta = nelec - nbasis = ham.nbasis + nbasis = hamiltonian.nbasis if rchola is not None: naux = rchola.shape[0] @@ -482,7 +482,7 @@ def local_energy_generic_cholesky_opt(ham, nelec, Ga, Gb, Ghalfa=None, Ghalfb=No e2b = 0.5 * (ecoul - exx) - return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) + return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) # FDM: deprecated remove? diff --git a/ipie/thermal/propagation/generic.py b/ipie/thermal/propagation/generic.py index 34927332..5310bedb 100644 --- a/ipie/thermal/propagation/generic.py +++ b/ipie/thermal/propagation/generic.py @@ -67,7 +67,7 @@ def __init__(self, system, hamiltonian, trial, qmc, options={}, verbose=False): ) # Mean field shifted one-body propagator - self.mu = hamiltonian.mu + self.mu = options.get("mu", -1.0) self.BT = trial.dmat self.BTinv = trial.dmat_inv diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index c9e03b8a..27fea9f6 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -6,7 +6,6 @@ from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.thermal.trial.onebody import OneBody - class MeanField(OneBody): def __init__(self, hamiltonian, nelec, beta, dt, options={}, H1=None, verbose=False): OneBody.__init__( diff --git a/ipie/thermal/trial/onebody.py b/ipie/thermal/trial/one_body.py similarity index 90% rename from ipie/thermal/trial/onebody.py rename to ipie/thermal/trial/one_body.py index 97539156..51629fc5 100644 --- a/ipie/thermal/trial/onebody.py +++ b/ipie/thermal/trial/one_body.py @@ -59,10 +59,10 @@ def __init__( self.deps = options.get("threshold", 1e-6) self.mu = options.get("mu", None) - self.num_slices = int(beta / dt) - self.stack_size = options.get("stack_size", None) + self.nslice = int(beta / dt) + self.nstack = options.get("nstack", None) - if self.stack_size == None: + if self.nstack == None: if verbose: print("# Estimating stack size from BT.") eigs, ev = scipy.linalg.eigh(self.dmat[0]) @@ -74,17 +74,17 @@ def __init__( # the product will scale roughly as cond(BT)^(number of products). # We can determine a conservative stack size by requiring that the # condition number of the product does not exceed 1e3. - self.stack_size = min(self.num_slices, int(3.0 / numpy.log10(self.cond))) + self.nstack = min(self.nslice, int(3.0 / numpy.log10(self.cond))) if verbose: print( "# Initial stack size, # of slices: {}, {}".format( - self.stack_size, self.num_slices + self.nstack, self.nslice ) ) # adjust stack size - self.stack_size = update_stack(self.stack_size, self.num_slices, verbose=verbose) - self.num_bins = int(beta / (self.stack_size * dt)) + self.nstack = update_stack(self.nstack, self.nslice, verbose=verbose) + self.num_bins = int(beta / (self.nstack * dt)) if verbose: print(f"# Number of stacks: {self.num_bins}") @@ -94,7 +94,7 @@ def __init__( if verbose: print("# Using alternate sign convention for chemical potential.") sign = -1 - dtau = self.stack_size * dt + dtau = self.nstack * dt self.dtau = dtau if self.mu is None: diff --git a/ipie/thermal/walkers/handler.py b/ipie/thermal/walkers/handler.py index 4d488954..4d64606e 100644 --- a/ipie/thermal/walkers/handler.py +++ b/ipie/thermal/walkers/handler.py @@ -5,7 +5,7 @@ import h5py import numpy -from ipie.thermal.walkers.uhf_walkers import ThermalWalker +from ipie.thermal.walkers.uhf_walkers import ThermalWalkers from ipie.utils.io import get_input_value from ipie.utils.misc import update_stack @@ -61,7 +61,7 @@ def __init__( elif trial.name == "thermal": self.walker_type = "thermal" self.walkers = [ - ThermalWalker( + ThermalWalkers( system, hamiltonian, trial, diff --git a/ipie/thermal/walkers/stack.py b/ipie/thermal/walkers/stack.py index 3fbd38cd..4c318430 100644 --- a/ipie/thermal/walkers/stack.py +++ b/ipie/thermal/walkers/stack.py @@ -3,12 +3,11 @@ from ipie.utils.misc import get_numeric_names - class PropagatorStack: def __init__( self, - stack_size, - ntime_slices, + nstack, + nslice, nbasis, dtype, BT=None, @@ -19,26 +18,24 @@ def __init__( thresh=1e-6, ): self.time_slice = 0 - self.stack_size = stack_size - self.ntime_slices = ntime_slices - self.nbins = ntime_slices // self.stack_size + self.nstack = nstack + self.nslice = nslice + self.nbins = nslice // self.nstack + self.nbasis = nbasis self.diagonal_trial = diagonal self.averaging = averaging self.thresh = thresh - self.lowrank = lowrank self.ovlp = numpy.asarray([1.0, 1.0]) + self.reortho = 1 if self.lowrank: assert diagonal - self.reortho = 1 - - if self.nbins * self.stack_size < self.ntime_slices: - print("stack_size must divide the total path length") - assert self.nbins * self.stack_size == self.ntime_slices + if self.nbins * self.nstack < self.nslice: + print("nstack must divide the total path length") + assert self.nbins * self.nstack == self.nslice - self.nbasis = nbasis self.dtype = dtype self.BT = BT self.BTinv = BTinv @@ -112,8 +109,8 @@ def set_buffer(self, buff): def set_all(self, BT): # Diagonal = True assumes BT is diagonal and left is also diagonal if self.diagonal_trial: - for i in range(0, self.ntime_slices): - ix = i // self.stack_size # bin index + for i in range(0, self.nslice): + ix = i // self.nstack # bin index # Commenting out these two. It is only useful for Hubbard self.left[ix, 0] = numpy.diag( numpy.multiply(BT[0].diagonal(), self.left[ix, 0].diagonal()) @@ -124,8 +121,8 @@ def set_all(self, BT): self.stack[ix, 0] = self.left[ix, 0].copy() self.stack[ix, 1] = self.left[ix, 1].copy() else: - for i in range(0, self.ntime_slices): - ix = i // self.stack_size # bin index + for i in range(0, self.nslice): + ix = i // self.nstack # bin index self.left[ix, 0] = numpy.dot(BT[0], self.left[ix, 0]) self.left[ix, 1] = numpy.dot(BT[1], self.left[ix, 1]) self.stack[ix, 0] = self.left[ix, 0].copy() @@ -180,8 +177,8 @@ def update(self, B): self.stack[self.block, 0] = B[0].dot(self.stack[self.block, 0]) self.stack[self.block, 1] = B[1].dot(self.stack[self.block, 1]) self.time_slice = self.time_slice + 1 - self.block = self.time_slice // self.stack_size - self.counter = (self.counter + 1) % self.stack_size + self.block = self.time_slice // self.nstack + self.counter = (self.counter + 1) % self.nstack def update_full_rank(self, B): # Diagonal = True assumes BT is diagonal and left is also diagonal @@ -215,8 +212,8 @@ def update_full_rank(self, B): self.stack[self.block, 1] = self.left[self.block, 1].dot(self.right[self.block, 1]) self.time_slice = self.time_slice + 1 # Count the time slice - self.block = self.time_slice // self.stack_size # move to the next block if necessary - self.counter = (self.counter + 1) % self.stack_size # Counting within a stack + self.block = self.time_slice // self.nstack # move to the next block if necessary + self.counter = (self.counter + 1) % self.nstack # Counting within a stack def update_low_rank(self, B): assert not self.averaging @@ -230,7 +227,7 @@ def update_low_rank(self, B): mR = B.shape[-1] # initial mR mL = B.shape[-1] # initial mR mT = B.shape[-1] # initial mR - next_block = (self.time_slice + 1) // self.stack_size # move to the next block if necessary + next_block = (self.time_slice + 1) // self.nstack # move to the next block if necessary # print("next_block", next_block) # print("self.block", self.block) if next_block > self.block: # Do QR and update here? @@ -390,5 +387,5 @@ def update_low_rank(self, B): # print("ovlp = {}".format(self.ovlp)) self.mT = mT self.time_slice = self.time_slice + 1 # Count the time slice - self.block = self.time_slice // self.stack_size # move to the next block if necessary - self.counter = (self.counter + 1) % self.stack_size # Counting within a stack + self.block = self.time_slice // self.nstack # move to the next block if necessary + self.counter = (self.counter + 1) % self.nstack # Counting within a stack diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py index 7c47c42c..80dfd213 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -1,23 +1,32 @@ import numpy import pytest -from ipie.legacy.hamiltonians.ueg import UEG as HamUEG -from ipie.legacy.systems.ueg import UEG -from ipie.thermal.trial.onebody import OneBody -from ipie.legacy.walkers.thermal import ThermalWalker +from ipie.hamiltonians.ueg import UEG as HamUEG +from ipie.systems.ueg import UEG +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers @pytest.mark.unit def test_thermal_walkers(): - options = {"rs": 2, "nup": 7, "ndown": 7, "ecut": 2, "write_integrals": False} + rs = 2 + ecut = 2 + nup = 7 + ndown = 7 + nelec = (nup, ndown) + options = {"rs": rs, "nup": nup, "ndown": ndown, "ecut": ecut, "write_integrals": False} + system = UEG(options=options) hamiltonian = HamUEG(system, options=options) beta = 1 - trial = OneBody(system, hamiltonian, beta, 0.05) + dt = 0.05 + verbose = True + trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) nwalkers = 10 - walkers = [ThermalWalker(system, hamiltonian, trial, verbose=i == 0) for i in range(nwalkers)] + nbasis = trial.dmat.shape[-1] + walkers = [UHFThermalWalkers(trial, nup, ndown, nbasis, nwalkers, verbose=i == 0) for i in range(nwalkers)] if __name__ == "__main__": diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index 0a6d530e..fcd89943 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -1,32 +1,61 @@ import numpy import scipy.linalg -from ipie.thermal.estimators.local_energy import local_energy_G from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number from ipie.thermal.walkers.stack import PropagatorStack from ipie.utils.misc import get_numeric_names, update_stack from ipie.walkers.base_walkers import BaseWalkers +from ipie.thermal.trial.one_body import OneBody -class ThermalWalkers(BaseWalkers): - # def __init__(self, system, hamiltonian, trial, walker_opts={}, verbose=False): +class UHFThermalWalkers(BaseWalkers): def __init__( self, - initial_walker: numpy.ndarray, + trial: OneBody, nup: int, ndown: int, nbasis: int, nwalkers: int, - mpi_handler=None, + nstack = None, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + mpi_handler = None, verbose: bool = False, ): - super().__init__(self, system, hamiltonian, trial, walker_opts=walker_opts) - self.num_slices = trial.num_slices - dtype = numpy.complex128 - self.G = numpy.zeros(trial.dmat.shape, dtype=dtype) + """UHF style walker. + """ + assert isinstance(trial, OneBody) + self.nup = nup + self.ndown = ndown + self.nbasis = nbasis + self.mpi_handler = mpi_handler + self.nslice = trial.nslice + self.nstack = nstack + + if self.nstack == None: + self.nstack = trial.nstack + + if (self.nslice // self.nstack) * self.nstack != self.nslice: + if verbose: + print("# Input stack size does not divide number of slices.") + self.nstack = update_stack(self.nstack, self.nslice, verbose) + + if self.nstack > trial.nstack: + if verbose: + print("# Walker stack size differs from that estimated from " "Trial density matrix.") + print(f"# Be careful. cond(BT)**nstack: {trial.cond ** self.nstack:10.3e}.") + + self.stack_length = self.nslice // self.nstack + self.lowrank = lowrank + self.lowrank_thresh = lowrank_thresh + + super().__init__(nwalkers, verbose=verbose) + + self.G = numpy.zeros(trial.dmat.shape, dtype=numpy.complex128) self.Ghalf = None - self.nbasis = trial.dmat[0].shape[0] - self.stack_size = walker_opts.get("stack_size", None) - max_diff_diag = numpy.linalg.norm((numpy.diag(trial.dmat[0].diagonal()) - trial.dmat[0])) + max_diff_diag = numpy.linalg.norm( + (numpy.diag( + trial.dmat[0].diagonal()) - trial.dmat[0])) + if max_diff_diag < 1e-10: self.diagonal_trial = True if verbose: @@ -36,31 +65,15 @@ def __init__( if verbose: print("# Trial density matrix is not diagonal.") - if self.stack_size == None: - self.stack_size = trial.stack_size - if (self.num_slices // self.stack_size) * self.stack_size != self.num_slices: - if verbose: - print("# Input stack size does not divide number of slices.") - self.stack_size = update_stack(self.stack_size, self.num_slices, verbose) - if self.stack_size > trial.stack_size: - if verbose: - print( - "# Walker stack size differs from that estimated from " "trial density matrix." - ) - print(f"# Be careful. cond(BT)**stack_size: {trial.cond ** self.stack_size:10.3e}.") - self.stack_length = self.num_slices // self.stack_size - if verbose: - print(f"# Walker stack size: {self.stack_size}") - - self.lowrank = walker_opts.get("low_rank", False) - self.lowrank_thresh = walker_opts.get("low_rank_thresh", 1e-6) if verbose: + print(f"# Walker stack size: {self.nstack}") print(f"# Using low rank trick: {self.lowrank}") + self.stack = PropagatorStack( - self.stack_size, - trial.num_slices, - trial.dmat.shape[-1], - dtype, + self.nstack, + self.nslice, + self.nbasis, + numpy.complex128, trial.dmat, trial.dmat_inv, diagonal=self.diagonal_trial, @@ -80,9 +93,9 @@ def __init__( ) self.stack.ovlp = numpy.array([1.0 / self.M0[0], 1.0 / self.M0[1]]) - # # temporary storage for stacks... - I = numpy.identity(hamiltonian.nbasis, dtype=dtype) - One = numpy.ones(hamiltonian.nbasis, dtype=dtype) + # Temporary storage for stacks... + I = numpy.identity(self.nbasis, dtype=numpy.complex128) + One = numpy.ones(self.nbasis, dtype=numpy.complex128) self.Tl = numpy.array([I, I]) self.Ql = numpy.array([I, I]) self.Dl = numpy.array([One, One]) @@ -92,18 +105,11 @@ def __init__( self.hybrid_energy = 0.0 if verbose: - # def local_energy(self, system, two_rdm=None): P = one_rdm_from_G(self.G) - eloc = local_energy_G(system, hamiltonian, self, P) nav = particle_number(P) - print("# Initial walker energy: {} {} {}".format(*eloc)) - print(f"# Initial walker electron number: {nav}") - # self.buff_names = ['weight', 'G', 'unscaled_weight', 'phase', 'Tl', - # 'Ql', 'Dl', 'Tr', 'Qr', 'Dr', 'M0'] + print(f"# Trial electron number: {nav}") + self.buff_names, self.buff_size = get_numeric_names(self.__dict__) - # self.buff_size = (self.G.size+3+self.Tl.size+2+ - # self.Ql.size+self.Dl.size+self.Tr.size+self.Qr.size - # +self.Dr.size) def greens_function(self, trial, slice_ix=None, inplace=True): if self.lowrank: @@ -114,7 +120,7 @@ def greens_function(self, trial, slice_ix=None, inplace=True): def greens_function_svd(self, trial, slice_ix=None, inplace=True): if slice_ix == None: slice_ix = self.stack.time_slice - bin_ix = slice_ix // self.stack.stack_size + bin_ix = slice_ix // self.stack.nstack # For final time slice want first block to be the rightmost (for energy # evaluation). if bin_ix == self.stack.nbins: @@ -159,7 +165,7 @@ def greens_function_qr(self, trial, slice_ix=None, inplace=True): if slice_ix == None: slice_ix = self.stack.time_slice - bin_ix = slice_ix // self.stack.stack_size + bin_ix = slice_ix // self.stack.nstack # For final time slice want first block to be the rightmost (for energy # evaluation). if bin_ix == self.stack.nbins: @@ -499,7 +505,7 @@ def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): if slice_ix == None: slice_ix = self.stack.time_slice - bin_ix = slice_ix // self.stack.stack_size + bin_ix = slice_ix // self.stack.nstack # For final time slice want first block to be the rightmost (for energy # evaluation). if bin_ix == self.stack.nbins: @@ -566,9 +572,10 @@ def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) ) return G + + # For compatibiltiy with BaseWalkers class. + def reortho(self): + pass - -# def local_energy_G(system, hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): -# def local_energy(self, system, two_rdm=None): -# rdm = one_rdm_from_G(self.G) -# return local_energy_G(system, hamiltonian, self, rdm) + def reortho_batched(self): + pass diff --git a/ipie/thermal/walkers/uhf_walkers2.py b/ipie/thermal/walkers/uhf_walkers2.py new file mode 100644 index 00000000..476c247a --- /dev/null +++ b/ipie/thermal/walkers/uhf_walkers2.py @@ -0,0 +1,593 @@ +import numpy +import scipy.linalg + +from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number +from ipie.thermal.walkers.stack import PropagatorStack +from ipie.utils.misc import get_numeric_names, update_stack +from ipie.walkers.base_walkers import BaseWalkers +from ipie.thermal.trial.one_body import OneBody + +class UHFThermalWalkers(BaseWalkers): + def __init__( + self, + trial: OneBody, + nup: int, + ndown: int, + nbasis: int, + nwalkers: int, + nstack = None, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + mpi_handler = None, + verbose: bool = False, + ): + """UHF style walker. + """ + assert isinstance(trial, OneBody) + self.nup = nup + self.ndown = ndown + self.nbasis = nbasis + self.mpi_handler = mpi_handler + self.nslice = trial.nslice + self.nstack = nstack + + if self.nstack == None: + self.nstack = trial.nstack + + if (self.nslice // self.nstack) * self.nstack != self.nslice: + if verbose: + print("# Input stack size does not divide number of slices.") + self.nstack = update_stack(self.nstack, self.nslice, verbose) + + if self.nstack > trial.nstack: + if verbose: + print("# Walker stack size differs from that estimated from " "Trial density matrix.") + print(f"# Be careful. cond(BT)**nstack: {trial.cond ** self.nstack:10.3e}.") + + self.stack_length = self.nslice // self.nstack + self.lowrank = lowrank + self.lowrank_thresh = lowrank_thresh + + super().__init__(nwalkers, verbose=verbose) + + self.Ga = numpy.zeros( + shape=(self.nwalkers, self.nbasis, self.nbasis), + dtype=numpy.complex128) + ) + self.Gb = numpy.zeros( + shape=(self.nwalkers, self.nbasis, self.nbasis), + dtype=numpy.complex128) + ) + self.Ghalf = None + max_diff_diag = numpy.linalg.norm( + (numpy.diag( + trial.dmat[0].diagonal()) - trial.dmat[0])) + + if max_diff_diag < 1e-10: + self.diagonal_trial = True + if verbose: + print("# Trial density matrix is diagonal.") + else: + self.diagonal_trial = False + if verbose: + print("# Trial density matrix is not diagonal.") + + if verbose: + print(f"# Walker stack size: {self.nstack}") + print(f"# Using low rank trick: {self.lowrank}") + + self.stacks = [ + PropagatorStack( + self.nstack, + self.nslice, + self.nbasis, + numpy.complex128, + trial.dmat, + trial.dmat_inv, + diagonal=self.diagonal_trial, + lowrank=self.lowrank, + thresh=self.lowrank_thresh, + ) for i in range(nwalkers) + ] + + self.M0a = numpy.array( + [ + scipy.linalg.det(self.G[0], check_finite=False), + scipy.linalg.det(self.G[1], check_finite=False), + ] + ) + + # Initialise all propagators to the trial density matrix. + for i, stack in enumerate(self.stacks): + stack.set_all(trial.dmat) + self.greens_function_qr_strat(trial) + stack.G = self.G[i] + + self.stack.ovlp = numpy.array([1.0 / self.M0[0], 1.0 / self.M0[1]]) + + # Temporary storage for stacks... + I = numpy.identity(self.nbasis, dtype=numpy.complex128) + One = numpy.ones(self.nbasis, dtype=numpy.complex128) + self.Tl = numpy.array([I, I]) + self.Ql = numpy.array([I, I]) + self.Dl = numpy.array([One, One]) + self.Tr = numpy.array([I, I]) + self.Qr = numpy.array([I, I]) + self.Dr = numpy.array([One, One]) + + self.hybrid_energy = 0.0 + if verbose: + P = one_rdm_from_G(self.G) + nav = particle_number(P) + print(f"# Trial electron number: {nav}") + + self.buff_names, self.buff_size = get_numeric_names(self.__dict__) + + def greens_function(self, trial, slice_ix=None, inplace=True): + if self.lowrank: + return self.stack.G + else: + return self.greens_function_qr_strat(trial, slice_ix=slice_ix, inplace=inplace) + + def greens_function_svd(self, trial, slice_ix=None, inplace=True): + if slice_ix == None: + slice_ix = self.stack.time_slice + bin_ix = slice_ix // self.stack.nstack + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + if inplace: + G = None + else: + G = numpy.zeros(self.G.shape, self.G.dtype) + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} + # in stable way. Iteratively construct SVD decompositions starting + # from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + (U1, S1, V1) = scipy.linalg.svd(B[spin]) + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + T1 = numpy.dot(B[spin], U1) + # todo optimise + T2 = numpy.dot(T1, numpy.diag(S1)) + (U1, S1, V) = scipy.linalg.svd(T2) + V1 = numpy.dot(V, V1) + A = numpy.dot(U1.dot(numpy.diag(S1)), V1) + # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. + # Care needs to be taken when adding the identity matrix. + T3 = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) + (U2, S2, V2) = scipy.linalg.svd(T3) + U3 = numpy.dot(U1, U2) + D3 = numpy.diag(1.0 / S2) + V3 = numpy.dot(V2, V1) + # G(l) = (U3 S2 V3)^{-1} + # = V3^{\dagger} D3 U3^{\dagger} + if inplace: + # self.G[spin] = (V3inv).dot(U3.conj().T) + self.G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) + else: + # G[spin] = (V3inv).dot(U3.conj().T) + G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) + return G + + def greens_function_qr(self, trial, slice_ix=None, inplace=True): + if slice_ix == None: + slice_ix = self.stack.time_slice + + bin_ix = slice_ix // self.stack.nstack + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} + # in stable way. Iteratively construct SVD decompositions starting + # from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + (U1, V1) = scipy.linalg.qr(B[spin], pivoting=False, check_finite=False) + + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + T1 = numpy.dot(B[spin], U1) + (U1, V) = scipy.linalg.qr(T1, pivoting=False, check_finite=False) + V1 = numpy.dot(V, V1) + + # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. + # Care needs to be taken when adding the identity matrix. + V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0])) + + T3 = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0]) + (U2, V2) = scipy.linalg.qr(T3, pivoting=False, check_finite=False) + + U3 = numpy.dot(U1, U2) + V3 = numpy.dot(V2, V1) + V3inv = scipy.linalg.solve_triangular(V3, numpy.identity(V3.shape[0])) + # G(l) = (U3 S2 V3)^{-1} + # = V3^{\dagger} D3 U3^{\dagger} + if inplace: + self.G[spin] = (V3inv).dot(U3.conj().T) + else: + G[spin] = (V3inv).dot(U3.conj().T) + return G + + def compute_left_right(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # right bit + # B(right) ... B(1) + if center_ix > 0: + # print ("center_ix > 0") + B = self.stack.get(0) + (self.Qr[spin], R1, P1) = scipy.linalg.qr( + B[spin], pivoting=True, check_finite=False + ) + # Form D matrices + self.Dr[spin] = R1.diagonal() + D1inv = 1.0 / R1.diagonal() + self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) + # now permute them + self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] + + for ix in range(1, center_ix): + B = self.stack.get(ix) + C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) + (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = 1.0 / R1.diagonal() + self.Dr[spin] = R1.diagonal() + # smarter permutation + # D^{-1} * R + tmp = numpy.einsum("i,ij->ij", D1inv, R1) + # D^{-1} * R * P^T + tmp[:, P1] = tmp[:, range(self.nbasis)] + # D^{-1} * R * P^T * T + self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) + + # left bit + # B(l) ... B(left) + if center_ix < self.stack.nbins - 1: + # print("center_ix < self.stack.nbins-1 first") + # We will assume that B matrices are all diagonal for left.... + B = self.stack.get(center_ix + 1) + self.Dl[spin] = B[spin].diagonal() + D1inv = 1.0 / B[spin].diagonal() + self.Ql[spin] = numpy.identity(B[spin].shape[0]) + self.Tl[spin] = numpy.identity(B[spin].shape[0]) + + for ix in range(center_ix + 2, self.stack.nbins): + # print("center_ix < self.stack.nbins-1 first inner loop") + B = self.stack.get(ix) + C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) + self.Dl[spin] = C2 + + def compute_right(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # right bit + # B(right) ... B(1) + if center_ix > 0: + # print ("center_ix > 0") + B = self.stack.get(0) + (self.Qr[spin], R1, P1) = scipy.linalg.qr( + B[spin], pivoting=True, check_finite=False + ) + # Form D matrices + self.Dr[spin] = R1.diagonal() + D1inv = 1.0 / R1.diagonal() + self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) + # now permute them + self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] + + for ix in range(1, center_ix): + B = self.stack.get(ix) + C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) + (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = 1.0 / R1.diagonal() + self.Dr[spin] = R1.diagonal() + # smarter permutation + # D^{-1} * R + tmp = numpy.einsum("i,ij->ij", D1inv, R1) + # D^{-1} * R * P^T + tmp[:, P1] = tmp[:, range(self.nbasis)] + # D^{-1} * R * P^T * T + self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) + + def compute_left(self, center_ix): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + # B(L) .... B(1) + for spin in [0, 1]: + # left bit + # B(l) ... B(left) + if center_ix < self.stack.nbins - 1: + # print("center_ix < self.stack.nbins-1 first") + # We will assume that B matrices are all diagonal for left.... + B = self.stack.get(center_ix + 1) + self.Dl[spin] = B[spin].diagonal() + self.Ql[spin] = numpy.identity(B[spin].shape[0]) + self.Tl[spin] = numpy.identity(B[spin].shape[0]) + + for ix in range(center_ix + 2, self.stack.nbins): + # print("center_ix < self.stack.nbins-1 first inner loop") + B = self.stack.get(ix) + C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) + self.Dl[spin] = C2.diagonal() + + def greens_function_left_right(self, center_ix, inplace=False, thresh=1e-6): + assert self.diagonal_trial + + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + mL = self.G.shape[1] + mR = self.G.shape[1] + mT = self.G.shape[1] + + Bc = self.stack.get(center_ix) + + nbsf = Bc.shape[1] + + # It goes to right to left and we sample (I + L*B*R) in the end + for spin in [0, 1]: + if center_ix > 0: # there exists right bit + mR = len(self.Dr[spin][numpy.abs(self.Dr[spin]) > thresh]) + + Ccr = numpy.einsum( + "ij,j->ij", + numpy.dot(Bc[spin], self.Qr[spin][:, :mR]), + self.Dr[spin][:mR], + ) # N x mR + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) + Dlcr = Rlcr[:mR, :mR].diagonal() # mR + Dinv = 1.0 / Dlcr # mR + tmp = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :mR]) # mR, mR x mR -> mR x mR + tmp[:, Plcr] = tmp[:, range(mR)] + Tlcr = numpy.dot(tmp, self.Tr[spin][:mR, :]) # mR x N + else: + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) + # Form D matrices + Dlcr = Rlcr.diagonal() + + mR = len(Dlcr[numpy.abs(Dlcr) > thresh]) + + Dinv = 1.0 / Rlcr.diagonal() + Tlcr = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :]) # mR x N + Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] # mR x N + + if center_ix < self.stack.nbins - 1: # there exists left bit + # assume left stack is all diagonal (i.e., QDT = diagonal -> Q and T are identity) + Clcr = numpy.einsum( + "i,ij->ij", + self.Dl[spin], + numpy.einsum("ij,j->ij", Qlcr[:, :mR], Dlcr[:mR]), + ) # N x mR + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr( + Clcr, pivoting=True, check_finite=False + ) # N x N, mR x mR + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Dlcr + + mT = len(Dlcr[numpy.abs(Dlcr) > thresh]) + + tmp = numpy.einsum("i,ij->ij", Dinv[:mT], Rlcr[:mT, :]) + tmp[:, Plcr] = tmp[:, range(mR)] # mT x mR + Tlcr = numpy.dot(tmp, Tlcr) # mT x N + else: + mT = mR + + # D = Ds Db^{-1} + Db = numpy.zeros(mT, Bc[spin].dtype) + Ds = numpy.zeros(mT, Bc[spin].dtype) + for i in range(mT): + absDlcr = abs(Dlcr[i]) + if absDlcr > 1.0: + Db[i] = 1.0 / absDlcr + Ds[i] = numpy.sign(Dlcr[i]) + else: + Db[i] = 1.0 + Ds[i] = Dlcr[i] + + if mT == nbsf: # No need for Woodbury + T1inv = scipy.linalg.inv(Tlcr, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), + numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), + ) + # return # This seems to change the answer WHY?? + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), + numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), + ) + else: # Use Woodbury + TQ = Tlcr.dot(Qlcr[:, :mT]) + TQinv = scipy.linalg.inv(TQ, check_finite=False) + tmp = scipy.linalg.inv( + numpy.einsum("ij,j->ij", TQinv, Db) + numpy.diag(Ds), + check_finite=False, + ) + A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv)) + if inplace: + self.G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( + numpy.diag(Dlcr[:mT]) + ).dot(A).dot(Tlcr) + else: + G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( + numpy.diag(Dlcr[:mT]) + ).dot(A).dot(Tlcr) + # print(mR,mT,nbsf) + # print("ref: mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) + return G + + def greens_function_left_right_no_truncation(self, center_ix, inplace=False): + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + Bc = self.stack.get(center_ix) + for spin in [0, 1]: + if center_ix > 0: # there exists right bit + # print("center_ix > 0 second") + Ccr = numpy.einsum("ij,j->ij", numpy.dot(Bc[spin], self.Qr[spin]), self.Dr[spin]) + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) + tmp[:, Plcr] = tmp[:, range(self.nbasis)] + Tlcr = numpy.dot(tmp, self.Tr[spin]) + else: + # print("center_ix > 0 else second") + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) + # Form D matrices + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + Tlcr = numpy.einsum("i,ij->ij", Dinv, Rlcr) + Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] + + if center_ix < self.stack.nbins - 1: # there exists left bit + # print("center_ix < self.stack.nbins-1 second") + # assume left stack is all diagonal + Clcr = numpy.einsum("i,ij->ij", self.Dl[spin], numpy.einsum("ij,j->ij", Qlcr, Dlcr)) + + (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Clcr, pivoting=True, check_finite=False) + Dlcr = Rlcr.diagonal() + Dinv = 1.0 / Rlcr.diagonal() + + tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) + tmp[:, Plcr] = tmp[:, range(self.nbasis)] + Tlcr = numpy.dot(tmp, Tlcr) + + # print("Dlcr = {}".format(Dlcr)) + + # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T + # Write D = Db^{-1} Ds + # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T + Db = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) + Ds = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) + for i in range(Db.shape[0]): + absDlcr = abs(Dlcr[i]) + if absDlcr > 1.0: + Db[i] = 1.0 / absDlcr + Ds[i] = numpy.sign(Dlcr[i]) + else: + Db[i] = 1.0 + Ds[i] = Dlcr[i] + + T1inv = scipy.linalg.inv(Tlcr, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) + ) + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) + ) + return G + + def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): + # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + if slice_ix == None: + slice_ix = self.stack.time_slice + + bin_ix = slice_ix // self.stack.nstack + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == self.stack.nbins: + bin_ix = -1 + + if not inplace: + G = numpy.zeros(self.G.shape, self.G.dtype) + else: + G = None + + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in + # stable way. Iteratively construct column pivoted QR decompositions + # (A = QDT) starting from the rightmost (product of) propagator(s). + B = self.stack.get((bin_ix + 1) % self.stack.nbins) + + (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) + # Form D matrices + D1 = numpy.diag(R1.diagonal()) + D1inv = numpy.diag(1.0 / R1.diagonal()) + T1 = numpy.einsum("ii,ij->ij", D1inv, R1) + # permute them + T1[:, P1] = T1[:, range(self.nbasis)] + + for i in range(2, self.stack.nbins + 1): + ix = (bin_ix + i) % self.stack.nbins + B = self.stack.get(ix) + C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) + (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = numpy.diag(1.0 / R1.diagonal()) + D1 = numpy.diag(R1.diagonal()) + tmp = numpy.einsum("ii,ij->ij", D1inv, R1) + tmp[:, P1] = tmp[:, range(self.nbasis)] + T1 = numpy.dot(tmp, T1) + + # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T + # Write D = Db^{-1} Ds + # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T + Db = numpy.zeros(B[spin].shape, B[spin].dtype) + Ds = numpy.zeros(B[spin].shape, B[spin].dtype) + for i in range(Db.shape[0]): + absDlcr = abs(Db[i, i]) + if absDlcr > 1.0: + Db[i, i] = 1.0 / absDlcr + Ds[i, i] = numpy.sign(D1[i, i]) + else: + Db[i, i] = 1.0 + Ds[i, i] = D1[i, i] + + T1inv = scipy.linalg.inv(T1, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("ii,ij->ij", Db, Q1.conj().T), T1inv) + Ds + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + self.G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) + ) + else: + G[spin] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) + ) + return G + + # For compatibiltiy with BaseWalkers class. + def reortho(self): + pass + + def reortho_batched(self): + pass From 8658e8f6ff17a2526fda3e5a56a2a599d9c135df Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Mon, 2 Oct 2023 12:02:35 -0400 Subject: [PATCH 29/84] add ueg_kernel --- ipie/estimators/ueg.py | 290 ++++++++++++++++++++++++++++++++ ipie/estimators/ueg_kernels.pyx | 169 +++++++++++++++++++ 2 files changed, 459 insertions(+) create mode 100644 ipie/estimators/ueg.py create mode 100644 ipie/estimators/ueg_kernels.pyx diff --git a/ipie/estimators/ueg.py b/ipie/estimators/ueg.py new file mode 100644 index 00000000..9906fc9d --- /dev/null +++ b/ipie/estimators/ueg.py @@ -0,0 +1,290 @@ + +import numpy + +from ipie.thermal.estimators.ueg_kernels import ( + build_J_opt, + build_K_opt, + coulomb_greens_function_per_qvec, + exchange_greens_function_per_qvec, +) + + +def exchange_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gprod, G): + for iq in range(nq): + for idxkpq, i in zip(kpq[iq], kpq_i[iq]): + for idxpmq, j in zip(pmq[iq], pmq_i[iq]): + Gprod[iq] += G[j, idxkpq] * G[i, idxpmq] + + +def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): + for iq in range(nq): + for idxkpq, i in zip(kpq[iq], kpq_i[iq]): + Gkpq[iq] += G[i, idxkpq] + for idxpmq, i in zip(pmq[iq], pmq_i[iq]): + Gpmq[iq] += G[i, idxpmq] + + +def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): + """Local energy computation for uniform electron gas + Parameters + ---------- + system : + system class + ham : + hamiltonian class + G : + Green's function + Returns + ------- + etot : float + total energy + ke : float + kinetic energy + pe : float + potential energy + """ + if ham.diagH1: + ke = numpy.einsum("sii,sii->", ham.H1, G) + else: + ke = numpy.einsum("sij,sij->", ham.H1, G) + + Gkpq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + Gpmq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + Gprod = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + + ne = [system.nup, system.ndown] + nq = numpy.shape(ham.qvecs)[0] + + for s in [0, 1]: + # exchange_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i,ham.ipmq_pmq, Gprod[s],G[s]) + # coulomb_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i, ham.ipmq_pmq,Gkpq[s], Gpmq[s],G[s]) + for iq in range(nq): + Gkpq[s, iq], Gpmq[s, iq] = coulomb_greens_function_per_qvec( + ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] + ) + Gprod[s, iq] = exchange_greens_function_per_qvec( + ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] + ) + + if two_rdm is None: + two_rdm = numpy.zeros((2, 2, len(ham.qvecs)), dtype=numpy.complex128) + two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] + essa = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 0]) + + two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] + essb = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[1, 1]) + + two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) + two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) + eos = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 1]) + ( + 1.0 / (2.0 * ham.vol) + ) * ham.vqvec.dot(two_rdm[1, 0]) + + pe = essa + essb + eos + + return (ke + pe, ke, pe) + + +# JHLFML +def build_J(system, Gpmq, Gkpq): + J = [ + numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), + numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), + ] + + for iq, q in enumerate(system.qvecs): + for idxi, i in enumerate(system.basis): + for idxj, j in enumerate(system.basis): + jpq = j + q + idxjpq = system.lookup_basis(jpq) + if (idxjpq is not None) and (idxjpq == idxi): + J[0][idxj, idxi] += ( + (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + ) + + for iq, q in enumerate(system.qvecs): + for idxi, i in enumerate(system.basis): + for idxj, j in enumerate(system.basis): + jpq = j - q + idxjmq = system.lookup_basis(jpq) + if (idxjmq is not None) and (idxjmq == idxi): + J[0][idxj, idxi] += ( + (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + ) + + J[1] = J[0] + + return J + + +def build_K(system, G): + K = numpy.zeros((2, system.nbasis, system.nbasis), dtype=numpy.complex128) + for s in [0, 1]: + for iq in range(len(system.vqvec)): + for idxjmq, idxj in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): + for idxkpq, idxk in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): + K[s, idxj, idxkpq] += ( + -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjmq, idxk] + ) + for iq in range(len(system.vqvec)): + for idxjpq, idxj in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): + for idxpmq, idxp in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): + K[s, idxj, idxpmq] += ( + -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjpq, idxp] + ) + return K + + +def fock_ueg(ham, G): + """Fock matrix computation for uniform electron gas + + Parameters + ---------- + ham : :class`ipie.legacy.hamiltonians.ueg` + UEG hamiltonian class. + G : :class:`numpy.ndarray` + Green's function. + Returns + ------- + F : :class:`numpy.ndarray` + Fock matrix (2, nbasis, nbasis). + """ + nbsf = ham.nbasis + nq = len(ham.qvecs) + assert nq == len(ham.vqvec) + + Fock = numpy.zeros((2, nbsf, nbsf), dtype=numpy.complex128) + Gkpq = numpy.zeros((2, nq), dtype=numpy.complex128) + Gpmq = numpy.zeros((2, nq), dtype=numpy.complex128) + + for s in [0, 1]: + coulomb_greens_function( + nq, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + Gkpq[s], + Gpmq[s], + G[s], + ) + + J = build_J_opt( + nq, + ham.vqvec, + ham.vol, + ham.nbasis, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + Gkpq, + Gpmq, + ) + + K = build_K_opt( + nq, + ham.vqvec, + ham.vol, + ham.nbasis, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + G, + ) + + for s in [0, 1]: + Fock[s] = ham.H1[s] + J[s] + K[s] + + return Fock + + +def unit_test(): + import numpy as np + + from ipie.legacy.systems.ueg import UEG + + inputs = {"nup": 7, "ndown": 7, "rs": 1.0, "ecut": 2.0} + system = UEG(inputs, True) + nbsf = system.nbasis + Pa = np.zeros([nbsf, nbsf], dtype=np.complex128) + Pb = np.zeros([nbsf, nbsf], dtype=np.complex128) + na = system.nup + nb = system.ndown + for i in range(na): + Pa[i, i] = 1.0 + for i in range(nb): + Pb[i, i] = 1.0 + P = np.array([Pa, Pb]) + etot, ekin, epot = local_energy_ueg(system, G=P) + print(f"ERHF = {etot}, {ekin}, {epot}") + + from ipie.legacy.estimators.greens_function import gab + from ipie.utils.linalg import exponentiate_matrix, reortho + + # numpy.random.seed() + rCa = numpy.random.randn(nbsf, na) + zCa = numpy.random.randn(nbsf, na) + rCb = numpy.random.randn(nbsf, nb) + zCb = numpy.random.randn(nbsf, nb) + + Ca = rCa + 1j * zCa + Cb = rCb + 1j * zCb + + Ca, detR = reortho(Ca) + Cb, detR = reortho(Cb) + # S = print(Ca.dot(Cb.T)) + # print(S) + # exit() + Ca = numpy.array(Ca, dtype=numpy.complex128) + Cb = numpy.array(Cb, dtype=numpy.complex128) + P = [gab(Ca, Ca), gab(Cb, Cb)] + # diff = P[0] - P[1] + # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) + + # solver = lib.diis.DIIS() + + # dt = 0.1 + # for i in range(100): + # # Compute Fock matrix + # Fock = fock_ueg(system, G=P) + # # Compute DIIS Errvec + # PFmFPa = P[0].dot(Fock[0]) - Fock[0].dot(P[0]) + # PFmFPb = P[1].dot(Fock[1]) - Fock[1].dot(P[1]) + # errvec = numpy.append(numpy.reshape(PFmFPa, nbsf*nbsf),numpy.reshape(PFmFPb, nbsf*nbsf)) + # RMS = np.sqrt(np.dot(errvec, errvec)) + # print ("{} {} {}".format(i,numpy.real(local_energy_ueg(system, P)), numpy.real(RMS))) + # # Form Fockvec + # Fock[0] = numpy.array(Fock[0]) + # Fock[1] = numpy.array(Fock[1]) + # Fockvec = numpy.append(numpy.reshape(Fock[0],nbsf*nbsf), numpy.reshape(Fock[1],nbsf*nbsf)) + # # Extrapolate Fockvec + # # Fockvec = solver.update(Fockvec, xerr=errvec) + + # # Apply Propagator + # Fock = numpy.reshape(Fockvec, (2, nbsf, nbsf)) + # ea, Ca = numpy.linalg.eig(Fock[0]) + # eb, Cb = numpy.linalg.eig(Fock[1]) + # sort_perm = ea.argsort() + # ea.sort() + # Ca = Ca[:, sort_perm] + # sort_perm = eb.argsort() + # eb.sort() + # Cb = Cb[:, sort_perm] + + # Ca = Ca[:,:na] + # Cb = Cb[:,:nb] + # Ca, detR = reortho(Ca) + # Cb, detR = reortho(Cb) + + # P = [gab(Ca, Ca), gab(Cb, Cb)] + # # expF = [exponentiate_matrix(-dt*Fock[0]), exponentiate_matrix(-dt*Fock[1])] + # # Ca = expF[0].dot(Ca) + # # Cb = expF[1].dot(Cb) + # # diff = P[0] - P[1] + # # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) + + +if __name__ == "__main__": + unit_test() diff --git a/ipie/estimators/ueg_kernels.pyx b/ipie/estimators/ueg_kernels.pyx new file mode 100644 index 00000000..9c7a25de --- /dev/null +++ b/ipie/estimators/ueg_kernels.pyx @@ -0,0 +1,169 @@ +import numpy + +cimport numpy + +import itertools +import math + +from ipie.thermal.estimators.utils import convolve + +DTYPE_CX = numpy.complex128 +DTYPE = numpy.float64 + + +def vq(numpy.ndarray q): + assert(q.shape[0] == 3) + cdef double q2 = numpy.dot(q, q) + if (q2 < 1e-10): + return 0.0 + else: + return 4*math.pi / q2 + +def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): + """ Add a diagonal term of two-body Hamiltonian to the one-body term + Parameters + ---------- + T : float + one-body Hamiltonian (i.e. kinetic energy) + Returns + ------- + h1e_mod: float + modified one-body Hamiltonian + """ + + cdef size_t nbsf = basis.shape[0] + cdef numpy.ndarray h1e_mod = T.copy() + cdef double fac = 1.0 / (2.0 * vol) + + for (i, ki) in enumerate(basis): + for (j, kj) in enumerate(basis): + if i != j: + q = kfac * (ki - kj) + h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) + return h1e_mod + +def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): + + cdef int nq = kpq_i.shape[0] + + cdef int idxkpq, idxpmq, i, j, iq + + cdef double complex Gkpq = 0.0 + cdef double complex Gpmq = 0.0 + + for (idxkpq,i) in zip(kpq,kpq_i): + Gkpq += G[i,idxkpq] + for (idxpmq,i) in zip(pmq,pmq_i): + Gpmq += G[i,idxpmq] + + return Gkpq, Gpmq + +def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): + + cdef int nkpq = kpq_i.shape[0] + cdef int npmq = pmq_i.shape[0] + + cdef double complex Gprod = 0.0 + + cdef int idxkpq, idxpmq, i, j + + for inkpq in range(nkpq): + idxkpq = kpq[inkpq] + i = kpq_i[inkpq] + for jnpmq in range(npmq): + idxpmq = pmq[jnpmq] + j = pmq_i[jnpmq] + Gprod += G[j,idxkpq]*G[i,idxpmq] + + return Gprod + +def exchange_greens_function_fft (long nocc, long nbsf, + long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, + double complex[:,:] CTdagger, double complex[:,:] Ghalf): + + assert (mesh.shape[0] == 3) + assert (qmesh.shape[0] == 3) + assert (Ghalf.shape[0] == nocc) + assert (Ghalf.shape[1] == nbsf) + assert (CTdagger.shape[0] == nocc) + assert (CTdagger.shape[1] == nbsf) + + cdef long ngrid = numpy.prod(mesh) + cdef long nqgrid = numpy.prod(qmesh) + + cdef long nq = qmap.shape[0] + cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) + + cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) + cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) + + for i in range(nocc): + for j in range(nocc): + Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) + CTdagger_j = numpy.asarray(CTdagger[j,:]) + + Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + Gh_i_cube[gmap] = Gh_i + CTdagger_j_cube[gmap] = CTdagger_j + + lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] + + Gh_j = numpy.asarray(Ghalf[j,:]) + CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) + + Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + Gh_j_cube[gmap] = Gh_j + CTdagger_i_cube[gmap] = CTdagger_i + + lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] + + Gprod += lQ_ji*lQ_ij + + return Gprod + +def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, + list kpq, list pmq_i, list pmq, + double complex[:,:] Gkpq, double complex[:,:] Gpmq): + + cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) + cdef int i, j + for iq in range(nq): + for i, j in zip(pmq_i[iq], pmq[iq]): + J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + for i, j in zip(kpq_i[iq], kpq[iq]): + J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + + J[1] = J[0] + + return J + +def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, + list kpq, list pmq_i, list pmq, + double complex[:,:,:] G): + + cdef numpy.ndarray K = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) + cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp + + for s in range(2): + for iq in range(nq): + for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): + for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): + K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] + return K From b5f7a94751fdd05f94c7f3cb0f0bfeb5a6685bef Mon Sep 17 00:00:00 2001 From: Joonho Lee Date: Mon, 2 Oct 2023 12:07:57 -0400 Subject: [PATCH 30/84] changes to thermal walker cleaning up --- ipie/estimators/ueg.py | 290 ------------------ ipie/estimators/ueg_kernels.pyx | 169 ---------- ipie/thermal/estimators/ueg.py | 7 +- ipie/thermal/walkers/stack.py | 7 +- .../walkers/tests/test_thermal_walkers.py | 31 +- ipie/thermal/walkers/uhf_walkers.py | 98 +++--- ipie/thermal/walkers/uhf_walkers2.py | 2 - 7 files changed, 97 insertions(+), 507 deletions(-) delete mode 100644 ipie/estimators/ueg.py delete mode 100644 ipie/estimators/ueg_kernels.pyx diff --git a/ipie/estimators/ueg.py b/ipie/estimators/ueg.py deleted file mode 100644 index 9906fc9d..00000000 --- a/ipie/estimators/ueg.py +++ /dev/null @@ -1,290 +0,0 @@ - -import numpy - -from ipie.thermal.estimators.ueg_kernels import ( - build_J_opt, - build_K_opt, - coulomb_greens_function_per_qvec, - exchange_greens_function_per_qvec, -) - - -def exchange_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gprod, G): - for iq in range(nq): - for idxkpq, i in zip(kpq[iq], kpq_i[iq]): - for idxpmq, j in zip(pmq[iq], pmq_i[iq]): - Gprod[iq] += G[j, idxkpq] * G[i, idxpmq] - - -def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): - for iq in range(nq): - for idxkpq, i in zip(kpq[iq], kpq_i[iq]): - Gkpq[iq] += G[i, idxkpq] - for idxpmq, i in zip(pmq[iq], pmq_i[iq]): - Gpmq[iq] += G[i, idxpmq] - - -def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): - """Local energy computation for uniform electron gas - Parameters - ---------- - system : - system class - ham : - hamiltonian class - G : - Green's function - Returns - ------- - etot : float - total energy - ke : float - kinetic energy - pe : float - potential energy - """ - if ham.diagH1: - ke = numpy.einsum("sii,sii->", ham.H1, G) - else: - ke = numpy.einsum("sij,sij->", ham.H1, G) - - Gkpq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - Gpmq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - Gprod = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - - ne = [system.nup, system.ndown] - nq = numpy.shape(ham.qvecs)[0] - - for s in [0, 1]: - # exchange_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i,ham.ipmq_pmq, Gprod[s],G[s]) - # coulomb_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i, ham.ipmq_pmq,Gkpq[s], Gpmq[s],G[s]) - for iq in range(nq): - Gkpq[s, iq], Gpmq[s, iq] = coulomb_greens_function_per_qvec( - ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] - ) - Gprod[s, iq] = exchange_greens_function_per_qvec( - ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] - ) - - if two_rdm is None: - two_rdm = numpy.zeros((2, 2, len(ham.qvecs)), dtype=numpy.complex128) - two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] - essa = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 0]) - - two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] - essb = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[1, 1]) - - two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) - two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) - eos = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 1]) + ( - 1.0 / (2.0 * ham.vol) - ) * ham.vqvec.dot(two_rdm[1, 0]) - - pe = essa + essb + eos - - return (ke + pe, ke, pe) - - -# JHLFML -def build_J(system, Gpmq, Gkpq): - J = [ - numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), - numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), - ] - - for iq, q in enumerate(system.qvecs): - for idxi, i in enumerate(system.basis): - for idxj, j in enumerate(system.basis): - jpq = j + q - idxjpq = system.lookup_basis(jpq) - if (idxjpq is not None) and (idxjpq == idxi): - J[0][idxj, idxi] += ( - (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - ) - - for iq, q in enumerate(system.qvecs): - for idxi, i in enumerate(system.basis): - for idxj, j in enumerate(system.basis): - jpq = j - q - idxjmq = system.lookup_basis(jpq) - if (idxjmq is not None) and (idxjmq == idxi): - J[0][idxj, idxi] += ( - (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - ) - - J[1] = J[0] - - return J - - -def build_K(system, G): - K = numpy.zeros((2, system.nbasis, system.nbasis), dtype=numpy.complex128) - for s in [0, 1]: - for iq in range(len(system.vqvec)): - for idxjmq, idxj in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): - for idxkpq, idxk in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): - K[s, idxj, idxkpq] += ( - -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjmq, idxk] - ) - for iq in range(len(system.vqvec)): - for idxjpq, idxj in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): - for idxpmq, idxp in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): - K[s, idxj, idxpmq] += ( - -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjpq, idxp] - ) - return K - - -def fock_ueg(ham, G): - """Fock matrix computation for uniform electron gas - - Parameters - ---------- - ham : :class`ipie.legacy.hamiltonians.ueg` - UEG hamiltonian class. - G : :class:`numpy.ndarray` - Green's function. - Returns - ------- - F : :class:`numpy.ndarray` - Fock matrix (2, nbasis, nbasis). - """ - nbsf = ham.nbasis - nq = len(ham.qvecs) - assert nq == len(ham.vqvec) - - Fock = numpy.zeros((2, nbsf, nbsf), dtype=numpy.complex128) - Gkpq = numpy.zeros((2, nq), dtype=numpy.complex128) - Gpmq = numpy.zeros((2, nq), dtype=numpy.complex128) - - for s in [0, 1]: - coulomb_greens_function( - nq, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - Gkpq[s], - Gpmq[s], - G[s], - ) - - J = build_J_opt( - nq, - ham.vqvec, - ham.vol, - ham.nbasis, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - Gkpq, - Gpmq, - ) - - K = build_K_opt( - nq, - ham.vqvec, - ham.vol, - ham.nbasis, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - G, - ) - - for s in [0, 1]: - Fock[s] = ham.H1[s] + J[s] + K[s] - - return Fock - - -def unit_test(): - import numpy as np - - from ipie.legacy.systems.ueg import UEG - - inputs = {"nup": 7, "ndown": 7, "rs": 1.0, "ecut": 2.0} - system = UEG(inputs, True) - nbsf = system.nbasis - Pa = np.zeros([nbsf, nbsf], dtype=np.complex128) - Pb = np.zeros([nbsf, nbsf], dtype=np.complex128) - na = system.nup - nb = system.ndown - for i in range(na): - Pa[i, i] = 1.0 - for i in range(nb): - Pb[i, i] = 1.0 - P = np.array([Pa, Pb]) - etot, ekin, epot = local_energy_ueg(system, G=P) - print(f"ERHF = {etot}, {ekin}, {epot}") - - from ipie.legacy.estimators.greens_function import gab - from ipie.utils.linalg import exponentiate_matrix, reortho - - # numpy.random.seed() - rCa = numpy.random.randn(nbsf, na) - zCa = numpy.random.randn(nbsf, na) - rCb = numpy.random.randn(nbsf, nb) - zCb = numpy.random.randn(nbsf, nb) - - Ca = rCa + 1j * zCa - Cb = rCb + 1j * zCb - - Ca, detR = reortho(Ca) - Cb, detR = reortho(Cb) - # S = print(Ca.dot(Cb.T)) - # print(S) - # exit() - Ca = numpy.array(Ca, dtype=numpy.complex128) - Cb = numpy.array(Cb, dtype=numpy.complex128) - P = [gab(Ca, Ca), gab(Cb, Cb)] - # diff = P[0] - P[1] - # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) - - # solver = lib.diis.DIIS() - - # dt = 0.1 - # for i in range(100): - # # Compute Fock matrix - # Fock = fock_ueg(system, G=P) - # # Compute DIIS Errvec - # PFmFPa = P[0].dot(Fock[0]) - Fock[0].dot(P[0]) - # PFmFPb = P[1].dot(Fock[1]) - Fock[1].dot(P[1]) - # errvec = numpy.append(numpy.reshape(PFmFPa, nbsf*nbsf),numpy.reshape(PFmFPb, nbsf*nbsf)) - # RMS = np.sqrt(np.dot(errvec, errvec)) - # print ("{} {} {}".format(i,numpy.real(local_energy_ueg(system, P)), numpy.real(RMS))) - # # Form Fockvec - # Fock[0] = numpy.array(Fock[0]) - # Fock[1] = numpy.array(Fock[1]) - # Fockvec = numpy.append(numpy.reshape(Fock[0],nbsf*nbsf), numpy.reshape(Fock[1],nbsf*nbsf)) - # # Extrapolate Fockvec - # # Fockvec = solver.update(Fockvec, xerr=errvec) - - # # Apply Propagator - # Fock = numpy.reshape(Fockvec, (2, nbsf, nbsf)) - # ea, Ca = numpy.linalg.eig(Fock[0]) - # eb, Cb = numpy.linalg.eig(Fock[1]) - # sort_perm = ea.argsort() - # ea.sort() - # Ca = Ca[:, sort_perm] - # sort_perm = eb.argsort() - # eb.sort() - # Cb = Cb[:, sort_perm] - - # Ca = Ca[:,:na] - # Cb = Cb[:,:nb] - # Ca, detR = reortho(Ca) - # Cb, detR = reortho(Cb) - - # P = [gab(Ca, Ca), gab(Cb, Cb)] - # # expF = [exponentiate_matrix(-dt*Fock[0]), exponentiate_matrix(-dt*Fock[1])] - # # Ca = expF[0].dot(Ca) - # # Cb = expF[1].dot(Cb) - # # diff = P[0] - P[1] - # # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) - - -if __name__ == "__main__": - unit_test() diff --git a/ipie/estimators/ueg_kernels.pyx b/ipie/estimators/ueg_kernels.pyx deleted file mode 100644 index 9c7a25de..00000000 --- a/ipie/estimators/ueg_kernels.pyx +++ /dev/null @@ -1,169 +0,0 @@ -import numpy - -cimport numpy - -import itertools -import math - -from ipie.thermal.estimators.utils import convolve - -DTYPE_CX = numpy.complex128 -DTYPE = numpy.float64 - - -def vq(numpy.ndarray q): - assert(q.shape[0] == 3) - cdef double q2 = numpy.dot(q, q) - if (q2 < 1e-10): - return 0.0 - else: - return 4*math.pi / q2 - -def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): - """ Add a diagonal term of two-body Hamiltonian to the one-body term - Parameters - ---------- - T : float - one-body Hamiltonian (i.e. kinetic energy) - Returns - ------- - h1e_mod: float - modified one-body Hamiltonian - """ - - cdef size_t nbsf = basis.shape[0] - cdef numpy.ndarray h1e_mod = T.copy() - cdef double fac = 1.0 / (2.0 * vol) - - for (i, ki) in enumerate(basis): - for (j, kj) in enumerate(basis): - if i != j: - q = kfac * (ki - kj) - h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) - return h1e_mod - -def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): - - cdef int nq = kpq_i.shape[0] - - cdef int idxkpq, idxpmq, i, j, iq - - cdef double complex Gkpq = 0.0 - cdef double complex Gpmq = 0.0 - - for (idxkpq,i) in zip(kpq,kpq_i): - Gkpq += G[i,idxkpq] - for (idxpmq,i) in zip(pmq,pmq_i): - Gpmq += G[i,idxpmq] - - return Gkpq, Gpmq - -def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): - - cdef int nkpq = kpq_i.shape[0] - cdef int npmq = pmq_i.shape[0] - - cdef double complex Gprod = 0.0 - - cdef int idxkpq, idxpmq, i, j - - for inkpq in range(nkpq): - idxkpq = kpq[inkpq] - i = kpq_i[inkpq] - for jnpmq in range(npmq): - idxpmq = pmq[jnpmq] - j = pmq_i[jnpmq] - Gprod += G[j,idxkpq]*G[i,idxpmq] - - return Gprod - -def exchange_greens_function_fft (long nocc, long nbsf, - long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, - double complex[:,:] CTdagger, double complex[:,:] Ghalf): - - assert (mesh.shape[0] == 3) - assert (qmesh.shape[0] == 3) - assert (Ghalf.shape[0] == nocc) - assert (Ghalf.shape[1] == nbsf) - assert (CTdagger.shape[0] == nocc) - assert (CTdagger.shape[1] == nbsf) - - cdef long ngrid = numpy.prod(mesh) - cdef long nqgrid = numpy.prod(qmesh) - - cdef long nq = qmap.shape[0] - cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) - - cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) - cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) - - for i in range(nocc): - for j in range(nocc): - Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) - CTdagger_j = numpy.asarray(CTdagger[j,:]) - - Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - Gh_i_cube[gmap] = Gh_i - CTdagger_j_cube[gmap] = CTdagger_j - - lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] - - Gh_j = numpy.asarray(Ghalf[j,:]) - CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) - - Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - Gh_j_cube[gmap] = Gh_j - CTdagger_i_cube[gmap] = CTdagger_i - - lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] - - Gprod += lQ_ji*lQ_ij - - return Gprod - -def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, - list kpq, list pmq_i, list pmq, - double complex[:,:] Gkpq, double complex[:,:] Gpmq): - - cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) - cdef int i, j - for iq in range(nq): - for i, j in zip(pmq_i[iq], pmq[iq]): - J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - for i, j in zip(kpq_i[iq], kpq[iq]): - J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - - J[1] = J[0] - - return J - -def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, - list kpq, list pmq_i, list pmq, - double complex[:,:,:] G): - - cdef numpy.ndarray K = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) - cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp - - for s in range(2): - for iq in range(nq): - for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): - for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): - K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] - return K diff --git a/ipie/thermal/estimators/ueg.py b/ipie/thermal/estimators/ueg.py index 802c5e05..9906fc9d 100644 --- a/ipie/thermal/estimators/ueg.py +++ b/ipie/thermal/estimators/ueg.py @@ -24,10 +24,12 @@ def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): Gpmq[iq] += G[i, idxpmq] -def local_energy_ueg(ham, G, Ghalf=None, two_rdm=None): +def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): """Local energy computation for uniform electron gas Parameters ---------- + system : + system class ham : hamiltonian class G : @@ -49,6 +51,8 @@ def local_energy_ueg(ham, G, Ghalf=None, two_rdm=None): Gkpq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) Gpmq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) Gprod = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + + ne = [system.nup, system.ndown] nq = numpy.shape(ham.qvecs)[0] for s in [0, 1]: @@ -77,6 +81,7 @@ def local_energy_ueg(ham, G, Ghalf=None, two_rdm=None): ) * ham.vqvec.dot(two_rdm[1, 0]) pe = essa + essb + eos + return (ke + pe, ke, pe) diff --git a/ipie/thermal/walkers/stack.py b/ipie/thermal/walkers/stack.py index 4c318430..8481ef29 100644 --- a/ipie/thermal/walkers/stack.py +++ b/ipie/thermal/walkers/stack.py @@ -46,8 +46,11 @@ def __init__( self.left = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) self.right = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) - self.G = numpy.asarray( - [numpy.eye(self.nbasis, dtype=dtype), numpy.eye(self.nbasis, dtype=dtype)] + self.Ga = numpy.asarray( + numpy.eye(self.nbasis, dtype=dtype) + ) + self.Gb = numpy.asarray( + numpy.eye(self.nbasis, dtype=dtype) ) if self.lowrank: diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py index 80dfd213..0dbfdcb6 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -6,6 +6,14 @@ from ipie.thermal.trial.one_body import OneBody from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.thermal import ThermalWalker + +try: + from ipie.thermal.estimators.ueg import local_energy_ueg +except ImportError as e: + print(e) @pytest.mark.unit def test_thermal_walkers(): @@ -16,18 +24,35 @@ def test_thermal_walkers(): nelec = (nup, ndown) options = {"rs": rs, "nup": nup, "ndown": ndown, "ecut": ecut, "write_integrals": False} + nwalkers = 5 + system = UEG(options=options) hamiltonian = HamUEG(system, options=options) + + legacy_hamiltonian = LegacyHamUEG(system, options=options) + beta = 1 dt = 0.05 verbose = True trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) - - nwalkers = 10 nbasis = trial.dmat.shape[-1] - walkers = [UHFThermalWalkers(trial, nup, ndown, nbasis, nwalkers, verbose=i == 0) for i in range(nwalkers)] + legacy_trial = LegacyOneBody(system, hamiltonian, beta, 0.05) + legacy_walkers = [ThermalWalker(system, legacy_hamiltonian, legacy_trial, verbose=i == 0) for i in range(nwalkers)] + + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, verbose=1) + + for iw in range(nwalkers): + legacy_eloc = local_energy_ueg(system,hamiltonian, legacy_walkers[iw].G) + eloc = local_energy_ueg(system,hamiltonian, numpy.array([walkers.Ga[iw],walkers.Gb[iw]])) + print(eloc) + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + + numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) if __name__ == "__main__": test_thermal_walkers() diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index fcd89943..8b9cd0cf 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -11,8 +11,6 @@ class UHFThermalWalkers(BaseWalkers): def __init__( self, trial: OneBody, - nup: int, - ndown: int, nbasis: int, nwalkers: int, nstack = None, @@ -24,8 +22,8 @@ def __init__( """UHF style walker. """ assert isinstance(trial, OneBody) - self.nup = nup - self.ndown = ndown + super().__init__(nwalkers, verbose=verbose) + self.nbasis = nbasis self.mpi_handler = mpi_handler self.nslice = trial.nslice @@ -48,10 +46,15 @@ def __init__( self.lowrank = lowrank self.lowrank_thresh = lowrank_thresh - super().__init__(nwalkers, verbose=verbose) - - self.G = numpy.zeros(trial.dmat.shape, dtype=numpy.complex128) + self.Ga = numpy.zeros( + shape=(self.nwalkers, self.nbasis, self.nbasis), + dtype=numpy.complex128) + self.Gb = numpy.zeros( + shape=(self.nwalkers, self.nbasis, self.nbasis), + dtype=numpy.complex128) + self.Ghalf = None + max_diff_diag = numpy.linalg.norm( (numpy.diag( trial.dmat[0].diagonal()) - trial.dmat[0])) @@ -69,7 +72,7 @@ def __init__( print(f"# Walker stack size: {self.nstack}") print(f"# Using low rank trick: {self.lowrank}") - self.stack = PropagatorStack( + self.stack = [PropagatorStack( self.nstack, self.nslice, self.nbasis, @@ -79,35 +82,45 @@ def __init__( diagonal=self.diagonal_trial, lowrank=self.lowrank, thresh=self.lowrank_thresh, - ) + ) for iw in range(self.nwalkers)] # Initialise all propagators to the trial density matrix. - self.stack.set_all(trial.dmat) - self.greens_function_qr_strat(trial) - self.stack.G = self.G - self.M0 = numpy.array( + for iw in range(self.nwalkers): + self.stack[iw].set_all(trial.dmat) + self.greens_function_qr_strat(iw) + self.stack[iw].Ga = self.Ga[iw] + self.stack[iw].Gb = self.Gb[iw] + self.M0a = numpy.array( [ - scipy.linalg.det(self.G[0], check_finite=False), - scipy.linalg.det(self.G[1], check_finite=False), + scipy.linalg.det(self.Ga[iw], check_finite=False) for iw in range(self.nwalkers) ] ) - self.stack.ovlp = numpy.array([1.0 / self.M0[0], 1.0 / self.M0[1]]) - - # Temporary storage for stacks... - I = numpy.identity(self.nbasis, dtype=numpy.complex128) - One = numpy.ones(self.nbasis, dtype=numpy.complex128) - self.Tl = numpy.array([I, I]) - self.Ql = numpy.array([I, I]) - self.Dl = numpy.array([One, One]) - self.Tr = numpy.array([I, I]) - self.Qr = numpy.array([I, I]) - self.Dr = numpy.array([One, One]) + self.M0b = numpy.array( + [ + scipy.linalg.det(self.Gb[iw], check_finite=False) for iw in range(self.nwalkers) + ] + ) + for iw in range(self.nwalkers): + self.stack[iw].ovlp = numpy.array([1.0 / self.M0a[iw], 1.0 / self.M0b[iw]]) + + # # Temporary storage for stacks... + # We should kill these here and store them in stack (10/02/2023) + # I = numpy.identity(self.nbasis, dtype=numpy.complex128) + # One = numpy.ones(self.nbasis, dtype=numpy.complex128) + # self.Tl = numpy.array([I, I]) + # self.Ql = numpy.array([I, I]) + # self.Dl = numpy.array([One, One]) + # self.Tr = numpy.array([I, I]) + # self.Qr = numpy.array([I, I]) + # self.Dr = numpy.array([One, One]) self.hybrid_energy = 0.0 if verbose: - P = one_rdm_from_G(self.G) - nav = particle_number(P) - print(f"# Trial electron number: {nav}") + for iw in range(self.nwalkers): + G = numpy.array([self.Ga[iw],self.Gb[iw]]) + P = one_rdm_from_G(G) + nav = particle_number(P) + print(f"# Trial electron number for {iw}-th walker: {nav}") self.buff_names, self.buff_size = get_numeric_names(self.__dict__) @@ -500,15 +513,15 @@ def greens_function_left_right_no_truncation(self, center_ix, inplace=False): ) return G - def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): + def greens_function_qr_strat(self, iw, slice_ix=None, inplace=True): # Use Stratification method (DOI 10.1109/IPDPS.2012.37) if slice_ix == None: - slice_ix = self.stack.time_slice + slice_ix = self.stack[iw].time_slice - bin_ix = slice_ix // self.stack.nstack + bin_ix = slice_ix // self.stack[iw].nstack # For final time slice want first block to be the rightmost (for energy # evaluation). - if bin_ix == self.stack.nbins: + if bin_ix == self.stack[iw].nbins: bin_ix = -1 if not inplace: @@ -520,7 +533,7 @@ def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in # stable way. Iteratively construct column pivoted QR decompositions # (A = QDT) starting from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) + B = self.stack[iw].get((bin_ix + 1) % self.stack[iw].nbins) (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) # Form D matrices @@ -530,9 +543,9 @@ def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): # permute them T1[:, P1] = T1[:, range(self.nbasis)] - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) + for i in range(2, self.stack[iw].nbins + 1): + ix = (bin_ix + i) % self.stack[iw].nbins + B = self.stack[iw].get(ix) C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) # Compute D matrices @@ -564,9 +577,14 @@ def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): # Then G = T^{-1} C^{-1} Db Q^{-1} # Q is unitary. if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) - ) + if spin == 0: + self.Ga[iw] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) + ) + else: + self.Gb[iw] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) + ) else: G[spin] = numpy.dot( numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) diff --git a/ipie/thermal/walkers/uhf_walkers2.py b/ipie/thermal/walkers/uhf_walkers2.py index 476c247a..1541de35 100644 --- a/ipie/thermal/walkers/uhf_walkers2.py +++ b/ipie/thermal/walkers/uhf_walkers2.py @@ -53,11 +53,9 @@ def __init__( self.Ga = numpy.zeros( shape=(self.nwalkers, self.nbasis, self.nbasis), dtype=numpy.complex128) - ) self.Gb = numpy.zeros( shape=(self.nwalkers, self.nbasis, self.nbasis), dtype=numpy.complex128) - ) self.Ghalf = None max_diff_diag = numpy.linalg.norm( (numpy.diag( From c840484ffe00dff495aa9687eb8a437a0527b87d Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 18 Oct 2023 11:07:53 -0400 Subject: [PATCH 31/84] Clean `thermal/propagator` to reflect the structure of 0T code. Test runs but incorrect numbers. --- ipie/hamiltonians/generic.py | 2 +- .../trial_density_matrices/mean_field.py | 20 +- ipie/thermal/propagation/force_bias.py | 28 + ipie/thermal/propagation/generic.py | 2 +- ipie/thermal/propagation/operations.py | 30 + ipie/thermal/propagation/phaseless_base.py | 191 ++++++ ipie/thermal/propagation/phaseless_generic.py | 28 + .../thermal/propagation/tests/test_generic.py | 188 ++++++ ipie/thermal/trial/mean_field.py | 2 +- ipie/thermal/trial/utils.py | 2 +- ipie/thermal/walkers/stack.py | 18 +- .../walkers/tests/test_thermal_walkers.py | 61 +- ipie/thermal/walkers/uhf_walkers.py | 462 ++------------ ipie/thermal/walkers/uhf_walkers2.py | 591 ------------------ 14 files changed, 568 insertions(+), 1057 deletions(-) create mode 100644 ipie/thermal/propagation/force_bias.py create mode 100644 ipie/thermal/propagation/operations.py create mode 100644 ipie/thermal/propagation/phaseless_base.py create mode 100644 ipie/thermal/propagation/phaseless_generic.py create mode 100644 ipie/thermal/propagation/tests/test_generic.py delete mode 100644 ipie/thermal/walkers/uhf_walkers2.py diff --git a/ipie/hamiltonians/generic.py b/ipie/hamiltonians/generic.py index 95466dd0..03ced908 100644 --- a/ipie/hamiltonians/generic.py +++ b/ipie/hamiltonians/generic.py @@ -102,7 +102,7 @@ def __init__(self, h1e, chol, ecore=0.0, verbose=False): self.chol = numpy.array(chol, dtype=numpy.complex128) # [M^2, nchol] self.nchol = self.chol.shape[-1] - self.nfields = self.nchol * 2 + self.nfields = 2 * self.nchol assert self.nbasis**2 == chol.shape[0] self.chunked = False diff --git a/ipie/legacy/trial_density_matrices/mean_field.py b/ipie/legacy/trial_density_matrices/mean_field.py index 46c01bb4..233912cf 100644 --- a/ipie/legacy/trial_density_matrices/mean_field.py +++ b/ipie/legacy/trial_density_matrices/mean_field.py @@ -96,16 +96,16 @@ def scf(self, system, beta, mu, P): change = numpy.linalg.norm(Pnew - Pold) if change < self.deps: break - if self.verbose: - N = particle_number(P).real - E = local_energy(system, P)[0].real - S = entropy(beta, mu, HMF) - omega = E - mu * N - 1.0 / beta * S - print( - " # Iteration: {:4d} dP: {:13.8e} Omega: {:13.8e}".format( - it, change, omega.real - ) - ) + #if self.verbose: + # N = particle_number(P).real + # E = local_energy(system, P)[0].real + # S = entropy(beta, mu, HMF) + # omega = E - mu * N - 1.0 / beta * S + # print( + # " # Iteration: {:4d} dP: {:13.8e} Omega: {:13.8e}".format( + # it, change, omega.real + # ) + # ) Pold = Pnew.copy() if self.verbose: N = particle_number(P).real diff --git a/ipie/thermal/propagation/force_bias.py b/ipie/thermal/propagation/force_bias.py new file mode 100644 index 00000000..cb4a86f4 --- /dev/null +++ b/ipie/thermal/propagation/force_bias.py @@ -0,0 +1,28 @@ +import numpy + +from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.utils.backend import arraylib as xp +from ipie.utils.backend import synchronize + +def construct_force_bias(hamiltonian, walkers): + r"""Compute optimal force bias. + + Parameters + ---------- + G: :class:`numpy.ndarray` + Walker's 1RDM: . + + Returns + ------- + xbar : :class:`numpy.ndarray` + Force bias. + """ + vbias = xp.empty((walkers.nwalkers, hamiltonian.nchol), dtype=walkers.Ga.dtype) + + for iw in range(walkers.nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + vbias[iw] = hamiltonian.chol.T.dot(P[0].ravel()) + vbias[iw] += hamiltonian.chol.T.dot(P[1].ravel()) + + return vbias + diff --git a/ipie/thermal/propagation/generic.py b/ipie/thermal/propagation/generic.py index 5310bedb..d2fd0efe 100644 --- a/ipie/thermal/propagation/generic.py +++ b/ipie/thermal/propagation/generic.py @@ -2,7 +2,7 @@ import numpy import scipy.sparse.linalg -from ipie.legacy.estimators.thermal import one_rdm_from_G +from ipie.thermal.estimators.thermal import one_rdm_from_G diff --git a/ipie/thermal/propagation/operations.py b/ipie/thermal/propagation/operations.py new file mode 100644 index 00000000..3b13c8c0 --- /dev/null +++ b/ipie/thermal/propagation/operations.py @@ -0,0 +1,30 @@ +from ipie.config import config +from ipie.utils.backend import arraylib as xp +from ipie.utils.backend import synchronize +from ipie.utils.misc import is_cupy + +def apply_exponential(VHS, exp_nmax): + """Apply exponential propagator of the HS transformation + + Parameters + ---------- + phi : numpy array + a state + VHS : numpy array + HS transformation potential + + Returns + ------- + phi : numpy array + Exp(VHS) * phi + """ + # Temporary array for matrix exponentiation. + phi = xp.identity(VHS.shape[-1], dtype=xp.complex128) + Temp = xp.zeros(phi.shape, dtype=phi.dtype) + xp.copyto(Temp, phi) + + for n in range(1, exp_nmax + 1): + Temp = VHS.dot(Temp) / n + phi += Temp + + return phi # Shape (nbasis, nbasis). diff --git a/ipie/thermal/propagation/phaseless_base.py b/ipie/thermal/propagation/phaseless_base.py new file mode 100644 index 00000000..55d39d9e --- /dev/null +++ b/ipie/thermal/propagation/phaseless_base.py @@ -0,0 +1,191 @@ +import time +import numpy +import scipy.linalg + +from abc import abstractmethod +from ipie.propagation.continuous_base import ContinuousBase +from ipie.thermal.propagation.force_bias import construct_force_bias +from ipie.thermal.propagation.operations import apply_exponential +from ipie.utils.backend import arraylib as xp +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol + +# TODO write test for propagator. + +def construct_mean_field_shift(hamiltonian, trial): + r"""Compute mean field shift. + + .. math:: + + \bar{v}_n = \sum_{ik\sigma} v_{(ik),n} G_{ik\sigma} + + """ + # hamiltonian.chol has shape (nbasis^2, nchol). + P = (trial.P[0] + trial.P[1]).ravel() + tmp_real = numpy.dot(hamiltonian.chol.T, P.real) + tmp_imag = numpy.dot(hamiltonian.chol.T, P.imag) + mf_shift = 1.0j * tmp_real - tmp_imag + return mf_shift # Shape (nchol,). + + +class PhaselessBase(ContinuousBase): + """A base class for generic continuous HS transform FT-AFQMC propagators.""" + + def __init__(self, time_step, mu, lowrank=False, verbose=False): + super().__init__(time_step, verbose=verbose) + self.mu = mu + self.sqrt_dt = self.dt**0.5 + self.isqrt_dt = 1j * self.sqrt_dt + + self.nfb_trig = 0 # number of force bias triggered + self.ebound = (2.0 / self.dt) ** 0.5 # energy bound range + self.mpi_handler = None + self.lowrank = lowrank + + + def build(self, hamiltonian, trial=None, walkers=None, mpi_handler=None, verbose=False): + # dt/2 one-body propagator + start = time.time() + self.mf_shift = construct_mean_field_shift(hamiltonian, trial) + + if verbose: + print(f"# Time to mean field shift: {time.time() - start} s") + print( + "# Absolute value of maximum component of mean field shift: " + "{:13.8e}.".format(numpy.max(numpy.abs(self.mf_shift))) + ) + + # Construct one-body propagator + self.BH1 = self.construct_one_body_propagator(hamiltonian) + + # Allocate force bias (we don't need to do this here - it will be allocated when it is needed) + self.vbias = None + + + def construct_one_body_propagator(self, hamiltonian): + r"""Construct mean-field shifted one-body propagator. + + .. math:: + + H1 \rightarrow H1 - v0 + v0_{ik} = \sum_n v_{(ik),n} \bar{v}_n + + Parameters + ---------- + hamiltonian : hamiltonian class. + Generic hamiltonian object. + dt : float + Timestep. + """ + nb = hamiltonian.nbasis + shift = 1j * numpy.einsum("mx,x->m", hamiltonian.chol, self.mf_shift).reshape(nb, nb) + muN = self.mu * numpy.identity(nb, dtype=hamiltonian.H1.dtype) + H1 = hamiltonian.h1e_mod - numpy.array([shift + muN, shift + muN]) + expH1 = numpy.array([ + scipy.linalg.expm(-0.5 * self.dt * H1[0]), + scipy.linalg.expm(-0.5 * self.dt * H1[1])]) + return expH1 # Shape (nbasis, nbasis). + + + def construct_two_body_propagator(self, walkers, hamiltonian, trial): + """Includes `nwalkers`. + """ + # Optimal force bias + xbar = xp.zeros((walkers.nwalkers, hamiltonian.nfields)) + start_time = time.time() + self.vbias = construct_force_bias(hamiltonian, walkers) + xbar = -self.sqrt_dt * (1j * self.vbias - self.mf_shift) + self.timer.tfbias += time.time() - start_time + + # Normally distrubted auxiliary fields. + xi = xp.random.normal(0.0, 1.0, hamiltonian.nfields * walkers.nwalkers).reshape( + walkers.nwalkers, hamiltonian.nfields) + xshifted = xi - xbar # Shape (nwalkers, nfields). + + # Constant factor arising from force bias and mean field shift + cmf = -self.sqrt_dt * xp.einsum("wx,x->w", xshifted, self.mf_shift) # Shape (nwalkers,). + # Constant factor arising from shifting the propability distribution. + cfb = xp.einsum("wx,wx->w", xi, xbar) - 0.5 * xp.einsum("wx,wx->w", xbar, xbar) # Shape (nwalkers,). + + xshifted = xshifted.T.copy() # Shape (nfields, nwalkers). + VHS = self.construct_VHS(hamiltonian, xshifted) # Shape (nwalkers, nbasis, nbasis). + return cmf, cfb, xshifted, VHS + + def propagate_walkers_one_body(self, walkers): + pass + + def propagate_walkers_two_body(self, walkers, hamiltonian, trial): + pass + + def propagate_walkers(self, walkers, hamiltonian, trial, eshift=0.): + start_time = time.time() + cmf, cfb, xshifted, VHS = self.construct_two_body_propagator(walkers, hamiltonian, trial) + assert walkers.nwalkers == xshifted.shape[-1] + self.timer.tvhs += time.time() - start_time + assert len(VHS.shape) == 3 + + start_time = time.time() + for iw in range(walkers.nwalkers): + stack = walkers.stack[iw] + BV = apply_exponential(VHS[iw], self.exp_nmax) # Shape (nbasis, nbasis). + B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) + B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) + + # Compute determinant ratio det(1+A')/det(1+A). + # 1. Current walker's Green's function. + tix = stack.nslice + G = walkers.greens_function(iw, slice_ix=tix, inplace=False) + + # 2. Compute updated Green's function. + stack.update_new(B) + walkers.greens_function(iw, slice_ix=tix, inplace=True) + + # 3. Compute det(G/G') + # Now apply phaseless approximation + self.update_weight(walkers, iw, G, cfb, cmf, eshift) + + self.timer.tupdate += time.time() - start_time + + + def update_weight(self, walkers, iw, G, cfb, cmf, eshift): + """Update weight for walker `iw`. + """ + M0a = scipy.linalg.det(G[0], check_finite=False) + M0b = scipy.linalg.det(G[1], check_finite=False) + Mnewa = scipy.linalg.det(walkers.Ga[iw], check_finite=False) + Mnewb = scipy.linalg.det(walkers.Gb[iw], check_finite=False) + + # ovlp = det( G^{-1} ) + ovlp_ratio = (M0a * M0b) / (Mnewa * Mnewb) # ovlp_new / ovlp_old + hybrid_energy = -(xp.log(ovlp_ratio) + cfb[iw] + cmf[iw]) / self.dt # Scalar. + hybrid_energy = self.apply_bound_hybrid(hybrid_energy, eshift) + importance_function = xp.exp( + -self.dt * (0.5 * (hybrid_energy + walkers.hybrid_energy) - eshift)) + + # Splitting w_k = |I(x, \bar{x}, |phi_k>)| e^{i theta_k}, where `k` + # labels the time slice. + magn = xp.abs(importance_function) + walkers.hybrid_energy = hybrid_energy + dtheta = (-self.dt * hybrid_energy - cfb[iw]).imag # Scalar. + cosine_fac = xp.amax([0., xp.cos(dtheta)]) + walkers.weight[iw] *= magn * cosine_fac + walkers.M0a[iw] = Mnewa + walkers.M0b[iw] = Mnewb + + + def apply_bound_hybrid(self, ehyb, eshift): # Shift is a number but ehyb is not + # For initial steps until first estimator communication, `eshift` will be + # zero and hybrid energy can be incorrect. So just avoid capping for + # first block until reasonable estimate of `eshift` can be computed. + if abs(eshift) < 1e-10: + return ehyb + + emax = eshift.real + self.ebound + emin = eshift.real - self.ebound + return xp.minimum(emax, xp.maximum(ehyb, emin)) + + + # Form VHS. + @abstractmethod + def construct_VHS(self, hamiltonian, xshifted): + pass + diff --git a/ipie/thermal/propagation/phaseless_generic.py b/ipie/thermal/propagation/phaseless_generic.py new file mode 100644 index 00000000..e4c5e5bf --- /dev/null +++ b/ipie/thermal/propagation/phaseless_generic.py @@ -0,0 +1,28 @@ +import math +import time + +import numpy +from ipie.config import config +from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol +from ipie.hamiltonians.generic_base import GenericBase +from ipie.thermal.propagation.operations import apply_exponential +from ipie.thermal.propagation.phaseless_base import PhaselessBase +from ipie.utils.backend import arraylib as xp +from ipie.utils.backend import synchronize +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers + + +class PhaselessGeneric(PhaselessBase): + """A class for performing phaseless propagation with real, generic, hamiltonian.""" + + def __init__(self, time_step, mu, exp_nmax=6, lowrank=False, verbose=False): + super().__init__(time_step, mu, lowrank=lowrank, verbose=verbose) + self.exp_nmax = exp_nmax + + def construct_VHS(self, hamiltonian, xshifted): + """Includes `nwalkers`. + """ + nwalkers = xshifted.shape[-1] # Shape (nfields, nwalkers). + VHS = hamiltonian.chol.dot(xshifted) # Shape (nbasis^2, nwalkers). + VHS = self.isqrt_dt * VHS.T.reshape(nwalkers, hamiltonian.nbasis, hamiltonian.nbasis) + return VHS # Shape (nwalkers, nbasis, nbasis). diff --git a/ipie/thermal/propagation/tests/test_generic.py b/ipie/thermal/propagation/tests/test_generic.py new file mode 100644 index 00000000..2b8a3d4a --- /dev/null +++ b/ipie/thermal/propagation/tests/test_generic.py @@ -0,0 +1,188 @@ +import numpy +import pytest +import h5py + +from pyscf import gto, scf, lo +from ipie.qmc.options import QMCOpts + +from ipie.systems.generic import Generic +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.thermal.estimators.thermal import one_rdm_from_G + +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField +from ipie.legacy.walkers.thermal import ThermalWalker +from ipie.legacy.thermal_propagation.continuous import Continuous +from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G + + +def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator): + for walker in legacy_walkers: + legacy_propagator.propagate_walker_phaseless( + legacy_hamiltonian, walker, legacy_trial) + + return legacy_walkers + + +def test_phaseless_generic_propagator(): + nocca = 5 + noccb = 5 + nelec = nocca + noccb + r0 = 1.75 + mol = gto.M( + atom=[("H", i * r0, 0, 0) for i in range(nelec)], + basis='sto-6g', + unit='Bohr', + verbose=5) + + mf = scf.UHF(mol).run() + mf.chkfile = 'scf.chk' + mo1 = mf.stability()[0] + dm1 = mf.make_rdm1(mo1, mf.mo_occ) + mf = mf.run(dm1) + mf.stability(return_status=True) + s1e = mol.intor("int1e_ovlp_sph") + ao_coeff = lo.orth.lowdin(s1e) + + path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" + with h5py.File(path + "reference_data/generic_integrals.h5", "r") as fa: + Lxmn = fa["LXmn"][:] + nchol = Lxmn.shape[0] + nbasis = Lxmn.shape[1] + + mu = -10. + beta = 0.1 + dt = 0.01 + nwalkers = 1 + seed = 7 + numpy.random.seed(seed) + blocks = 10 + stabilise_freq = 10 + pop_control_freq = 1 + nsteps = 1 + nslice = 5 + + lowrank = False + verbose = True + + options = { + "qmc": { + "dt": dt, + "nwalkers": nwalkers, + "blocks": blocks, + "nsteps": nsteps, + "beta": beta, + "rng_seed": seed, + "pop_control_freq": pop_control_freq, + "stabilise_freq": stabilise_freq, + "batched": False + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank + + }, + + "hamiltonian": { + "name": "Generic", + "integrals": path + "reference_data/generic_integrals.h5", + "_alt_convention": False, + "symmetry": False, + "sparse": False, + "mu": mu + }, + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + system = Generic(mol.nelec, verbose=verbose) + hamiltonian = get_hamiltonian(system, options["hamiltonian"]) + trial = MeanField(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + nbasis = trial.dmat.shape[-1] + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + propagator = PhaselessGeneric(dt, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_system = Generic(mol.nelec, verbose=verbose) + legacy_system.mu = mu + + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore, + options=options["hamiltonian"]) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, dt, + verbose=verbose) + legacy_walkers = [ + ThermalWalker( + legacy_system, legacy_hamiltonian, legacy_trial, + walker_opts=options, verbose=i == 0) for i in range(nwalkers)] + + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps + + legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_propagator = Continuous( + options["propagator"], qmc_opts, legacy_system, + legacy_hamiltonian,legacy_trial, verbose=verbose, + lowrank=lowrank) + + for t in range(nslice): + propagator.propagate_walkers(walkers, hamiltonian, trial) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + + # Check. + for iw in range(nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + eloc = local_energy_generic_cholesky(hamiltonian, P) + + legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers[iw].G)) + legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.reshape( + (hamiltonian.nchol, hamiltonian.nbasis**2)).T + legacy_eloc = legacy_local_energy_generic_cholesky( + legacy_system, legacy_hamiltonian, legacy_P) + + print(f'\nt = {t}') + print(f'iw = {iw}') + print(f'eloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') + + #numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + #numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) + #numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) + #numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) + #numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) + + + +if __name__ == "__main__": + test_phaseless_generic_propagator() diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index 27fea9f6..7add8197 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -4,7 +4,7 @@ from ipie.thermal.estimators.fock import fock_matrix from ipie.thermal.estimators.thermal import greens_function, one_rdm_stable, particle_number from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential -from ipie.thermal.trial.onebody import OneBody +from ipie.thermal.trial.one_body import OneBody class MeanField(OneBody): def __init__(self, hamiltonian, nelec, beta, dt, options={}, H1=None, verbose=False): diff --git a/ipie/thermal/trial/utils.py b/ipie/thermal/trial/utils.py index b474af53..138ebfbe 100644 --- a/ipie/thermal/trial/utils.py +++ b/ipie/thermal/trial/utils.py @@ -1,5 +1,5 @@ from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.onebody import OneBody +from ipie.thermal.trial.one_body import OneBody def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, comm=None, verbose=False): diff --git a/ipie/thermal/walkers/stack.py b/ipie/thermal/walkers/stack.py index 8481ef29..49e238c9 100644 --- a/ipie/thermal/walkers/stack.py +++ b/ipie/thermal/walkers/stack.py @@ -46,12 +46,8 @@ def __init__( self.left = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) self.right = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) - self.Ga = numpy.asarray( - numpy.eye(self.nbasis, dtype=dtype) - ) - self.Gb = numpy.asarray( - numpy.eye(self.nbasis, dtype=dtype) - ) + self.G = numpy.asarray([numpy.eye(self.nbasis, dtype=dtype), # Ga + numpy.eye(self.nbasis, dtype=dtype)]) # Gb if self.lowrank: self.update_new = self.update_low_rank @@ -310,9 +306,8 @@ def update_low_rank(self, B): self.theta[s][:, :] = 0.0 self.theta[s][:mT, :] = Qlcr_pad[:, :mT].dot(numpy.diag(Dlcr[:mT])).T # self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.CT[s][:,:mT].dot(self.theta[s][:mT,:]) - self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.theta[s][:mT, :].T.dot( - self.CT[s][:, :mT].T.conj() - ) + self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) -\ + self.theta[s][:mT, :].T.dot(self.CT[s][:, :mT].T.conj()) # self.CT[s][:,:mT] = self.CT[s][:,:mT].conj() # print("# mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) @@ -379,9 +374,8 @@ def update_low_rank(self, B): self.theta[s][:, :] = 0.0 self.theta[s][:mT, :] = Qlcr_pad[:, :mT].dot(numpy.diag(Dlcr[:mT])).T # self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.CT[s][:,:mT].dot(self.theta[s][:mT,:]) - self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) - self.theta[s][:mT, :].T.dot( - self.CT[s][:, :mT].T.conj() - ) + self.G[s] = numpy.eye(self.nbasis, dtype=B[s].dtype) -\ + self.theta[s][:mT, :].T.dot(self.CT[s][:, :mT].T.conj()) # self.CT = numpy.zeros(shape=(2, nbasis, nbasis),dtype=dtype) # self.theta = numpy.zeros(shape=(2, nbasis, nbasis),dtype=dtype) diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py index 0dbfdcb6..49ee7b95 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -1,19 +1,19 @@ import numpy import pytest -from ipie.hamiltonians.ueg import UEG as HamUEG from ipie.systems.ueg import UEG +from ipie.hamiltonians.ueg import UEG as HamUEG from ipie.thermal.trial.one_body import OneBody from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.estimators.ueg import local_energy_ueg +from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.legacy.systems.ueg import UEG as LegacyUEG from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody from ipie.legacy.walkers.thermal import ThermalWalker - -try: - from ipie.thermal.estimators.ueg import local_energy_ueg -except ImportError as e: - print(e) +from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G @pytest.mark.unit def test_thermal_walkers(): @@ -22,33 +22,50 @@ def test_thermal_walkers(): nup = 7 ndown = 7 nelec = (nup, ndown) - options = {"rs": rs, "nup": nup, "ndown": ndown, "ecut": ecut, "write_integrals": False} nwalkers = 5 - - system = UEG(options=options) - hamiltonian = HamUEG(system, options=options) - - legacy_hamiltonian = LegacyHamUEG(system, options=options) - - beta = 1 dt = 0.05 + lowrank = True verbose = True + options = {"rs": rs, "nup": nup, "ndown": ndown, "ecut": ecut, + "write_integrals": False, "low_rank" : lowrank} + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + system = UEG(options=options) + hamiltonian = HamUEG(system, options=options) trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) nbasis = trial.dmat.shape[-1] + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) - legacy_trial = LegacyOneBody(system, hamiltonian, beta, 0.05) - legacy_walkers = [ThermalWalker(system, legacy_hamiltonian, legacy_trial, verbose=i == 0) for i in range(nwalkers)] - - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, verbose=1) + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_system = UEG(options=options) + legacy_hamiltonian = LegacyHamUEG(legacy_system, options=options) + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, dt, verbose=verbose) + legacy_walkers = [ + ThermalWalker( + legacy_system, legacy_hamiltonian, legacy_trial, + walker_opts=options, verbose=i == 0) for i in range(nwalkers)] for iw in range(nwalkers): - legacy_eloc = local_energy_ueg(system,hamiltonian, legacy_walkers[iw].G) - eloc = local_energy_ueg(system,hamiltonian, numpy.array([walkers.Ga[iw],walkers.Gb[iw]])) - print(eloc) - numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + eloc = local_energy_ueg(system, hamiltonian, P) + + legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers[iw].G)) + legacy_eloc = legacy_local_energy_ueg(legacy_system, legacy_hamiltonian, legacy_P) + print(f'\niw = {iw}') + print(f'eloc = {eloc}') + print(f'legacy_eloc = {legacy_eloc}') + + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index 8b9cd0cf..ff30775c 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -52,7 +52,6 @@ def __init__( self.Gb = numpy.zeros( shape=(self.nwalkers, self.nbasis, self.nbasis), dtype=numpy.complex128) - self.Ghalf = None max_diff_diag = numpy.linalg.norm( @@ -88,18 +87,15 @@ def __init__( for iw in range(self.nwalkers): self.stack[iw].set_all(trial.dmat) self.greens_function_qr_strat(iw) - self.stack[iw].Ga = self.Ga[iw] - self.stack[iw].Gb = self.Gb[iw] - self.M0a = numpy.array( - [ - scipy.linalg.det(self.Ga[iw], check_finite=False) for iw in range(self.nwalkers) - ] - ) - self.M0b = numpy.array( - [ - scipy.linalg.det(self.Gb[iw], check_finite=False) for iw in range(self.nwalkers) - ] - ) + self.stack[iw].G[0] = self.Ga[iw] + self.stack[iw].G[1] = self.Gb[iw] + + # Shape (nwalkers,). + self.M0a = numpy.array([ + scipy.linalg.det(self.Ga[iw], check_finite=False) for iw in range(self.nwalkers)]) + self.M0b = numpy.array([ + scipy.linalg.det(self.Gb[iw], check_finite=False) for iw in range(self.nwalkers)]) + for iw in range(self.nwalkers): self.stack[iw].ovlp = numpy.array([1.0 / self.M0a[iw], 1.0 / self.M0b[iw]]) @@ -117,423 +113,48 @@ def __init__( self.hybrid_energy = 0.0 if verbose: for iw in range(self.nwalkers): - G = numpy.array([self.Ga[iw],self.Gb[iw]]) + G = numpy.array([self.Ga[iw], self.Gb[iw]]) P = one_rdm_from_G(G) nav = particle_number(P) print(f"# Trial electron number for {iw}-th walker: {nav}") self.buff_names, self.buff_size = get_numeric_names(self.__dict__) - def greens_function(self, trial, slice_ix=None, inplace=True): - if self.lowrank: - return self.stack.G - else: - return self.greens_function_qr_strat(trial, slice_ix=slice_ix, inplace=inplace) - - def greens_function_svd(self, trial, slice_ix=None, inplace=True): - if slice_ix == None: - slice_ix = self.stack.time_slice - bin_ix = slice_ix // self.stack.nstack - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == self.stack.nbins: - bin_ix = -1 - if inplace: - G = None - else: - G = numpy.zeros(self.G.shape, self.G.dtype) - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} - # in stable way. Iteratively construct SVD decompositions starting - # from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) - (U1, S1, V1) = scipy.linalg.svd(B[spin]) - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) - T1 = numpy.dot(B[spin], U1) - # todo optimise - T2 = numpy.dot(T1, numpy.diag(S1)) - (U1, S1, V) = scipy.linalg.svd(T2) - V1 = numpy.dot(V, V1) - A = numpy.dot(U1.dot(numpy.diag(S1)), V1) - # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. - # Care needs to be taken when adding the identity matrix. - T3 = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) - (U2, S2, V2) = scipy.linalg.svd(T3) - U3 = numpy.dot(U1, U2) - D3 = numpy.diag(1.0 / S2) - V3 = numpy.dot(V2, V1) - # G(l) = (U3 S2 V3)^{-1} - # = V3^{\dagger} D3 U3^{\dagger} - if inplace: - # self.G[spin] = (V3inv).dot(U3.conj().T) - self.G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) - else: - # G[spin] = (V3inv).dot(U3.conj().T) - G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) - return G - - def greens_function_qr(self, trial, slice_ix=None, inplace=True): - if slice_ix == None: - slice_ix = self.stack.time_slice - - bin_ix = slice_ix // self.stack.nstack - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == self.stack.nbins: - bin_ix = -1 - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} - # in stable way. Iteratively construct SVD decompositions starting - # from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) - (U1, V1) = scipy.linalg.qr(B[spin], pivoting=False, check_finite=False) - - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) - T1 = numpy.dot(B[spin], U1) - (U1, V) = scipy.linalg.qr(T1, pivoting=False, check_finite=False) - V1 = numpy.dot(V, V1) - - # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. - # Care needs to be taken when adding the identity matrix. - V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0])) - - T3 = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0]) - (U2, V2) = scipy.linalg.qr(T3, pivoting=False, check_finite=False) - - U3 = numpy.dot(U1, U2) - V3 = numpy.dot(V2, V1) - V3inv = scipy.linalg.solve_triangular(V3, numpy.identity(V3.shape[0])) - # G(l) = (U3 S2 V3)^{-1} - # = V3^{\dagger} D3 U3^{\dagger} - if inplace: - self.G[spin] = (V3inv).dot(U3.conj().T) - else: - G[spin] = (V3inv).dot(U3.conj().T) - return G - - def compute_left_right(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # right bit - # B(right) ... B(1) - if center_ix > 0: - # print ("center_ix > 0") - B = self.stack.get(0) - (self.Qr[spin], R1, P1) = scipy.linalg.qr( - B[spin], pivoting=True, check_finite=False - ) - # Form D matrices - self.Dr[spin] = R1.diagonal() - D1inv = 1.0 / R1.diagonal() - self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) - # now permute them - self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] - - for ix in range(1, center_ix): - B = self.stack.get(ix) - C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) - (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = 1.0 / R1.diagonal() - self.Dr[spin] = R1.diagonal() - # smarter permutation - # D^{-1} * R - tmp = numpy.einsum("i,ij->ij", D1inv, R1) - # D^{-1} * R * P^T - tmp[:, P1] = tmp[:, range(self.nbasis)] - # D^{-1} * R * P^T * T - self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) - - # left bit - # B(l) ... B(left) - if center_ix < self.stack.nbins - 1: - # print("center_ix < self.stack.nbins-1 first") - # We will assume that B matrices are all diagonal for left.... - B = self.stack.get(center_ix + 1) - self.Dl[spin] = B[spin].diagonal() - D1inv = 1.0 / B[spin].diagonal() - self.Ql[spin] = numpy.identity(B[spin].shape[0]) - self.Tl[spin] = numpy.identity(B[spin].shape[0]) - - for ix in range(center_ix + 2, self.stack.nbins): - # print("center_ix < self.stack.nbins-1 first inner loop") - B = self.stack.get(ix) - C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) - self.Dl[spin] = C2 - - def compute_right(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # right bit - # B(right) ... B(1) - if center_ix > 0: - # print ("center_ix > 0") - B = self.stack.get(0) - (self.Qr[spin], R1, P1) = scipy.linalg.qr( - B[spin], pivoting=True, check_finite=False - ) - # Form D matrices - self.Dr[spin] = R1.diagonal() - D1inv = 1.0 / R1.diagonal() - self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) - # now permute them - self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] - - for ix in range(1, center_ix): - B = self.stack.get(ix) - C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) - (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = 1.0 / R1.diagonal() - self.Dr[spin] = R1.diagonal() - # smarter permutation - # D^{-1} * R - tmp = numpy.einsum("i,ij->ij", D1inv, R1) - # D^{-1} * R * P^T - tmp[:, P1] = tmp[:, range(self.nbasis)] - # D^{-1} * R * P^T * T - self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) - - def compute_left(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # left bit - # B(l) ... B(left) - if center_ix < self.stack.nbins - 1: - # print("center_ix < self.stack.nbins-1 first") - # We will assume that B matrices are all diagonal for left.... - B = self.stack.get(center_ix + 1) - self.Dl[spin] = B[spin].diagonal() - self.Ql[spin] = numpy.identity(B[spin].shape[0]) - self.Tl[spin] = numpy.identity(B[spin].shape[0]) - - for ix in range(center_ix + 2, self.stack.nbins): - # print("center_ix < self.stack.nbins-1 first inner loop") - B = self.stack.get(ix) - C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) - self.Dl[spin] = C2.diagonal() - - def greens_function_left_right(self, center_ix, inplace=False, thresh=1e-6): - assert self.diagonal_trial - - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - - mL = self.G.shape[1] - mR = self.G.shape[1] - mT = self.G.shape[1] - - Bc = self.stack.get(center_ix) - - nbsf = Bc.shape[1] - - # It goes to right to left and we sample (I + L*B*R) in the end - for spin in [0, 1]: - if center_ix > 0: # there exists right bit - mR = len(self.Dr[spin][numpy.abs(self.Dr[spin]) > thresh]) - - Ccr = numpy.einsum( - "ij,j->ij", - numpy.dot(Bc[spin], self.Qr[spin][:, :mR]), - self.Dr[spin][:mR], - ) # N x mR - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) - Dlcr = Rlcr[:mR, :mR].diagonal() # mR - Dinv = 1.0 / Dlcr # mR - tmp = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :mR]) # mR, mR x mR -> mR x mR - tmp[:, Plcr] = tmp[:, range(mR)] - Tlcr = numpy.dot(tmp, self.Tr[spin][:mR, :]) # mR x N - else: - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) - # Form D matrices - Dlcr = Rlcr.diagonal() - - mR = len(Dlcr[numpy.abs(Dlcr) > thresh]) - - Dinv = 1.0 / Rlcr.diagonal() - Tlcr = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :]) # mR x N - Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] # mR x N - - if center_ix < self.stack.nbins - 1: # there exists left bit - # assume left stack is all diagonal (i.e., QDT = diagonal -> Q and T are identity) - Clcr = numpy.einsum( - "i,ij->ij", - self.Dl[spin], - numpy.einsum("ij,j->ij", Qlcr[:, :mR], Dlcr[:mR]), - ) # N x mR - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr( - Clcr, pivoting=True, check_finite=False - ) # N x N, mR x mR - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Dlcr - - mT = len(Dlcr[numpy.abs(Dlcr) > thresh]) - - tmp = numpy.einsum("i,ij->ij", Dinv[:mT], Rlcr[:mT, :]) - tmp[:, Plcr] = tmp[:, range(mR)] # mT x mR - Tlcr = numpy.dot(tmp, Tlcr) # mT x N - else: - mT = mR - # D = Ds Db^{-1} - Db = numpy.zeros(mT, Bc[spin].dtype) - Ds = numpy.zeros(mT, Bc[spin].dtype) - for i in range(mT): - absDlcr = abs(Dlcr[i]) - if absDlcr > 1.0: - Db[i] = 1.0 / absDlcr - Ds[i] = numpy.sign(Dlcr[i]) - else: - Db[i] = 1.0 - Ds[i] = Dlcr[i] - - if mT == nbsf: # No need for Woodbury - T1inv = scipy.linalg.inv(Tlcr, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) - Cinv = scipy.linalg.inv(C, check_finite=False) - - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), - numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), - ) - # return # This seems to change the answer WHY?? - else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), - numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), - ) - else: # Use Woodbury - TQ = Tlcr.dot(Qlcr[:, :mT]) - TQinv = scipy.linalg.inv(TQ, check_finite=False) - tmp = scipy.linalg.inv( - numpy.einsum("ij,j->ij", TQinv, Db) + numpy.diag(Ds), - check_finite=False, - ) - A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv)) - if inplace: - self.G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( - numpy.diag(Dlcr[:mT]) - ).dot(A).dot(Tlcr) - else: - G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( - numpy.diag(Dlcr[:mT]) - ).dot(A).dot(Tlcr) - # print(mR,mT,nbsf) - # print("ref: mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) - return G - - def greens_function_left_right_no_truncation(self, center_ix, inplace=False): - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) + def greens_function(self, iw, slice_ix=None, inplace=True): + """Return the Green's function for walker `iw`. + """ + if self.lowrank: + return self.stack[iw].G # G[0] = Ga, G[1] = Gb else: - G = None - - Bc = self.stack.get(center_ix) - for spin in [0, 1]: - if center_ix > 0: # there exists right bit - # print("center_ix > 0 second") - Ccr = numpy.einsum("ij,j->ij", numpy.dot(Bc[spin], self.Qr[spin]), self.Dr[spin]) - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) - tmp[:, Plcr] = tmp[:, range(self.nbasis)] - Tlcr = numpy.dot(tmp, self.Tr[spin]) - else: - # print("center_ix > 0 else second") - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) - # Form D matrices - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - Tlcr = numpy.einsum("i,ij->ij", Dinv, Rlcr) - Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] - - if center_ix < self.stack.nbins - 1: # there exists left bit - # print("center_ix < self.stack.nbins-1 second") - # assume left stack is all diagonal - Clcr = numpy.einsum("i,ij->ij", self.Dl[spin], numpy.einsum("ij,j->ij", Qlcr, Dlcr)) - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Clcr, pivoting=True, check_finite=False) - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - - tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) - tmp[:, Plcr] = tmp[:, range(self.nbasis)] - Tlcr = numpy.dot(tmp, Tlcr) - - # print("Dlcr = {}".format(Dlcr)) - - # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T - # Write D = Db^{-1} Ds - # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T - Db = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) - Ds = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) - for i in range(Db.shape[0]): - absDlcr = abs(Dlcr[i]) - if absDlcr > 1.0: - Db[i] = 1.0 / absDlcr - Ds[i] = numpy.sign(Dlcr[i]) - else: - Db[i] = 1.0 - Ds[i] = Dlcr[i] - - T1inv = scipy.linalg.inv(Tlcr, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) - Cinv = scipy.linalg.inv(C, check_finite=False) + return self.greens_function_qr_strat(iw, slice_ix=slice_ix, inplace=inplace) - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) - ) - else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) - ) - return G def greens_function_qr_strat(self, iw, slice_ix=None, inplace=True): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) + """Compute the Green's function for walker with index `iw` at time + `slice_ix`. Uses the Stratification method (DOI 10.1109/IPDPS.2012.37) + """ + stack_iw = self.stack[iw] + if slice_ix == None: - slice_ix = self.stack[iw].time_slice + slice_ix = stack_iw.time_slice - bin_ix = slice_ix // self.stack[iw].nstack + bin_ix = slice_ix // stack_iw.nstack # For final time slice want first block to be the rightmost (for energy # evaluation). - if bin_ix == self.stack[iw].nbins: + if bin_ix == stack_iw.nbins: bin_ix = -1 + Ga_iw, Gb_iw = None, None if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None + Ga_iw = numpy.zeros(self.Ga[iw].shape, self.Ga.dtype) + Gb_iw = numpy.zeros(self.Gb[iw].shape, self.Gb.dtype) for spin in [0, 1]: # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in # stable way. Iteratively construct column pivoted QR decompositions # (A = QDT) starting from the rightmost (product of) propagator(s). - B = self.stack[iw].get((bin_ix + 1) % self.stack[iw].nbins) + B = stack_iw.get((bin_ix + 1) % stack_iw.nbins) (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) # Form D matrices @@ -543,9 +164,9 @@ def greens_function_qr_strat(self, iw, slice_ix=None, inplace=True): # permute them T1[:, P1] = T1[:, range(self.nbasis)] - for i in range(2, self.stack[iw].nbins + 1): - ix = (bin_ix + i) % self.stack[iw].nbins - B = self.stack[iw].get(ix) + for i in range(2, stack_iw.nbins + 1): + ix = (bin_ix + i) % stack_iw.nbins + B = stack_iw.get(ix) C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) # Compute D matrices @@ -579,17 +200,22 @@ def greens_function_qr_strat(self, iw, slice_ix=None, inplace=True): if inplace: if spin == 0: self.Ga[iw] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) - ) + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) else: self.Gb[iw] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) - ) + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) + else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) - ) - return G + if spin == 0: + Ga_iw = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) + + else: + Gb_iw = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) + + return Ga_iw, Gb_iw + # For compatibiltiy with BaseWalkers class. def reortho(self): diff --git a/ipie/thermal/walkers/uhf_walkers2.py b/ipie/thermal/walkers/uhf_walkers2.py deleted file mode 100644 index 1541de35..00000000 --- a/ipie/thermal/walkers/uhf_walkers2.py +++ /dev/null @@ -1,591 +0,0 @@ -import numpy -import scipy.linalg - -from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number -from ipie.thermal.walkers.stack import PropagatorStack -from ipie.utils.misc import get_numeric_names, update_stack -from ipie.walkers.base_walkers import BaseWalkers -from ipie.thermal.trial.one_body import OneBody - -class UHFThermalWalkers(BaseWalkers): - def __init__( - self, - trial: OneBody, - nup: int, - ndown: int, - nbasis: int, - nwalkers: int, - nstack = None, - lowrank: bool = False, - lowrank_thresh: float = 1e-6, - mpi_handler = None, - verbose: bool = False, - ): - """UHF style walker. - """ - assert isinstance(trial, OneBody) - self.nup = nup - self.ndown = ndown - self.nbasis = nbasis - self.mpi_handler = mpi_handler - self.nslice = trial.nslice - self.nstack = nstack - - if self.nstack == None: - self.nstack = trial.nstack - - if (self.nslice // self.nstack) * self.nstack != self.nslice: - if verbose: - print("# Input stack size does not divide number of slices.") - self.nstack = update_stack(self.nstack, self.nslice, verbose) - - if self.nstack > trial.nstack: - if verbose: - print("# Walker stack size differs from that estimated from " "Trial density matrix.") - print(f"# Be careful. cond(BT)**nstack: {trial.cond ** self.nstack:10.3e}.") - - self.stack_length = self.nslice // self.nstack - self.lowrank = lowrank - self.lowrank_thresh = lowrank_thresh - - super().__init__(nwalkers, verbose=verbose) - - self.Ga = numpy.zeros( - shape=(self.nwalkers, self.nbasis, self.nbasis), - dtype=numpy.complex128) - self.Gb = numpy.zeros( - shape=(self.nwalkers, self.nbasis, self.nbasis), - dtype=numpy.complex128) - self.Ghalf = None - max_diff_diag = numpy.linalg.norm( - (numpy.diag( - trial.dmat[0].diagonal()) - trial.dmat[0])) - - if max_diff_diag < 1e-10: - self.diagonal_trial = True - if verbose: - print("# Trial density matrix is diagonal.") - else: - self.diagonal_trial = False - if verbose: - print("# Trial density matrix is not diagonal.") - - if verbose: - print(f"# Walker stack size: {self.nstack}") - print(f"# Using low rank trick: {self.lowrank}") - - self.stacks = [ - PropagatorStack( - self.nstack, - self.nslice, - self.nbasis, - numpy.complex128, - trial.dmat, - trial.dmat_inv, - diagonal=self.diagonal_trial, - lowrank=self.lowrank, - thresh=self.lowrank_thresh, - ) for i in range(nwalkers) - ] - - self.M0a = numpy.array( - [ - scipy.linalg.det(self.G[0], check_finite=False), - scipy.linalg.det(self.G[1], check_finite=False), - ] - ) - - # Initialise all propagators to the trial density matrix. - for i, stack in enumerate(self.stacks): - stack.set_all(trial.dmat) - self.greens_function_qr_strat(trial) - stack.G = self.G[i] - - self.stack.ovlp = numpy.array([1.0 / self.M0[0], 1.0 / self.M0[1]]) - - # Temporary storage for stacks... - I = numpy.identity(self.nbasis, dtype=numpy.complex128) - One = numpy.ones(self.nbasis, dtype=numpy.complex128) - self.Tl = numpy.array([I, I]) - self.Ql = numpy.array([I, I]) - self.Dl = numpy.array([One, One]) - self.Tr = numpy.array([I, I]) - self.Qr = numpy.array([I, I]) - self.Dr = numpy.array([One, One]) - - self.hybrid_energy = 0.0 - if verbose: - P = one_rdm_from_G(self.G) - nav = particle_number(P) - print(f"# Trial electron number: {nav}") - - self.buff_names, self.buff_size = get_numeric_names(self.__dict__) - - def greens_function(self, trial, slice_ix=None, inplace=True): - if self.lowrank: - return self.stack.G - else: - return self.greens_function_qr_strat(trial, slice_ix=slice_ix, inplace=inplace) - - def greens_function_svd(self, trial, slice_ix=None, inplace=True): - if slice_ix == None: - slice_ix = self.stack.time_slice - bin_ix = slice_ix // self.stack.nstack - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == self.stack.nbins: - bin_ix = -1 - if inplace: - G = None - else: - G = numpy.zeros(self.G.shape, self.G.dtype) - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} - # in stable way. Iteratively construct SVD decompositions starting - # from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) - (U1, S1, V1) = scipy.linalg.svd(B[spin]) - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) - T1 = numpy.dot(B[spin], U1) - # todo optimise - T2 = numpy.dot(T1, numpy.diag(S1)) - (U1, S1, V) = scipy.linalg.svd(T2) - V1 = numpy.dot(V, V1) - A = numpy.dot(U1.dot(numpy.diag(S1)), V1) - # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. - # Care needs to be taken when adding the identity matrix. - T3 = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) - (U2, S2, V2) = scipy.linalg.svd(T3) - U3 = numpy.dot(U1, U2) - D3 = numpy.diag(1.0 / S2) - V3 = numpy.dot(V2, V1) - # G(l) = (U3 S2 V3)^{-1} - # = V3^{\dagger} D3 U3^{\dagger} - if inplace: - # self.G[spin] = (V3inv).dot(U3.conj().T) - self.G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) - else: - # G[spin] = (V3inv).dot(U3.conj().T) - G[spin] = (V3.conj().T).dot(D3).dot(U3.conj().T) - return G - - def greens_function_qr(self, trial, slice_ix=None, inplace=True): - if slice_ix == None: - slice_ix = self.stack.time_slice - - bin_ix = slice_ix // self.stack.nstack - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == self.stack.nbins: - bin_ix = -1 - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} - # in stable way. Iteratively construct SVD decompositions starting - # from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) - (U1, V1) = scipy.linalg.qr(B[spin], pivoting=False, check_finite=False) - - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) - T1 = numpy.dot(B[spin], U1) - (U1, V) = scipy.linalg.qr(T1, pivoting=False, check_finite=False) - V1 = numpy.dot(V, V1) - - # Final SVD decomposition to construct G(l) = [I + A(l)]^{-1}. - # Care needs to be taken when adding the identity matrix. - V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0])) - - T3 = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0]) - (U2, V2) = scipy.linalg.qr(T3, pivoting=False, check_finite=False) - - U3 = numpy.dot(U1, U2) - V3 = numpy.dot(V2, V1) - V3inv = scipy.linalg.solve_triangular(V3, numpy.identity(V3.shape[0])) - # G(l) = (U3 S2 V3)^{-1} - # = V3^{\dagger} D3 U3^{\dagger} - if inplace: - self.G[spin] = (V3inv).dot(U3.conj().T) - else: - G[spin] = (V3inv).dot(U3.conj().T) - return G - - def compute_left_right(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # right bit - # B(right) ... B(1) - if center_ix > 0: - # print ("center_ix > 0") - B = self.stack.get(0) - (self.Qr[spin], R1, P1) = scipy.linalg.qr( - B[spin], pivoting=True, check_finite=False - ) - # Form D matrices - self.Dr[spin] = R1.diagonal() - D1inv = 1.0 / R1.diagonal() - self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) - # now permute them - self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] - - for ix in range(1, center_ix): - B = self.stack.get(ix) - C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) - (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = 1.0 / R1.diagonal() - self.Dr[spin] = R1.diagonal() - # smarter permutation - # D^{-1} * R - tmp = numpy.einsum("i,ij->ij", D1inv, R1) - # D^{-1} * R * P^T - tmp[:, P1] = tmp[:, range(self.nbasis)] - # D^{-1} * R * P^T * T - self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) - - # left bit - # B(l) ... B(left) - if center_ix < self.stack.nbins - 1: - # print("center_ix < self.stack.nbins-1 first") - # We will assume that B matrices are all diagonal for left.... - B = self.stack.get(center_ix + 1) - self.Dl[spin] = B[spin].diagonal() - D1inv = 1.0 / B[spin].diagonal() - self.Ql[spin] = numpy.identity(B[spin].shape[0]) - self.Tl[spin] = numpy.identity(B[spin].shape[0]) - - for ix in range(center_ix + 2, self.stack.nbins): - # print("center_ix < self.stack.nbins-1 first inner loop") - B = self.stack.get(ix) - C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) - self.Dl[spin] = C2 - - def compute_right(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # right bit - # B(right) ... B(1) - if center_ix > 0: - # print ("center_ix > 0") - B = self.stack.get(0) - (self.Qr[spin], R1, P1) = scipy.linalg.qr( - B[spin], pivoting=True, check_finite=False - ) - # Form D matrices - self.Dr[spin] = R1.diagonal() - D1inv = 1.0 / R1.diagonal() - self.Tr[spin] = numpy.einsum("i,ij->ij", D1inv, R1) - # now permute them - self.Tr[spin][:, P1] = self.Tr[spin][:, range(self.nbasis)] - - for ix in range(1, center_ix): - B = self.stack.get(ix) - C2 = numpy.einsum("ij,j->ij", numpy.dot(B[spin], self.Qr[spin]), self.Dr[spin]) - (self.Qr[spin], R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = 1.0 / R1.diagonal() - self.Dr[spin] = R1.diagonal() - # smarter permutation - # D^{-1} * R - tmp = numpy.einsum("i,ij->ij", D1inv, R1) - # D^{-1} * R * P^T - tmp[:, P1] = tmp[:, range(self.nbasis)] - # D^{-1} * R * P^T * T - self.Tr[spin] = numpy.dot(tmp, self.Tr[spin]) - - def compute_left(self, center_ix): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - # B(L) .... B(1) - for spin in [0, 1]: - # left bit - # B(l) ... B(left) - if center_ix < self.stack.nbins - 1: - # print("center_ix < self.stack.nbins-1 first") - # We will assume that B matrices are all diagonal for left.... - B = self.stack.get(center_ix + 1) - self.Dl[spin] = B[spin].diagonal() - self.Ql[spin] = numpy.identity(B[spin].shape[0]) - self.Tl[spin] = numpy.identity(B[spin].shape[0]) - - for ix in range(center_ix + 2, self.stack.nbins): - # print("center_ix < self.stack.nbins-1 first inner loop") - B = self.stack.get(ix) - C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) - self.Dl[spin] = C2.diagonal() - - def greens_function_left_right(self, center_ix, inplace=False, thresh=1e-6): - assert self.diagonal_trial - - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - - mL = self.G.shape[1] - mR = self.G.shape[1] - mT = self.G.shape[1] - - Bc = self.stack.get(center_ix) - - nbsf = Bc.shape[1] - - # It goes to right to left and we sample (I + L*B*R) in the end - for spin in [0, 1]: - if center_ix > 0: # there exists right bit - mR = len(self.Dr[spin][numpy.abs(self.Dr[spin]) > thresh]) - - Ccr = numpy.einsum( - "ij,j->ij", - numpy.dot(Bc[spin], self.Qr[spin][:, :mR]), - self.Dr[spin][:mR], - ) # N x mR - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) - Dlcr = Rlcr[:mR, :mR].diagonal() # mR - Dinv = 1.0 / Dlcr # mR - tmp = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :mR]) # mR, mR x mR -> mR x mR - tmp[:, Plcr] = tmp[:, range(mR)] - Tlcr = numpy.dot(tmp, self.Tr[spin][:mR, :]) # mR x N - else: - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) - # Form D matrices - Dlcr = Rlcr.diagonal() - - mR = len(Dlcr[numpy.abs(Dlcr) > thresh]) - - Dinv = 1.0 / Rlcr.diagonal() - Tlcr = numpy.einsum("i,ij->ij", Dinv[:mR], Rlcr[:mR, :]) # mR x N - Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] # mR x N - - if center_ix < self.stack.nbins - 1: # there exists left bit - # assume left stack is all diagonal (i.e., QDT = diagonal -> Q and T are identity) - Clcr = numpy.einsum( - "i,ij->ij", - self.Dl[spin], - numpy.einsum("ij,j->ij", Qlcr[:, :mR], Dlcr[:mR]), - ) # N x mR - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr( - Clcr, pivoting=True, check_finite=False - ) # N x N, mR x mR - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Dlcr - - mT = len(Dlcr[numpy.abs(Dlcr) > thresh]) - - tmp = numpy.einsum("i,ij->ij", Dinv[:mT], Rlcr[:mT, :]) - tmp[:, Plcr] = tmp[:, range(mR)] # mT x mR - Tlcr = numpy.dot(tmp, Tlcr) # mT x N - else: - mT = mR - - # D = Ds Db^{-1} - Db = numpy.zeros(mT, Bc[spin].dtype) - Ds = numpy.zeros(mT, Bc[spin].dtype) - for i in range(mT): - absDlcr = abs(Dlcr[i]) - if absDlcr > 1.0: - Db[i] = 1.0 / absDlcr - Ds[i] = numpy.sign(Dlcr[i]) - else: - Db[i] = 1.0 - Ds[i] = Dlcr[i] - - if mT == nbsf: # No need for Woodbury - T1inv = scipy.linalg.inv(Tlcr, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) - Cinv = scipy.linalg.inv(C, check_finite=False) - - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), - numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), - ) - # return # This seems to change the answer WHY?? - else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), - numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), - ) - else: # Use Woodbury - TQ = Tlcr.dot(Qlcr[:, :mT]) - TQinv = scipy.linalg.inv(TQ, check_finite=False) - tmp = scipy.linalg.inv( - numpy.einsum("ij,j->ij", TQinv, Db) + numpy.diag(Ds), - check_finite=False, - ) - A = numpy.einsum("i,ij->ij", Db, tmp.dot(TQinv)) - if inplace: - self.G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( - numpy.diag(Dlcr[:mT]) - ).dot(A).dot(Tlcr) - else: - G[spin] = numpy.eye(nbsf, dtype=Bc[spin].dtype) - Qlcr[:, :mT].dot( - numpy.diag(Dlcr[:mT]) - ).dot(A).dot(Tlcr) - # print(mR,mT,nbsf) - # print("ref: mL, mR, mT = {}, {}, {}".format(mL, mR, mT)) - return G - - def greens_function_left_right_no_truncation(self, center_ix, inplace=False): - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - - Bc = self.stack.get(center_ix) - for spin in [0, 1]: - if center_ix > 0: # there exists right bit - # print("center_ix > 0 second") - Ccr = numpy.einsum("ij,j->ij", numpy.dot(Bc[spin], self.Qr[spin]), self.Dr[spin]) - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Ccr, pivoting=True, check_finite=False) - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) - tmp[:, Plcr] = tmp[:, range(self.nbasis)] - Tlcr = numpy.dot(tmp, self.Tr[spin]) - else: - # print("center_ix > 0 else second") - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Bc[spin], pivoting=True, check_finite=False) - # Form D matrices - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - Tlcr = numpy.einsum("i,ij->ij", Dinv, Rlcr) - Tlcr[:, Plcr] = Tlcr[:, range(self.nbasis)] - - if center_ix < self.stack.nbins - 1: # there exists left bit - # print("center_ix < self.stack.nbins-1 second") - # assume left stack is all diagonal - Clcr = numpy.einsum("i,ij->ij", self.Dl[spin], numpy.einsum("ij,j->ij", Qlcr, Dlcr)) - - (Qlcr, Rlcr, Plcr) = scipy.linalg.qr(Clcr, pivoting=True, check_finite=False) - Dlcr = Rlcr.diagonal() - Dinv = 1.0 / Rlcr.diagonal() - - tmp = numpy.einsum("i,ij->ij", Dinv, Rlcr) - tmp[:, Plcr] = tmp[:, range(self.nbasis)] - Tlcr = numpy.dot(tmp, Tlcr) - - # print("Dlcr = {}".format(Dlcr)) - - # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T - # Write D = Db^{-1} Ds - # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T - Db = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) - Ds = numpy.zeros(Bc[spin].shape[-1], Bc[spin].dtype) - for i in range(Db.shape[0]): - absDlcr = abs(Dlcr[i]) - if absDlcr > 1.0: - Db[i] = 1.0 / absDlcr - Ds[i] = numpy.sign(Dlcr[i]) - else: - Db[i] = 1.0 - Ds[i] = Dlcr[i] - - T1inv = scipy.linalg.inv(Tlcr, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("i,ij->ij", Db, Qlcr.conj().T), T1inv) + numpy.diag(Ds) - Cinv = scipy.linalg.inv(C, check_finite=False) - - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) - ) - else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("i,ij->ij", Db, Qlcr.conj().T) - ) - return G - - def greens_function_qr_strat(self, trial, slice_ix=None, inplace=True): - # Use Stratification method (DOI 10.1109/IPDPS.2012.37) - if slice_ix == None: - slice_ix = self.stack.time_slice - - bin_ix = slice_ix // self.stack.nstack - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == self.stack.nbins: - bin_ix = -1 - - if not inplace: - G = numpy.zeros(self.G.shape, self.G.dtype) - else: - G = None - - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in - # stable way. Iteratively construct column pivoted QR decompositions - # (A = QDT) starting from the rightmost (product of) propagator(s). - B = self.stack.get((bin_ix + 1) % self.stack.nbins) - - (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) - # Form D matrices - D1 = numpy.diag(R1.diagonal()) - D1inv = numpy.diag(1.0 / R1.diagonal()) - T1 = numpy.einsum("ii,ij->ij", D1inv, R1) - # permute them - T1[:, P1] = T1[:, range(self.nbasis)] - - for i in range(2, self.stack.nbins + 1): - ix = (bin_ix + i) % self.stack.nbins - B = self.stack.get(ix) - C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) - (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = numpy.diag(1.0 / R1.diagonal()) - D1 = numpy.diag(R1.diagonal()) - tmp = numpy.einsum("ii,ij->ij", D1inv, R1) - tmp[:, P1] = tmp[:, range(self.nbasis)] - T1 = numpy.dot(tmp, T1) - - # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T - # Write D = Db^{-1} Ds - # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T - Db = numpy.zeros(B[spin].shape, B[spin].dtype) - Ds = numpy.zeros(B[spin].shape, B[spin].dtype) - for i in range(Db.shape[0]): - absDlcr = abs(Db[i, i]) - if absDlcr > 1.0: - Db[i, i] = 1.0 / absDlcr - Ds[i, i] = numpy.sign(D1[i, i]) - else: - Db[i, i] = 1.0 - Ds[i, i] = D1[i, i] - - T1inv = scipy.linalg.inv(T1, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("ii,ij->ij", Db, Q1.conj().T), T1inv) + Ds - Cinv = scipy.linalg.inv(C, check_finite=False) - - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - self.G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) - ) - else: - G[spin] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T) - ) - return G - - # For compatibiltiy with BaseWalkers class. - def reortho(self): - pass - - def reortho_batched(self): - pass From 381fab022fcc7b7e7ae826f68297d64f284c060e Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 13 Dec 2023 11:29:23 +0800 Subject: [PATCH 32/84] Test for thermal/propagation matches legacy if we provide the same random auxiliary fields --- ipie/legacy/thermal_propagation/continuous.py | 10 +- .../trial_density_matrices/mean_field.py | 4 +- ipie/thermal/propagation/continuous.py | 290 ------- ipie/thermal/propagation/generic.py | 165 ---- ipie/thermal/propagation/phaseless_base.py | 53 +- ipie/thermal/propagation/planewave.py | 718 ------------------ ipie/thermal/propagation/propagator.py | 4 + .../thermal/propagation/tests/test_generic.py | 204 +++-- .../propagation/tests/test_operations.py | 190 +++++ ipie/thermal/propagation/utils.py | 47 -- ipie/thermal/qmc/thermal_afqmc.py | 460 +++++------ ipie/thermal/qmc/thermal_afqmc_clean.py | 191 ----- ipie/thermal/trial/mean_field.py | 80 +- ipie/thermal/trial/one_body.py | 72 +- ipie/thermal/trial/tests/test_mean_field.py | 69 ++ ipie/thermal/trial/tests/test_one_body.py | 69 ++ ipie/thermal/trial/utils.py | 5 + ipie/thermal/walkers/handler.py | 370 --------- ipie/thermal/walkers/walker.py | 135 ---- 19 files changed, 793 insertions(+), 2343 deletions(-) delete mode 100644 ipie/thermal/propagation/continuous.py delete mode 100644 ipie/thermal/propagation/generic.py delete mode 100644 ipie/thermal/propagation/planewave.py create mode 100644 ipie/thermal/propagation/propagator.py create mode 100644 ipie/thermal/propagation/tests/test_operations.py delete mode 100644 ipie/thermal/propagation/utils.py delete mode 100644 ipie/thermal/qmc/thermal_afqmc_clean.py create mode 100644 ipie/thermal/trial/tests/test_mean_field.py create mode 100644 ipie/thermal/trial/tests/test_one_body.py delete mode 100644 ipie/thermal/walkers/handler.py delete mode 100644 ipie/thermal/walkers/walker.py diff --git a/ipie/legacy/thermal_propagation/continuous.py b/ipie/legacy/thermal_propagation/continuous.py index a97c6dc4..211a3796 100644 --- a/ipie/legacy/thermal_propagation/continuous.py +++ b/ipie/legacy/thermal_propagation/continuous.py @@ -84,7 +84,7 @@ def __init__(self, options, qmc, system, hamiltonian, trial, verbose=False, lowr if verbose: print("# Finished setting up propagator.") - def two_body_propagator(self, walker, system, trial): + def two_body_propagator(self, walker, system, trial, xi=None): r"""Continuous Hubbard-Statonovich transformation. Parameters @@ -97,7 +97,9 @@ def two_body_propagator(self, walker, system, trial): Trial wavefunction object. """ # Normally distrubted auxiliary fields. - xi = numpy.random.normal(0.0, 1.0, system.nfields) + if xi is None: # For debugging. + xi = numpy.random.normal(0.0, 1.0, system.nfields) + if self.force_bias: P = one_rdm_from_G(walker.G) xbar = self.propagator.construct_force_bias(system, P, trial) @@ -206,7 +208,7 @@ def propagate_walker_free(self, system, walker, trial, eshift=0): except ZeroDivisionError: walker.weight = 0.0 - def propagate_walker_phaseless(self, system, walker, trial, eshift=0): + def propagate_walker_phaseless(self, system, walker, trial, eshift=0, xi=None): r"""Propagate walker using phaseless approximation. Uses importance sampling and the hybrid method. @@ -223,7 +225,7 @@ def propagate_walker_phaseless(self, system, walker, trial, eshift=0): Trial wavefunction object. """ - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, system, trial) + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, system, trial, xi=xi) BV = self.exponentiate(VHS) B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) diff --git a/ipie/legacy/trial_density_matrices/mean_field.py b/ipie/legacy/trial_density_matrices/mean_field.py index 233912cf..1fe8e1e2 100644 --- a/ipie/legacy/trial_density_matrices/mean_field.py +++ b/ipie/legacy/trial_density_matrices/mean_field.py @@ -41,7 +41,7 @@ def thermal_hartree_fock(self, system, beta): mu_old = self.mu P = self.P.copy() if self.verbose: - print("# Determining Thermal Hartree--Fock Density Matrix.") + print("# Determining Thermal Hartree-Fock Density Matrix.") for it in range(self.max_macro_it): if self.verbose: print(f"# Macro iteration: {it}") @@ -49,7 +49,7 @@ def thermal_hartree_fock(self, system, beta): rho = numpy.array([scipy.linalg.expm(-dt * HMF[0]), scipy.linalg.expm(-dt * HMF[1])]) if self.find_mu: mu = find_chemical_potential( - system, + system._alt_convention, rho, dt, self.num_bins, diff --git a/ipie/thermal/propagation/continuous.py b/ipie/thermal/propagation/continuous.py deleted file mode 100644 index cfd43a43..00000000 --- a/ipie/thermal/propagation/continuous.py +++ /dev/null @@ -1,290 +0,0 @@ -import cmath -import math - -import numpy -import scipy.sparse.linalg - -from ipie.thermal.estimators.thermal import one_rdm_from_G -from ipie.thermal.propagation.generic import GenericContinuous -from ipie.thermal.propagation.planewave import PlaneWave - - -class Continuous(object): - """Propagator for generic many-electron Hamiltonian. - - Uses continuous HS transformation for exponential of two body operator. - - Parameters - ---------- - options : dict - Propagator input options. - qmc : :class:`pie.qmc.options.QMCOpts` - QMC options. - system : :class:`pie.system.System` - System object. - trial : :class:`pie.trial_wavefunctioin.Trial` - Trial wavefunction object. - verbose : bool - If true print out more information during setup. - """ - - def __init__(self, options, qmc, system, hamiltonian, trial, verbose=False, lowrank=False): - if verbose: - print("# Parsing continuous propagator input options.") - print("# Using continuous Hubbar--Stratonovich transformations.") - - # Input options - self.hs_type = "continuous" - self.exp_nmax = options.get("expansion_order", 6) - - optimised = options.get("optimised", True) - # Derived Attributes - self.dt = qmc.dt - self.sqrt_dt = qmc.dt**0.5 - self.isqrt_dt = 1j * self.sqrt_dt - self.nfb_trig = 0 - self.lowrank = lowrank - - self.propagator = get_continuous_propagator( - system, hamiltonian, trial, qmc, options=options, verbose=verbose - ) - # Mean field shifted one-body propagator - self.mu = hamiltonian.mu - self.propagator.construct_one_body_propagator(hamiltonian, qmc.dt) - - self.BH1 = self.propagator.BH1 - self.BT = trial.dmat - self.BTinv = trial.dmat_inv - self.BT_BP = None - - self.mf_const_fac = cmath.exp(-self.dt * self.propagator.mf_core) - self.nstblz = qmc.nstblz - - self.ebound = (2.0 / self.dt) ** 0.5 - self.mean_local_energy = 0 - self.free_projection = options.get("free_projection", False) - self.force_bias = options.get("force_bias", True) - if self.free_projection: - if verbose: - print("# Using free projection.") - print("# Setting force_bias to False with free projection.") - self.force_bias = options.get("force_bias", False) - self.propagate_walker = self.propagate_walker_free - else: - if verbose: - print("# Using phaseless approximation.") - if self.force_bias: - print(f"# Setting force bias to {self.force_bias!r}.") - self.propagate_walker = self.propagate_walker_phaseless - if verbose: - print("# Finished setting up propagator.") - - def two_body_propagator(self, walker, system, trial): - r"""Continuous Hubbard-Statonovich transformation. - - Parameters - ---------- - walker : :class:`pie.walker.Walker` walker object to be updated. On - output we have acted on phi by B_V(x). - system : :class:`pie.system.System` - System object. - trial : :class:`pie.trial_wavefunctioin.Trial` - Trial wavefunction object. - """ - # Normally distrubted auxiliary fields. - xi = numpy.random.normal(0.0, 1.0, system.nfields) - if self.force_bias: - P = one_rdm_from_G(walker.G) - xbar = self.propagator.construct_force_bias(system, P, trial) - else: - xbar = numpy.zeros(xi.shape, dtype=numpy.complex128) - - for i in range(system.nfields): - if numpy.absolute(xbar[i]) > 1.0: - # if self.nfb_trig < 10: - # print("# Rescaling force bias is triggered") - # print("# Warning will only be printed 10 times on root.") - self.nfb_trig += 1 - xbar[i] /= numpy.absolute(xbar[i]) - # Constant factor arising from shifting the propability distribution. - cfb = xi.dot(xbar) - 0.5 * xbar.dot(xbar) - xshifted = xi - xbar - # Constant factor arising from force bias and mean field shift - cmf = -self.sqrt_dt * xshifted.dot(self.propagator.mf_shift) - - # Operator terms contributing to propagator. - VHS = self.propagator.construct_VHS(system, xshifted) - - return (cmf, cfb, xshifted, VHS) - - def estimate_eshift(self, walker): - return 0.0 - - def exponentiate(self, VHS, debug=False): - """Apply exponential propagator of the HS transformation - Parameters - ---------- - system : - system class - phi : numpy array - a state - VHS : numpy array - HS transformation potential - Returns - ------- - phi : numpy array - Exp(VHS) * phi - """ - # JOONHO: exact exponential - # copy = numpy.copy(phi) - # phi = scipy.linalg.expm(VHS).dot(copy) - phi = numpy.identity(VHS.shape[0], dtype=numpy.complex128) - if debug: - copy = numpy.copy(phi) - c2 = scipy.linalg.expm(VHS).dot(copy) - - Temp = numpy.identity(VHS.shape[0], dtype=numpy.complex128) - - for n in range(1, self.exp_nmax + 1): - Temp = VHS.dot(Temp) / n - phi += Temp - if debug: - print(f"DIFF: {(c2 - phi).sum() / c2.size: 10.8e}") - return phi - - def propagate_walker_free(self, system, walker, trial, eshift=0): - r"""Free projection for continuous HS transformation. - - .. Warning:: - Currently not implemented. - - - Parameters - ---------- - walker : :class:`walker.Walker` - Walker object to be updated. on output we have acted on - :math:`|\phi_i\rangle` by :math:`B` and updated the weight - appropriately. Updates inplace. - state : :class:`state.State` - Simulation state. - """ - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, system, trial) - BV = self.exponentiate(VHS) - - B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) - B = numpy.array([self.BH1[0].dot(B[0]), self.BH1[1].dot(B[1])]) - - # Compute determinant ratio det(1+A')/det(1+A). - # 1. Current walker's green's function. - G = walker.greens_function(trial, inplace=False) - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function(trial, inplace=True) - # 3. Compute det(G/G') - M0 = [ - scipy.linalg.det(G[0], check_finite=False), - scipy.linalg.det(G[1], check_finite=False), - ] - Mnew = [ - scipy.linalg.det(walker.G[0], check_finite=False), - scipy.linalg.det(walker.G[1], check_finite=False), - ] - # Could save M0 rather than recompute. - try: - # Could save M0 rather than recompute. - oratio = (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) - walker.ot = 1.0 - # Constant terms are included in the walker's weight. - (magn, phase) = cmath.polar(cmath.exp(cmf + cfb) * oratio) - walker.weight *= magn - walker.phase *= cmath.exp(1j * phase) - except ZeroDivisionError: - walker.weight = 0.0 - - def propagate_walker_phaseless(self, system, walker, trial, eshift=0): - r"""Propagate walker using phaseless approximation. - - Uses importance sampling and the hybrid method. - - Parameters - ---------- - walker : :class:`walker.Walker` - Walker object to be updated. On output we have acted on phi with the - propagator B(x), and updated the weight appropriately. Updates - inplace. - system : :class:`pie.system.System` - System object. - trial : :class:`pie.trial_wavefunctioin.Trial` - Trial wavefunction object. - """ - - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, system, trial) - BV = self.exponentiate(VHS) - - B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) - B = numpy.array([self.BH1[0].dot(B[0]), self.BH1[1].dot(B[1])]) - - # Compute determinant ratio det(1+A')/det(1+A). - # 1. Current walker's green's function. - tix = walker.stack.ntime_slices - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function(None, slice_ix=tix, inplace=True) - # 3. Compute det(G/G') - M0 = walker.M0 - Mnew = [ - scipy.linalg.det(walker.G[0], check_finite=False), - scipy.linalg.det(walker.G[1], check_finite=False), - ] - try: - # Could save M0 rather than recompute. - oratio = (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) - # Might want to cap this at some point - hybrid_energy = cmath.log(oratio) + cfb + cmf - Q = cmath.exp(hybrid_energy) - expQ = self.mf_const_fac * Q - (magn, phase) = cmath.polar(expQ) - - if not math.isinf(magn): - # Determine cosine phase from Arg(det(1+A'(x))/det(1+A(x))). - # Note this doesn't include exponential factor from shifting - # propability distribution. - dtheta = cmath.phase(cmath.exp(hybrid_energy - cfb)) - cosine_fac = max(0, math.cos(dtheta)) - walker.weight *= magn * cosine_fac - walker.M0 = Mnew - else: - walker.weight = 0.0 - except ZeroDivisionError: - walker.weight = 0.0 - - -def get_continuous_propagator(system, hamiltonian, trial, qmc, options={}, verbose=False): - """Wrapper to select propagator class. - - Parameters - ---------- - options : dict - Propagator input options. - qmc : :class:`pie.qmc.QMCOpts` class - Trial wavefunction input options. - system : class - System class. - trial : class - Trial wavefunction object. - - Returns - ------- - propagator : class or None - Propagator object. - """ - if system.name == "UEG": - propagator = PlaneWave(system, hamiltonian, trial, qmc, options=options, verbose=verbose) - elif system.name == "Generic": - propagator = GenericContinuous( - system, hamiltonian, trial, qmc, options=options, verbose=verbose - ) - else: - propagator = None - - return propagator diff --git a/ipie/thermal/propagation/generic.py b/ipie/thermal/propagation/generic.py deleted file mode 100644 index d2fd0efe..00000000 --- a/ipie/thermal/propagation/generic.py +++ /dev/null @@ -1,165 +0,0 @@ - -import numpy -import scipy.sparse.linalg - -from ipie.thermal.estimators.thermal import one_rdm_from_G - - - -class GenericContinuous(object): - """Propagator for generic many-electron Hamiltonian. - - Uses continuous HS transformation for exponential of two body operator. - - Parameters - ---------- - options : dict - Propagator input options. - qmc : :class:`pie.qmc.options.QMCOpts` - QMC options. - system : :class:`pie.system.System` - System object. - trial : :class:`pie.trial_wavefunctioin.Trial` - Trial wavefunction object. - verbose : bool - If true print out more information during setup. - """ - - def __init__(self, system, hamiltonian, trial, qmc, options={}, verbose=False): - if verbose: - print("# Parsing continuous propagator input options.") - - # Input options - self.hs_type = "continuous" - self.free_projection = options.get("free_projection", False) - if verbose: - print("# Using phaseless approximation: %r" % (not self.free_projection)) - self.exp_nmax = options.get("expansion_order", 6) - self.force_bias = options.get("force_bias", True) - if self.free_projection: - if verbose: - print("# Setting force_bias to False with free projection.") - self.force_bias = False - else: - if verbose: - print(f"# Setting force bias to {self.force_bias!r}.") - - optimised = options.get("optimised", True) - if optimised: - self.construct_force_bias = self.construct_force_bias_fast - self.construct_VHS = self.construct_VHS_fast - else: - self.construct_force_bias = self.construct_force_bias_slow - self.construct_VHS = self.construct_VHS_slow - # Derived Attributes - self.dt = qmc.dt - self.sqrt_dt = qmc.dt**0.5 - self.isqrt_dt = 1j * self.sqrt_dt - self.nfb_trig = 0 - - P = one_rdm_from_G(trial.G) - # Mean field shifts (2,nchol_vec). - self.mf_shift = self.construct_mean_field_shift(hamiltonian, P) - if verbose: - print( - "# Absolute value of maximum component of mean field shift: " - "{:13.8e}.".format(numpy.max(numpy.abs(self.mf_shift))) - ) - - # Mean field shifted one-body propagator - self.mu = options.get("mu", -1.0) - - self.BT = trial.dmat - self.BTinv = trial.dmat_inv - - # Constant core contribution modified by mean field shift. - self.mf_core = hamiltonian.ecore + 0.5 * numpy.dot(self.mf_shift, self.mf_shift) - self.nstblz = qmc.nstblz - - self.ebound = (2.0 / self.dt) ** 0.5 - self.mean_local_energy = 0 - if verbose: - print("# Finished setting up propagator.") - - def construct_mean_field_shift(self, system, P): - if system.sparse: - mf_shift = 1j * P[0].ravel() * system.chol_vecs - mf_shift += 1j * P[1].ravel() * system.chol_vecs - else: - # mf_shift = 1j * numpy.einsum("lpq,spq->l", system.chol_vecs, P) - mf_shift = 1j * numpy.einsum("lpq,spq->l", system.hs_pot, P) - return mf_shift - - def construct_one_body_propagator(self, system, dt): - """Construct mean-field shifted one-body propagator. - - Parameters - ---------- - dt : float - Timestep. - chol_vecs : :class:`numpy.ndarray` - Cholesky vectors. - h1e_mod : :class:`numpy.ndarray` - One-body operator including factor from factorising two-body - Hamiltonian. - """ - if system.sparse: - nb = system.nbasis - shift = 1j * system.hs_pot.dot(self.mf_shift).reshape(nb, nb) - else: - shift = 1j * numpy.einsum("l,lpq->pq", self.mf_shift, system.hs_pot) - I = numpy.identity(system.nbasis, dtype=system.H1.dtype) - muN = self.mu * I - H1 = system.h1e_mod - numpy.array([shift + muN, shift + muN]) - - self.BH1 = numpy.array( - [scipy.linalg.expm(-0.5 * dt * H1[0]), scipy.linalg.expm(-0.5 * dt * H1[1])] - ) - - def construct_force_bias_slow(self, system, P, trial): - r"""Compute optimal force bias. - - Uses explicit expression. - - Parameters - ---------- - G: :class:`numpy.ndarray` - Walker's 1RDM: . - - Returns - ------- - xbar : :class:`numpy.ndarray` - Force bias. - """ - vbias = numpy.einsum("lpq,pq->l", system.hs_pot, P[0]) - vbias += numpy.einsum("lpq,pq->l", system.hs_pot, P[1]) - return -self.sqrt_dt * (1j * vbias - self.mf_shift) - - def construct_force_bias_fast(self, system, P, trial): - r"""Compute optimal force bias. - - Uses explicit expression. - - Parameters - ---------- - G: :class:`numpy.ndarray` - Walker's 1RDM: . - - Returns - ------- - xbar : :class:`numpy.ndarray` - Force bias. - """ - # vbias = P[0].ravel() * system.hs_pot - # vbias += P[1].ravel() * system.hs_pot - vbias = system.chol_vecs.T.dot(P[0].ravel()) - vbias += system.chol_vecs.T.dot(P[1].ravel()) - return -self.sqrt_dt * (1j * vbias - self.mf_shift) - - def construct_VHS_slow(self, system, shifted): - return self.isqrt_dt * numpy.einsum("l,lpq->pq", shifted, system.hs_pot) - - def construct_VHS_fast(self, system, xshifted): - VHS = system.chol_vecs.dot(xshifted) - VHS = VHS.reshape(system.nbasis, system.nbasis) - return self.isqrt_dt * VHS diff --git a/ipie/thermal/propagation/phaseless_base.py b/ipie/thermal/propagation/phaseless_base.py index 55d39d9e..c71c2eb4 100644 --- a/ipie/thermal/propagation/phaseless_base.py +++ b/ipie/thermal/propagation/phaseless_base.py @@ -4,23 +4,26 @@ from abc import abstractmethod from ipie.propagation.continuous_base import ContinuousBase +from ipie.thermal.estimators.thermal import one_rdm_from_G from ipie.thermal.propagation.force_bias import construct_force_bias from ipie.thermal.propagation.operations import apply_exponential from ipie.utils.backend import arraylib as xp from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol -# TODO write test for propagator. +# TODO: Add lowrank implementation. + def construct_mean_field_shift(hamiltonian, trial): r"""Compute mean field shift. .. math:: - \bar{v}_n = \sum_{ik\sigma} v_{(ik),n} G_{ik\sigma} + \bar{v}_n = \sum_{ik\sigma} v_{(ik),n} P_{ik\sigma} """ # hamiltonian.chol has shape (nbasis^2, nchol). - P = (trial.P[0] + trial.P[1]).ravel() + P = one_rdm_from_G(trial.G) + P = (P[0] + P[1]).ravel() tmp_real = numpy.dot(hamiltonian.chol.T, P.real) tmp_imag = numpy.dot(hamiltonian.chol.T, P.imag) mf_shift = 1.0j * tmp_real - tmp_imag @@ -38,6 +41,7 @@ def __init__(self, time_step, mu, lowrank=False, verbose=False): self.nfb_trig = 0 # number of force bias triggered self.ebound = (2.0 / self.dt) ** 0.5 # energy bound range + self.fbbound = 1.0 self.mpi_handler = None self.lowrank = lowrank @@ -71,7 +75,7 @@ def construct_one_body_propagator(self, hamiltonian): Parameters ---------- - hamiltonian : hamiltonian class. + hamiltonian : hamiltonian class Generic hamiltonian object. dt : float Timestep. @@ -86,8 +90,24 @@ def construct_one_body_propagator(self, hamiltonian): return expH1 # Shape (nbasis, nbasis). - def construct_two_body_propagator(self, walkers, hamiltonian, trial): - """Includes `nwalkers`. + def construct_two_body_propagator(self, walkers, hamiltonian, trial, debug=False): + r"""Construct two-body propagator. + + .. math:: + \bar{x}_n &= \sqrt{\Delta\tau} \bar{v}_n \\ + x_\mathrm{shifted}_n &= x_n - \bar{x}_n \\ + C_{MF} &= -\sqrt{\Delta\tau} \sum_{n} x_\mathrm{shifted}_n \bar{v}_n \\ + &= -\sqrt{\Delta\tau} \sum_{n} (x_n - \sqrt{\Delta\tau} \bar{v}_n) \bar{v}_n \\ + &= -\sqrt{\Delta\tau} \sum_{n} x_n \bar{v}_n + \Delta\tau \sum_{n} \bar{v}_n^2. + + Parameters + ---------- + walkers: walker class + UHFThermalWalkers object. + hamiltonian : hamiltonian class + Generic hamiltonian object. + trial : trial class + Trial dnsity matrix. """ # Optimal force bias xbar = xp.zeros((walkers.nwalkers, hamiltonian.nfields)) @@ -96,9 +116,14 @@ def construct_two_body_propagator(self, walkers, hamiltonian, trial): xbar = -self.sqrt_dt * (1j * self.vbias - self.mf_shift) self.timer.tfbias += time.time() - start_time + # Force bias bounding + xbar = self.apply_bound_force_bias(xbar, self.fbbound) + # Normally distrubted auxiliary fields. xi = xp.random.normal(0.0, 1.0, hamiltonian.nfields * walkers.nwalkers).reshape( walkers.nwalkers, hamiltonian.nfields) + + if debug: self.xi = xi # For debugging. xshifted = xi - xbar # Shape (nwalkers, nfields). # Constant factor arising from force bias and mean field shift @@ -116,9 +141,10 @@ def propagate_walkers_one_body(self, walkers): def propagate_walkers_two_body(self, walkers, hamiltonian, trial): pass - def propagate_walkers(self, walkers, hamiltonian, trial, eshift=0.): + def propagate_walkers(self, walkers, hamiltonian, trial, eshift=0., debug=False): start_time = time.time() - cmf, cfb, xshifted, VHS = self.construct_two_body_propagator(walkers, hamiltonian, trial) + cmf, cfb, xshifted, VHS = self.construct_two_body_propagator( + walkers, hamiltonian, trial, debug=debug) assert walkers.nwalkers == xshifted.shape[-1] self.timer.tvhs += time.time() - start_time assert len(VHS.shape) == 3 @@ -128,7 +154,7 @@ def propagate_walkers(self, walkers, hamiltonian, trial, eshift=0.): stack = walkers.stack[iw] BV = apply_exponential(VHS[iw], self.exp_nmax) # Shape (nbasis, nbasis). B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) - B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) + B = numpy.array([self.BH1[0].dot(B[0]), self.BH1[1].dot(B[1])]) # Compute determinant ratio det(1+A')/det(1+A). # 1. Current walker's Green's function. @@ -171,6 +197,15 @@ def update_weight(self, walkers, iw, G, cfb, cmf, eshift): walkers.M0a[iw] = Mnewa walkers.M0b[iw] = Mnewb + def apply_bound_force_bias(self, xbar, max_bound=1.0): + absxbar = xp.abs(xbar) + idx_to_rescale = absxbar > max_bound + nonzeros = absxbar > 1e-13 + xbar_rescaled = xbar.copy() + xbar_rescaled[nonzeros] = xbar_rescaled[nonzeros] / absxbar[nonzeros] + xbar = xp.where(idx_to_rescale, xbar_rescaled, xbar) + self.nfb_trig += xp.sum(idx_to_rescale) + return xbar def apply_bound_hybrid(self, ehyb, eshift): # Shift is a number but ehyb is not # For initial steps until first estimator communication, `eshift` will be diff --git a/ipie/thermal/propagation/planewave.py b/ipie/thermal/propagation/planewave.py deleted file mode 100644 index d8e330b9..00000000 --- a/ipie/thermal/propagation/planewave.py +++ /dev/null @@ -1,718 +0,0 @@ -import cmath -import math - -import numpy -import scipy.sparse.linalg -from scipy.linalg import sqrtm - -from ipie.thermal.estimators.thermal import one_rdm_from_G - - -class PlaneWave(object): - """PlaneWave class""" - - def __init__(self, system, hamiltonian, trial, qmc, options={}, verbose=False, lowrank=False): - self.verbose = verbose - if verbose: - print("# Parsing plane wave propagator input options.") - # Input options - self.hs_type = "plane_wave" - self.free_projection = options.get("free_projection", False) - self.optimised = options.get("optimised", True) - self.lowrank = lowrank - self.exp_nmax = options.get("expansion_order", 6) - self.nstblz = qmc.nstblz - self.fb_bound = options.get("fb_bound", 1.0) - # Derived Attributes - self.dt = qmc.dt - self.sqrt_dt = qmc.dt**0.5 - self.isqrt_dt = 1j * self.sqrt_dt - self.num_vplus = hamiltonian.nfields // 2 - self.mf_shift = self.construct_mf_shift(hamiltonian, trial) - if verbose: - print( - "# Absolute value of maximum component of mean field shift: " - "{:13.8e}.".format(numpy.max(numpy.abs(self.mf_shift))) - ) - if verbose: - print("# Number of fields = %i" % hamiltonian.nfields) - print(f"# Using lowrank propagation: {self.lowrank}") - - self.vbias = numpy.zeros(hamiltonian.nfields, dtype=numpy.complex128) - - # Constant core contribution modified by mean field shift. - mf_core = hamiltonian.ecore - - self.construct_one_body_propagator(hamiltonian, qmc.dt) - - self.BT = trial.dmat - self.BTinv = trial.dmat_inv - - self.mf_const_fac = 1 - - # todo : ? - self.BT_BP = self.BT - self.nstblz = qmc.nstblz - - self.ebound = (2.0 / self.dt) ** 0.5 - self.mean_local_energy = 0 - - # self.propagate_walker_phaseless = self.propagate_walker_phaseless_full_rank - if self.lowrank: - self.propagate_walker_free = self.propagate_walker_phaseless_low_rank - self.propagate_walker_phaseless = self.propagate_walker_phaseless_low_rank - else: - self.propagate_walker_free = self.propagate_walker_free_full_rank - self.propagate_walker_phaseless = self.propagate_walker_phaseless_full_rank - - if self.free_projection: - if verbose: - print("# Using free projection") - self.propagate_walker = self.propagate_walker_free - else: - if verbose: - print("# Using phaseless approximation") - self.propagate_walker = self.propagate_walker_phaseless - if verbose: - print("# Finished setting up propagator.") - self.nfb_trig = False - - def construct_mf_shift(self, hamiltonian, trial): - P = one_rdm_from_G(trial.G) - P = P.reshape(2, hamiltonian.nbasis * hamiltonian.nbasis) - mf_shift = numpy.zeros(hamiltonian.nfields, numpy.complex128) - mf_shift[: self.num_vplus] = P[0].T * hamiltonian.iA + P[1].T * hamiltonian.iA - mf_shift[self.num_vplus :] = P[0].T * hamiltonian.iB + P[1].T * hamiltonian.iB - return mf_shift - - def construct_one_body_propagator(self, hamiltonian, dt): - """Construct the one-body propagator Exp(-dt/2 H0) - Parameters - ---------- - hamiltonian : - hamiltonian class - dt : float - time-step - Returns - ------- - self.BH1 : numpy array - Exp(-dt/2 H0) - """ - H1 = hamiltonian.h1e_mod - I = numpy.identity(H1[0].shape[0], dtype=H1.dtype) - print(f"hamiltonian.mu = {hamiltonian.mu}") - # No spin dependence for the moment. - self.BH1 = numpy.array( - [ - scipy.linalg.expm(-0.5 * dt * H1[0] + 0.5 * dt * hamiltonian.mu * I), - scipy.linalg.expm(-0.5 * dt * H1[1] + 0.5 * dt * hamiltonian.mu * I), - ] - ) - - def two_body_potentials(self, hamiltonian, iq): - """Calculatate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q - Parameters - ---------- - hamiltonian : - hamiltonian class - q : float - a plane-wave vector - Returns - ------- - iA : numpy array - Eq.(13a) - iB : numpy array - Eq.(13b) - """ - rho_q = hamiltonian.density_operator(iq) - qscaled = hamiltonian.kfac * hamiltonian.qvecs[iq] - - # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol - piovol = math.pi / (hamiltonian.vol) - factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 - - # JOONHO: include a factor of 1j - iA = 1j * factor * (rho_q + rho_q.getH()) - iB = -factor * (rho_q - rho_q.getH()) - return (iA, iB) - - def construct_force_bias(self, hamiltonian, G): - """Compute the force bias term as in Eq.(33) of DOI:10.1002/wcms.1364 - Parameters - ---------- - hamiltonian : - hamiltonian class - G : numpy array - Green's function - Returns - ------- - force bias : numpy array - -sqrt(dt) * vbias - """ - for i, qi in enumerate(hamiltonian.qvecs): - (iA, iB) = self.two_body_potentials(hamiltonian, i) - # Deal with spin more gracefully - self.vbias[i] = iA.dot(G[0]).diagonal().sum() + iA.dot(G[1]).diagonal().sum() - self.vbias[i + self.num_vplus] = ( - iB.dot(G[0]).diagonal().sum() + iB.dot(G[1]).diagonal().sum() - ) - return -self.sqrt_dt * self.vbias - - def construct_VHS_outofcore(self, hamiltonian, xshifted): - """Construct the one body potential from the HS transformation - Parameters - ---------- - hamiltonian : - hamiltonian class - xshifted : numpy array - shifited auxiliary field - Returns - ------- - VHS : numpy array - the HS potential - """ - VHS = numpy.zeros((hamiltonian.nbasis, hamiltonian.nbasis), dtype=numpy.complex128) - - for i, qi in enumerate(hamiltonian.qvecs): - (iA, iB) = self.two_body_potentials(hamiltonian, i) - VHS = VHS + (xshifted[i] * iA).todense() - VHS = VHS + (xshifted[i + self.num_vplus] * iB).todense() - return VHS * self.sqrt_dt - - def construct_VHS_incore(self, hamiltonian, xshifted): - """Construct the one body potential from the HS transformation - Parameters - ---------- - hamiltonian : - hamiltonian class - xshifted : numpy array - shifited auxiliary field - Returns - ------- - VHS : numpy array - the HS potential - """ - VHS = numpy.zeros((hamiltonian.nbasis, hamiltonian.nbasis), dtype=numpy.complex128) - VHS = ( - hamiltonian.iA * xshifted[: self.num_vplus] - + hamiltonian.iB * xshifted[self.num_vplus :] - ) - VHS = VHS.reshape(hamiltonian.nbasis, hamiltonian.nbasis) - return VHS * self.sqrt_dt - - def construct_force_bias_incore(self, hamiltonian, G): - """Compute the force bias term as in Eq.(33) of DOI:10.1002/wcms.1364 - Parameters - ---------- - hamiltonian : - hamiltonian class - G : numpy array - Green's function - Returns - ------- - force bias : numpy array - -sqrt(dt) * vbias - """ - Gvec = G.reshape(2, hamiltonian.nbasis * hamiltonian.nbasis) - self.vbias[: self.num_vplus] = Gvec[0].T * hamiltonian.iA + Gvec[1].T * hamiltonian.iA - self.vbias[self.num_vplus :] = Gvec[0].T * hamiltonian.iB + Gvec[1].T * hamiltonian.iB - return -self.sqrt_dt * self.vbias - - def propagate_greens_function(self, walker, B, Binv): - if walker.stack.time_slice < walker.stack.ntime_slices: - walker.G[0] = B[0].dot(walker.G[0]).dot(Binv[0]) - walker.G[1] = B[1].dot(walker.G[1]).dot(Binv[1]) - - def two_body_propagator(self, walker, hamiltonian, force_bias=True): - """It appliese the two-body propagator - Parameters - ---------- - walker : - walker class - hamiltonian : - hamiltonian class - fb : boolean - wheter to use force bias - Returns - ------- - cxf : float - the constant factor arises from mean-field shift (hard-coded for UEG for now) - cfb : float - the constant factor arises from the force-bias - xshifted : numpy array - shifited auxiliary field - """ - - # Normally distrubted auxiliary fields. - xi = numpy.random.normal(0.0, 1.0, hamiltonian.nfields) - - # Optimal force bias. - xbar = numpy.zeros(hamiltonian.nfields) - if force_bias: - rdm = one_rdm_from_G(walker.G) - xbar = self.construct_force_bias_incore(hamiltonian, rdm) - - for i in range(hamiltonian.nfields): - if numpy.absolute(xbar[i]) > self.fb_bound: - if not self.nfb_trig and self.verbose: - print("# Rescaling force bias is triggered.") - print("# Warning will only be printed once per thread.") - print(f"# Bound = {self.fb_bound}") - xb = (xbar[i].real, xbar[i].imag) - vb = abs(xbar[i]) / self.sqrt_dt - vb = (vb.real, vb.imag) - print("XBAR: (%f,%f)" % xb) - print(": (%f,%f)" % vb) - self.nfb_trig = True - walker.rescaled_fb = True - xbar[i] /= numpy.absolute(xbar[i]) - - xshifted = xi - xbar - - # Constant factors: Note they are not exponentiated. - # Constant factor arising from force bias and mean field shift - cmf = -self.sqrt_dt * xshifted.dot(self.mf_shift) - # Constant factor arising from shifting the propability distribution. - cfb = xi.dot(xbar) - 0.5 * xbar.dot(xbar) - - # print(xbar.dot(xbar)) - - # Operator terms contributing to propagator. - VHS = self.construct_VHS_incore(hamiltonian, xshifted) - - return (cmf, cfb, xshifted, VHS) - - def exponentiate(self, VHS, debug=False): - """Apply exponential propagator of the HS transformation - Parameters - ---------- - system : - system class - phi : numpy array - a state - VHS : numpy array - HS transformation potential - Returns - ------- - phi : numpy array - Exp(VHS) * phi - """ - # JOONHO: exact exponential - # copy = numpy.copy(phi) - # phi = scipy.linalg.expm(VHS).dot(copy) - phi = numpy.identity(VHS.shape[0], dtype=numpy.complex128) - if debug: - copy = numpy.copy(phi) - c2 = scipy.linalg.expm(VHS).dot(copy) - - Temp = numpy.identity(VHS.shape[0], dtype=numpy.complex128) - - for n in range(1, self.exp_nmax + 1): - Temp = VHS.dot(Temp) / n - phi += Temp - if debug: - print(f"DIFF: {(c2 - phi).sum() / c2.size: 10.8e}") - return phi - - def estimate_eshift(self, walker): - return 0.0 - - def propagate_walker_free_full_rank( - self, system, hamiltonian, walker, trial, eshift=0, force_bias=False - ): - """Free projection propagator - Parameters - ---------- - walker : - walker class - system : - system class - trial : - trial wavefunction class - Returns - ------- - """ - - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator( - walker, hamiltonian, force_bias=force_bias - ) - BV = self.exponentiate(VHS) # could use a power-series method to build this - - B = numpy.array( - [ - numpy.einsum("ij,jj->ij", BV, self.BH1[0]), - numpy.einsum("ij,jj->ij", BV, self.BH1[1]), - ] - ) - B = numpy.array( - [ - numpy.einsum("ii,ij->ij", self.BH1[0], B[0]), - numpy.einsum("ii,ij->ij", self.BH1[1], B[1]), - ] - ) - - # Compute determinant ratio det(1+A')/det(1+A). - if self.optimised: - icur = walker.stack.time_slice // walker.stack.stack_size - inext = (walker.stack.time_slice + 1) // walker.stack.stack_size - if walker.stack.counter == 0: - walker.compute_left_right(icur) - # 1. Current walker's green's function. - # Green's function that takes Left Right and Center - G = walker.greens_function_left_right_no_truncation(icur, inplace=False) - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function_left_right_no_truncation(icur, inplace=True) - else: - # Compute determinant ratio det(1+A')/det(1+A). - # 1. Current walker's green's function. - G = walker.greens_function(None, slice_ix=walker.stack.ntime_slices, inplace=False) - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function(None, slice_ix=walker.stack.ntime_slices, inplace=True) - - # 3. Compute det(G/G') - M0 = numpy.array( - [ - scipy.linalg.det(G[0], check_finite=False), - scipy.linalg.det(G[1], check_finite=False), - ] - ) - Mnew = numpy.array( - [ - scipy.linalg.det(walker.G[0], check_finite=False), - scipy.linalg.det(walker.G[1], check_finite=False), - ] - ) - - try: - # Could save M0 rather than recompute. - oratio = (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) - - walker.ot = 1.0 - # Constant terms are included in the walker's weight. - (magn, phase) = cmath.polar(cmath.exp(cmf + cfb) * oratio) - walker.weight *= magn - walker.phase *= cmath.exp(1j * phase) - except ZeroDivisionError: - walker.weight = 0.0 - - def propagate_walker_free_low_rank(self, system, walker, trial, eshift=0, force_bias=False): - """Free projection propagator - Parameters - ---------- - walker : - walker class - system : - system class - trial : - trial wavefunction class - Returns - ------- - """ - - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator( - walker, hamiltonian, force_bias=force_bias - ) - BV = self.exponentiate(VHS) # could use a power-series method to build this - - B = numpy.array( - [ - numpy.einsum("ij,jj->ij", BV, self.BH1[0]), - numpy.einsum("ij,jj->ij", BV, self.BH1[1]), - ] - ) - B = numpy.array( - [ - numpy.einsum("ii,ij->ij", self.BH1[0], B[0]), - numpy.einsum("ii,ij->ij", self.BH1[1], B[1]), - ] - ) - - # Compute determinant ratio det(1+A')/det(1+A). - if self.optimised: - icur = walker.stack.time_slice // walker.stack.stack_size - inext = (walker.stack.time_slice + 1) // walker.stack.stack_size - if walker.stack.counter == 0: - walker.compute_left_right(icur) - # 1. Current walker's green's function. - # Green's function that takes Left Right and Center - G = walker.greens_function_left_right_no_truncation(icur, inplace=False) - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function_left_right_no_truncation(icur, inplace=True) - else: - # Compute determinant ratio det(1+A')/det(1+A). - # 1. Current walker's green's function. - tix = walker.stack.ntime_slices - G = walker.greens_function(None, slice_ix=tix, inplace=False) - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function(None, slice_ix=tix, inplace=True) - - ovlp = numpy.asarray(walker.stack.ovlp).copy() - walker.stack.update_new(B) - ovlp_new = numpy.asarray(walker.stack.ovlp).copy() - walker.G = walker.stack.G.copy() - - try: - # Could save M0 rather than recompute. - oratio = (ovlp_new[0] * ovlp_new[1]) / (ovlp[0] * ovlp[1]) - - walker.ot = 1.0 - # Constant terms are included in the walker's weight. - (magn, phase) = cmath.polar(cmath.exp(cmf + cfb) * oratio) - walker.weight *= magn - walker.phase *= cmath.exp(1j * phase) - except ZeroDivisionError: - walker.weight = 0.0 - - def propagate_walker_phaseless_full_rank(self, hamiltonian, walker, trial, eshift=0): - # """Phaseless propagator - # Parameters - # ---------- - # walker : - # walker class - # system : - # system class - # trial : - # trial wavefunction class - # Returns - # ------- - # """ - - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, hamiltonian, True) - BV = self.exponentiate(VHS) # could use a power-series method to build this - - B = numpy.array( - [ - numpy.einsum("ij,jj->ij", BV, self.BH1[0]), - numpy.einsum("ij,jj->ij", BV, self.BH1[1]), - ] - ) - B = numpy.array( - [ - numpy.einsum("ii,ij->ij", self.BH1[0], B[0]), - numpy.einsum("ii,ij->ij", self.BH1[1], B[1]), - ] - ) - if self.optimised: - icur = walker.stack.time_slice // walker.stack.stack_size - inext = (walker.stack.time_slice + 1) // walker.stack.stack_size - if walker.stack.counter == 0: - walker.compute_left_right(icur) - # 1. Current walker's green's function. - # Green's function that takes Left Right and Center - # print("walker.stack.G (before) = ", walker.G) - G = walker.greens_function_left_right_no_truncation(icur, inplace=False) - # print("G (before) = ", G) - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function_left_right_no_truncation(icur, inplace=True) - # print("G (after) = ", walker.G) - else: - # Compute determinant ratio det(1+A')/det(1+A). - # 1. Current walker's green's function. - tix = walker.stack.ntime_slices - G = walker.greens_function(None, slice_ix=tix, inplace=False) - # 2. Compute updated green's function. - walker.stack.update_new(B) - walker.greens_function(None, slice_ix=tix, inplace=True) - - # 3. Compute det(G/G') - M0 = walker.M0 - Mnew = numpy.array( - [ - scipy.linalg.det(walker.G[0], check_finite=False), - scipy.linalg.det(walker.G[1], check_finite=False), - ] - ) - - # Could save M0 rather than recompute. - try: - oratio = (M0[0] * M0[1]) / (Mnew[0] * Mnew[1]) - # Might want to cap this at some point - hybrid_energy = cmath.log(oratio) + cfb + cmf - Q = cmath.exp(hybrid_energy) - expQ = self.mf_const_fac * Q - (magn, phase) = cmath.polar(expQ) - if not math.isinf(magn): - # Determine cosine phase from Arg(det(1+A'(x))/det(1+A(x))). - # Note this doesn't include exponential factor from shifting - # propability distribution. - dtheta = cmath.phase(cmath.exp(hybrid_energy - cfb)) - cosine_fac = max(0, math.cos(dtheta)) - walker.weight *= magn * cosine_fac - walker.M0 = Mnew - else: - walker.weight = 0.0 - except ZeroDivisionError: - walker.weight = 0.0 - - def propagate_walker_phaseless_low_rank(self, hamiltonian, walker, trial, eshift=0): - # """Phaseless propagator - # Parameters - # ---------- - # walker : - # walker class - # system : - # system class - # trial : - # trial wavefunction class - # Returns - # ------- - # """ - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, hamiltonian, True) - BV = self.exponentiate(VHS) # could use a power-series method to build this - - B = numpy.array( - [ - numpy.einsum("ij,jj->ij", BV, self.BH1[0]), - numpy.einsum("ij,jj->ij", BV, self.BH1[1]), - ] - ) - B = numpy.array( - [ - numpy.einsum("ii,ij->ij", self.BH1[0], B[0]), - numpy.einsum("ii,ij->ij", self.BH1[1], B[1]), - ] - ) - - icur = walker.stack.time_slice // walker.stack.stack_size - # - # local index within a stack = walker.stack.counter - # global stack index = icur - ovlp = numpy.asarray(walker.stack.ovlp).copy() - walker.stack.update_new(B) - ovlp_new = numpy.asarray(walker.stack.ovlp).copy() - walker.G = walker.stack.G.copy() - - # Could save M0 rather than recompute. - try: - oratio = (ovlp_new[0] * ovlp_new[1]) / (ovlp[0] * ovlp[1]) - # Might want to cap this at some point - hybrid_energy = cmath.log(oratio) + cfb + cmf - Q = cmath.exp(hybrid_energy) - expQ = self.mf_const_fac * Q - (magn, phase) = cmath.polar(expQ) - if not math.isinf(magn): - # Determine cosine phase from Arg(det(1+A'(x))/det(1+A(x))). - # Note this doesn't include exponential factor from shifting - # propability distribution. - dtheta = cmath.phase(cmath.exp(hybrid_energy - cfb)) - cosine_fac = max(0, math.cos(dtheta)) - walker.weight *= magn * cosine_fac - # walker.M0 = Mnew - walker.M0 = ovlp_new - else: - walker.weight = 0.0 - except ZeroDivisionError: - walker.weight = 0.0 - - def propagate_greens_function(self, walker): - if walker.stack.time_slice < walker.stack.ntime_slices: - walker.G[0] = self.BT[0].dot(walker.G[0]).dot(self.BTinv[0]) - walker.G[1] = self.BT[1].dot(walker.G[1]).dot(self.BTinv[1]) - - -def unit_test(): - import cProfile - - from ipie.legacy.estimators.pw_fft import local_energy_pw_fft - from ipie.legacy.estimators.ueg import local_energy_ueg - from ipie.legacy.qmc.options import QMCOpts - from ipie.legacy.systems.ueg import UEG - from ipie.legacy.trial_density_matrices.onebody import OneBody - from ipie.legacy.walkers.thermal import ThermalWalker - from ipie.qmc.comm import FakeComm - from ipie.legacy.systems.pw_fft import PW_FFT - - beta = 16.0 - dt = 0.005 - - # beta = 0.5 - # dt = 0.05 - - lowrank = True - # lowrank = False - - stack_size = 10 - - ecuts = [4.0, 8.0, 10.0, 12.0, 16.0, 21.0, 21.5, 32.0] - for ecut in ecuts: - inputs = { - "nup": 33, - "ndown": 33, - "thermal": True, - "beta": beta, - "rs": 1.0, - "ecut": ecut, - "dt": dt, - "nwalkers": 10, - "lowrank": lowrank, - "stack_size": stack_size, - } - - system = UEG(inputs, True) - - qmc = QMCOpts(inputs, system, True) - - comm = FakeComm() - - trial = OneBody(comm, system, beta, dt, options=inputs, verbose=True) - - propagator = PlaneWave(system, trial, qmc, inputs, True) - - walker = ThermalWalker( - {"stack_size": trial.stack_size, "low_rank": lowrank}, - system, - trial, - verbose=True, - ) - eshift = 0.0 + 0.0j - - numpy.random.seed(7) - - pr = cProfile.Profile() - pr.enable() - for ts in range(0, walker.num_slices): - propagator.propagate_walker_phaseless( - walker=walker, system=system, trial=trial, eshift=eshift - ) - - if lowrank: - system = PW_FFT(inputs, False) - sort_basis = numpy.argsort(numpy.diag(system.H1[0]), kind="mergesort") - inv_sort_basis = numpy.zeros_like(sort_basis) - - for i, idx in enumerate(sort_basis): - inv_sort_basis[idx] = i - - mT = walker.stack.mT - Ctrial = numpy.zeros((system.nbasis, walker.stack.mT * 2), dtype=numpy.complex128) - Ctrial[:, :mT] = walker.stack.CT[0][:, :mT] - Ctrial[:, mT:] = walker.stack.CT[1][:, :mT] - - P = one_rdm_from_G(walker.G) - # Ptmp = Ctrial[:,:mT].conj().dot(walker.stack.theta[0,:mT,:]) - - # Reorder to FFT - P[:, :, :] = P[:, inv_sort_basis, :] - P[:, :, :] = P[:, :, inv_sort_basis] - Theta = walker.stack.theta[:, :mT, :] - Theta[:, :, :] = Theta[:, :, inv_sort_basis] - Ctrial = Ctrial[inv_sort_basis, :] - - print(f"E = {local_energy_pw_fft(system, G=P, Ghalf=Theta, trial=Ctrial)}") - else: - P = one_rdm_from_G(walker.G) - print(numpy.diag(walker.G[0].real)) - print(f"weight = {walker.weight}") - print(f"E = {local_energy_ueg(system, P)}") - - pr.disable() - pr.print_stats(sort="tottime") - - -if __name__ == "__main__": - unit_test() diff --git a/ipie/thermal/propagation/propagator.py b/ipie/thermal/propagation/propagator.py new file mode 100644 index 00000000..298b2190 --- /dev/null +++ b/ipie/thermal/propagation/propagator.py @@ -0,0 +1,4 @@ +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric + +Propagator = {GenericRealChol: PhaselessGeneric, GenericComplexChol: PhaselessGeneric} diff --git a/ipie/thermal/propagation/tests/test_generic.py b/ipie/thermal/propagation/tests/test_generic.py index 2b8a3d4a..901af72f 100644 --- a/ipie/thermal/propagation/tests/test_generic.py +++ b/ipie/thermal/propagation/tests/test_generic.py @@ -1,6 +1,5 @@ import numpy import pytest -import h5py from pyscf import gto, scf, lo from ipie.qmc.options import QMCOpts @@ -8,6 +7,7 @@ from ipie.systems.generic import Generic from ipie.hamiltonians.utils import get_hamiltonian from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.trial.one_body import OneBody from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric from ipie.thermal.estimators.generic import local_energy_generic_cholesky @@ -15,21 +15,24 @@ from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody from ipie.legacy.walkers.thermal import ThermalWalker from ipie.legacy.thermal_propagation.continuous import Continuous from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator): - for walker in legacy_walkers: +def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator, xi=None): + if xi is None: + xi = [None] * legacy_walkers.nwalker + + for iw, walker in enumerate(legacy_walkers): legacy_propagator.propagate_walker_phaseless( - legacy_hamiltonian, walker, legacy_trial) + legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) return legacy_walkers - -def test_phaseless_generic_propagator(): +def setup_objs(mf_trial=False, seed=None): nocca = 5 noccb = 5 nelec = nocca + noccb @@ -40,36 +43,21 @@ def test_phaseless_generic_propagator(): unit='Bohr', verbose=5) - mf = scf.UHF(mol).run() - mf.chkfile = 'scf.chk' - mo1 = mf.stability()[0] - dm1 = mf.make_rdm1(mo1, mf.mo_occ) - mf = mf.run(dm1) - mf.stability(return_status=True) - s1e = mol.intor("int1e_ovlp_sph") - ao_coeff = lo.orth.lowdin(s1e) - - path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" - with h5py.File(path + "reference_data/generic_integrals.h5", "r") as fa: - Lxmn = fa["LXmn"][:] - nchol = Lxmn.shape[0] - nbasis = Lxmn.shape[1] - mu = -10. beta = 0.1 dt = 0.01 - nwalkers = 1 - seed = 7 + nwalkers = 5 numpy.random.seed(seed) blocks = 10 stabilise_freq = 10 pop_control_freq = 1 nsteps = 1 - nslice = 5 + nslice = 3 lowrank = False verbose = True + path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" options = { "qmc": { "dt": dt, @@ -108,7 +96,11 @@ def test_phaseless_generic_propagator(): print('----------------------------') system = Generic(mol.nelec, verbose=verbose) hamiltonian = get_hamiltonian(system, options["hamiltonian"]) - trial = MeanField(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + trial = OneBody(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + + if mf_trial: + trial = MeanField(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + nbasis = trial.dmat.shape[-1] walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, verbose=verbose) @@ -121,7 +113,6 @@ def test_phaseless_generic_propagator(): print('------------------------------') legacy_system = Generic(mol.nelec, verbose=verbose) legacy_system.mu = mu - legacy_hamiltonian = LegacyHamGeneric( h1e=hamiltonian.H1, chol=hamiltonian.chol, @@ -132,9 +123,12 @@ def test_phaseless_generic_propagator(): (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] legacy_hamiltonian.mu = options["hamiltonian"]["mu"] - - legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, dt, - verbose=verbose) + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, dt, + verbose=verbose) + if mf_trial: + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, dt, + verbose=verbose) + legacy_walkers = [ ThermalWalker( legacy_system, legacy_hamiltonian, legacy_trial, @@ -145,23 +139,124 @@ def test_phaseless_generic_propagator(): qmc_opts.ntot_walkers = nwalkers qmc_opts.beta = beta qmc_opts.nsteps = nsteps - + qmc_opts.dt = dt + qmc_opts.seed = seed + legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) legacy_propagator = Continuous( options["propagator"], qmc_opts, legacy_system, - legacy_hamiltonian,legacy_trial, verbose=verbose, + legacy_hamiltonian, legacy_trial, verbose=verbose, lowrank=lowrank) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator} + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers, + 'propagator': legacy_propagator} + + return objs, legacy_objs - for t in range(nslice): - propagator.propagate_walkers(walkers, hamiltonian, trial) - legacy_walkers = legacy_propagate_walkers( - legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator) - legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + +def test_mf_shift(verbose=False): + seed = 7 + objs, legacy_objs = setup_objs(seed=seed) + propagator = objs['propagator'] + legacy_propagator = legacy_objs['propagator'] + + if verbose: + print(f'\nlegacy_mf_shift = \n{legacy_propagator.propagator.mf_shift}\n') + print(f'mf_shift = \n{propagator.mf_shift}\n') + + numpy.testing.assert_almost_equal(legacy_propagator.propagator.mf_shift, + propagator.mf_shift, decimal=10) + +def test_BH1(verbose=False): + seed = 7 + objs, legacy_objs = setup_objs(seed=seed) + propagator = objs['propagator'] + legacy_propagator = legacy_objs['propagator'] + + if verbose: + print(f'\nlegacy_BH1 = \n{legacy_propagator.propagator.BH1}\n') + print(f'BH1 = \n{propagator.BH1}\n') + + numpy.testing.assert_almost_equal(legacy_propagator.propagator.BH1, + propagator.BH1, decimal=10) + + +def test_construct_two_body_propagator(verbose=False): + seed = 7 + objs, legacy_objs = setup_objs(seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + cmf, cfb, xshifted, VHS = propagator.construct_two_body_propagator( + walkers, hamiltonian, trial) + + legacy_cmf = [] + legacy_cfb = [] + legacy_xshifted = [] + legacy_VHS = [] + + for iw in range(walkers.nwalkers): + _cmf, _cfb, _xshifted, _VHS = legacy_propagator.two_body_propagator( + legacy_walkers[iw], legacy_hamiltonian, + legacy_trial, xi=propagator.xi[iw]) + legacy_cmf.append(_cmf) + legacy_cfb.append(_cfb) + legacy_xshifted.append(_xshifted) + legacy_VHS.append(_VHS) + + legacy_xshifted = numpy.array(legacy_xshifted).T + + if verbose: + print(f'\nlegacy_cmf = {legacy_cmf}') + print(f'cmf = {cmf}') + + print(f'\nlegacy_cfb = {legacy_cfb}') + print(f'cfb = {cfb}') + + print(f'\nlegacy_xshifted = \n{legacy_xshifted}\n') + print(f'xshifted = \n{xshifted}\n') - # Check. - for iw in range(nwalkers): + print(f'legacy_VHS = \n{legacy_VHS}\n') + print(f'VHS = \n{VHS}\n') + + numpy.testing.assert_almost_equal(legacy_cmf, cmf, decimal=10) + numpy.testing.assert_almost_equal(legacy_cfb, cfb, decimal=10) + numpy.testing.assert_almost_equal(legacy_xshifted, xshifted, decimal=10) + numpy.testing.assert_almost_equal(legacy_VHS, VHS, decimal=10) + + +def test_phaseless_generic_propagator(mf_trial=False, verbose=False): + seed = 7 + objs, legacy_objs = setup_objs(mf_trial=mf_trial, seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + for t in range(walkers.stack[0].nslice): + for iw in range(walkers.nwalkers): P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) eloc = local_energy_generic_cholesky(hamiltonian, P) @@ -170,19 +265,30 @@ def test_phaseless_generic_propagator(): (hamiltonian.nchol, hamiltonian.nbasis**2)).T legacy_eloc = legacy_local_energy_generic_cholesky( legacy_system, legacy_hamiltonian, legacy_P) + legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - print(f'\nt = {t}') - print(f'iw = {iw}') - print(f'eloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') + if verbose: + print(f'\nt = {t}') + print(f'iw = {iw}') + print(f'eloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') - #numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) - #numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) - #numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) - #numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) - #numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_P, P, decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, xi=propagator.xi) if __name__ == "__main__": - test_phaseless_generic_propagator() + #test_mf_shift(verbose=True) + #test_BH1(verbose=True) + #test_construct_two_body_propagator(verbose=True) + test_phaseless_generic_propagator(mf_trial=True, verbose=True) diff --git a/ipie/thermal/propagation/tests/test_operations.py b/ipie/thermal/propagation/tests/test_operations.py new file mode 100644 index 00000000..2fdc14ba --- /dev/null +++ b/ipie/thermal/propagation/tests/test_operations.py @@ -0,0 +1,190 @@ +import numpy +import pytest + +from pyscf import gto, scf, lo +from ipie.qmc.options import QMCOpts + +from ipie.systems.generic import Generic +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.operations import apply_exponential +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric + +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.thermal import ThermalWalker +from ipie.legacy.thermal_propagation.continuous import Continuous + +def setup_objs(mf_trial=False, seed=None): + nocca = 5 + noccb = 5 + nelec = nocca + noccb + r0 = 1.75 + mol = gto.M( + atom=[("H", i * r0, 0, 0) for i in range(nelec)], + basis='sto-6g', + unit='Bohr', + verbose=5) + + mu = -10. + beta = 0.1 + dt = 0.01 + nwalkers = 5 + numpy.random.seed(seed) + blocks = 10 + stabilise_freq = 10 + pop_control_freq = 1 + nsteps = 1 + nslice = 3 + + lowrank = False + verbose = True + + path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" + options = { + "qmc": { + "dt": dt, + "nwalkers": nwalkers, + "blocks": blocks, + "nsteps": nsteps, + "beta": beta, + "rng_seed": seed, + "pop_control_freq": pop_control_freq, + "stabilise_freq": stabilise_freq, + "batched": False + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank + + }, + + "hamiltonian": { + "name": "Generic", + "integrals": path + "reference_data/generic_integrals.h5", + "_alt_convention": False, + "symmetry": False, + "sparse": False, + "mu": mu + }, + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + system = Generic(mol.nelec, verbose=verbose) + hamiltonian = get_hamiltonian(system, options["hamiltonian"]) + trial = OneBody(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + + if mf_trial: + trial = MeanField(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + + nbasis = trial.dmat.shape[-1] + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + propagator = PhaselessGeneric(dt, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_system = Generic(mol.nelec, verbose=verbose) + legacy_system.mu = mu + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore, + options=options["hamiltonian"]) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, dt, + verbose=verbose) + if mf_trial: + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, dt, + verbose=verbose) + + legacy_walkers = [ + ThermalWalker( + legacy_system, legacy_hamiltonian, legacy_trial, + walker_opts=options, verbose=i == 0) for i in range(nwalkers)] + + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps + qmc_opts.dt = dt + qmc_opts.seed = seed + + legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_propagator = Continuous( + options["propagator"], qmc_opts, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose, + lowrank=lowrank) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator} + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers, + 'propagator': legacy_propagator} + + return objs, legacy_objs + + +def test_apply_exponential(verbose=False): + seed = 7 + objs, legacy_objs = setup_objs(seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + _, _, _, VHS = propagator.construct_two_body_propagator(walkers, hamiltonian, trial, debug=True) + + exp = [] + legacy_exp = [] + for iw in range(walkers.nwalkers): + _, _, _, _VHS = legacy_propagator.two_body_propagator( + legacy_walkers[iw], legacy_hamiltonian, + legacy_trial, xi=propagator.xi[iw]) + _exp = apply_exponential(VHS[iw], propagator.exp_nmax) + _legacy_exp = legacy_propagator.exponentiate(_VHS, debug=True) + exp.append(_exp) + legacy_exp.append(_legacy_exp) + + exp = numpy.array(exp) + legacy_exp = numpy.array(legacy_exp) + + if verbose: + print(f'\nexp_nmax = {propagator.exp_nmax}') + print(f'legacy_exp = \n{legacy_exp}\n') + print(f'exp = \n{exp}\n') + + numpy.testing.assert_almost_equal(legacy_exp, exp, decimal=10) + + +if __name__ == "__main__": + test_apply_exponential(verbose=True) diff --git a/ipie/thermal/propagation/utils.py b/ipie/thermal/propagation/utils.py deleted file mode 100644 index 59959cbd..00000000 --- a/ipie/thermal/propagation/utils.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Routines for performing propagation of a walker""" - -from ipie.thermal.propagation.continuous import Continuous -from ipie.thermal.propagation.planewave import PlaneWave - - -def get_propagator(options, qmc, system, hamiltonian, trial, verbose=False, lowrank=False): - """Wrapper to select propagator class. - - Parameters - ---------- - options : dict - Propagator input options. - qmc : :class:`pie.qmc.QMCOpts` class - Trial wavefunction input options. - system : class - System class. - trial : class - Trial wavefunction object. - - Returns - ------- - propagator : class or None - Propagator object. - """ - if hamiltonian.name == "UEG": - propagator = PlaneWave( - system, - hamiltonian, - trial, - qmc, - options=options, - verbose=verbose, - lowrank=lowrank, - ) - else: - propagator = Continuous( - options, - qmc, - system, - hamiltonian, - trial, - verbose=verbose, - lowrank=lowrank, - ) - - return propagator diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index 987a76d2..a1e01522 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -1,267 +1,136 @@ """Driver to perform AFQMC calculation""" import time import uuid +from typing import Dict, Optional, Tuple -from ipie.thermal.estimators.estimators import Estimators -from ipie.thermal.estimators.local_energy import local_energy -from ipie.hamiltonians.utils import get_hamiltonian -from ipie.thermal.propagation.utils import get_propagator -from ipie.thermal.trial.utils import get_trial_density_matrix -from ipie.thermal.walkers.handler import Walkers -from ipie.qmc.options import QMCOpts +from ipie.thermal.propagation.propagator import Propagator +from ipie.thermal.walkers import UHFThermalWalkers +from ipie.thermal.qmc.options import ThermalQMCParams +from ipie.qmc.afqmc import AFQMC from ipie.qmc.utils import set_rng_seed -from ipie.systems.utils import get_system -from ipie.utils.io import get_input_value, to_json from ipie.utils.misc import get_git_info, print_env_info -from ipie.utils.mpi import get_shared_comm +from ipie.systems.generic import Generic +from ipie.utils.mpi import MPIHandler -class ThermalAFQMC(object): - """AFQMC driver. +## This is now only applicable to the Generic case! +## See test_generic.py for example. - Non-zero temperature AFQMC using open ended random walk. +class ThermalAFQMC(AFQMC): + """Thermal AFQMC driver. Parameters ---------- - model : dict - Input parameters for model system. - qmc_opts : dict - Input options relating to qmc parameters. - estimates : dict - Input options relating to what estimator to calculate. - trial : dict - Input options relating to trial wavefunction. - propagator : dict - Input options relating to propagator. - parallel : bool - If true we are running in parallel. + hamiltonian : + Hamiltonian describing the system. + trial : + Trial density matrix. + walkers : + Walkers used for open ended random walk. + propagator : + Class describing how to propagate walkers. + params : + Parameters of simulation. See QMCParams for description. verbose : bool - If true we print out additional setup information. + How much information to print. Attributes ---------- - uuid : string - Simulation state uuid. - sha1 : string - Git hash. - seed : int - RNG seed. This is set during initialisation in calc. - root : bool - If true we are on the root / master processor. - nprocs : int - Number of processors. - rank : int - Processor id. - cplx : bool - If true then most numpy arrays are complex valued. - init_time : float - Calculation initialisation (cpu) time. - init_time : float - Human readable initialisation time. - system : system object. - Container for model input options. - qmc : :class:`pie.state.QMCOpts` object. - Container for qmc input options. - trial : :class:`pie.trial_wavefunction.X' object - Trial wavefunction class. - propagators : :class:`pie.propagation.Projectors` object - Container for system specific propagation routines. - estimators : :class:`pie.estimators.Estimators` object - Estimator handler. - walk : :class:`pie.walkers.Walkers` object - Stores walkers which sample the partition function. + _parallel_rng_seed : int + Seed deduced from params.rng_seed which is generally different on each + MPI process. """ + def __init__(self, + system, # For compatibility with 0T AFQMC code. + hamiltonian, + trial, + walkers, + propagator, + params: QMCParams, + verbose: int = 0): + super().__init__(system, hamiltonian, trial, walkers, propagator, params, verbose) - def __init__( - self, - comm, - options=None, - system=None, - hamiltonian=None, - trial=None, - parallel=False, - verbose=None, - ): - if verbose is not None: - self.verbosity = verbose - if comm.rank != 0: - self.verbosity = 0 - verbose = verbose > 0 and comm.rank == 0 - else: - self.verbosity = 0 - verbose = False - qmc_opts = get_input_value( - options, - "qmc", - default={}, - alias=["qmc_options"], - verbose=self.verbosity > 1, - ) - if qmc_opts.get("beta") is None: - print("Shouldn't call ThermalAFQMC without specifying beta") - exit() - # 1. Environment attributes - if comm.rank == 0: - self.uuid = str(uuid.uuid1()) - get_sha1 = options.get("get_sha1", True) - if get_sha1: - self.sha1, self.branch, self.local_mods = get_git_info() - else: - self.sha1 = "None" - if verbose: - self.sys_info = print_env_info( - self.sha1, self.branch, self.local_mods, self.uuid, comm.size - ) - # Hack - this is modified later if running in parallel on - # initialisation. - self.root = comm.rank == 0 - self.nprocs = comm.size - self.rank = comm.rank - self._init_time = time.time() - self.run_time = (time.asctime(),) - self.shared_comm = get_shared_comm(comm, verbose=verbose) - - # 2. Calculation objects. - sys_opts = options.get("system") - if system is not None: - self.system = system - else: - sys_opts = get_input_value( - options, - "system", - default={}, - alias=["model"], - verbose=self.verbosity > 1, - ) - sys_opts["thermal"] = True - self.system = get_system(sys_opts=sys_opts, verbose=verbose) - - if hamiltonian is not None: - self.hamiltonian = hamiltonian - else: - ham_opts = get_input_value( - options, "hamiltonian", default={}, verbose=self.verbosity > 1 - ) - # backward compatibility with previous code (to be removed) - for item in sys_opts.items(): - if item[0].lower() == "name" and "name" in ham_opts.keys(): - continue - ham_opts[item[0]] = item[1] - self.hamiltonian = get_hamiltonian( - self.system, ham_opts, verbose=verbose, comm=self.shared_comm - ) + def build( + nelec: Tuple[], + mu: float, + beta: float, + hamiltonian, + trial, + num_walkers: int = 100, + seed: int = None, + num_steps_per_block: int = 25, + num_blocks: int = 100, + timestep: float = 0.005, + stabilize_freq: int = 5, + pop_control_freq: int = 5, + lowrank: bool = False, + verbose: bool = True) -> "Thermal AFQMC": + """Factory method to build thermal AFQMC driver from hamiltonian and trial density matrix. - self.qmc = QMCOpts(qmc_opts, verbose) - self.qmc.rng_seed = set_rng_seed(self.qmc.rng_seed, comm) - self.qmc.ntime_slices = int(round(self.qmc.beta / self.qmc.dt)) - # Overide whatever's in the input file due to structure of FT algorithm. - self.qmc.nsteps = 1 - self.qmc.total_steps = self.qmc.nblocks - if verbose: - print("# Number of time slices = %i" % self.qmc.ntime_slices) - self.cplx = True - if trial is not None: - self.trial = trial - if verbose: - print( - "# Trial density matrix passed from input: {} ".format( - self.trial.__class__.__name__ - ) - ) - else: - trial_opts = get_input_value( - options, - "trial", - default={}, - alias=["trial_density"], - verbose=self.verbosity > 1, - ) - self.trial = get_trial_density_matrix( - self.qmc.dt, - comm=comm, - options=trial_opts, - verbose=verbose, - ) - - self.qmc.ntot_walkers = self.qmc.nwalkers - # Number of walkers per core/rank. - self.qmc.nwalkers = int(self.qmc.nwalkers / comm.size) - # Total number of walkers. - self.qmc.ntot_walkers = self.qmc.nwalkers * self.nprocs - if self.qmc.nwalkers == 0: - if comm.rank == 0 and verbose: - print("# WARNING: Not enough walkers for selected core count.") - print( - "# There must be at least one walker per core set in the " - "input file." - ) - print("# Setting one walker per core.") - self.qmc.nwalkers = 1 - self.qmc.ntot_walkers = self.qmc.nwalkers * self.nprocs - wlk_opts = get_input_value( - options, - "walkers", - default={}, - alias=["walker", "walker_opts"], - verbose=self.verbosity > 1, - ) - self.walk = Walkers( - self.system, - self.hamiltonian, - self.trial, - self.qmc, - walker_opts=wlk_opts, - verbose=verbose, - ) - lowrank = self.walk.walkers[0].lowrank - prop_opts = get_input_value( - options, - "propagator", - default={}, - alias=["prop", "propagation"], - verbose=self.verbosity > 1, - ) - self.propagators = get_propagator( - prop_opts, - self.qmc, - self.system, - self.hamiltonian, - self.trial, - verbose=verbose, - lowrank=lowrank, - ) + Parameters + ---------- + nelec : tuple(int, int) + Number of alpha and beta electrons. + mu : float + Chemical potential. + beta : float + Inverse temperature. + hamiltonian : + Hamiltonian describing the system. + trial : + Trial density matrix. + num_walkers : int + Number of walkers per MPI process used in the simulation. The TOTAL + number of walkers is num_walkers * number of processes. + num_steps_per_block : int + Number of Monte Carlo steps before estimators are evaluatied. + Default 25. + num_blocks : int + Number of blocks to perform. Total number of steps = num_blocks * + num_steps_per_block. + timestep : float + Imaginary timestep. Default 0.005. + stabilize_freq : float + Frequency at which to perform QR factorization of walkers (in units + of steps.) Default 25. + pop_control_freq : int + Frequency at which to perform population control (in units of + steps.) Default 25. + lowrank : bool + Low-rank algorithm for thermal propagation. + verbose : bool + Log verbosity. Default True i.e. print information to stdout. + """ + mpi_handler = MPIHandler() + comm = mpi_handler.comm + params = QMCParams( + num_walkers=num_walkers, + total_num_walkers=num_walkers * comm.size, + num_blocks=num_blocks, + num_steps_per_block=num_steps_per_block, + timestep=timestep, + beta=beta, + num_stblz=stabilize_freq, + pop_control_freq=pop_control_freq, + rng_seed=seed) + + walkers = UHFThermalWalkers(trial, hamiltonian.nbasis, num_walkers, + lowrank=lowrank, verbose=verbose) + propagator = Propagator[type(hamiltonian)]( + timestep, beta, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + return ThermalAFQMC( + system, + hamiltonian, + trial, + walkers, + propagator, + params, + verbose=(verbose and comm.rank == 0)) - self.tsetup = time.time() - self._init_time - est_opts = get_input_value( - options, - "estimators", - default={}, - alias=["estimates"], - verbose=self.verbosity > 1, - ) - self.estimators = Estimators( - est_opts, - self.root, - self.qmc, - self.system, - self.hamiltonian, - self.trial, - self.propagators.BT_BP, - verbose, - ) - # stabilization frequency might be updated due to wrong user input - if self.qmc.nstblz != self.propagators.nstblz: - self.propagators.nstblz = self.qmc.nstblz - if comm.rank == 0: - json_string = to_json(self) - self.estimators.json_string = json_string - self.estimators.dump_metadata() - if verbose: - self.estimators.estimators["mixed"].print_key() - self.estimators.estimators["mixed"].print_header() - def run(self, walk=None, comm=None, verbose=None): - """Perform AFQMC simulation on state object using open-ended random walk. + def run(self, walkers=None, comm=None, verbose=None): + """Perform Thermal AFQMC simulation on state object using open-ended random walk. Parameters ---------- @@ -271,40 +140,67 @@ def run(self, walk=None, comm=None, verbose=None): Initial wavefunction / distribution of walkers. comm : MPI communicator """ - if walk is not None: - self.walk = walk self.setup_timers() - # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) - (E_T, ke, pe) = local_energy( - self.hamiltonian, self.walk.walkers[0], self.trial - ) - # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) + ft_setup time.time() + + if walkers is not None: + self.walkers = walkers + # Calculate estimates for initial distribution of walkers. self.estimators.estimators["mixed"].update( self.qmc, self.hamiltonian, self.trial, - self.walk, + self.walkers, 0, self.propagators.free_projection, ) # Print out zeroth step for convenience. - self.estimators.estimators["mixed"].print_step(comm, self.nprocs, 0, 1) + self.estimators.estimators["mixed"].print_step(comm, comm.size, 0, 1) + + num_walkers = self.walkers.nwalkers + total_steps = self.params.num_steps_per_block * self.params.num_blocks + num_slices = self.params.num_slices - for step in range(1, self.qmc.total_steps + 1): + for step in range(1, total_steps + 1): start_path = time.time() - for ts in range(0, self.qmc.ntime_slices): + + for ts in range(num_slices): if self.verbosity >= 2 and comm.rank == 0: - print(" # Timeslice %d of %d." % (ts, self.qmc.ntime_slices)) + print(" # Timeslice %d of %d." % (ts, num_slices)) + start = time.time() - for w in self.walk.walkers: - self.propagators.propagate_walker(self.hamiltonian, w, ts, 0) - if (abs(w.weight) > w.total_weight * 0.10) and ts > 0: - w.weight = w.total_weight * 0.10 + self.propagator.propagate_walkers( + self.walkers, self.hamiltonian, self.trial, eshift) + + start_clip = time.time() + if step > 1: + wbound = self.pcontrol.total_weight * 0.10 + xp.clip(self.walkers.weight, a_min=-wbound, a_max=wbound, + out=self.walkers.weight) # in-place clipping + + self.tprop_clip += time.time() - start_clip + + start_barrier = time.time() + if step % self.params.pop_control_freq == 0: + comm.Barrier() + self.tprop_barrier += time.time() - start_barrier + + if step % self.params.pop_control_freq == 0: + start = time.time() + self.pcontrol.pop_control(self.walkers, comm) + synchronize() + self.tpopc += time.time() - start + self.tpopc_send = self.pcontrol.timer.send_time + self.tpopc_recv = self.pcontrol.timer.recv_time + self.tpopc_comm = self.pcontrol.timer.communication_time + self.tpopc_non_comm = self.pcontrol.timer.non_communication_time + self.tprop += time.time() - start + start = time.time() if ts % self.qmc.npop_control == 0 and ts != 0: - self.walk.pop_control(comm) + self.walkers.pop_control(comm) self.tpopc += time.time() - start self.tpath += time.time() - start_path start = time.time() @@ -312,18 +208,18 @@ def run(self, walk=None, comm=None, verbose=None): self.qmc, self.hamiltonian, self.trial, - self.walk, + self.walkers, step, self.propagators.free_projection, ) self.testim += time.time() - start self.estimators.print_step( comm, - self.nprocs, + comm.size, step, free_projection=self.propagators.free_projection, ) - self.walk.reset(self.trial) + self.walkers.reset(self.trial) def finalise(self, verbose): """Tidy up. @@ -333,19 +229,7 @@ def finalise(self, verbose): verbose : bool If true print out some information to stdout. """ - if self.root: - if verbose: - print(f"# End Time: {time.asctime()}") - print(f"# Running time : {time.time() - self._init_time:.6f} seconds") - print("# Timing breakdown (per processor, per path/slice):") - print(f"# - Setup: {self.tsetup:f} s") - nsteps = self.qmc.nsteps - nslice = nsteps * self.qmc.ntime_slices - npcon = nslice // self.qmc.npop_control - print(f"# - Path update: {self.tpath / nsteps:f} s") - print(f"# - Propagation: {self.tprop / nslice:f} s") - print(f"# - Estimators: {self.testim / nsteps:f} s") - print(f"# - Population control: {self.tpopc / npcon:f} s") + pass def determine_dtype(self, propagator, system): """Determine dtype for trial wavefunction and walkers. @@ -362,8 +246,32 @@ def determine_dtype(self, propagator, system): twist = system.ktwist.all() is not None return continuous or twist + def get_env_info(self): + this_uuid = str(uuid.uuid1()) + + try: + sha1, branch, local_mods = get_git_info() + + except: + sha1 = "None" + branch = "None" + local_mods = [] + + if self.verbose: + self.sys_info = print_env_info( + sha1, + branch, + local_mods, + this_uuid, + self.mpi_handler.size, + ) + + mem_avail = get_host_memory() + print(f"# Available memory on the node is {mem_avail:4.3f} GB") + def setup_timers(self): self.tpath = 0 self.tprop = 0 + self.tprop_clip = 0 self.testim = 0 self.tpopc = 0 diff --git a/ipie/thermal/qmc/thermal_afqmc_clean.py b/ipie/thermal/qmc/thermal_afqmc_clean.py deleted file mode 100644 index c4aace74..00000000 --- a/ipie/thermal/qmc/thermal_afqmc_clean.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Driver to perform AFQMC calculation""" -import time -import uuid -from ipie.thermal.propagation.utils import get_propagator -from ipie.thermal.walkers.handler import Walkers -from ipie.qmc.options import QMCOpts -from ipie.qmc.utils import set_rng_seed -from ipie.utils.misc import get_git_info, print_env_info -from ipie.qmc.afqmc import AFQMC -from ipie.qmc.options import QMCParams -from ipie.systems.generic import Generic -from ipie.utils.mpi import MPIHandler - - -## This is now only applicable to the Generic case! -## See test_generic.py for example. - -class ThermalAFQMC(AFQMC): - def __init__( - self, - num_elec, - mu, - beta, - hamiltonian, - trial, - num_walkers: int = 100, - seed: int = None, - num_steps_per_block: int = 25, - num_blocks: int = 100, - timestep: float = 0.005, - stabilize_freq=5, - pop_control_freq=5, - verbose=True, - ): - - mpi_handler = MPIHandler() - comm = mpi_handler.comm - params = QMCParams( - num_walkers=num_walkers, - total_num_walkers=num_walkers * comm.size, - num_blocks=num_blocks, - num_steps_per_block=num_steps_per_block, - timestep=timestep, - num_stblz=stabilize_freq, - pop_control_freq=pop_control_freq, - rng_seed=seed, - ) - - system = Generic(num_elec, verbose) - system.mu = mu - - qmc = QMCOpts() # should be removed later after walker is cleaned up - qmc.nwalkers = num_walkers - qmc.ntot_walkers = num_walkers * comm.size - qmc.beta = beta - qmc.total_steps = num_blocks - qmc.nsteps = 1 - qmc.ntime_slices = int(round(beta / timestep)) - qmc.rng_seed = set_rng_seed(seed, comm) - qmc.dt = timestep - - if comm.rank == 0: - self.uuid = str(uuid.uuid1()) - get_sha1 = True - if get_sha1: - self.sha1, self.branch, self.local_mods = get_git_info() - else: - self.sha1 = "None" - if verbose: - self.sys_info = print_env_info( - self.sha1, self.branch, self.local_mods, self.uuid, comm.size - ) - - self.qmc = qmc - self.qmc.nstblz = 10 - self.qmc.npop_control = 1 - - wlk_opts = {} # should be removed later after walker is cleaned up - walkers = Walkers( - system, - hamiltonian, - trial, - qmc, - walker_opts=wlk_opts, - verbose=verbose) - - prop_opts = {} # should be removed later after walker is cleaned up - - propagator = get_propagator( - prop_opts, - qmc, - system, - hamiltonian, - trial, - verbose=verbose - ) - self.propagators = propagator - self.root = True - - super().__init__(system, hamiltonian, trial, walkers, propagator, params, verbose) - - def run(self, walkers=None, comm=None, verbose=None): - """Perform AFQMC simulation on state object using open-ended random walk. - - Parameters - ---------- - state : :class:`pie.state.State` object - Model and qmc parameters. - walk: :class:`pie.walker.Walkers` object - Initial wavefunction / distribution of walkers. - comm : MPI communicator - """ - if walkers is not None: - self.walkers = walkers - self.setup_timers() - # Calculate estimates for initial distribution of walkers. - self.estimators.estimators["mixed"].update( - self.qmc, - self.hamiltonian, - self.trial, - self.walkers, - 0, - self.propagators.free_projection, - ) - # Print out zeroth step for convenience. - self.estimators.estimators["mixed"].print_step(comm, comm.size, 0, 1) - - for step in range(1, self.qmc.total_steps + 1): - start_path = time.time() - for ts in range(0, self.qmc.ntime_slices): - if self.verbosity >= 2 and comm.rank == 0: - print(" # Timeslice %d of %d." % (ts, self.qmc.ntime_slices)) - start = time.time() - for w in self.walkers.walkers: - self.propagators.propagate_walker(self.hamiltonian, w, ts, 0) - if (abs(w.weight) > w.total_weight * 0.10) and ts > 0: - w.weight = w.total_weight * 0.10 - self.tprop += time.time() - start - start = time.time() - if ts % self.qmc.npop_control == 0 and ts != 0: - self.walkers.pop_control(comm) - self.tpopc += time.time() - start - self.tpath += time.time() - start_path - start = time.time() - self.estimators.update( - self.qmc, - self.hamiltonian, - self.trial, - self.walkers, - step, - self.propagators.free_projection, - ) - self.testim += time.time() - start - self.estimators.print_step( - comm, - comm.size, - step, - free_projection=self.propagators.free_projection, - ) - self.walkers.reset(self.trial) - - def finalise(self, verbose): - """Tidy up. - - Parameters - ---------- - verbose : bool - If true print out some information to stdout. - """ - pass - - def determine_dtype(self, propagator, system): - """Determine dtype for trial wavefunction and walkers. - - Parameters - ---------- - propagator : dict - Propagator input options. - system : object - System object. - """ - hs_type = propagator.get("hubbard_stratonovich", "discrete") - continuous = "continuous" in hs_type - twist = system.ktwist.all() is not None - return continuous or twist - - def setup_timers(self): - self.tpath = 0 - self.tprop = 0 - self.testim = 0 - self.tpopc = 0 diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index 7add8197..10f00ab2 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -8,94 +8,88 @@ class MeanField(OneBody): def __init__(self, hamiltonian, nelec, beta, dt, options={}, H1=None, verbose=False): - OneBody.__init__( - self, hamiltonian, nelec, beta, dt, options=options, H1=H1, verbose=verbose - ) + OneBody.__init__(self, hamiltonian, nelec, beta, dt, options=options, + H1=H1, verbose=verbose) if verbose: print(" # Building THF density matrix.") + self.alpha = options.get("alpha", 0.75) self.max_scf_it = options.get("max_scf_it", self.max_it) self.max_macro_it = options.get("max_macro_it", self.max_it) self.find_mu = options.get("find_mu", True) self.P, HMF, self.mu = self.thermal_hartree_fock(hamiltonian, beta) muN = self.mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) - self.dmat = numpy.array( - [ - scipy.linalg.expm(-dt * (HMF[0] - muN)), - scipy.linalg.expm(-dt * (HMF[1] - muN)), - ] - ) - self.dmat_inv = numpy.array( - [ - scipy.linalg.inv(self.dmat[0], check_finite=False), - scipy.linalg.inv(self.dmat[1], check_finite=False), - ] - ) - self.G = numpy.array([greens_function(self.dmat[0]), greens_function(self.dmat[1])]) + self.dmat = numpy.array([scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN))]) + self.dmat_inv = numpy.array([scipy.linalg.inv(self.dmat[0], check_finite=False), + scipy.linalg.inv(self.dmat[1], check_finite=False)]) + self.G = numpy.array([greens_function(self.dmat[0]), + greens_function(self.dmat[1])]) self.nav = particle_number(self.P).real def thermal_hartree_fock(self, hamiltonian, beta): dt = self.dtau mu_old = self.mu P = self.P.copy() + if self.verbose: - print("# Determining Thermal Hartree--Fock Density Matrix.") + print("# Determining Thermal Hartree-Fock Density Matrix.") + for it in range(self.max_macro_it): if self.verbose: - print(f"# Macro iteration: {it}") + print(f"\n# Macro iteration: {it}") + HMF = self.scf(hamiltonian, beta, mu_old, P) - rho = numpy.array([scipy.linalg.expm(-dt * HMF[0]), scipy.linalg.expm(-dt * HMF[1])]) + rho = numpy.array([scipy.linalg.expm(-dt * HMF[0]), + scipy.linalg.expm(-dt * HMF[1])]) if self.find_mu: mu = find_chemical_potential( - hamiltonian._alt_convention, - rho, - dt, - self.num_bins, - self.nav, - deps=self.deps, - max_it=self.max_it, - verbose=self.verbose, - ) + hamiltonian._alt_convention, rho, dt, self.num_bins, self.nav, + deps=self.deps, max_it=self.max_it, verbose=self.verbose) + else: mu = self.mu + rho_mu = compute_rho(rho, mu_old, dt) P = one_rdm_stable(rho_mu, self.num_bins) dmu = abs(mu - mu_old) + if self.verbose: print(f"# New mu: {mu:13.8e} Old mu: {mu_old:13.8e} Dmu: {dmu:13.8e}") + if dmu < self.deps: break + mu_old = mu + return P, HMF, mu def scf(self, hamiltonian, beta, mu, P): - # 1. Compute HMF + # Compute HMF HMF = fock_matrix(hamiltonian, P) dt = self.dtau muN = mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) - rho = numpy.array( - [ - scipy.linalg.expm(-dt * (HMF[0] - muN)), - scipy.linalg.expm(-dt * (HMF[1] - muN)), - ] - ) + rho = numpy.array([scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN))]) Pold = one_rdm_stable(rho, self.num_bins) + if self.verbose: - print(" # Running Thermal SCF.") + print("# Running Thermal SCF.") + for it in range(self.max_scf_it): HMF = fock_matrix(hamiltonian, Pold) - rho = numpy.array( - [ - scipy.linalg.expm(-dt * (HMF[0] - muN)), - scipy.linalg.expm(-dt * (HMF[1] - muN)), - ] - ) + rho = numpy.array([scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN))]) Pnew = (1 - self.alpha) * one_rdm_stable(rho, self.num_bins) + self.alpha * Pold change = numpy.linalg.norm(Pnew - Pold) + if change < self.deps: break + Pold = Pnew.copy() + if self.verbose: N = particle_number(P).real - print(f" # Average particle number: {N:13.8e}") + print(f"# Average particle number: {N:13.8e}") + return HMF diff --git a/ipie/thermal/trial/one_body.py b/ipie/thermal/trial/one_body.py index 51629fc5..71b4ba34 100644 --- a/ipie/thermal/trial/one_body.py +++ b/ipie/thermal/trial/one_body.py @@ -12,24 +12,18 @@ class OneBody(object): - def __init__( - self, - hamiltonian, - nelec, - beta, - dt, - options={}, - nav=None, - H1=None, - verbose=False, - ): + def __init__(self, hamiltonian, nelec, beta, dt, options={}, nav=None, + H1=None, verbose=False): self.name = "thermal" self.verbose = verbose + if H1 is None: try: self.H1 = hamiltonian.H1 + except AttributeError: self.H1 = hamiltonian.h1e + else: self.H1 = H1 @@ -42,16 +36,21 @@ def __init__( dmat_down = scipy.linalg.expm(-dt * (self.H1[1])) self.dmat = numpy.array([dmat_up, dmat_down]) cond = numpy.linalg.cond(self.dmat[0]) + if verbose: print(f"# condition number of BT: {cond: 10e}") self.nelec = nelec + if nav is not None: self.nav = nav + else: self.nav = options.get("nav", None) + if self.nav is None: self.nav = numpy.sum(nelec) + if verbose: print(f"# Target average electron number: {self.nav}") @@ -65,6 +64,7 @@ def __init__( if self.nstack == None: if verbose: print("# Estimating stack size from BT.") + eigs, ev = scipy.linalg.eigh(self.dmat[0]) emax = numpy.max(eigs) emin = numpy.min(eigs) @@ -75,14 +75,12 @@ def __init__( # We can determine a conservative stack size by requiring that the # condition number of the product does not exceed 1e3. self.nstack = min(self.nslice, int(3.0 / numpy.log10(self.cond))) + if verbose: - print( - "# Initial stack size, # of slices: {}, {}".format( - self.nstack, self.nslice - ) - ) + print("# Initial stack size, # of slices: {}, {}".format( + self.nstack, self.nslice)) - # adjust stack size + # Adjust stack size self.nstack = update_stack(self.nstack, self.nslice, verbose=verbose) self.num_bins = int(beta / (self.nstack * dt)) @@ -93,49 +91,35 @@ def __init__( if hamiltonian._alt_convention: if verbose: print("# Using alternate sign convention for chemical potential.") + sign = -1 + dtau = self.nstack * dt self.dtau = dtau if self.mu is None: - self.rho = numpy.array( - [ - scipy.linalg.expm(-dtau * (self.H1[0])), - scipy.linalg.expm(-dtau * (self.H1[1])), - ] - ) + self.rho = numpy.array([scipy.linalg.expm(-dtau * (self.H1[0])), + scipy.linalg.expm(-dtau * (self.H1[1]))]) self.mu = find_chemical_potential( - hamiltonian._alt_convention, - self.rho, - dtau, - self.num_bins, - self.nav, - deps=self.deps, - max_it=self.max_it, - verbose=verbose, - ) + hamiltonian._alt_convention, self.rho, dtau, self.num_bins, + self.nav, deps=self.deps, max_it=self.max_it, verbose=verbose) + else: - self.rho = numpy.array( - [ - scipy.linalg.expm(-dtau * (self.H1[0])), - scipy.linalg.expm(-dtau * (self.H1[1])), - ] - ) + self.rho = numpy.array([scipy.linalg.expm(-dtau * (self.H1[0])), + scipy.linalg.expm(-dtau * (self.H1[1]))]) if self.verbose: print(f"# Chemical potential in trial density matrix: {self.mu: .10e}") self.P = one_rdm_stable(compute_rho(self.rho, self.mu, dtau, sign=sign), self.num_bins) self.nav = particle_number(self.P).real + if self.verbose: print(f"# Average particle number in trial density matrix: {self.nav}") + self.dmat = compute_rho(self.dmat, self.mu, dt, sign=sign) - self.dmat_inv = numpy.array( - [ - scipy.linalg.inv(self.dmat[0], check_finite=False), - scipy.linalg.inv(self.dmat[1], check_finite=False), - ] - ) + self.dmat_inv = numpy.array([scipy.linalg.inv(self.dmat[0], check_finite=False), + scipy.linalg.inv(self.dmat[1], check_finite=False)]) self.G = numpy.array([greens_function(self.dmat[0]), greens_function(self.dmat[1])]) self.error = False diff --git a/ipie/thermal/trial/tests/test_mean_field.py b/ipie/thermal/trial/tests/test_mean_field.py new file mode 100644 index 00000000..61233c8e --- /dev/null +++ b/ipie/thermal/trial/tests/test_mean_field.py @@ -0,0 +1,69 @@ +import numpy +import pytest + +from pyscf import gto, scf, lo + +from ipie.systems.generic import Generic +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.thermal.trial.mean_field import MeanField + + +def setup_objs(): + nocca = 5 + noccb = 5 + nelec = nocca + noccb + r0 = 1.75 + mol = gto.M( + atom=[("H", i * r0, 0, 0) for i in range(nelec)], + basis='sto-6g', + unit='Bohr', + verbose=5) + + mu = -10. + path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" + options = { + "hamiltonian": { + "name": "Generic", + "integrals": path + "reference_data/generic_integrals.h5", + "_alt_convention": False, + "symmetry": False, + "sparse": False, + "mu": mu + }, + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + system = Generic(mol.nelec) + hamiltonian = get_hamiltonian(system, options["hamiltonian"]) + objs = {'mol': mol, + 'hamiltonian': hamiltonian} + + return objs + + +def test_mean_field(): + beta = 0.1 + dt = 0.01 + verbose = True + objs = setup_objs() + mol = objs['mol'] + hamiltonian = objs['hamiltonian'] + nbasis = hamiltonian.nbasis + trial = MeanField(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + + assert trial.nelec == mol.nelec + numpy.testing.assert_almost_equal(trial.nav, numpy.sum(mol.nelec), decimal=6) + assert trial.rho.shape == (2, nbasis, nbasis) + assert trial.dmat.shape == (2, nbasis, nbasis) + assert trial.P.shape == (2, nbasis, nbasis) + assert trial.G.shape == (2, nbasis, nbasis) + + +if __name__ == '__main__': + test_mean_field() + + + diff --git a/ipie/thermal/trial/tests/test_one_body.py b/ipie/thermal/trial/tests/test_one_body.py new file mode 100644 index 00000000..b049c3c4 --- /dev/null +++ b/ipie/thermal/trial/tests/test_one_body.py @@ -0,0 +1,69 @@ +import numpy +import pytest + +from pyscf import gto, scf, lo + +from ipie.systems.generic import Generic +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.thermal.trial.one_body import OneBody + + +def setup_objs(): + nocca = 5 + noccb = 5 + nelec = nocca + noccb + r0 = 1.75 + mol = gto.M( + atom=[("H", i * r0, 0, 0) for i in range(nelec)], + basis='sto-6g', + unit='Bohr', + verbose=5) + + mu = -10. + path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" + options = { + "hamiltonian": { + "name": "Generic", + "integrals": path + "reference_data/generic_integrals.h5", + "_alt_convention": False, + "symmetry": False, + "sparse": False, + "mu": mu + }, + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + system = Generic(mol.nelec) + hamiltonian = get_hamiltonian(system, options["hamiltonian"]) + objs = {'mol': mol, + 'hamiltonian': hamiltonian} + + return objs + + +def test_one_body(): + beta = 0.1 + dt = 0.01 + verbose = True + objs = setup_objs() + mol = objs['mol'] + hamiltonian = objs['hamiltonian'] + nbasis = hamiltonian.nbasis + trial = OneBody(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + + assert trial.nelec == mol.nelec + numpy.testing.assert_almost_equal(trial.nav, numpy.sum(mol.nelec), decimal=6) + assert trial.rho.shape == (2, nbasis, nbasis) + assert trial.dmat.shape == (2, nbasis, nbasis) + assert trial.P.shape == (2, nbasis, nbasis) + assert trial.G.shape == (2, nbasis, nbasis) + + +if __name__ == '__main__': + test_one_body() + + + diff --git a/ipie/thermal/trial/utils.py b/ipie/thermal/trial/utils.py index 138ebfbe..1b94697e 100644 --- a/ipie/thermal/trial/utils.py +++ b/ipie/thermal/trial/utils.py @@ -25,14 +25,19 @@ def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, comm=None H1=hamiltonian.h1e_mod, verbose=verbose, ) + elif trial_type == "one_body": trial = OneBody(hamiltonian, nelec, beta, dt, options=options, verbose=verbose) + elif trial_type == "thermal_hartree_fock": trial = MeanField(hamiltonian, nelec, beta, dt, options=options, verbose=verbose) + else: trial = None + else: trial = None + if comm is not None: trial = comm.bcast(trial) diff --git a/ipie/thermal/walkers/handler.py b/ipie/thermal/walkers/handler.py deleted file mode 100644 index 4d64606e..00000000 --- a/ipie/thermal/walkers/handler.py +++ /dev/null @@ -1,370 +0,0 @@ -import cmath -import sys -import time - -import h5py -import numpy - -from ipie.thermal.walkers.uhf_walkers import ThermalWalkers -from ipie.utils.io import get_input_value -from ipie.utils.misc import update_stack - - -class Walkers(object): - """Container for groups of walkers which make up a wavefunction. - - Parameters - ---------- - system : object - System object. - trial : object - Trial wavefunction object. - nwalkers : int - Number of walkers to initialise. - nprop_tot : int - Total number of propagators to store for back propagation + itcf. - nbp : int - Number of back propagation steps. - """ - - def __init__( - self, - system, - hamiltonian, - trial, - qmc, - walker_opts={}, - verbose=False, - comm=None, - nprop_tot=None, - nbp=None, - ): - self.nwalkers = qmc.nwalkers - self.ntot_walkers = qmc.ntot_walkers - self.write_freq = walker_opts.get("write_freq", 0) - self.write_file = walker_opts.get("write_file", "restart.h5") - self.use_log_shift = walker_opts.get("use_log_shift", False) - self.shift_counter = 1 - self.read_file = walker_opts.get("read_file", None) - if comm is None: - rank = 0 - else: - rank = comm.rank - if verbose: - print("# Setting up walkers.handler.Walkers.") - print(f"# qmc.nwalkers = {self.nwalkers}") - print(f"# qmc.ntot_walkers = {self.ntot_walkers}") - - if trial.name in ["MultiSlater", "coherent_state"]: - print(trial.name) - raise NotImplementedError - elif trial.name == "thermal": - self.walker_type = "thermal" - self.walkers = [ - ThermalWalkers( - system, - hamiltonian, - trial, - walker_opts=walker_opts, - verbose=(verbose and w == 0), - ) - for w in range(qmc.nwalkers) - ] - self.buff_size = self.walkers[0].buff_size + self.walkers[0].stack.buff_size - self.walker_buffer = numpy.zeros(self.buff_size, dtype=numpy.complex128) - stack_size = self.walkers[0].stack_size - else: - raise NotImplementedError - if hamiltonian.name == "Generic" or system.name == "UEG": - dtype = complex - else: - dtype = int - self.pcont_method = get_input_value( - walker_opts, - "population_control", - alias=["pop_control"], - default="pair_branch", - verbose=verbose, - ) - self.min_weight = walker_opts.get("min_weight", 0.1) - self.max_weight = walker_opts.get("max_weight", 4.0) - if verbose: - print(f"# Using {self.pcont_method} population control algorithm.") - mem = float(self.walker_buffer.nbytes) / (1024.0**3) - print(f"# Buffer size for communication: {mem:13.8e} GB") - if mem > 2.0: - # TODO: FDM FIX THIS - print(" # Warning: Walker buffer size > 2GB. May run into MPI" "issues.") - if not self.walker_type == "thermal": - walker_size = 3 + self.walkers[0].phi.size - if self.write_freq > 0: - self.write_restart = True - self.dsets = [] - with h5py.File(self.write_file, "w", driver="mpio", comm=comm) as fh5: - for i in range(self.ntot_walkers): - fh5.create_dataset("walker_%d" % i, (walker_size,), dtype=numpy.complex128) - - else: - self.write_restart = False - if self.read_file is not None: - if verbose: - print(f"# Reading walkers from {self.read_file} file series.") - self.read_walkers(comm) - self.target_weight = qmc.ntot_walkers - self.nw = qmc.nwalkers - self.set_total_weight(qmc.ntot_walkers) - - if verbose: - print("# Finish setting up walkers.handler.Walkers.") - - - def pop_control(self, comm): - if self.ntot_walkers == 1: - return - if self.use_log_shift: - self.update_log_ovlp(comm) - weights = numpy.array([abs(w.weight) for w in self.walkers]) - global_weights = numpy.empty(len(weights) * comm.size) - comm.Allgather(weights, global_weights) - total_weight = sum(global_weights) - # Rescale weights to combat exponential decay/growth. - scale = total_weight / self.target_weight - if total_weight < 1e-8: - if comm.rank == 0: - print(f"# Warning: Total weight is {total_weight:13.8e}: ") - print("# Something is seriously wrong.") - sys.exit() - self.set_total_weight(total_weight) - # Todo: Just standardise information we want to send between routines. - for w in self.walkers: - w.unscaled_weight = w.weight - w.weight = w.weight / scale - if self.pcont_method == "comb": - global_weights = global_weights / scale - self.comb(comm, global_weights) - elif self.pcont_method == "pair_branch": - self.pair_branch(comm) - else: - if comm.rank == 0: - print("Unknown population control method.") - - def comb(self, comm, weights): - """Apply the comb method of population control / branching. - - See Booth & Gubernatis PRE 80, 046704 (2009). - - Parameters - ---------- - comm : MPI communicator - """ - # Need make a copy to since the elements in psi are only references to - # walker objects in memory. We don't want future changes in a given - # element of psi having unintended consequences. - # todo : add phase to walker for free projection - if comm.rank == 0: - parent_ix = numpy.zeros(len(weights), dtype="i") - else: - parent_ix = numpy.empty(len(weights), dtype="i") - if comm.rank == 0: - total_weight = sum(weights) - cprobs = numpy.cumsum(weights) - r = numpy.random.random() - comb = [ - (i + r) * (total_weight / self.target_weight) for i in range(self.target_weight) - ] - iw = 0 - ic = 0 - while ic < len(comb): - if comb[ic] < cprobs[iw]: - parent_ix[iw] += 1 - ic += 1 - else: - iw += 1 - data = {"ix": parent_ix} - else: - data = None - - data = comm.bcast(data, root=0) - parent_ix = data["ix"] - # Keep total weight saved for capping purposes. - # where returns a tuple (array,), selecting first element. - kill = numpy.where(parent_ix == 0)[0] - clone = numpy.where(parent_ix > 1)[0] - reqs = [] - walker_buffers = [] - # First initiate non-blocking sends of walkers. - comm.barrier() - for i, (c, k) in enumerate(zip(clone, kill)): - # Sending from current processor? - if c // self.nw == comm.rank: - # Location of walker to clone in local list. - clone_pos = c % self.nw - # copying walker data to intermediate buffer to avoid issues - # with accessing walker data during send. Might not be - # necessary. - dest_proc = k // self.nw - # with h5py.File('before_{}.h5'.format(comm.rank), 'a') as fh5: - # fh5['walker_{}_{}_{}'.format(c,k,dest_proc)] = self.walkers[clone_pos].get_buffer() - buff = self.walkers[clone_pos].get_buffer() - reqs.append(comm.Isend(buff, dest=dest_proc, tag=i)) - # Now receive walkers on processors where walkers are to be killed. - for i, (c, k) in enumerate(zip(clone, kill)): - # Receiving to current processor? - if k // self.nw == comm.rank: - # Processor we are receiving from. - source_proc = c // self.nw - # Location of walker to kill in local list of walkers. - kill_pos = k % self.nw - comm.Recv(self.walker_buffer, source=source_proc, tag=i) - # with h5py.File('walkers_recv.h5', 'w') as fh5: - # fh5['walk_{}'.format(k)] = self.walker_buffer.copy() - self.walkers[kill_pos].set_buffer(self.walker_buffer) - # with h5py.File('after_{}.h5'.format(comm.rank), 'a') as fh5: - # fh5['walker_{}_{}_{}'.format(c,k,comm.rank)] = self.walkers[kill_pos].get_buffer() - # Complete non-blocking send. - for rs in reqs: - rs.wait() - # Necessary? - # if len(kill) > 0 or len(clone) > 0: - # sys.exit() - comm.Barrier() - # Reset walker weight. - # TODO: check this. - for w in self.walkers: - w.weight = 1.0 - - def pair_branch(self, comm): - walker_info = [[abs(w.weight), 1, comm.rank, comm.rank] for w in self.walkers] - glob_inf = comm.gather(walker_info, root=0) - # Want same random number seed used on all processors - if comm.rank == 0: - # Rescale weights. - glob_inf = numpy.array([item for sub in glob_inf for item in sub]) - total_weight = sum(w[0] for w in glob_inf) - sort = numpy.argsort(glob_inf[:, 0], kind="mergesort") - isort = numpy.argsort(sort, kind="mergesort") - glob_inf = glob_inf[sort] - s = 0 - e = len(glob_inf) - 1 - tags = [] - isend = 0 - while s < e: - if glob_inf[s][0] < self.min_weight or glob_inf[e][0] > self.max_weight: - # sum of paired walker weights - wab = glob_inf[s][0] + glob_inf[e][0] - r = numpy.random.rand() - if r < glob_inf[e][0] / wab: - # clone large weight walker - glob_inf[e][0] = 0.5 * wab - glob_inf[e][1] = 2 - # Processor we will send duplicated walker to - glob_inf[e][3] = glob_inf[s][2] - send = glob_inf[s][2] - # Kill small weight walker - glob_inf[s][0] = 0.0 - glob_inf[s][1] = 0 - glob_inf[s][3] = glob_inf[e][2] - else: - # clone small weight walker - glob_inf[s][0] = 0.5 * wab - glob_inf[s][1] = 2 - # Processor we will send duplicated walker to - glob_inf[s][3] = glob_inf[e][2] - send = glob_inf[e][2] - # Kill small weight walker - glob_inf[e][0] = 0.0 - glob_inf[e][1] = 0 - glob_inf[e][3] = glob_inf[s][2] - tags.append([send]) - s += 1 - e -= 1 - else: - break - nw = self.nwalkers - glob_inf = glob_inf[isort].reshape((comm.size, nw, 4)) - else: - data = None - total_weight = 0 - data = comm.scatter(glob_inf, root=0) - # Keep total weight saved for capping purposes. - walker_buffers = [] - reqs = [] - for iw, walker in enumerate(data): - if walker[1] > 1: - tag = int(comm.rank * len(walker_info) + walker[3]) - self.walkers[iw].weight = walker[0] - buff = self.walkers[iw].get_buffer() - reqs.append(comm.Isend(buff, dest=int(round(walker[3])), tag=tag)) - for iw, walker in enumerate(data): - if walker[1] == 0: - tag = int(walker[3] * len(walker_info) + comm.rank) - comm.Recv(self.walker_buffer, source=int(round(walker[3])), tag=tag) - self.walkers[iw].set_buffer(self.walker_buffer) - for r in reqs: - r.wait() - - def set_total_weight(self, total_weight): - for w in self.walkers: - w.total_weight = total_weight - w.old_total_weight = w.total_weight - - def reset(self, trial): - for w in self.walkers: - w.stack.reset() - w.stack.set_all(trial.dmat) - w.greens_function(trial) - w.weight = 1.0 - w.phase = 1.0 + 0.0j - - def get_write_buffer(self, i): - w = self.walkers[i] - buff = numpy.concatenate([[w.weight], [w.phase], [w.ot], w.phi.ravel()]) - return buff - - def set_walker_from_buffer(self, i, buff): - w = self.walkers[i] - w.weight = buff[0] - w.phase = buff[1] - w.ot = buff[2] - w.phi = buff[3:].reshape(self.walkers[i].phi.shape) - - def write_walkers(self, comm): - start = time.time() - with h5py.File(self.write_file, "r+", driver="mpio", comm=comm) as fh5: - for i, w in enumerate(self.walkers): - ix = i + self.nwalkers * comm.rank - buff = self.get_write_buffer(i) - fh5["walker_%d" % ix][:] = self.get_write_buffer(i) - if comm.rank == 0: - print(" # Writing walkers to file.") - print(f" # Time to write restart: {time.time() - start:13.8e} s") - - def update_log_ovlp(self, comm): - send = numpy.zeros(3, dtype=numpy.complex128) - # Overlap log factor - send[0] = sum(abs(w.ot) for w in self.walkers) - # Det R log factor - send[1] = sum(abs(w.detR) for w in self.walkers) - send[2] = sum(abs(w.log_detR) for w in self.walkers) - global_av = numpy.zeros(3, dtype=numpy.complex128) - comm.Allreduce(send, global_av) - log_shift = numpy.log(global_av[0] / self.ntot_walkers) - detR_shift = numpy.log(global_av[1] / self.ntot_walkers) - log_detR_shift = global_av[2] / self.ntot_walkers - # w.log_shift = -0.5 - n = self.shift_counter - nm1 = self.shift_counter - 1 - for w in self.walkers: - w.log_shift = (w.log_shift * nm1 + log_shift) / n - w.log_detR_shift = (w.log_detR_shift * nm1 + log_detR_shift) / n - w.detR_shift = (w.detR_shift * nm1 + detR_shift) / n - self.shift_counter += 1 - - def read_walkers(self, comm): - with h5py.File(self.read_file, "r") as fh5: - for i, w in enumerate(self.walkers): - try: - ix = i + self.nwalkers * comm.rank - self.set_walker_from_buffer(i, fh5["walker_%d" % ix][:]) - except KeyError: - print(f" # Could not read walker data from: {self.read_file}") diff --git a/ipie/thermal/walkers/walker.py b/ipie/thermal/walkers/walker.py deleted file mode 100644 index 60ad312e..00000000 --- a/ipie/thermal/walkers/walker.py +++ /dev/null @@ -1,135 +0,0 @@ -import numpy - -class Walker(object): - """Walker base class. - - Parameters - ---------- - system : object - System object. - trial : object - Trial wavefunction object. - options : dict - Input options - index : int - Element of trial wavefunction to initalise walker to. - nprop_tot : int - Number of back propagation steps (including imaginary time correlation - functions.) - nbp : int - Number of back propagation steps. - """ - - def __init__( - self, - system, - hamiltonian, - trial, - walker_opts={}, - index=0, - nprop_tot=None, - nbp=None, - ): - self.weight = walker_opts.get("weight", 1.0) - self.unscaled_weight = self.weight - self.phase = 1 + 0j - self.alive = 1 - self.phi = numpy.array(trial.init.copy(), dtype=numpy.complex128) - self.nup = system.nup - self.ndown = system.ndown - self.total_weight = 0.0 - self.ot = 1.0 - self.ovlp = 1.0 - # self.E_L = local_energy(system, self.G, self.Gmod, trail._rchol)[0].real - self.E_L = 0.0 - self.eloc = 0.0 - # walkers overlap at time tau before backpropagation occurs - self.ot_bp = 1.0 - # walkers weight at time tau before backpropagation occurs - self.weight_bp = self.weight - # Historic wavefunction for back propagation. - self.phi_old = self.phi.copy() - self.hybrid_energy = 0.0 - # Historic wavefunction for ITCF. - self.phi_right = self.phi.copy() - self.weights = numpy.array( - [1.0] - ) # This is going to be for MSD trial... (should be named a lot better than this) - self.detR = 1.0 - self.detR_shift = 0.0 - self.log_detR = 0.0 - self.log_shift = 0.0 - self.log_detR_shift = 0.0 - # Number of propagators to store for back propagation / ITCF. - self.field_configs = None - self.stack = None - - def get_buffer(self): - """Get walker buffer for MPI communication - - Returns - ------- - buff : dict - Relevant walker information for population control. - """ - s = 0 - buff = numpy.zeros(self.buff_size, dtype=numpy.complex128) - for d in self.buff_names: - data = self.__dict__[d] - if isinstance(data, (numpy.ndarray)): - buff[s : s + data.size] = data.ravel() - s += data.size - elif isinstance(data, list): - for l in data: - if isinstance(l, (numpy.ndarray)): - buff[s : s + l.size] = l.ravel() - s += l.size - elif isinstance(l, (int, float, complex)): - buff[s : s + 1] = l - s += 1 - else: - buff[s : s + 1] = data - s += 1 - if self.field_configs is not None: - stack_buff = self.field_configs.get_buffer() - return numpy.concatenate((buff, stack_buff)) - elif self.stack is not None: - stack_buff = self.stack.get_buffer() - return numpy.concatenate((buff, stack_buff)) - else: - return buff - - def set_buffer(self, buff): - """Set walker buffer following MPI communication - - Parameters - ------- - buff : dict - Relevant walker information for population control. - """ - s = 0 - for d in self.buff_names: - data = self.__dict__[d] - if isinstance(data, numpy.ndarray): - self.__dict__[d] = buff[s : s + data.size].reshape(data.shape).copy() - s += data.size - elif isinstance(data, list): - for ix, l in enumerate(data): - if isinstance(l, (numpy.ndarray)): - self.__dict__[d][ix] = buff[s : s + l.size].reshape(l.shape).copy() - s += l.size - elif isinstance(l, (int, float, complex)): - self.__dict__[d][ix] = buff[s] - s += 1 - else: - if isinstance(self.__dict__[d], int): - self.__dict__[d] = int(buff[s].real) - elif isinstance(self.__dict__[d], float): - self.__dict__[d] = buff[s].real - else: - self.__dict__[d] = buff[s] - s += 1 - if self.field_configs is not None: - self.field_configs.set_buffer(buff[self.buff_size :]) - if self.stack is not None: - self.stack.set_buffer(buff[self.buff_size :]) From b940a8c35ad61ca3c3dea2668bc5885f0d26712c Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 21 Dec 2023 21:37:23 +0800 Subject: [PATCH 33/84] Remove `system` dependence from `estimators/`, propagating through tests and 0T code. `pytest --ignore=thermal -v` passes. --- ipie/estimators/energy.py | 34 ++-- ipie/estimators/estimator_base.py | 2 +- ipie/estimators/generic.py | 150 ++++++------------ ipie/estimators/handler.py | 10 +- ipie/estimators/local_energy.py | 33 ++-- ipie/estimators/local_energy_batch.py | 26 ++- ipie/estimators/local_energy_noci.py | 5 +- ipie/estimators/local_energy_sd.py | 30 +--- ipie/estimators/local_energy_sd_chunked.py | 8 +- ipie/estimators/local_energy_wicks.py | 46 +++--- ipie/estimators/tests/test_estimators.py | 16 +- ipie/estimators/tests/test_generic.py | 13 +- ipie/estimators/tests/test_generic_batch.py | 49 +++--- ipie/estimators/tests/test_generic_chunked.py | 11 +- .../tests/test_generic_chunked_gpu.py | 15 +- ipie/estimators/tests/test_generic_complex.py | 9 +- ipie/estimators/tests/test_generic_noci.py | 42 ++--- ipie/estimators/tests/test_generic_phmsd.py | 143 ++++++++--------- ipie/legacy/estimators/generic.py | 31 ++++ ipie/legacy/estimators/local_energy.py | 2 +- ipie/qmc/afqmc.py | 5 - ipie/qmc/tests/test_afqmc_multi_det_batch.py | 2 - ipie/qmc/tests/test_afqmc_single_det_batch.py | 4 - ipie/trial_wavefunction/noci.py | 2 +- ipie/trial_wavefunction/particle_hole.py | 2 +- ipie/trial_wavefunction/single_det.py | 8 +- ipie/trial_wavefunction/tests/test_noci.py | 4 + .../tests/test_particle_hole.py | 6 + .../tests/test_wavefunction_base.py | 4 + ipie/walkers/tests/test_multi_det_batch.py | 8 +- 30 files changed, 328 insertions(+), 392 deletions(-) diff --git a/ipie/estimators/energy.py b/ipie/estimators/energy.py index d8a6936b..65cd906a 100644 --- a/ipie/estimators/energy.py +++ b/ipie/estimators/energy.py @@ -30,7 +30,6 @@ local_energy_multi_det_trial_wicks_batch_opt_chunked, ) from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol -from ipie.systems.generic import Generic from ipie.trial_wavefunction.noci import NOCI from ipie.trial_wavefunction.particle_hole import ( ParticleHole, @@ -45,76 +44,69 @@ @plum.dispatch def local_energy( - system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: SingleDet + hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: SingleDet ): - return local_energy_batch(system, hamiltonian, walkers, trial) + return local_energy_batch(hamiltonian, walkers, trial) @plum.dispatch def local_energy( - system: Generic, hamiltonian: GenericComplexChol, walkers: UHFWalkers, trial: SingleDet, ): - return local_energy_single_det_uhf(system, hamiltonian, walkers, trial) + return local_energy_single_det_uhf(hamiltonian, walkers, trial) @plum.dispatch def local_energy( - system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: ParticleHoleNaive, ): - return local_energy_multi_det_trial_batch(system, hamiltonian, walkers, trial) + return local_energy_multi_det_trial_batch(hamiltonian, walkers, trial) @plum.dispatch def local_energy( - system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: ParticleHole, ): - return local_energy_multi_det_trial_wicks_batch_opt_chunked(system, hamiltonian, walkers, trial) + return local_energy_multi_det_trial_wicks_batch_opt_chunked(hamiltonian, walkers, trial) @plum.dispatch def local_energy( - system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: ParticleHoleNonChunked, ): - return local_energy_multi_det_trial_wicks_batch_opt(system, hamiltonian, walkers, trial) + return local_energy_multi_det_trial_wicks_batch_opt(hamiltonian, walkers, trial) @plum.dispatch def local_energy( - system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: ParticleHoleSlow, ): - return local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walkers, trial) + return local_energy_multi_det_trial_wicks_batch(hamiltonian, walkers, trial) @plum.dispatch -def local_energy(system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: NOCI): - return local_energy_noci(system, hamiltonian, walkers, trial) +def local_energy(hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: NOCI): + return local_energy_noci(hamiltonian, walkers, trial) class EnergyEstimator(EstimatorBase): def __init__( self, - system=None, - ham=None, + hamiltonian=None, trial=None, filename=None, ): - assert system is not None - assert ham is not None + assert hamiltonian is not None assert trial is not None super().__init__() self._eshift = 0.0 @@ -131,10 +123,10 @@ def __init__( self.print_to_stdout = True self.ascii_filename = filename - def compute_estimator(self, system, walkers, hamiltonian, trial, istep=1): + def compute_estimator(self, walkers, hamiltonian, trial, istep=1): trial.calc_greens_function(walkers) # Need to be able to dispatch here - energy = local_energy(system, hamiltonian, walkers, trial) + energy = local_energy(hamiltonian, walkers, trial) self._data["ENumer"] = xp.sum(walkers.weight * energy[:, 0].real) self._data["EDenom"] = xp.sum(walkers.weight) self._data["E1Body"] = xp.sum(walkers.weight * energy[:, 1].real) diff --git a/ipie/estimators/estimator_base.py b/ipie/estimators/estimator_base.py index c78c9322..77d0c41d 100644 --- a/ipie/estimators/estimator_base.py +++ b/ipie/estimators/estimator_base.py @@ -89,7 +89,7 @@ def shape(self, shape) -> tuple: self._shape = shape @abstractmethod - def compute_estimator(self, system, walkers, hamiltonian, trial) -> np.ndarray: + def compute_estimator(self, walkers, hamiltonian, trial) -> np.ndarray: ... @property diff --git a/ipie/estimators/generic.py b/ipie/estimators/generic.py index ce0d3167..d545713e 100644 --- a/ipie/estimators/generic.py +++ b/ipie/estimators/generic.py @@ -23,47 +23,14 @@ from ipie.utils.backend import synchronize -# FDM: deprecated remove? -def local_energy_generic_opt(system, G, Ghalf=None, eri=None): - """Compute local energy using half-rotated eri tensor.""" - - na = system.nup - nb = system.ndown - M = system.nbasis - assert eri is not None - - vipjq_aa = eri[0, : na**2 * M**2].reshape((na, M, na, M)) - vipjq_bb = eri[0, na**2 * M**2 : na**2 * M**2 + nb**2 * M**2].reshape( - (nb, M, nb, M) - ) - vipjq_ab = eri[0, na**2 * M**2 + nb**2 * M**2 :].reshape((na, M, nb, M)) - - Ga, Gb = Ghalf[0], Ghalf[1] - # Element wise multiplication. - e1b = numpy.sum(system.H1[0] * G[0]) + numpy.sum(system.H1[1] * G[1]) - # Coulomb - eJaa = 0.5 * numpy.einsum("irjs,ir,js", vipjq_aa, Ga, Ga) - eJbb = 0.5 * numpy.einsum("irjs,ir,js", vipjq_bb, Gb, Gb) - eJab = numpy.einsum("irjs,ir,js", vipjq_ab, Ga, Gb) - - eKaa = -0.5 * numpy.einsum("irjs,is,jr", vipjq_aa, Ga, Ga) - eKbb = -0.5 * numpy.einsum("irjs,is,jr", vipjq_bb, Gb, Gb) - - e2b = eJaa + eJbb + eJab + eKaa + eKbb - - return (e1b + e2b + system.ecore, e1b + system.ecore, e2b) - - -def local_energy_generic_cholesky(system, ham, G, Ghalf=None): +def local_energy_generic_cholesky(hamiltonian, G, Ghalf=None): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. Parameters ---------- - system : :class:`Generic` - generic system information - ham : :class:`Generic` + hamiltonian : :class:`Generic` ab-initio hamiltonian information G : :class:`numpy.ndarray` Walker's "green's function" @@ -76,17 +43,17 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): Total , one and two-body energies. """ # Element wise multiplication. - e1b = numpy.sum(ham.H1[0] * G[0]) + numpy.sum(ham.H1[1] * G[1]) - nbasis = ham.nbasis - nchol = ham.nchol + e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) + nbasis = hamiltonian.nbasis + nchol = hamiltonian.nchol Ga, Gb = G[0], G[1] - if numpy.isrealobj(ham.chol): - Xa = ham.chol.T.dot(Ga.real.ravel()) + 1.0j * ham.chol.T.dot(Ga.imag.ravel()) - Xb = ham.chol.T.dot(Gb.real.ravel()) + 1.0j * ham.chol.T.dot(Gb.imag.ravel()) + if numpy.isrealobj(hamiltonian.chol): + Xa = hamiltonian.chol.T.dot(Ga.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Ga.imag.ravel()) + Xb = hamiltonian.chol.T.dot(Gb.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Gb.imag.ravel()) else: - Xa = ham.chol.T.dot(Ga.ravel()) - Xb = ham.chol.T.dot(Gb.ravel()) + Xa = hamiltonian.chol.T.dot(Ga.ravel()) + Xb = hamiltonian.chol.T.dot(Gb.ravel()) ecoul = numpy.dot(Xa, Xa) ecoul += numpy.dot(Xb, Xb) @@ -98,9 +65,9 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): GbT = Gb.T.copy() exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - if numpy.isrealobj(ham.chol): + if numpy.isrealobj(hamiltonian.chol): for x in range(nchol): # write a cython function that calls blas for this. - Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) + Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) T[:, :].real = GaT.real.dot(Lmn) T[:, :].imag = GaT.imag.dot(Lmn) exx += numpy.trace(T.dot(T)) @@ -109,7 +76,7 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): exx += numpy.trace(T.dot(T)) else: for x in range(nchol): # write a cython function that calls blas for this. - Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) + Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) T[:, :] = GaT.dot(Lmn) exx += numpy.trace(T.dot(T)) T[:, :] = GbT.dot(Lmn) @@ -117,18 +84,16 @@ def local_energy_generic_cholesky(system, ham, G, Ghalf=None): e2b = 0.5 * (ecoul - exx) - return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) + return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) -def local_energy_cholesky_opt_dG(system, ecore, Ghalfa, Ghalfb, trial): +def local_energy_cholesky_opt_dG(ecore, Ghalfa, Ghalfb, trial): r"""Calculate local for generic two-body hamiltonian. This uses the density difference trick. Parameters ---------- - system : :class:`Generic` - generic system information ecore : float Core energy Ghalfa : :class:`numpy.ndarray` @@ -153,7 +118,7 @@ def local_energy_cholesky_opt_dG(system, ecore, Ghalfa, Ghalfb, trial): dGhalfa = dGhalfa.astype(numpy.complex64) dGhalfb = dGhalfb.astype(numpy.complex64) - deJ, deK = half_rotated_cholesky_jk(system, dGhalfa, dGhalfb, trial) + deJ, deK = half_rotated_cholesky_jk(dGhalfa, dGhalfb, trial) de2 = deJ + deK if trial.mixed_precision: @@ -168,15 +133,13 @@ def local_energy_cholesky_opt_dG(system, ecore, Ghalfa, Ghalfb, trial): return (etot, e1, e2) -def local_energy_cholesky_opt(system, ecore, Ghalfa, Ghalfb, trial): +def local_energy_cholesky_opt(ecore, Ghalfa, Ghalfb, trial): r"""Calculate local for generic two-body hamiltonian. This uses the half-rotated cholesky decomposed two-electron integrals. Parameters ---------- - system : :class:`Generic` - System information for Generic. Ghalfa : :class:`numpy.ndarray` Walker's half-rotated "green's function" shape is nalpha x nbasis Ghalfa : :class:`numpy.ndarray` @@ -189,22 +152,20 @@ def local_energy_cholesky_opt(system, ecore, Ghalfa, Ghalfb, trial): (E, T, V): tuple Total, one and two-body energies. """ - e1b = half_rotated_cholesky_hcore(system, Ghalfa, Ghalfb, trial) - eJ, eK = half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial) + e1b = half_rotated_cholesky_hcore(Ghalfa, Ghalfb, trial) + eJ, eK = half_rotated_cholesky_jk(Ghalfa, Ghalfb, trial) e2b = eJ + eK return (e1b + e2b + ecore, e1b + ecore, e2b) -def half_rotated_cholesky_hcore(system, Ghalfa, Ghalfb, trial): +def half_rotated_cholesky_hcore(Ghalfa, Ghalfb, trial): r"""Calculate local for generic two-body hamiltonian. This uses the half-rotated core hamiltonian. Parameters ---------- - system : :class:`Generic` - System information for Generic. Ghalfa : :class:`numpy.ndarray` Walker's half-rotated "green's function" shape is nalpha x nbasis Ghalfa : :class:`numpy.ndarray` @@ -268,7 +229,7 @@ def ecoul_kernel_rchol_complex(rchola, rcholb, rcholbara, rcholbarb, Ghalfa, Gha @jit(nopython=True, fastmath=True) -def exx_kernel_rchol_complex(rchol, rcholbar, Ghalf): +def exx_kernel_rchol_complex(rchol, Ghalf): """Compute exchange contribution for complex rchol. Parameters @@ -281,24 +242,22 @@ def exx_kernel_rchol_complex(rchol, rcholbar, Ghalf): Returns ------- exx : :class:`numpy.ndarray` - exchange contribution for all walkers. + exchange contribution for given green's function. """ naux = rchol.shape[0] nocc = Ghalf.shape[0] - nbsf = Ghalf.shape[1] - T1 = xp.zeros((nocc, nocc), dtype=numpy.complex128) - T2 = xp.zeros((nocc, nocc), dtype=numpy.complex128) - exx = 0. + 0.j + nbasis = Ghalf.shape[1] + + exx = 0 + 0j + GhalfT = Ghalf.T.copy() # Fix this with gpu env for jx in range(naux): - rcholx = rchol[jx].reshape(nocc, nbsf) - rcholbarx = rcholbar[jx].reshape(nocc, nbsf) - T1 = rcholx.dot(Ghalf.T) - T2 = rcholbarx.dot(Ghalf.T) - exx += xp.dot(T1.ravel(), T2.T.ravel()) - exx *= 0.5 + rmi = rchol[jx].reshape((nocc, nbasis)) + T = rmi.dot(GhalfT) + exx += numpy.dot(T.ravel(), T.T.ravel()) return exx + def cholesky_jk_ghf(chol, G): nbasis = G.shape[0] // 2 @@ -354,6 +313,7 @@ def half_rotated_cholesky_jk(Ghalfa, Ghalfb, trial): exx : :class:`numpy.ndarray` Exchange energy. """ + rchola = trial._rchola rcholb = trial._rcholb @@ -361,39 +321,23 @@ def half_rotated_cholesky_jk(Ghalfa, Ghalfb, trial): if xp.isrealobj(rchola) and xp.isrealobj(rcholb): Xa = rchola.dot(Ghalfa.real.ravel()) + 1.0j * rchola.dot(Ghalfa.imag.ravel()) Xb = rcholb.dot(Ghalfb.real.ravel()) + 1.0j * rcholb.dot(Ghalfb.imag.ravel()) - ecoul = xp.dot(Xa, Xa) - ecoul += xp.dot(Xb, Xb) - ecoul += 2 * xp.dot(Xa, Xb) else: - rcholbara = trial._rcholbara - rcholbarb = trial._rcholbarb - ecoul = 2.0 * ecoul_kernel_rchol_complex( - rchola, rcholb, rcholbara, rcholbarb, Ghalfa, Ghalfb - ) + Xa = rchola.dot(Ghalfa.ravel()) + Xb = rcholb.dot(Ghalfb.ravel()) + ecoul = xp.dot(Xa, Xa) + ecoul += xp.dot(Xb, Xb) + ecoul += 2 * xp.dot(Xa, Xb) + exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta if xp.isrealobj(rchola) and xp.isrealobj(rcholb): exx = exx_kernel_rchol_real(rchola, Ghalfa) + exx_kernel_rchol_real(rcholb, Ghalfb) else: - rcholbara = trial._rcholbara - rcholbarb = trial._rcholbarb - exx = exx_kernel_rchol_complex(rchola, rcholbara, Ghalfa) - exx += exx_kernel_rchol_complex(rcholb, rcholbarb, Ghalfb) - exx *= 2.0 + exx = exx_kernel_rchol_complex(rchola, Ghalfa) + exx_kernel_rchol_complex(rcholb, Ghalfb) + synchronize() return 0.5 * ecoul, -0.5 * exx # JK energy -# FDM: Mark for deletion -def core_contribution(system, Gcore): - hc_a = numpy.einsum("pqrs,pq->rs", system.h2e, Gcore[0]) - 0.5 * numpy.einsum( - "prsq,pq->rs", system.h2e, Gcore[0] - ) - hc_b = numpy.einsum("pqrs,pq->rs", system.h2e, Gcore[1]) - 0.5 * numpy.einsum( - "prsq,pq->rs", system.h2e, Gcore[1] - ) - return (hc_a, hc_b) - - def core_contribution_cholesky(chol, G): nb = G[0].shape[-1] cmat = chol.reshape((-1, nb * nb)) @@ -410,12 +354,12 @@ def core_contribution_cholesky(chol, G): return (hca, hcb) -def fock_generic(system, P): - if system.sparse: - mf_shift = 1j * P[0].ravel() * system.hs_pot - mf_shift += 1j * P[1].ravel() * system.hs_pot - VMF = 1j * system.hs_pot.dot(mf_shift).reshape(system.nbasis, system.nbasis) +def fock_generic(hamiltonian, P): + if hamiltonian.sparse: + mf_shift = 1j * P[0].ravel() * hamiltonian.hs_pot + mf_shift += 1j * P[1].ravel() * hamiltonian.hs_pot + VMF = 1j * hamiltonian.hs_pot.dot(mf_shift).reshape(hamiltonian.nbasis, hamiltonian.nbasis) else: - mf_shift = 1j * numpy.einsum("lpq,spq->l", system.hs_pot, P) - VMF = 1j * numpy.einsum("lpq,l->pq", system.hs_pot, mf_shift) - return system.h1e_mod - VMF + mf_shift = 1j * numpy.einsum("lpq,spq->l", hamiltonian.hs_pot, P) + VMF = 1j * numpy.einsum("lpq,l->pq", hamiltonian.hs_pot, mf_shift) + return hamiltonian.h1e_mod - VMF diff --git a/ipie/estimators/handler.py b/ipie/estimators/handler.py index a35dbfe1..a02190e8 100644 --- a/ipie/estimators/handler.py +++ b/ipie/estimators/handler.py @@ -45,8 +45,6 @@ class EstimatorHandler(object): ---------- comm : MPI.COMM_WORLD MPI Communicator - system : :class:`ipie.hubbard.Hubbard` / system object in general. - Container for model input options. trial : :class:`ipie.trial_wavefunction.X' object Trial wavefunction class. verbose : bool @@ -64,7 +62,6 @@ class EstimatorHandler(object): def __init__( self, comm, - system, hamiltonian, trial, walker_state=None, @@ -107,8 +104,7 @@ def __init__( for obs in observables: try: est = _predefined_estimators[obs]( - system=system, - ham=hamiltonian, + hamiltonian=hamiltonian, trial=trial, ) self[obs] = est @@ -190,7 +186,7 @@ def increment_file_number(self): self.index = self.index + 1 self.filename = self.basename + f".{self.index}.h5" - def compute_estimators(self, comm, system, hamiltonian, trial, walker_batch): + def compute_estimators(self, hamiltonian, trial, walker_batch): """Update estimators with bached psi Parameters @@ -201,7 +197,7 @@ def compute_estimators(self, comm, system, hamiltonian, trial, walker_batch): # TODO: generalize for different block groups (loop over groups) offset = self.num_walker_props for k, e in self.items(): - e.compute_estimator(system, walker_batch, hamiltonian, trial) + e.compute_estimator(walker_batch, hamiltonian, trial) start = offset + self.get_offset(k) end = start + int(self[k].size) self.local_estimates[start:end] += e.data diff --git a/ipie/estimators/local_energy.py b/ipie/estimators/local_energy.py index 1129c684..756c548c 100644 --- a/ipie/estimators/local_energy.py +++ b/ipie/estimators/local_energy.py @@ -16,20 +16,20 @@ # Fionn Malone # +import numpy + from ipie.estimators.generic import local_energy_cholesky_opt, local_energy_generic_cholesky from ipie.estimators.greens_function_single_det import gab_mod_ovlp from ipie.legacy.estimators.ci import get_hmatel from ipie.utils.backend import arraylib as xp -def local_energy_G(system, hamiltonian, trial, G, Ghalf): +def local_energy_G(hamiltonian, trial, G, Ghalf): """Compute local energy from a given Green's function G. Parameters ---------- - system : system object - System being studied. - system : hamiltonian object + hamiltonian : hamiltonian object Hamiltonian being studied. trial : trial wavefunction object Trial wavefunction. @@ -49,32 +49,31 @@ def local_energy_G(system, hamiltonian, trial, G, Ghalf): # if type(hamiltonian) == Generic[hamiltonian.chol.dtype]: if Ghalf is not None: return local_energy_cholesky_opt( - system, hamiltonian.ecore, Ghalfa=Ghalf[0], Ghalfb=Ghalf[1], trial=trial, ) else: - return local_energy_generic_cholesky(system, hamiltonian, G) + return local_energy_generic_cholesky(hamiltonian, G) -def local_energy(system, hamiltonian, walker, trial): - return local_energy_G(system, hamiltonian, trial, walker.G, walker.Ghalf) +def local_energy(hamiltonian, walker, trial): + return local_energy_G(hamiltonian, trial, walker.G, walker.Ghalf) -def variational_energy(system, hamiltonian, trial): +def variational_energy(hamiltonian, trial): assert len(trial.psi.shape) == 2 or len(trial.psi) == 1 - return local_energy(system, hamiltonian, trial, trial) + return local_energy(hamiltonian, trial, trial) -def variational_energy_ortho_det(system, ham, occs, coeffs): +def variational_energy_ortho_det(nelec, hamiltonian, occs, coeffs): """Compute variational energy for CI-like multi-determinant expansion. Parameters ---------- - system : :class:`ipie.system` object - System object. + nelec :tuple + Number of alpha and beta electrons. occs : list of lists list of determinants. coeffs : :class:`numpy.ndarray` @@ -89,13 +88,13 @@ def variational_energy_ortho_det(system, ham, occs, coeffs): denom = 0.0 one_body = 0.0 two_body = 0.0 - nel = system.nup + system.ndown + ne = numpy.sum(nelec) for i, (occi, ci) in enumerate(zip(occs, coeffs)): denom += ci.conj() * ci for j in range(0, i + 1): cj = coeffs[j] occj = occs[j] - etot, e1b, e2b = ci.conj() * cj * get_hmatel(ham, nel, occi, occj) + etot, e1b, e2b = ci.conj() * cj * get_hmatel(hamiltonian, ne, occi, occj) evar += etot one_body += e1b two_body += e2b @@ -107,7 +106,7 @@ def variational_energy_ortho_det(system, ham, occs, coeffs): return evar / denom, one_body / denom, two_body / denom -def variational_energy_noci(system, hamiltonian, trial): +def variational_energy_noci(hamiltonian, trial): weight = 0 energies = 0 denom = 0 @@ -120,7 +119,7 @@ def variational_energy_noci(system, hamiltonian, trial): weight = (trial.coeffs[i].conj() * trial.coeffs[j]) * ovlp G = xp.array([Gup, Gdn]) # Ghalf = [Ghalfa, Ghalfb] - e = xp.array(local_energy_G(system, hamiltonian, trial, G, Ghalf=None)) + e = xp.array(local_energy_G(hamiltonian, trial, G, Ghalf=None)) energies += weight * e denom += weight return tuple(energies / denom) diff --git a/ipie/estimators/local_energy_batch.py b/ipie/estimators/local_energy_batch.py index ddf491eb..b62cb525 100644 --- a/ipie/estimators/local_energy_batch.py +++ b/ipie/estimators/local_energy_batch.py @@ -33,13 +33,11 @@ # TODO: should pass hamiltonian here and make it work for all possible types # this is a generic local_energy handler. So many possible combinations of local energy strategies... -def local_energy_batch(system, hamiltonian, walkers, trial): +def local_energy_batch(hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : Walkers object @@ -57,35 +55,31 @@ def local_energy_batch(system, hamiltonian, walkers, trial): if config.get_option("use_gpu"): if hamiltonian.chunked: return local_energy_single_det_uhf_batch_chunked_gpu( - system, hamiltonian, walkers, trial - ) + hamiltonian, walkers, trial) else: - return local_energy_single_det_batch_gpu(system, hamiltonian, walkers, trial) + return local_energy_single_det_batch_gpu(hamiltonian, walkers, trial) elif walkers.rhf: - return local_energy_single_det_rhf_batch(system, hamiltonian, walkers, trial) + return local_energy_single_det_rhf_batch(hamiltonian, walkers, trial) else: if hamiltonian.chunked: return local_energy_single_det_uhf_batch_chunked( - system, hamiltonian, walkers, trial - ) + hamiltonian, walkers, trial) else: - return local_energy_single_det_uhf(system, hamiltonian, walkers, trial) + return local_energy_single_det_uhf(hamiltonian, walkers, trial) # \TODO switch to this - # return local_energy_single_det_uhf(system, hamiltonian, walkers, trial) + # return local_energy_single_det_uhf(hamiltonian, walkers, trial) else: print("# Warning: local_energy_batch is not production level for multi-det trials.") - return local_energy_multi_det_trial_batch(system, hamiltonian, walkers, trial) + return local_energy_multi_det_trial_batch(hamiltonian, walkers, trial) -def local_energy_multi_det_trial_batch(system, hamiltonian, walkers, trial): +def local_energy_multi_det_trial_batch(hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once) with MSD. Naive O(Ndet) algorithm, no optimizations. Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : Walkers object @@ -119,7 +113,7 @@ def local_energy_multi_det_trial_batch(system, hamiltonian, walkers, trial): G = [Ga[idet], Gb[idet]] _ = [Ghalfa[idet], Ghalfb[idet]] # return (e1b+e2b+ham.ecore, e1b+ham.ecore, e2b) - e = list(local_energy_G(system, hamiltonian, trial, G, Ghalf=None)) + e = list(local_energy_G(hamiltonian, trial, G, Ghalf=None)) numer0 += w[idet] * e[0] numer1 += w[idet] * e[1] numer2 += w[idet] * e[2] diff --git a/ipie/estimators/local_energy_noci.py b/ipie/estimators/local_energy_noci.py index 0f56420d..f2947650 100644 --- a/ipie/estimators/local_energy_noci.py +++ b/ipie/estimators/local_energy_noci.py @@ -20,14 +20,13 @@ exx_kernel_batch_real_rchol, ) from ipie.hamiltonians.generic import GenericRealChol -from ipie.systems.generic import Generic from ipie.trial_wavefunction.noci import NOCI from ipie.utils.backend import arraylib as xp from ipie.walkers.uhf_walkers import UHFWalkersNOCI def local_energy_noci( - system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkersNOCI, trial: NOCI + hamiltonian: GenericRealChol, walkers: UHFWalkersNOCI, trial: NOCI ): """Compute local energy for walker batch (all walkers at once). @@ -35,8 +34,6 @@ def local_energy_noci( Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch diff --git a/ipie/estimators/local_energy_sd.py b/ipie/estimators/local_energy_sd.py index 279ae022..dc186829 100644 --- a/ipie/estimators/local_energy_sd.py +++ b/ipie/estimators/local_energy_sd.py @@ -26,7 +26,6 @@ from ipie.utils.backend import arraylib as xp from ipie.utils.backend import synchronize -from ipie.systems.generic import Generic from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol from ipie.walkers.uhf_walkers import UHFWalkers from ipie.trial_wavefunction.single_det import SingleDet @@ -260,7 +259,6 @@ def exx_kernel_batch_complex_rchol(rchol, rcholbar, Ghalf_batch): @plum.dispatch def local_energy_single_det_uhf( - system: Generic, hamiltonian: GenericComplexChol, walkers: UHFWalkers, trial: SingleDet, @@ -271,8 +269,6 @@ def local_energy_single_det_uhf( Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -315,15 +311,13 @@ def local_energy_single_det_uhf( return energy -def local_energy_single_det_batch(system, hamiltonian, walkers, trial): +def local_energy_single_det_batch(hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Single determinant case. Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -341,13 +335,13 @@ def local_energy_single_det_batch(system, hamiltonian, walkers, trial): for idx in range(nwalkers): G = [walkers.Ga[idx], walkers.Gb[idx]] Ghalf = [walkers.Ghalfa[idx], walkers.Ghalfb[idx]] - energy += [list(local_energy_G(system, hamiltonian, trial, G, Ghalf))] + energy += [list(local_energy_G(hamiltonian, trial, G, Ghalf))] energy = xp.array(energy, dtype=numpy.complex128) return energy -def local_energy_single_det_batch_einsum(system, hamiltonian, walkers, trial): +def local_energy_single_det_batch_einsum(hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Use einsum rather than numba kernels. @@ -356,8 +350,6 @@ def local_energy_single_det_batch_einsum(system, hamiltonian, walkers, trial): Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -442,15 +434,13 @@ def local_energy_single_det_batch_einsum(system, hamiltonian, walkers, trial): return energy -def local_energy_single_det_rhf_batch(system, hamiltonian, walkers, trial): +def local_energy_single_det_rhf_batch(hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Single determinant RHF case. Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -547,7 +537,7 @@ def two_body_energy_uhf(trial, walkers): @plum.dispatch def local_energy_single_det_uhf( - system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: SingleDet + hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: SingleDet ): """Compute local energy for walker batch (all walkers at once). @@ -555,8 +545,6 @@ def local_energy_single_det_uhf( Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -596,7 +584,7 @@ def local_energy_single_det_uhf( return energy -def local_energy_single_det_batch_gpu_old(system, hamiltonian, walkers, trial): +def local_energy_single_det_batch_gpu_old(hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Single determinant UHF GPU case. @@ -605,8 +593,6 @@ def local_energy_single_det_batch_gpu_old(system, hamiltonian, walkers, trial): Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -675,7 +661,7 @@ def local_energy_single_det_batch_gpu_old(system, hamiltonian, walkers, trial): return energy -def local_energy_single_det_batch_gpu(system, hamiltonian, walkers, trial, max_mem=2.0): +def local_energy_single_det_batch_gpu(hamiltonian, walkers, trial, max_mem=2.0): """Compute local energy for walker batch (all walkers at once). Single determinant UHF GPU case. @@ -684,8 +670,6 @@ def local_energy_single_det_batch_gpu(system, hamiltonian, walkers, trial, max_m Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch diff --git a/ipie/estimators/local_energy_sd_chunked.py b/ipie/estimators/local_energy_sd_chunked.py index c164d90e..b167b8e6 100644 --- a/ipie/estimators/local_energy_sd_chunked.py +++ b/ipie/estimators/local_energy_sd_chunked.py @@ -35,15 +35,13 @@ # are accumulated. -def local_energy_single_det_uhf_batch_chunked(system, hamiltonian, walker_batch, trial): +def local_energy_single_det_uhf_batch_chunked(hamiltonian, walker_batch, trial): """Compute local energy for walker batch (all walkers at once). Single determinant UHF case. Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walker_batch : WalkerBatch @@ -235,7 +233,7 @@ def exx_kernel_batch_rchol_gpu_low_mem(rchola_chunk, Ghalfa, buff): def local_energy_single_det_uhf_batch_chunked_gpu( - system, hamiltonian, walker_batch, trial, max_mem=2.0 + hamiltonian, walker_batch, trial, max_mem=2.0 ): """Compute local energy for walker batch (all walkers at once). @@ -243,8 +241,6 @@ def local_energy_single_det_uhf_batch_chunked_gpu( Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walker_batch : WalkerBatch diff --git a/ipie/estimators/local_energy_wicks.py b/ipie/estimators/local_energy_wicks.py index 7aa158df..eacb8b7b 100644 --- a/ipie/estimators/local_energy_wicks.py +++ b/ipie/estimators/local_energy_wicks.py @@ -32,15 +32,13 @@ from ipie.utils.linalg import minor_mask, minor_mask4 -def local_energy_multi_det_trial_wicks_batch(system, ham, walkers, trial): +def local_energy_multi_det_trial_wicks_batch(hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -54,11 +52,11 @@ def local_energy_multi_det_trial_wicks_batch(system, ham, walkers, trial): Total, one-body and two-body energies. """ nwalkers = walkers.nwalkers - nbasis = ham.nbasis - nchol = ham.nchol + nbasis = hamiltonian.nbasis + nchol = hamiltonian.nchol Ga = walkers.Ga.reshape((nwalkers, nbasis * nbasis)) Gb = walkers.Gb.reshape((nwalkers, nbasis * nbasis)) - e1bs = Ga.dot(ham.H1[0].ravel()) + Gb.dot(ham.H1[1].ravel()) + ham.ecore + e1bs = Ga.dot(hamiltonian.H1[0].ravel()) + Gb.dot(hamiltonian.H1[1].ravel()) + hamiltonian.ecore e2bs = [] for iwalker in range(nwalkers): @@ -77,15 +75,15 @@ def local_energy_multi_det_trial_wicks_batch(system, ham, walkers, trial): G0 = [G0a, G0b] # contribution 1 (disconnected) - cont1 = local_energy_generic_cholesky(system, ham, G0)[2] + cont1 = local_energy_generic_cholesky(hamiltonian, G0)[2] # contribution 2 (half-connected, two-leg, one-body-like) # First, Coulomb-like term - Xa = ham.chol.T.dot(G0[0].ravel()) # numpy.einsum("m,xm->x", G0[0].ravel(), ham.chol) - Xb = ham.chol.T.dot(G0[1].ravel()) # numpy.einsum("m,xm->x", G0[1].ravel(), ham.chol) + Xa = hamiltonian.chol.T.dot(G0[0].ravel()) # numpy.einsum("m,xm->x", G0[0].ravel(), hamiltonian.chol) + Xb = hamiltonian.chol.T.dot(G0[1].ravel()) # numpy.einsum("m,xm->x", G0[1].ravel(), hamiltonian.chol) - LXa = numpy.einsum("mx,x->m", ham.chol, Xa, optimize=True) - LXb = numpy.einsum("mx,x->m", ham.chol, Xb, optimize=True) + LXa = numpy.einsum("mx,x->m", hamiltonian.chol, Xa, optimize=True) + LXb = numpy.einsum("mx,x->m", hamiltonian.chol, Xb, optimize=True) LXa = LXa.reshape((nbasis, nbasis)) LXb = LXb.reshape((nbasis, nbasis)) @@ -103,7 +101,7 @@ def local_energy_multi_det_trial_wicks_batch(system, ham, walkers, trial): cont2_Kaa = 0.0 + 0.0j cont2_Kbb = 0.0 + 0.0j for x in range(nchol): - Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) + Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) LGL = Lmn.dot(G0a.T).dot(Lmn) cont2_Kaa -= numpy.sum(LGL * QCIGa) @@ -119,14 +117,14 @@ def local_energy_multi_det_trial_wicks_batch(system, ham, walkers, trial): "iq,pj,ijx->qpx", Q0a, G0a, - ham.chol.reshape((nbasis, nbasis, nchol)), + hamiltonian.chol.reshape((nbasis, nbasis, nchol)), optimize=True, ) Lbb = numpy.einsum( "iq,pj,ijx->qpx", Q0b, G0b, - ham.chol.reshape((nbasis, nbasis, nchol)), + hamiltonian.chol.reshape((nbasis, nbasis, nchol)), optimize=True, ) @@ -549,7 +547,7 @@ def build_contributions12( return cont1_J + cont1_K, cont2_J + cont2_K -def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, ham, walkers, trial, max_mem=2.0): +def local_energy_multi_det_trial_wicks_batch_opt_chunked(hamiltonian, walkers, trial, max_mem=2.0): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. @@ -561,8 +559,6 @@ def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, ham, walkers, t Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -578,11 +574,11 @@ def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, ham, walkers, t Total, one-body and two-body energies. """ nwalkers = walkers.nwalkers - nbasis = ham.nbasis - nchol = ham.nchol + nbasis = hamiltonian.nbasis + nchol = hamiltonian.nchol Ga = walkers.Ga.reshape((nwalkers, nbasis * nbasis)) Gb = walkers.Gb.reshape((nwalkers, nbasis * nbasis)) - e1b = Ga.dot(ham.H1[0].ravel()) + Gb.dot(ham.H1[1].ravel()) + ham.ecore + e1b = Ga.dot(hamiltonian.H1[0].ravel()) + Gb.dot(hamiltonian.H1[1].ravel()) + hamiltonian.ecore ovlpa0 = walkers.det_ovlpas[:, 0] ovlpb0 = walkers.det_ovlpbs[:, 0] @@ -861,7 +857,7 @@ def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, ham, walkers, t return walker_energies -def local_energy_multi_det_trial_wicks_batch_opt(system, ham, walkers, trial, max_mem=2.0): +def local_energy_multi_det_trial_wicks_batch_opt(hamiltonian, walkers, trial, max_mem=2.0): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. @@ -874,8 +870,6 @@ def local_energy_multi_det_trial_wicks_batch_opt(system, ham, walkers, trial, ma Parameters ---------- - system : system object - System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -891,11 +885,11 @@ def local_energy_multi_det_trial_wicks_batch_opt(system, ham, walkers, trial, ma Total, one-body and two-body energies. """ nwalkers = walkers.nwalkers - nbasis = ham.nbasis - nchol = ham.nchol + nbasis = hamiltonian.nbasis + nchol = hamiltonian.nchol Ga = walkers.Ga.reshape((nwalkers, nbasis * nbasis)) Gb = walkers.Gb.reshape((nwalkers, nbasis * nbasis)) - e1b = Ga.dot(ham.H1[0].ravel()) + Gb.dot(ham.H1[1].ravel()) + ham.ecore + e1b = Ga.dot(hamiltonian.H1[0].ravel()) + Gb.dot(hamiltonian.H1[1].ravel()) + hamiltonian.ecore ovlpa0 = walkers.det_ovlpas[:, 0] ovlpb0 = walkers.det_ovlpbs[:, 0] diff --git a/ipie/estimators/tests/test_estimators.py b/ipie/estimators/tests/test_estimators.py index 59adc89f..79c7465e 100644 --- a/ipie/estimators/tests/test_estimators.py +++ b/ipie/estimators/tests/test_estimators.py @@ -31,8 +31,8 @@ def test_energy_estimator(): naux = 30 nwalker = 10 system, ham, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) - estim = EnergyEstimator(system=system, ham=ham, trial=trial) - estim.compute_estimator(system, walker_batch, ham, trial) + estim = EnergyEstimator(hamiltonian=ham, trial=trial) + estim.compute_estimator(walker_batch, ham, trial) assert len(estim.names) == 5 assert estim["ENumer"].real == pytest.approx(-754.0373585215561) assert estim["ETotal"] == pytest.approx(0.0) @@ -55,14 +55,13 @@ def test_estimator_handler(): naux = 30 nwalker = 10 system, ham, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) - estim = EnergyEstimator(system=system, ham=ham, trial=trial, filename=tmp1.name) + estim = EnergyEstimator(hamiltonian=ham, trial=trial, filename=tmp1.name) estim.print_to_stdout = False from ipie.config import MPI comm = MPI.COMM_WORLD handler = EstimatorHandler( comm, - system, ham, trial, block_size=10, @@ -72,5 +71,10 @@ def test_estimator_handler(): handler["energy1"] = estim handler.json_string = "" handler.initialize(comm) - handler.compute_estimators(comm, system, ham, trial, walker_batch) - handler.compute_estimators(comm, system, ham, trial, walker_batch) + handler.compute_estimators(ham, trial, walker_batch) + handler.compute_estimators(ham, trial, walker_batch) + + +if __name__ == "__main__": + test_energy_estimator() + test_estimator_handler() diff --git a/ipie/estimators/tests/test_generic.py b/ipie/estimators/tests/test_generic.py index 4e9af561..0f2b28ce 100644 --- a/ipie/estimators/tests/test_generic.py +++ b/ipie/estimators/tests/test_generic.py @@ -33,16 +33,16 @@ def test_local_energy_cholesky(): numpy.random.seed(7) nmo = 24 nelec = (4, 2) + nup, ndown = nelec h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=enuc, ) - ci, wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) + ci, wfn = get_random_nomsd(nup, ndown, ham.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - e = local_energy_generic_cholesky(system, ham, trial.G, Ghalf=trial.Ghalf) + e = local_energy_generic_cholesky(ham, trial.G, Ghalf=trial.Ghalf) assert e[0] == pytest.approx(20.6826247016273) assert e[1] == pytest.approx(23.0173528796140) assert e[2] == pytest.approx(-2.3347281779866) @@ -53,17 +53,17 @@ def test_local_energy_cholesky_opt(): numpy.random.seed(7) nmo = 24 nelec = (4, 2) + nup, ndown = nelec h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=enuc, ) - ci, wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) + ci, wfn = get_random_nomsd(nup, ndown, ham.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) trial.half_rotate(ham) - e = local_energy_cholesky_opt(system, ham.ecore, trial.Ghalf[0], trial.Ghalf[1], trial) + e = local_energy_cholesky_opt(ham.ecore, trial.Ghalf[0], trial.Ghalf[1], trial) assert e[0] == pytest.approx(20.6826247016273) assert e[1] == pytest.approx(23.0173528796140) assert e[2] == pytest.approx(-2.3347281779866) @@ -89,7 +89,6 @@ def test_local_energy_cholesky_opt_batched(): Gahalf_batched = numpy.array([trial.Ghalf[0], trial.Ghalf[0], trial.Ghalf[0]]) Gbhalf_batched = numpy.array([trial.Ghalf[1], trial.Ghalf[1], trial.Ghalf[1]]) res = local_energy_generic_cholesky_opt_batched( - system, ham, Ga_batched, Gb_batched, diff --git a/ipie/estimators/tests/test_generic_batch.py b/ipie/estimators/tests/test_generic_batch.py index 27bf0003..73232e99 100644 --- a/ipie/estimators/tests/test_generic_batch.py +++ b/ipie/estimators/tests/test_generic_batch.py @@ -43,18 +43,18 @@ def test_greens_function_batch(): numpy.random.seed(7) nmo = 10 nelec = (6, 5) + nup, ndown = nelec nwalkers = 12 nsteps = 25 dt = 0.005 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) + wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) trial = ParticleHole(wfn, nelec, nmo) trial.build() trial.half_rotate(ham) @@ -67,9 +67,10 @@ def test_greens_function_batch(): ecore=0, ) + system = Generic(nelec=nelec) legacy_walkers = build_legacy_test_case(wfn, init, system, legacy_ham, nsteps, nwalkers, dt) numpy.random.seed(7) - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) for iw in range(nwalkers): walkers.phia[iw] = legacy_walkers[iw].phi[:, : nelec[0]].copy() @@ -91,18 +92,18 @@ def test_local_energy_single_det_batch(): numpy.random.seed(7) nmo = 10 nelec = (5, 5) + nup, ndown = nelec nwalkers = 10 nsteps = 25 dt = 0.005 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -122,6 +123,7 @@ def test_local_energy_single_det_batch(): options={"symmetry": False}, ) numpy.random.seed(7) + system = Generic(nelec=nelec) legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) @@ -129,15 +131,15 @@ def test_local_energy_single_det_batch(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": 10}) prop = PhaselessGeneric(time_step=qmc["dt"]) prop.build(ham, trial) - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) for i in range(nsteps): prop.propagate_walkers(walkers, ham, trial, 0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_batch(system, ham, walkers, trial) - energies_uhf = local_energy_single_det_uhf(system, ham, walkers, trial) + energies = local_energy_single_det_batch(ham, walkers, trial) + energies_uhf = local_energy_single_det_uhf(ham, walkers, trial) assert numpy.allclose(energies, energies_uhf) @@ -154,6 +156,7 @@ def test_local_energy_single_det_batch_packed(): numpy.random.seed(7) nmo = 10 nelec = (5, 5) + nup, ndown = nelec nwalkers = 10 nsteps = 25 dt = 0.005 @@ -168,8 +171,6 @@ def test_local_energy_single_det_batch_packed(): pack_cholesky(idx[0], idx[1], chol_packed, chol) chol = chol.reshape((nmo * nmo, nchol)) - system = Generic(nelec=nelec) - ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol, @@ -187,7 +188,7 @@ def test_local_energy_single_det_batch_packed(): ) # Test PH type wavefunction. - ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -199,6 +200,7 @@ def test_local_energy_single_det_batch_packed(): trial.half_rotate(ham) numpy.random.seed(7) + system = Generic(nelec=nelec) legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) @@ -206,18 +208,18 @@ def test_local_energy_single_det_batch_packed(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(time_step=qmc["dt"]) prop.build(ham, trial) - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) for i in range(nsteps): prop.propagate_walkers(walkers, ham, trial, 0.0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_batch(system, ham, walkers, trial) + energies = local_energy_single_det_batch(ham, walkers, trial) for iw in range(nwalkers): # unnecessary test - # energy = local_energy_single_det_batch(system, ham, walkers, trial, iw = iw) + # energy = local_energy_single_det_batch(ham, walkers, trial, iw = iw) # assert numpy.allclose(energy, energies[iw]) assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) assert numpy.allclose(walkers.phib[iw], legacy_walkers[iw].phi[:, nelec[0] :]) @@ -231,16 +233,15 @@ def test_local_energy_single_det_batch_rhf(): numpy.random.seed(7) nmo = 10 nelec = (5, 5) + nup, ndown = nelec nwalkers = 10 nsteps = 25 dt = 0.005 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0 ) - ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) - ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -260,6 +261,7 @@ def test_local_energy_single_det_batch_rhf(): options={"symmetry": False}, ) + system = Generic(nelec=nelec) legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) @@ -271,7 +273,7 @@ def test_local_energy_single_det_batch_rhf(): # walkers = SingleDetWalkerBatch( # system, ham, trial, nwalkers, init, walker_opts={"rhf": True} # ) - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) walkers.rhf = True for i in range(nsteps): @@ -279,7 +281,7 @@ def test_local_energy_single_det_batch_rhf(): walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_rhf_batch(system, ham, walkers, trial) + energies = local_energy_single_det_rhf_batch(ham, walkers, trial) for iw in range(nwalkers): assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) @@ -294,6 +296,7 @@ def test_local_energy_single_det_batch_rhf_packed(): numpy.random.seed(7) nmo = 10 nelec = (5, 5) + nup, ndown = nelec nwalkers = 10 nsteps = 25 dt = 0.005 @@ -310,7 +313,6 @@ def test_local_energy_single_det_batch_rhf_packed(): pack_cholesky(idx[0], idx[1], chol_packed, chol) chol = chol.reshape((nmo * nmo, nchol)) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol, @@ -325,7 +327,7 @@ def test_local_energy_single_det_batch_rhf_packed(): options={"symmetry": True}, ) - ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -338,6 +340,7 @@ def test_local_energy_single_det_batch_rhf_packed(): init[:, : nelec[0]] = init[:, nelec[0] :].copy() numpy.random.seed(7) + system = Generic(nelec=nelec) legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) @@ -349,7 +352,7 @@ def test_local_energy_single_det_batch_rhf_packed(): # walkers = SingleDetWalkerBatch( # system, ham, trial, nwalkers, init, walker_opts=walker_opts # ) - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) walkers.rhf = True @@ -358,7 +361,7 @@ def test_local_energy_single_det_batch_rhf_packed(): walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_rhf_batch(system, ham, walkers, trial) + energies = local_energy_single_det_rhf_batch(ham, walkers, trial) for iw in range(nwalkers): assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) diff --git a/ipie/estimators/tests/test_generic_chunked.py b/ipie/estimators/tests/test_generic_chunked.py index 0b1d3af2..022b5be5 100644 --- a/ipie/estimators/tests/test_generic_chunked.py +++ b/ipie/estimators/tests/test_generic_chunked.py @@ -48,6 +48,7 @@ def test_generic_chunked(): numpy.random.seed(7) nmo = 24 nelec = (4, 2) + nup, ndown = nelec h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) h1e = comm.bcast(h1e) @@ -70,12 +71,12 @@ def test_generic_chunked(): chol = chol.reshape((nmo * nmo, nchol)) - system = Generic(nelec=nelec) ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, ecore=enuc) - _, wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) + _, wfn = get_random_nomsd(nup, ndown, ham.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) trial.half_rotate(ham) + system = Generic(nelec=nelec) trial.calculate_energy(system, ham) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) @@ -93,7 +94,7 @@ def test_generic_chunked(): init_walker = numpy.hstack([trial.psi0a, trial.psi0b]) walkers = UHFWalkersTrial( - trial, init_walker, system.nup, system.ndown, ham.nbasis, nwalkers, mpi_handler=mpi_handler + trial, init_walker, nup, ndown, ham.nbasis, nwalkers, mpi_handler=mpi_handler ) walkers.build(trial) @@ -101,9 +102,9 @@ def test_generic_chunked(): prop.propagate_walkers(walkers, ham, trial, trial.energy) walkers.reortho() - energies = local_energy_single_det_batch(system, ham, walkers, trial) + energies = local_energy_single_det_batch(ham, walkers, trial) - energies_chunked = local_energy_single_det_uhf_batch_chunked(system, ham, walkers, trial) + energies_chunked = local_energy_single_det_uhf_batch_chunked(ham, walkers, trial) assert numpy.allclose(energies, energies_chunked) diff --git a/ipie/estimators/tests/test_generic_chunked_gpu.py b/ipie/estimators/tests/test_generic_chunked_gpu.py index 3e36a90e..8b3722d5 100644 --- a/ipie/estimators/tests/test_generic_chunked_gpu.py +++ b/ipie/estimators/tests/test_generic_chunked_gpu.py @@ -55,6 +55,7 @@ def test_generic_chunked_gpu(): numpy.random.seed(7) nmo = 24 nelec = (4, 2) + nup, ndown = nelec h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) h1e = comm.bcast(h1e) @@ -77,12 +78,12 @@ def test_generic_chunked_gpu(): chol = chol.reshape((nmo * nmo, nchol)) - system = Generic(nelec=nelec) ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, chol_packed=chol_packed, ecore=enuc) - wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) + wfn = get_random_nomsd(nup, ndown, ham.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) trial.half_rotate(ham) + system = Generic(nelec=nelec) trial.calculate_energy(system, ham) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) @@ -99,8 +100,7 @@ def test_generic_chunked_gpu(): prop.build(ham, trial, mpi_handler=mpi_handler) walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, mpi_handler=mpi_handler - ) + trial, init, nup, ndown, ham.nbasis, nwalkers, mpi_handler=mpi_handler) walkers.build(trial) if not no_gpu: prop.cast_to_cupy() @@ -114,11 +114,10 @@ def test_generic_chunked_gpu(): trial._rchola = cupy.asarray(trial._rchola) trial._rcholb = cupy.asarray(trial._rcholb) - energies_einsum = local_energy_single_det_batch_gpu(system, ham, walkers, trial) - energies_chunked = local_energy_single_det_uhf_batch_chunked_gpu(system, ham, walkers, trial) + energies_einsum = local_energy_single_det_batch_gpu(ham, walkers, trial) + energies_chunked = local_energy_single_det_uhf_batch_chunked_gpu(ham, walkers, trial) energies_chunked_low_mem = local_energy_single_det_uhf_batch_chunked_gpu( - system, ham, walkers, trial, max_mem=1e-6 - ) + ham, walkers, trial, max_mem=1e-6) assert numpy.allclose(energies_einsum, energies_chunked) assert numpy.allclose(energies_einsum, energies_chunked_low_mem) diff --git a/ipie/estimators/tests/test_generic_complex.py b/ipie/estimators/tests/test_generic_complex.py index 105dca02..5a5d630f 100644 --- a/ipie/estimators/tests/test_generic_complex.py +++ b/ipie/estimators/tests/test_generic_complex.py @@ -22,7 +22,6 @@ from ipie.estimators.energy import local_energy from ipie.utils.testing import build_test_case_handlers -from ipie.systems.generic import Generic from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.utils.misc import dotdict @@ -57,7 +56,6 @@ def test_local_energy_single_det_vs_real(): ham = test_handler.hamiltonian walkers = test_handler.walkers - system = Generic(nelec) trial = test_handler.trial chol = ham.chol @@ -67,10 +65,10 @@ def test_local_energy_single_det_vs_real(): numpy.array(ham.H1, dtype=numpy.complex128), cx_chol, ham.ecore, verbose=False ) - energy = local_energy(system, ham, walkers, trial) + energy = local_energy(ham, walkers, trial) trial.half_rotate(cx_ham) - cx_energy = local_energy(system, cx_ham, walkers, trial) + cx_energy = local_energy(cx_ham, walkers, trial) numpy.testing.assert_allclose(energy, cx_energy, atol=1e-10) @@ -106,12 +104,11 @@ def test_local_energy_single_det_vs_eri(): ham = test_handler.hamiltonian walkers = test_handler.walkers - system = Generic(nelec) trial = test_handler.trial walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) - energy = local_energy(system, ham, walkers, trial) + energy = local_energy(ham, walkers, trial) etot = energy[:, 0] e1 = energy[:, 1] e2 = energy[:, 2] diff --git a/ipie/estimators/tests/test_generic_noci.py b/ipie/estimators/tests/test_generic_noci.py index 1cb1aec9..2732faf9 100644 --- a/ipie/estimators/tests/test_generic_noci.py +++ b/ipie/estimators/tests/test_generic_noci.py @@ -22,7 +22,6 @@ from ipie.estimators.energy import local_energy from ipie.estimators.local_energy_wicks import local_energy_multi_det_trial_wicks_batch_opt_chunked from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.systems.generic import Generic from ipie.trial_wavefunction.noci import NOCI from ipie.trial_wavefunction.particle_hole import ParticleHole from ipie.trial_wavefunction.single_det import SingleDet @@ -35,23 +34,22 @@ def test_greens_function_noci(): np.random.seed(7) nmo = 12 nelec = (7, 7) + nup, ndown = nelec nwalkers = 10 nsteps = 100 ndets = 11 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. coeffs, wfn, init = get_random_nomsd( - system.nup, system.ndown, ham.nbasis, ndet=ndets, init=True - ) + nup, ndown, ham.nbasis, ndet=ndets, init=True) trial = NOCI((coeffs, wfn), nelec, nmo) trial.build() trial.half_rotate(ham) g = trial.build_one_rdm() assert np.isclose(g[0].trace(), nelec[0]) assert np.isclose(g[1].trace(), nelec[0]) - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) assert walkers.Gia.shape == (ndets, nwalkers, nmo, nmo) assert walkers.Ghalfa.shape == (ndets, nwalkers, nelec[0], nmo) @@ -68,15 +66,15 @@ def test_local_energy_noci(): np.random.seed(7) nmo = 12 nelec = (7, 7) + nup, ndown = nelec nwalkers = 10 nsteps = 100 ndets = 11 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. coeffs, wfn, init = get_random_nomsd( - system.nup, system.ndown, ham.nbasis, ndet=ndets, init=True, cplx=False + nup, ndown, ham.nbasis, ndet=ndets, init=True, cplx=False ) wfn0 = wfn[0].copy() for i in range(len(wfn)): @@ -86,27 +84,27 @@ def test_local_energy_noci(): trial.build() trial.half_rotate(ham) g = trial.build_one_rdm() - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) - energy = local_energy(system, ham, walkers, trial) + energy = local_energy(ham, walkers, trial) trial_sd = SingleDet(wfn[0], nelec, nmo) - walkers_sd = UHFWalkersTrial(trial_sd, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers_sd = UHFWalkersTrial(trial_sd, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) - energy_sd = local_energy(system, ham, walkers, trial) + energy_sd = local_energy(ham, walkers, trial) assert np.allclose(energy, energy_sd) coeffs, wfn, init = get_random_nomsd( - system.nup, system.ndown, ham.nbasis, ndet=ndets, init=True, cplx=False + nup, ndown, ham.nbasis, ndet=ndets, init=True, cplx=False ) trial = NOCI((coeffs, wfn), nelec, nmo) trial.build() trial.half_rotate(ham) g = trial.build_one_rdm() - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) - energy = local_energy(system, ham, walkers, trial) + energy = local_energy(ham, walkers, trial) assert not np.allclose(energy, energy_sd) # Test against PHMSD - wfn, init = get_random_phmsd_opt(system.nup, system.ndown, ham.nbasis, ndet=11, init=True) + wfn, init = get_random_phmsd_opt(nup, ndown, ham.nbasis, ndet=11, init=True) trial_phmsd = ParticleHole( wfn, nelec, @@ -124,14 +122,14 @@ def test_local_energy_noci(): trial = NOCI((wfn[0], noci), nelec, nmo) trial.build() trial.half_rotate(ham) - walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers.build(trial) ovlp_noci = trial.calc_overlap(walkers) trial.calc_greens_function(walkers) fb_noci = trial.calc_force_bias(ham, walkers) - energy = local_energy(system, ham, walkers, trial) + energy = local_energy(ham, walkers, trial) walkers_phmsd = UHFWalkersTrial( - trial_phmsd, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_phmsd, init, nup, ndown, ham.nbasis, nwalkers ) walkers_phmsd.build(trial_phmsd) trial_phmsd.calc_greens_function(walkers_phmsd) @@ -140,6 +138,10 @@ def test_local_energy_noci(): assert np.allclose(walkers_phmsd.Gb, walkers.Gb) assert np.allclose(fb_noci, trial_phmsd.calc_force_bias(ham, walkers)) e_phmsd = local_energy_multi_det_trial_wicks_batch_opt_chunked( - system, ham, walkers_phmsd, trial_phmsd - ) + ham, walkers_phmsd, trial_phmsd) assert np.allclose(energy, e_phmsd) + + +if __name__ == '__main__': + test_greens_function_noci() + test_local_energy_noci() diff --git a/ipie/estimators/tests/test_generic_phmsd.py b/ipie/estimators/tests/test_generic_phmsd.py index 1bd5e5e2..440c53a8 100644 --- a/ipie/estimators/tests/test_generic_phmsd.py +++ b/ipie/estimators/tests/test_generic_phmsd.py @@ -55,16 +55,16 @@ def test_greens_function_wicks_opt(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) + nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=3000, init=True) + wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=3000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # wfn_2 = (ci[:100], oa[:100], ob[:100]) @@ -84,13 +84,13 @@ def test_greens_function_wicks_opt(): trial_opt.build() numpy.random.seed(7) - walkers_wick = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers_wick = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers_wick.build(trial) - walkers_slow = UHFWalkersTrial(trial_slow, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers_slow = UHFWalkersTrial(trial_slow, init, nup, ndown, ham.nbasis, nwalkers) walkers_slow.build(trial_slow) - walkers_opt = UHFWalkersTrial(trial_opt, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers_opt = UHFWalkersTrial(trial_opt, init, nup, ndown, ham.nbasis, nwalkers) walkers_opt.build(trial_opt) options = {"hybrid": True} @@ -139,15 +139,15 @@ def test_greens_function_edge_cases(): numpy.random.seed(7) nmo = 12 nelec = (1, 1) + nup, ndown = nelec nwalkers = 10 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. - wfn, init = get_random_phmsd_opt(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) + wfn, init = get_random_phmsd_opt(nup, ndown, ham.nbasis, ndet=1, init=True) trial = ParticleHole(wfn, nelec, nmo, verbose=False) trial.build() - walkers_wick = UHFWalkersParticleHole(init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers_wick = UHFWalkersParticleHole(init, nup, ndown, ham.nbasis, nwalkers) walkers_wick.build(trial) ovlps_ref_wick = greens_function_multi_det_wicks_opt(walkers_wick, trial) @@ -249,17 +249,17 @@ def test_det_matrix(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) + nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=3000, init=True) + wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=3000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -275,7 +275,7 @@ def test_det_matrix(): prop = PhaselessGeneric(qmc["dt"]) prop.build(ham, trial) - walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walker_batch.build(trial) numpy.random.seed(7) @@ -314,19 +314,19 @@ def test_phmsd_local_energy(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) + nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - # wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=5, init=True) + # wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=5, init=True) wfn, init = get_random_phmsd( - system.nup, system.ndown, ham.nbasis, ndet=3000, init=True, cmplx=False + nup, ndown, ham.nbasis, ndet=3000, init=True, cmplx=False ) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too @@ -351,21 +351,21 @@ def test_phmsd_local_energy(): trial_test.build() trial_test.half_rotate(ham) numpy.random.seed(7) - walkers_wick = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walkers_wick = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walkers_wick.build(trial) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) options = {"hybrid": True} - walker_batch = UHFWalkersTrial(trial_slow, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial_slow, init, nup, ndown, ham.nbasis, nwalkers) walker_batch.build(trial_slow) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_test, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_test.build(trial_test) walker_batch_test2 = UHFWalkersTrial( - trial, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_test2.build(trial) @@ -396,11 +396,10 @@ def test_phmsd_local_energy(): assert numpy.allclose(walker_batch_test2.Gb, walker_batch.Gb) assert numpy.allclose(walker_batch_test.det_ovlpas, walker_batch_test2.det_ovlpas) assert numpy.allclose(walker_batch_test.det_ovlpbs, walker_batch_test2.det_ovlpbs) - e_simple = local_energy_multi_det_trial_batch(system, ham, walker_batch, trial) - e_wicks = local_energy_multi_det_trial_wicks_batch(system, ham, walker_batch_test2, trial) + e_simple = local_energy_multi_det_trial_batch(ham, walker_batch, trial) + e_wicks = local_energy_multi_det_trial_wicks_batch(ham, walker_batch_test2, trial) e_wicks_opt = local_energy_multi_det_trial_wicks_batch_opt( - system, ham, walker_batch_test, trial_test - ) + ham, walker_batch_test, trial_test) assert numpy.allclose(e_simple, e_wicks) assert numpy.allclose(e_simple, e_wicks_opt) @@ -412,16 +411,16 @@ def test_kernels_energy(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) + nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) - wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=5000, init=True) + wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=5000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -436,7 +435,7 @@ def test_kernels_energy(): prop = PhaselessGeneric(qmc["dt"]) prop.build(ham, trial) - walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walker_batch.build(trial) numpy.random.seed(7) for i in range(nsteps): @@ -461,8 +460,8 @@ def test_kernels_energy(): nbasis = ham.nbasis from ipie.utils.testing import shaped_normal - Laa = shaped_normal((nwalkers, nbasis, system.nup, nchol)) - Lbb = shaped_normal((nwalkers, nbasis, system.ndown, nchol)) + Laa = shaped_normal((nwalkers, nbasis, nup, nchol)) + Lbb = shaped_normal((nwalkers, nbasis, ndown, nchol)) # 1. fill_opp_spin_factors_batched_singles( trial.cre_ex_b[1], @@ -629,17 +628,17 @@ def test_kernels_gf(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) + nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, # options={"symmetry": False}, ) - wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=5000, init=True) + wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=5000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -654,7 +653,7 @@ def test_kernels_gf(): prop = PhaselessGeneric(qmc["dt"]) prop.build(ham, trial) - walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walker_batch.build(trial) numpy.random.seed(7) @@ -746,12 +745,12 @@ def test_kernels_gf_active_space(): numpy.random.seed(7) nmo = 30 nelec = (9, 9) + nup, ndown = nelec nwalkers = 1 nsteps = 100 nact = 12 ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), @@ -805,12 +804,12 @@ def test_kernels_gf_active_space(): init = numpy.hstack([I[:, : nelec[0]], I[:, : nelec[1]]]) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_ref, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_test, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_test.build(trial_test) @@ -934,12 +933,12 @@ def test_kernels_energy_active_space(): numpy.random.seed(7) nmo = 30 nelec = (9, 9) + nup, ndown = nelec nwalkers = 1 nsteps = 100 nact = 12 ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), @@ -997,12 +996,12 @@ def test_kernels_energy_active_space(): prop.build(ham, trial_ref) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_ref, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_test, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_test.build(trial_test) @@ -1040,7 +1039,7 @@ def test_kernels_energy_active_space(): walker_batch_ref.CIb.fill(0.0 + 0.0j) from ipie.utils.testing import shaped_normal - Lbb = shaped_normal((nwalkers, nmo, system.ndown, nchol)) + Lbb = shaped_normal((nwalkers, nmo, ndown, nchol)) slices_alpha, slices_beta = trial_test.slices_alpha, trial_test.slices_beta assert trial_ref.nfrozen != trial_test.nfrozen # 1. @@ -1217,13 +1216,13 @@ def test_phmsd_local_energy_active_space(): numpy.random.seed(7) nmo = 30 nelec = (9, 9) + nup, ndown = nelec nwalkers = 1 nsteps = 100 nact = 12 ncore = 2 core = [0, 1] h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), @@ -1269,12 +1268,12 @@ def test_phmsd_local_energy_active_space(): prop.build(ham, trial_ref) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_ref, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_test, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_test.build(trial_test) @@ -1300,10 +1299,9 @@ def test_phmsd_local_energy_active_space(): # assert numpy.allclose(walker_batch_test.CIa, walker_batch_ref.CIa) # assert numpy.allclose(walker_batch_test.CIb, walker_batch_ref.CIb) assert trial_ref.nfrozen != trial_test.nfrozen - e_wicks_opt = local_energy_multi_det_trial_wicks_batch(system, ham, walker_batch_ref, trial_ref) + e_wicks_opt = local_energy_multi_det_trial_wicks_batch(ham, walker_batch_ref, trial_ref) e_wicks_opt_act = local_energy_multi_det_trial_wicks_batch_opt( - system, ham, walker_batch_test, trial_test - ) + ham, walker_batch_test, trial_test) assert numpy.allclose(e_wicks_opt, e_wicks_opt_act) @@ -1312,13 +1310,14 @@ def test_phmsd_local_energy_active_space(): def test_phmsd_local_energy_active_space_polarised(): numpy.random.seed(7) nelec = (9, 7) + nup, ndown = nelec + ne = numpy.sum(nelec) nwalkers = 1 nsteps = 10 nact = 12 nmo = 20 ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), @@ -1328,7 +1327,7 @@ def test_phmsd_local_energy_active_space_polarised(): from ipie.utils.testing import get_random_phmsd_opt, shaped_normal wfn, init = get_random_phmsd_opt(7, 5, nact, ndet=100, init=True) - init = shaped_normal((nmo, system.ne)) + init = shaped_normal((nmo, ne)) ci, occa, occb = wfn core = [0, 1] with_core_a = numpy.array( @@ -1363,16 +1362,16 @@ def test_phmsd_local_energy_active_space_polarised(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) options = {"hybrid": True} - walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walker_batch.build(trial) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_test, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_test.build(trial_test) walker_batch_test_chunked = UHFWalkersTrial( - trial_test_chunked, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_test_chunked, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_test_chunked.build(trial_test_chunked) @@ -1405,27 +1404,26 @@ def test_phmsd_local_energy_active_space_polarised(): assert numpy.allclose(walker_batch.Gb, walker_batch_test.Gb) assert numpy.allclose(walker_batch.Ga, walker_batch_test_chunked.Ga) assert numpy.allclose(walker_batch.Gb, walker_batch_test_chunked.Gb) - e_ref = local_energy_multi_det_trial_batch(system, ham, walker_batch, trial) + e_ref = local_energy_multi_det_trial_batch(ham, walker_batch, trial) e_wicks = local_energy_multi_det_trial_wicks_batch_opt( - system, ham, walker_batch_test, trial_test - ) + ham, walker_batch_test, trial_test) assert numpy.allclose(e_ref, e_wicks) e_wicks_chunked = local_energy_multi_det_trial_wicks_batch_opt_chunked( - system, ham, walker_batch_test_chunked, trial_test_chunked - ) + ham, walker_batch_test_chunked, trial_test_chunked) @pytest.mark.unit def test_phmsd_local_energy_active_space_non_aufbau(): numpy.random.seed(7) nelec = (9, 9) + nup, ndown = nelec + ne = numpy.sum(nelec) nwalkers = 4 nsteps = 10 nact = 12 nmo = 20 ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - system = Generic(nelec=nelec) ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), @@ -1435,7 +1433,7 @@ def test_phmsd_local_energy_active_space_non_aufbau(): from ipie.utils.testing import get_random_phmsd_opt, shaped_normal wfn, init = get_random_phmsd_opt(7, 7, nact, ndet=100, init=True, cmplx_coeffs=False) - init = shaped_normal((nmo, system.ne)) + init = shaped_normal((nmo, ne)) ci, occa, occb = wfn tmp = occa[0] occa[0] = occa[2] @@ -1494,16 +1492,16 @@ def test_phmsd_local_energy_active_space_non_aufbau(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) options = {"hybrid": True} - walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) walker_batch.build(trial) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_ref, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers + trial_test, init, nup, ndown, ham.nbasis, nwalkers ) walker_batch_test.build(trial_test) @@ -1553,14 +1551,12 @@ def test_phmsd_local_energy_active_space_non_aufbau(): assert numpy.allclose(walker_batch_test.det_ovlpas, walker_batch_ref.det_ovlpas) assert numpy.allclose(walker_batch_test.det_ovlpbs, walker_batch_ref.det_ovlpbs) assert trial_ref.nfrozen != trial_test.nfrozen - e_wicks = local_energy_multi_det_trial_batch(system, ham, walker_batch, trial) - e_wicks_opt = local_energy_multi_det_trial_wicks_batch(system, ham, walker_batch_ref, trial_ref) + e_wicks = local_energy_multi_det_trial_batch(ham, walker_batch, trial) + e_wicks_opt = local_energy_multi_det_trial_wicks_batch(ham, walker_batch_ref, trial_ref) e_wicks_opt_act = local_energy_multi_det_trial_wicks_batch_opt( - system, ham, walker_batch_test, trial_test - ) + ham, walker_batch_test, trial_test) e_wicks_opt_chunk = local_energy_multi_det_trial_wicks_batch_opt_chunked( - system, ham, walker_batch_test, trial_test - ) + ham, walker_batch_test, trial_test) assert numpy.allclose(e_wicks, e_wicks_opt) assert numpy.allclose(e_wicks_opt, e_wicks_opt_act) @@ -1569,10 +1565,15 @@ def test_phmsd_local_energy_active_space_non_aufbau(): if __name__ == "__main__": test_greens_function_wicks_opt() - # test_cofactor_matrix() - # test_cofactor_matrix_4() - # test_det_matrix() - # test_phmsd_local_energy() - # test_kernels_energy() - # test_kernels_gf() - # test_kernels_gf_active_space() + test_greens_function_edge_cases() + test_cofactor_matrix() + test_cofactor_matrix_4() + test_det_matrix() + test_phmsd_local_energy() + test_kernels_energy() + test_kernels_gf() + test_kernels_gf_active_space() + test_kernels_energy_active_space() + test_phmsd_local_energy_active_space() + test_phmsd_local_energy_active_space_polarised() + test_phmsd_local_energy_active_space_non_aufbau() diff --git a/ipie/legacy/estimators/generic.py b/ipie/legacy/estimators/generic.py index 1682e1e9..910a5f92 100644 --- a/ipie/legacy/estimators/generic.py +++ b/ipie/legacy/estimators/generic.py @@ -190,6 +190,37 @@ def _exx_compute_batch(rchol_a, rchol_b, GaT_stacked, GbT_stacked, lwalker): return exx_vec_b + exx_vec_a +# FDM: deprecated remove? +def local_energy_generic_opt(system, G, Ghalf=None, eri=None): + """Compute local energy using half-rotated eri tensor.""" + + na = system.nup + nb = system.ndown + M = system.nbasis + assert eri is not None + + vipjq_aa = eri[0, : na**2 * M**2].reshape((na, M, na, M)) + vipjq_bb = eri[0, na**2 * M**2 : na**2 * M**2 + nb**2 * M**2].reshape( + (nb, M, nb, M) + ) + vipjq_ab = eri[0, na**2 * M**2 + nb**2 * M**2 :].reshape((na, M, nb, M)) + + Ga, Gb = Ghalf[0], Ghalf[1] + # Element wise multiplication. + e1b = numpy.sum(system.H1[0] * G[0]) + numpy.sum(system.H1[1] * G[1]) + # Coulomb + eJaa = 0.5 * numpy.einsum("irjs,ir,js", vipjq_aa, Ga, Ga) + eJbb = 0.5 * numpy.einsum("irjs,ir,js", vipjq_bb, Gb, Gb) + eJab = numpy.einsum("irjs,ir,js", vipjq_ab, Ga, Gb) + + eKaa = -0.5 * numpy.einsum("irjs,is,jr", vipjq_aa, Ga, Ga) + eKbb = -0.5 * numpy.einsum("irjs,is,jr", vipjq_bb, Gb, Gb) + + e2b = eJaa + eJbb + eJab + eKaa + eKbb + + return (e1b + e2b + system.ecore, e1b + system.ecore, e2b) + + def local_energy_generic_cholesky_opt_batched( system, ham, diff --git a/ipie/legacy/estimators/local_energy.py b/ipie/legacy/estimators/local_energy.py index 8de3ce93..53225747 100644 --- a/ipie/legacy/estimators/local_energy.py +++ b/ipie/legacy/estimators/local_energy.py @@ -5,10 +5,10 @@ from ipie.legacy.estimators.ueg import local_energy_ueg except ImportError as e: print(e) -from ipie.estimators.generic import local_energy_generic_opt from ipie.legacy.estimators.ci import get_hmatel from ipie.legacy.estimators.generic import ( local_energy_generic, + local_energy_generic_opt, local_energy_generic_cholesky, local_energy_generic_cholesky_opt, local_energy_generic_cholesky_opt_stochastic, diff --git a/ipie/qmc/afqmc.py b/ipie/qmc/afqmc.py index 560fcfa6..f7a9ec9d 100644 --- a/ipie/qmc/afqmc.py +++ b/ipie/qmc/afqmc.py @@ -236,7 +236,6 @@ def setup_estimators( comm = self.mpi_handler.comm self.estimators = EstimatorHandler( self.mpi_handler.comm, - self.system, self.hamiltonian, self.trial, walker_state=self.accumulators, @@ -254,8 +253,6 @@ def setup_estimators( self.estimators.initialize(comm) # Calculate estimates for initial distribution of walkers. self.estimators.compute_estimators( - comm, - self.system, self.hamiltonian, self.trial, self.walkers, @@ -396,8 +393,6 @@ def run( start = time.time() if step % self.params.num_steps_per_block == 0: self.estimators.compute_estimators( - comm, - self.system, self.hamiltonian, self.trial, self.walkers, diff --git a/ipie/qmc/tests/test_afqmc_multi_det_batch.py b/ipie/qmc/tests/test_afqmc_multi_det_batch.py index 34a462e2..8ba18da6 100644 --- a/ipie/qmc/tests/test_afqmc_multi_det_batch.py +++ b/ipie/qmc/tests/test_afqmc_multi_det_batch.py @@ -78,8 +78,6 @@ def test_generic_multi_det_batch(): afqmc.run(verbose=0, estimator_filename=tmpf.name) afqmc.finalise(verbose=0) afqmc.estimators.compute_estimators( - comm, - afqmc.system, afqmc.hamiltonian, afqmc.trial, afqmc.walkers, diff --git a/ipie/qmc/tests/test_afqmc_single_det_batch.py b/ipie/qmc/tests/test_afqmc_single_det_batch.py index d401310b..658c0ae0 100644 --- a/ipie/qmc/tests/test_afqmc_single_det_batch.py +++ b/ipie/qmc/tests/test_afqmc_single_det_batch.py @@ -81,8 +81,6 @@ def test_generic_single_det_batch(): afqmc.run(verbose=False, estimator_filename=tmpf.name) afqmc.finalise(verbose=0) afqmc.estimators.compute_estimators( - comm, - afqmc.system, afqmc.hamiltonian, afqmc.trial, afqmc.walkers, @@ -187,8 +185,6 @@ def test_generic_single_det_batch_density_diff(): afqmc.run(verbose=False, estimator_filename=tmpf.name) afqmc.finalise(verbose=0) afqmc.estimators.compute_estimators( - comm, - afqmc.system, afqmc.hamiltonian, afqmc.trial, afqmc.walkers, diff --git a/ipie/trial_wavefunction/noci.py b/ipie/trial_wavefunction/noci.py index b369fef6..28dc3668 100644 --- a/ipie/trial_wavefunction/noci.py +++ b/ipie/trial_wavefunction/noci.py @@ -35,7 +35,7 @@ def build(self) -> None: ... def calculate_energy(self, system, hamiltonian): - return variational_energy_noci(system, hamiltonian, self) + return variational_energy_noci(hamiltonian, self) def half_rotate(self, hamiltonian, comm=None): orbsa = self.psi[: self.num_dets, :, : self.nalpha] diff --git a/ipie/trial_wavefunction/particle_hole.py b/ipie/trial_wavefunction/particle_hole.py index fd891b24..22ba161a 100644 --- a/ipie/trial_wavefunction/particle_hole.py +++ b/ipie/trial_wavefunction/particle_hole.py @@ -399,7 +399,7 @@ def calculate_energy(self, system, hamiltonian): print("# Computing trial wavefunction energy.") # Cannot use usual energy evaluation routines if trial is orthogonal. self.energy, self.e1b, self.e2b = variational_energy_ortho_det( - system, hamiltonian, self.spin_occs, self.coeffs + system.nelec, hamiltonian, self.spin_occs, self.coeffs ) if self.verbose: print(f"# Variational energy of trial wavefunction: {self.energy.real}") diff --git a/ipie/trial_wavefunction/single_det.py b/ipie/trial_wavefunction/single_det.py index bfbaa940..ddc65eba 100644 --- a/ipie/trial_wavefunction/single_det.py +++ b/ipie/trial_wavefunction/single_det.py @@ -35,10 +35,10 @@ def __init__(self, wavefunction, num_elec, num_basis, verbose=False): self.num_elec = num_elec self._num_dets = 1 self._max_num_dets = 1 - #imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) - #if imag_norm <= 1e-8: - # print("# making trial wavefunction MO coefficient real") - #self.psi = numpy.array(self.psi.real, dtype=numpy.float64) + imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) + if imag_norm <= 1e-8: + #print("# making trial wavefunction MO coefficient real") + self.psi = numpy.array(self.psi.real, dtype=numpy.float64) self.psi0a = self.psi[:, : self.nalpha] self.psi0b = self.psi[:, self.nalpha :] diff --git a/ipie/trial_wavefunction/tests/test_noci.py b/ipie/trial_wavefunction/tests/test_noci.py index 1db2004b..d7acf4d2 100644 --- a/ipie/trial_wavefunction/tests/test_noci.py +++ b/ipie/trial_wavefunction/tests/test_noci.py @@ -33,3 +33,7 @@ def test_noci(): assert trial._rH1a.shape == (trial.num_dets, nalpha, nbasis) assert trial._rH1b.shape == (trial.num_dets, nbeta, nbasis) trial.calculate_energy(sys, ham) + + +if __name__ == '__main__': + test_noci() diff --git a/ipie/trial_wavefunction/tests/test_particle_hole.py b/ipie/trial_wavefunction/tests/test_particle_hole.py index 3acbccfc..9b7ce2bf 100644 --- a/ipie/trial_wavefunction/tests/test_particle_hole.py +++ b/ipie/trial_wavefunction/tests/test_particle_hole.py @@ -147,3 +147,9 @@ def test_wicks_opt_chunked(): assert trial._rH1b.shape == (nbeta, nbasis) assert trial._rchola_act.shape == (naux, nbasis * trial.nact) assert trial._rcholb_act.shape == (naux, nbasis * trial.nact) + + +if __name__ == '__main__': + test_wicks_slow() + test_wicks_opt() + test_wicks_opt_chunked() diff --git a/ipie/trial_wavefunction/tests/test_wavefunction_base.py b/ipie/trial_wavefunction/tests/test_wavefunction_base.py index bd7d168f..94e47cff 100644 --- a/ipie/trial_wavefunction/tests/test_wavefunction_base.py +++ b/ipie/trial_wavefunction/tests/test_wavefunction_base.py @@ -16,3 +16,7 @@ def test_wavefunction_base(): ) assert trial.nelec == (nalpha, nbeta) assert trial.nbasis == num_basis + + +if __name__ == '__main__': + test_wavefunction_base() diff --git a/ipie/walkers/tests/test_multi_det_batch.py b/ipie/walkers/tests/test_multi_det_batch.py index f526a4d8..b2c6cd0f 100644 --- a/ipie/walkers/tests/test_multi_det_batch.py +++ b/ipie/walkers/tests/test_multi_det_batch.py @@ -220,16 +220,16 @@ def test_walker_energy(): greens_function_multi_det_wicks_opt( walkers_opt, trial_opt ) # compute green's function using Wick's theorem - e_wicks = local_energy_multi_det_trial_wicks_batch(system, ham, walkers0, trial) - e_wicks_opt = local_energy_multi_det_trial_wicks_batch_opt(system, ham, walkers_opt, trial_opt) + e_wicks = local_energy_multi_det_trial_wicks_batch(ham, walkers0, trial) + e_wicks_opt = local_energy_multi_det_trial_wicks_batch_opt(ham, walkers_opt, trial_opt) greens_function_multi_det(walkers, trial_slow) - e_simple = local_energy_multi_det_trial_batch(system, ham, walkers, trial_slow) + e_simple = local_energy_multi_det_trial_batch(ham, walkers, trial_slow) assert e_simple[:, 0] == pytest.approx(energies) assert e_wicks_opt[:, 0] == pytest.approx(e_wicks[:, 0]) assert e_wicks[:, 0] == pytest.approx(energies) - # e = local_energy_batch(system, ham, walkers, trial, iw=0) + # e = local_energy_batch(ham, walkers, trial, iw=0) # assert e[:,0] == pytest.approx(energies[0]) From 405b847bb57734c59dffced3643731728978e4dc Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 3 Jan 2024 12:28:39 +0800 Subject: [PATCH 34/84] Updated Thermal AFQMC driver. Added thermal estimators. Added tests. Results agree with legacy for `GenericRealChol`. --- ipie/estimators/generic.py | 43 +-- ipie/thermal/estimators/energy.py | 89 +++++ ipie/thermal/estimators/generic.py | 113 +++++-- ipie/thermal/estimators/greens_function.py | 118 +++++++ ipie/thermal/estimators/handler.py | 225 +++++++++++++ ipie/thermal/estimators/particle_number.py | 56 ++++ .../estimators/tests/test_estimators.py | 175 ++++++++++ .../estimators/tests/test_generic_complex.py | 180 +++++++++++ ipie/thermal/estimators/thermal.py | 148 +-------- ipie/thermal/propagation/force_bias.py | 33 +- ipie/thermal/propagation/phaseless_base.py | 122 ++++++- ipie/thermal/propagation/phaseless_generic.py | 23 +- .../thermal/propagation/tests/test_generic.py | 63 ++-- .../propagation/tests/test_operations.py | 42 +-- ipie/thermal/qmc/options.py | 38 +++ ipie/thermal/qmc/thermal_afqmc.py | 306 +++++++++++++----- ipie/thermal/trial/mean_field.py | 3 +- ipie/thermal/trial/one_body.py | 7 +- ipie/thermal/walkers/base_walkers.py | 17 + .../walkers/tests/test_thermal_walkers.py | 140 ++++++-- ipie/thermal/walkers/uhf_walkers.py | 96 +----- ipie/trial_wavefunction/single_det.py | 6 +- 22 files changed, 1579 insertions(+), 464 deletions(-) create mode 100644 ipie/thermal/estimators/energy.py create mode 100644 ipie/thermal/estimators/greens_function.py create mode 100644 ipie/thermal/estimators/handler.py create mode 100644 ipie/thermal/estimators/particle_number.py create mode 100644 ipie/thermal/estimators/tests/test_estimators.py create mode 100644 ipie/thermal/estimators/tests/test_generic_complex.py create mode 100644 ipie/thermal/qmc/options.py create mode 100644 ipie/thermal/walkers/base_walkers.py diff --git a/ipie/estimators/generic.py b/ipie/estimators/generic.py index d545713e..a7674fff 100644 --- a/ipie/estimators/generic.py +++ b/ipie/estimators/generic.py @@ -229,7 +229,7 @@ def ecoul_kernel_rchol_complex(rchola, rcholb, rcholbara, rcholbarb, Ghalfa, Gha @jit(nopython=True, fastmath=True) -def exx_kernel_rchol_complex(rchol, Ghalf): +def exx_kernel_rchol_complex(rchol, rcholbar, Ghalf): """Compute exchange contribution for complex rchol. Parameters @@ -242,19 +242,22 @@ def exx_kernel_rchol_complex(rchol, Ghalf): Returns ------- exx : :class:`numpy.ndarray` - exchange contribution for given green's function. + exchange contribution for all walkers. """ naux = rchol.shape[0] nocc = Ghalf.shape[0] - nbasis = Ghalf.shape[1] - - exx = 0 + 0j - GhalfT = Ghalf.T.copy() + nbsf = Ghalf.shape[1] + T1 = xp.zeros((nocc, nocc), dtype=numpy.complex128) + T2 = xp.zeros((nocc, nocc), dtype=numpy.complex128) + exx = 0. + 0.j # Fix this with gpu env for jx in range(naux): - rmi = rchol[jx].reshape((nocc, nbasis)) - T = rmi.dot(GhalfT) - exx += numpy.dot(T.ravel(), T.T.ravel()) + rcholx = rchol[jx].reshape(nocc, nbsf) + rcholbarx = rcholbar[jx].reshape(nocc, nbsf) + T1 = rcholx.dot(Ghalf.T) + T2 = rcholbarx.dot(Ghalf.T) + exx += xp.dot(T1.ravel(), T2.T.ravel()) + exx *= 0.5 return exx @@ -313,7 +316,6 @@ def half_rotated_cholesky_jk(Ghalfa, Ghalfb, trial): exx : :class:`numpy.ndarray` Exchange energy. """ - rchola = trial._rchola rcholb = trial._rcholb @@ -321,19 +323,24 @@ def half_rotated_cholesky_jk(Ghalfa, Ghalfb, trial): if xp.isrealobj(rchola) and xp.isrealobj(rcholb): Xa = rchola.dot(Ghalfa.real.ravel()) + 1.0j * rchola.dot(Ghalfa.imag.ravel()) Xb = rcholb.dot(Ghalfb.real.ravel()) + 1.0j * rcholb.dot(Ghalfb.imag.ravel()) + ecoul = xp.dot(Xa, Xa) + ecoul += xp.dot(Xb, Xb) + ecoul += 2 * xp.dot(Xa, Xb) else: - Xa = rchola.dot(Ghalfa.ravel()) - Xb = rcholb.dot(Ghalfb.ravel()) + rcholbara = trial._rcholbara + rcholbarb = trial._rcholbarb + ecoul = 2.0 * ecoul_kernel_rchol_complex( + rchola, rcholb, rcholbara, rcholbarb, Ghalfa, Ghalfb + ) - ecoul = xp.dot(Xa, Xa) - ecoul += xp.dot(Xb, Xb) - ecoul += 2 * xp.dot(Xa, Xb) - exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta if xp.isrealobj(rchola) and xp.isrealobj(rcholb): exx = exx_kernel_rchol_real(rchola, Ghalfa) + exx_kernel_rchol_real(rcholb, Ghalfb) else: - exx = exx_kernel_rchol_complex(rchola, Ghalfa) + exx_kernel_rchol_complex(rcholb, Ghalfb) - + rcholbara = trial._rcholbara + rcholbarb = trial._rcholbarb + exx = exx_kernel_rchol_complex(rchola, rcholbara, Ghalfa) + exx += exx_kernel_rchol_complex(rcholb, rcholbarb, Ghalfb) + exx *= 2.0 synchronize() return 0.5 * ecoul, -0.5 * exx # JK energy diff --git a/ipie/thermal/estimators/energy.py b/ipie/thermal/estimators/energy.py new file mode 100644 index 00000000..99db8b03 --- /dev/null +++ b/ipie/thermal/estimators/energy.py @@ -0,0 +1,89 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Author: Fionn Malone +# + +import plum +import numpy + +from ipie.utils.backend import arraylib as xp +from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol +from ipie.estimators.estimator_base import EstimatorBase + +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.thermal.estimators.generic import local_energy_generic_cholesky + + +def local_energy( + hamiltonian: GenericRealChol, + walkers: UHFThermalWalkers): + energies = numpy.zeros((walkers.nwalkers, 3), dtype=numpy.complex128) + + for iw in range(walkers.nwalkers): + walkers.calc_greens_function(iw) # In-place update of GF. + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + energy = local_energy_generic_cholesky(hamiltonian, P) + + for i in range(3): + energies[iw, i] = energy[i] + + return energies + +class ThermalEnergyEstimator(EstimatorBase): + def __init__(self, hamiltonian=None, trial=None, filename=None): + super().__init__() + self._eshift = 0.0 + self.scalar_estimator = True + self._data = { + "ENumer": 0.0j, + "EDenom": 0.0j, + "ETotal": 0.0j, + "E1Body": 0.0j, + "E2Body": 0.0j, + } + + self._shape = (len(self.names),) + self._data_index = {k: i for i, k in enumerate(list(self._data.keys()))} + self.print_to_stdout = True + self.ascii_filename = filename + + def compute_estimator(self, walkers, hamiltonian, trial, istep=1): + # Need to be able to dispatch here. + # Re-calculated Green's function in `local_energy`. + energy = local_energy(hamiltonian, walkers) + self._data["ENumer"] = xp.sum(walkers.weight * energy[:, 0].real) + self._data["EDenom"] = xp.sum(walkers.weight) + self._data["E1Body"] = xp.sum(walkers.weight * energy[:, 1].real) + self._data["E2Body"] = xp.sum(walkers.weight * energy[:, 2].real) + return self.data + + def get_index(self, name): + index = self._data_index.get(name, None) + + if index is None: + raise RuntimeError(f"Unknown estimator {name}") + + return index + + def post_reduce_hook(self, data): + ix_proj = self._data_index["ETotal"] + ix_nume = self._data_index["ENumer"] + ix_deno = self._data_index["EDenom"] + data[ix_proj] = data[ix_nume] / data[ix_deno] + ix_nume = self._data_index["E1Body"] + data[ix_nume] = data[ix_nume] / data[ix_deno] + ix_nume = self._data_index["E2Body"] + data[ix_nume] = data[ix_nume] / data[ix_deno] diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py index f8513ae2..f9ac3929 100644 --- a/ipie/thermal/estimators/generic.py +++ b/ipie/thermal/estimators/generic.py @@ -1,7 +1,7 @@ - +import plum import numpy - from ipie.utils.misc import is_cupy +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol def local_energy_generic_pno( @@ -224,8 +224,8 @@ def local_energy_generic_cholesky_opt_batched( e2b_vec = 0.5 * (ecoul_vec - exx_vec) return (e1_vec + e2b_vec + hamiltonian.ecore, e1_vec + hamiltonian.ecore, e2b_vec) - -def local_energy_generic_cholesky(hamiltonian, G, Ghalf=None): +@plum.dispatch +def local_energy_generic_cholesky(hamiltonian: GenericRealChol, G): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. @@ -236,8 +236,6 @@ def local_energy_generic_cholesky(hamiltonian, G, Ghalf=None): ab-initio hamiltonian information G : :class:`numpy.ndarray` Walker's "green's function" - Ghalf : :class:`numpy.ndarray` - Walker's "half-rotated" "green's function" Returns ------- @@ -250,41 +248,88 @@ def local_energy_generic_cholesky(hamiltonian, G, Ghalf=None): nchol = hamiltonian.nchol Ga, Gb = G[0], G[1] - if numpy.isrealobj(hamiltonian.chol): - Xa = hamiltonian.chol.T.dot(Ga.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Ga.imag.ravel()) - Xb = hamiltonian.chol.T.dot(Gb.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Gb.imag.ravel()) - else: - Xa = hamiltonian.chol.T.dot(Ga.ravel()) - Xb = hamiltonian.chol.T.dot(Gb.ravel()) + # Ecoul. + Xa = hamiltonian.chol.T.dot(Ga.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Ga.imag.ravel()) + Xb = hamiltonian.chol.T.dot(Gb.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Gb.imag.ravel()) + X = Xa + Xb + ecoul = 0.5 * numpy.dot(X, X) + + # Ex. + GaT = Ga.T.copy() + GbT = Gb.T.copy() + T = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) + exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - ecoul = numpy.dot(Xa, Xa) - ecoul += numpy.dot(Xb, Xb) - ecoul += 2 * numpy.dot(Xa, Xb) + for x in range(nchol): # write a cython function that calls blas for this. + Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) + T[:, :].real = GaT.real.dot(Lmn) + T[:, :].imag = GaT.imag.dot(Lmn) + exx += numpy.trace(T.dot(T)) + T[:, :].real = GbT.real.dot(Lmn) + T[:, :].imag = GbT.imag.dot(Lmn) + exx += numpy.trace(T.dot(T)) + + exx *= 0.5 + e2b = ecoul - exx + return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) - T = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) +@plum.dispatch +def local_energy_generic_cholesky(hamiltonian: GenericComplexChol, G): + r"""Calculate local for generic two-body hamiltonian. + + This uses the cholesky decomposed two-electron integrals. + + Parameters + ---------- + hamiltonian : :class:`Generic` + ab-initio hamiltonian information + G : :class:`numpy.ndarray` + Walker's "green's function" + + Returns + ------- + (E, T, V): tuple + Local, kinetic and potential energies. + """ + # Element wise multiplication. + e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) + nbasis = hamiltonian.nbasis + nchol = hamiltonian.nchol + Ga, Gb = G[0], G[1] + + # Ecoul. + XAa = hamiltonian.A.T.dot(Ga.ravel()) + XAb = hamiltonian.A.T.dot(Gb.ravel()) + XA = XAa + XAb + + XBa = hamiltonian.B.T.dot(Ga.ravel()) + XBb = hamiltonian.B.T.dot(Gb.ravel()) + XB = XBa + XBb + + ecoul = 0.5 * (numpy.dot(XA, XA) + numpy.dot(XB, XB)) + + # Ex. GaT = Ga.T.copy() GbT = Gb.T.copy() - + TA = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) + TB = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - if numpy.isrealobj(hamiltonian.chol): - for x in range(nchol): # write a cython function that calls blas for this. - Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) - T[:, :].real = GaT.real.dot(Lmn) - T[:, :].imag = GaT.imag.dot(Lmn) - exx += numpy.trace(T.dot(T)) - T[:, :].real = GbT.real.dot(Lmn) - T[:, :].imag = GbT.imag.dot(Lmn) - exx += numpy.trace(T.dot(T)) - else: - for x in range(nchol): # write a cython function that calls blas for this. - Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) - T[:, :] = GaT.dot(Lmn) - exx += numpy.trace(T.dot(T)) - T[:, :] = GbT.dot(Lmn) - exx += numpy.trace(T.dot(T)) - e2b = 0.5 * (ecoul - exx) + for x in range(nchol): # write a cython function that calls blas for this. + Amn = hamiltonian.A[:, x].reshape((nbasis, nbasis)) + Bmn = hamiltonian.B[:, x].reshape((nbasis, nbasis)) + TA[:, :] = GaT.dot(Amn) + TB[:, :] = GaT.dot(Bmn) + exx += numpy.trace(TA.dot(TA)) + numpy.trace(TB.dot(TB)) + + TA[:, :] = GbT.dot(Amn) + TB[:, :] = GbT.dot(Bmn) + exx += numpy.trace(TA.dot(TA)) + numpy.trace(TB.dot(TB)) + + exx *= 0.5 + e2b = ecoul - exx + print(ecoul, -exx) return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) diff --git a/ipie/thermal/estimators/greens_function.py b/ipie/thermal/estimators/greens_function.py new file mode 100644 index 00000000..6760f147 --- /dev/null +++ b/ipie/thermal/estimators/greens_function.py @@ -0,0 +1,118 @@ +import numpy +import scipy.linalg + +def greens_function(A): + r"""Construct Greens function from density matrix. + + .. math:: + G_{ij} = \langle c_{i} c_j^{\dagger} \rangle \\ + = \left[\frac{1}{1+A}\right]_{ij} + + Uses stable algorithm from White et al. (1988) + + Parameters + ---------- + A : :class:`numpy.ndarray` + Density matrix (product of B matrices). + + Returns + ------- + G : :class:`numpy.ndarray` + Thermal Green's function. + """ + G = numpy.zeros(A.shape, dtype=A.dtype) + (U1, S1, V1) = scipy.linalg.svd(A) + T = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) + (U2, S2, V2) = scipy.linalg.svd(T) + U3 = numpy.dot(U1, U2) + D3 = numpy.diag(1.0 / S2) + V3 = numpy.dot(V2, V1) + G = (V3.conj().T).dot(D3).dot(U3.conj().T) + return G + + +def greens_function_qr_strat(walkers, iw, slice_ix=None, inplace=True): + """Compute the Green's function for walker with index `iw` at time + `slice_ix`. Uses the Stratification method (DOI 10.1109/IPDPS.2012.37) + """ + stack_iw = walkers.stack[iw] + + if slice_ix == None: + slice_ix = stack_iw.time_slice + + bin_ix = slice_ix // stack_iw.nstack + # For final time slice want first block to be the rightmost (for energy + # evaluation). + if bin_ix == stack_iw.nbins: + bin_ix = -1 + + Ga_iw, Gb_iw = None, None + if not inplace: + Ga_iw = numpy.zeros(walkers.Ga[iw].shape, walkers.Ga.dtype) + Gb_iw = numpy.zeros(walkers.Gb[iw].shape, walkers.Gb.dtype) + + for spin in [0, 1]: + # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in + # stable way. Iteratively construct column pivoted QR decompositions + # (A = QDT) starting from the rightmost (product of) propagator(s). + B = stack_iw.get((bin_ix + 1) % stack_iw.nbins) + + (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) + # Form D matrices + D1 = numpy.diag(R1.diagonal()) + D1inv = numpy.diag(1.0 / R1.diagonal()) + T1 = numpy.einsum("ii,ij->ij", D1inv, R1) + # permute them + T1[:, P1] = T1[:, range(walkers.nbasis)] + + for i in range(2, stack_iw.nbins + 1): + ix = (bin_ix + i) % stack_iw.nbins + B = stack_iw.get(ix) + C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) + (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) + # Compute D matrices + D1inv = numpy.diag(1.0 / R1.diagonal()) + D1 = numpy.diag(R1.diagonal()) + tmp = numpy.einsum("ii,ij->ij", D1inv, R1) + tmp[:, P1] = tmp[:, range(walkers.nbasis)] + T1 = numpy.dot(tmp, T1) + + # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T + # Write D = Db^{-1} Ds + # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T + Db = numpy.zeros(B[spin].shape, B[spin].dtype) + Ds = numpy.zeros(B[spin].shape, B[spin].dtype) + for i in range(Db.shape[0]): + absDlcr = abs(Db[i, i]) + if absDlcr > 1.0: + Db[i, i] = 1.0 / absDlcr + Ds[i, i] = numpy.sign(D1[i, i]) + else: + Db[i, i] = 1.0 + Ds[i, i] = D1[i, i] + + T1inv = scipy.linalg.inv(T1, check_finite=False) + # C = (Db Q^{-1}T^{-1}+Ds) + C = numpy.dot(numpy.einsum("ii,ij->ij", Db, Q1.conj().T), T1inv) + Ds + Cinv = scipy.linalg.inv(C, check_finite=False) + + # Then G = T^{-1} C^{-1} Db Q^{-1} + # Q is unitary. + if inplace: + if spin == 0: + walkers.Ga[iw] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) + else: + walkers.Gb[iw] = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) + + else: + if spin == 0: + Ga_iw = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) + + else: + Gb_iw = numpy.dot( + numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) + + return Ga_iw, Gb_iw diff --git a/ipie/thermal/estimators/handler.py b/ipie/thermal/estimators/handler.py new file mode 100644 index 00000000..f1b57410 --- /dev/null +++ b/ipie/thermal/estimators/handler.py @@ -0,0 +1,225 @@ +"""Routines and classes for estimation of observables.""" + +from __future__ import print_function + +import os +from typing import Tuple, Union + +import h5py +import numpy + +from ipie.config import config, MPI +from ipie.thermal.estimators.energy import ThermalEnergyEstimator +from ipie.thermal.estimators.particle_number import ThermalNumberEstimator +from ipie.estimators.estimator_base import EstimatorBase +from ipie.estimators.utils import H5EstimatorHelper +from ipie.utils.io import format_fixed_width_strings + +# Some supported (non-custom) estimators +_predefined_estimators = { + "energy": ThermalEnergyEstimator, + "nav": ThermalNumberEstimator, +} + + +class ThermalEstimatorHandler(object): + """Container for qmc options of observables. + + Parameters + ---------- + comm : MPI.COMM_WORLD + MPI Communicator + trial : :class:`ipie.trial_wavefunction.X' object + Trial wavefunction class. + verbose : bool + If true we print out additional setup information. + options: dict + input options detailing which estimators to calculate. By default only + mixed options will be calculated. + + Attributes + ---------- + estimators : dict + Dictionary of estimator objects. + """ + + def __init__( + self, + comm, + hamiltonian, + trial, + walker_state=None, + verbose: bool = False, + filename: Union[str, None] = None, + block_size: int = 1, + basename: str = "estimates", + overwrite=True, + observables: Tuple[str] = ("energy", "nav"), # TODO: Use factory method! + index: int = 0 + ): + if verbose: + print("# Setting up estimator object.") + if comm.rank == 0: + self.basename = basename + self.filename = filename + self.index = 0 + if self.filename is None: + self.filename = f"{self.basename}.{self.index}.h5" + while os.path.isfile(self.filename) and not overwrite: + self.index = int(self.filename.split(".")[1]) + self.index = self.index + 1 + self.filename = f"{self.basename}.{self.index}.h5" + if verbose: + print(f"# Writing estimator data to {self.filename}") + else: + self.filename = None + self.buffer_size = config.get_option("estimator_buffer_size") + if walker_state is not None: + self.num_walker_props = walker_state.size + self.walker_header = walker_state.names + else: + self.num_walker_props = 0 + self.walker_header = "" + self._estimators = {} + self._shapes = [] + self._offsets = {} + self.json_string = "{}" + # TODO: Replace this, should be built outside + for obs in observables: + try: + est = _predefined_estimators[obs]( + hamiltonian=hamiltonian, + trial=trial) + self[obs] = est + except KeyError: + raise RuntimeError(f"unknown observable: {obs}") + if verbose: + print("# Finished settting up estimator object.") + + def __setitem__(self, name: str, estimator: EstimatorBase) -> None: + over_writing = self._estimators.get(name) is not None + self._estimators[name] = estimator + if not over_writing: + self._shapes.append(estimator.shape) + if len(self._offsets.keys()) == 0: + self._offsets[name] = 0 + prev_obs = name + else: + prev_obs = list(self._offsets.keys())[-1] + offset = self._estimators[prev_obs].size + self._offsets[prev_obs] + self._offsets[name] = offset + + def get_offset(self, name: str) -> int: + offset = self._offsets.get(name) + assert offset is not None, f"Unknown estimator name {name}" + return offset + + def __getitem__(self, key): + return self._estimators[key] + + @property + def items(self): + return self._estimators.items + + @property + def size(self): + return sum(o.size for k, o in self._estimators.items()) + + def initialize(self, comm): + self.local_estimates = numpy.zeros( + (self.size + self.num_walker_props), dtype=numpy.complex128 + ) + self.global_estimates = numpy.zeros( + (self.size + self.num_walker_props), dtype=numpy.complex128 + ) + header = f"{'Block':>17s} " + header += format_fixed_width_strings(self.walker_header) + header += " " + for k, e in self.items(): + if e.print_to_stdout: + header += e.header_to_text + if comm.rank == 0: + with h5py.File(self.filename, "w") as fh5: + pass + self.dump_metadata() + self.output = H5EstimatorHelper( + self.filename, + base="block_size_1", + chunk_size=self.buffer_size, + shape=(self.size + self.num_walker_props,), + ) + if comm.rank == 0: + with h5py.File(self.filename, "r+") as fh5: + fh5["block_size_1/num_walker_props"] = self.num_walker_props + fh5["block_size_1/walker_prop_header"] = self.walker_header + for k, o in self.items(): + fh5[f"block_size_1/shape/{k}"] = o.shape + fh5[f"block_size_1/size/{k}"] = o.size + fh5[f"block_size_1/scalar/{k}"] = int(o.scalar_estimator) + fh5[f"block_size_1/names/{k}"] = " ".join(name for name in o.names) + fh5[f"block_size_1/offset/{k}"] = self.num_walker_props + self.get_offset(k) + if comm.rank == 0: + print(header) + + def dump_metadata(self): + with h5py.File(self.filename, "a") as fh5: + fh5["metadata"] = self.json_string + + def increment_file_number(self): + self.index = self.index + 1 + self.filename = self.basename + f".{self.index}.h5" + + def compute_estimators(self, hamiltonian, trial, walker_batch): + """Update estimators with bached psi + + Parameters + ---------- + """ + # Compute all estimators + # For the moment only consider estimators compute per block. + # TODO: generalize for different block groups (loop over groups) + offset = self.num_walker_props + for k, e in self.items(): + e.compute_estimator(walker_batch, hamiltonian, trial) + start = offset + self.get_offset(k) + end = start + int(self[k].size) + self.local_estimates[start:end] += e.data + + def print_block(self, comm, block, walker_factors, div_factor=None): + self.local_estimates[: walker_factors.size] = walker_factors.buffer + comm.Reduce(self.local_estimates, self.global_estimates, op=MPI.SUM) + output_string = " " + # Get walker data. + offset = walker_factors.size + if comm.rank == 0: + walker_factors.post_reduce_hook(self.global_estimates[:offset], block) + output_string += walker_factors.to_text(self.global_estimates[:offset]) + output_string += " " + for k, e in self.items(): + if comm.rank == 0: + start = offset + self.get_offset(k) + end = start + int(self[k].size) + est_data = self.global_estimates[start:end] + e.post_reduce_hook(est_data) + est_string = e.data_to_text(est_data) + e.to_ascii_file(est_string) + if e.print_to_stdout: + output_string += est_string + if comm.rank == 0: + shift = self.global_estimates[walker_factors.get_index("HybridEnergy")] + + else: + shift = None + walker_factors.eshift = comm.bcast(shift) + if comm.rank == 0: + self.output.push_to_chunk(self.global_estimates, f"data") + self.output.increment() + if comm.rank == 0: + print(f"{block:>17d} " + output_string) + self.zero() + + def zero(self): + self.local_estimates[:] = 0.0 + self.global_estimates[:] = 0.0 + for _, e in self.items(): + e.zero() diff --git a/ipie/thermal/estimators/particle_number.py b/ipie/thermal/estimators/particle_number.py new file mode 100644 index 00000000..f246d830 --- /dev/null +++ b/ipie/thermal/estimators/particle_number.py @@ -0,0 +1,56 @@ +from ipie.estimators.estimator_base import EstimatorBase +import plum +import numpy + +from ipie.utils.backend import arraylib as xp +from ipie.estimators.estimator_base import EstimatorBase +from ipie.thermal.estimators.thermal import particle_number, one_rdm_from_G + + +class ThermalNumberEstimator(EstimatorBase): + def __init__(self, hamiltonian=None, trial=None, filename=None): + # We define a dictionary to contain whatever we want to compute. + # Note we typically want to separate the numerator and denominator of + # the estimator. + # We require complex valued buffers for accumulation + self._data = { + "NavNumer": 0.0j, + "NavDenom": 0.0j, + "Nav": 0.0j, + } + + # We also need to specify the shape of the desired estimator + self._shape = (len(self.names),) + + # Optional but good to know (we can redirect to custom filepath (ascii) + # and / or print to stdout but we shouldnt do this for non scalar + # quantities. + self._data_index = {k: i for i, k in enumerate(list(self._data.keys()))} + self.print_to_stdout = True + self.ascii_filename = filename + + # Must specify that we're dealing with array valued estimator. + self.scalar_estimator = True + + def compute_estimator(self, walkers, hamiltonian, trial): + for iw in range(walkers.nwalkers): + walkers.calc_greens_function(iw) + nav_iw = particle_number(one_rdm_from_G( + numpy.array([walkers.Ga[iw], walkers.Gb[iw]]))) + self._data["NavNumer"] += walkers.weight[iw] * nav_iw + + self._data["NavDenom"] = sum(walkers.weight) + + def get_index(self, name): + index = self._data_index.get(name, None) + + if index is None: + raise RuntimeError(f"Unknown estimator {name}") + + return index + + def post_reduce_hook(self, data): + ix_proj = self._data_index["Nav"] + ix_nume = self._data_index["NavNumer"] + ix_deno = self._data_index["NavDenom"] + data[ix_proj] = data[ix_nume] / data[ix_deno] diff --git a/ipie/thermal/estimators/tests/test_estimators.py b/ipie/thermal/estimators/tests/test_estimators.py new file mode 100644 index 00000000..93eff636 --- /dev/null +++ b/ipie/thermal/estimators/tests/test_estimators.py @@ -0,0 +1,175 @@ +import pytest +import tempfile +import numpy +from pyscf import gto +from typing import Tuple, Union + +from ipie.systems.generic import Generic +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.estimators.energy import ThermalEnergyEstimator +from ipie.thermal.estimators.handler import ThermalEstimatorHandler +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric + +def build_test_case_handlers(nelec: Tuple[int, int], + options: Union[dict, None] = None, + seed: Union[int, None] = None, + choltol: float = 1e-3, + complex_integrals: bool = False, + verbose: bool = False): + if seed is not None: + numpy.random.seed(seed) + + # Unpack options + mu = options['mu'] + nbasis = options['nbasis'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + lowrank = options['lowrank'] + + sym = 8 + if complex_integrals: sym = 4 + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=choltol) + + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options['hamiltonian']['name'] + hamiltonian._alt_convention = options['hamiltonian']['_alt_convention'] + hamiltonian.sparse = options['hamiltonian']['sparse'] + + trial = MeanField(hamiltonian, nelec, beta, timestep) + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank) + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + for t in range(walkers.stack[0].nslice): + propagator.propagate_walkers(walkers, hamiltonian, trial) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator} + return objs + + +def test_energy_estimator(): + nocca = 5 + noccb = 5 + nelec = (nocca, noccb) + nbasis = 10 + + mu = -10.0 + beta = 0.1 + timestep = 0.01 + nwalkers = 1 + seed = 7 + lowrank = False + verbose = True + + options = { + 'mu': mu, + 'nbasis': nbasis, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': 7, + 'lowrank': lowrank, + + 'hamiltonian': { + 'name': 'Generic', + '_alt_convention': False, + 'sparse': False, + 'mu': mu + } + } + + objs = build_test_case_handlers(nelec, options, seed, choltol=1e-10, + complex_integrals=False, verbose=verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + + estim = ThermalEnergyEstimator(hamiltonian=hamiltonian, trial=trial) + estim.compute_estimator(walkers, hamiltonian, trial) + assert len(estim.names) == 5 + #assert estim["ENumer"].real == pytest.approx(-754.0373585215561) + #assert estim["ETotal"] == pytest.approx(0.0) + tmp = estim.data.copy() + estim.post_reduce_hook(tmp) + #assert tmp[estim.get_index("ETotal")] == pytest.approx(-75.40373585215562) + assert estim.print_to_stdout + assert estim.ascii_filename == None + assert estim.shape == (5,) + header = estim.header_to_text + data_to_text = estim.data_to_text(tmp) + assert len(data_to_text.split()) == 5 + +def test_estimator_handler(): + nocca = 5 + noccb = 5 + nelec = (nocca, noccb) + nbasis = 10 + + mu = -10.0 + beta = 0.1 + timestep = 0.01 + nwalkers = 1 + seed = 7 + lowrank = False + verbose = True + + options = { + 'mu': mu, + 'nbasis': nbasis, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': 7, + 'lowrank': lowrank, + + 'hamiltonian': { + 'name': 'Generic', + '_alt_convention': False, + 'sparse': False, + 'mu': mu + } + } + + with tempfile.NamedTemporaryFile() as tmp1, tempfile.NamedTemporaryFile() as tmp2: + objs = build_test_case_handlers(nelec, options, seed, choltol=1e-10, + complex_integrals=False, verbose=verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + + estim = ThermalEnergyEstimator(hamiltonian=hamiltonian, trial=trial, + filename=tmp1.name) + estim.print_to_stdout = False + from ipie.config import MPI + + comm = MPI.COMM_WORLD + handler = ThermalEstimatorHandler( + comm, + hamiltonian, + trial, + block_size=10, + observables=("energy",), + filename=tmp2.name) + handler["energy1"] = estim + handler.json_string = "" + handler.initialize(comm) + handler.compute_estimators(hamiltonian, trial, walkers) + + +if __name__ == "__main__": + test_energy_estimator() + test_estimator_handler() + + + diff --git a/ipie/thermal/estimators/tests/test_generic_complex.py b/ipie/thermal/estimators/tests/test_generic_complex.py new file mode 100644 index 00000000..e044ef4f --- /dev/null +++ b/ipie/thermal/estimators/tests/test_generic_complex.py @@ -0,0 +1,180 @@ +import numpy +import pytest +from typing import Tuple, Union + +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.thermal.estimators.thermal import one_rdm_from_G + + +def build_test_case_handlers(nelec: Tuple[int, int], + options: Union[dict, None] = None, + seed: Union[int, None] = None, + choltol: float = 1e-3, + complex_integrals: bool = False, + verbose: bool = False): + if seed is not None: + numpy.random.seed(seed) + + # Unpack options + mu = options['mu'] + nbasis = options['nbasis'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + lowrank = options['lowrank'] + + sym = 8 + if complex_integrals: sym = 4 + h1e, chol, _, eri = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=choltol) + + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options['hamiltonian']['name'] + hamiltonian._alt_convention = options['hamiltonian']['_alt_convention'] + hamiltonian.sparse = options['hamiltonian']['sparse'] + hamiltonian.eri = eri.copy() + + trial = MeanField(hamiltonian, nelec, beta, timestep) + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank) + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + for t in range(walkers.stack[0].nslice): + propagator.propagate_walkers(walkers, hamiltonian, trial) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator} + return objs + + +def test_local_energy_vs_real(): + nocca = 5 + noccb = 5 + nelec = (nocca, noccb) + nbasis = 10 + + mu = -10.0 + beta = 0.1 + timestep = 0.01 + nwalkers = 1 + seed = 7 + lowrank = False + verbose = True + + options = { + 'mu': mu, + 'nbasis': nbasis, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': 7, + 'lowrank': lowrank, + + 'hamiltonian': { + 'name': 'Generic', + '_alt_convention': False, + 'sparse': False, + 'mu': mu + } + } + + objs = build_test_case_handlers(nelec, options, seed, choltol=1e-10, + complex_integrals=False, verbose=verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + + chol = hamiltonian.chol + cx_chol = numpy.array(chol, dtype=numpy.complex128) + cx_hamiltonian = HamGeneric( + numpy.array(hamiltonian.H1, dtype=numpy.complex128), cx_chol, + hamiltonian.ecore, verbose=False) + + for iw in range(walkers.nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + energy = local_energy_generic_cholesky(hamiltonian, P) + cx_energy = local_energy_generic_cholesky(cx_hamiltonian, P) + numpy.testing.assert_allclose(energy, cx_energy, atol=1e-10) + + +def test_local_energy_vs_eri(): + nocca = 5 + noccb = 5 + nelec = (nocca, noccb) + nbasis = 10 + + mu = -10.0 + beta = 0.1 + timestep = 0.01 + nwalkers = 1 + seed = 7 + lowrank = False + verbose = True + + options = { + 'mu': mu, + 'nbasis': nbasis, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': 7, + 'lowrank': lowrank, + + 'hamiltonian': { + 'name': 'Generic', + '_alt_convention': False, + 'sparse': False, + 'mu': mu + } + } + + objs = build_test_case_handlers(nelec, options, seed, choltol=1e-10, + complex_integrals=False, verbose=verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + + eri = hamiltonian.eri.reshape(nbasis, nbasis, nbasis, nbasis) + chol = hamiltonian.chol.copy() + nchol = chol.shape[1] + chol = chol.reshape(nbasis, nbasis, nchol) + + # Check if chol and eri are consistent. + eri_chol = numpy.einsum('mnx,slx->mnls', chol, chol.conj()) + numpy.testing.assert_allclose(eri, eri_chol, atol=1e-10) + + for iw in range(walkers.nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + Pa, Pb = P + Ptot = Pa + Pb + etot, e1, e2 = local_energy_generic_cholesky(hamiltonian, P) + + # Test 1-body term. + h1e = hamiltonian.H1[0] + e1ref = numpy.einsum('ij,ij->', h1e, Ptot) + numpy.testing.assert_allclose(e1, e1ref, atol=1e-10) + + # Test 2-body term. + ecoul = 0.5 * numpy.einsum('ijkl,ij,kl->', eri, Ptot, Ptot) + exx = -0.5 * numpy.einsum('ijkl,il,kj->', eri, Pa, Pa) + exx -= 0.5 * numpy.einsum('ijkl,il,kj->', eri, Pb, Pb) + e2ref = ecoul + exx + numpy.testing.assert_allclose(e2, e2ref, atol=1e-10) + + etotref = e1ref + e2ref + numpy.testing.assert_allclose(etot, etotref, atol=1e-10) + + +if __name__ == '__main__': + test_local_energy_vs_real() + test_local_energy_vs_eri() diff --git a/ipie/thermal/estimators/thermal.py b/ipie/thermal/estimators/thermal.py index 04526308..a7e8c4e7 100644 --- a/ipie/thermal/estimators/thermal.py +++ b/ipie/thermal/estimators/thermal.py @@ -1,119 +1,6 @@ import numpy import scipy.linalg - -def fermi_factor(ek, beta, mu): - return 1.0 / (numpy.exp(beta * (ek - mu)) + 1.0) - - -def greens_function_unstable(A): - r"""Construct Green's function from density matrix. - - .. math:: - G_{ij} = \langle c_{i} c_j^{\dagger} \rangle \\ - = \left[\frac{1}{1+A}\right]_{ij} - - Parameters - ---------- - A : :class:`numpy.ndarray` - Density matrix (product of B matrices). - - Returns - ------- - G : :class:`numpy.ndarray` - Thermal Green's function. - """ - I = numpy.identity(A.shape[-1]) - return numpy.array([scipy.linalg.inv(I + A[0]), scipy.linalg.inv(I + A[1])]) - - -def greens_function(A): - r"""Construct Greens function from density matrix. - - .. math:: - G_{ij} = \langle c_{i} c_j^{\dagger} \rangle \\ - = \left[\frac{1}{1+A}\right]_{ij} - - Uses stable algorithm from White et al. (1988) - - Parameters - ---------- - A : :class:`numpy.ndarray` - Density matrix (product of B matrices). - - Returns - ------- - G : :class:`numpy.ndarray` - Thermal Green's function. - """ - G = numpy.zeros(A.shape, dtype=A.dtype) - (U1, S1, V1) = scipy.linalg.svd(A) - T = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) - (U2, S2, V2) = scipy.linalg.svd(T) - U3 = numpy.dot(U1, U2) - D3 = numpy.diag(1.0 / S2) - V3 = numpy.dot(V2, V1) - G = (V3.conj().T).dot(D3).dot(U3.conj().T) - return G - - -def inverse_greens_function(A): - """Inverse greens function from A""" - - Ginv = numpy.zeros(A.shape, dtype=A.dtype) - (U1, S1, V1) = scipy.linalg.svd(A) - T = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) - (U2, S2, V2) = scipy.linalg.svd(T) - U3 = numpy.dot(U1, U2) - D3 = numpy.diag(S2) - V3 = numpy.dot(V2, V1) - Ginv = (V3.conj().T).dot(D3).dot(U3.conj().T) - return Ginv - - -def inverse_greens_function_qr(A): - """Inverse greens function from A""" - - Ginv = numpy.zeros(A.shape, dtype=A.dtype) - - (U1, V1) = scipy.linalg.qr(A, pivoting=False) - V1inv = scipy.linalg.solve_triangular(V1, numpy.identity(V1.shape[0])) - T = numpy.dot(U1.conj().T, V1inv) + numpy.identity(V1.shape[0]) - (U2, V2) = scipy.linalg.qr(T, pivoting=False) - U3 = numpy.dot(U1, U2) - V3 = numpy.dot(V2, V1) - Ginv = U3.dot(V3) - # (U1,S1,V1) = scipy.linalg.svd(A) - # T = numpy.dot(U1.conj().T, V1.conj().T) + numpy.diag(S1) - # (U2,S2,V2) = scipy.linalg.svd(T) - # U3 = numpy.dot(U1, U2) - # D3 = numpy.diag(S2) - # V3 = numpy.dot(V2, V1) - # Ginv = (V3.conj().T).dot(D3).dot(U3.conj().T) - return Ginv - - -def one_rdm(A): - r"""Compute one-particle reduced density matrix - - .. math:: - rho_{ij} = \langle c_{i}^{\dagger} c_{j} \rangle \\ - = 1 - G_{ji} - Parameters - ---------- - A : :class:`numpy.ndarray` - Density matrix (product of B matrices). - - Returns - ------- - P : :class:`numpy.ndarray` - Thermal 1RDM. - """ - I = numpy.identity(A.shape[-1]) - G = numpy.array([greens_function(A[0]), greens_function(A[1])]) - return numpy.array([I - G[0].T, I - G[1].T]) - - def one_rdm_from_G(G): r"""Compute one-particle reduced density matrix from Green's function. @@ -133,24 +20,6 @@ def one_rdm_from_G(G): I = numpy.identity(G.shape[-1]) return numpy.array([I - G[0].T, I - G[1].T], dtype=numpy.complex128) - -def particle_number(dmat): - """Compute average particle number. - - Parameters - ---------- - dmat : :class:`numpy.ndarray` - Thermal 1RDM. - - Returns - ------- - nav : float - Average particle number. - """ - nav = dmat[0].trace() + dmat[1].trace() - return nav - - def one_rdm_stable(BT, num_slices): nbasis = BT.shape[-1] G = [] @@ -199,8 +68,25 @@ def one_rdm_stable(BT, num_slices): G.append(numpy.dot(numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T))) return one_rdm_from_G(numpy.array(G)) +def particle_number(dmat): + """Compute average particle number from the thermal 1RDM. + + Parameters + ---------- + dmat : :class:`numpy.ndarray` + Thermal 1RDM. + + Returns + ------- + nav : float + Average particle number. + """ + nav = dmat[0].trace() + dmat[1].trace() + return nav def entropy(beta, mu, H): + """Compute the entropy. + """ assert numpy.linalg.norm(H[0] - H[1]) < 1e-12 eigs, eigv = numpy.linalg.eigh(H[0]) p_i = fermi_factor(eigs, beta, mu) diff --git a/ipie/thermal/propagation/force_bias.py b/ipie/thermal/propagation/force_bias.py index cb4a86f4..69cbdd9f 100644 --- a/ipie/thermal/propagation/force_bias.py +++ b/ipie/thermal/propagation/force_bias.py @@ -1,10 +1,13 @@ +import plum import numpy +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol from ipie.thermal.estimators.thermal import one_rdm_from_G from ipie.utils.backend import arraylib as xp from ipie.utils.backend import synchronize -def construct_force_bias(hamiltonian, walkers): +@plum.dispatch +def construct_force_bias(hamiltonian: GenericRealChol, walkers): r"""Compute optimal force bias. Parameters @@ -21,8 +24,32 @@ def construct_force_bias(hamiltonian, walkers): for iw in range(walkers.nwalkers): P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) - vbias[iw] = hamiltonian.chol.T.dot(P[0].ravel()) - vbias[iw] += hamiltonian.chol.T.dot(P[1].ravel()) + vbias[iw] = hamiltonian.chol.T.dot(P[0].ravel()) + hamiltonian.chol.T.dot(P[1].ravel()) + + return vbias + + +@plum.dispatch +def construct_force_bias(hamiltonian: GenericComplexChol, walkers): + r"""Compute optimal force bias. + + Parameters + ---------- + G: :class:`numpy.ndarray` + Walker's 1RDM: . + + Returns + ------- + xbar : :class:`numpy.ndarray` + Force bias. + """ + nchol = hamiltonian.nchol + vbias = xp.empty((walkers.nwalkers, hamiltonian.nfields), dtype=walkers.Ga.dtype) + + for iw in range(walkers.nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + vbias[iw, :nchol] = hamiltonian.A.T.dot(P[0].ravel()) + hamiltonian.A.T.dot(P[1].ravel()) + vbias[iw, nchol:] = hamiltonian.B.T.dot(P[0].ravel()) + hamiltonian.B.T.dot(P[1].ravel()) return vbias diff --git a/ipie/thermal/propagation/phaseless_base.py b/ipie/thermal/propagation/phaseless_base.py index c71c2eb4..ae67318c 100644 --- a/ipie/thermal/propagation/phaseless_base.py +++ b/ipie/thermal/propagation/phaseless_base.py @@ -1,4 +1,7 @@ import time +import plum +import math +import cmath import numpy import scipy.linalg @@ -11,9 +14,10 @@ from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol # TODO: Add lowrank implementation. +# Ref: 10.1103/PhysRevB.80.214116 for bounds. - -def construct_mean_field_shift(hamiltonian, trial): +@plum.dispatch +def construct_mean_field_shift(hamiltonian: GenericRealChol, trial): r"""Compute mean field shift. .. math:: @@ -30,6 +34,25 @@ def construct_mean_field_shift(hamiltonian, trial): return mf_shift # Shape (nchol,). +@plum.dispatch +def construct_mean_field_shift(hamiltonian: GenericComplexChol, trial): + r"""Compute mean field shift. + + .. math:: + + \bar{v}_n = \sum_{ik\sigma} v_{(ik),n} P_{ik\sigma} + + """ + # hamiltonian.chol has shape (nbasis^2, nchol). + P = one_rdm_from_G(trial.G) + P = (P[0] + P[1]).ravel() + nchol = hamiltonian.nchol + mf_shift = numpy.zeros(hamiltonian.nfields, dtype=hamiltonian.chol.dtype) + mf_shift[:nchol] = 1j * numpy.dot(hamiltonian.A.T, P.ravel()) + mf_shift[nchol:] = 1j * numpy.dot(hamiltonian.B.T, P.ravel()) + return mf_shift # Shape (nchol,). + + class PhaselessBase(ContinuousBase): """A base class for generic continuous HS transform FT-AFQMC propagators.""" @@ -64,8 +87,13 @@ def build(self, hamiltonian, trial=None, walkers=None, mpi_handler=None, verbose # Allocate force bias (we don't need to do this here - it will be allocated when it is needed) self.vbias = None + # Legacy attributes. + self.mf_core = hamiltonian.ecore + 0.5 * numpy.dot(self.mf_shift, self.mf_shift) + self.mf_const_fac = cmath.exp(-self.dt * self.mf_core) + - def construct_one_body_propagator(self, hamiltonian): + @plum.dispatch + def construct_one_body_propagator(self, hamiltonian: GenericRealChol): r"""Construct mean-field shifted one-body propagator. .. math:: @@ -89,6 +117,35 @@ def construct_one_body_propagator(self, hamiltonian): scipy.linalg.expm(-0.5 * self.dt * H1[1])]) return expH1 # Shape (nbasis, nbasis). + + @plum.dispatch + def construct_one_body_propagator(self, hamiltonian: GenericComplexChol): + r"""Construct mean-field shifted one-body propagator. + + .. math:: + + H1 \rightarrow H1 - v0 + v0_{ik} = \sum_n v_{(ik),n} \bar{v}_n + + Parameters + ---------- + hamiltonian : hamiltonian class + Generic hamiltonian object. + dt : float + Timestep. + """ + nb = hamiltonian.nbasis + nchol = hamiltonian.nchol + shift = xp.zeros((nb, nb), dtype=hamiltonian.chol.dtype) + shift = 1j * numpy.einsum("mx,x->m", hamiltonian.A, self.mf_shift[:nchol]).reshape(nb, nb) + shift += 1j * numpy.einsum("mx,x->m", hamiltonian.B, self.mf_shift[nchol:]).reshape(nb, nb) + muN = self.mu * numpy.identity(nb, dtype=hamiltonian.H1.dtype) + H1 = hamiltonian.h1e_mod - numpy.array([shift + muN, shift + muN]) + expH1 = numpy.array([ + scipy.linalg.expm(-0.5 * self.dt * H1[0]), + scipy.linalg.expm(-0.5 * self.dt * H1[1])]) + return expH1 # Shape (nbasis, nbasis). + def construct_two_body_propagator(self, walkers, hamiltonian, trial, debug=False): r"""Construct two-body propagator. @@ -159,17 +216,24 @@ def propagate_walkers(self, walkers, hamiltonian, trial, eshift=0., debug=False) # Compute determinant ratio det(1+A')/det(1+A). # 1. Current walker's Green's function. tix = stack.nslice - G = walkers.greens_function(iw, slice_ix=tix, inplace=False) + start_time = time.time() + G = walkers.calc_greens_function(iw, slice_ix=tix, inplace=False) + self.timer.tgf += time.time() - start_time # 2. Compute updated Green's function. + start_time = time.time() stack.update_new(B) - walkers.greens_function(iw, slice_ix=tix, inplace=True) + walkers.calc_greens_function(iw, slice_ix=tix, inplace=True) # 3. Compute det(G/G') # Now apply phaseless approximation - self.update_weight(walkers, iw, G, cfb, cmf, eshift) + if debug: + self.update_weight_legacy(walkers, iw, G, cfb, cmf, eshift) - self.timer.tupdate += time.time() - start_time + else: + self.update_weight(walkers, iw, G, cfb, cmf, eshift) + + self.timer.tupdate += time.time() - start_time def update_weight(self, walkers, iw, G, cfb, cmf, eshift): @@ -179,7 +243,7 @@ def update_weight(self, walkers, iw, G, cfb, cmf, eshift): M0b = scipy.linalg.det(G[1], check_finite=False) Mnewa = scipy.linalg.det(walkers.Ga[iw], check_finite=False) Mnewb = scipy.linalg.det(walkers.Gb[iw], check_finite=False) - + # ovlp = det( G^{-1} ) ovlp_ratio = (M0a * M0b) / (Mnewa * Mnewb) # ovlp_new / ovlp_old hybrid_energy = -(xp.log(ovlp_ratio) + cfb[iw] + cmf[iw]) / self.dt # Scalar. @@ -197,6 +261,47 @@ def update_weight(self, walkers, iw, G, cfb, cmf, eshift): walkers.M0a[iw] = Mnewa walkers.M0b[iw] = Mnewb + + def update_weight_legacy(self, walkers, iw, G, cfb, cmf, eshift): + """Update weight for walker `iw` using legacy code. + """ + M0a = scipy.linalg.det(G[0], check_finite=False) + M0b = scipy.linalg.det(G[1], check_finite=False) + Mnewa = scipy.linalg.det(walkers.Ga[iw], check_finite=False) + Mnewb = scipy.linalg.det(walkers.Gb[iw], check_finite=False) + _cfb = cfb[iw] + _cmf = cmf[iw] + + try: + # Could save M0 rather than recompute. + oratio = (M0a * M0b) / (Mnewa * Mnewb) + # Might want to cap this at some point + hybrid_energy = cmath.log(oratio) + _cfb + _cmf + Q = cmath.exp(hybrid_energy) + #hybrid_energy = -(cmath.log(oratio) + _cfb + _cmf) / self.dt + #walkers.hybrid_energy = hybrid_energy + self.mf_core + #Q = cmath.exp(-self.dt * hybrid_energy) + #hybrid_energy = cmath.log(oratio) + _cfb + _cmf + expQ = self.mf_const_fac * Q + (magn, phase) = cmath.polar(expQ) + + if not math.isinf(magn): + # Determine cosine phase from Arg(det(1+A'(x))/det(1+A(x))). + # Note this doesn't include exponential factor from shifting + # proability distribution. + dtheta = cmath.phase(cmath.exp(hybrid_energy - _cfb)) + cosine_fac = max(0, math.cos(dtheta)) + walkers.weight[iw] *= magn * cosine_fac + walkers.M0a[iw] = Mnewa + walkers.M0b[iw] = Mnewb + + else: + walkers.weight[iw] = 0. + + except ZeroDivisionError: + walkers.weight[iw] = 0. + + def apply_bound_force_bias(self, xbar, max_bound=1.0): absxbar = xp.abs(xbar) idx_to_rescale = absxbar > max_bound @@ -207,6 +312,7 @@ def apply_bound_force_bias(self, xbar, max_bound=1.0): self.nfb_trig += xp.sum(idx_to_rescale) return xbar + def apply_bound_hybrid(self, ehyb, eshift): # Shift is a number but ehyb is not # For initial steps until first estimator communication, `eshift` will be # zero and hybrid energy can be incorrect. So just avoid capping for diff --git a/ipie/thermal/propagation/phaseless_generic.py b/ipie/thermal/propagation/phaseless_generic.py index e4c5e5bf..b602b23a 100644 --- a/ipie/thermal/propagation/phaseless_generic.py +++ b/ipie/thermal/propagation/phaseless_generic.py @@ -1,9 +1,10 @@ -import math import time +import math +import plum import numpy from ipie.config import config -from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol from ipie.hamiltonians.generic_base import GenericBase from ipie.thermal.propagation.operations import apply_exponential from ipie.thermal.propagation.phaseless_base import PhaselessBase @@ -18,11 +19,25 @@ class PhaselessGeneric(PhaselessBase): def __init__(self, time_step, mu, exp_nmax=6, lowrank=False, verbose=False): super().__init__(time_step, mu, lowrank=lowrank, verbose=verbose) self.exp_nmax = exp_nmax - - def construct_VHS(self, hamiltonian, xshifted): + + @plum.dispatch + def construct_VHS(self, hamiltonian: GenericRealChol, xshifted: xp.ndarray): """Includes `nwalkers`. """ nwalkers = xshifted.shape[-1] # Shape (nfields, nwalkers). VHS = hamiltonian.chol.dot(xshifted) # Shape (nbasis^2, nwalkers). VHS = self.isqrt_dt * VHS.T.reshape(nwalkers, hamiltonian.nbasis, hamiltonian.nbasis) return VHS # Shape (nwalkers, nbasis, nbasis). + + @plum.dispatch + def construct_VHS(self, hamiltonian: GenericComplexChol, xshifted: xp.ndarray): + """Includes `nwalkers`. + """ + nwalkers = xshifted.shape[-1] + nchol = hamiltonian.nchol + VHS = self.isqrt_dt * ( + hamiltonian.A.dot(xshifted[:nchol]) + hamiltonian.B.dot(xshifted[nchol:]) + ) + VHS = VHS.T.copy() + VHS = VHS.reshape(nwalkers, hamiltonian.nbasis, hamiltonian.nbasis) + return VHS diff --git a/ipie/thermal/propagation/tests/test_generic.py b/ipie/thermal/propagation/tests/test_generic.py index 901af72f..4aa7af51 100644 --- a/ipie/thermal/propagation/tests/test_generic.py +++ b/ipie/thermal/propagation/tests/test_generic.py @@ -1,10 +1,11 @@ import numpy import pytest -from pyscf import gto, scf, lo from ipie.qmc.options import QMCOpts from ipie.systems.generic import Generic +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.hamiltonians.utils import get_hamiltonian from ipie.thermal.trial.mean_field import MeanField from ipie.thermal.trial.one_body import OneBody @@ -35,29 +36,25 @@ def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, l def setup_objs(mf_trial=False, seed=None): nocca = 5 noccb = 5 - nelec = nocca + noccb - r0 = 1.75 - mol = gto.M( - atom=[("H", i * r0, 0, 0) for i in range(nelec)], - basis='sto-6g', - unit='Bohr', - verbose=5) + nelec = (nocca, noccb) + nbasis = 10 mu = -10. - beta = 0.1 + beta = 0.02 dt = 0.01 - nwalkers = 5 + nwalkers = 2 numpy.random.seed(seed) blocks = 10 stabilise_freq = 10 pop_control_freq = 1 nsteps = 1 - nslice = 3 lowrank = False verbose = True + complex_integrals = False + sym = 8 + if complex_integrals: sym = 4 - path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" options = { "qmc": { "dt": dt, @@ -77,31 +74,34 @@ def setup_objs(mf_trial=False, seed=None): "walkers": { "low_rank": lowrank - }, "hamiltonian": { "name": "Generic", - "integrals": path + "reference_data/generic_integrals.h5", "_alt_convention": False, - "symmetry": False, "sparse": False, "mu": mu - }, + } } # Test. print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - system = Generic(mol.nelec, verbose=verbose) - hamiltonian = get_hamiltonian(system, options["hamiltonian"]) - trial = OneBody(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) if mf_trial: - trial = MeanField(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + trial = MeanField(hamiltonian, nelec, beta, dt, verbose=verbose) - nbasis = trial.dmat.shape[-1] walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, verbose=verbose) propagator = PhaselessGeneric(dt, mu, lowrank=lowrank, verbose=verbose) @@ -111,13 +111,12 @@ def setup_objs(mf_trial=False, seed=None): print('\n------------------------------') print('Constructing legacy objects...') print('------------------------------') - legacy_system = Generic(mol.nelec, verbose=verbose) + legacy_system = Generic(nelec, verbose=verbose) legacy_system.mu = mu legacy_hamiltonian = LegacyHamGeneric( h1e=hamiltonian.H1, chol=hamiltonian.chol, - ecore=hamiltonian.ecore, - options=options["hamiltonian"]) + ecore=hamiltonian.ecore) legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) @@ -142,8 +141,6 @@ def setup_objs(mf_trial=False, seed=None): qmc_opts.dt = dt qmc_opts.seed = seed - legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) legacy_propagator = Continuous( options["propagator"], qmc_opts, legacy_system, legacy_hamiltonian, legacy_trial, verbose=verbose, @@ -204,7 +201,7 @@ def test_construct_two_body_propagator(verbose=False): legacy_propagator = legacy_objs['propagator'] cmf, cfb, xshifted, VHS = propagator.construct_two_body_propagator( - walkers, hamiltonian, trial) + walkers, hamiltonian, trial, debug=True) legacy_cmf = [] legacy_cfb = [] @@ -261,18 +258,16 @@ def test_phaseless_generic_propagator(mf_trial=False, verbose=False): eloc = local_energy_generic_cholesky(hamiltonian, P) legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers[iw].G)) - legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.reshape( - (hamiltonian.nchol, hamiltonian.nbasis**2)).T legacy_eloc = legacy_local_energy_generic_cholesky( legacy_system, legacy_hamiltonian, legacy_P) - legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) if verbose: print(f'\nt = {t}') print(f'iw = {iw}') print(f'eloc = \n{eloc}\n') print(f'legacy_eloc = \n{legacy_eloc}\n') + print(f'walkers.weight = \n{walkers.weight[iw]}\n') + print(f'legacy_walkers.weight = \n{legacy_walkers[iw].weight}\n') numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) @@ -288,7 +283,7 @@ def test_phaseless_generic_propagator(mf_trial=False, verbose=False): if __name__ == "__main__": - #test_mf_shift(verbose=True) - #test_BH1(verbose=True) - #test_construct_two_body_propagator(verbose=True) + test_mf_shift(verbose=True) + test_BH1(verbose=True) + test_construct_two_body_propagator(verbose=True) test_phaseless_generic_propagator(mf_trial=True, verbose=True) diff --git a/ipie/thermal/propagation/tests/test_operations.py b/ipie/thermal/propagation/tests/test_operations.py index 2fdc14ba..7b27baa1 100644 --- a/ipie/thermal/propagation/tests/test_operations.py +++ b/ipie/thermal/propagation/tests/test_operations.py @@ -5,7 +5,8 @@ from ipie.qmc.options import QMCOpts from ipie.systems.generic import Generic -from ipie.hamiltonians.utils import get_hamiltonian +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.thermal.trial.mean_field import MeanField from ipie.thermal.trial.one_body import OneBody from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers @@ -21,13 +22,8 @@ def setup_objs(mf_trial=False, seed=None): nocca = 5 noccb = 5 - nelec = nocca + noccb - r0 = 1.75 - mol = gto.M( - atom=[("H", i * r0, 0, 0) for i in range(nelec)], - basis='sto-6g', - unit='Bohr', - verbose=5) + nelec = (nocca, noccb) + nbasis = 10 mu = -10. beta = 0.1 @@ -38,12 +34,13 @@ def setup_objs(mf_trial=False, seed=None): stabilise_freq = 10 pop_control_freq = 1 nsteps = 1 - nslice = 3 lowrank = False verbose = True + complex_integrals = False + sym = 8 + if complex_integrals: sym = 4 - path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" options = { "qmc": { "dt": dt, @@ -68,9 +65,7 @@ def setup_objs(mf_trial=False, seed=None): "hamiltonian": { "name": "Generic", - "integrals": path + "reference_data/generic_integrals.h5", "_alt_convention": False, - "symmetry": False, "sparse": False, "mu": mu }, @@ -80,14 +75,20 @@ def setup_objs(mf_trial=False, seed=None): print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - system = Generic(mol.nelec, verbose=verbose) - hamiltonian = get_hamiltonian(system, options["hamiltonian"]) - trial = OneBody(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) if mf_trial: - trial = MeanField(hamiltonian, mol.nelec, beta, dt, verbose=verbose) + trial = MeanField(hamiltonian, nelec, beta, dt, verbose=verbose) - nbasis = trial.dmat.shape[-1] walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, verbose=verbose) propagator = PhaselessGeneric(dt, mu, lowrank=lowrank, verbose=verbose) @@ -97,7 +98,7 @@ def setup_objs(mf_trial=False, seed=None): print('\n------------------------------') print('Constructing legacy objects...') print('------------------------------') - legacy_system = Generic(mol.nelec, verbose=verbose) + legacy_system = Generic(nelec, verbose=verbose) legacy_system.mu = mu legacy_hamiltonian = LegacyHamGeneric( h1e=hamiltonian.H1, @@ -128,8 +129,8 @@ def setup_objs(mf_trial=False, seed=None): qmc_opts.dt = dt qmc_opts.seed = seed - legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + #legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( + # (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) legacy_propagator = Continuous( options["propagator"], qmc_opts, legacy_system, legacy_hamiltonian, legacy_trial, verbose=verbose, @@ -174,6 +175,7 @@ def test_apply_exponential(verbose=False): _legacy_exp = legacy_propagator.exponentiate(_VHS, debug=True) exp.append(_exp) legacy_exp.append(_legacy_exp) + numpy.testing.assert_allclose(_VHS, VHS[iw]) exp = numpy.array(exp) legacy_exp = numpy.array(legacy_exp) diff --git a/ipie/thermal/qmc/options.py b/ipie/thermal/qmc/options.py new file mode 100644 index 00000000..4d9585eb --- /dev/null +++ b/ipie/thermal/qmc/options.py @@ -0,0 +1,38 @@ +from dataclasses import dataclass +from typing import Optional + +from ipie.qmc.options import QMCParams + +_no_default = object() + +@dataclass +class ThermalQMCParams(QMCParams): + r"""Input options and certain constants / parameters derived from them. + + Args: + beta: inverse temperature. + num_walkers: number of walkers **per** core / task / computational unit. + total_num_walkers: The total number of walkers in the simulation. + timestep: The timestep delta_t + num_steps_per_block: Number of steps of propagation before estimators + are evaluated. + num_blocks: The number of blocks. Total number of iterations = + num_blocks * num_steps_per_block. + num_stblz: number of steps before QR stabilization of walkers is performed. + pop_control_freq: Frequency at which population control occurs. + rng_seed: The random number seed. If run in parallel the seeds on other + cores / threads are determined from this. + """ + # This is a hack to get around the error: + # + # TypeError: non-default argument 'beta' follows default argument + # + # due to inheritance from the QMCParams dataclass which has default attributes. + # Ref: https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses + beta: float = _no_default + pop_control_method: str = 'pair_branch' + + def __post_init__(self): + if self.beta is _no_default: + raise TypeError("__init__ missing 1 required argument: 'beta'") + diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index a1e01522..1208833f 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -1,16 +1,26 @@ """Driver to perform AFQMC calculation""" +import numpy import time +import json import uuid from typing import Dict, Optional, Tuple +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.walkers.base_walkers import ThermalWalkerAccumulator from ipie.thermal.propagation.propagator import Propagator -from ipie.thermal.walkers import UHFThermalWalkers +from ipie.thermal.estimators.handler import ThermalEstimatorHandler from ipie.thermal.qmc.options import ThermalQMCParams -from ipie.qmc.afqmc import AFQMC -from ipie.qmc.utils import set_rng_seed + +from ipie.utils.io import to_json +from ipie.utils.backend import arraylib as xp +from ipie.utils.backend import get_host_memory from ipie.utils.misc import get_git_info, print_env_info -from ipie.systems.generic import Generic from ipie.utils.mpi import MPIHandler +from ipie.systems.generic import Generic +from ipie.estimators.estimator_base import EstimatorBase +from ipie.walkers.pop_controller import PopController +from ipie.qmc.afqmc import AFQMC +from ipie.qmc.utils import set_rng_seed ## This is now only applicable to the Generic case! @@ -30,7 +40,7 @@ class ThermalAFQMC(AFQMC): propagator : Class describing how to propagate walkers. params : - Parameters of simulation. See QMCParams for description. + Parameters of simulation. See ThermalQMCParams for description. verbose : bool How much information to print. @@ -46,12 +56,14 @@ def __init__(self, trial, walkers, propagator, - params: QMCParams, - verbose: int = 0): + params: ThermalQMCParams, + debug: bool = False, + verbose: bool = False): super().__init__(system, hamiltonian, trial, walkers, propagator, params, verbose) + self.debug = debug def build( - nelec: Tuple[], + nelec: Tuple[int, int], mu: float, beta: float, hamiltonian, @@ -103,13 +115,13 @@ def build( """ mpi_handler = MPIHandler() comm = mpi_handler.comm - params = QMCParams( + params = ThermalQMCParams( + beta=beta, num_walkers=num_walkers, total_num_walkers=num_walkers * comm.size, num_blocks=num_blocks, num_steps_per_block=num_steps_per_block, timestep=timestep, - beta=beta, num_stblz=stabilize_freq, pop_control_freq=pop_control_freq, rng_seed=seed) @@ -129,99 +141,128 @@ def build( verbose=(verbose and comm.rank == 0)) - def run(self, walkers=None, comm=None, verbose=None): + def run(self, + walkers = None, + verbose: bool = True, + estimator_filename = None, + additional_estimators: Optional[Dict[str, EstimatorBase]] = None): """Perform Thermal AFQMC simulation on state object using open-ended random walk. Parameters ---------- state : :class:`pie.state.State` object Model and qmc parameters. - walk: :class:`pie.walker.Walkers` object + + walkers: :class:`pie.walker.Walkers` object Initial wavefunction / distribution of walkers. - comm : MPI communicator + + estimator_filename : str + File to write estimates to. + + additional_estimators : dict + Dictionary of additional estimators to evaluate. """ + # Setup. self.setup_timers() - ft_setup time.time() + ft_setup = time.time() + eshift = 0. if walkers is not None: self.walkers = walkers - # Calculate estimates for initial distribution of walkers. - self.estimators.estimators["mixed"].update( - self.qmc, - self.hamiltonian, - self.trial, - self.walkers, - 0, - self.propagators.free_projection, - ) - # Print out zeroth step for convenience. - self.estimators.estimators["mixed"].print_step(comm, comm.size, 0, 1) + self.pcontrol = PopController( + self.params.num_walkers, + self.params.num_steps_per_block, + self.mpi_handler, + self.params.pop_control_method, + verbose=self.verbose) + + self.get_env_info() + self.setup_estimators(estimator_filename, additional_estimators=additional_estimators) + comm = self.mpi_handler.comm + self.tsetup += time.time() - ft_setup + + print(f'comm.size = {comm.size}') + print(f'comm.rank = {comm.rank}') + + # Propagate. num_walkers = self.walkers.nwalkers total_steps = self.params.num_steps_per_block * self.params.num_blocks - num_slices = self.params.num_slices + # TODO: This magic value of 2 is pretty much never controlled on input. + # Moreover I'm not convinced having a two stage shift update actually + # matters at all. + num_eqlb_steps = 2.0 / self.params.timestep + num_slices = numpy.rint(self.params.beta / self.params.timestep).astype(int) for step in range(1, total_steps + 1): start_path = time.time() - for ts in range(num_slices): + for t in range(num_slices): if self.verbosity >= 2 and comm.rank == 0: - print(" # Timeslice %d of %d." % (ts, num_slices)) + print(" # Timeslice %d of %d." % (t, num_slices)) start = time.time() self.propagator.propagate_walkers( - self.walkers, self.hamiltonian, self.trial, eshift) + self.walkers, self.hamiltonian, self.trial, eshift, debug=self.debug) + + self.tprop_fbias = self.propagator.timer.tfbias + self.tprop_update = self.propagator.timer.tupdate + self.tprop_vhs = self.propagator.timer.tvhs + self.tprop_gemm = self.propagator.timer.tgemm start_clip = time.time() - if step > 1: + if t > 0: wbound = self.pcontrol.total_weight * 0.10 xp.clip(self.walkers.weight, a_min=-wbound, a_max=wbound, - out=self.walkers.weight) # in-place clipping + out=self.walkers.weight) # In-place clipping self.tprop_clip += time.time() - start_clip start_barrier = time.time() - if step % self.params.pop_control_freq == 0: + if t % self.params.pop_control_freq == 0: comm.Barrier() - self.tprop_barrier += time.time() - start_barrier - - if step % self.params.pop_control_freq == 0: - start = time.time() - self.pcontrol.pop_control(self.walkers, comm) - synchronize() - self.tpopc += time.time() - start - self.tpopc_send = self.pcontrol.timer.send_time - self.tpopc_recv = self.pcontrol.timer.recv_time - self.tpopc_comm = self.pcontrol.timer.communication_time - self.tpopc_non_comm = self.pcontrol.timer.non_communication_time + self.tprop_barrier += time.time() - start_barrier self.tprop += time.time() - start + + print(f'self.walkers.weight = {self.walkers.weight}') + if (t > 0) and (t % self.params.pop_control_freq == 0): + start = time.time() + self.pcontrol.pop_control(self.walkers, comm) + self.tpopc += time.time() - start + self.tpopc_send = self.pcontrol.timer.send_time + self.tpopc_recv = self.pcontrol.timer.recv_time + self.tpopc_comm = self.pcontrol.timer.communication_time + self.tpopc_non_comm = self.pcontrol.timer.non_communication_time + + # Accumulate weight, hybrid energy etc. across block. + start = time.time() + self.accumulators.update(self.walkers) + self.testim += time.time() - start - start = time.time() - if ts % self.qmc.npop_control == 0 and ts != 0: - self.walkers.pop_control(comm) - self.tpopc += time.time() - start - self.tpath += time.time() - start_path + # Calculate estimators. start = time.time() - self.estimators.update( - self.qmc, - self.hamiltonian, - self.trial, - self.walkers, - step, - self.propagators.free_projection, - ) + if step % self.params.num_steps_per_block == 0: + self.estimators.compute_estimators(self.hamiltonian, + self.trial, self.walkers) + + self.estimators.print_block( + comm, step // self.params.num_steps_per_block, self.accumulators) + self.accumulators.zero(self.walkers, self.trial) + self.testim += time.time() - start - self.estimators.print_step( - comm, - comm.size, - step, - free_projection=self.propagators.free_projection, - ) - self.walkers.reset(self.trial) - def finalise(self, verbose): + if step < num_eqlb_steps: + eshift = self.accumulators.eshift + + else: + eshift += self.accumulators.eshift - eshift + + self.tpath += time.time() - start_path + + + def finalise(self, verbose=False): """Tidy up. Parameters @@ -229,22 +270,90 @@ def finalise(self, verbose): verbose : bool If true print out some information to stdout. """ - pass + nsteps_per_block = max(self.params.num_steps_per_block, 1) + nblocks = max(self.params.num_blocks, 1) + nstblz = max(nsteps_per_block // self.params.num_stblz, 1) + npcon = max(nsteps_per_block // self.params.pop_control_freq, 1) - def determine_dtype(self, propagator, system): - """Determine dtype for trial wavefunction and walkers. + if self.mpi_handler.rank == 0: + if verbose: + print(f"# End Time: {time.asctime():s}") + print(f"# Running time : {time.time() - self._init_time:.6f} seconds") + print("# Timing breakdown (per call, total calls per block, total blocks):") + print(f"# - Setup: {self.tsetup:.6f} s") + print( + "# - Path update: {:.6f} s / block for {} total blocks".format( + self.tpath / (nblocks), nblocks + ) + ) + print( + "# - Propagation: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tprop / (nblocks * nsteps_per_block), nsteps_per_block, nblocks + ) + ) + print( + "# - Force bias: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tprop_fbias / (nblocks * nsteps_per_block), nsteps_per_block, nblocks + ) + ) + print( + "# - VHS: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tprop_vhs / (nblocks * nsteps_per_block), nsteps_per_block, nblocks + ) + ) + print( + "# - Green's Function: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tprop_gf / (nblocks * nsteps_per_block), nsteps_per_block, nblocks + ) + ) + print( + "# - Overlap: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tprop_ovlp / (nblocks * nsteps_per_block), nsteps_per_block, nblocks + ) + ) + print( + "# - Weights Update: {:.6f} s / call for {} call(s) in each of {} blocks".format( + (self.tprop_update + self.tprop_clip) / (nblocks * nsteps_per_block), + nsteps_per_block, + nblocks, + ) + ) + print( + "# - GEMM operations: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tprop_gemm / (nblocks * nsteps_per_block), nsteps_per_block, nblocks + ) + ) + print( + "# - Barrier: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tprop_barrier / (nblocks * nsteps_per_block), nsteps_per_block, nblocks + ) + ) + print( + "# - Estimators: {:.6f} s / call for {} call(s)".format( + self.testim / nblocks, nblocks + ) + ) + print( + "# - Orthogonalisation: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tortho / (nstblz * nblocks), nstblz, nblocks + ) + ) + print( + "# - Population control: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tpopc / (npcon * nblocks), npcon, nblocks + ) + ) + print( + "# - Commnication: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tpopc_comm / (npcon * nblocks), npcon, nblocks + ) + ) + print( + "# - Non-Commnication: {:.6f} s / call for {} call(s) in each of {} blocks".format( + self.tpopc_non_comm / (npcon * nblocks), npcon, nblocks + ) + ) - Parameters - ---------- - propagator : dict - Propagator input options. - system : object - System object. - """ - hs_type = propagator.get("hubbard_stratonovich", "discrete") - continuous = "continuous" in hs_type - twist = system.ktwist.all() is not None - return continuous or twist def get_env_info(self): this_uuid = str(uuid.uuid1()) @@ -268,10 +377,51 @@ def get_env_info(self): mem_avail = get_host_memory() print(f"# Available memory on the node is {mem_avail:4.3f} GB") + + + def setup_estimators( + self, + filename, + additional_estimators: Optional[Dict[str, EstimatorBase]] = None): + self.accumulators = ThermalWalkerAccumulator( + ["Weight", "WeightFactor", "HybridEnergy"], self.params.num_steps_per_block) + comm = self.mpi_handler.comm + self.estimators = ThermalEstimatorHandler( + self.mpi_handler.comm, + self.hamiltonian, + self.trial, + walker_state=self.accumulators, + verbose=(comm.rank == 0 and self.verbose), + filename=filename) + + if additional_estimators is not None: + for k, v in additional_estimators.items(): + self.estimators[k] = v + + # TODO: Move this to estimator and log uuid etc in serialization + json.encoder.FLOAT_REPR = lambda o: format(o, ".6f") + json_string = to_json(self) + self.estimators.json_string = json_string + self.estimators.initialize(comm) + + # Calculate estimates for initial distribution of walkers. + self.estimators.compute_estimators(self.hamiltonian, + self.trial, self.walkers) + self.accumulators.update(self.walkers) + self.estimators.print_block(comm, 0, self.accumulators) + self.accumulators.zero(self.walkers, self.trial) + def setup_timers(self): + self.tsetup = 0 self.tpath = 0 + self.tprop = 0 + self.tprop_barrier = 0 + self.tprop_fbias = 0 + self.tprop_update = 0 + self.tprop_vhs = 0 self.tprop_clip = 0 + self.testim = 0 self.tpopc = 0 diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index 10f00ab2..26ad1cdb 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -2,7 +2,8 @@ import scipy.linalg from ipie.thermal.estimators.fock import fock_matrix -from ipie.thermal.estimators.thermal import greens_function, one_rdm_stable, particle_number +from ipie.thermal.estimators.greens_function import greens_function +from ipie.thermal.estimators.thermal import one_rdm_stable, particle_number from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.thermal.trial.one_body import OneBody diff --git a/ipie/thermal/trial/one_body.py b/ipie/thermal/trial/one_body.py index 71b4ba34..b24d125d 100644 --- a/ipie/thermal/trial/one_body.py +++ b/ipie/thermal/trial/one_body.py @@ -2,11 +2,8 @@ import numpy import scipy.linalg -from ipie.thermal.estimators.thermal import ( - greens_function, - one_rdm_stable, - particle_number, -) +from ipie.thermal.estimators.greens_function import greens_function +from ipie.thermal.estimators.thermal import one_rdm_stable, particle_number from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.utils.misc import update_stack diff --git a/ipie/thermal/walkers/base_walkers.py b/ipie/thermal/walkers/base_walkers.py new file mode 100644 index 00000000..a99f95b3 --- /dev/null +++ b/ipie/thermal/walkers/base_walkers.py @@ -0,0 +1,17 @@ +import numpy +from ipie.walkers.base_walkers import WalkerAccumulator + + +class ThermalWalkerAccumulator(WalkerAccumulator): + def __init__(self, names, nsteps): + super().__init__(names, nsteps) + + def zero(self, walkers, trial): + self.buffer.fill(0.j) + walkers.weight = numpy.ones(walkers.nwalkers) + walkers.phase = numpy.ones(walkers.nwalkers, dtype=numpy.complex128) + + for iw in range(walkers.nwalkers): + walkers.stack[iw].reset() + walkers.stack[iw].set_all(trial.dmat) + walkers.calc_greens_function(iw) diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py index 49ee7b95..93830d77 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -1,69 +1,140 @@ import numpy import pytest -from ipie.systems.ueg import UEG -from ipie.hamiltonians.ueg import UEG as HamUEG +from ipie.systems.generic import Generic +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.thermal.trial.mean_field import MeanField from ipie.thermal.trial.one_body import OneBody from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.estimators.ueg import local_energy_ueg +from ipie.thermal.estimators.generic import local_energy_generic_cholesky from ipie.thermal.estimators.thermal import one_rdm_from_G -from ipie.legacy.systems.ueg import UEG as LegacyUEG -from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody from ipie.legacy.walkers.thermal import ThermalWalker -from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg +from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -@pytest.mark.unit -def test_thermal_walkers(): - rs = 2 - ecut = 2 - nup = 7 - ndown = 7 - nelec = (nup, ndown) - - nwalkers = 5 - beta = 1 - dt = 0.05 - lowrank = True +def setup_objs(mf_trial=False, seed=None): + nocca = 5 + noccb = 5 + nelec = (nocca, noccb) + nbasis = 10 + + mu = -10. + beta = 0.02 + dt = 0.01 + nwalkers = 2 + numpy.random.seed(seed) + + lowrank = False verbose = True - options = {"rs": rs, "nup": nup, "ndown": ndown, "ecut": ecut, - "write_integrals": False, "low_rank" : lowrank} - + complex_integrals = False + sym = 8 + if complex_integrals: sym = 4 + + options = { + "walkers": { + "low_rank": lowrank + }, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + } + } + # Test. print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - system = UEG(options=options) - hamiltonian = HamUEG(system, options=options) + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) - nbasis = trial.dmat.shape[-1] + + if mf_trial: + trial = MeanField(hamiltonian, nelec, beta, dt, verbose=verbose) + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, verbose=verbose) - + # Legacy. print('\n------------------------------') print('Constructing legacy objects...') print('------------------------------') - legacy_system = UEG(options=options) - legacy_hamiltonian = LegacyHamUEG(legacy_system, options=options) - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, dt, verbose=verbose) + legacy_system = Generic(nelec, verbose=verbose) + legacy_system.mu = mu + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, dt, + verbose=verbose) + if mf_trial: + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, dt, + verbose=verbose) + legacy_walkers = [ ThermalWalker( legacy_system, legacy_hamiltonian, legacy_trial, walker_opts=options, verbose=i == 0) for i in range(nwalkers)] - for iw in range(nwalkers): + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers} + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers} + + return objs, legacy_objs + +@pytest.mark.unit +def test_thermal_walkers(): + verbose = True + seed = 7 + objs, legacy_objs = setup_objs(seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + + for iw in range(walkers.nwalkers): P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) - eloc = local_energy_ueg(system, hamiltonian, P) + eloc = local_energy_generic_cholesky(hamiltonian, P) legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers[iw].G)) - legacy_eloc = legacy_local_energy_ueg(legacy_system, legacy_hamiltonian, legacy_P) + legacy_eloc = legacy_local_energy_generic_cholesky( + legacy_system, legacy_hamiltonian, legacy_P) - print(f'\niw = {iw}') - print(f'eloc = {eloc}') - print(f'legacy_eloc = {legacy_eloc}') + if verbose: + print(f'\niw = {iw}') + print(f'eloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') + print(f'walkers.weight = \n{walkers.weight[iw]}\n') + print(f'legacy_walkers.weight = \n{legacy_walkers[iw].weight}\n') numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) @@ -71,5 +142,6 @@ def test_thermal_walkers(): numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) + if __name__ == "__main__": test_thermal_walkers() diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index ff30775c..bfc2d09f 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -2,6 +2,7 @@ import scipy.linalg from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number +from ipie.thermal.estimators.greens_function import greens_function_qr_strat from ipie.thermal.walkers.stack import PropagatorStack from ipie.utils.misc import get_numeric_names, update_stack from ipie.walkers.base_walkers import BaseWalkers @@ -86,7 +87,7 @@ def __init__( # Initialise all propagators to the trial density matrix. for iw in range(self.nwalkers): self.stack[iw].set_all(trial.dmat) - self.greens_function_qr_strat(iw) + greens_function_qr_strat(self, iw) self.stack[iw].G[0] = self.Ga[iw] self.stack[iw].G[1] = self.Gb[iw] @@ -121,101 +122,14 @@ def __init__( self.buff_names, self.buff_size = get_numeric_names(self.__dict__) - def greens_function(self, iw, slice_ix=None, inplace=True): + def calc_greens_function(self, iw, slice_ix=None, inplace=True): """Return the Green's function for walker `iw`. """ if self.lowrank: return self.stack[iw].G # G[0] = Ga, G[1] = Gb - else: - return self.greens_function_qr_strat(iw, slice_ix=slice_ix, inplace=inplace) - - - def greens_function_qr_strat(self, iw, slice_ix=None, inplace=True): - """Compute the Green's function for walker with index `iw` at time - `slice_ix`. Uses the Stratification method (DOI 10.1109/IPDPS.2012.37) - """ - stack_iw = self.stack[iw] - - if slice_ix == None: - slice_ix = stack_iw.time_slice - - bin_ix = slice_ix // stack_iw.nstack - # For final time slice want first block to be the rightmost (for energy - # evaluation). - if bin_ix == stack_iw.nbins: - bin_ix = -1 - - Ga_iw, Gb_iw = None, None - if not inplace: - Ga_iw = numpy.zeros(self.Ga[iw].shape, self.Ga.dtype) - Gb_iw = numpy.zeros(self.Gb[iw].shape, self.Gb.dtype) - - for spin in [0, 1]: - # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in - # stable way. Iteratively construct column pivoted QR decompositions - # (A = QDT) starting from the rightmost (product of) propagator(s). - B = stack_iw.get((bin_ix + 1) % stack_iw.nbins) - - (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) - # Form D matrices - D1 = numpy.diag(R1.diagonal()) - D1inv = numpy.diag(1.0 / R1.diagonal()) - T1 = numpy.einsum("ii,ij->ij", D1inv, R1) - # permute them - T1[:, P1] = T1[:, range(self.nbasis)] - - for i in range(2, stack_iw.nbins + 1): - ix = (bin_ix + i) % stack_iw.nbins - B = stack_iw.get(ix) - C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) - (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) - # Compute D matrices - D1inv = numpy.diag(1.0 / R1.diagonal()) - D1 = numpy.diag(R1.diagonal()) - tmp = numpy.einsum("ii,ij->ij", D1inv, R1) - tmp[:, P1] = tmp[:, range(self.nbasis)] - T1 = numpy.dot(tmp, T1) - - # G^{-1} = 1+A = 1+QDT = Q (Q^{-1}T^{-1}+D) T - # Write D = Db^{-1} Ds - # Then G^{-1} = Q Db^{-1}(Db Q^{-1}T^{-1}+Ds) T - Db = numpy.zeros(B[spin].shape, B[spin].dtype) - Ds = numpy.zeros(B[spin].shape, B[spin].dtype) - for i in range(Db.shape[0]): - absDlcr = abs(Db[i, i]) - if absDlcr > 1.0: - Db[i, i] = 1.0 / absDlcr - Ds[i, i] = numpy.sign(D1[i, i]) - else: - Db[i, i] = 1.0 - Ds[i, i] = D1[i, i] - - T1inv = scipy.linalg.inv(T1, check_finite=False) - # C = (Db Q^{-1}T^{-1}+Ds) - C = numpy.dot(numpy.einsum("ii,ij->ij", Db, Q1.conj().T), T1inv) + Ds - Cinv = scipy.linalg.inv(C, check_finite=False) - - # Then G = T^{-1} C^{-1} Db Q^{-1} - # Q is unitary. - if inplace: - if spin == 0: - self.Ga[iw] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) - else: - self.Gb[iw] = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) - - else: - if spin == 0: - Ga_iw = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) - - else: - Gb_iw = numpy.dot( - numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T)) - - return Ga_iw, Gb_iw + else: + return greens_function_qr_strat(self, iw, slice_ix=slice_ix, inplace=inplace) # For compatibiltiy with BaseWalkers class. def reortho(self): diff --git a/ipie/trial_wavefunction/single_det.py b/ipie/trial_wavefunction/single_det.py index ddc65eba..3f778703 100644 --- a/ipie/trial_wavefunction/single_det.py +++ b/ipie/trial_wavefunction/single_det.py @@ -25,7 +25,7 @@ # class for UHF trial class SingleDet(TrialWavefunctionBase): - def __init__(self, wavefunction, num_elec, num_basis, verbose=False): + def __init__(self, wavefunction, num_elec, num_basis, cplx=False, verbose=False): assert isinstance(wavefunction, numpy.ndarray) assert len(wavefunction.shape) == 2 super().__init__(wavefunction, num_elec, num_basis, verbose=verbose) @@ -36,8 +36,8 @@ def __init__(self, wavefunction, num_elec, num_basis, verbose=False): self._num_dets = 1 self._max_num_dets = 1 imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) - if imag_norm <= 1e-8: - #print("# making trial wavefunction MO coefficient real") + if (not cplx) and (imag_norm <= 1e-8): + #print("# making trial wavefunction MO coefficient real") self.psi = numpy.array(self.psi.real, dtype=numpy.float64) self.psi0a = self.psi[:, : self.nalpha] From e8f67adef18551b649b8a39b72ea4d0c08bd4ecc Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 3 Jan 2024 17:48:03 +0800 Subject: [PATCH 35/84] UEG energies agree with legacy in `propagators/tests` Added pytests. --- ipie/thermal/estimators/generic.py | 5 +- .../estimators/tests/test_estimators.py | 4 + .../estimators/tests/test_generic_complex.py | 52 ++ .../thermal/propagation/tests/test_generic.py | 5 + .../propagation/tests/test_operations.py | 2 + .../thermal/propagation/tests/ueg/test_ueg.py | 261 ++++++++ .../propagation/tests/ueg/test_ueg_0T.py | 256 ++++++++ ipie/thermal/propagation/tests/ueg/ueg.py | 563 ++++++++++++++++++ .../propagation/tests/ueg/ueg_trial.npy | Bin 0 -> 12896 bytes ipie/thermal/trial/tests/test_mean_field.py | 1 + ipie/thermal/trial/tests/test_one_body.py | 1 + .../walkers/tests/test_thermal_walkers.py | 2 + 12 files changed, 1149 insertions(+), 3 deletions(-) create mode 100644 ipie/thermal/propagation/tests/ueg/test_ueg.py create mode 100644 ipie/thermal/propagation/tests/ueg/test_ueg_0T.py create mode 100644 ipie/thermal/propagation/tests/ueg/ueg.py create mode 100644 ipie/thermal/propagation/tests/ueg/ueg_trial.npy diff --git a/ipie/thermal/estimators/generic.py b/ipie/thermal/estimators/generic.py index f9ac3929..8d87fb8e 100644 --- a/ipie/thermal/estimators/generic.py +++ b/ipie/thermal/estimators/generic.py @@ -224,6 +224,7 @@ def local_energy_generic_cholesky_opt_batched( e2b_vec = 0.5 * (ecoul_vec - exx_vec) return (e1_vec + e2b_vec + hamiltonian.ecore, e1_vec + hamiltonian.ecore, e2b_vec) + @plum.dispatch def local_energy_generic_cholesky(hamiltonian: GenericRealChol, G): r"""Calculate local for generic two-body hamiltonian. @@ -329,13 +330,11 @@ def local_energy_generic_cholesky(hamiltonian: GenericComplexChol, G): exx *= 0.5 e2b = ecoul - exx - print(ecoul, -exx) return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) def local_energy_generic_cholesky_opt_stochastic( - hamiltonian, nelec, nsamples, G, Ghalf=None, rchol=None, C0=None, ecoul0=None, exxa0=None, exxb0=None -): + hamiltonian, nelec, nsamples, G, Ghalf=None, rchol=None, C0=None, ecoul0=None, exxa0=None, exxb0=None): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. Parameters diff --git a/ipie/thermal/estimators/tests/test_estimators.py b/ipie/thermal/estimators/tests/test_estimators.py index 93eff636..2e32048e 100644 --- a/ipie/thermal/estimators/tests/test_estimators.py +++ b/ipie/thermal/estimators/tests/test_estimators.py @@ -14,6 +14,7 @@ from ipie.thermal.estimators.handler import ThermalEstimatorHandler from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric + def build_test_case_handlers(nelec: Tuple[int, int], options: Union[dict, None] = None, seed: Union[int, None] = None, @@ -58,6 +59,7 @@ def build_test_case_handlers(nelec: Tuple[int, int], return objs +@pytest.mark.unit def test_energy_estimator(): nocca = 5 noccb = 5 @@ -110,6 +112,8 @@ def test_energy_estimator(): data_to_text = estim.data_to_text(tmp) assert len(data_to_text.split()) == 5 + +@pytest.mark.unit def test_estimator_handler(): nocca = 5 noccb = 5 diff --git a/ipie/thermal/estimators/tests/test_generic_complex.py b/ipie/thermal/estimators/tests/test_generic_complex.py index e044ef4f..2e20fcc3 100644 --- a/ipie/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/thermal/estimators/tests/test_generic_complex.py @@ -2,7 +2,11 @@ import pytest from typing import Tuple, Union +from ipie.utils.misc import dotdict from ipie.utils.testing import generate_hamiltonian +from ipie.utils.testing import build_test_case_handlers as build_test_case_handlers_0T +from ipie.estimators.energy import local_energy + from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.hamiltonians.utils import get_hamiltonian from ipie.thermal.trial.mean_field import MeanField @@ -57,6 +61,7 @@ def build_test_case_handlers(nelec: Tuple[int, int], return objs +@pytest.mark.unit def test_local_energy_vs_real(): nocca = 5 noccb = 5 @@ -107,6 +112,7 @@ def test_local_energy_vs_real(): numpy.testing.assert_allclose(energy, cx_energy, atol=1e-10) +@pytest.mark.unit def test_local_energy_vs_eri(): nocca = 5 noccb = 5 @@ -175,6 +181,52 @@ def test_local_energy_vs_eri(): numpy.testing.assert_allclose(etot, etotref, atol=1e-10) +@pytest.mark.unit +def test_local_energy_0T_single_det(): + numpy.random.seed(7) + nmo = 10 + nelec = (6, 5) + nwalkers = 1 + nsteps = 25 + qmc = dotdict( + { + "dt": 0.005, + "nstblz": 5, + "nwalkers": nwalkers, + "hybrid": True, + "num_steps": nsteps, + } + ) + + handler_0T = build_test_case_handlers_0T( + nelec, + nmo, + num_dets=1, + options=qmc, + seed=7, + complex_integrals=True, + complex_trial=True, + trial_type="single_det", + choltol=1e-10, + ) + + hamiltonian = handler_0T.hamiltonian + walkers = handler_0T.walkers + trial = handler_0T.trial + walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) + energy = local_energy(hamiltonian, walkers, trial) + test_energy = numpy.array( + [local_energy_generic_cholesky( + hamiltonian, + numpy.array([walkers.Ga[0], walkers.Gb[0]]))]) + + print(f'\n0T energy = \n{energy}\n') + print(f'test_energy = \n{test_energy}\n') + + numpy.testing.assert_allclose(energy, test_energy, atol=1e-10) + + if __name__ == '__main__': test_local_energy_vs_real() test_local_energy_vs_eri() + test_local_energy_0T_single_det() diff --git a/ipie/thermal/propagation/tests/test_generic.py b/ipie/thermal/propagation/tests/test_generic.py index 4aa7af51..da29ca7d 100644 --- a/ipie/thermal/propagation/tests/test_generic.py +++ b/ipie/thermal/propagation/tests/test_generic.py @@ -33,6 +33,7 @@ def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, l return legacy_walkers + def setup_objs(mf_trial=False, seed=None): nocca = 5 noccb = 5 @@ -160,6 +161,7 @@ def setup_objs(mf_trial=False, seed=None): return objs, legacy_objs +@pytest.mark.unit def test_mf_shift(verbose=False): seed = 7 objs, legacy_objs = setup_objs(seed=seed) @@ -173,6 +175,7 @@ def test_mf_shift(verbose=False): numpy.testing.assert_almost_equal(legacy_propagator.propagator.mf_shift, propagator.mf_shift, decimal=10) +@pytest.mark.unit def test_BH1(verbose=False): seed = 7 objs, legacy_objs = setup_objs(seed=seed) @@ -187,6 +190,7 @@ def test_BH1(verbose=False): propagator.BH1, decimal=10) +@pytest.mark.unit def test_construct_two_body_propagator(verbose=False): seed = 7 objs, legacy_objs = setup_objs(seed=seed) @@ -238,6 +242,7 @@ def test_construct_two_body_propagator(verbose=False): numpy.testing.assert_almost_equal(legacy_VHS, VHS, decimal=10) +@pytest.mark.unit def test_phaseless_generic_propagator(mf_trial=False, verbose=False): seed = 7 objs, legacy_objs = setup_objs(mf_trial=mf_trial, seed=seed) diff --git a/ipie/thermal/propagation/tests/test_operations.py b/ipie/thermal/propagation/tests/test_operations.py index 7b27baa1..ca525253 100644 --- a/ipie/thermal/propagation/tests/test_operations.py +++ b/ipie/thermal/propagation/tests/test_operations.py @@ -19,6 +19,7 @@ from ipie.legacy.walkers.thermal import ThermalWalker from ipie.legacy.thermal_propagation.continuous import Continuous + def setup_objs(mf_trial=False, seed=None): nocca = 5 noccb = 5 @@ -150,6 +151,7 @@ def setup_objs(mf_trial=False, seed=None): return objs, legacy_objs +@pytest.mark.unit def test_apply_exponential(verbose=False): seed = 7 objs, legacy_objs = setup_objs(seed=seed) diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg.py b/ipie/thermal/propagation/tests/ueg/test_ueg.py new file mode 100644 index 00000000..59ddc739 --- /dev/null +++ b/ipie/thermal/propagation/tests/ueg/test_ueg.py @@ -0,0 +1,261 @@ +import pytest +import numpy + +from ueg import UEG +from pyscf import gto, scf, ao2mo +from ipie.qmc.options import QMCOpts + +from ipie.systems.generic import Generic +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.thermal.estimators.thermal import one_rdm_from_G + +from ipie.legacy.systems.ueg import UEG as LegacyUEG +from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.thermal import ThermalWalker +from ipie.legacy.thermal_propagation.planewave import PlaneWave +from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G + + +def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, lowrank=False, xi=None): + if xi is None: + xi = [None] * legacy_walkers.nwalker + + for iw, walker in enumerate(legacy_walkers): + if lowrank: + legacy_propagator.propagate_walker_phaseless_low_rank( + legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) + + else: + legacy_propagator.propagate_walker_phaseless_full_rank( + legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) + + + return legacy_walkers + + +def setup_objs(seed=None): + mu = -10. + beta = 0.01 + timestep = 0.002 + nwalkers = 1 + numpy.random.seed(seed) + nblocks = 10 + stabilise_freq = 10 + pop_control_freq = 1 + nsteps_per_block = 1 + + lowrank = False + verbose = True + + options = { + "qmc": { + "dt": timestep, + "nwalkers": nwalkers, + "blocks": nblocks, + "nsteps": nsteps_per_block, + "beta": beta, + "rng_seed": seed, + "pop_control_freq": pop_control_freq, + "stabilise_freq": stabilise_freq, + "batched": False + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank + }, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + } + } + + # Generate UEG integrals. + ueg_opts = { + "nup": 7, + "ndown": 7, + "rs": 1., + "ecut": 2.5, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + } + + ueg = UEG(ueg_opts, verbose=verbose) + ueg.build(verbose=verbose) + nbasis = ueg.nbasis + nchol = ueg.nchol + nelec = (ueg.nup, ueg.ndown) + nup, ndown = nelec + + h1 = ueg.H1[0] + chol = 2. * ueg.chol_vecs.toarray().copy() + #ecore = ueg.ecore + ecore = 0. + + if verbose: + print(numpy.amax(numpy.absolute(chol.imag))) + print(f"# nbasis = {nbasis}") + print(f"# nchol = {nchol}") + print(f"# nup = {nup}") + print(f"# ndown = {ndown}") + + # ------------------------------------------------------------------------- + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + # 1. Build Hamiltonian. + hamiltonian = HamGeneric( + numpy.array([h1, h1], dtype=numpy.complex128), + numpy.array(chol, dtype=numpy.complex128), + ecore, + verbose=verbose) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + # 2. Build trial. + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + + # 3. Build walkers. + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + + # 4. Build propagator. + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + # ------------------------------------------------------------------------- + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + + # 1. Build out system. + legacy_system = LegacyUEG(options=ueg_opts) + + # 2. Build Hamiltonian. + legacy_hamiltonian = LegacyHamUEG(legacy_system, options=ueg_opts) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + + # 3. Build trial. + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) + + # 4. Build walkers. + legacy_walkers = [ + ThermalWalker( + legacy_system, legacy_hamiltonian, legacy_trial, + walker_opts=options, verbose=i == 0) for i in range(nwalkers)] + + # 5. Build propagator. + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps_per_block + qmc_opts.dt = timestep + qmc_opts.seed = seed + + legacy_propagator = PlaneWave(legacy_system, legacy_hamiltonian, legacy_trial, qmc_opts, + options=options["propagator"], lowrank=lowrank, verbose=verbose) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator} + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers, + 'propagator': legacy_propagator} + + return objs, legacy_objs + + +@pytest.mark.unit +def test_phaseless_generic_propagator(verbose=False): + seed = 7 + objs, legacy_objs = setup_objs(seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + h1e = legacy_hamiltonian.H1[0] + eri = legacy_hamiltonian.eri_4() + + for t in range(walkers.stack[0].nslice): + for iw in range(walkers.nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + eloc = local_energy_generic_cholesky(hamiltonian, P) + + legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers[iw].G)) + legacy_eloc = legacy_local_energy_ueg(legacy_system, legacy_hamiltonian, legacy_P) + + legacy_Pa, legacy_Pb = legacy_P + legacy_Ptot = legacy_Pa + legacy_Pb + ref_e1 = numpy.einsum('ij,ij->', h1e, legacy_Ptot) + + Ptot = legacy_Ptot + Pa = legacy_Pa + Pb = legacy_Pb + + ecoul = 0.5 * numpy.einsum('ijkl,ij,kl->', eri, Ptot, Ptot) + exx = -0.5 * numpy.einsum('ijkl,il,kj->', eri, Pa, Pa) + exx -= 0.5 * numpy.einsum('ijkl,il,kj->', eri, Pb, Pb) + ref_e2 = ecoul + exx + ref_eloc = (ref_e1 + ref_e2, ref_e1, ref_e2) + + if verbose: + print(f'\nt = {t}') + print(f'iw = {iw}') + print(f'eloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') + print(f'ref_eloc = \n{ref_eloc}\n') + print(f'walkers.weight = \n{walkers.weight[iw]}\n') + print(f'legacy_walkers.weight = \n{legacy_walkers[iw].weight}\n') + + numpy.testing.assert_almost_equal(legacy_P, P, decimal=10) + numpy.testing.assert_almost_equal(legacy_trial.dmat, trial.dmat, decimal=10) + numpy.testing.assert_allclose(eloc, ref_eloc, atol=1e-10) + numpy.testing.assert_allclose(legacy_eloc, ref_eloc, atol=1e-10) + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + + numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) + + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, xi=propagator.xi) + + +if __name__ == "__main__": + test_phaseless_generic_propagator(verbose=True) diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py b/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py new file mode 100644 index 00000000..6734b637 --- /dev/null +++ b/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py @@ -0,0 +1,256 @@ +import numpy +import pytest + +from pyscf import gto, scf, ao2mo +from ipie.qmc.options import QMCOpts +from ipie.utils.linalg import diagonalise_sorted +from ueg import UEG + +from ipie.systems.generic import Generic +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.trial_wavefunction.single_det import SingleDet +from ipie.walkers.walkers_dispatch import UHFWalkersTrial +from ipie.estimators.local_energy import local_energy_G + +from ipie.legacy.systems.ueg import UEG as LegacyUEG +from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG +from ipie.legacy.trial_wavefunction.free_electron import FreeElectron +from ipie.legacy.trial_wavefunction.multi_slater import MultiSlater +from ipie.legacy.walkers.handler import Walkers +from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G + + +def setup_objs(seed=None): + mu = -10. + nwalkers = 1 + numpy.random.seed(seed) + nblocks = 10 + nsteps_per_block = 1 + timestep = 0.005 + verbose = True + + options = { + "qmc": { + "nwalkers": nwalkers, + "blocks": nblocks, + "nsteps": nsteps_per_block, + "timestep": timestep, + "rng_seed": seed, + "batched": False + }, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + } + } + + # Generate UEG integrals. + ueg_opts = { + "nup": 7, + "ndown": 7, + "rs": 1., + "ecut": 2.5, + "thermal": False, + "write_integrals": False, + } + + ueg = UEG(ueg_opts, verbose=verbose) + ueg.build() + nbasis = ueg.nbasis + nchol = ueg.nchol + nelec = (ueg.nup, ueg.ndown) + nup, ndown = nelec + + h1 = ueg.H1[0] + chol = 2. * ueg.chol_vecs.toarray() + #ecore = ueg.ecore + ecore = 0. + + # ------------------------------------------------------------------------- + # Build trial wavefunction. + # For pyscf. + U = ueg.compute_real_transformation() + h1_8 = U.T.conj() @ h1 @ U + eri_8 = ueg.eri_8() # 8-fold eri + eri_8 = ao2mo.restore(8, eri_8, nbasis) + + mol = gto.M() + mol.nelectron = numpy.sum(nelec) + mol.spin = nup - ndown + mol.max_memory = 60000 # MB + mol.incore_anyway = True + + # PW guess. + dm0a = numpy.zeros(nbasis) + dm0b = numpy.zeros(nbasis) + dm0a[:nup] = 1 + dm0b[:ndown] = 1 + dm0 = numpy.array([numpy.diag(dm0a), numpy.diag(dm0b)]) + + mf = scf.UHF(mol) + #mf.level_shift = 0.5 + mf.max_cycle = 5000 + mf.get_hcore = lambda *args: h1_8 + mf.get_ovlp = lambda *args: numpy.eye(nbasis) + mf._eri = eri_8 + e = mf.kernel(dm0) + + Ca, Cb = mf.mo_coeff + psia = Ca[:, :nup] + psib = Cb[:, :ndown] + psi0 = numpy.zeros((nbasis, numpy.sum(nelec)), dtype=numpy.complex128) + psi0[:, :nup] = psia + psi0[:, nup:] = psib + numpy.save('ueg_trial', psi0) + + if verbose: + print(numpy.amax(numpy.absolute(chol.imag))) + print(f"# nbasis = {nbasis}") + print(f"# nchol = {nchol}") + print(f"# nup = {nup}") + print(f"# ndown = {ndown}") + + # ------------------------------------------------------------------------- + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + # 1. Build out system. + system = Generic(nelec=nelec, verbose=verbose) + + # 2. Build Hamiltonian. + hamiltonian = HamGeneric( + numpy.array([h1, h1], dtype=numpy.complex128), + numpy.array(chol, dtype=numpy.complex128), + ecore, + verbose=verbose) + + # 3. Build trial. + trial = SingleDet(psi0, nelec, nbasis, cplx=True, verbose=verbose) + trial.build() + trial.half_rotate(hamiltonian) + trial.calculate_energy(system, hamiltonian) + if verbose: print(f"\n# trial.energy = {trial.energy}\n") + + # Check against RHF solutions of 10.1063/1.5109572 + assert numpy.allclose(numpy.around(trial.energy, 6), 13.603557) # rs = 1, nbasis = 57 + assert numpy.allclose(trial.energy, e) + + # 4. Build walkers. + walkers = UHFWalkersTrial(trial, psi0, system.nup, system.ndown, hamiltonian.nbasis, + nwalkers, verbose=verbose) + walkers.build(trial) + walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) + + # ------------------------------------------------------------------------- + # Legacy. + legacy_opts = { + "trial": { + "read_in": "ueg_trial.npy" + }, + + "qmc": options["qmc"], + "hamiltonian": options["hamiltonian"], + } + + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + + # 1. Build out system. + legacy_system = LegacyUEG(options=ueg_opts) + + # 2. Build Hamiltonian. + legacy_hamiltonian = LegacyHamUEG(legacy_system, options=ueg_opts) + + # 3. Build trial. + coeffs = numpy.array([1]) + psi = numpy.array([psi0]) + wfn = [coeffs, psi] + legacy_trial = MultiSlater(legacy_system, legacy_hamiltonian, wfn, + nbasis=nbasis, cplx=True, verbose=verbose) + + # 4. Build walkers. + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers + qmc_opts.nsteps = nsteps_per_block + qmc_opts.dt = timestep + qmc_opts.seed = seed + + legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, + qmc_opts, verbose=verbose) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers} + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers} + + return objs, legacy_objs + + +@pytest.mark.unit +def test_ueg_0T(verbose=False): + seed = 7 + objs, legacy_objs = setup_objs(seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + + h1e = legacy_hamiltonian.H1[0] + eri = legacy_hamiltonian.eri_4() + + for iw in range(walkers.nwalkers): + G = numpy.array([walkers.Ga[iw], walkers.Gb[iw]]) + Ghalf = numpy.array([walkers.Ghalfa[iw], walkers.Ghalfb[iw]]) + eloc = local_energy_G(hamiltonian, trial, G, Ghalf) + + legacy_eloc = legacy_local_energy_ueg(legacy_system, legacy_hamiltonian, legacy_walkers.walkers[iw].G) + + legacy_Ga, legacy_Gb = legacy_walkers.walkers[iw].G + legacy_Gtot = legacy_Ga + legacy_Gb + ref_e1 = numpy.einsum('ij,ij->', h1e, legacy_Gtot) + + Gtot = legacy_Gtot + Ga = legacy_Ga + Gb = legacy_Gb + + ecoul = 0.5 * numpy.einsum('ijkl,ij,kl->', eri, Gtot, Gtot) + exx = -0.5 * numpy.einsum('ijkl,il,kj->', eri, Ga, Ga) + exx -= 0.5 * numpy.einsum('ijkl,il,kj->', eri, Gb, Gb) + ref_e2 = ecoul + exx + ref_eloc = (ref_e1 + ref_e2, ref_e1, ref_e2) + + if verbose: + print(f'\niw = {iw}') + print(f'eloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') + print(f'ref_eloc = \n{ref_eloc}\n') + print(f'walkers.weight = \n{walkers.weight[iw]}\n') + print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') + + numpy.testing.assert_allclose(eloc, ref_eloc, atol=1e-10) + numpy.testing.assert_allclose(legacy_eloc, ref_eloc, atol=1e-10) + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) + + +if __name__ == "__main__": + test_ueg_0T(verbose=True) diff --git a/ipie/thermal/propagation/tests/ueg/ueg.py b/ipie/thermal/propagation/tests/ueg/ueg.py new file mode 100644 index 00000000..fa0d8d7d --- /dev/null +++ b/ipie/thermal/propagation/tests/ueg/ueg.py @@ -0,0 +1,563 @@ +import numpy +import scipy.sparse +from ipie.utils.io import write_qmcpack_sparse + + +class UEG(object): + """UEG system class (integrals read from fcidump) + + Parameters + ---------- + nup : int + Number of up electrons. + + ndown : int + Number of down electrons. + + rs : float + Density parameter. + + ecut : float + Scaled cutoff energy. + + ktwist : :class:`numpy.ndarray` + Twist vector. + + verbose : bool + Print extra information. + + Attributes + ---------- + T : :class:`numpy.ndarray` + One-body part of the Hamiltonian. This is diagonal in plane wave basis. + + ecore : float + Madelung contribution to the total energy. + + h1e_mod : :class:`numpy.ndarray` + Modified one-body Hamiltonian. + + nfields : int + Number of field configurations per walker for back propagation. + + basis : :class:`numpy.ndarray` + Basis vectors within a cutoff. + + kfac : float + Scale factor (2pi/L). + """ + + def __init__(self, options, verbose=False): + if verbose: + print("# Parsing input options.") + + self.name = "UEG" + self.nup = options.get("nup") + self.ndown = options.get("ndown") + self.nelec = (self.nup, self.ndown) + self.rs = options.get("rs") + self.ecut = options.get("ecut") + self.ktwist = numpy.array(options.get("ktwist", [0, 0, 0])).reshape(3) + + self.thermal = options.get("thermal", False) + self._alt_convention = options.get("alt_convention", False) + self.write_ints = options.get("write_integrals", False) + + self.sparse = True + self.control_variate = False + self.diagH1 = True + + # Total # of electrons. + self.ne = self.nup + self.ndown + # Spin polarisation. + self.zeta = (self.nup - self.ndown) / self.ne + # Density. + self.rho = ((4.0 * numpy.pi) / 3.0 * self.rs**3.0) ** (-1.0) + # Box Length. + self.L = self.rs * (4.0 * self.ne * numpy.pi / 3.0) ** (1 / 3.0) + # Volume + self.vol = self.L**3.0 + # k-space grid spacing. + self.kfac = 2 * numpy.pi / self.L + # Fermi Wavevector (infinite system). + self.kf = (3 * (self.zeta + 1) * numpy.pi**2 * self.ne / self.L**3) ** (1 / 3.0) + # Fermi energy (inifinite systems). + self.ef = 0.5 * self.kf**2 + # Core energy. + self.ecore = 0.5 * self.ne * self.madelung() + + if verbose: + if self.thermal: + print("# Thermal UEG activated.") + + print(f"# Number of spin-up electrons: {self.nup:d}") + print(f"# Number of spin-down electrons: {self.ndown:d}") + print(f"# rs: {self.rs:6.4e}") + print(f"# Spin polarisation (zeta): {self.zeta:6.4e}") + print(f"# Electron density (rho): {self.rho:13.8e}") + print(f"# Box Length (L): {self.L:13.8e}") + print(f"# Volume: {self.vol:13.8e}") + print(f"# k-space factor (2pi/L): {self.kfac:13.8e}") + + + def build(self, verbose=False): + # Get plane wave basis vectors and corresponding eigenvalues. + self.sp_eigv, self.basis, self.nmax = self.sp_energies( + self.ktwist, self.kfac, self.ecut) + self.shifted_nmax = 2 * self.nmax + self.imax_sq = numpy.dot(self.basis[-1], self.basis[-1]) + self.create_lookup_table() + + for i, k in enumerate(self.basis): + assert i == self.lookup_basis(k) + + # Number of plane waves. + self.nbasis = len(self.sp_eigv) + self.nactive = self.nbasis + self.ncore = 0 + self.nfv = 0 + self.mo_coeff = None + + # --------------------------------------------------------------------- + T = numpy.diag(self.sp_eigv) + h1e_mod = self.mod_one_body(T) + self.H1 = numpy.array([T, T]) # Making alpha and beta. + self.h1e_mod = numpy.array([h1e_mod, h1e_mod]) + + # --------------------------------------------------------------------- + # Allowed momentum transfers (4*ecut). + eigs, qvecs, self.qnmax = self.sp_energies(self.ktwist, self.kfac, 4 * self.ecut) + + # Omit Q = 0 term. + self.qvecs = numpy.copy(qvecs[1:]) + self.vqvec = numpy.array([self.vq(self.kfac * q) for q in self.qvecs]) + + # Number of momentum transfer vectors / auxiliary fields. + # Can reduce by symmetry but be stupid for the moment. + self.nchol = len(self.qvecs) + self.nfields = 2 * len(self.qvecs) + self.get_momentum_transfers() + + if verbose: + print(f"# Number of plane waves: {self.nbasis:d}") + print(f"# Number of Cholesky vectors: {self.nchol:d}.") + print(f"# Number of auxiliary fields: {self.nfields:d}.") + print("# Constructing two-body potentials incore.") + + # --------------------------------------------------------------------- + self.chol_vecs, self.iA, self.iB = self.two_body_potentials_incore() + + if self.write_ints: + self.write_integrals() + + if verbose: + print("# Approximate memory required for " + "two-body potentials: {:13.8e} GB.".format((3 * self.iA.nnz * 16 / (1024**3)))) + print("# Finished constructing two-body potentials.") + print("# Finished building UEG object.") + + + def sp_energies(self, ks, kfac, ecut): + """Calculate the allowed kvectors and resulting single particle eigenvalues (basically kinetic energy) + which can fit in the sphere in kspace determined by ecut. + + Parameters + ---------- + kfac : float + kspace grid spacing. + + ecut : float + energy cutoff. + + Returns + ------- + spval : :class:`numpy.ndarray` + Array containing sorted single particle eigenvalues. + + kval : :class:`numpy.ndarray` + Array containing basis vectors, sorted according to their + corresponding single-particle energy. + """ + + # Scaled Units to match with HANDE. + # So ecut is measured in units of 1/kfac^2. + nmax = int(numpy.ceil(numpy.sqrt((2 * ecut)))) + + spval = [] + vec = [] + kval = [] + + for ni in range(-nmax, nmax + 1): + for nj in range(-nmax, nmax + 1): + for nk in range(-nmax, nmax + 1): + spe = 0.5 * (ni**2 + nj**2 + nk**2) + + if spe <= ecut: + kijk = [ni, nj, nk] + + # Reintroduce 2 \pi / L factor. + ek = 0.5 * numpy.dot(numpy.array(kijk) + ks, numpy.array(kijk) + ks) + kval.append(kijk) + spval.append(kfac**2 * ek) + + # Sort the arrays in terms of increasing energy. + spval = numpy.array(spval) + ix = numpy.argsort(spval, kind="mergesort") + spval = spval[ix] + kval = numpy.array(kval)[ix] + return spval, kval, nmax + + + def create_lookup_table(self): + basis_ix = [] + for k in self.basis: + basis_ix.append(self.map_basis_to_index(k)) + + self.lookup = numpy.zeros(max(basis_ix) + 1, dtype=int) + + for i, b in enumerate(basis_ix): + self.lookup[b] = i + + self.max_ix = max(basis_ix) + + + def lookup_basis(self, vec): + if numpy.dot(vec, vec) <= self.imax_sq: + ix = self.map_basis_to_index(vec) + + if ix >= len(self.lookup): + ib = None + + else: + ib = self.lookup[ix] + + return ib + + else: + ib = None + + + def map_basis_to_index(self, k): + return ((k[0] + self.nmax) + + self.shifted_nmax * (k[1] + self.nmax) + + self.shifted_nmax * self.shifted_nmax * (k[2] + self.nmax)) + + + def get_momentum_transfers(self): + """Get arrays of plane wave basis vectors connected by momentum transfers Q.""" + nlimit = self.nup + if self.thermal: + nlimit = self.nbasis + + self.ikpq_i = [] + self.ikpq_kpq = [] + + for iq, q in enumerate(self.qvecs): + idxkpq_list_i = [] + idxkpq_list_kpq = [] + + for i, k in enumerate(self.basis[0:nlimit]): + kpq = k + q + idxkpq = self.lookup_basis(kpq) + + if idxkpq is not None: + idxkpq_list_i += [i] + idxkpq_list_kpq += [idxkpq] + + self.ikpq_i += [idxkpq_list_i] + self.ikpq_kpq += [idxkpq_list_kpq] + + # --------------------------------------------------------------------- + self.ipmq_i = [] + self.ipmq_pmq = [] + + for iq, q in enumerate(self.qvecs): + idxpmq_list_i = [] + idxpmq_list_pmq = [] + + for i, p in enumerate(self.basis[0:nlimit]): + pmq = p - q + idxpmq = self.lookup_basis(pmq) + + if idxpmq is not None: + idxpmq_list_i += [i] + idxpmq_list_pmq += [idxpmq] + + self.ipmq_i += [idxpmq_list_i] + self.ipmq_pmq += [idxpmq_list_pmq] + + for iq, q in enumerate(self.qvecs): + self.ikpq_i[iq] = numpy.array(self.ikpq_i[iq], dtype=numpy.int64) + self.ikpq_kpq[iq] = numpy.array(self.ikpq_kpq[iq], dtype=numpy.int64) + self.ipmq_i[iq] = numpy.array(self.ipmq_i[iq], dtype=numpy.int64) + self.ipmq_pmq[iq] = numpy.array(self.ipmq_pmq[iq], dtype=numpy.int64) + + + def madelung(self): + """Use expression in Schoof et al. (PhysRevLett.115.130402) for the + Madelung contribution to the total energy fitted to L.M. Fraser et al. + Phys. Rev. B 53, 1814. + + Parameters + ---------- + rs : float + Wigner-Seitz radius. + + ne : int + Number of electrons. + + Returns + ------- + v_M: float + Madelung potential (in Hartrees). + """ + c1 = -2.837297 + c2 = (3.0 / (4.0 * numpy.pi)) ** (1.0 / 3.0) + return c1 * c2 / (self.ne ** (1.0 / 3.0) * self.rs) + + + def mod_one_body(self, T): + """Absorb the diagonal term of the two-body Hamiltonian to the one-body term. + Essentially adding the third term in Eq.(11b) of Phys. Rev. B 75, 245123. + + Parameters + ---------- + T : float + one-body Hamiltonian (i.e. kinetic energy) + + Returns + ------- + h1e_mod: float + modified one-body Hamiltonian + """ + h1e_mod = numpy.copy(T) + + fac = 1.0 / (2.0 * self.vol) + for i, ki in enumerate(self.basis): + for j, kj in enumerate(self.basis): + if i != j: + q = self.kfac * (ki - kj) + h1e_mod[i, i] = h1e_mod[i, i] - fac * self.vq(q) + + return h1e_mod + + + def vq(self, q): + """The typical 3D Coulomb kernel + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + v_M: float + 3D Coulomb kernel (in Hartrees) + """ + return 4 * numpy.pi / numpy.dot(q, q) + + + def density_operator(self, iq): + """Density operator as defined in Eq.(6) of Phys. Rev. B 75, 245123. + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + rho_q: float + density operator + """ + nnz = self.rho_ikpq_kpq[iq].shape[0] # Number of non-zeros + ones = numpy.ones((nnz), dtype=numpy.complex128) + rho_q = scipy.sparse.csc_matrix( + (ones, (self.rho_ikpq_kpq[iq], self.rho_ikpq_i[iq])), + shape=(self.nbasis, self.nbasis), + dtype=numpy.complex128) + return rho_q + + + def scaled_density_operator_incore(self, transpose): + """Density operator as defined in Eq.(6) of PRB(75)245123 + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + rho_q: float + density operator + """ + rho_ikpq_i = [] + rho_ikpq_kpq = [] + + for iq, q in enumerate(self.qvecs): + idxkpq_list_i = [] + idxkpq_list_kpq = [] + + for i, k in enumerate(self.basis): + kpq = k + q + idxkpq = self.lookup_basis(kpq) + + if idxkpq is not None: + idxkpq_list_i += [i] + idxkpq_list_kpq += [idxkpq] + + rho_ikpq_i += [idxkpq_list_i] + rho_ikpq_kpq += [idxkpq_list_kpq] + + for iq, q in enumerate(self.qvecs): + rho_ikpq_i[iq] = numpy.array(rho_ikpq_i[iq], dtype=numpy.int64) + rho_ikpq_kpq[iq] = numpy.array(rho_ikpq_kpq[iq], dtype=numpy.int64) + + nq = len(self.qvecs) + nnz = 0 + for iq in range(nq): + nnz += rho_ikpq_kpq[iq].shape[0] + + col_index = [] + row_index = [] + values = [] + + if transpose: + for iq in range(nq): + qscaled = self.kfac * self.qvecs[iq] + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = numpy.pi / (self.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + for innz, kpq in enumerate(rho_ikpq_kpq[iq]): + row_index += [rho_ikpq_kpq[iq][innz] + rho_ikpq_i[iq][innz] * self.nbasis] + col_index += [iq] + values += [factor] + + else: + for iq in range(nq): + qscaled = self.kfac * self.qvecs[iq] + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = numpy.pi / (self.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + for innz, kpq in enumerate(rho_ikpq_kpq[iq]): + row_index += [rho_ikpq_kpq[iq][innz] * self.nbasis + rho_ikpq_i[iq][innz]] + col_index += [iq] + values += [factor] + + rho_q = scipy.sparse.csc_matrix( + (values, (row_index, col_index)), + shape=(self.nbasis * self.nbasis, nq), + dtype=numpy.complex128) + return rho_q + + + def two_body_potentials_incore(self): + """Calculate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q + + Returns + ------- + iA : numpy array + Eq.(13a) + + iB : numpy array + Eq.(13b) + """ + rho_q = self.scaled_density_operator_incore(False) + rho_qH = self.scaled_density_operator_incore(True) + iA = 1j * (rho_q + rho_qH) + iB = -(rho_q - rho_qH) + return (rho_q, iA, iB) + + + def hijkl(self, i, j, k, l): + """Compute = (ik|jl) = 1/Omega * 4pi/(kk-ki)**2 + + Checks for momentum conservation k_i + k_j = k_k + k_k, or + k_k - k_i = k_j - k_l. + + Parameters + ---------- + i, j, k, l : int + Orbital indices for integral (ik|jl) = . + + Returns + ------- + integral : float + (ik|jl) + """ + q1 = self.basis[k] - self.basis[i] + q2 = self.basis[j] - self.basis[l] + + if numpy.dot(q1, q1) > 1e-12 and numpy.dot(q1 - q2, q1 - q2) < 1e-12: + return 1.0 / self.vol * self.vq(self.kfac * q1) + + else: + return 0.0 + + + def compute_real_transformation(self): + U22 = numpy.zeros((2, 2), dtype=numpy.complex128) + U22[0, 0] = 1.0 / numpy.sqrt(2.0) + U22[0, 1] = 1.0 / numpy.sqrt(2.0) + U22[1, 0] = -1.0j / numpy.sqrt(2.0) + U22[1, 1] = 1.0j / numpy.sqrt(2.0) + + U = numpy.zeros((self.nbasis, self.nbasis), dtype=numpy.complex128) + + for i, b in enumerate(self.basis): + if numpy.sum(b * b) == 0: + U[i, i] = 1.0 + + else: + mb = -b + diff = numpy.einsum("ij->i", (self.basis - mb) ** 2) + idx = numpy.argwhere(diff == 0) + assert idx.ravel().shape[0] == 1 + + if i < idx: + idx = idx.ravel()[0] + U[i, i] = U22[0, 0] + U[i, idx] = U22[0, 1] + U[idx, i] = U22[1, 0] + U[idx, idx] = U22[1, 1] + + else: + continue + + U = U.T.copy() + return U + + + def eri_4(self): + eri_chol = 4 * self.chol_vecs.dot(self.chol_vecs.T) + eri_chol = ( + eri_chol.toarray().reshape((self.nbasis, self.nbasis, self.nbasis, self.nbasis)).real) + eri_chol = eri_chol.transpose(0, 1, 3, 2) + return eri_chol + + + def eri_8(self): + """Compute 8-fold symmetric integrals. Useful for running standard + quantum chemistry methods,""" + eri = self.eri_4() + U = self.compute_real_transformation() + eri0 = numpy.einsum("mp,mnls->pnls", U.conj(), eri, optimize=True) + eri1 = numpy.einsum("nq,pnls->pqls", U, eri0, optimize=True) + eri2 = numpy.einsum("lr,pqls->pqrs", U.conj(), eri1, optimize=True) + eri3 = numpy.einsum("st,pqrs->pqrt", U, eri2, optimize=True).real + return eri3 + + + def write_integrals(self, filename="ueg_integrals.h5"): + write_qmcpack_sparse( + self.H1[0], + 2 * self.chol_vecs.toarray(), + self.nelec, + self.nbasis, + enuc=0.0, + filename=filename) + diff --git a/ipie/thermal/propagation/tests/ueg/ueg_trial.npy b/ipie/thermal/propagation/tests/ueg/ueg_trial.npy new file mode 100644 index 0000000000000000000000000000000000000000..7cfba666c941ee47d15768d16c502137b443892b GIT binary patch literal 12896 zcmeH{F>1pw7)I5#r_iPryadt~LZDl=mMk4Q6_Yq*2uZO+mk{V3a-d!*M~ItP;;W!b z9BT+qgRS2Nee(0uzk7Xq8Nc6{FSBveqMDR$VBK)idvuv~vsJk+^X12?oEEgUxw|19eI?%^r3z5ab>xAweoYmQ_8e7cA0cbJ_f7p_z1nP~s1^Hb-=-`l!wblCqi zlZa>Q_2czg=B4JHI`2Q;VIMKij_TBTjTR>4`Uf3-pI`n`d10N7_v`&go#%P^eCmck zqW=wVcpnMiTQ~~vs0rW$J}3cvP#T;Me82}KfDcN8{(ukopak$iY0w|=0UwkAJ}3?P z13ut`62J$gL4Uvpd{6@Tpfue03VbF{Q)2FK?&f4(x5-!13oALd{7$nhrcwg Gs5$_5)38YZ literal 0 HcmV?d00001 diff --git a/ipie/thermal/trial/tests/test_mean_field.py b/ipie/thermal/trial/tests/test_mean_field.py index 61233c8e..d5a4a04b 100644 --- a/ipie/thermal/trial/tests/test_mean_field.py +++ b/ipie/thermal/trial/tests/test_mean_field.py @@ -44,6 +44,7 @@ def setup_objs(): return objs +@pytest.mark.unit def test_mean_field(): beta = 0.1 dt = 0.01 diff --git a/ipie/thermal/trial/tests/test_one_body.py b/ipie/thermal/trial/tests/test_one_body.py index b049c3c4..9237180c 100644 --- a/ipie/thermal/trial/tests/test_one_body.py +++ b/ipie/thermal/trial/tests/test_one_body.py @@ -44,6 +44,7 @@ def setup_objs(): return objs +@pytest.mark.unit def test_one_body(): beta = 0.1 dt = 0.01 diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py index 93830d77..bdd28f54 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -18,6 +18,7 @@ from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G + def setup_objs(mf_trial=False, seed=None): nocca = 5 noccb = 5 @@ -107,6 +108,7 @@ def setup_objs(mf_trial=False, seed=None): return objs, legacy_objs + @pytest.mark.unit def test_thermal_walkers(): verbose = True From 108fb7dd18db201a8cde4ed2b148caa92ebbd91e Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 4 Jan 2024 11:31:40 +0800 Subject: [PATCH 36/84] Except KeyError --- ipie/analysis/extraction.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ipie/analysis/extraction.py b/ipie/analysis/extraction.py index f9103afd..ec33ac8b 100755 --- a/ipie/analysis/extraction.py +++ b/ipie/analysis/extraction.py @@ -230,7 +230,10 @@ def extract_test_data_hdf5(filename, skip=10): data = extract_mixed_estimates(filename) # use list so can json serialise easily. data = data.drop(["Iteration", "Time"], axis=1)[::skip].to_dict(orient="list") - data["sys_info"] = get_metadata(filename)["sys_info"] + try: + data["sys_info"] = get_metadata(filename)["sys_info"] + except KeyError: + print("\n# No 'sys_info' metadata!") try: mrdm = extract_rdm(filename, est_type="mixed", rdm_type="one_rdm") except (KeyError, TypeError, AttributeError): From 0ffdd6fc02b8ada6d5ca1af55eb131c58db7c08e Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 4 Jan 2024 11:39:05 +0800 Subject: [PATCH 37/84] Reshape legacy Hamiltonian `chol_vecs` for backwards compatibility. --- ipie/legacy/thermal_propagation/generic.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ipie/legacy/thermal_propagation/generic.py b/ipie/legacy/thermal_propagation/generic.py index 7454b5df..9c4c63de 100644 --- a/ipie/legacy/thermal_propagation/generic.py +++ b/ipie/legacy/thermal_propagation/generic.py @@ -23,7 +23,7 @@ class GenericContinuous(object): qmc : :class:`pie.qmc.options.QMCOpts` QMC options. system : :class:`pie.system.System` - System object. + System object is actually HAMILTONIAN!!! trial : :class:`pie.trial_wavefunctioin.Trial` Trial wavefunction object. verbose : bool @@ -91,7 +91,10 @@ def construct_mean_field_shift(self, system, P): mf_shift = 1j * P[0].ravel() * system.chol_vecs mf_shift += 1j * P[1].ravel() * system.chol_vecs else: + # Need to reshape `chol_vecs` just to run the einsum lol. + system.chol_vecs = system.chol_vecs.T.reshape(system.nchol, system.nbasis, system.nbasis) mf_shift = 1j * numpy.einsum("lpq,spq->l", system.chol_vecs, P) + system.chol_vecs = system.chol_vecs.reshape(system.nchol, system.nbasis**2).T return mf_shift def construct_one_body_propagator(self, system, dt): From 3b64917d539089896f8ca284ab6795765a155778 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 4 Jan 2024 11:42:52 +0800 Subject: [PATCH 38/84] Add flags for debugging in legacy code. Correct for backwards compatibility. --- ipie/legacy/estimators/ueg.py | 27 +++++++++++++------ ipie/legacy/propagation/pw.py | 2 +- ipie/legacy/thermal_propagation/planewave.py | 14 +++++----- .../legacy/trial_wavefunction/multi_slater.py | 3 ++- 4 files changed, 29 insertions(+), 17 deletions(-) diff --git a/ipie/legacy/estimators/ueg.py b/ipie/legacy/estimators/ueg.py index dde01443..210bb0ac 100644 --- a/ipie/legacy/estimators/ueg.py +++ b/ipie/legacy/estimators/ueg.py @@ -25,7 +25,7 @@ def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): Gpmq[iq] += G[i, idxpmq] -def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): +def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None, debug=False): """Local energy computation for uniform electron gas Parameters ---------- @@ -69,20 +69,31 @@ def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): if two_rdm is None: two_rdm = numpy.zeros((2, 2, len(ham.qvecs)), dtype=numpy.complex128) - two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] - essa = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 0]) + two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] - essb = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[1, 1]) - two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) - eos = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 1]) + ( - 1.0 / (2.0 * ham.vol) - ) * ham.vqvec.dot(two_rdm[1, 0]) + essa = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 0]) + essb = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[1, 1]) + eos = (1.0 / (2.0 * ham.vol)) * ( + ham.vqvec.dot(two_rdm[0, 1]) + ham.vqvec.dot(two_rdm[1, 0])) pe = essa + essb + eos + if debug: + ecoul, exx = 0., 0. + + for s1 in range(2): + exx -= (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(Gprod[s1]) + + for s2 in range(2): + ecoul += (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(numpy.multiply(Gkpq[s1], Gpmq[s2])) + + print(f'\n# ueg ecoul = {ecoul}') + print(f'# ueg exx = {exx}') + print(f'# ueg e2 = {(ecoul + exx)}') + return (ke + pe, ke, pe) diff --git a/ipie/legacy/propagation/pw.py b/ipie/legacy/propagation/pw.py index 379d4f9f..87445311 100644 --- a/ipie/legacy/propagation/pw.py +++ b/ipie/legacy/propagation/pw.py @@ -5,7 +5,7 @@ import numpy import scipy -from ipie.estimators.utils import convolve, scipy_fftconvolve +from ipie.legacy.estimators.utils import convolve, scipy_fftconvolve from ipie.legacy.propagation.operations import kinetic_real diff --git a/ipie/legacy/thermal_propagation/planewave.py b/ipie/legacy/thermal_propagation/planewave.py index 8b258c38..0fef03e8 100644 --- a/ipie/legacy/thermal_propagation/planewave.py +++ b/ipie/legacy/thermal_propagation/planewave.py @@ -105,7 +105,6 @@ def construct_one_body_propagator(self, hamiltonian, dt): """ H1 = hamiltonian.h1e_mod I = numpy.identity(H1[0].shape[0], dtype=H1.dtype) - print(f"hamiltonian.mu = {hamiltonian.mu}") # No spin dependence for the moment. self.BH1 = numpy.array( [ @@ -228,7 +227,7 @@ def propagate_greens_function(self, walker, B, Binv): walker.G[0] = B[0].dot(walker.G[0]).dot(Binv[0]) walker.G[1] = B[1].dot(walker.G[1]).dot(Binv[1]) - def two_body_propagator(self, walker, hamiltonian, force_bias=True): + def two_body_propagator(self, walker, hamiltonian, force_bias=True, xi=None): """It appliese the two-body propagator Parameters ---------- @@ -249,7 +248,8 @@ def two_body_propagator(self, walker, hamiltonian, force_bias=True): """ # Normally distrubted auxiliary fields. - xi = numpy.random.normal(0.0, 1.0, hamiltonian.nfields) + if xi is None: + xi = numpy.random.normal(0.0, 1.0, hamiltonian.nfields) # Optimal force bias. xbar = numpy.zeros(hamiltonian.nfields) @@ -472,7 +472,7 @@ def propagate_walker_free_low_rank(self, system, walker, trial, eshift=0, force_ except ZeroDivisionError: walker.weight = 0.0 - def propagate_walker_phaseless_full_rank(self, hamiltonian, walker, trial, eshift=0): + def propagate_walker_phaseless_full_rank(self, hamiltonian, walker, trial, eshift=0, xi=None): # """Phaseless propagator # Parameters # ---------- @@ -486,7 +486,7 @@ def propagate_walker_phaseless_full_rank(self, hamiltonian, walker, trial, eshif # ------- # """ - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, hamiltonian, True) + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, hamiltonian, True, xi=xi) BV = self.exponentiate(VHS) # could use a power-series method to build this B = numpy.array( @@ -554,7 +554,7 @@ def propagate_walker_phaseless_full_rank(self, hamiltonian, walker, trial, eshif except ZeroDivisionError: walker.weight = 0.0 - def propagate_walker_phaseless_low_rank(self, hamiltonian, walker, trial, eshift=0): + def propagate_walker_phaseless_low_rank(self, hamiltonian, walker, trial, eshift=0, xi=None): # """Phaseless propagator # Parameters # ---------- @@ -567,7 +567,7 @@ def propagate_walker_phaseless_low_rank(self, hamiltonian, walker, trial, eshift # Returns # ------- # """ - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, hamiltonian, True) + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, hamiltonian, True, xi=xi) BV = self.exponentiate(VHS) # could use a power-series method to build this B = numpy.array( diff --git a/ipie/legacy/trial_wavefunction/multi_slater.py b/ipie/legacy/trial_wavefunction/multi_slater.py index 1553c9f2..d198a5c0 100644 --- a/ipie/legacy/trial_wavefunction/multi_slater.py +++ b/ipie/legacy/trial_wavefunction/multi_slater.py @@ -30,6 +30,7 @@ def __init__( nbasis=None, options={}, init=None, + cplx=False, verbose=False, orbs=None, ): @@ -48,7 +49,7 @@ def __init__( else: self.psi = wfn[1] imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) - if imag_norm <= 1e-8: + if (not cplx) and (imag_norm <= 1e-8): # print("# making trial wavefunction MO coefficient real") self.psi = numpy.array(self.psi.real, dtype=numpy.float64) self.coeffs = numpy.array(wfn[0], dtype=numpy.complex128) From 01f60e0c67495f69df8ddbab26423a9aff05dfe2 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 4 Jan 2024 12:16:13 +0800 Subject: [PATCH 39/84] Updated Thermal AFQMC--tests agree with legacy for both UEG and Generic Hamiltonians. --- ipie/thermal/estimators/estimators.py | 131 ---- ipie/thermal/estimators/fock.py | 12 - ipie/thermal/estimators/greens_function.py | 8 +- ipie/thermal/estimators/mixed.py | 475 --------------- ipie/thermal/estimators/ueg.py | 290 --------- ipie/thermal/estimators/ueg_kernels.pyx | 169 ------ ipie/thermal/estimators/utils.py | 318 ---------- ...generic.py => test_generic_propagation.py} | 2 +- .../propagation/tests/ueg/test_ueg_0T.py | 4 +- .../{test_ueg.py => test_ueg_propagation.py} | 5 +- ipie/thermal/qmc/options.py | 11 +- ipie/thermal/qmc/tests/run_legacy.py | 267 +++++++++ ipie/thermal/qmc/tests/test_generic.py | 307 ++++++++++ ipie/thermal/qmc/tests/test_run.py | 147 +++++ ipie/thermal/qmc/tests/ueg/test_ueg.py | 422 +++++++++++++ ipie/thermal/qmc/tests/ueg/ueg.py | 563 ++++++++++++++++++ ipie/thermal/qmc/thermal_afqmc.py | 58 +- ipie/thermal/trial/mean_field.py | 14 +- ipie/thermal/trial/one_body.py | 8 +- ipie/thermal/walkers/base_walkers.py | 17 - ipie/thermal/walkers/stack.py | 42 +- ipie/thermal/walkers/uhf_walkers.py | 10 + 22 files changed, 1795 insertions(+), 1485 deletions(-) delete mode 100644 ipie/thermal/estimators/estimators.py delete mode 100644 ipie/thermal/estimators/fock.py delete mode 100644 ipie/thermal/estimators/mixed.py delete mode 100644 ipie/thermal/estimators/ueg.py delete mode 100644 ipie/thermal/estimators/ueg_kernels.pyx delete mode 100644 ipie/thermal/estimators/utils.py rename ipie/thermal/propagation/tests/{test_generic.py => test_generic_propagation.py} (100%) rename ipie/thermal/propagation/tests/ueg/{test_ueg.py => test_ueg_propagation.py} (99%) create mode 100644 ipie/thermal/qmc/tests/run_legacy.py create mode 100644 ipie/thermal/qmc/tests/test_generic.py create mode 100644 ipie/thermal/qmc/tests/test_run.py create mode 100644 ipie/thermal/qmc/tests/ueg/test_ueg.py create mode 100644 ipie/thermal/qmc/tests/ueg/ueg.py delete mode 100644 ipie/thermal/walkers/base_walkers.py diff --git a/ipie/thermal/estimators/estimators.py b/ipie/thermal/estimators/estimators.py deleted file mode 100644 index 065f5f7c..00000000 --- a/ipie/thermal/estimators/estimators.py +++ /dev/null @@ -1,131 +0,0 @@ -"""Routines and classes for estimation of observables.""" - -from __future__ import print_function - -import os -import h5py -import numpy - -from ipie.thermal.estimators.mixed import Mixed - - -class Estimators(object): - """Container for qmc estimates of observables. - - Parameters - ---------- - estimates : dict - input options detailing which estimators to calculate. By default only - mixed estimates will be calculated. - root : bool - True if on root/master processor. - qmc : :class:`ipie.state.QMCOpts` object. - Container for qmc input options. - trial : :class:`ipie.trial_wavefunction.X' object - Trial wavefunction class. - BT2 : :class:`numpy.ndarray` - One body propagator. - verbose : bool - If true we print out additional setup information. - - Attributes - ---------- - h5f : :class:`h5py.File` - Output file object. - estimates : dict - Dictionary of estimator objects. - back_propagation : bool - True if doing back propagation, specified in estimates dict. - nbp : int - Number of back propagation steps. - nprop_tot : int - Total number of auxiliary field configurations we store / use for back - propagation and itcf calculation. - calc_itcf : bool - True if calculating imaginary time correlation functions (ITCFs). - """ - - def __init__(self, estimates, root, qmc, hamiltonian, trial, BT2, verbose=False): - if verbose: - print("# Setting up estimator object.") - if root: - self.index = estimates.get("index", 0) - self.filename = estimates.get("filename", None) - self.basename = estimates.get("basename", "estimates") - if self.filename is None: - overwrite = estimates.get("overwrite", True) - self.filename = self.basename + f".{self.index}.h5" - while os.path.isfile(self.filename) and not overwrite: - self.index = int(self.filename.split(".")[1]) - self.index = self.index + 1 - self.filename = self.basename + f".{self.index}.h5" - with h5py.File(self.filename, "w") as fh5: - pass - if verbose: - print(f"# Writing estimator data to {self.filename}.") - else: - self.filename = None - # Sub-members: - # 1. Back-propagation - mixed = estimates.get("mixed", {}) - self.estimators = {} - dtype = complex - self.estimators["mixed"] = Mixed( - mixed, hamiltonian, root, self.filename, qmc, trial, dtype - ) - self.nprop_tot = None - self.nbp = None - # 2. Imaginary time correlation functions. - if verbose: - print("# Finished settting up estimator object.") - - def reset(self, root): - if root: - self.increment_file_number() - self.dump_metadata() - for k, e in self.estimators.items(): - e.setup_output(self.filename) - - def dump_metadata(self): - with h5py.File(self.filename, "a") as fh5: - fh5["metadata"] = self.json_string - - def increment_file_number(self): - self.index = self.index + 1 - self.filename = self.basename + f".{self.index}.h5" - - def print_step(self, comm, nprocs, step, nsteps=None, free_projection=False): - """Print QMC estimates. - - Parameters - ---------- - comm : - MPI communicator. - nprocs : int - Number of processors. - step : int - Current iteration number. - nmeasure : int - Number of steps between measurements. - """ - for k, e in self.estimators.items(): - e.print_step(comm, nprocs, step, nsteps=nsteps, free_projection=free_projection) - - def update(self, qmc, hamiltonian, trial, psi, step, free_projection=False): - """Update estimators - - Parameters - ---------- - qmc : :class:`ipie.state.QMCOpts` object. - Container for qmc input options. - trial : :class:`ipie.trial_wavefunction.X' object - Trial wavefunction class. - psi : :class:`ipie.legacy.walkers.Walkers` object - CPMC wavefunction. - step : int - Current simulation step - free_projection : bool - True if doing free projection. - """ - for k, e in self.estimators.items(): - e.update(qmc, hamiltonian, trial, psi, step, free_projection) diff --git a/ipie/thermal/estimators/fock.py b/ipie/thermal/estimators/fock.py deleted file mode 100644 index 63f493b0..00000000 --- a/ipie/thermal/estimators/fock.py +++ /dev/null @@ -1,12 +0,0 @@ -from ipie.thermal.estimators.generic import fock_generic -from ipie.thermal.estimators.ueg import fock_ueg - - -def fock_matrix(hamiltonian, G): - if hamiltonian.name == "UEG": - return fock_ueg(hamiltonian, G) - elif hamiltonian.name == "Generic": - return fock_generic(hamiltonian, G) - else: - print(f"# Fock matrix not implemented for {hamiltonian.name}") - return None diff --git a/ipie/thermal/estimators/greens_function.py b/ipie/thermal/estimators/greens_function.py index 6760f147..c2c9b4ed 100644 --- a/ipie/thermal/estimators/greens_function.py +++ b/ipie/thermal/estimators/greens_function.py @@ -43,7 +43,7 @@ def greens_function_qr_strat(walkers, iw, slice_ix=None, inplace=True): bin_ix = slice_ix // stack_iw.nstack # For final time slice want first block to be the rightmost (for energy # evaluation). - if bin_ix == stack_iw.nbins: + if bin_ix == stack_iw.stack_length: bin_ix = -1 Ga_iw, Gb_iw = None, None @@ -55,7 +55,7 @@ def greens_function_qr_strat(walkers, iw, slice_ix=None, inplace=True): # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in # stable way. Iteratively construct column pivoted QR decompositions # (A = QDT) starting from the rightmost (product of) propagator(s). - B = stack_iw.get((bin_ix + 1) % stack_iw.nbins) + B = stack_iw.get((bin_ix + 1) % stack_iw.stack_length) (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) # Form D matrices @@ -65,8 +65,8 @@ def greens_function_qr_strat(walkers, iw, slice_ix=None, inplace=True): # permute them T1[:, P1] = T1[:, range(walkers.nbasis)] - for i in range(2, stack_iw.nbins + 1): - ix = (bin_ix + i) % stack_iw.nbins + for i in range(2, stack_iw.stack_length + 1): + ix = (bin_ix + i) % stack_iw.stack_length B = stack_iw.get(ix) C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) diff --git a/ipie/thermal/estimators/mixed.py b/ipie/thermal/estimators/mixed.py deleted file mode 100644 index 5f641c52..00000000 --- a/ipie/thermal/estimators/mixed.py +++ /dev/null @@ -1,475 +0,0 @@ -import h5py -import numpy - -try: - from ipie.config import MPI - - mpi_sum = MPI.SUM -except ImportError: - mpi_sum = None -import time - -from ipie.estimators.greens_function import greens_function -#from ipie.estimators.local_energy_batch import local_energy_batch -from ipie.estimators.utils import H5EstimatorHelper -from ipie.thermal.estimators.local_energy import local_energy -from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number -from ipie.utils.io import format_fixed_width_floats, format_fixed_width_strings -from ipie.utils.misc import dotdict, is_cupy - - -class Mixed(object): - """Class for computing mixed estimates. - - Parameters - ---------- - mixed : dict - Input options for mixed estimates. - root : bool - True if on root/master processor. - qmc : :class:`ipie.state.QMCOpts` object. - Container for qmc input options. - trial : :class:`ipie.trial_wavefunction.X' object - Trial wavefunction class. - dtype : complex or float - Output type. - - Attributes - ---------- - nmeasure : int - Max number of measurements. - nreg : int - Number of regular estimates (exluding iteration). - G : :class:`numpy.ndarray` - One-particle RDM. - estimates : :class:`numpy.ndarray` - Store for mixed estimates per processor. - global_estimates : :class:`numpy.ndarray` - Store for mixed estimates accross all processors. - names : :class:`ipie.estimators.EstimEnum` - Enum for locating estimates in estimates array. - header : int - Output header. - key : dict - Explanation of output. - output : :class:`ipie.estimators.H5EstimatorHelper` - Class for outputting data to HDF5 group. - output : :class:`ipie.estimators.H5EstimatorHelper` - Class for outputting rdm data to HDF5 group. - """ - - def __init__(self, mixed_opts, hamiltonian, root, filename, qmc, trial, dtype): - self.average_gf = mixed_opts.get("average_gf", False) - self.eval_energy = mixed_opts.get("evaluate_energy", True) - self.calc_one_rdm = mixed_opts.get("one_rdm", False) - self.calc_two_rdm = mixed_opts.get("two_rdm", None) - self.energy_eval_freq = mixed_opts.get("energy_eval_freq", None) - if self.energy_eval_freq is None: - self.energy_eval_freq = qmc.nsteps - self.verbose = mixed_opts.get("verbose", True) - # number of steps per block - self.nsteps = qmc.nsteps - self.header = [ - "Iteration", - "WeightFactor", - "Weight", - "ENumer", - "EDenom", - "ETotal", - "E1Body", - "E2Body", - "EHybrid", - "Overlap", - ] - if qmc.beta is not None: - self.thermal = True - self.header.append("Nav") - else: - self.thermal = False - self.header.append("Time") - self.nreg = len(self.header[1:]) - self.dtype = dtype - self.G = numpy.zeros((2, hamiltonian.nbasis, hamiltonian.nbasis), dtype) - if self.calc_one_rdm: - dms_size = self.G.size - else: - dms_size = 0 - self.eshift = numpy.array([0, 0]) - # Abuse of language for the moment. Only accumulates S(k) for UEG. - # This works only for finite temperature so temporarily disabled - # TODO: Add functionality to accumulate 2RDM? - if self.calc_two_rdm is not None: - if self.calc_two_rdm == "structure_factor": - two_rdm_shape = ( - 2, - 2, - len(hamiltonian.qvecs), - ) - self.two_rdm = numpy.zeros(two_rdm_shape, dtype=numpy.complex128) - dms_size += self.two_rdm.size - else: - self.two_rdm = None - - self.estimates = numpy.zeros(self.nreg + dms_size, dtype=dtype) - self.names = get_estimator_enum(self.thermal) - self.estimates[self.names.time] = time.time() - self.global_estimates = numpy.zeros(self.nreg + dms_size, dtype=dtype) - self.key = { - "Iteration": "Simulation iteration. iteration*dt = tau.", - "WeightFactor": "Rescaling Factor from population control.", - "Weight": "Total walker weight.", - "E_num": "Numerator for projected energy estimator.", - "E_denom": "Denominator for projected energy estimator.", - "ETotal": "Projected energy estimator.", - "E1Body": "Mixed one-body energy estimator.", - "E2Body": "Mixed two-body energy estimator.", - "EHybrid": "Hybrid energy.", - "Overlap": "Walker average overlap.", - "Nav": "Average number of electrons.", - "Time": "Time per processor to complete one iteration.", - } - if root: - self.setup_output(filename) - - -# def update_batch( -# self, qmc, system, hamiltonian, trial, walker_batch, step, free_projection=False -# ): -# """Update mixed estimates for walkers. -# -# Parameters -# ---------- -# qmc : :class:`ipie.state.QMCOpts` object. -# Container for qmc input options. -# system : system object. -# Container for model input options. -# hamiltonian : hamiltonian object. -# Container for hamiltonian input options. -# trial : :class:`ipie.trial_wavefunction.X' object -# Trial wavefunction class. -# psi : :class:`ipie.legacy.walkers.Walkers` object -# CPMC wavefunction. -# step : int -# Current simulation step -# free_projection : bool -# True if doing free projection. -# """ -# assert free_projection == False -# assert self.thermal == False -# if is_cupy( -# walker_batch.weight -# ): # if even one array is a cupy array we should assume the rest is done with cupy -# import cupy -# -# assert cupy.is_available() -# array = cupy.array -# zeros = cupy.zeros -# sum = cupy.sum -# abs = cupy.abs -# else: -# array = numpy.array -# zeros = numpy.zeros -# sum = numpy.sum -# abs = numpy.abs -# -# # When using importance sampling we only need to know the current -# # walkers weight as well as the local energy, the walker's overlap -# # with the trial wavefunction is not needed. -# if step % self.energy_eval_freq == 0: -# greens_function(walker_batch, trial) -# if self.eval_energy: -# energy = local_energy_batch(system, hamiltonian, walker_batch, trial) -# else: -# energy = zeros(walker_batch.nwalkers, 3, dtype=numpy.complex128) -# self.estimates[self.names.enumer] += sum(walker_batch.weight * energy[:, 0].real) -# self.estimates[self.names.e1b : self.names.e2b + 1] += array( -# [ -# sum(walker_batch.weight * energy[:, 1].real), -# sum(walker_batch.weight * energy[:, 2].real), -# ] -# ) -# self.estimates[self.names.edenom] += sum(walker_batch.weight) -# -# self.estimates[self.names.uweight] += sum(walker_batch.unscaled_weight) -# self.estimates[self.names.weight] += sum(walker_batch.weight) -# self.estimates[self.names.ovlp] += sum(walker_batch.weight * abs(walker_batch.ovlp)) -# self.estimates[self.names.ehyb] += sum(walker_batch.weight * walker_batch.hybrid_energy) -# -# if self.calc_one_rdm: -# start = self.names.time + 1 -# end = self.names.time + 1 + w.G.size -# self.estimates[start:end] += w.weight * w.G.flatten().real -# if self.calc_two_rdm is not None: -# start = end -# end = end + self.two_rdm.size -# self.estimates[start:end] += w.weight * self.two_rdm.flatten().real - - - def update(self, qmc, hamiltonian, trial, psi, step, free_projection=False): - """Update mixed estimates for walkers. - - Parameters - ---------- - qmc : :class:`ipie.state.QMCOpts` object. - Container for qmc input options. - hamiltonian : hamiltonian object. - Container for hamiltonian input options. - trial : :class:`ipie.trial_wavefunction.X' object - Trial wavefunction class. - psi : :class:`ipie.legacy.walkers.Walkers` object - CPMC wavefunction. - step : int - Current simulation step - free_projection : bool - True if doing free projection. - """ - if free_projection: - for i, w in enumerate(psi.walkers): - # For T > 0 w.ot = 1 always. - wfac = w.weight * w.ot * w.phase # * numpy.exp(w.log_detR-w.log_detR_shift) - if step % self.energy_eval_freq == 0: - w.greens_function(trial) - if self.eval_energy: - if self.thermal: - E, T, V = local_energy(hamiltonian, w, trial) - else: - E, T, V = local_energy( - hamiltonian, - w, - rchol=trial._rchol, - eri=trial._eri, - ) - else: - E, T, V = 0, 0, 0 - self.estimates[self.names.enumer] += wfac * E - self.estimates[self.names.e1b : self.names.e2b + 1] += wfac * numpy.array( - [T, V] - ) - self.estimates[self.names.edenom] += wfac - if self.thermal: - nav = particle_number(one_rdm_from_G(w.G)) - self.estimates[self.names.nav] += wfac * nav - self.estimates[self.names.uweight] += w.unscaled_weight - self.estimates[self.names.weight] += wfac - self.estimates[self.names.ehyb] += wfac * w.hybrid_energy - self.estimates[self.names.ovlp] += w.weight * abs(w.ot) - else: - # When using importance sampling we only need to know the current - # walkers weight as well as the local energy, the walker's overlap - # with the trial wavefunction is not needed. - for i, w in enumerate(psi.walkers): - if self.thermal: - if self.average_gf: - E_sum = 0 - T_sum = 0 - V_sum = 0 - nav = 0 - for ts in range(w.stack_length): - w.greens_function(trial, slice_ix=ts * w.stack_size) - E, T, V = local_energy(hamiltonian, w, trial) - E_sum += E - T_sum += T - V_sum += V - nav += particle_number(one_rdm_from_G(w.G)) - self.estimates[self.names.nav] += w.weight * nav / w.stack_length - self.estimates[self.names.enumer] += w.weight * E_sum.real / w.stack_length - self.estimates[self.names.e1b : self.names.e2b + 1] += ( - w.weight * numpy.array([T_sum, V_sum]).real / w.stack_length - ) - else: - w.greens_function(trial) - E, T, V = local_energy(hamiltonian, w, trial) - nav = particle_number(one_rdm_from_G(w.G)) - self.estimates[self.names.nav] += w.weight * nav - self.estimates[self.names.enumer] += w.weight * E.real - self.estimates[self.names.e1b : self.names.e2b + 1] += ( - w.weight * numpy.array([T, V]).real - ) - self.estimates[self.names.edenom] += w.weight - else: - if step % self.energy_eval_freq == 0: - w.greens_function(trial) - if self.eval_energy: - E, T, V = local_energy(hamiltonian, w, trial) - else: - E, T, V = 0, 0, 0 - - self.estimates[self.names.enumer] += w.weight * w.le_oratio * E.real - self.estimates[self.names.e1b : self.names.e2b + 1] += ( - w.weight * w.le_oratio * numpy.array([T, V]).real - ) - self.estimates[self.names.edenom] += w.weight * w.le_oratio - - self.estimates[self.names.uweight] += w.unscaled_weight - self.estimates[self.names.weight] += w.weight - self.estimates[self.names.ovlp] += w.weight * abs(w.ot) - self.estimates[self.names.ehyb] += w.weight * w.hybrid_energy - if self.calc_one_rdm: - start = self.names.time + 1 - end = self.names.time + 1 + w.G.size - self.estimates[start:end] += w.weight * w.G.flatten().real - if self.calc_two_rdm is not None: - start = end - end = end + self.two_rdm.size - self.estimates[start:end] += w.weight * self.two_rdm.flatten().real - - def print_step(self, comm, nprocs, step, nsteps=None, free_projection=False): - """Print mixed estimates to file. - - This reduces estimates arrays over processors. On return estimates - arrays are zerod. - - Parameters - ---------- - comm : - MPI communicator. - nprocs : int - Number of processors. - step : int - Current iteration number. - nmeasure : int - Number of steps between measurements. - """ - if is_cupy( - self.estimates - ): # if even one array is a cupy array we should assume the rest is done with cupy - import cupy - - assert cupy.is_available() - array = cupy.asnumpy - else: - array = numpy.array - - if step % self.nsteps != 0: - return - if nsteps is None: - nsteps = self.nsteps - es = array(self.estimates) - ns = self.names - es[ns.time] = (time.time() - es[ns.time]) / nprocs - es[ns.uweight : ns.weight + 1] /= nsteps - es[ns.ehyb : ns.time + 1] /= nsteps - comm.Reduce(es, self.global_estimates, op=mpi_sum) - gs = self.global_estimates - if comm.rank == 0: - gs[ns.eproj] = gs[ns.enumer] - gs[ns.eproj : ns.e2b + 1] = gs[ns.eproj : ns.e2b + 1] / gs[ns.edenom] - gs[ns.ehyb] /= gs[ns.weight] - gs[ns.ovlp] /= gs[ns.weight] - eshift = numpy.array([gs[ns.ehyb], gs[ns.eproj]]) - else: - eshift = numpy.array([0, 0]) - if self.thermal and comm.rank == 0: - gs[ns.nav] = gs[ns.nav] / gs[ns.weight] - eshift = comm.bcast(eshift, root=0) - self.eshift = eshift - if comm.rank == 0: - if self.verbose: - print(format_fixed_width_floats([step] + list(gs[: ns.time + 1].real))) - self.output.push([step] + list(gs[: ns.time + 1]), "energies") - if self.calc_one_rdm: - start = self.nreg - end = self.nreg + self.G.size - rdm = gs[start:end].reshape(self.G.shape) / nsteps - self.output.push(rdm / gs[ns.weight], "one_rdm") - if self.calc_two_rdm: - start = self.nreg + self.G.size - rdm = gs[start:].reshape(self.two_rdm.shape) / nsteps - self.output.push(rdm / gs[ns.weight], "two_rdm") - self.output.increment() - self.zero() - - def print_key(self, eol="", encode=False): - """Print out information about what the estimates are. - - Parameters - ---------- - eol : string, optional - String to append to output, e.g., Default : ''. - encode : bool - In True encode output to be utf-8. - """ - header = ( - eol - + "# Explanation of output column headers:\n" - + "# -------------------------------------" - + eol - ) - if encode: - header = header.encode("utf-8") - print(header) - for k, v in self.key.items(): - s = f"# {k} : {v}" + eol - if encode: - s = s.encode("utf-8") - print(s) - - def print_header(self, eol="", encode=False): - r"""Print out header for estimators - - Parameters - ---------- - eol : string, optional - String to append to output, Default : ''. - encode : bool - In True encode output to be utf-8. - - Returns - ------- - None - """ - s = format_fixed_width_strings(self.header) + eol - if encode: - s = s.encode("utf-8") - print(s) - - def get_shift(self, hybrid=True): - """get hybrid shift. - - parameters - ---------- - hybrid : bool - true if using hybrid propgation - returns - ------- - eshift : float - walker averaged hybrid energy. - """ - if hybrid: - return self.eshift[0].real - else: - return self.eshift[1].real - - def zero(self): - """Zero (in the appropriate sense) various estimator arrays.""" - self.estimates[:] = 0 - self.global_estimates[:] = 0 - self.estimates[self.names.time] = time.time() - - def setup_output(self, filename): - with h5py.File(filename, "a") as fh5: - fh5["basic/headers"] = numpy.array(self.header).astype("S") - self.output = H5EstimatorHelper(filename, "basic") - - -def get_estimator_enum(thermal=False): - keys = [ - "uweight", - "weight", - "enumer", - "edenom", - "eproj", - "e1b", - "e2b", - "ehyb", - "ovlp", - ] - if thermal: - keys.append("nav") - keys.append("time") - enum = {} - for v, k in enumerate(keys): - enum[k] = v - return dotdict(enum) - - diff --git a/ipie/thermal/estimators/ueg.py b/ipie/thermal/estimators/ueg.py deleted file mode 100644 index 9906fc9d..00000000 --- a/ipie/thermal/estimators/ueg.py +++ /dev/null @@ -1,290 +0,0 @@ - -import numpy - -from ipie.thermal.estimators.ueg_kernels import ( - build_J_opt, - build_K_opt, - coulomb_greens_function_per_qvec, - exchange_greens_function_per_qvec, -) - - -def exchange_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gprod, G): - for iq in range(nq): - for idxkpq, i in zip(kpq[iq], kpq_i[iq]): - for idxpmq, j in zip(pmq[iq], pmq_i[iq]): - Gprod[iq] += G[j, idxkpq] * G[i, idxpmq] - - -def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): - for iq in range(nq): - for idxkpq, i in zip(kpq[iq], kpq_i[iq]): - Gkpq[iq] += G[i, idxkpq] - for idxpmq, i in zip(pmq[iq], pmq_i[iq]): - Gpmq[iq] += G[i, idxpmq] - - -def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None): - """Local energy computation for uniform electron gas - Parameters - ---------- - system : - system class - ham : - hamiltonian class - G : - Green's function - Returns - ------- - etot : float - total energy - ke : float - kinetic energy - pe : float - potential energy - """ - if ham.diagH1: - ke = numpy.einsum("sii,sii->", ham.H1, G) - else: - ke = numpy.einsum("sij,sij->", ham.H1, G) - - Gkpq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - Gpmq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - Gprod = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - - ne = [system.nup, system.ndown] - nq = numpy.shape(ham.qvecs)[0] - - for s in [0, 1]: - # exchange_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i,ham.ipmq_pmq, Gprod[s],G[s]) - # coulomb_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i, ham.ipmq_pmq,Gkpq[s], Gpmq[s],G[s]) - for iq in range(nq): - Gkpq[s, iq], Gpmq[s, iq] = coulomb_greens_function_per_qvec( - ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] - ) - Gprod[s, iq] = exchange_greens_function_per_qvec( - ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] - ) - - if two_rdm is None: - two_rdm = numpy.zeros((2, 2, len(ham.qvecs)), dtype=numpy.complex128) - two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] - essa = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 0]) - - two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] - essb = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[1, 1]) - - two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) - two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) - eos = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 1]) + ( - 1.0 / (2.0 * ham.vol) - ) * ham.vqvec.dot(two_rdm[1, 0]) - - pe = essa + essb + eos - - return (ke + pe, ke, pe) - - -# JHLFML -def build_J(system, Gpmq, Gkpq): - J = [ - numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), - numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), - ] - - for iq, q in enumerate(system.qvecs): - for idxi, i in enumerate(system.basis): - for idxj, j in enumerate(system.basis): - jpq = j + q - idxjpq = system.lookup_basis(jpq) - if (idxjpq is not None) and (idxjpq == idxi): - J[0][idxj, idxi] += ( - (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - ) - - for iq, q in enumerate(system.qvecs): - for idxi, i in enumerate(system.basis): - for idxj, j in enumerate(system.basis): - jpq = j - q - idxjmq = system.lookup_basis(jpq) - if (idxjmq is not None) and (idxjmq == idxi): - J[0][idxj, idxi] += ( - (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - ) - - J[1] = J[0] - - return J - - -def build_K(system, G): - K = numpy.zeros((2, system.nbasis, system.nbasis), dtype=numpy.complex128) - for s in [0, 1]: - for iq in range(len(system.vqvec)): - for idxjmq, idxj in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): - for idxkpq, idxk in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): - K[s, idxj, idxkpq] += ( - -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjmq, idxk] - ) - for iq in range(len(system.vqvec)): - for idxjpq, idxj in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): - for idxpmq, idxp in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): - K[s, idxj, idxpmq] += ( - -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjpq, idxp] - ) - return K - - -def fock_ueg(ham, G): - """Fock matrix computation for uniform electron gas - - Parameters - ---------- - ham : :class`ipie.legacy.hamiltonians.ueg` - UEG hamiltonian class. - G : :class:`numpy.ndarray` - Green's function. - Returns - ------- - F : :class:`numpy.ndarray` - Fock matrix (2, nbasis, nbasis). - """ - nbsf = ham.nbasis - nq = len(ham.qvecs) - assert nq == len(ham.vqvec) - - Fock = numpy.zeros((2, nbsf, nbsf), dtype=numpy.complex128) - Gkpq = numpy.zeros((2, nq), dtype=numpy.complex128) - Gpmq = numpy.zeros((2, nq), dtype=numpy.complex128) - - for s in [0, 1]: - coulomb_greens_function( - nq, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - Gkpq[s], - Gpmq[s], - G[s], - ) - - J = build_J_opt( - nq, - ham.vqvec, - ham.vol, - ham.nbasis, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - Gkpq, - Gpmq, - ) - - K = build_K_opt( - nq, - ham.vqvec, - ham.vol, - ham.nbasis, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - G, - ) - - for s in [0, 1]: - Fock[s] = ham.H1[s] + J[s] + K[s] - - return Fock - - -def unit_test(): - import numpy as np - - from ipie.legacy.systems.ueg import UEG - - inputs = {"nup": 7, "ndown": 7, "rs": 1.0, "ecut": 2.0} - system = UEG(inputs, True) - nbsf = system.nbasis - Pa = np.zeros([nbsf, nbsf], dtype=np.complex128) - Pb = np.zeros([nbsf, nbsf], dtype=np.complex128) - na = system.nup - nb = system.ndown - for i in range(na): - Pa[i, i] = 1.0 - for i in range(nb): - Pb[i, i] = 1.0 - P = np.array([Pa, Pb]) - etot, ekin, epot = local_energy_ueg(system, G=P) - print(f"ERHF = {etot}, {ekin}, {epot}") - - from ipie.legacy.estimators.greens_function import gab - from ipie.utils.linalg import exponentiate_matrix, reortho - - # numpy.random.seed() - rCa = numpy.random.randn(nbsf, na) - zCa = numpy.random.randn(nbsf, na) - rCb = numpy.random.randn(nbsf, nb) - zCb = numpy.random.randn(nbsf, nb) - - Ca = rCa + 1j * zCa - Cb = rCb + 1j * zCb - - Ca, detR = reortho(Ca) - Cb, detR = reortho(Cb) - # S = print(Ca.dot(Cb.T)) - # print(S) - # exit() - Ca = numpy.array(Ca, dtype=numpy.complex128) - Cb = numpy.array(Cb, dtype=numpy.complex128) - P = [gab(Ca, Ca), gab(Cb, Cb)] - # diff = P[0] - P[1] - # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) - - # solver = lib.diis.DIIS() - - # dt = 0.1 - # for i in range(100): - # # Compute Fock matrix - # Fock = fock_ueg(system, G=P) - # # Compute DIIS Errvec - # PFmFPa = P[0].dot(Fock[0]) - Fock[0].dot(P[0]) - # PFmFPb = P[1].dot(Fock[1]) - Fock[1].dot(P[1]) - # errvec = numpy.append(numpy.reshape(PFmFPa, nbsf*nbsf),numpy.reshape(PFmFPb, nbsf*nbsf)) - # RMS = np.sqrt(np.dot(errvec, errvec)) - # print ("{} {} {}".format(i,numpy.real(local_energy_ueg(system, P)), numpy.real(RMS))) - # # Form Fockvec - # Fock[0] = numpy.array(Fock[0]) - # Fock[1] = numpy.array(Fock[1]) - # Fockvec = numpy.append(numpy.reshape(Fock[0],nbsf*nbsf), numpy.reshape(Fock[1],nbsf*nbsf)) - # # Extrapolate Fockvec - # # Fockvec = solver.update(Fockvec, xerr=errvec) - - # # Apply Propagator - # Fock = numpy.reshape(Fockvec, (2, nbsf, nbsf)) - # ea, Ca = numpy.linalg.eig(Fock[0]) - # eb, Cb = numpy.linalg.eig(Fock[1]) - # sort_perm = ea.argsort() - # ea.sort() - # Ca = Ca[:, sort_perm] - # sort_perm = eb.argsort() - # eb.sort() - # Cb = Cb[:, sort_perm] - - # Ca = Ca[:,:na] - # Cb = Cb[:,:nb] - # Ca, detR = reortho(Ca) - # Cb, detR = reortho(Cb) - - # P = [gab(Ca, Ca), gab(Cb, Cb)] - # # expF = [exponentiate_matrix(-dt*Fock[0]), exponentiate_matrix(-dt*Fock[1])] - # # Ca = expF[0].dot(Ca) - # # Cb = expF[1].dot(Cb) - # # diff = P[0] - P[1] - # # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) - - -if __name__ == "__main__": - unit_test() diff --git a/ipie/thermal/estimators/ueg_kernels.pyx b/ipie/thermal/estimators/ueg_kernels.pyx deleted file mode 100644 index 9c7a25de..00000000 --- a/ipie/thermal/estimators/ueg_kernels.pyx +++ /dev/null @@ -1,169 +0,0 @@ -import numpy - -cimport numpy - -import itertools -import math - -from ipie.thermal.estimators.utils import convolve - -DTYPE_CX = numpy.complex128 -DTYPE = numpy.float64 - - -def vq(numpy.ndarray q): - assert(q.shape[0] == 3) - cdef double q2 = numpy.dot(q, q) - if (q2 < 1e-10): - return 0.0 - else: - return 4*math.pi / q2 - -def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): - """ Add a diagonal term of two-body Hamiltonian to the one-body term - Parameters - ---------- - T : float - one-body Hamiltonian (i.e. kinetic energy) - Returns - ------- - h1e_mod: float - modified one-body Hamiltonian - """ - - cdef size_t nbsf = basis.shape[0] - cdef numpy.ndarray h1e_mod = T.copy() - cdef double fac = 1.0 / (2.0 * vol) - - for (i, ki) in enumerate(basis): - for (j, kj) in enumerate(basis): - if i != j: - q = kfac * (ki - kj) - h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) - return h1e_mod - -def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): - - cdef int nq = kpq_i.shape[0] - - cdef int idxkpq, idxpmq, i, j, iq - - cdef double complex Gkpq = 0.0 - cdef double complex Gpmq = 0.0 - - for (idxkpq,i) in zip(kpq,kpq_i): - Gkpq += G[i,idxkpq] - for (idxpmq,i) in zip(pmq,pmq_i): - Gpmq += G[i,idxpmq] - - return Gkpq, Gpmq - -def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): - - cdef int nkpq = kpq_i.shape[0] - cdef int npmq = pmq_i.shape[0] - - cdef double complex Gprod = 0.0 - - cdef int idxkpq, idxpmq, i, j - - for inkpq in range(nkpq): - idxkpq = kpq[inkpq] - i = kpq_i[inkpq] - for jnpmq in range(npmq): - idxpmq = pmq[jnpmq] - j = pmq_i[jnpmq] - Gprod += G[j,idxkpq]*G[i,idxpmq] - - return Gprod - -def exchange_greens_function_fft (long nocc, long nbsf, - long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, - double complex[:,:] CTdagger, double complex[:,:] Ghalf): - - assert (mesh.shape[0] == 3) - assert (qmesh.shape[0] == 3) - assert (Ghalf.shape[0] == nocc) - assert (Ghalf.shape[1] == nbsf) - assert (CTdagger.shape[0] == nocc) - assert (CTdagger.shape[1] == nbsf) - - cdef long ngrid = numpy.prod(mesh) - cdef long nqgrid = numpy.prod(qmesh) - - cdef long nq = qmap.shape[0] - cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) - - cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) - cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) - - for i in range(nocc): - for j in range(nocc): - Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) - CTdagger_j = numpy.asarray(CTdagger[j,:]) - - Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - Gh_i_cube[gmap] = Gh_i - CTdagger_j_cube[gmap] = CTdagger_j - - lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] - - Gh_j = numpy.asarray(Ghalf[j,:]) - CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) - - Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - Gh_j_cube[gmap] = Gh_j - CTdagger_i_cube[gmap] = CTdagger_i - - lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] - - Gprod += lQ_ji*lQ_ij - - return Gprod - -def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, - list kpq, list pmq_i, list pmq, - double complex[:,:] Gkpq, double complex[:,:] Gpmq): - - cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) - cdef int i, j - for iq in range(nq): - for i, j in zip(pmq_i[iq], pmq[iq]): - J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - for i, j in zip(kpq_i[iq], kpq[iq]): - J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - - J[1] = J[0] - - return J - -def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, - list kpq, list pmq_i, list pmq, - double complex[:,:,:] G): - - cdef numpy.ndarray K = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) - cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp - - for s in range(2): - for iq in range(nq): - for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): - for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): - K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] - return K diff --git a/ipie/thermal/estimators/utils.py b/ipie/thermal/estimators/utils.py deleted file mode 100644 index 8665fe0b..00000000 --- a/ipie/thermal/estimators/utils.py +++ /dev/null @@ -1,318 +0,0 @@ - -try: - import pyfftw -except ImportError: - pass -import numpy -import scipy - -try: - from scipy.fft._helper import _init_nd_shape_and_axes, next_fast_len -except ModuleNotFoundError: - pass - - -# Stolen from scipy -def scipy_fftconvolve(in1, in2, mesh1=None, mesh2=None, mode="full", axes=None): - """Convolve two N-dimensional arrays using FFT. - Convolve `in1` and `in2` using the fast Fourier transform method, with - the output size determined by the `mode` argument. - This is generally much faster than `convolve` for large arrays (n > ~500), - but can be slower when only a few output values are needed, and can only - output float arrays (int or object array inputs will be cast to float). - As of v0.19, `convolve` automatically chooses this method or the direct - method based on an estimation of which is faster. - Parameters - ---------- - in1 : array_like - First input. - in2 : array_like - Second input. Should have the same number of dimensions as `in1`. - mode : str {'full', 'valid', 'same'}, optional - A string indicating the size of the output: - ``full`` - The output is the full discrete linear convolution - of the inputs. (Default) - ``valid`` - The output consists only of those elements that do not - rely on the zero-padding. In 'valid' mode, either `in1` or `in2` - must be at least as large as the other in every dimension. - ``same`` - The output is the same size as `in1`, centered - with respect to the 'full' output. - axis : tuple, optional - axes : int or array_like of ints or None, optional - Axes over which to compute the convolution. - The default is over all axes. - Returns - ------- - out : array - An N-dimensional array containing a subset of the discrete linear - convolution of `in1` with `in2`. - """ - - if not mesh1 == None: - in1 = in1.reshape(mesh1) - if not mesh2 == None: - in2 = in2.reshape(mesh2) - - in1 = numpy.asarray(in1) - in2 = numpy.asarray(in2) - noaxes = axes is None - - if in1.ndim == in2.ndim == 0: # scalar inputs - return in1 * in2 - elif in1.ndim != in2.ndim: - raise ValueError("in1 and in2 should have the same dimensionality") - elif in1.size == 0 or in2.size == 0: # empty arrays - return numpy.array([]) - - _, axes = _init_nd_shape_and_axes_sorted(in1, shape=None, axes=axes) - - if not noaxes and not axes.size: - raise ValueError("when provided, axes cannot be empty") - - if noaxes: - other_axes = numpy.array([], dtype=numpy.intc) - else: - other_axes = numpy.setdiff1d(numpy.arange(in1.ndim), axes) - - s1 = numpy.array(in1.shape) - s2 = numpy.array(in2.shape) - - if not numpy.all( - (s1[other_axes] == s2[other_axes]) | (s1[other_axes] == 1) | (s2[other_axes] == 1) - ): - raise ValueError(f"incompatible shapes for in1 and in2: {in1.shape} and {in2.shape}") - - complex_result = numpy.issubdtype(in1.dtype, numpy.complexfloating) or numpy.issubdtype( - in2.dtype, numpy.complexfloating - ) - shape = numpy.maximum(s1, s2) - shape[axes] = s1[axes] + s2[axes] - 1 - - # Check that input sizes are compatible with 'valid' mode - if scipy.signal.signaltools._inputs_swap_needed(mode, s1, s2): - # Convolution is commutative; order doesn't have any effect on output - in1, s1, in2, s2 = in2, s2, in1, s1 - - # Speed up FFT by padding to optimal size for FFTPACK - fshape = [next_fast_len(d) for d in shape[axes]] - fslice = tuple([slice(sz) for sz in shape]) - - # Pre-1.9 NumPy FFT routines are not threadsafe. For older NumPys, make - # sure we only call rfftn/irfftn from one thread at a time. - - # If we're here, it's either because we need a complex result, or we - # failed to acquire _rfft_lock (meaning rfftn isn't threadsafe and - # is already in use by another thread). In either case, use the - # (threadsafe but slower) SciPy complex-FFT routines instead. - sp1 = numpy.fft.fftn(in1, fshape, axes=axes) - sp2 = numpy.fft.fftn(in2, fshape, axes=axes) - ret = numpy.fft.ifftn(sp1 * sp2, axes=axes)[fslice].copy() - - if not complex_result: - ret = ret.real - - if mode == "full": - return ret - elif mode == "same": - return scipy.signal.signaltools._centered(ret, s1) - elif mode == "valid": - shape_valid = shape.copy() - shape_valid[axes] = s1[axes] - s2[axes] + 1 - return scipy.signal.signaltools._centered(ret, shape_valid) - else: - raise ValueError("acceptable mode flags are 'valid'," " 'same', or 'full'") - - -def convolve(f, g, mesh, backend=numpy.fft): - f_ = f.reshape(*mesh) - g_ = g.reshape(*mesh) - shape = numpy.maximum(f_.shape, g_.shape) - min_shape = numpy.array(f_.shape) + numpy.array(g_.shape) - 1 - - nqtot = numpy.prod(min_shape) - fshape = [next_fast_len(d) for d in min_shape] - - finv = backend.ifftn(f_, s=fshape) - ginv = backend.ifftn(g_, s=fshape) - fginv = finv * ginv - fq = backend.fftn(fginv).copy().ravel() - fq = fq.reshape(fshape) - fq = fq[: min_shape[0], : min_shape[1], : min_shape[2]] - fq = fq.reshape(nqtot) * numpy.prod(fshape) - return fq - - -# Stolen from scipy -def scipy_fftconvolve(in1, in2, mesh1=None, mesh2=None, mode="full", axes=None): - """Convolve two N-dimensional arrays using FFT. - Convolve `in1` and `in2` using the fast Fourier transform method, with - the output size determined by the `mode` argument. - This is generally much faster than `convolve` for large arrays (n > ~500), - but can be slower when only a few output values are needed, and can only - output float arrays (int or object array inputs will be cast to float). - As of v0.19, `convolve` automatically chooses this method or the direct - method based on an estimation of which is faster. - Parameters - ---------- - in1 : array_like - First input. - in2 : array_like - Second input. Should have the same number of dimensions as `in1`. - mode : str {'full', 'valid', 'same'}, optional - A string indicating the size of the output: - ``full`` - The output is the full discrete linear convolution - of the inputs. (Default) - ``valid`` - The output consists only of those elements that do not - rely on the zero-padding. In 'valid' mode, either `in1` or `in2` - must be at least as large as the other in every dimension. - ``same`` - The output is the same size as `in1`, centered - with respect to the 'full' output. - axis : tuple, optional - axes : int or array_like of ints or None, optional - Axes over which to compute the convolution. - The default is over all axes. - Returns - ------- - out : array - An N-dimensional array containing a subset of the discrete linear - convolution of `in1` with `in2`. - """ - - if not mesh1 == None: - in1 = in1.reshape(mesh1) - if not mesh2 == None: - in2 = in2.reshape(mesh2) - - in1 = numpy.asarray(in1) - in2 = numpy.asarray(in2) - noaxes = axes is None - - if in1.ndim == in2.ndim == 0: # scalar inputs - return in1 * in2 - elif in1.ndim != in2.ndim: - raise ValueError("in1 and in2 should have the same dimensionality") - elif in1.size == 0 or in2.size == 0: # empty arrays - return numpy.array([]) - - _, axes = _init_nd_shape_and_axes_sorted(in1, shape=None, axes=axes) - - if not noaxes and not axes.size: - raise ValueError("when provided, axes cannot be empty") - - if noaxes: - other_axes = numpy.array([], dtype=numpy.intc) - else: - other_axes = numpy.setdiff1d(numpy.arange(in1.ndim), axes) - - s1 = numpy.array(in1.shape) - s2 = numpy.array(in2.shape) - - if not numpy.all( - (s1[other_axes] == s2[other_axes]) | (s1[other_axes] == 1) | (s2[other_axes] == 1) - ): - raise ValueError(f"incompatible shapes for in1 and in2: {in1.shape} and {in2.shape}") - - complex_result = numpy.issubdtype(in1.dtype, numpy.complexfloating) or numpy.issubdtype( - in2.dtype, numpy.complexfloating - ) - shape = numpy.maximum(s1, s2) - shape[axes] = s1[axes] + s2[axes] - 1 - - # Check that input sizes are compatible with 'valid' mode - if scipy.signal.signaltools._inputs_swap_needed(mode, s1, s2): - # Convolution is commutative; order doesn't have any effect on output - in1, s1, in2, s2 = in2, s2, in1, s1 - - # Speed up FFT by padding to optimal size for FFTPACK - fshape = [next_fast_len(d) for d in shape[axes]] - fslice = tuple([slice(sz) for sz in shape]) - - # Pre-1.9 NumPy FFT routines are not threadsafe. For older NumPys, make - # sure we only call rfftn/irfftn from one thread at a time. - - # If we're here, it's either because we need a complex result, or we - # failed to acquire _rfft_lock (meaning rfftn isn't threadsafe and - # is already in use by another thread). In either case, use the - # (threadsafe but slower) SciPy complex-FFT routines instead. - sp1 = numpy.fft.fftn(in1, fshape, axes=axes) - sp2 = numpy.fft.fftn(in2, fshape, axes=axes) - ret = numpy.fft.ifftn(sp1 * sp2, axes=axes)[fslice].copy() - - if not complex_result: - ret = ret.real - - if mode == "full": - return ret - elif mode == "same": - return scipy.signal.signaltools._centered(ret, s1) - elif mode == "valid": - shape_valid = shape.copy() - shape_valid[axes] = s1[axes] - s2[axes] + 1 - return scipy.signal.signaltools._centered(ret, shape_valid) - else: - raise ValueError("acceptable mode flags are 'valid'," " 'same', or 'full'") - - -def convolve(f, g, mesh, backend=numpy.fft): - f_ = f.reshape(*mesh) - g_ = g.reshape(*mesh) - shape = numpy.maximum(f_.shape, g_.shape) - min_shape = numpy.array(f_.shape) + numpy.array(g_.shape) - 1 - - nqtot = numpy.prod(min_shape) - fshape = [next_fast_len(d) for d in min_shape] - - finv = backend.ifftn(f_, s=fshape) - ginv = backend.ifftn(g_, s=fshape) - fginv = finv * ginv - fq = backend.fftn(fginv).copy().ravel() - fq = fq.reshape(fshape) - fq = fq[: min_shape[0], : min_shape[1], : min_shape[2]] - fq = fq.reshape(nqtot) * numpy.prod(fshape) - return fq - - -def _init_nd_shape_and_axes_sorted(x, shape, axes): - """Handle and sort shape and axes arguments for n-dimensional transforms. - - This is identical to `_init_nd_shape_and_axes`, except the axes are - returned in sorted order and the shape is reordered to match. - - Parameters - ---------- - x : array_like - The input array. - shape : int or array_like of ints or None - The shape of the result. If both `shape` and `axes` (see below) are - None, `shape` is ``x.shape``; if `shape` is None but `axes` is - not None, then `shape` is ``scipy.take(x.shape, axes, axis=0)``. - If `shape` is -1, the size of the corresponding dimension of `x` is - used. - axes : int or array_like of ints or None - Axes along which the calculation is computed. - The default is over all axes. - Negative indices are automatically converted to their positive - counterpart. - - Returns - ------- - shape : array - The shape of the result. It is a 1D integer array. - axes : array - The shape of the result. It is a 1D integer array. - - """ - noaxes = axes is None - shape, axes = _init_nd_shape_and_axes(x, shape, axes) - - if not noaxes: - shape = shape[axes.argsort()] - axes.sort() - - return shape, axes diff --git a/ipie/thermal/propagation/tests/test_generic.py b/ipie/thermal/propagation/tests/test_generic_propagation.py similarity index 100% rename from ipie/thermal/propagation/tests/test_generic.py rename to ipie/thermal/propagation/tests/test_generic_propagation.py index da29ca7d..a6e75e79 100644 --- a/ipie/thermal/propagation/tests/test_generic.py +++ b/ipie/thermal/propagation/tests/test_generic_propagation.py @@ -44,7 +44,6 @@ def setup_objs(mf_trial=False, seed=None): beta = 0.02 dt = 0.01 nwalkers = 2 - numpy.random.seed(seed) blocks = 10 stabilise_freq = 10 pop_control_freq = 1 @@ -55,6 +54,7 @@ def setup_objs(mf_trial=False, seed=None): complex_integrals = False sym = 8 if complex_integrals: sym = 4 + numpy.random.seed(seed) options = { "qmc": { diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py b/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py index 6734b637..3c63b8d0 100644 --- a/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py +++ b/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py @@ -26,11 +26,11 @@ def setup_objs(seed=None): mu = -10. nwalkers = 1 - numpy.random.seed(seed) nblocks = 10 nsteps_per_block = 1 timestep = 0.005 verbose = True + numpy.random.seed(seed) options = { "qmc": { @@ -43,7 +43,7 @@ def setup_objs(seed=None): }, "hamiltonian": { - "name": "Generic", + "name": "UEG", "_alt_convention": False, "sparse": False, "mu": mu diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg.py b/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py similarity index 99% rename from ipie/thermal/propagation/tests/ueg/test_ueg.py rename to ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py index 59ddc739..c7e8c4ee 100644 --- a/ipie/thermal/propagation/tests/ueg/test_ueg.py +++ b/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py @@ -8,7 +8,6 @@ from ipie.systems.generic import Generic from ipie.utils.testing import generate_hamiltonian from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.hamiltonians.utils import get_hamiltonian from ipie.thermal.trial.one_body import OneBody from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric @@ -47,7 +46,6 @@ def setup_objs(seed=None): beta = 0.01 timestep = 0.002 nwalkers = 1 - numpy.random.seed(seed) nblocks = 10 stabilise_freq = 10 pop_control_freq = 1 @@ -55,6 +53,7 @@ def setup_objs(seed=None): lowrank = False verbose = True + numpy.random.seed(seed) options = { "qmc": { @@ -78,7 +77,7 @@ def setup_objs(seed=None): }, "hamiltonian": { - "name": "Generic", + "name": "UEG", "_alt_convention": False, "sparse": False, "mu": mu diff --git a/ipie/thermal/qmc/options.py b/ipie/thermal/qmc/options.py index 4d9585eb..dd5c2d1d 100644 --- a/ipie/thermal/qmc/options.py +++ b/ipie/thermal/qmc/options.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from typing import Optional +from typing import ClassVar from ipie.qmc.options import QMCParams @@ -23,15 +23,18 @@ class ThermalQMCParams(QMCParams): rng_seed: The random number seed. If run in parallel the seeds on other cores / threads are determined from this. """ + # Due to structure of FT algorithm, `num_steps_per_block` is fixed at 1. + # Overide whatever input for backward compatibility. + num_steps_per_block: ClassVar[float] = 1 + beta: float = _no_default + pop_control_method: str = 'pair_branch' + # This is a hack to get around the error: # # TypeError: non-default argument 'beta' follows default argument # # due to inheritance from the QMCParams dataclass which has default attributes. # Ref: https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses - beta: float = _no_default - pop_control_method: str = 'pair_branch' - def __post_init__(self): if self.beta is _no_default: raise TypeError("__init__ missing 1 required argument: 'beta'") diff --git a/ipie/thermal/qmc/tests/run_legacy.py b/ipie/thermal/qmc/tests/run_legacy.py new file mode 100644 index 00000000..b2345635 --- /dev/null +++ b/ipie/thermal/qmc/tests/run_legacy.py @@ -0,0 +1,267 @@ +import json +import os +import sys +import tempfile +import h5py +import uuid +import pytest +import numpy +from typing import Tuple, Union + +from pyscf import gto, scf, lo +from ipie.config import MPI +from ipie.systems.generic import Generic +from ipie.hamiltonians.utils import get_hamiltonian +from ipie.qmc.options import QMCOpts + +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.qmc.options import ThermalQMCParams +from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC +from ipie.thermal.estimators.energy import local_energy +from ipie.analysis.extraction import ( + extract_test_data_hdf5, + extract_data, + extract_observable, + extract_mixed_estimates) + +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.thermal import ThermalWalker +from ipie.legacy.thermal_propagation.continuous import Continuous +from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G +from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 + +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) + +else: + test_id = None + +test_id = comm.bcast(test_id, root=0) + + +def build_legacy_driver_instance(nelec: Tuple[int, int], + hamiltonian, + options: Union[dict, None] = None, + seed: Union[int, None] = None, + verbose: bool = False): + if seed is not None: + numpy.random.seed(seed) + + # Unpack options + nup, ndown = nelec + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + + legacy_options = { + "qmc": { + "dt": timestep, + "nwalkers": nwalkers, + "blocks": nblocks, + "nsteps": nsteps_per_block, + "beta": beta, + "rng_seed": seed, + "pop_control_freq": pop_control_freq, + "stabilise_freq": stabilize_freq, + "batched": False + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank, + "pop_control": pop_control_method + }, + + "system": { + "name": "Generic", + "nup": nup, + "ndown": ndown, + "mu": mu + }, + + "hamiltonian": options["hamiltonian"], + "estimators": options["estimators"] + } + + legacy_system = Generic(nelec) + legacy_system.mu = mu + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore, + options=legacy_options["hamiltonian"]) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep) + + legacy_walkers = [ + ThermalWalker( + legacy_system, legacy_hamiltonian, legacy_trial, + walker_opts=options, verbose=i == 0) for i in range(nwalkers)] + + #legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( + # (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose) + return afqmc + + +def build_driver_test_instance(nelec: Tuple[int, int], + options: Union[dict, None] = None, + seed: Union[int, None] = None, + debug: bool = False, + verbose: bool = False): + if seed is not None: + numpy.random.seed(seed) + + # Unpack options + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + + params = ThermalQMCParams( + num_walkers=nwalkers, + total_num_walkers=nwalkers * comm.size, + num_blocks=nblocks, + num_steps_per_block=nsteps_per_block, + timestep=timestep, + beta=beta, + num_stblz=stabilize_freq, + pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, + rng_seed=seed) + + system = Generic(nelec) + hamiltonian = get_hamiltonian(system, options["hamiltonian"]) + trial = MeanField(hamiltonian, nelec, beta, timestep) + + nbasis = trial.dmat.shape[-1] + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank) + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank) + propagator.build(hamiltonian, trial=trial, walkers=walkers) + + eloc = local_energy(hamiltonian, walkers) + print(f'# Initial energy = {eloc[0]}') + + afqmc = ThermalAFQMC(system, hamiltonian, trial, walkers, propagator, + params, debug=debug, verbose=verbose) + return afqmc, hamiltonian, walkers + + +def run_legacy(): + ref_path = "reference_data/generic/" + + # Thermal AFQMC params. + nocca = 5 + noccb = 5 + nelec = (nocca, noccb) + + mu = -10.0 + beta = 0.1 + timestep = 0.01 + nwalkers = 9 + seed = 7 + nsteps_per_block = 10 + nblocks = 10 + stabilize_freq = 10 + pop_control_freq = 1 + pop_control_method = 'comb' + lowrank = False + verbose = True + debug = True + + with tempfile.NamedTemporaryFile() as tmpf: + options = { + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': 7, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + + "hamiltonian": { + "name": "Generic", + "integrals": ref_path + "generic_integrals.h5", + "_alt_convention": False, + "symmetry": False, + "sparse": False, + "mu": mu + }, + + "estimators": { + "filename": tmpf.name, + } + } + + # --------------------------------------------------------------------- + # Test. + # --------------------------------------------------------------------- + afqmc, hamiltonian, walkers = build_driver_test_instance(nelec, options, seed, debug, verbose) + + # --------------------------------------------------------------------- + # Legacy. + # --------------------------------------------------------------------- + print('\n------------------------------') + print('Running Legacy ThermalAFQMC...') + print('------------------------------') + legacy_afqmc = build_legacy_driver_instance(nelec, hamiltonian, options, seed, verbose) + legacy_afqmc.run(comm=comm) + legacy_afqmc.finalise(verbose=False) + legacy_afqmc.estimators.estimators["mixed"].update( + legacy_afqmc.qmc, + legacy_afqmc.system, + legacy_afqmc.hamiltonian, + legacy_afqmc.trial, + legacy_afqmc.walk, + 0, + legacy_afqmc.propagators.free_projection) + legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) + + enum = legacy_afqmc.estimators.estimators["mixed"].names + legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] + legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] + + if verbose: + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') + + + +if __name__ == '__main__': + run_legacy() + diff --git a/ipie/thermal/qmc/tests/test_generic.py b/ipie/thermal/qmc/tests/test_generic.py new file mode 100644 index 00000000..77b4fddd --- /dev/null +++ b/ipie/thermal/qmc/tests/test_generic.py @@ -0,0 +1,307 @@ +import json +import tempfile +import h5py +import uuid +import pytest +import numpy +from typing import Union + +from ipie.config import MPI +from ipie.utils.testing import generate_hamiltonian +from ipie.systems.generic import Generic +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.qmc.options import QMCOpts + +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.qmc.options import ThermalQMCParams +from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC +from ipie.thermal.estimators.energy import local_energy +from ipie.analysis.extraction import ( + extract_test_data_hdf5, + extract_data, + extract_observable, + extract_mixed_estimates) + +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.thermal import ThermalWalker +from ipie.legacy.thermal_propagation.continuous import Continuous +from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G +from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC + + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 + +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) + +else: + test_id = None + +test_id = comm.bcast(test_id, root=0) + + +def build_driver_test_instance(options: Union[dict, None], + seed: Union[int, None], + debug: bool = False, + verbose: bool = False): + # Unpack options + nelec = options['nelec'] + nbasis = options['nbasis'] + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + lowrank = options['lowrank'] + numpy.random.seed(seed) + + complex_integrals = False + sym = 8 + if complex_integrals: sym = 4 + + params = ThermalQMCParams( + num_walkers=nwalkers, + total_num_walkers=nwalkers * comm.size, + num_blocks=nblocks, + timestep=timestep, + beta=beta, + num_stblz=stabilize_freq, + pop_control_freq=pop_control_freq, + rng_seed=seed) + + system = Generic(nelec=nelec) + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + trial = MeanField(hamiltonian, nelec, beta, timestep) + + nbasis = trial.dmat.shape[-1] + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank) + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank) + propagator.build(hamiltonian, trial=trial, walkers=walkers) + + eloc = local_energy(hamiltonian, walkers) + print(f'# Initial energy = {eloc[0]}') + + afqmc = ThermalAFQMC(system, hamiltonian, trial, walkers, propagator, + params, debug=debug, verbose=verbose) + return afqmc, hamiltonian, walkers + + +def build_legacy_driver_instance(hamiltonian, + options: Union[dict, None], + seed: Union[int, None], + verbose: bool = False): + # Unpack options + nelec = options['nelec'] + nup, ndown = nelec + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + lowrank = options['lowrank'] + numpy.random.seed(seed) + + legacy_options = { + "qmc": { + "dt": timestep, + "nwalkers": nwalkers, + "blocks": nblocks, + "nsteps": nsteps_per_block, + "beta": beta, + "rng_seed": seed, + "pop_control_freq": pop_control_freq, + "stabilise_freq": stabilize_freq, + "batched": False + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank + }, + + "system": { + "name": "Generic", + "nup": nup, + "ndown": ndown, + "mu": mu + }, + + "hamiltonian": options["hamiltonian"], + "estimators": options["estimators"] + } + + legacy_system = Generic(nelec) + legacy_system.mu = mu + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore, + options=legacy_options["hamiltonian"]) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep) + + legacy_walkers = [ + ThermalWalker( + legacy_system, legacy_hamiltonian, legacy_trial, + walker_opts=options, verbose=i == 0) for i in range(nwalkers)] + + #legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( + # (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose) + return afqmc + + +@pytest.mark.unit +def test_thermal_afqmc(): + # Thermal AFQMC params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + + mu = -10.0 + beta = 0.1 + timestep = 0.01 + nwalkers = 1 + seed = 7 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 8 + stabilize_freq = 10 + pop_control_freq = 1 + lowrank = False + verbose = True + debug = True + + with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'lowrank': lowrank, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "estimators": { + "filename": tmpf2.name, # For legacy. + }, + } + + # --------------------------------------------------------------------- + # Test. + # --------------------------------------------------------------------- + print('\n-----------------------') + print('Running ThermalAFQMC...') + print('-----------------------') + afqmc, hamiltonian, walkers = build_driver_test_instance(options, seed, debug, verbose) + afqmc.run(walkers, verbose, estimator_filename=tmpf1.name) + afqmc.finalise() + afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + + test_energy_data = extract_observable(afqmc.estimators.filename, "energy") + test_energy_numer = afqmc.estimators["energy"]["ENumer"] + test_energy_denom = afqmc.estimators["energy"]["EDenom"] + test_number_data = extract_observable(afqmc.estimators.filename, "nav") + + # --------------------------------------------------------------------- + # Legacy. + # --------------------------------------------------------------------- + print('\n------------------------------') + print('Running Legacy ThermalAFQMC...') + print('------------------------------') + legacy_afqmc = build_legacy_driver_instance(hamiltonian, options, seed, verbose) + legacy_afqmc.run(comm=comm) + legacy_afqmc.finalise(verbose=False) + legacy_afqmc.estimators.estimators["mixed"].update( + legacy_afqmc.qmc, + legacy_afqmc.system, + legacy_afqmc.hamiltonian, + legacy_afqmc.trial, + legacy_afqmc.walk, + 0, + legacy_afqmc.propagators.free_projection) + legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) + + enum = legacy_afqmc.estimators.estimators["mixed"].names + legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] + legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] + + if verbose: + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(f'test filename: {afqmc.estimators.filename}') + print(f'legacy filename: {legacy_afqmc.estimators.filename}') + print(f'\ntest_energy_data: \n{test_energy_data}\n') + print(f'test_number_data: \n{test_number_data}\n') + print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') + + # Check. + assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) + assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) + assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) + assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) + + assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) + assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) + assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) + assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) + assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) + assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) + assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) + assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) + assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) + + +if __name__ == '__main__': + test_thermal_afqmc() + diff --git a/ipie/thermal/qmc/tests/test_run.py b/ipie/thermal/qmc/tests/test_run.py new file mode 100644 index 00000000..6f1b3640 --- /dev/null +++ b/ipie/thermal/qmc/tests/test_run.py @@ -0,0 +1,147 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + +import os +import sys +import tempfile +import uuid +import json +import h5py +import numpy + +from pyscf import gto, scf, lo +from ipie.config import MPI +from ipie.systems.generic import Generic +from ipie.hamiltonians.utils import get_hamiltonian + +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.qmc.options import ThermalQMCParams +from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC +from ipie.thermal.estimators.energy import local_energy +from ipie.analysis.extraction import extract_test_data_hdf5, extract_observable + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 + +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) + +else: + test_id = None + +test_id = comm.bcast(test_id, root=0) + + +def test_thermal_afqmc(): + ref_path = "reference_data/generic/" + + # Build `mol` object. + nocca = 5 + noccb = 5 + nelec = nocca + noccb + r0 = 1.75 + mol = gto.M( + atom=[("H", i * r0, 0, 0) for i in range(nelec)], + basis='sto-6g', + unit='Bohr', + verbose=5) + + # Build `scf` object. + mf = scf.UHF(mol).run() + mf.chkfile = 'scf.chk' + mo1 = mf.stability()[0] + dm1 = mf.make_rdm1(mo1, mf.mo_occ) + mf = mf.run(dm1) + mf.stability(return_status=True) + s1e = mol.intor("int1e_ovlp_sph") + ao_coeff = lo.orth.lowdin(s1e) + + with h5py.File(ref_path + "generic_integrals.h5", "r") as fa: + Lxmn = fa["LXmn"][:] + nchol = Lxmn.shape[0] + nbasis = Lxmn.shape[1] + + # Thermal AFQMC params. + mu = -10.0 + beta = 0.1 + timestep = 0.01 + nwalkers = 2 + seed = 7 + nsteps_per_block = 1 + nblocks = 10 + stabilize_freq = 10 + pop_control_freq = 1 + lowrank = False + verbose = True + + params = ThermalQMCParams( + num_walkers=nwalkers, + total_num_walkers=nwalkers * comm.size, + num_blocks=nblocks, + num_steps_per_block=nsteps_per_block, + timestep=timestep, + beta=beta, + num_stblz=stabilize_freq, + pop_control_freq=pop_control_freq, + rng_seed=seed) + + options = { + "hamiltonian": { + "name": "Generic", + "integrals": ref_path + "generic_integrals.h5", + "_alt_convention": False, + "symmetry": False, + "sparse": False, + "mu": mu + }, + } + + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + system = Generic(mol.nelec, verbose=verbose) + hamiltonian = get_hamiltonian(system, options["hamiltonian"]) + trial = MeanField(hamiltonian, mol.nelec, beta, timestep, verbose=verbose) + + nbasis = trial.dmat.shape[-1] + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + eloc = local_energy(hamiltonian, walkers) + print(f'# Initial energy = {eloc[0]}') + + afqmc = ThermalAFQMC(system, hamiltonian, trial, walkers, propagator, params, verbose) + afqmc.run(walkers, verbose) + afqmc.finalise() + afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + #numer_batch = afqmc.estimators["energy"]["ENumer"] + #denom_batch = afqmc.estimators["energy"]["EDenom"] + data_batch = extract_observable(afqmc.estimators.filename, "energy") + print(data_batch) + + +if __name__ == '__main__': + test_thermal_afqmc() + diff --git a/ipie/thermal/qmc/tests/ueg/test_ueg.py b/ipie/thermal/qmc/tests/ueg/test_ueg.py new file mode 100644 index 00000000..331fee9c --- /dev/null +++ b/ipie/thermal/qmc/tests/ueg/test_ueg.py @@ -0,0 +1,422 @@ +import os +import sys +import json +import pprint +import tempfile +import h5py +import uuid +import pytest +import numpy +from typing import Union + +from ueg import UEG +from ipie.config import MPI +from ipie.systems.generic import Generic +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.qmc.options import QMCOpts + +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.qmc.options import ThermalQMCParams +from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC +from ipie.thermal.estimators.energy import local_energy +from ipie.analysis.extraction import ( + get_metadata, + extract_test_data_hdf5, + extract_data, + extract_observable, + extract_mixed_estimates) + +from ipie.legacy.systems.ueg import UEG as LegacyUEG +from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.thermal import ThermalWalker +from ipie.legacy.thermal_propagation.planewave import PlaneWave +from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G +from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC + + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 + +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) + +else: + test_id = None + +test_id = comm.bcast(test_id, root=0) + + +def compare_test_data(ref_data, test_data): + comparison = {} + + for k, v in ref_data.items(): + alias = [k] + + if k == "sys_info": + continue + + elif k == "EHybrid": + alias.append("HybridEnergy") + + err = 0 + ref = ref_data[k] + + for a in alias: + try: + test = test_data[a] + comparison[k] = ( + numpy.array(ref), + numpy.array(test), + numpy.max(numpy.abs(numpy.array(ref) - numpy.array(test))) < 1e-10) + + except KeyError: + err += 1 + + if err == len(alias): + print(f"# Issue with test data key {k}") + + return comparison + + +def build_driver_test_instance(ueg: UEG, + options: Union[dict, None], + seed: Union[int, None], + debug: bool = False, + verbose: bool = False): + # Unpack options + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + lowrank = options['lowrank'] + numpy.random.seed(seed) + + nbasis = ueg.nbasis + nchol = ueg.nchol + nelec = (ueg.nup, ueg.ndown) + nup, ndown = nelec + + h1 = ueg.H1[0] + chol = 2. * ueg.chol_vecs.toarray().copy() + #ecore = ueg.ecore + ecore = 0. + + params = ThermalQMCParams( + num_walkers=nwalkers, + total_num_walkers=nwalkers * comm.size, + num_blocks=nblocks, + timestep=timestep, + beta=beta, + num_stblz=stabilize_freq, + pop_control_freq=pop_control_freq, + rng_seed=seed) + + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + # 1. Build Hamiltonian. + hamiltonian = HamGeneric( + numpy.array([h1, h1], dtype=numpy.complex128), + numpy.array(chol, dtype=numpy.complex128), + ecore, + verbose=verbose) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + # 2. Build trial. + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + + # 3. Build walkers. + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + + # 4. Build propagator. + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + eloc = local_energy(hamiltonian, walkers) + print(f'# Initial energy = {eloc[0]}') + + # 5. Build Thermal AFQMC driver. + # Dummy system. + system = None + afqmc = ThermalAFQMC(system, hamiltonian, trial, walkers, propagator, + params, debug=debug, verbose=verbose) + return afqmc, hamiltonian, walkers + + +def build_legacy_driver_instance(hamiltonian, + options: Union[dict, None], + seed: Union[int, None], + verbose: bool = False): + # Unpack options + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + lowrank = options['lowrank'] + numpy.random.seed(seed) + + legacy_options = { + "qmc": { + "dt": timestep, + "nwalkers": nwalkers, + "blocks": nblocks, + "nsteps": nsteps_per_block, + "beta": beta, + "rng_seed": seed, + "pop_control_freq": pop_control_freq, + "stabilise_freq": stabilize_freq, + "batched": False + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank + }, + + "ueg_opts": options["ueg_opts"], + "hamiltonian": options["hamiltonian"], + "estimators": options["estimators"] + } + + # 1. Build out system. + legacy_system = LegacyUEG(options=legacy_options["ueg_opts"]) + legacy_system.mu = mu + + # 2. Build Hamiltonian. + legacy_hamiltonian = LegacyHamUEG(legacy_system, options=legacy_options["ueg_opts"]) + legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] + + # 3. Build trial. + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) + + # 4. Build walkers. + legacy_walkers = [ + ThermalWalker( + legacy_system, legacy_hamiltonian, legacy_trial, + walker_opts=legacy_options, verbose=i == 0) for i in range(nwalkers)] + + # 5. Build propagator. + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps_per_block + qmc_opts.dt = timestep + qmc_opts.seed = seed + + legacy_propagator = PlaneWave(legacy_system, legacy_hamiltonian, legacy_trial, qmc_opts, + options=legacy_options["propagator"], lowrank=lowrank, verbose=verbose) + afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose) + return afqmc + + +@pytest.mark.unit +def test_thermal_afqmc(against_ref=False): + # Thermal AFQMC params. + seed = 7 + mu = -1. + beta = 0.1 + timestep = 0.01 + nwalkers = 1 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 11 + stabilize_freq = 10 + pop_control_freq = 1 + lowrank = False + verbose = True + debug = True + numpy.random.seed(seed) + + with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: + ueg_opts = { + "nup": 7, + "ndown": 7, + "rs": 1., + "ecut": 1., + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + } + + # Generate UEG integrals. + ueg = UEG(ueg_opts, verbose=verbose) + ueg.build(verbose=verbose) + nbasis = ueg.nbasis + nchol = ueg.nchol + nelec = (ueg.nup, ueg.ndown) + nup, ndown = nelec + + if verbose: + print(f"# nbasis = {nbasis}") + print(f"# nchol = {nchol}") + print(f"# nup = {nup}") + print(f"# ndown = {ndown}") + + # --------------------------------------------------------------------- + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'lowrank': lowrank, + + "hamiltonian": { + "name": "UEG", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "estimators": { + "filename": tmpf2.name, # For legacy. + }, + + "ueg_opts": ueg_opts + } + + # --------------------------------------------------------------------- + # Test. + # --------------------------------------------------------------------- + print('\n-----------------------') + print('Running ThermalAFQMC...') + print('-----------------------') + afqmc, hamiltonian, walkers = build_driver_test_instance(ueg, options, seed, debug, verbose) + afqmc.run(walkers, verbose, estimator_filename=tmpf1.name) + afqmc.finalise() + afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + + test_energy_data = extract_observable(afqmc.estimators.filename, "energy") + test_energy_numer = afqmc.estimators["energy"]["ENumer"] + test_energy_denom = afqmc.estimators["energy"]["EDenom"] + test_number_data = extract_observable(afqmc.estimators.filename, "nav") + + # --------------------------------------------------------------------- + # Legacy. + # --------------------------------------------------------------------- + print('\n------------------------------') + print('Running Legacy ThermalAFQMC...') + print('------------------------------') + legacy_afqmc = build_legacy_driver_instance(hamiltonian, options, seed, verbose) + legacy_afqmc.run(comm=comm) + legacy_afqmc.finalise(verbose=False) + legacy_afqmc.estimators.estimators["mixed"].update( + legacy_afqmc.qmc, + legacy_afqmc.system, + legacy_afqmc.hamiltonian, + legacy_afqmc.trial, + legacy_afqmc.walk, + 0, + legacy_afqmc.propagators.free_projection) + legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) + + enum = legacy_afqmc.estimators.estimators["mixed"].names + legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] + legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] + + # --------------------------------------------------------------------- + if verbose: + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(f'test filename: {afqmc.estimators.filename}') + print(f'legacy filename: {legacy_afqmc.estimators.filename}') + print(f'\ntest_energy_data: \n{test_energy_data}\n') + print(f'test_number_data: \n{test_number_data}\n') + print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') + + # Check. + assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) + assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) + assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) + assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) + + assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) + assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) + assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) + assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) + assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) + assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) + assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) + assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) + assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) + + # --------------------------------------------------------------------- + # Test against reference data. + if against_ref: + _data_dir = os.path.abspath(os.path.dirname(__file__)).split("ueg")[0] + "/reference_data/" + _legacy_test_dir = "ueg" + _legacy_test = _data_dir + _legacy_test_dir + "/reference_1walker.json" + + test_name = _legacy_test_dir + with open(_legacy_test, "r") as f: + ref_data = json.load(f) + + skip_val = ref_data.get("extract_skip_value", 10) + _test_energy_data = test_energy_data[::skip_val].to_dict(orient="list") + _test_number_data = test_number_data[::skip_val].to_dict(orient="list") + energy_comparison = compare_test_data(ref_data, _test_energy_data) + number_comparison = compare_test_data(ref_data, _test_number_data) + + print('\nenergy comparison:') + pprint.pprint(energy_comparison) + print('\nnumber comparison:') + pprint.pprint(number_comparison) + + local_err_count = 0 + + for k, v in energy_comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + + for k, v in number_comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + + if local_err_count == 0: + print(f"\n*** PASSED : {test_name} ***") + + +if __name__ == '__main__': + test_thermal_afqmc(against_ref=True) + diff --git a/ipie/thermal/qmc/tests/ueg/ueg.py b/ipie/thermal/qmc/tests/ueg/ueg.py new file mode 100644 index 00000000..fa0d8d7d --- /dev/null +++ b/ipie/thermal/qmc/tests/ueg/ueg.py @@ -0,0 +1,563 @@ +import numpy +import scipy.sparse +from ipie.utils.io import write_qmcpack_sparse + + +class UEG(object): + """UEG system class (integrals read from fcidump) + + Parameters + ---------- + nup : int + Number of up electrons. + + ndown : int + Number of down electrons. + + rs : float + Density parameter. + + ecut : float + Scaled cutoff energy. + + ktwist : :class:`numpy.ndarray` + Twist vector. + + verbose : bool + Print extra information. + + Attributes + ---------- + T : :class:`numpy.ndarray` + One-body part of the Hamiltonian. This is diagonal in plane wave basis. + + ecore : float + Madelung contribution to the total energy. + + h1e_mod : :class:`numpy.ndarray` + Modified one-body Hamiltonian. + + nfields : int + Number of field configurations per walker for back propagation. + + basis : :class:`numpy.ndarray` + Basis vectors within a cutoff. + + kfac : float + Scale factor (2pi/L). + """ + + def __init__(self, options, verbose=False): + if verbose: + print("# Parsing input options.") + + self.name = "UEG" + self.nup = options.get("nup") + self.ndown = options.get("ndown") + self.nelec = (self.nup, self.ndown) + self.rs = options.get("rs") + self.ecut = options.get("ecut") + self.ktwist = numpy.array(options.get("ktwist", [0, 0, 0])).reshape(3) + + self.thermal = options.get("thermal", False) + self._alt_convention = options.get("alt_convention", False) + self.write_ints = options.get("write_integrals", False) + + self.sparse = True + self.control_variate = False + self.diagH1 = True + + # Total # of electrons. + self.ne = self.nup + self.ndown + # Spin polarisation. + self.zeta = (self.nup - self.ndown) / self.ne + # Density. + self.rho = ((4.0 * numpy.pi) / 3.0 * self.rs**3.0) ** (-1.0) + # Box Length. + self.L = self.rs * (4.0 * self.ne * numpy.pi / 3.0) ** (1 / 3.0) + # Volume + self.vol = self.L**3.0 + # k-space grid spacing. + self.kfac = 2 * numpy.pi / self.L + # Fermi Wavevector (infinite system). + self.kf = (3 * (self.zeta + 1) * numpy.pi**2 * self.ne / self.L**3) ** (1 / 3.0) + # Fermi energy (inifinite systems). + self.ef = 0.5 * self.kf**2 + # Core energy. + self.ecore = 0.5 * self.ne * self.madelung() + + if verbose: + if self.thermal: + print("# Thermal UEG activated.") + + print(f"# Number of spin-up electrons: {self.nup:d}") + print(f"# Number of spin-down electrons: {self.ndown:d}") + print(f"# rs: {self.rs:6.4e}") + print(f"# Spin polarisation (zeta): {self.zeta:6.4e}") + print(f"# Electron density (rho): {self.rho:13.8e}") + print(f"# Box Length (L): {self.L:13.8e}") + print(f"# Volume: {self.vol:13.8e}") + print(f"# k-space factor (2pi/L): {self.kfac:13.8e}") + + + def build(self, verbose=False): + # Get plane wave basis vectors and corresponding eigenvalues. + self.sp_eigv, self.basis, self.nmax = self.sp_energies( + self.ktwist, self.kfac, self.ecut) + self.shifted_nmax = 2 * self.nmax + self.imax_sq = numpy.dot(self.basis[-1], self.basis[-1]) + self.create_lookup_table() + + for i, k in enumerate(self.basis): + assert i == self.lookup_basis(k) + + # Number of plane waves. + self.nbasis = len(self.sp_eigv) + self.nactive = self.nbasis + self.ncore = 0 + self.nfv = 0 + self.mo_coeff = None + + # --------------------------------------------------------------------- + T = numpy.diag(self.sp_eigv) + h1e_mod = self.mod_one_body(T) + self.H1 = numpy.array([T, T]) # Making alpha and beta. + self.h1e_mod = numpy.array([h1e_mod, h1e_mod]) + + # --------------------------------------------------------------------- + # Allowed momentum transfers (4*ecut). + eigs, qvecs, self.qnmax = self.sp_energies(self.ktwist, self.kfac, 4 * self.ecut) + + # Omit Q = 0 term. + self.qvecs = numpy.copy(qvecs[1:]) + self.vqvec = numpy.array([self.vq(self.kfac * q) for q in self.qvecs]) + + # Number of momentum transfer vectors / auxiliary fields. + # Can reduce by symmetry but be stupid for the moment. + self.nchol = len(self.qvecs) + self.nfields = 2 * len(self.qvecs) + self.get_momentum_transfers() + + if verbose: + print(f"# Number of plane waves: {self.nbasis:d}") + print(f"# Number of Cholesky vectors: {self.nchol:d}.") + print(f"# Number of auxiliary fields: {self.nfields:d}.") + print("# Constructing two-body potentials incore.") + + # --------------------------------------------------------------------- + self.chol_vecs, self.iA, self.iB = self.two_body_potentials_incore() + + if self.write_ints: + self.write_integrals() + + if verbose: + print("# Approximate memory required for " + "two-body potentials: {:13.8e} GB.".format((3 * self.iA.nnz * 16 / (1024**3)))) + print("# Finished constructing two-body potentials.") + print("# Finished building UEG object.") + + + def sp_energies(self, ks, kfac, ecut): + """Calculate the allowed kvectors and resulting single particle eigenvalues (basically kinetic energy) + which can fit in the sphere in kspace determined by ecut. + + Parameters + ---------- + kfac : float + kspace grid spacing. + + ecut : float + energy cutoff. + + Returns + ------- + spval : :class:`numpy.ndarray` + Array containing sorted single particle eigenvalues. + + kval : :class:`numpy.ndarray` + Array containing basis vectors, sorted according to their + corresponding single-particle energy. + """ + + # Scaled Units to match with HANDE. + # So ecut is measured in units of 1/kfac^2. + nmax = int(numpy.ceil(numpy.sqrt((2 * ecut)))) + + spval = [] + vec = [] + kval = [] + + for ni in range(-nmax, nmax + 1): + for nj in range(-nmax, nmax + 1): + for nk in range(-nmax, nmax + 1): + spe = 0.5 * (ni**2 + nj**2 + nk**2) + + if spe <= ecut: + kijk = [ni, nj, nk] + + # Reintroduce 2 \pi / L factor. + ek = 0.5 * numpy.dot(numpy.array(kijk) + ks, numpy.array(kijk) + ks) + kval.append(kijk) + spval.append(kfac**2 * ek) + + # Sort the arrays in terms of increasing energy. + spval = numpy.array(spval) + ix = numpy.argsort(spval, kind="mergesort") + spval = spval[ix] + kval = numpy.array(kval)[ix] + return spval, kval, nmax + + + def create_lookup_table(self): + basis_ix = [] + for k in self.basis: + basis_ix.append(self.map_basis_to_index(k)) + + self.lookup = numpy.zeros(max(basis_ix) + 1, dtype=int) + + for i, b in enumerate(basis_ix): + self.lookup[b] = i + + self.max_ix = max(basis_ix) + + + def lookup_basis(self, vec): + if numpy.dot(vec, vec) <= self.imax_sq: + ix = self.map_basis_to_index(vec) + + if ix >= len(self.lookup): + ib = None + + else: + ib = self.lookup[ix] + + return ib + + else: + ib = None + + + def map_basis_to_index(self, k): + return ((k[0] + self.nmax) + + self.shifted_nmax * (k[1] + self.nmax) + + self.shifted_nmax * self.shifted_nmax * (k[2] + self.nmax)) + + + def get_momentum_transfers(self): + """Get arrays of plane wave basis vectors connected by momentum transfers Q.""" + nlimit = self.nup + if self.thermal: + nlimit = self.nbasis + + self.ikpq_i = [] + self.ikpq_kpq = [] + + for iq, q in enumerate(self.qvecs): + idxkpq_list_i = [] + idxkpq_list_kpq = [] + + for i, k in enumerate(self.basis[0:nlimit]): + kpq = k + q + idxkpq = self.lookup_basis(kpq) + + if idxkpq is not None: + idxkpq_list_i += [i] + idxkpq_list_kpq += [idxkpq] + + self.ikpq_i += [idxkpq_list_i] + self.ikpq_kpq += [idxkpq_list_kpq] + + # --------------------------------------------------------------------- + self.ipmq_i = [] + self.ipmq_pmq = [] + + for iq, q in enumerate(self.qvecs): + idxpmq_list_i = [] + idxpmq_list_pmq = [] + + for i, p in enumerate(self.basis[0:nlimit]): + pmq = p - q + idxpmq = self.lookup_basis(pmq) + + if idxpmq is not None: + idxpmq_list_i += [i] + idxpmq_list_pmq += [idxpmq] + + self.ipmq_i += [idxpmq_list_i] + self.ipmq_pmq += [idxpmq_list_pmq] + + for iq, q in enumerate(self.qvecs): + self.ikpq_i[iq] = numpy.array(self.ikpq_i[iq], dtype=numpy.int64) + self.ikpq_kpq[iq] = numpy.array(self.ikpq_kpq[iq], dtype=numpy.int64) + self.ipmq_i[iq] = numpy.array(self.ipmq_i[iq], dtype=numpy.int64) + self.ipmq_pmq[iq] = numpy.array(self.ipmq_pmq[iq], dtype=numpy.int64) + + + def madelung(self): + """Use expression in Schoof et al. (PhysRevLett.115.130402) for the + Madelung contribution to the total energy fitted to L.M. Fraser et al. + Phys. Rev. B 53, 1814. + + Parameters + ---------- + rs : float + Wigner-Seitz radius. + + ne : int + Number of electrons. + + Returns + ------- + v_M: float + Madelung potential (in Hartrees). + """ + c1 = -2.837297 + c2 = (3.0 / (4.0 * numpy.pi)) ** (1.0 / 3.0) + return c1 * c2 / (self.ne ** (1.0 / 3.0) * self.rs) + + + def mod_one_body(self, T): + """Absorb the diagonal term of the two-body Hamiltonian to the one-body term. + Essentially adding the third term in Eq.(11b) of Phys. Rev. B 75, 245123. + + Parameters + ---------- + T : float + one-body Hamiltonian (i.e. kinetic energy) + + Returns + ------- + h1e_mod: float + modified one-body Hamiltonian + """ + h1e_mod = numpy.copy(T) + + fac = 1.0 / (2.0 * self.vol) + for i, ki in enumerate(self.basis): + for j, kj in enumerate(self.basis): + if i != j: + q = self.kfac * (ki - kj) + h1e_mod[i, i] = h1e_mod[i, i] - fac * self.vq(q) + + return h1e_mod + + + def vq(self, q): + """The typical 3D Coulomb kernel + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + v_M: float + 3D Coulomb kernel (in Hartrees) + """ + return 4 * numpy.pi / numpy.dot(q, q) + + + def density_operator(self, iq): + """Density operator as defined in Eq.(6) of Phys. Rev. B 75, 245123. + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + rho_q: float + density operator + """ + nnz = self.rho_ikpq_kpq[iq].shape[0] # Number of non-zeros + ones = numpy.ones((nnz), dtype=numpy.complex128) + rho_q = scipy.sparse.csc_matrix( + (ones, (self.rho_ikpq_kpq[iq], self.rho_ikpq_i[iq])), + shape=(self.nbasis, self.nbasis), + dtype=numpy.complex128) + return rho_q + + + def scaled_density_operator_incore(self, transpose): + """Density operator as defined in Eq.(6) of PRB(75)245123 + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + rho_q: float + density operator + """ + rho_ikpq_i = [] + rho_ikpq_kpq = [] + + for iq, q in enumerate(self.qvecs): + idxkpq_list_i = [] + idxkpq_list_kpq = [] + + for i, k in enumerate(self.basis): + kpq = k + q + idxkpq = self.lookup_basis(kpq) + + if idxkpq is not None: + idxkpq_list_i += [i] + idxkpq_list_kpq += [idxkpq] + + rho_ikpq_i += [idxkpq_list_i] + rho_ikpq_kpq += [idxkpq_list_kpq] + + for iq, q in enumerate(self.qvecs): + rho_ikpq_i[iq] = numpy.array(rho_ikpq_i[iq], dtype=numpy.int64) + rho_ikpq_kpq[iq] = numpy.array(rho_ikpq_kpq[iq], dtype=numpy.int64) + + nq = len(self.qvecs) + nnz = 0 + for iq in range(nq): + nnz += rho_ikpq_kpq[iq].shape[0] + + col_index = [] + row_index = [] + values = [] + + if transpose: + for iq in range(nq): + qscaled = self.kfac * self.qvecs[iq] + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = numpy.pi / (self.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + for innz, kpq in enumerate(rho_ikpq_kpq[iq]): + row_index += [rho_ikpq_kpq[iq][innz] + rho_ikpq_i[iq][innz] * self.nbasis] + col_index += [iq] + values += [factor] + + else: + for iq in range(nq): + qscaled = self.kfac * self.qvecs[iq] + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = numpy.pi / (self.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + for innz, kpq in enumerate(rho_ikpq_kpq[iq]): + row_index += [rho_ikpq_kpq[iq][innz] * self.nbasis + rho_ikpq_i[iq][innz]] + col_index += [iq] + values += [factor] + + rho_q = scipy.sparse.csc_matrix( + (values, (row_index, col_index)), + shape=(self.nbasis * self.nbasis, nq), + dtype=numpy.complex128) + return rho_q + + + def two_body_potentials_incore(self): + """Calculate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q + + Returns + ------- + iA : numpy array + Eq.(13a) + + iB : numpy array + Eq.(13b) + """ + rho_q = self.scaled_density_operator_incore(False) + rho_qH = self.scaled_density_operator_incore(True) + iA = 1j * (rho_q + rho_qH) + iB = -(rho_q - rho_qH) + return (rho_q, iA, iB) + + + def hijkl(self, i, j, k, l): + """Compute = (ik|jl) = 1/Omega * 4pi/(kk-ki)**2 + + Checks for momentum conservation k_i + k_j = k_k + k_k, or + k_k - k_i = k_j - k_l. + + Parameters + ---------- + i, j, k, l : int + Orbital indices for integral (ik|jl) = . + + Returns + ------- + integral : float + (ik|jl) + """ + q1 = self.basis[k] - self.basis[i] + q2 = self.basis[j] - self.basis[l] + + if numpy.dot(q1, q1) > 1e-12 and numpy.dot(q1 - q2, q1 - q2) < 1e-12: + return 1.0 / self.vol * self.vq(self.kfac * q1) + + else: + return 0.0 + + + def compute_real_transformation(self): + U22 = numpy.zeros((2, 2), dtype=numpy.complex128) + U22[0, 0] = 1.0 / numpy.sqrt(2.0) + U22[0, 1] = 1.0 / numpy.sqrt(2.0) + U22[1, 0] = -1.0j / numpy.sqrt(2.0) + U22[1, 1] = 1.0j / numpy.sqrt(2.0) + + U = numpy.zeros((self.nbasis, self.nbasis), dtype=numpy.complex128) + + for i, b in enumerate(self.basis): + if numpy.sum(b * b) == 0: + U[i, i] = 1.0 + + else: + mb = -b + diff = numpy.einsum("ij->i", (self.basis - mb) ** 2) + idx = numpy.argwhere(diff == 0) + assert idx.ravel().shape[0] == 1 + + if i < idx: + idx = idx.ravel()[0] + U[i, i] = U22[0, 0] + U[i, idx] = U22[0, 1] + U[idx, i] = U22[1, 0] + U[idx, idx] = U22[1, 1] + + else: + continue + + U = U.T.copy() + return U + + + def eri_4(self): + eri_chol = 4 * self.chol_vecs.dot(self.chol_vecs.T) + eri_chol = ( + eri_chol.toarray().reshape((self.nbasis, self.nbasis, self.nbasis, self.nbasis)).real) + eri_chol = eri_chol.transpose(0, 1, 3, 2) + return eri_chol + + + def eri_8(self): + """Compute 8-fold symmetric integrals. Useful for running standard + quantum chemistry methods,""" + eri = self.eri_4() + U = self.compute_real_transformation() + eri0 = numpy.einsum("mp,mnls->pnls", U.conj(), eri, optimize=True) + eri1 = numpy.einsum("nq,pnls->pqls", U, eri0, optimize=True) + eri2 = numpy.einsum("lr,pqls->pqrs", U.conj(), eri1, optimize=True) + eri3 = numpy.einsum("st,pqrs->pqrt", U, eri2, optimize=True).real + return eri3 + + + def write_integrals(self, filename="ueg_integrals.h5"): + write_qmcpack_sparse( + self.H1[0], + 2 * self.chol_vecs.toarray(), + self.nelec, + self.nbasis, + enuc=0.0, + filename=filename) + diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index 1208833f..3a59a402 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -6,7 +6,6 @@ from typing import Dict, Optional, Tuple from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.walkers.base_walkers import ThermalWalkerAccumulator from ipie.thermal.propagation.propagator import Propagator from ipie.thermal.estimators.handler import ThermalEstimatorHandler from ipie.thermal.qmc.options import ThermalQMCParams @@ -19,6 +18,7 @@ from ipie.systems.generic import Generic from ipie.estimators.estimator_base import EstimatorBase from ipie.walkers.pop_controller import PopController +from ipie.walkers.base_walkers import WalkerAccumulator from ipie.qmc.afqmc import AFQMC from ipie.qmc.utils import set_rng_seed @@ -68,10 +68,10 @@ def build( beta: float, hamiltonian, trial, - num_walkers: int = 100, + nwalkers: int = 100, seed: int = None, - num_steps_per_block: int = 25, - num_blocks: int = 100, + nsteps_per_block: int = 25, + nblocks: int = 100, timestep: float = 0.005, stabilize_freq: int = 5, pop_control_freq: int = 5, @@ -91,15 +91,15 @@ def build( Hamiltonian describing the system. trial : Trial density matrix. - num_walkers : int + nwalkers : int Number of walkers per MPI process used in the simulation. The TOTAL - number of walkers is num_walkers * number of processes. - num_steps_per_block : int - Number of Monte Carlo steps before estimators are evaluatied. + number of walkers is nwalkers * number of processes. + nsteps_per_block : int + Number of Monte Carlo steps before estimators are evaluated. Default 25. - num_blocks : int - Number of blocks to perform. Total number of steps = num_blocks * - num_steps_per_block. + nblocks : int + Number of blocks to perform. Total number of steps = nblocks * + nsteps_per_block. timestep : float Imaginary timestep. Default 0.005. stabilize_freq : float @@ -117,16 +117,16 @@ def build( comm = mpi_handler.comm params = ThermalQMCParams( beta=beta, - num_walkers=num_walkers, - total_num_walkers=num_walkers * comm.size, - num_blocks=num_blocks, - num_steps_per_block=num_steps_per_block, + num_walkers=nwalkers, + total_num_walkers=nwalkers * comm.size, + num_blocks=nblocks, + num_steps_per_block=nsteps_per_block, timestep=timestep, num_stblz=stabilize_freq, pop_control_freq=pop_control_freq, rng_seed=seed) - walkers = UHFThermalWalkers(trial, hamiltonian.nbasis, num_walkers, + walkers = UHFThermalWalkers(trial, hamiltonian.nbasis, nwalkers, lowrank=lowrank, verbose=verbose) propagator = Propagator[type(hamiltonian)]( timestep, beta, lowrank=lowrank, verbose=verbose) @@ -187,20 +187,23 @@ def run(self, print(f'comm.rank = {comm.rank}') # Propagate. - num_walkers = self.walkers.nwalkers + nwalkers = self.walkers.nwalkers total_steps = self.params.num_steps_per_block * self.params.num_blocks # TODO: This magic value of 2 is pretty much never controlled on input. # Moreover I'm not convinced having a two stage shift update actually # matters at all. - num_eqlb_steps = 2.0 / self.params.timestep - num_slices = numpy.rint(self.params.beta / self.params.timestep).astype(int) + neqlb_steps = 2.0 / self.params.timestep + nslices = numpy.rint(self.params.beta / self.params.timestep).astype(int) + + print(f'total_steps = {total_steps}') + print(f'nslices = {nslices}') for step in range(1, total_steps + 1): start_path = time.time() - for t in range(num_slices): + for t in range(nslices): if self.verbosity >= 2 and comm.rank == 0: - print(" # Timeslice %d of %d." % (t, num_slices)) + print(" # Timeslice %d of %d." % (t, nslices)) start = time.time() self.propagator.propagate_walkers( @@ -215,7 +218,7 @@ def run(self, if t > 0: wbound = self.pcontrol.total_weight * 0.10 xp.clip(self.walkers.weight, a_min=-wbound, a_max=wbound, - out=self.walkers.weight) # In-place clipping + out=self.walkers.weight) # In-place clipping. self.tprop_clip += time.time() - start_clip @@ -226,7 +229,7 @@ def run(self, self.tprop_barrier += time.time() - start_barrier self.tprop += time.time() - start - print(f'self.walkers.weight = {self.walkers.weight}') + #print(f'self.walkers.weight = {self.walkers.weight}') if (t > 0) and (t % self.params.pop_control_freq == 0): start = time.time() self.pcontrol.pop_control(self.walkers, comm) @@ -249,16 +252,17 @@ def run(self, self.estimators.print_block( comm, step // self.params.num_steps_per_block, self.accumulators) - self.accumulators.zero(self.walkers, self.trial) + self.accumulators.zero() self.testim += time.time() - start - if step < num_eqlb_steps: + if step < neqlb_steps: eshift = self.accumulators.eshift else: eshift += self.accumulators.eshift - eshift + self.walkers.reset(self.trial) # Reset stack, weights, phase. self.tpath += time.time() - start_path @@ -383,7 +387,7 @@ def setup_estimators( self, filename, additional_estimators: Optional[Dict[str, EstimatorBase]] = None): - self.accumulators = ThermalWalkerAccumulator( + self.accumulators = WalkerAccumulator( ["Weight", "WeightFactor", "HybridEnergy"], self.params.num_steps_per_block) comm = self.mpi_handler.comm self.estimators = ThermalEstimatorHandler( @@ -409,7 +413,7 @@ def setup_estimators( self.trial, self.walkers) self.accumulators.update(self.walkers) self.estimators.print_block(comm, 0, self.accumulators) - self.accumulators.zero(self.walkers, self.trial) + self.accumulators.zero() def setup_timers(self): diff --git a/ipie/thermal/trial/mean_field.py b/ipie/thermal/trial/mean_field.py index 26ad1cdb..f9d81076 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/thermal/trial/mean_field.py @@ -1,7 +1,7 @@ import numpy import scipy.linalg -from ipie.thermal.estimators.fock import fock_matrix +from ipie.thermal.estimators.generic import fock_generic from ipie.thermal.estimators.greens_function import greens_function from ipie.thermal.estimators.thermal import one_rdm_stable, particle_number from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential @@ -45,14 +45,14 @@ def thermal_hartree_fock(self, hamiltonian, beta): scipy.linalg.expm(-dt * HMF[1])]) if self.find_mu: mu = find_chemical_potential( - hamiltonian._alt_convention, rho, dt, self.num_bins, self.nav, + hamiltonian._alt_convention, rho, dt, self.stack_length, self.nav, deps=self.deps, max_it=self.max_it, verbose=self.verbose) else: mu = self.mu rho_mu = compute_rho(rho, mu_old, dt) - P = one_rdm_stable(rho_mu, self.num_bins) + P = one_rdm_stable(rho_mu, self.stack_length) dmu = abs(mu - mu_old) if self.verbose: @@ -67,21 +67,21 @@ def thermal_hartree_fock(self, hamiltonian, beta): def scf(self, hamiltonian, beta, mu, P): # Compute HMF - HMF = fock_matrix(hamiltonian, P) + HMF = fock_generic(hamiltonian, P) dt = self.dtau muN = mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) rho = numpy.array([scipy.linalg.expm(-dt * (HMF[0] - muN)), scipy.linalg.expm(-dt * (HMF[1] - muN))]) - Pold = one_rdm_stable(rho, self.num_bins) + Pold = one_rdm_stable(rho, self.stack_length) if self.verbose: print("# Running Thermal SCF.") for it in range(self.max_scf_it): - HMF = fock_matrix(hamiltonian, Pold) + HMF = fock_generic(hamiltonian, Pold) rho = numpy.array([scipy.linalg.expm(-dt * (HMF[0] - muN)), scipy.linalg.expm(-dt * (HMF[1] - muN))]) - Pnew = (1 - self.alpha) * one_rdm_stable(rho, self.num_bins) + self.alpha * Pold + Pnew = (1 - self.alpha) * one_rdm_stable(rho, self.stack_length) + self.alpha * Pold change = numpy.linalg.norm(Pnew - Pold) if change < self.deps: diff --git a/ipie/thermal/trial/one_body.py b/ipie/thermal/trial/one_body.py index b24d125d..b471b635 100644 --- a/ipie/thermal/trial/one_body.py +++ b/ipie/thermal/trial/one_body.py @@ -79,10 +79,10 @@ def __init__(self, hamiltonian, nelec, beta, dt, options={}, nav=None, # Adjust stack size self.nstack = update_stack(self.nstack, self.nslice, verbose=verbose) - self.num_bins = int(beta / (self.nstack * dt)) + self.stack_length = int(beta / (self.nstack * dt)) if verbose: - print(f"# Number of stacks: {self.num_bins}") + print(f"# Number of stacks: {self.stack_length}") sign = 1 if hamiltonian._alt_convention: @@ -98,7 +98,7 @@ def __init__(self, hamiltonian, nelec, beta, dt, options={}, nav=None, self.rho = numpy.array([scipy.linalg.expm(-dtau * (self.H1[0])), scipy.linalg.expm(-dtau * (self.H1[1]))]) self.mu = find_chemical_potential( - hamiltonian._alt_convention, self.rho, dtau, self.num_bins, + hamiltonian._alt_convention, self.rho, dtau, self.stack_length, self.nav, deps=self.deps, max_it=self.max_it, verbose=verbose) else: @@ -108,7 +108,7 @@ def __init__(self, hamiltonian, nelec, beta, dt, options={}, nav=None, if self.verbose: print(f"# Chemical potential in trial density matrix: {self.mu: .10e}") - self.P = one_rdm_stable(compute_rho(self.rho, self.mu, dtau, sign=sign), self.num_bins) + self.P = one_rdm_stable(compute_rho(self.rho, self.mu, dtau, sign=sign), self.stack_length) self.nav = particle_number(self.P).real if self.verbose: diff --git a/ipie/thermal/walkers/base_walkers.py b/ipie/thermal/walkers/base_walkers.py deleted file mode 100644 index a99f95b3..00000000 --- a/ipie/thermal/walkers/base_walkers.py +++ /dev/null @@ -1,17 +0,0 @@ -import numpy -from ipie.walkers.base_walkers import WalkerAccumulator - - -class ThermalWalkerAccumulator(WalkerAccumulator): - def __init__(self, names, nsteps): - super().__init__(names, nsteps) - - def zero(self, walkers, trial): - self.buffer.fill(0.j) - walkers.weight = numpy.ones(walkers.nwalkers) - walkers.phase = numpy.ones(walkers.nwalkers, dtype=numpy.complex128) - - for iw in range(walkers.nwalkers): - walkers.stack[iw].reset() - walkers.stack[iw].set_all(trial.dmat) - walkers.calc_greens_function(iw) diff --git a/ipie/thermal/walkers/stack.py b/ipie/thermal/walkers/stack.py index 49e238c9..1d8e6991 100644 --- a/ipie/thermal/walkers/stack.py +++ b/ipie/thermal/walkers/stack.py @@ -20,7 +20,7 @@ def __init__( self.time_slice = 0 self.nstack = nstack self.nslice = nslice - self.nbins = nslice // self.nstack + self.stack_length = self.nslice // self.nstack self.nbasis = nbasis self.diagonal_trial = diagonal self.averaging = averaging @@ -32,9 +32,9 @@ def __init__( if self.lowrank: assert diagonal - if self.nbins * self.nstack < self.nslice: + if self.stack_length * self.nstack < self.nslice: print("nstack must divide the total path length") - assert self.nbins * self.nstack == self.nslice + assert self.stack_length * self.nstack == self.nslice self.dtype = dtype self.BT = BT @@ -42,9 +42,9 @@ def __init__( self.counter = 0 self.block = 0 - self.stack = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) - self.left = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) - self.right = numpy.zeros(shape=(self.nbins, 2, nbasis, nbasis), dtype=dtype) + self.stack = numpy.zeros((self.stack_length, 2, nbasis, nbasis), dtype=dtype) + self.left = numpy.zeros((self.stack_length, 2, nbasis, nbasis), dtype=dtype) + self.right = numpy.zeros((self.stack_length, 2, nbasis, nbasis), dtype=dtype) self.G = numpy.asarray([numpy.eye(self.nbasis, dtype=dtype), # Ga numpy.eye(self.nbasis, dtype=dtype)]) # Gb @@ -56,16 +56,16 @@ def __init__( # Global block matrix if self.lowrank: - self.Ql = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) - self.Dl = numpy.zeros(shape=(2, nbasis), dtype=dtype) - self.Tl = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + self.Ql = numpy.zeros((2, nbasis, nbasis), dtype=dtype) + self.Dl = numpy.zeros((2, nbasis), dtype=dtype) + self.Tl = numpy.zeros((2, nbasis, nbasis), dtype=dtype) - self.Qr = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) - self.Dr = numpy.zeros(shape=(2, nbasis), dtype=dtype) - self.Tr = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + self.Qr = numpy.zeros((2, nbasis, nbasis), dtype=dtype) + self.Dr = numpy.zeros((2, nbasis), dtype=dtype) + self.Tr = numpy.zeros((2, nbasis, nbasis), dtype=dtype) - self.CT = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) - self.theta = numpy.zeros(shape=(2, nbasis, nbasis), dtype=dtype) + self.CT = numpy.zeros((2, nbasis, nbasis), dtype=dtype) + self.theta = numpy.zeros((2, nbasis, nbasis), dtype=dtype) self.mT = nbasis self.buff_names, self.buff_size = get_numeric_names(self.__dict__) @@ -137,7 +137,7 @@ def set_all(self, BT): def reset(self): self.time_slice = 0 self.block = 0 - for i in range(0, self.nbins): + for i in range(0, self.stack_length): self.stack[i, 0] = numpy.identity(self.nbasis, dtype=self.dtype) self.stack[i, 1] = numpy.identity(self.nbasis, dtype=self.dtype) self.right[i, 0] = numpy.identity(self.nbasis, dtype=self.dtype) @@ -163,8 +163,8 @@ def initialize_left(self): self.Ql[spin] = numpy.identity(B[spin].shape[0]) self.Tl[spin] = numpy.identity(B[spin].shape[0]) - # for ix in range(2, self.nbins): - for ix in range(1, self.nbins): + # for ix in range(2, self.stack_length): + for ix in range(1, self.stack_length): B = self.stack[ix] C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) self.Dl[spin] = C2 @@ -175,7 +175,7 @@ def update(self, B): self.stack[self.block, 1] = numpy.identity(B.shape[-1], dtype=B.dtype) self.stack[self.block, 0] = B[0].dot(self.stack[self.block, 0]) self.stack[self.block, 1] = B[1].dot(self.stack[self.block, 1]) - self.time_slice = self.time_slice + 1 + self.time_slice += 1 self.block = self.time_slice // self.nstack self.counter = (self.counter + 1) % self.nstack @@ -210,8 +210,8 @@ def update_full_rank(self, B): self.stack[self.block, 0] = self.left[self.block, 0].dot(self.right[self.block, 0]) self.stack[self.block, 1] = self.left[self.block, 1].dot(self.right[self.block, 1]) - self.time_slice = self.time_slice + 1 # Count the time slice - self.block = self.time_slice // self.nstack # move to the next block if necessary + self.time_slice += 1 # Count the time slice + self.block = self.time_slice // self.nstack # Move to the next block if necessary self.counter = (self.counter + 1) % self.nstack # Counting within a stack def update_low_rank(self, B): @@ -383,6 +383,6 @@ def update_low_rank(self, B): # print("ovlp = {}".format(self.ovlp)) self.mT = mT - self.time_slice = self.time_slice + 1 # Count the time slice + self.time_slice += 1 # Count the time slice self.block = self.time_slice // self.nstack # move to the next block if necessary self.counter = (self.counter + 1) % self.nstack # Counting within a stack diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index bfc2d09f..32da2847 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -131,6 +131,16 @@ def calc_greens_function(self, iw, slice_ix=None, inplace=True): else: return greens_function_qr_strat(self, iw, slice_ix=slice_ix, inplace=inplace) + + def reset(self, trial): + self.weight = numpy.ones(self.nwalkers) + self.phase = numpy.ones(self.nwalkers, dtype=numpy.complex128) + + for iw in range(self.nwalkers): + self.stack[iw].reset() + self.stack[iw].set_all(trial.dmat) + self.calc_greens_function(iw) + # For compatibiltiy with BaseWalkers class. def reortho(self): pass From 96076c735e2ede51b1548f4e77b83c0154461b33 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 4 Jan 2024 12:17:55 +0800 Subject: [PATCH 40/84] Comment out for backwards compatibility. --- ipie/legacy/qmc/thermal_afqmc.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ipie/legacy/qmc/thermal_afqmc.py b/ipie/legacy/qmc/thermal_afqmc.py index f4e60a9c..2fb15e54 100644 --- a/ipie/legacy/qmc/thermal_afqmc.py +++ b/ipie/legacy/qmc/thermal_afqmc.py @@ -116,10 +116,10 @@ def __init__( self.sha1, self.branch, self.local_mods = get_git_info() else: self.sha1 = "None" - if verbose: - self.sys_info = print_env_info( - self.sha1, self.branch, self.local_mods, self.uuid, comm.size - ) + #if verbose: + # self.sys_info = print_env_info( + # self.sha1, self.branch, self.local_mods, self.uuid, comm.size + # ) # Hack - this is modified later if running in parallel on # initialisation. self.root = comm.rank == 0 From de505312f4f2ae1091ecb67e74ba49fcab7502a7 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Fri, 2 Feb 2024 16:17:52 -0500 Subject: [PATCH 41/84] Fix propagation bug in legacy. Add tests. Buffer sizing for MPI commmunication in progress. --- ipie/legacy/thermal_propagation/continuous.py | 7 +- ipie/thermal/propagation/phaseless_base.py | 1 - .../tests/test_generic_propagation.py | 2 +- .../tests/ueg/test_ueg_propagation.py | 2 +- ipie/thermal/qmc/tests/test_generic.py | 6 +- ipie/thermal/walkers/tests/test_buffers.py | 210 ++++++++++++ .../walkers/tests/test_population_control.py | 315 ++++++++++++++++++ 7 files changed, 536 insertions(+), 7 deletions(-) create mode 100644 ipie/thermal/walkers/tests/test_buffers.py create mode 100644 ipie/thermal/walkers/tests/test_population_control.py diff --git a/ipie/legacy/thermal_propagation/continuous.py b/ipie/legacy/thermal_propagation/continuous.py index 211a3796..6bac7af0 100644 --- a/ipie/legacy/thermal_propagation/continuous.py +++ b/ipie/legacy/thermal_propagation/continuous.py @@ -234,11 +234,16 @@ def propagate_walker_phaseless(self, system, walker, trial, eshift=0, xi=None): # Compute determinant ratio det(1+A')/det(1+A). # 1. Current walker's green's function. tix = walker.stack.ntime_slices + G = walker.greens_function(None, slice_ix=tix, inplace=False) # 2. Compute updated green's function. walker.stack.update_new(B) walker.greens_function(None, slice_ix=tix, inplace=True) # 3. Compute det(G/G') - M0 = walker.M0 + #M0 = walker.M0 + M0 = [ + scipy.linalg.det(G[0], check_finite=False), + scipy.linalg.det(G[1], check_finite=False) + ] Mnew = [ scipy.linalg.det(walker.G[0], check_finite=False), scipy.linalg.det(walker.G[1], check_finite=False), diff --git a/ipie/thermal/propagation/phaseless_base.py b/ipie/thermal/propagation/phaseless_base.py index ae67318c..34502ec4 100644 --- a/ipie/thermal/propagation/phaseless_base.py +++ b/ipie/thermal/propagation/phaseless_base.py @@ -301,7 +301,6 @@ def update_weight_legacy(self, walkers, iw, G, cfb, cmf, eshift): except ZeroDivisionError: walkers.weight[iw] = 0. - def apply_bound_force_bias(self, xbar, max_bound=1.0): absxbar = xp.abs(xbar) idx_to_rescale = absxbar > max_bound diff --git a/ipie/thermal/propagation/tests/test_generic_propagation.py b/ipie/thermal/propagation/tests/test_generic_propagation.py index a6e75e79..9262dfa2 100644 --- a/ipie/thermal/propagation/tests/test_generic_propagation.py +++ b/ipie/thermal/propagation/tests/test_generic_propagation.py @@ -43,7 +43,7 @@ def setup_objs(mf_trial=False, seed=None): mu = -10. beta = 0.02 dt = 0.01 - nwalkers = 2 + nwalkers = 10 blocks = 10 stabilise_freq = 10 pop_control_freq = 1 diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py b/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py index c7e8c4ee..d1c02c78 100644 --- a/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py +++ b/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py @@ -45,7 +45,7 @@ def setup_objs(seed=None): mu = -10. beta = 0.01 timestep = 0.002 - nwalkers = 1 + nwalkers = 10 nblocks = 10 stabilise_freq = 10 pop_control_freq = 1 diff --git a/ipie/thermal/qmc/tests/test_generic.py b/ipie/thermal/qmc/tests/test_generic.py index 77b4fddd..6051d31a 100644 --- a/ipie/thermal/qmc/tests/test_generic.py +++ b/ipie/thermal/qmc/tests/test_generic.py @@ -186,16 +186,16 @@ def test_thermal_afqmc(): nup = 5 ndown = 5 nelec = (nup, ndown) - nbasis = 10 + nbasis = 20 mu = -10.0 beta = 0.1 timestep = 0.01 - nwalkers = 1 + nwalkers = 10 seed = 7 # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! nsteps_per_block = 1 - nblocks = 8 + nblocks = 12 stabilize_freq = 10 pop_control_freq = 1 lowrank = False diff --git a/ipie/thermal/walkers/tests/test_buffers.py b/ipie/thermal/walkers/tests/test_buffers.py new file mode 100644 index 00000000..fbb16042 --- /dev/null +++ b/ipie/thermal/walkers/tests/test_buffers.py @@ -0,0 +1,210 @@ +import numpy +import pytest +from typing import Union + +from ipie.config import MPI +from ipie.utils.mpi import MPIHandler +from ipie.utils.testing import generate_hamiltonian +from ipie.walkers.pop_controller import get_buffer, set_buffer +from ipie.systems.generic import Generic +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.qmc.options import QMCOpts + +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers + +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.handler import Walkers + + +def setup_objs(mpi_handler, pop_control_method, seed=None): + nocca = 5 + noccb = 5 + nelec = (nocca, noccb) + nbasis = 10 + + mu = -10. + beta = 0.03 + timestep = 0.01 + nwalkers = 10 + nblocks = 3 + stabilize_freq = 10 + pop_control_freq = 1 + nsteps = 1 + + lowrank = False + verbose = True + complex_integrals = False + sym = 8 + if complex_integrals: sym = 4 + numpy.random.seed(seed) + + options = { + "qmc": { + "dt": timestep, + "nwalkers": nwalkers, + "blocks": nblocks, + "nsteps": nsteps, + "beta": beta, + "rng_seed": seed, + "stabilize_freq": stabilize_freq, + "batched": False, + }, + + "walkers": { + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method, + "low_rank": lowrank + }, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + } + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + #trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) + + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + walkers.buff_names = ['weight', 'unscaled_weight', 'phase', 'hybrid_energy', 'ovlp'] + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_system = Generic(nelec, verbose=verbose) + legacy_system.mu = mu + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, + verbose=verbose) + #legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep, + # verbose=verbose) + + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps + qmc_opts.dt = timestep + qmc_opts.seed = seed + + legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, + qmc_opts, walker_opts=options['walkers'], + verbose=verbose, comm=mpi_handler.comm) + + for iw in range(legacy_walkers.nwalkers): + legacy_walkers.walkers[iw].buff_names = walkers.buff_names + legacy_walkers.walkers[iw].buff_size = walkers.buff_size + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'nblocks': nblocks} + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers} + + return objs, legacy_objs + + +#@pytest.mark.unit +def test_get_buffer(): + mpi_handler = MPIHandler() + pop_control_method = 'stochastic_reconfiguration' + seed = 7 + objs, legacy_objs = setup_objs(mpi_handler, pop_control_method, seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + nblocks = objs['nblocks'] + + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + + print(f'\nwalkers.buff_names : \n{walkers.buff_names}\n') + print(f'legacy_walkers.buff_names : \n{legacy_walkers.walkers[0].buff_names}\n') + + # Test equivalence of `stack.__dict__`. + for iw in range(walkers.nwalkers): + for key in walkers.stack[iw].__dict__.keys(): + legacy_key = key + if key == 'nstack': legacy_key = 'stack_size' + elif key == 'nslice': legacy_key = 'ntime_slices' + elif key == 'stack_length': legacy_key = 'nbins' + val = walkers.stack[iw].__dict__[key] + legacy_val = legacy_walkers.walkers[iw].stack.__dict__[legacy_key] + + if isinstance(val, (int, float, complex, numpy.float64, numpy.complex128, numpy.ndarray)): + numpy.testing.assert_allclose(val, legacy_val) + + elif isinstance(val, str): + assert val == legacy_val + + else: continue + + # Test equivalence of `stack.get_buffer()` buffer size. + for iw in range(walkers.nwalkers): + buff = walkers.stack[iw].get_buffer() + legacy_buff = legacy_walkers.walkers[iw].stack.get_buffer() + assert buff.size == legacy_buff.size + + # Test equivalence of `walker.buff_names`. + assert walkers.buff_names == legacy_walkers.walkers[0].buff_names + + # Test equivalence of `walkers.get_buffer()` buffer size with the given + # `walkers.buff_names`. + for iw in range(walkers.nwalkers): + for name in walkers.buff_names: + val = walkers.__dict__[name] + legacy_val = legacy_walkers.walkers[iw].__dict__[name] + + if isinstance(val, (int, float, complex, numpy.float64, numpy.complex128, numpy.ndarray)): + numpy.testing.assert_allclose(val, legacy_val) + + elif isinstance(val, str): + assert val == legacy_val + + else: continue + + # + for iw in range(walkers.nwalkers): + buff = get_buffer(walkers, iw) + legacy_buff = legacy_walkers.walkers[iw].get_buffer() + assert buff.size == legacy_buff.size + + +if __name__ == "__main__": + test_get_buffer() + diff --git a/ipie/thermal/walkers/tests/test_population_control.py b/ipie/thermal/walkers/tests/test_population_control.py new file mode 100644 index 00000000..dfac601f --- /dev/null +++ b/ipie/thermal/walkers/tests/test_population_control.py @@ -0,0 +1,315 @@ +import numpy +import pytest +from typing import Union + +from ipie.config import MPI +from ipie.utils.mpi import MPIHandler +from ipie.utils.testing import generate_hamiltonian +from ipie.walkers.pop_controller import PopController +from ipie.systems.generic import Generic +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.qmc.options import QMCOpts + +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric + +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.handler import Walkers +from ipie.legacy.thermal_propagation.continuous import Continuous + + +def legacy_propagate_walkers(legacy_hamiltonian, + legacy_trial, + legacy_walkers, + legacy_propagator, + xi=None): + if xi is None: + xi = [None] * legacy_walkers.nwalkers + + for iw, walker in enumerate(legacy_walkers.walkers): + legacy_propagator.propagate_walker_phaseless( + legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) + + return legacy_walkers + + +def setup_objs(mpi_handler, pop_control_method, seed=None): + nocca = 5 + noccb = 5 + nelec = (nocca, noccb) + nbasis = 10 + + mu = -10. + beta = 0.03 + timestep = 0.01 + nwalkers = 10 + nblocks = 3 + stabilize_freq = 10 + pop_control_freq = 1 + nsteps = 1 + + lowrank = False + verbose = True + complex_integrals = False + sym = 8 + if complex_integrals: sym = 4 + numpy.random.seed(seed) + + options = { + "qmc": { + "dt": timestep, + "nwalkers": nwalkers, + "blocks": nblocks, + "nsteps": nsteps, + "beta": beta, + "rng_seed": seed, + "stabilize_freq": stabilize_freq, + "batched": False, + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method, + "low_rank": lowrank + }, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + } + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + #trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) + + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + pcontrol = PopController(nwalkers, nsteps, mpi_handler, pop_control_method, verbose=verbose) + + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_system = Generic(nelec, verbose=verbose) + legacy_system.mu = mu + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, + verbose=verbose) + #legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep, + # verbose=verbose) + + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps + qmc_opts.dt = timestep + qmc_opts.seed = seed + + legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, + qmc_opts, walker_opts=options['walkers'], + verbose=verbose, comm=mpi_handler.comm) + + legacy_propagator = Continuous( + options["propagator"], qmc_opts, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose, + lowrank=lowrank) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator, + 'pcontrol': pcontrol, + 'nblocks': nblocks} + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers, + 'propagator': legacy_propagator} + + return objs, legacy_objs + + +@pytest.mark.unit +def test_pair_branch_batch(): + mpi_handler = MPIHandler() + pop_control_method = 'pair_branch' + seed = 7 + objs, legacy_objs = setup_objs(mpi_handler, pop_control_method, seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + pcontrol = objs['pcontrol'] + nblocks = objs['nblocks'] + + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + for block in range(nblocks): + for t in range(walkers.stack[0].nslice): + print('\n------------------------------------------') + print(f'block = {block}, t = {t}') + print(f'walkers.weight[0] = {walkers.weight[0]}') + print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') + print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') + print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') + print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') + print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') + + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, xi=propagator.xi) + + if t > 0: + pcontrol.pop_control(walkers, mpi_handler.comm) + legacy_walkers.pop_control(mpi_handler.comm) + + walkers.reset(trial) # Reset stack, weights, phase. + legacy_walkers.reset(legacy_trial) + + for iw in range(walkers.nwalkers): + assert numpy.allclose(walkers.Ga[iw], legacy_walkers.walkers[iw].G[0]) + assert numpy.allclose(walkers.Gb[iw], legacy_walkers.walkers[iw].G[1]) + assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) + assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) + +#@pytest.mark.unit +def test_comb_batch(): + mpi_handler = MPIHandler() + pop_control_method = 'comb' + seed = 7 + objs, legacy_objs = setup_objs(mpi_handler, pop_control_method, seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + pcontrol = objs['pcontrol'] + nblocks = objs['nblocks'] + + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + for block in range(nblocks): + for t in range(walkers.stack[0].nslice): + print('\n------------------------------------------') + print(f'block = {block}, t = {t}') + print(f'walkers.weight[0] = {walkers.weight[0]}') + print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') + print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') + print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') + print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') + print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') + + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, xi=propagator.xi) + + if t > 0: + pcontrol.pop_control(walkers, mpi_handler.comm) + legacy_walkers.pop_control(mpi_handler.comm) + + walkers.reset(trial) # Reset stack, weights, phase. + legacy_walkers.reset(legacy_trial) + + for iw in range(walkers.nwalkers): + assert numpy.allclose(walkers.Ga[iw], legacy_walkers.walkers[iw].G[0]) + assert numpy.allclose(walkers.Gb[iw], legacy_walkers.walkers[iw].G[1]) + assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) + assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) + +#@pytest.mark.unit +def test_stochastic_reconfiguration_batch(): + mpi_handler = MPIHandler() + pop_control_method = 'stochastic_reconfiguration' + seed = 7 + objs, legacy_objs = setup_objs(mpi_handler, pop_control_method, seed=seed) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + pcontrol = objs['pcontrol'] + nblocks = objs['nblocks'] + + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + for block in range(nblocks): + for t in range(walkers.stack[0].nslice): + print('\n------------------------------------------') + print(f'block = {block}, t = {t}') + print(f'walkers.weight[0] = {walkers.weight[0]}') + print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') + print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') + print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') + print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') + print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') + + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, xi=propagator.xi) + + if t > 0: + pcontrol.pop_control(walkers, mpi_handler.comm) + legacy_walkers.pop_control(mpi_handler.comm) + + walkers.reset(trial) # Reset stack, weights, phase. + legacy_walkers.reset(legacy_trial) + + for iw in range(walkers.nwalkers): + assert numpy.allclose(walkers.Ga[iw], legacy_walkers.walkers[iw].G[0]) + assert numpy.allclose(walkers.Gb[iw], legacy_walkers.walkers[iw].G[1]) + assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) + assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) + +if __name__ == "__main__": + test_pair_branch_batch() + #test_comb_batch() + #test_stochastic_reconfiguration_batch() From 6c83d86d7089fb33f5b4ebe43edf0993c22f4b31 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 25 Feb 2024 18:43:44 -0500 Subject: [PATCH 42/84] Fixed buffer sizing for FT-AFQMC and MPI, specifically for the `comb` population control function. However, MPI doesn't work for now. Fixed weight update code in legacy for both `generic` and `planewave` thermal propagation. --- ipie/legacy/thermal_propagation/continuous.py | 1 - ipie/legacy/thermal_propagation/planewave.py | 5 +- .../tests/ueg/test_ueg_propagation.py | 4 +- ipie/thermal/qmc/tests/test_generic.py | 18 +- ipie/thermal/qmc/tests/ueg/test_ueg.py | 183 +++++++++++++-- ipie/thermal/qmc/thermal_afqmc.py | 6 - .../ft_ueg_ecut1.0_rs1.0/input.json | 2 +- .../ft_ueg_ecut1.0_rs1.0/input_1walker.json | 32 +++ ipie/thermal/walkers/stack.py | 4 +- ipie/thermal/walkers/tests/test_buffers.py | 210 ------------------ .../walkers/tests/test_population_control.py | 2 +- ipie/thermal/walkers/uhf_walkers.py | 6 +- ipie/trial_wavefunction/single_det.py | 2 +- .../tests/test_single_det_trial.py | 4 +- ipie/walkers/pop_controller.py | 59 ++--- ipie/walkers/tests/test_population_control.py | 4 + 16 files changed, 256 insertions(+), 286 deletions(-) create mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input_1walker.json delete mode 100644 ipie/thermal/walkers/tests/test_buffers.py diff --git a/ipie/legacy/thermal_propagation/continuous.py b/ipie/legacy/thermal_propagation/continuous.py index 6bac7af0..68653baf 100644 --- a/ipie/legacy/thermal_propagation/continuous.py +++ b/ipie/legacy/thermal_propagation/continuous.py @@ -239,7 +239,6 @@ def propagate_walker_phaseless(self, system, walker, trial, eshift=0, xi=None): walker.stack.update_new(B) walker.greens_function(None, slice_ix=tix, inplace=True) # 3. Compute det(G/G') - #M0 = walker.M0 M0 = [ scipy.linalg.det(G[0], check_finite=False), scipy.linalg.det(G[1], check_finite=False) diff --git a/ipie/legacy/thermal_propagation/planewave.py b/ipie/legacy/thermal_propagation/planewave.py index 0fef03e8..a0a92871 100644 --- a/ipie/legacy/thermal_propagation/planewave.py +++ b/ipie/legacy/thermal_propagation/planewave.py @@ -525,7 +525,10 @@ def propagate_walker_phaseless_full_rank(self, hamiltonian, walker, trial, eshif walker.greens_function(None, slice_ix=tix, inplace=True) # 3. Compute det(G/G') - M0 = walker.M0 + M0 = [ + scipy.linalg.det(G[0], check_finite=False), + scipy.linalg.det(G[1], check_finite=False) + ] Mnew = numpy.array( [ scipy.linalg.det(walker.G[0], check_finite=False), diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py b/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py index d1c02c78..c39e1654 100644 --- a/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py +++ b/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py @@ -45,8 +45,8 @@ def setup_objs(seed=None): mu = -10. beta = 0.01 timestep = 0.002 - nwalkers = 10 - nblocks = 10 + nwalkers = 3 + nblocks = 2 stabilise_freq = 10 pop_control_freq = 1 nsteps_per_block = 1 diff --git a/ipie/thermal/qmc/tests/test_generic.py b/ipie/thermal/qmc/tests/test_generic.py index 6051d31a..d1209acb 100644 --- a/ipie/thermal/qmc/tests/test_generic.py +++ b/ipie/thermal/qmc/tests/test_generic.py @@ -28,6 +28,7 @@ from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.walkers.handler import Walkers from ipie.legacy.walkers.thermal import ThermalWalker from ipie.legacy.thermal_propagation.continuous import Continuous from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky @@ -63,6 +64,7 @@ def build_driver_test_instance(options: Union[dict, None], nblocks = options['nblocks'] stabilize_freq = options['stabilize_freq'] pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] lowrank = options['lowrank'] numpy.random.seed(seed) @@ -78,6 +80,7 @@ def build_driver_test_instance(options: Union[dict, None], beta=beta, num_stblz=stabilize_freq, pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, rng_seed=seed) system = Generic(nelec=nelec) @@ -119,6 +122,7 @@ def build_legacy_driver_instance(hamiltonian, nblocks = options['nblocks'] stabilize_freq = options['stabilize_freq'] pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] lowrank = options['lowrank'] numpy.random.seed(seed) @@ -140,7 +144,9 @@ def build_legacy_driver_instance(hamiltonian, }, "walkers": { - "low_rank": lowrank + "low_rank": lowrank, + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method }, "system": { @@ -168,13 +174,6 @@ def build_legacy_driver_instance(hamiltonian, legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep) - legacy_walkers = [ - ThermalWalker( - legacy_system, legacy_hamiltonian, legacy_trial, - walker_opts=options, verbose=i == 0) for i in range(nwalkers)] - - #legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( - # (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, legacy_hamiltonian, legacy_trial, verbose=verbose) return afqmc @@ -198,6 +197,8 @@ def test_thermal_afqmc(): nblocks = 12 stabilize_freq = 10 pop_control_freq = 1 + pop_control_method = 'pair_branch' + #pop_control_method = 'comb' lowrank = False verbose = True debug = True @@ -215,6 +216,7 @@ def test_thermal_afqmc(): 'nblocks': nblocks, 'stabilize_freq': stabilize_freq, 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, 'lowrank': lowrank, "hamiltonian": { diff --git a/ipie/thermal/qmc/tests/ueg/test_ueg.py b/ipie/thermal/qmc/tests/ueg/test_ueg.py index 331fee9c..f29745b5 100644 --- a/ipie/thermal/qmc/tests/ueg/test_ueg.py +++ b/ipie/thermal/qmc/tests/ueg/test_ueg.py @@ -97,6 +97,7 @@ def build_driver_test_instance(ueg: UEG, nblocks = options['nblocks'] stabilize_freq = options['stabilize_freq'] pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] lowrank = options['lowrank'] numpy.random.seed(seed) @@ -118,6 +119,7 @@ def build_driver_test_instance(ueg: UEG, beta=beta, num_stblz=stabilize_freq, pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, rng_seed=seed) print('\n----------------------------') @@ -169,6 +171,7 @@ def build_legacy_driver_instance(hamiltonian, nblocks = options['nblocks'] stabilize_freq = options['stabilize_freq'] pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] lowrank = options['lowrank'] numpy.random.seed(seed) @@ -190,7 +193,9 @@ def build_legacy_driver_instance(hamiltonian, }, "walkers": { - "low_rank": lowrank + "low_rank": lowrank, + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method }, "ueg_opts": options["ueg_opts"], @@ -210,30 +215,14 @@ def build_legacy_driver_instance(hamiltonian, # 3. Build trial. legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) - # 4. Build walkers. - legacy_walkers = [ - ThermalWalker( - legacy_system, legacy_hamiltonian, legacy_trial, - walker_opts=legacy_options, verbose=i == 0) for i in range(nwalkers)] - - # 5. Build propagator. - qmc_opts = QMCOpts() - qmc_opts.nwalkers = nwalkers - qmc_opts.ntot_walkers = nwalkers - qmc_opts.beta = beta - qmc_opts.nsteps = nsteps_per_block - qmc_opts.dt = timestep - qmc_opts.seed = seed - - legacy_propagator = PlaneWave(legacy_system, legacy_hamiltonian, legacy_trial, qmc_opts, - options=legacy_options["propagator"], lowrank=lowrank, verbose=verbose) + # 4. Build Thermal AFQMC. afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, legacy_hamiltonian, legacy_trial, verbose=verbose) return afqmc @pytest.mark.unit -def test_thermal_afqmc(against_ref=False): +def test_thermal_afqmc_1walker(against_ref=False): # Thermal AFQMC params. seed = 7 mu = -1. @@ -245,6 +234,10 @@ def test_thermal_afqmc(against_ref=False): nblocks = 11 stabilize_freq = 10 pop_control_freq = 1 + + # `pop_control_method` doesn't matter for 1 walker. + pop_control_method = "pair_branch" + #pop_control_method = "comb" lowrank = False verbose = True debug = True @@ -288,6 +281,7 @@ def test_thermal_afqmc(against_ref=False): 'nblocks': nblocks, 'stabilize_freq': stabilize_freq, 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, 'lowrank': lowrank, "hamiltonian": { @@ -414,9 +408,156 @@ def test_thermal_afqmc(against_ref=False): print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") if local_err_count == 0: - print(f"\n*** PASSED : {test_name} ***") + print(f"\n*** PASSED : {test_name} ***\n") + +@pytest.mark.unit +def test_thermal_afqmc(): + # Thermal AFQMC params. + seed = 7 + mu = -1. + beta = 0.1 + timestep = 0.01 + nwalkers = 32 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 11 + stabilize_freq = 10 + pop_control_freq = 1 + pop_control_method = "pair_branch" + #pop_control_method = "comb" + lowrank = False + verbose = True + debug = True + numpy.random.seed(seed) + + with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: + ueg_opts = { + "nup": 7, + "ndown": 7, + "rs": 1., + "ecut": 1., + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + } + + # Generate UEG integrals. + ueg = UEG(ueg_opts, verbose=verbose) + ueg.build(verbose=verbose) + nbasis = ueg.nbasis + nchol = ueg.nchol + nelec = (ueg.nup, ueg.ndown) + nup, ndown = nelec + + if verbose: + print(f"# nbasis = {nbasis}") + print(f"# nchol = {nchol}") + print(f"# nup = {nup}") + print(f"# ndown = {ndown}") + + # --------------------------------------------------------------------- + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + + "hamiltonian": { + "name": "UEG", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "estimators": { + "filename": tmpf2.name, # For legacy. + }, + + "ueg_opts": ueg_opts + } + + # --------------------------------------------------------------------- + # Test. + # --------------------------------------------------------------------- + print('\n-----------------------') + print('Running ThermalAFQMC...') + print('-----------------------') + afqmc, hamiltonian, walkers = build_driver_test_instance(ueg, options, seed, debug, verbose) + afqmc.run(walkers, verbose, estimator_filename=tmpf1.name) + afqmc.finalise() + afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + + test_energy_data = extract_observable(afqmc.estimators.filename, "energy") + test_energy_numer = afqmc.estimators["energy"]["ENumer"] + test_energy_denom = afqmc.estimators["energy"]["EDenom"] + test_number_data = extract_observable(afqmc.estimators.filename, "nav") + + # --------------------------------------------------------------------- + # Legacy. + # --------------------------------------------------------------------- + print('\n------------------------------') + print('Running Legacy ThermalAFQMC...') + print('------------------------------') + legacy_afqmc = build_legacy_driver_instance(hamiltonian, options, seed, verbose) + legacy_afqmc.run(comm=comm) + legacy_afqmc.finalise(verbose=False) + legacy_afqmc.estimators.estimators["mixed"].update( + legacy_afqmc.qmc, + legacy_afqmc.system, + legacy_afqmc.hamiltonian, + legacy_afqmc.trial, + legacy_afqmc.walk, + 0, + legacy_afqmc.propagators.free_projection) + legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) + + enum = legacy_afqmc.estimators.estimators["mixed"].names + legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] + legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] + + # --------------------------------------------------------------------- + if verbose: + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(f'test filename: {afqmc.estimators.filename}') + print(f'legacy filename: {legacy_afqmc.estimators.filename}') + print(f'\ntest_energy_data: \n{test_energy_data}\n') + print(f'test_number_data: \n{test_number_data}\n') + print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') + + assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) + assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) + assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) + + assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) + assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) + assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) + assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) + assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) + assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) + assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) + assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) + assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) if __name__ == '__main__': - test_thermal_afqmc(against_ref=True) + test_thermal_afqmc_1walker(against_ref=True) + test_thermal_afqmc() diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index 3a59a402..f7f38dbe 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -182,9 +182,6 @@ def run(self, comm = self.mpi_handler.comm self.tsetup += time.time() - ft_setup - - print(f'comm.size = {comm.size}') - print(f'comm.rank = {comm.rank}') # Propagate. nwalkers = self.walkers.nwalkers @@ -195,9 +192,6 @@ def run(self, neqlb_steps = 2.0 / self.params.timestep nslices = numpy.rint(self.params.beta / self.params.timestep).astype(int) - print(f'total_steps = {total_steps}') - print(f'nslices = {nslices}') - for step in range(1, total_steps + 1): start_path = time.time() diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json index 7f7aa195..65f888c9 100644 --- a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json +++ b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json @@ -9,7 +9,7 @@ }, "qmc": { "dt": 0.01, - "nwalkers": 1, + "nwalkers": 32, "blocks": 10, "nsteps": 10, "beta": 0.1, diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input_1walker.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input_1walker.json new file mode 100644 index 00000000..7f7aa195 --- /dev/null +++ b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input_1walker.json @@ -0,0 +1,32 @@ +{ + "system": { + "name": "UEG", + "nup": 7, + "ndown": 7, + "rs": 1.0, + "mu": -1.0, + "ecut": 1.0 + }, + "qmc": { + "dt": 0.01, + "nwalkers": 1, + "blocks": 10, + "nsteps": 10, + "beta": 0.1, + "rng_seed": 7, + "pop_control_freq": 1, + "stabilise_freq": 10, + "batched": false + }, + "trial": { + "name": "one_body" + }, + "walkers": { + "population_control": "pair_branch" + }, + "estimators": { + "mixed": { + "one_rdm": true + } + } +} diff --git a/ipie/thermal/walkers/stack.py b/ipie/thermal/walkers/stack.py index 1d8e6991..529c284a 100644 --- a/ipie/thermal/walkers/stack.py +++ b/ipie/thermal/walkers/stack.py @@ -69,7 +69,9 @@ def __init__( self.mT = nbasis self.buff_names, self.buff_size = get_numeric_names(self.__dict__) - # set all entries to be the identity matrix + self.stack_buffer = numpy.zeros(self.buff_size, dtype=numpy.complex128) + + # Set all entries to be the identity matrix self.reset() def get(self, ix): diff --git a/ipie/thermal/walkers/tests/test_buffers.py b/ipie/thermal/walkers/tests/test_buffers.py deleted file mode 100644 index fbb16042..00000000 --- a/ipie/thermal/walkers/tests/test_buffers.py +++ /dev/null @@ -1,210 +0,0 @@ -import numpy -import pytest -from typing import Union - -from ipie.config import MPI -from ipie.utils.mpi import MPIHandler -from ipie.utils.testing import generate_hamiltonian -from ipie.walkers.pop_controller import get_buffer, set_buffer -from ipie.systems.generic import Generic -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.qmc.options import QMCOpts - -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers - -from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.handler import Walkers - - -def setup_objs(mpi_handler, pop_control_method, seed=None): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) - nbasis = 10 - - mu = -10. - beta = 0.03 - timestep = 0.01 - nwalkers = 10 - nblocks = 3 - stabilize_freq = 10 - pop_control_freq = 1 - nsteps = 1 - - lowrank = False - verbose = True - complex_integrals = False - sym = 8 - if complex_integrals: sym = 4 - numpy.random.seed(seed) - - options = { - "qmc": { - "dt": timestep, - "nwalkers": nwalkers, - "blocks": nblocks, - "nsteps": nsteps, - "beta": beta, - "rng_seed": seed, - "stabilize_freq": stabilize_freq, - "batched": False, - }, - - "walkers": { - "pop_control_freq": pop_control_freq, - "pop_control": pop_control_method, - "low_rank": lowrank - }, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - } - } - - # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, - sym=sym, tol=1e-10) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nbasis**2)).T.copy(), - ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - - trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) - #trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) - - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) - walkers.buff_names = ['weight', 'unscaled_weight', 'phase', 'hybrid_energy', 'ovlp'] - - # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_system = Generic(nelec, verbose=verbose) - legacy_system.mu = mu - legacy_hamiltonian = LegacyHamGeneric( - h1e=hamiltonian.H1, - chol=hamiltonian.chol, - ecore=hamiltonian.ecore) - legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) - legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, - verbose=verbose) - #legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep, - # verbose=verbose) - - qmc_opts = QMCOpts() - qmc_opts.nwalkers = nwalkers - qmc_opts.ntot_walkers = nwalkers - qmc_opts.beta = beta - qmc_opts.nsteps = nsteps - qmc_opts.dt = timestep - qmc_opts.seed = seed - - legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, - qmc_opts, walker_opts=options['walkers'], - verbose=verbose, comm=mpi_handler.comm) - - for iw in range(legacy_walkers.nwalkers): - legacy_walkers.walkers[iw].buff_names = walkers.buff_names - legacy_walkers.walkers[iw].buff_size = walkers.buff_size - - objs = {'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers, - 'nblocks': nblocks} - - legacy_objs = {'system': legacy_system, - 'trial': legacy_trial, - 'hamiltonian': legacy_hamiltonian, - 'walkers': legacy_walkers} - - return objs, legacy_objs - - -#@pytest.mark.unit -def test_get_buffer(): - mpi_handler = MPIHandler() - pop_control_method = 'stochastic_reconfiguration' - seed = 7 - objs, legacy_objs = setup_objs(mpi_handler, pop_control_method, seed=seed) - trial = objs['trial'] - hamiltonian = objs['hamiltonian'] - walkers = objs['walkers'] - nblocks = objs['nblocks'] - - legacy_system = legacy_objs['system'] - legacy_trial = legacy_objs['trial'] - legacy_hamiltonian = legacy_objs['hamiltonian'] - legacy_walkers = legacy_objs['walkers'] - - print(f'\nwalkers.buff_names : \n{walkers.buff_names}\n') - print(f'legacy_walkers.buff_names : \n{legacy_walkers.walkers[0].buff_names}\n') - - # Test equivalence of `stack.__dict__`. - for iw in range(walkers.nwalkers): - for key in walkers.stack[iw].__dict__.keys(): - legacy_key = key - if key == 'nstack': legacy_key = 'stack_size' - elif key == 'nslice': legacy_key = 'ntime_slices' - elif key == 'stack_length': legacy_key = 'nbins' - val = walkers.stack[iw].__dict__[key] - legacy_val = legacy_walkers.walkers[iw].stack.__dict__[legacy_key] - - if isinstance(val, (int, float, complex, numpy.float64, numpy.complex128, numpy.ndarray)): - numpy.testing.assert_allclose(val, legacy_val) - - elif isinstance(val, str): - assert val == legacy_val - - else: continue - - # Test equivalence of `stack.get_buffer()` buffer size. - for iw in range(walkers.nwalkers): - buff = walkers.stack[iw].get_buffer() - legacy_buff = legacy_walkers.walkers[iw].stack.get_buffer() - assert buff.size == legacy_buff.size - - # Test equivalence of `walker.buff_names`. - assert walkers.buff_names == legacy_walkers.walkers[0].buff_names - - # Test equivalence of `walkers.get_buffer()` buffer size with the given - # `walkers.buff_names`. - for iw in range(walkers.nwalkers): - for name in walkers.buff_names: - val = walkers.__dict__[name] - legacy_val = legacy_walkers.walkers[iw].__dict__[name] - - if isinstance(val, (int, float, complex, numpy.float64, numpy.complex128, numpy.ndarray)): - numpy.testing.assert_allclose(val, legacy_val) - - elif isinstance(val, str): - assert val == legacy_val - - else: continue - - # - for iw in range(walkers.nwalkers): - buff = get_buffer(walkers, iw) - legacy_buff = legacy_walkers.walkers[iw].get_buffer() - assert buff.size == legacy_buff.size - - -if __name__ == "__main__": - test_get_buffer() - diff --git a/ipie/thermal/walkers/tests/test_population_control.py b/ipie/thermal/walkers/tests/test_population_control.py index dfac601f..03be42d9 100644 --- a/ipie/thermal/walkers/tests/test_population_control.py +++ b/ipie/thermal/walkers/tests/test_population_control.py @@ -44,7 +44,7 @@ def setup_objs(mpi_handler, pop_control_method, seed=None): nbasis = 10 mu = -10. - beta = 0.03 + beta = 0.1 timestep = 0.01 nwalkers = 10 nblocks = 3 diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/thermal/walkers/uhf_walkers.py index 32da2847..7eeedc9a 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/thermal/walkers/uhf_walkers.py @@ -119,8 +119,10 @@ def __init__( nav = particle_number(P) print(f"# Trial electron number for {iw}-th walker: {nav}") - self.buff_names, self.buff_size = get_numeric_names(self.__dict__) - + #self.buff_names, self.buff_size = get_numeric_names(self.__dict__) + self.buff_names += ["Ga", "Gb"] + self.buff_size = round(self.set_buff_size_single_walker() / float(self.nwalkers)) + self.walker_buffer = numpy.zeros(self.buff_size, dtype=numpy.complex128) def calc_greens_function(self, iw, slice_ix=None, inplace=True): """Return the Green's function for walker `iw`. diff --git a/ipie/trial_wavefunction/single_det.py b/ipie/trial_wavefunction/single_det.py index 3f778703..052f0c39 100644 --- a/ipie/trial_wavefunction/single_det.py +++ b/ipie/trial_wavefunction/single_det.py @@ -37,7 +37,7 @@ def __init__(self, wavefunction, num_elec, num_basis, cplx=False, verbose=False) self._max_num_dets = 1 imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) if (not cplx) and (imag_norm <= 1e-8): - #print("# making trial wavefunction MO coefficient real") + #print("# making trial wavefunction MO coefficient real") self.psi = numpy.array(self.psi.real, dtype=numpy.float64) self.psi0a = self.psi[:, : self.nalpha] diff --git a/ipie/trial_wavefunction/tests/test_single_det_trial.py b/ipie/trial_wavefunction/tests/test_single_det_trial.py index 96a4e524..97125309 100644 --- a/ipie/trial_wavefunction/tests/test_single_det_trial.py +++ b/ipie/trial_wavefunction/tests/test_single_det_trial.py @@ -40,7 +40,7 @@ def test_single_det(): assert trial._rH1b.shape == (nbeta, nbasis) -@pytest.mark.unit +#@pytest.mark.unit def test_single_det_ghf(): nbasis = 10 naux = 5 * nbasis @@ -135,5 +135,5 @@ def test_single_det_all_up(): if __name__ == "__main__": test_single_det() - test_single_det_ghf() + #test_single_det_ghf() test_single_det_all_up() diff --git a/ipie/walkers/pop_controller.py b/ipie/walkers/pop_controller.py index dd76b4c4..9754e678 100644 --- a/ipie/walkers/pop_controller.py +++ b/ipie/walkers/pop_controller.py @@ -4,7 +4,7 @@ from ipie.config import MPI from ipie.utils.backend import arraylib as xp - +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers class PopControllerTimer: def __init__(self): @@ -136,7 +136,7 @@ def get_buffer(walkers, iw): buff = numpy.zeros(walkers.buff_size, dtype=numpy.complex128) for d in walkers.buff_names: data = walkers.__dict__[d] - if data is None: + if (data is None) or isinstance(data, (int, float, complex, numpy.float64, numpy.complex128)): continue assert data.size % walkers.nwalkers == 0 # Only walker-specific data is being communicated if isinstance(data[iw], (xp.ndarray)): @@ -153,6 +153,11 @@ def get_buffer(walkers, iw): else: buff[s : s + 1] = xp.array(data[iw]) s += 1 + + if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): + stack_buff = walkers.stack[iw].get_buffer() + buff = numpy.concatenate((buff, stack_buff)) + return buff @@ -166,20 +171,18 @@ def set_buffer(walkers, iw, buff): s = 0 for d in walkers.buff_names: data = walkers.__dict__[d] - if data is None: + if (data is None) or isinstance(data, (int, float, complex, numpy.float64, numpy.complex128)): continue assert data.size % walkers.nwalkers == 0 # Only walker-specific data is being communicated if isinstance(data[iw], xp.ndarray): walkers.__dict__[d][iw] = xp.array( - buff[s : s + data[iw].size].reshape(data[iw].shape).copy() - ) + buff[s : s + data[iw].size].reshape(data[iw].shape).copy()) s += data[iw].size elif isinstance(data[iw], list): for ix, l in enumerate(data[iw]): if isinstance(l, (xp.ndarray)): walkers.__dict__[d][iw][ix] = xp.array( - buff[s : s + l.size].reshape(l.shape).copy() - ) + buff[s : s + l.size].reshape(l.shape).copy()) s += l.size elif isinstance(l, (int, float, complex)): walkers.__dict__[d][iw][ix] = buff[s] @@ -192,6 +195,9 @@ def set_buffer(walkers, iw, buff): else: walkers.__dict__[d][iw] = buff[s] s += 1 + + if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): + walkers.stack[iw].set_buffer(buff[walkers.buff_size:]) def comb(walkers, comm, weights, target_weight, timer=PopControllerTimer()): @@ -270,14 +276,22 @@ def comb(walkers, comm, weights, target_weight, timer=PopControllerTimer()): source_proc = c // walkers.nwalkers # Location of walker to kill in local list of walkers. kill_pos = k % walkers.nwalkers + buffer = walkers.walker_buffer timer.add_non_communication() timer.start_time() - comm.Recv(walkers.walker_buffer, source=source_proc, tag=i) + + if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): + buffer = numpy.concatenate((walkers.walker_buffer, walkers.stack[0].stack_buffer)) + comm.Recv(buffer, source=source_proc, tag=i) + + else: + comm.Recv(buffer, source=source_proc, tag=i) + # with h5py.File('walkers_recv.h5', 'w') as fh5: # fh5['walk_{}'.format(k)] = walkers.walker_buffer.copy() timer.add_recv_time() timer.start_time() - set_buffer(walkers, kill_pos, walkers.walker_buffer) + set_buffer(walkers, kill_pos, buffer) timer.add_non_communication() # with h5py.File('after_{}.h5'.format(comm.rank), 'a') as fh5: # fh5['walker_{}_{}_{}'.format(c,k,comm.rank)] = walkers.walkers[kill_pos].get_buffer() @@ -316,19 +330,16 @@ def pair_branch(walkers, comm, max_weight, min_weight, timer=PopControllerTimer( glob_inf_1.fill(1) glob_inf_2 = numpy.array( [[r for i in range(walkers.nwalkers)] for r in range(comm.size)], - dtype=numpy.int64, - ) + dtype=numpy.int64) glob_inf_3 = numpy.array( [[r for i in range(walkers.nwalkers)] for r in range(comm.size)], - dtype=numpy.int64, - ) + dtype=numpy.int64) timer.add_non_communication() timer.start_time() - comm.Gather( - walker_info_0, glob_inf_0, root=0 - ) # gather |w_i| from all processors (comm.size x nwalkers) + # Gather |w_i| from all processors (comm.size x nwalkers) + comm.Gather(walker_info_0, glob_inf_0, root=0) timer.add_communication() # Want same random number seed used on all processors @@ -337,19 +348,9 @@ def pair_branch(walkers, comm, max_weight, min_weight, timer=PopControllerTimer( # Rescale weights. glob_inf = numpy.zeros((walkers.nwalkers * comm.size, 4), dtype=numpy.float64) glob_inf[:, 0] = glob_inf_0.ravel() # contains walker |w_i| - glob_inf[ - :, 1 - ] = glob_inf_1.ravel() # all initialized to 1 when it becomes 2 then it will be "branched" - glob_inf[ - :, 2 - ] = ( - glob_inf_2.ravel() - ) # contain processor+walker indices (initial) (i.e., where walkers live) - glob_inf[ - :, 3 - ] = ( - glob_inf_3.ravel() - ) # contain processor+walker indices (final) (i.e., where walkers live) + glob_inf[:, 1] = glob_inf_1.ravel() # all initialized to 1 when it becomes 2 then it will be "branched" + glob_inf[:, 2] = glob_inf_2.ravel() # contain processor+walker indices (initial) (i.e., where walkers live) + glob_inf[:, 3] = glob_inf_3.ravel() # contain processor+walker indices (final) (i.e., where walkers live) sort = numpy.argsort(glob_inf[:, 0], kind="mergesort") isort = numpy.argsort(sort, kind="mergesort") glob_inf = glob_inf[sort] diff --git a/ipie/walkers/tests/test_population_control.py b/ipie/walkers/tests/test_population_control.py index 4dcd6374..1ee26d5f 100644 --- a/ipie/walkers/tests/test_population_control.py +++ b/ipie/walkers/tests/test_population_control.py @@ -68,6 +68,10 @@ def test_pair_branch_batch(): batched_data.walkers.weight[iw], legacy_data.walker_handler.walkers[iw].weight, ) + assert numpy.allclose( + batched_data.walkers.unscaled_weight[iw], + legacy_data.walker_handler.walkers[iw].unscaled_weight, + ) assert pytest.approx(batched_data.walkers.weight[0]) == 0.2571750688329709 assert pytest.approx(batched_data.walkers.weight[1]) == 1.0843219322894988 From 54d4acdab294a760efebaa87627dc4509b8f4679 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Mon, 4 Mar 2024 16:31:06 -0600 Subject: [PATCH 43/84] remove `ueg` in `ipie/systems` and ft tests in `ipie/qmc/tests` --- ipie/qmc/tests/test_ft_integration.py | 117 --------------------- ipie/qmc/tests/test_ft_mpi_integration.py | 121 ---------------------- ipie/systems/__init__.py | 1 - ipie/systems/tests/test_ueg.py | 65 ------------ ipie/systems/ueg.py | 95 ----------------- 5 files changed, 399 deletions(-) delete mode 100644 ipie/qmc/tests/test_ft_integration.py delete mode 100644 ipie/qmc/tests/test_ft_mpi_integration.py delete mode 100644 ipie/systems/tests/test_ueg.py delete mode 100644 ipie/systems/ueg.py diff --git a/ipie/qmc/tests/test_ft_integration.py b/ipie/qmc/tests/test_ft_integration.py deleted file mode 100644 index 17000af3..00000000 --- a/ipie/qmc/tests/test_ft_integration.py +++ /dev/null @@ -1,117 +0,0 @@ -# Copyright 2022 The ipie Developers. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Authors: Fionn Malone -# Joonho Lee -# - -import json -import os -import sys -import tempfile -import uuid - -import numpy as np - -from ipie.analysis.extraction import extract_test_data_hdf5 -from ipie.config import MPI -from ipie.qmc.calc import get_driver, read_input - -_built_legacy = True - - -comm = MPI.COMM_WORLD -serial_test = comm.size == 1 -# Unique filename to avoid name collision when running through CI. -if comm.rank == 0: - test_id = str(uuid.uuid1()) -else: - test_id = None -test_id = comm.bcast(test_id, root=0) - -_data_dir = os.path.abspath(os.path.dirname(__file__)) + "/reference_data/" -_legacy_test_dirs = [ - "ft_4x4_hubbard_discrete", - "ft_ueg_ecut1.0_rs1.0", -] - - -_legacy_tests = [ - (_data_dir + d + "/input.json", _data_dir + d + "/reference_nompi.json") for d in _legacy_test_dirs -] - - -def compare_test_data(ref, test): - comparison = {} - for k, v in ref.items(): - if k == "sys_info": - continue - try: - comparison[k] = ( - np.array(ref[k]), - np.array(test[k]), - np.max(np.abs(np.array(ref[k]) - np.array(test[k]))) < 1e-10, - ) - except KeyError: - print(f"# Issue with test data key {k}") - return comparison - - -def run_test_system(input_file, benchmark_file, legacy_job=False): - comm = MPI.COMM_WORLD - input_dict = read_input(input_file, comm) - if input_dict["system"].get("integrals") is not None: - input_dict["system"]["integrals"] = input_file[:-10] + "afqmc.h5" - input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" - elif ("hamiltonian" in input_dict) and (input_dict["hamiltonian"].get("integrals") is not None): - input_dict["hamiltonian"]["integrals"] = input_file[:-10] + "afqmc.h5" - input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" - with tempfile.NamedTemporaryFile() as tmpf: - input_dict["estimators"]["filename"] = tmpf.name - if _built_legacy and legacy_job: - from ipie.legacy.qmc.calc import get_driver as get_legacy_driver - - input_dict["qmc"]["batched"] = False - afqmc = get_legacy_driver(input_dict, comm) - afqmc.run(comm=comm) - afqmc.finalise(comm) - else: - print('here') - afqmc = get_driver(input_dict, comm) - afqmc.run(estimator_filename=tmpf.name) - afqmc.finalise() - with open(benchmark_file, "r") as f: - ref_data = json.load(f) - skip_val = ref_data.get("extract_skip_value", 10) - test_data = extract_test_data_hdf5(tmpf.name, skip=skip_val) - comparison = compare_test_data(ref_data, test_data) - - return comparison - - -if __name__ == "__main__": - err_count = 0 - for test_name, (ind, outd) in zip(_legacy_test_dirs, _legacy_tests): - comparison = run_test_system(ind, outd, legacy_job=True) - local_err_count = 0 - for k, v in comparison.items(): - if not v[-1]: - local_err_count += 1 - print(f" *** FAILED *** : mismatch between benchmark and test run: {test_name}") - err_count += 1 - print(f"name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") - if local_err_count == 0: - print(f"*** PASSED : {test_name} ***") - err_count = comm.bcast(err_count) - sys.exit(err_count) diff --git a/ipie/qmc/tests/test_ft_mpi_integration.py b/ipie/qmc/tests/test_ft_mpi_integration.py deleted file mode 100644 index 411074f2..00000000 --- a/ipie/qmc/tests/test_ft_mpi_integration.py +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright 2022 The ipie Developers. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Authors: Fionn Malone -# Joonho Lee -# - -import json -import os -import sys -import tempfile -import uuid - -import numpy as np - -from ipie.analysis.extraction import extract_test_data_hdf5 -from ipie.config import MPI -from ipie.qmc.calc import get_driver, read_input - -_built_legacy = True - - -comm = MPI.COMM_WORLD -serial_test = comm.size == 1 -# Unique filename to avoid name collision when running through CI. -if comm.rank == 0: - test_id = str(uuid.uuid1()) -else: - test_id = None -test_id = comm.bcast(test_id, root=0) - -_data_dir = os.path.abspath(os.path.dirname(__file__)) + "/reference_data/" -_legacy_test_dirs = [ - "ft_4x4_hubbard_discrete", - "ft_ueg_ecut1.0_rs1.0", -] -_legacy_tests = [ - (_data_dir + d + "/input.json", _data_dir + d + "/reference.json") for d in _legacy_test_dirs -] - - -def compare_test_data(ref, test): - comparison = {} - for k, v in ref.items(): - if k == "sys_info": - continue - try: - comparison[k] = ( - np.array(ref[k]), - np.array(test[k]), - np.max(np.abs(np.array(ref[k]) - np.array(test[k]))) < 1e-10, - ) - except KeyError: - print(f"# Issue with test data key {k}") - return comparison - - -def run_test_system(input_file, benchmark_file, legacy_job=False): - comm = MPI.COMM_WORLD - input_dict = read_input(input_file, comm) - if input_dict["system"].get("integrals") is not None: - input_dict["system"]["integrals"] = input_file[:-10] + "afqmc.h5" - input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" - elif ("hamiltonian" in input_dict) and (input_dict["hamiltonian"].get("integrals") is not None): - input_dict["hamiltonian"]["integrals"] = input_file[:-10] + "afqmc.h5" - input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" - with tempfile.NamedTemporaryFile() as tmpf: - input_dict["estimators"]["filename"] = tmpf.name - if _built_legacy and legacy_job: - from ipie.legacy.qmc.calc import get_driver as get_legacy_driver - - input_dict["qmc"]["batched"] = False - afqmc = get_legacy_driver(input_dict, comm) - afqmc.run(comm=comm) - afqmc.finalise(comm) - else: - afqmc = get_driver(input_dict, comm) - afqmc.run(estimator_filename=tmpf.name) - afqmc.finalise() - if comm.rank == 0: - with open(benchmark_file, "r") as f: - ref_data = json.load(f) - skip_val = ref_data.get("extract_skip_value", 10) - test_data = extract_test_data_hdf5(tmpf.name, skip=skip_val) - comparison = compare_test_data(ref_data, test_data) - else: - comparison = None - comm.barrier() - comparison = comm.bcast(comparison) - return comparison - - -if __name__ == "__main__": - err_count = 0 - for test_name, (ind, outd) in zip(_legacy_test_dirs, _legacy_tests): - comparison = run_test_system(ind, outd, legacy_job=True) - local_err_count = 0 - if comm.rank == 0: - for k, v in comparison.items(): - if not v[-1]: - local_err_count += 1 - print(f" *** FAILED *** : mismatch between benchmark and test run: {test_name}") - err_count += 1 - print(f"name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") - else: - err_count = None - if local_err_count == 0 and comm.rank == 0: - print(f"*** PASSED : {test_name} ***") - err_count = comm.bcast(err_count) - sys.exit(err_count) diff --git a/ipie/systems/__init__.py b/ipie/systems/__init__.py index cccf70de..7c4485e6 100644 --- a/ipie/systems/__init__.py +++ b/ipie/systems/__init__.py @@ -17,4 +17,3 @@ # from .generic import Generic -from .ueg import UEG diff --git a/ipie/systems/tests/test_ueg.py b/ipie/systems/tests/test_ueg.py deleted file mode 100644 index 922eba7b..00000000 --- a/ipie/systems/tests/test_ueg.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright 2022 The ipie Developers. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Authors: Fionn Malone -# Joonho Lee -# - -# TODO: write UEG test - -import os -import tempfile - -import math -import numpy -import pytest - -from ipie.config import MPI -from ipie.systems.ueg import UEG - - -@pytest.mark.unit -def test_ueg(): - numpy.random.seed(7) - nup = 7 - ndown = 5 - ne = nup + ndown - rs = 1. - mu = -1. - ecut = 1. - sys_opts = { - "nup": nup, - "ndown": ndown, - "rs": rs, - "mu": mu, - "ecut": ecut - } - sys = UEG(sys_opts, verbose=True) - assert sys.nup == nup - assert sys.ndown == ndown - assert sys.rs == rs - assert sys.mu == mu - assert sys.ecut == ecut - assert sys.ne == nup + ndown - assert sys.zeta == (nup - ndown) / ne - assert sys.rho == ((4.0 * math.pi) / 3.0 * rs**3.0)**(-1.0) - assert sys.L == rs * (4.0 * ne * math.pi / 3.0) ** (1.0 / 3.0) - assert sys.vol == sys.L**3.0 - assert sys.kfac == 2 * math.pi / sys.L - assert sys.kf == (3 * (sys.zeta + 1) * math.pi**2 * ne / sys.L**3) ** (1.0 / 3.0) - assert sys.ef == 0.5 * sys.kf**2 - - -if __name__ == "__main__": - test_ueg() diff --git a/ipie/systems/ueg.py b/ipie/systems/ueg.py deleted file mode 100644 index 454d3693..00000000 --- a/ipie/systems/ueg.py +++ /dev/null @@ -1,95 +0,0 @@ -import math -import numpy - -class UEG(object): - """UEG system class (integrals read from fcidump) - Parameters - ---------- - nup : int - Number of up electrons. - ndown : int - Number of down electrons. - rs : float - Density parameter. - ecut : float - Scaled cutoff energy. - ktwist : :class:`numpy.ndarray` - Twist vector. - verbose : bool - Print extra information. - Attributes - ---------- - T : :class:`numpy.ndarray` - One-body part of the Hamiltonian. This is diagonal in plane wave basis. - ecore : float - Madelung contribution to the total energy. - h1e_mod : :class:`numpy.ndarray` - Modified one-body Hamiltonian. - nfields : int - Number of field configurations per walker for back propagation. - basis : :class:`numpy.ndarray` - Basis vectors within a cutoff. - kfac : float - Scale factor (2pi/L). - """ - - def __init__(self, options, verbose=False): - if verbose: - print("# Parsing input options for systems.UEG.") - self.name = "UEG" - self.nup = options.get("nup") - self.ndown = options.get("ndown") - self.nelec = (self.nup, self.ndown) - self.rs = options.get("rs") - self.ecut = options.get("ecut") - self.ktwist = numpy.array(options.get("ktwist", [0, 0, 0])).reshape(3) - self.control_variate = False - self.mu = options.get("mu", None) - if verbose: - print(f"# Number of spin-up electrons: {self.nup:d}") - print(f"# Number of spin-down electrons: {self.ndown:d}") - print(f"# rs: {self.rs:6.4e}") - if self.mu is not None: - print(f"# mu: {self.mu:6.4e}") - - self.thermal = options.get("thermal", False) - if self.thermal and verbose: - print("# Thermal UEG activated") - self._alt_convention = options.get("alt_convention", False) - self.sparse = True - - # total # of electrons - self.ne = self.nup + self.ndown - # spin polarisation - self.zeta = (self.nup - self.ndown) / self.ne - # Density. - self.rho = ((4.0 * math.pi) / 3.0 * self.rs**3.0) ** (-1.0) - # Box Length. - self.L = self.rs * (4.0 * self.ne * math.pi / 3.0) ** (1 / 3.0) - # Volume - self.vol = self.L**3.0 - # k-space grid spacing. - self.kfac = 2 * math.pi / self.L - # Fermi Wavevector (infinite system). - self.kf = (3 * (self.zeta + 1) * math.pi**2 * self.ne / self.L**3) ** (1 / 3.0) - # Fermi energy (inifinite systems). - self.ef = 0.5 * self.kf**2 - if verbose: - print(f"# Spin polarisation (zeta): {self.zeta:6.4e}") - print(f"# Electron density (rho): {self.rho:13.8e}") - print(f"# Box Length (L): {self.L:13.8e}") - print(f"# Volume: {self.vol:13.8e}") - print(f"# k-space factor (2pi/L): {self.kfac:13.8e}") - - -def unit_test(): - from numpy import linalg as LA - - from ipie.estimators import ci as pieci - - options = {"nup": 2, "ndown": 2, "rs": 1.0, "thermal": True, "ecut": 3} - system = UEG(options, True) - - -if __name__ == "__main__": - unit_test() From e262624dc64bc7179be3ae5fc6eb842ea0925a83 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Mon, 4 Mar 2024 16:49:26 -0600 Subject: [PATCH 44/84] remove `ueg` from `ipie/hamiltonians` --- ipie/hamiltonians/tests/ueg_test.py | 56 ---- ipie/hamiltonians/ueg.py | 491 ---------------------------- ipie/hamiltonians/utils.py | 16 - 3 files changed, 563 deletions(-) delete mode 100644 ipie/hamiltonians/tests/ueg_test.py delete mode 100644 ipie/hamiltonians/ueg.py diff --git a/ipie/hamiltonians/tests/ueg_test.py b/ipie/hamiltonians/tests/ueg_test.py deleted file mode 100644 index 453a2fdd..00000000 --- a/ipie/hamiltonians/tests/ueg_test.py +++ /dev/null @@ -1,56 +0,0 @@ -import pytest -import numpy - -from ipie.systems.ueg import UEG as SysUEG -from ipie.hamiltonians.ueg import UEG - -# TODO: write UEG test - -@pytest.mark.unit -def test_hamiltonian(): - numpy.random.seed(7) - nup = 7 - ndown = 5 - ne = nup + ndown - rs = 1. - mu = -1. - ecut = 1. - sys_opts = { - "nup": nup, - "ndown": ndown, - "rs": rs, - "mu": mu, - "ecut": ecut - } - ham_opts = {} # Default - sys = SysUEG(sys_opts) - ham = UEG(sys, ham_opts, verbose=True) - assert hasattr(ham, "h1e_mod") == True - -@pytest.mark.unit -def test_skip_cholesky(): - numpy.random.seed(7) - nup = 7 - ndown = 5 - ne = nup + ndown - rs = 1. - mu = -1. - ecut = 1. - sys_opts = { - "nup": nup, - "ndown": ndown, - "rs": rs, - "mu": mu, - "ecut": ecut - } - ham_opts = { - "skip_cholesky": True - } - sys = SysUEG(sys_opts) - ham = UEG(sys, ham_opts, verbose=True) - assert hasattr(ham, "h1e_mod") == False - - -if __name__ == "__main__": - test_hamiltonian() - test_skip_cholesky() diff --git a/ipie/hamiltonians/ueg.py b/ipie/hamiltonians/ueg.py deleted file mode 100644 index 3097319a..00000000 --- a/ipie/hamiltonians/ueg.py +++ /dev/null @@ -1,491 +0,0 @@ -import math - -import numpy -import scipy.linalg -import scipy.sparse - -from ipie.utils.io import write_qmcpack_sparse - - -class UEG(object): - """UEG system class (integrals read from fcidump) - Parameters - ---------- - nup : int - Number of up electrons. - ndown : int - Number of down electrons. - rs : float - Density parameter. - ecut : float - Scaled cutoff energy. - ktwist : :class:`numpy.ndarray` - Twist vector. - verbose : bool - Print extra information. - Attributes - ---------- - T : :class:`numpy.ndarray` - One-body part of the Hamiltonian. This is diagonal in plane wave basis. - ecore : float - Madelung contribution to the total energy. - h1e_mod : :class:`numpy.ndarray` - Modified one-body Hamiltonian. - nfields : int - Number of field configurations per walker for back propagation. - basis : :class:`numpy.ndarray` - Basis vectors within a cutoff. - kfac : float - Scale factor (2pi/L). - """ - - def __init__(self, system, options, verbose=False): - if verbose: - print("# Parsing input options.") - self.name = "UEG" - - # Inherit from system. - self.mu = system.mu - self.kfac = system.kfac - self.vol = system.vol - self._alt_convention = system._alt_convention - - self.sparse = True - skip_cholesky = options.get("skip_cholesky", False) - - # Core energy - self.ecore = 0.5 * system.ne * self.madelung(system) - self.diagH1 = True - - # Get plane wave basis vectors and corresponding eigenvalues. - (self.sp_eigv, self.basis, self.nmax) = self.sp_energies( - system.ktwist, self.kfac, system.ecut - ) - - self.shifted_nmax = 2 * self.nmax - self.imax_sq = numpy.dot(self.basis[-1], self.basis[-1]) - self.create_lookup_table() - for i, k in enumerate(self.basis): - assert i == self.lookup_basis(k) - - # Number of plane waves. - self.nbasis = len(self.sp_eigv) - self.nactive = self.nbasis - self.ncore = 0 - self.nfv = 0 - self.mo_coeff = None - - # Allowed momentum transfers (4*ecut). - (eigs, qvecs, self.qnmax) = self.sp_energies(system.ktwist, self.kfac, 4 * system.ecut) - - # Omit Q = 0 term. - self.qvecs = numpy.copy(qvecs[1:]) - self.vqvec = numpy.array([self.vq(self.kfac * q) for q in self.qvecs]) - - # Number of momentum transfer vectors / auxiliary fields. - # Can reduce by symmetry but be stupid for the moment. - self.nchol = len(self.qvecs) - self.nfields = 2 * len(self.qvecs) - if verbose: - print(f"# Number of plane waves: {self.nbasis:d}") - print(f"# Number of Cholesky vectors: {self.nchol:d}.") - - # For consistency with frozen core molecular code. - self.orbs = None - self.frozen_core = False - T = numpy.diag(self.sp_eigv) - self.H1 = numpy.array([T, T]) # Making alpha and beta - - if skip_cholesky == False: - h1e_mod = self.mod_one_body(T, system) - self.h1e_mod = numpy.array([h1e_mod, h1e_mod]) - - self.orbs = None - self._opt = True - - nlimit = system.nup - if system.thermal: - nlimit = self.nbasis - - # Get arrays of plane wave basis vectors connected by momentum transfers Q. - self.ikpq_i = [] - self.ikpq_kpq = [] - for iq, q in enumerate(self.qvecs): - idxkpq_list_i = [] - idxkpq_list_kpq = [] - for i, k in enumerate(self.basis[0:nlimit]): - kpq = k + q - idxkpq = self.lookup_basis(kpq) - if idxkpq is not None: - idxkpq_list_i += [i] - idxkpq_list_kpq += [idxkpq] - self.ikpq_i += [idxkpq_list_i] - self.ikpq_kpq += [idxkpq_list_kpq] - - self.ipmq_i = [] - self.ipmq_pmq = [] - for iq, q in enumerate(self.qvecs): - idxpmq_list_i = [] - idxpmq_list_pmq = [] - for i, p in enumerate(self.basis[0:nlimit]): - pmq = p - q - idxpmq = self.lookup_basis(pmq) - if idxpmq is not None: - idxpmq_list_i += [i] - idxpmq_list_pmq += [idxpmq] - self.ipmq_i += [idxpmq_list_i] - self.ipmq_pmq += [idxpmq_list_pmq] - - for iq, q in enumerate(self.qvecs): - self.ikpq_i[iq] = numpy.array(self.ikpq_i[iq], dtype=numpy.int64) - self.ikpq_kpq[iq] = numpy.array(self.ikpq_kpq[iq], dtype=numpy.int64) - self.ipmq_i[iq] = numpy.array(self.ipmq_i[iq], dtype=numpy.int64) - self.ipmq_pmq[iq] = numpy.array(self.ipmq_pmq[iq], dtype=numpy.int64) - - if skip_cholesky == False: - if verbose: - print("# Constructing two-body potentials incore.") - - (self.chol_vecs, self.iA, self.iB) = self.two_body_potentials_incore() - write_ints = options.get("write_integrals", False) - - if write_ints: - self.write_integrals(system) - - if verbose: - print( - "# Approximate memory required for " - "two-body potentials: {:13.8e} GB.".format((3 * self.iA.nnz * 16 / (1024**3))) - ) - print("# Finished constructing two-body potentials.") - print("# Finished setting up UEG system object.") - - def sp_energies(self, ks, kfac, ecut): - """Calculate the allowed kvectors and resulting single particle eigenvalues (basically kinetic energy) - which can fit in the sphere in kspace determined by ecut. - Parameters - ---------- - kfac : float - kspace grid spacing. - ecut : float - energy cutoff. - Returns - ------- - spval : :class:`numpy.ndarray` - Array containing sorted single particle eigenvalues. - kval : :class:`numpy.ndarray` - Array containing basis vectors, sorted according to their - corresponding single-particle energy. - """ - - # Scaled Units to match with HANDE. - # So ecut is measured in units of 1/kfac^2. - nmax = int(math.ceil(numpy.sqrt((2 * ecut)))) - - spval = [] - vec = [] - kval = [] - - for ni in range(-nmax, nmax + 1): - for nj in range(-nmax, nmax + 1): - for nk in range(-nmax, nmax + 1): - spe = 0.5 * (ni**2 + nj**2 + nk**2) - if spe <= ecut: - kijk = [ni, nj, nk] - kval.append(kijk) - # Reintroduce 2 \pi / L factor. - ek = 0.5 * numpy.dot(numpy.array(kijk) + ks, numpy.array(kijk) + ks) - spval.append(kfac**2 * ek) - - # Sort the arrays in terms of increasing energy. - spval = numpy.array(spval) - ix = numpy.argsort(spval, kind="mergesort") - spval = spval[ix] - kval = numpy.array(kval)[ix] - - return (spval, kval, nmax) - - def create_lookup_table(self): - basis_ix = [] - for k in self.basis: - basis_ix.append(self.map_basis_to_index(k)) - self.lookup = numpy.zeros(max(basis_ix) + 1, dtype=int) - for i, b in enumerate(basis_ix): - self.lookup[b] = i - self.max_ix = max(basis_ix) - - def lookup_basis(self, vec): - if numpy.dot(vec, vec) <= self.imax_sq: - ix = self.map_basis_to_index(vec) - if ix >= len(self.lookup): - ib = None - else: - ib = self.lookup[ix] - return ib - else: - ib = None - - def map_basis_to_index(self, k): - return ( - (k[0] + self.nmax) - + self.shifted_nmax * (k[1] + self.nmax) - + self.shifted_nmax * self.shifted_nmax * (k[2] + self.nmax) - ) - - def madelung(self, system): - """Use expression in Schoof et al. (PhysRevLett.115.130402) for the - Madelung contribution to the total energy fitted to L.M. Fraser et al. - Phys. Rev. B 53, 1814. - Parameters - ---------- - rs : float - Wigner-Seitz radius. - ne : int - Number of electrons. - Returns - ------- - v_M: float - Madelung potential (in Hartrees). - """ - c1 = -2.837297 - c2 = (3.0 / (4.0 * math.pi)) ** (1.0 / 3.0) - return c1 * c2 / (system.ne ** (1.0 / 3.0) * system.rs) - - def vq(self, q): - """The typical 3D Coulomb kernel - Parameters - ---------- - q : float - a plane-wave vector - Returns - ------- - v_M: float - 3D Coulomb kernel (in Hartrees) - """ - return 4 * math.pi / numpy.dot(q, q) - - def mod_one_body(self, T, system): - """Absorb the diagonal term of the two-body Hamiltonian to the one-body term. - Essentially adding the third term in Eq.(11b) of Phys. Rev. B 75, 245123. - Parameters - ---------- - T : float - one-body Hamiltonian (i.e. kinetic energy) - Returns - ------- - h1e_mod: float - modified one-body Hamiltonian - """ - h1e_mod = numpy.copy(T) - - fac = 1.0 / (2.0 * system.vol) - for i, ki in enumerate(self.basis): - for j, kj in enumerate(self.basis): - if i != j: - q = self.kfac * (ki - kj) - h1e_mod[i, i] = h1e_mod[i, i] - fac * self.vq(q) - return h1e_mod - - def density_operator(self, iq): - """Density operator as defined in Eq.(6) of Phys. Rev. B 75, 245123. - Parameters - ---------- - q : float - a plane-wave vector - Returns - ------- - rho_q: float - density operator - """ - nnz = self.rho_ikpq_kpq[iq].shape[0] # Number of non-zeros - ones = numpy.ones((nnz), dtype=numpy.complex128) - rho_q = scipy.sparse.csc_matrix( - (ones, (self.rho_ikpq_kpq[iq], self.rho_ikpq_i[iq])), - shape=(self.nbasis, self.nbasis), - dtype=numpy.complex128, - ) - return rho_q - - def scaled_density_operator_incore(self, transpose): - """Density operator as defined in Eq.(6) of PRB(75)245123 - Parameters - ---------- - q : float - a plane-wave vector - Returns - ------- - rho_q: float - density operator - """ - rho_ikpq_i = [] - rho_ikpq_kpq = [] - for iq, q in enumerate(self.qvecs): - idxkpq_list_i = [] - idxkpq_list_kpq = [] - for i, k in enumerate(self.basis): - kpq = k + q - idxkpq = self.lookup_basis(kpq) - if idxkpq is not None: - idxkpq_list_i += [i] - idxkpq_list_kpq += [idxkpq] - rho_ikpq_i += [idxkpq_list_i] - rho_ikpq_kpq += [idxkpq_list_kpq] - - for iq, q in enumerate(self.qvecs): - rho_ikpq_i[iq] = numpy.array(rho_ikpq_i[iq], dtype=numpy.int64) - rho_ikpq_kpq[iq] = numpy.array(rho_ikpq_kpq[iq], dtype=numpy.int64) - - nq = len(self.qvecs) - nnz = 0 - for iq in range(nq): - nnz += rho_ikpq_kpq[iq].shape[0] - - col_index = [] - row_index = [] - - values = [] - - if transpose: - for iq in range(nq): - qscaled = self.kfac * self.qvecs[iq] - # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol - piovol = math.pi / (self.vol) - factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 - - for innz, kpq in enumerate(rho_ikpq_kpq[iq]): - row_index += [rho_ikpq_kpq[iq][innz] + rho_ikpq_i[iq][innz] * self.nbasis] - col_index += [iq] - values += [factor] - else: - for iq in range(nq): - qscaled = self.kfac * self.qvecs[iq] - # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol - piovol = math.pi / (self.vol) - factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 - - for innz, kpq in enumerate(rho_ikpq_kpq[iq]): - row_index += [rho_ikpq_kpq[iq][innz] * self.nbasis + rho_ikpq_i[iq][innz]] - col_index += [iq] - values += [factor] - - rho_q = scipy.sparse.csc_matrix( - (values, (row_index, col_index)), - shape=(self.nbasis * self.nbasis, nq), - dtype=numpy.complex128, - ) - - return rho_q - - def two_body_potentials_incore(self): - """Calculate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q - - Parameters - ---------- - system : - system class - q : float - a plane-wave vector - Returns - ------- - iA : numpy array - Eq.(13a) - iB : numpy array - Eq.(13b) - """ - # qscaled = self.kfac * self.qvecs - - # # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol - - rho_q = self.scaled_density_operator_incore(False) - rho_qH = self.scaled_density_operator_incore(True) - - iA = 1j * (rho_q + rho_qH) - iB = -(rho_q - rho_qH) - - return (rho_q, iA, iB) - - def write_integrals(self, system, filename="hamil.h5"): - write_qmcpack_sparse( - self.H1[0], - 2 * self.chol_vecs.toarray(), - system.nelec, - self.nbasis, - enuc=0.0, - filename=filename, - ) - - def hijkl(self, i, j, k, l): - """Compute = (ik|jl) = 1/Omega * 4pi/(kk-ki)**2 - - Checks for momentum conservation k_i + k_j = k_k + k_k, or - k_k - k_i = k_j - k_l. - - Parameters - ---------- - i, j, k, l : int - Orbital indices for integral (ik|jl) = . - - Returns - ------- - integral : float - (ik|jl) - """ - q1 = self.basis[k] - self.basis[i] - q2 = self.basis[j] - self.basis[l] - if numpy.dot(q1, q1) > 1e-12 and numpy.dot(q1 - q2, q1 - q2) < 1e-12: - return 1.0 / self.vol * self.vq(self.kfac * q1) - else: - return 0.0 - - def compute_real_transformation(self): - U22 = numpy.zeros((2, 2), dtype=numpy.complex128) - U22[0, 0] = 1.0 / numpy.sqrt(2.0) - U22[0, 1] = 1.0 / numpy.sqrt(2.0) - U22[1, 0] = -1.0j / numpy.sqrt(2.0) - U22[1, 1] = 1.0j / numpy.sqrt(2.0) - - U = numpy.zeros((self.nbasis, self.nbasis), dtype=numpy.complex128) - - for i, b in enumerate(self.basis): - if numpy.sum(b * b) == 0: - U[i, i] = 1.0 - else: - mb = -b - diff = numpy.einsum("ij->i", (self.basis - mb) ** 2) - idx = numpy.argwhere(diff == 0) - assert idx.ravel().shape[0] == 1 - if i < idx: - idx = idx.ravel()[0] - U[i, i] = U22[0, 0] - U[i, idx] = U22[0, 1] - U[idx, i] = U22[1, 0] - U[idx, idx] = U22[1, 1] - else: - continue - - U = U.T.copy() - return U - - def eri_4(self): - eri_chol = 4 * self.chol_vecs.dot(self.chol_vecs.T) - eri_chol = ( - eri_chol.toarray().reshape((self.nbasis, self.nbasis, self.nbasis, self.nbasis)).real - ) - eri_chol = eri_chol.transpose(0, 1, 3, 2) - return eri_chol - - # Compute 8-fold symmetric integrals. Useful for running standard quantum chemistry methods - def eri_8(self): - eri = self.eri_4() - U = self.compute_real_transformation() - - eri0 = numpy.einsum("mp,mnls->pnls", U.conj(), eri, optimize=True) - eri1 = numpy.einsum("nq,pnls->pqls", U, eri0, optimize=True) - eri2 = numpy.einsum("lr,pqls->pqrs", U.conj(), eri1, optimize=True) - eri3 = numpy.einsum("st,pqrs->pqrt", U, eri2, optimize=True).real - - return eri3 - - -if __name__ == "__main__": - unit_test() diff --git a/ipie/hamiltonians/utils.py b/ipie/hamiltonians/utils.py index b3a0e503..c867c9fb 100644 --- a/ipie/hamiltonians/utils.py +++ b/ipie/hamiltonians/utils.py @@ -22,9 +22,7 @@ import numpy from ipie.systems.generic import Generic as SysGeneric -from ipie.systems.ueg import UEG as SysUEG from ipie.hamiltonians.generic import Generic, construct_h1e_mod, read_integrals -from ipie.hamiltonians.ueg import UEG from ipie.utils.io import get_input_value from ipie.utils.mpi import get_shared_array, have_shared_mem from ipie.utils.pack_numba import pack_cholesky @@ -101,20 +99,6 @@ def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): verbose=verbose, ) - ham._alt_convention = ham_opts["_alt_convention"] - ham.sparse = ham_opts["sparse"] - ham.name = ham_opts["name"] - ham.hs_pot = chol.T.reshape(nchol, nbsf, nbsf) - ham.chol_vecs = chol - ham.mu = ham_opts["mu"] - - elif isinstance(system, SysUEG): - ham = UEG( - system, - ham_opts, - verbose=verbose, - ) - else: if comm.rank == 0: print(f"# Error: unrecognized hamiltonian name {ham_opts['name']}.") From 87077d84bf3dc32cec77fb1fcd3dc1721ad76f4d Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Mon, 4 Mar 2024 16:50:57 -0600 Subject: [PATCH 45/84] remove `ueg` from `ipie/hamiltonians` --- ipie/hamiltonians/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ipie/hamiltonians/__init__.py b/ipie/hamiltonians/__init__.py index db8dba3f..c2aa068f 100644 --- a/ipie/hamiltonians/__init__.py +++ b/ipie/hamiltonians/__init__.py @@ -18,4 +18,3 @@ from .generic_base import GenericBase from .generic import Generic -from .ueg import UEG From 518d1cff545672e266bd0e69928dcc465a252e31 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Mon, 4 Mar 2024 16:57:49 -0600 Subject: [PATCH 46/84] remove FT reference data from `ipie/qmc/tests/reference_data` --- .../ft_4x4_hubbard_discrete/input.json | 32 ------------------- .../ft_4x4_hubbard_discrete/reference.json | 1 - .../reference_nompi.json | 1 - .../ft_ueg_ecut1.0_rs1.0/input.json | 32 ------------------- .../ft_ueg_ecut1.0_rs1.0/reference.json | 1 - .../ft_ueg_ecut1.0_rs1.0/reference_nompi.json | 1 - 6 files changed, 68 deletions(-) delete mode 100644 ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/input.json delete mode 100644 ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference.json delete mode 100644 ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json delete mode 100644 ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json delete mode 100644 ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json delete mode 100644 ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json diff --git a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/input.json b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/input.json deleted file mode 100644 index 3a3b9be6..00000000 --- a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/input.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "system": { - "name": "Hubbard", - "nx": 4, - "ny": 4, - "nup": 7, - "ndown": 7, - "mu": 0.1, - "U": 4 - }, - "qmc": { - "dt": 0.01, - "nwalkers": 32, - "blocks": 10, - "nsteps": 10, - "rng_seed": 7, - "beta": 0.25, - "pop_control_freq": 5, - "stabilise_freq": 10, - "batched": false - }, - "trial": { - "name": "one_body" - }, - "walkers": { - "pop_control": "comb" - }, - "propagator": { - "hubbard_stratonovich": "discrete" - }, - "estimators": {} -} diff --git a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference.json b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference.json deleted file mode 100644 index 904b376c..00000000 --- a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [32.0, 44.98447572409485], "Weight": [32.0, 42.93486118721573], "ENumer": [152.0047418107582, 24.59220437157029], "EDenom": [32.0, 42.93486118721573], "ETotal": [4.7501481815861935, 0.5727794079579522], "E1Body": [-7.499853241434115, -7.179410491868211], "E2Body": [12.250001423020308, 7.752189899826164], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154433, 13.205553548235017], "sys_info": {"nranks": 4, "branch": "develop", "sha1": "5de52c915d59fc1e026bb3b42812f6daa4d1010b", "numpy": {"version": "1.18.4", "path": "/usr/local/lib/python3.7/site-packages/numpy", "BLAS": {"lib": "openblas openblas", "path": "/usr/local/lib"}}, "scipy": {"version": "1.4.1", "path": "/usr/local/lib/python3.7/site-packages/scipy"}, "h5py": {"version": "2.10.0", "path": "/usr/local/lib/python3.7/site-packages/h5py"}, "mpi4py": {"version": "3.0.1", "path": "/usr/local/lib/python3.7/site-packages/mpi4py", "mpicc": "/usr/local/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json deleted file mode 100644 index 0fbf7b3e..00000000 --- a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [32.0, 44.98645457011622], "Weight": [32.0, 43.034282083027925], "ENumer": [152.0047418107588, 20.184762894579933], "EDenom": [32.0, 43.034282083027925], "ETotal": [4.750148181586212, 0.4690391454802612], "E1Body": [-7.499853241434117, -7.214851781729806], "E2Body": [12.250001423020322, 7.683890927210067], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154442, 13.233641168838517], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "a67b7598397a8e99b75d50bc67fd18ec2ee20b76-dirty", "numpy": {"version": "1.24.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}, "mpi4py": {"version": "3.1.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/mpi4py", "mpicc": "/sw/spack/delta-2022-03/apps/openmpi/4.1.4-gcc-11.2.0-7ooytax/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json deleted file mode 100644 index 65f888c9..00000000 --- a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "system": { - "name": "UEG", - "nup": 7, - "ndown": 7, - "rs": 1.0, - "mu": -1.0, - "ecut": 1.0 - }, - "qmc": { - "dt": 0.01, - "nwalkers": 32, - "blocks": 10, - "nsteps": 10, - "beta": 0.1, - "rng_seed": 7, - "pop_control_freq": 1, - "stabilise_freq": 10, - "batched": false - }, - "trial": { - "name": "one_body" - }, - "walkers": { - "population_control": "pair_branch" - }, - "estimators": { - "mixed": { - "one_rdm": true - } - } -} diff --git a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json deleted file mode 100644 index c278179f..00000000 --- a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [32.0, 47.94831398616111], "Weight": [32.0, 31.999999999999996], "ENumer": [853.4128425513718, 986.7912119123343], "EDenom": [32.0, 31.999999999999996], "ETotal": [26.66915132973037, 30.837225372260455], "E1Body": [28.374994808285745, 33.21707786343164], "E2Body": [-1.705843478555375, -2.379852491171182], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209672, 16.375812925843057], "sys_info": {"nranks": 4, "branch": "hubbard_updates", "sha1": "618262bc7511a252e2f2bb3f23cc96fa4e8b9eb5", "numpy": {"version": "1.18.4", "path": "/usr/local/lib/python3.7/site-packages/numpy", "BLAS": {"lib": "openblas openblas", "path": "/usr/local/lib"}}, "scipy": {"version": "1.4.1", "path": "/usr/local/lib/python3.7/site-packages/scipy"}, "h5py": {"version": "2.10.0", "path": "/usr/local/lib/python3.7/site-packages/h5py"}, "mpi4py": {"version": "3.0.1", "path": "/usr/local/lib/python3.7/site-packages/mpi4py", "mpicc": "/usr/local/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json deleted file mode 100644 index 553a1533..00000000 --- a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [32.0, 47.79071285048463], "Weight": [32.0, 31.999999999999996], "ENumer": [853.4128425513711, 986.9792326724249], "EDenom": [32.0, 31.999999999999996], "ETotal": [26.669151329730347, 30.843101021013286], "E1Body": [28.374994808285724, 33.221059734849845], "E2Body": [-1.7058434785553744, -2.3779587138365548], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209661, 16.377795476555466], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "a67b7598397a8e99b75d50bc67fd18ec2ee20b76-dirty", "numpy": {"version": "1.24.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}, "mpi4py": {"version": "3.1.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/mpi4py", "mpicc": "/sw/spack/delta-2022-03/apps/openmpi/4.1.4-gcc-11.2.0-7ooytax/bin/mpicc"}}} \ No newline at end of file From cb6435bfd3f4ec2177b380b4820f3568f2f67b2e Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Tue, 5 Mar 2024 00:14:59 -0600 Subject: [PATCH 47/84] remove `ueg` in `ipie/systems` --- ipie/systems/utils.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/ipie/systems/utils.py b/ipie/systems/utils.py index 55049f08..6822f2c4 100644 --- a/ipie/systems/utils.py +++ b/ipie/systems/utils.py @@ -19,7 +19,6 @@ import sys from ipie.systems.generic import Generic -from ipie.systems.ueg import UEG def get_system(sys_opts=None, verbose=0, comm=None): @@ -39,7 +38,6 @@ def get_system(sys_opts=None, verbose=0, comm=None): """ assert sys_opts is not None sys_type = sys_opts.get("name") - if sys_type is None or sys_type == "Generic": nup, ndown = sys_opts.get("nup"), sys_opts.get("ndown") if nup is None or ndown is None: @@ -49,16 +47,9 @@ def get_system(sys_opts=None, verbose=0, comm=None): nelec = (nup, ndown) system = Generic(nelec, verbose) - #system.mu = sys_opts["mu"] - - - elif sys_type == "UEG": - system = UEG(sys_opts, verbose) - else: if comm.rank == 0: print(f"# Error: unrecognized system name {sys_type}.") raise ValueError - return system From 2c2bb327d3709646764605e38773c93d419bc94c Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Tue, 5 Mar 2024 10:08:34 -0600 Subject: [PATCH 48/84] undo minor 0T change --- ipie/hamiltonians/utils.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ipie/hamiltonians/utils.py b/ipie/hamiltonians/utils.py index c867c9fb..6c7e7b4f 100644 --- a/ipie/hamiltonians/utils.py +++ b/ipie/hamiltonians/utils.py @@ -98,7 +98,6 @@ def get_hamiltonian(system, ham_opts=None, verbose=0, comm=None): ecore=enuc, verbose=verbose, ) - else: if comm.rank == 0: print(f"# Error: unrecognized hamiltonian name {ham_opts['name']}.") From bfedef81b8d4365a9d7e837f94da89ed815cd819 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Tue, 5 Mar 2024 10:23:44 -0600 Subject: [PATCH 49/84] Remove `ueg_kernel` compilation in `thermal/estimators` --- setup.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/setup.py b/setup.py index 33c5b757..d67e8eb0 100644 --- a/setup.py +++ b/setup.py @@ -22,12 +22,6 @@ extra_compile_args=["-O3"], include_dirs=[numpy.get_include()], ), - Extension( - "ipie.thermal.estimators.ueg_kernels", - ["ipie/thermal/estimators/ueg_kernels.pyx"], - extra_compile_args=["-O3"], - include_dirs=[numpy.get_include()], - ), ] cythonized_extension = cythonize( extensions, From 51e8ae3d903357df1f101fc260dc7e3328b0fcb6 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Fri, 8 Mar 2024 17:24:31 -0500 Subject: [PATCH 50/84] Update tests and restore `system` dependence in this branch. --- ipie/estimators/energy.py | 30 +- ipie/estimators/estimator_base.py | 2 +- ipie/estimators/generic.py | 24 +- ipie/estimators/handler.py | 8 +- ipie/estimators/local_energy.py | 33 +- ipie/estimators/local_energy_batch.py | 26 +- ipie/estimators/local_energy_noci.py | 5 +- ipie/estimators/local_energy_sd.py | 30 +- ipie/estimators/local_energy_sd_chunked.py | 8 +- ipie/estimators/local_energy_wicks.py | 14 +- ipie/estimators/tests/test_estimators.py | 17 +- ipie/estimators/tests/test_generic.py | 29 +- ipie/estimators/tests/test_generic_batch.py | 117 ++-- ipie/estimators/tests/test_generic_chunked.py | 23 +- .../tests/test_generic_chunked_gpu.py | 29 +- ipie/estimators/tests/test_generic_complex.py | 29 +- ipie/estimators/tests/test_generic_noci.py | 62 +- ipie/estimators/tests/test_generic_phmsd.py | 238 ++++---- ipie/legacy/thermal_propagation/continuous.py | 4 +- ipie/qmc/afqmc.py | 5 + ipie/qmc/tests/test_afqmc_multi_det_batch.py | 2 + ipie/qmc/tests/test_afqmc_single_det_batch.py | 4 + ipie/thermal/estimators/local_energy.py | 138 ++--- .../estimators/tests/test_estimators.py | 190 +++--- ipie/thermal/estimators/tests/test_generic.py | 112 ++++ .../estimators/tests/test_generic_complex.py | 199 +++---- ipie/thermal/propagation/phaseless_base.py | 4 +- .../tests/test_generic_propagation.py | 294 --------- .../propagation/tests/test_operations.py | 203 ++----- .../propagation/tests/test_prop_generic.py | 247 ++++++++ .../propagation/tests/ueg/test_prop_ueg.py | 155 +++++ .../propagation/tests/ueg/test_ueg_0T.py | 9 +- .../tests/ueg/test_ueg_propagation.py | 260 -------- .../propagation/tests/ueg/ueg_trial.npy | Bin 12896 -> 0 bytes .../thermal/qmc/tests/reference_data/ueg/note | 1 + ipie/thermal/qmc/tests/test_afqmc_generic.py | 180 ++++++ ipie/thermal/qmc/tests/test_generic.py | 309 ---------- ipie/thermal/qmc/tests/ueg/test_afqmc_ueg.py | 460 ++++++++++++++ ipie/thermal/qmc/tests/ueg/test_ueg.py | 563 ------------------ ipie/thermal/qmc/thermal_afqmc.py | 46 +- ipie/thermal/trial/chem_pot.py | 12 +- ipie/thermal/trial/one_body.py | 1 + ipie/thermal/trial/tests/test_chem_pot.py | 34 ++ ipie/thermal/trial/tests/test_mean_field.py | 2 + ipie/thermal/trial/tests/test_one_body.py | 1 + ipie/thermal/utils/legacy_testing.py | 425 +++++++++++++ ipie/thermal/utils/testing.py | 340 +++++++++++ ipie/thermal/{qmc/tests/ueg => utils}/ueg.py | 0 .../walkers/tests/test_population_control.py | 557 +++++++++++------ .../walkers/tests/test_thermal_walkers.py | 258 +++++--- ipie/trial_wavefunction/noci.py | 2 +- ipie/trial_wavefunction/particle_hole.py | 2 +- ipie/trial_wavefunction/single_det.py | 2 +- ipie/walkers/tests/test_multi_det_batch.py | 8 +- 54 files changed, 3230 insertions(+), 2523 deletions(-) create mode 100644 ipie/thermal/estimators/tests/test_generic.py delete mode 100644 ipie/thermal/propagation/tests/test_generic_propagation.py create mode 100644 ipie/thermal/propagation/tests/test_prop_generic.py create mode 100644 ipie/thermal/propagation/tests/ueg/test_prop_ueg.py delete mode 100644 ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py delete mode 100644 ipie/thermal/propagation/tests/ueg/ueg_trial.npy create mode 100644 ipie/thermal/qmc/tests/reference_data/ueg/note create mode 100644 ipie/thermal/qmc/tests/test_afqmc_generic.py delete mode 100644 ipie/thermal/qmc/tests/test_generic.py create mode 100644 ipie/thermal/qmc/tests/ueg/test_afqmc_ueg.py delete mode 100644 ipie/thermal/qmc/tests/ueg/test_ueg.py create mode 100644 ipie/thermal/trial/tests/test_chem_pot.py create mode 100644 ipie/thermal/utils/legacy_testing.py create mode 100644 ipie/thermal/utils/testing.py rename ipie/thermal/{qmc/tests/ueg => utils}/ueg.py (100%) diff --git a/ipie/estimators/energy.py b/ipie/estimators/energy.py index 65cd906a..2ba5b50f 100644 --- a/ipie/estimators/energy.py +++ b/ipie/estimators/energy.py @@ -30,6 +30,7 @@ local_energy_multi_det_trial_wicks_batch_opt_chunked, ) from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol +from ipie.systems.generic import Generic from ipie.trial_wavefunction.noci import NOCI from ipie.trial_wavefunction.particle_hole import ( ParticleHole, @@ -44,68 +45,75 @@ @plum.dispatch def local_energy( - hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: SingleDet + system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: SingleDet ): - return local_energy_batch(hamiltonian, walkers, trial) + return local_energy_batch(system, hamiltonian, walkers, trial) @plum.dispatch def local_energy( + system: Generic, hamiltonian: GenericComplexChol, walkers: UHFWalkers, trial: SingleDet, ): - return local_energy_single_det_uhf(hamiltonian, walkers, trial) + return local_energy_single_det_uhf(system, hamiltonian, walkers, trial) @plum.dispatch def local_energy( + system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: ParticleHoleNaive, ): - return local_energy_multi_det_trial_batch(hamiltonian, walkers, trial) + return local_energy_multi_det_trial_batch(system, hamiltonian, walkers, trial) @plum.dispatch def local_energy( + system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: ParticleHole, ): - return local_energy_multi_det_trial_wicks_batch_opt_chunked(hamiltonian, walkers, trial) + return local_energy_multi_det_trial_wicks_batch_opt_chunked(system, hamiltonian, walkers, trial) @plum.dispatch def local_energy( + system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: ParticleHoleNonChunked, ): - return local_energy_multi_det_trial_wicks_batch_opt(hamiltonian, walkers, trial) + return local_energy_multi_det_trial_wicks_batch_opt(system, hamiltonian, walkers, trial) @plum.dispatch def local_energy( + system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: ParticleHoleSlow, ): - return local_energy_multi_det_trial_wicks_batch(hamiltonian, walkers, trial) + return local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walkers, trial) @plum.dispatch -def local_energy(hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: NOCI): - return local_energy_noci(hamiltonian, walkers, trial) +def local_energy(system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: NOCI): + return local_energy_noci(system, hamiltonian, walkers, trial) class EnergyEstimator(EstimatorBase): def __init__( self, + system=None, hamiltonian=None, trial=None, filename=None, ): + assert system is not None assert hamiltonian is not None assert trial is not None super().__init__() @@ -123,10 +131,10 @@ def __init__( self.print_to_stdout = True self.ascii_filename = filename - def compute_estimator(self, walkers, hamiltonian, trial, istep=1): + def compute_estimator(self, system, walkers, hamiltonian, trial, istep=1): trial.calc_greens_function(walkers) # Need to be able to dispatch here - energy = local_energy(hamiltonian, walkers, trial) + energy = local_energy(system, hamiltonian, walkers, trial) self._data["ENumer"] = xp.sum(walkers.weight * energy[:, 0].real) self._data["EDenom"] = xp.sum(walkers.weight) self._data["E1Body"] = xp.sum(walkers.weight * energy[:, 1].real) diff --git a/ipie/estimators/estimator_base.py b/ipie/estimators/estimator_base.py index 77d0c41d..c78c9322 100644 --- a/ipie/estimators/estimator_base.py +++ b/ipie/estimators/estimator_base.py @@ -89,7 +89,7 @@ def shape(self, shape) -> tuple: self._shape = shape @abstractmethod - def compute_estimator(self, walkers, hamiltonian, trial) -> np.ndarray: + def compute_estimator(self, system, walkers, hamiltonian, trial) -> np.ndarray: ... @property diff --git a/ipie/estimators/generic.py b/ipie/estimators/generic.py index a7674fff..bda07b13 100644 --- a/ipie/estimators/generic.py +++ b/ipie/estimators/generic.py @@ -23,13 +23,15 @@ from ipie.utils.backend import synchronize -def local_energy_generic_cholesky(hamiltonian, G, Ghalf=None): +def local_energy_generic_cholesky(system, hamiltonian, G, Ghalf=None): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. Parameters ---------- + system : :class:`Generic` + System information for Generic. hamiltonian : :class:`Generic` ab-initio hamiltonian information G : :class:`numpy.ndarray` @@ -87,13 +89,15 @@ def local_energy_generic_cholesky(hamiltonian, G, Ghalf=None): return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) -def local_energy_cholesky_opt_dG(ecore, Ghalfa, Ghalfb, trial): +def local_energy_cholesky_opt_dG(system, ecore, Ghalfa, Ghalfb, trial): r"""Calculate local for generic two-body hamiltonian. This uses the density difference trick. Parameters ---------- + system : :class:`Generic` + System information for Generic. ecore : float Core energy Ghalfa : :class:`numpy.ndarray` @@ -118,7 +122,7 @@ def local_energy_cholesky_opt_dG(ecore, Ghalfa, Ghalfb, trial): dGhalfa = dGhalfa.astype(numpy.complex64) dGhalfb = dGhalfb.astype(numpy.complex64) - deJ, deK = half_rotated_cholesky_jk(dGhalfa, dGhalfb, trial) + deJ, deK = half_rotated_cholesky_jk(system, dGhalfa, dGhalfb, trial) de2 = deJ + deK if trial.mixed_precision: @@ -133,13 +137,15 @@ def local_energy_cholesky_opt_dG(ecore, Ghalfa, Ghalfb, trial): return (etot, e1, e2) -def local_energy_cholesky_opt(ecore, Ghalfa, Ghalfb, trial): +def local_energy_cholesky_opt(system, ecore, Ghalfa, Ghalfb, trial): r"""Calculate local for generic two-body hamiltonian. This uses the half-rotated cholesky decomposed two-electron integrals. Parameters ---------- + system : :class:`Generic` + System information for Generic. Ghalfa : :class:`numpy.ndarray` Walker's half-rotated "green's function" shape is nalpha x nbasis Ghalfa : :class:`numpy.ndarray` @@ -152,20 +158,22 @@ def local_energy_cholesky_opt(ecore, Ghalfa, Ghalfb, trial): (E, T, V): tuple Total, one and two-body energies. """ - e1b = half_rotated_cholesky_hcore(Ghalfa, Ghalfb, trial) - eJ, eK = half_rotated_cholesky_jk(Ghalfa, Ghalfb, trial) + e1b = half_rotated_cholesky_hcore(system, Ghalfa, Ghalfb, trial) + eJ, eK = half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial) e2b = eJ + eK return (e1b + e2b + ecore, e1b + ecore, e2b) -def half_rotated_cholesky_hcore(Ghalfa, Ghalfb, trial): +def half_rotated_cholesky_hcore(system, Ghalfa, Ghalfb, trial): r"""Calculate local for generic two-body hamiltonian. This uses the half-rotated core hamiltonian. Parameters ---------- + system : :class:`Generic` + System information for Generic. Ghalfa : :class:`numpy.ndarray` Walker's half-rotated "green's function" shape is nalpha x nbasis Ghalfa : :class:`numpy.ndarray` @@ -297,7 +305,7 @@ def cholesky_jk_ghf(chol, G): return 0.5 * ecoul, -0.5 * exx # JK energy -def half_rotated_cholesky_jk(Ghalfa, Ghalfb, trial): +def half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial): """Compute exchange and coulomb contributions via jitted kernels. Parameters diff --git a/ipie/estimators/handler.py b/ipie/estimators/handler.py index a02190e8..ab9fc2da 100644 --- a/ipie/estimators/handler.py +++ b/ipie/estimators/handler.py @@ -43,6 +43,8 @@ class EstimatorHandler(object): Parameters ---------- + system : :class:`ipie.hubbard.Hubbard` / system object in general. + Container for model input options. comm : MPI.COMM_WORLD MPI Communicator trial : :class:`ipie.trial_wavefunction.X' object @@ -62,6 +64,7 @@ class EstimatorHandler(object): def __init__( self, comm, + system, hamiltonian, trial, walker_state=None, @@ -104,6 +107,7 @@ def __init__( for obs in observables: try: est = _predefined_estimators[obs]( + system=system, hamiltonian=hamiltonian, trial=trial, ) @@ -186,7 +190,7 @@ def increment_file_number(self): self.index = self.index + 1 self.filename = self.basename + f".{self.index}.h5" - def compute_estimators(self, hamiltonian, trial, walker_batch): + def compute_estimators(self, comm, system, hamiltonian, trial, walker_batch): """Update estimators with bached psi Parameters @@ -197,7 +201,7 @@ def compute_estimators(self, hamiltonian, trial, walker_batch): # TODO: generalize for different block groups (loop over groups) offset = self.num_walker_props for k, e in self.items(): - e.compute_estimator(walker_batch, hamiltonian, trial) + e.compute_estimator(system, walker_batch, hamiltonian, trial) start = offset + self.get_offset(k) end = start + int(self[k].size) self.local_estimates[start:end] += e.data diff --git a/ipie/estimators/local_energy.py b/ipie/estimators/local_energy.py index 756c548c..db032a20 100644 --- a/ipie/estimators/local_energy.py +++ b/ipie/estimators/local_energy.py @@ -16,20 +16,20 @@ # Fionn Malone # -import numpy - from ipie.estimators.generic import local_energy_cholesky_opt, local_energy_generic_cholesky from ipie.estimators.greens_function_single_det import gab_mod_ovlp from ipie.legacy.estimators.ci import get_hmatel from ipie.utils.backend import arraylib as xp -def local_energy_G(hamiltonian, trial, G, Ghalf): +def local_energy_G(system, hamiltonian, trial, G, Ghalf): """Compute local energy from a given Green's function G. Parameters ---------- - hamiltonian : hamiltonian object + system : system object + System being studied. + system : hamiltonian object Hamiltonian being studied. trial : trial wavefunction object Trial wavefunction. @@ -49,31 +49,32 @@ def local_energy_G(hamiltonian, trial, G, Ghalf): # if type(hamiltonian) == Generic[hamiltonian.chol.dtype]: if Ghalf is not None: return local_energy_cholesky_opt( + system, hamiltonian.ecore, Ghalfa=Ghalf[0], Ghalfb=Ghalf[1], trial=trial, ) else: - return local_energy_generic_cholesky(hamiltonian, G) + return local_energy_generic_cholesky(system, hamiltonian, G) -def local_energy(hamiltonian, walker, trial): - return local_energy_G(hamiltonian, trial, walker.G, walker.Ghalf) +def local_energy(system, hamiltonian, walker, trial): + return local_energy_G(system, hamiltonian, trial, walker.G, walker.Ghalf) -def variational_energy(hamiltonian, trial): +def variational_energy(system, hamiltonian, trial): assert len(trial.psi.shape) == 2 or len(trial.psi) == 1 - return local_energy(hamiltonian, trial, trial) + return local_energy(system, hamiltonian, trial, trial) -def variational_energy_ortho_det(nelec, hamiltonian, occs, coeffs): +def variational_energy_ortho_det(system, hamiltonian, occs, coeffs): """Compute variational energy for CI-like multi-determinant expansion. Parameters ---------- - nelec :tuple - Number of alpha and beta electrons. + system : :class:`ipie.system` object + System object. occs : list of lists list of determinants. coeffs : :class:`numpy.ndarray` @@ -88,13 +89,13 @@ def variational_energy_ortho_det(nelec, hamiltonian, occs, coeffs): denom = 0.0 one_body = 0.0 two_body = 0.0 - ne = numpy.sum(nelec) + nel = system.nup + system.ndown for i, (occi, ci) in enumerate(zip(occs, coeffs)): denom += ci.conj() * ci for j in range(0, i + 1): cj = coeffs[j] occj = occs[j] - etot, e1b, e2b = ci.conj() * cj * get_hmatel(hamiltonian, ne, occi, occj) + etot, e1b, e2b = ci.conj() * cj * get_hmatel(hamiltonian, nel, occi, occj) evar += etot one_body += e1b two_body += e2b @@ -106,7 +107,7 @@ def variational_energy_ortho_det(nelec, hamiltonian, occs, coeffs): return evar / denom, one_body / denom, two_body / denom -def variational_energy_noci(hamiltonian, trial): +def variational_energy_noci(system, hamiltonian, trial): weight = 0 energies = 0 denom = 0 @@ -119,7 +120,7 @@ def variational_energy_noci(hamiltonian, trial): weight = (trial.coeffs[i].conj() * trial.coeffs[j]) * ovlp G = xp.array([Gup, Gdn]) # Ghalf = [Ghalfa, Ghalfb] - e = xp.array(local_energy_G(hamiltonian, trial, G, Ghalf=None)) + e = xp.array(local_energy_G(system, hamiltonian, trial, G, Ghalf=None)) energies += weight * e denom += weight return tuple(energies / denom) diff --git a/ipie/estimators/local_energy_batch.py b/ipie/estimators/local_energy_batch.py index b62cb525..ddf491eb 100644 --- a/ipie/estimators/local_energy_batch.py +++ b/ipie/estimators/local_energy_batch.py @@ -33,11 +33,13 @@ # TODO: should pass hamiltonian here and make it work for all possible types # this is a generic local_energy handler. So many possible combinations of local energy strategies... -def local_energy_batch(hamiltonian, walkers, trial): +def local_energy_batch(system, hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : Walkers object @@ -55,31 +57,35 @@ def local_energy_batch(hamiltonian, walkers, trial): if config.get_option("use_gpu"): if hamiltonian.chunked: return local_energy_single_det_uhf_batch_chunked_gpu( - hamiltonian, walkers, trial) + system, hamiltonian, walkers, trial + ) else: - return local_energy_single_det_batch_gpu(hamiltonian, walkers, trial) + return local_energy_single_det_batch_gpu(system, hamiltonian, walkers, trial) elif walkers.rhf: - return local_energy_single_det_rhf_batch(hamiltonian, walkers, trial) + return local_energy_single_det_rhf_batch(system, hamiltonian, walkers, trial) else: if hamiltonian.chunked: return local_energy_single_det_uhf_batch_chunked( - hamiltonian, walkers, trial) + system, hamiltonian, walkers, trial + ) else: - return local_energy_single_det_uhf(hamiltonian, walkers, trial) + return local_energy_single_det_uhf(system, hamiltonian, walkers, trial) # \TODO switch to this - # return local_energy_single_det_uhf(hamiltonian, walkers, trial) + # return local_energy_single_det_uhf(system, hamiltonian, walkers, trial) else: print("# Warning: local_energy_batch is not production level for multi-det trials.") - return local_energy_multi_det_trial_batch(hamiltonian, walkers, trial) + return local_energy_multi_det_trial_batch(system, hamiltonian, walkers, trial) -def local_energy_multi_det_trial_batch(hamiltonian, walkers, trial): +def local_energy_multi_det_trial_batch(system, hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once) with MSD. Naive O(Ndet) algorithm, no optimizations. Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : Walkers object @@ -113,7 +119,7 @@ def local_energy_multi_det_trial_batch(hamiltonian, walkers, trial): G = [Ga[idet], Gb[idet]] _ = [Ghalfa[idet], Ghalfb[idet]] # return (e1b+e2b+ham.ecore, e1b+ham.ecore, e2b) - e = list(local_energy_G(hamiltonian, trial, G, Ghalf=None)) + e = list(local_energy_G(system, hamiltonian, trial, G, Ghalf=None)) numer0 += w[idet] * e[0] numer1 += w[idet] * e[1] numer2 += w[idet] * e[2] diff --git a/ipie/estimators/local_energy_noci.py b/ipie/estimators/local_energy_noci.py index f2947650..0f56420d 100644 --- a/ipie/estimators/local_energy_noci.py +++ b/ipie/estimators/local_energy_noci.py @@ -20,13 +20,14 @@ exx_kernel_batch_real_rchol, ) from ipie.hamiltonians.generic import GenericRealChol +from ipie.systems.generic import Generic from ipie.trial_wavefunction.noci import NOCI from ipie.utils.backend import arraylib as xp from ipie.walkers.uhf_walkers import UHFWalkersNOCI def local_energy_noci( - hamiltonian: GenericRealChol, walkers: UHFWalkersNOCI, trial: NOCI + system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkersNOCI, trial: NOCI ): """Compute local energy for walker batch (all walkers at once). @@ -34,6 +35,8 @@ def local_energy_noci( Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch diff --git a/ipie/estimators/local_energy_sd.py b/ipie/estimators/local_energy_sd.py index dc186829..279ae022 100644 --- a/ipie/estimators/local_energy_sd.py +++ b/ipie/estimators/local_energy_sd.py @@ -26,6 +26,7 @@ from ipie.utils.backend import arraylib as xp from ipie.utils.backend import synchronize +from ipie.systems.generic import Generic from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol from ipie.walkers.uhf_walkers import UHFWalkers from ipie.trial_wavefunction.single_det import SingleDet @@ -259,6 +260,7 @@ def exx_kernel_batch_complex_rchol(rchol, rcholbar, Ghalf_batch): @plum.dispatch def local_energy_single_det_uhf( + system: Generic, hamiltonian: GenericComplexChol, walkers: UHFWalkers, trial: SingleDet, @@ -269,6 +271,8 @@ def local_energy_single_det_uhf( Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -311,13 +315,15 @@ def local_energy_single_det_uhf( return energy -def local_energy_single_det_batch(hamiltonian, walkers, trial): +def local_energy_single_det_batch(system, hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Single determinant case. Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -335,13 +341,13 @@ def local_energy_single_det_batch(hamiltonian, walkers, trial): for idx in range(nwalkers): G = [walkers.Ga[idx], walkers.Gb[idx]] Ghalf = [walkers.Ghalfa[idx], walkers.Ghalfb[idx]] - energy += [list(local_energy_G(hamiltonian, trial, G, Ghalf))] + energy += [list(local_energy_G(system, hamiltonian, trial, G, Ghalf))] energy = xp.array(energy, dtype=numpy.complex128) return energy -def local_energy_single_det_batch_einsum(hamiltonian, walkers, trial): +def local_energy_single_det_batch_einsum(system, hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Use einsum rather than numba kernels. @@ -350,6 +356,8 @@ def local_energy_single_det_batch_einsum(hamiltonian, walkers, trial): Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -434,13 +442,15 @@ def local_energy_single_det_batch_einsum(hamiltonian, walkers, trial): return energy -def local_energy_single_det_rhf_batch(hamiltonian, walkers, trial): +def local_energy_single_det_rhf_batch(system, hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Single determinant RHF case. Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -537,7 +547,7 @@ def two_body_energy_uhf(trial, walkers): @plum.dispatch def local_energy_single_det_uhf( - hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: SingleDet + system: Generic, hamiltonian: GenericRealChol, walkers: UHFWalkers, trial: SingleDet ): """Compute local energy for walker batch (all walkers at once). @@ -545,6 +555,8 @@ def local_energy_single_det_uhf( Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -584,7 +596,7 @@ def local_energy_single_det_uhf( return energy -def local_energy_single_det_batch_gpu_old(hamiltonian, walkers, trial): +def local_energy_single_det_batch_gpu_old(system, hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Single determinant UHF GPU case. @@ -593,6 +605,8 @@ def local_energy_single_det_batch_gpu_old(hamiltonian, walkers, trial): Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -661,7 +675,7 @@ def local_energy_single_det_batch_gpu_old(hamiltonian, walkers, trial): return energy -def local_energy_single_det_batch_gpu(hamiltonian, walkers, trial, max_mem=2.0): +def local_energy_single_det_batch_gpu(system, hamiltonian, walkers, trial, max_mem=2.0): """Compute local energy for walker batch (all walkers at once). Single determinant UHF GPU case. @@ -670,6 +684,8 @@ def local_energy_single_det_batch_gpu(hamiltonian, walkers, trial, max_mem=2.0): Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch diff --git a/ipie/estimators/local_energy_sd_chunked.py b/ipie/estimators/local_energy_sd_chunked.py index b167b8e6..c164d90e 100644 --- a/ipie/estimators/local_energy_sd_chunked.py +++ b/ipie/estimators/local_energy_sd_chunked.py @@ -35,13 +35,15 @@ # are accumulated. -def local_energy_single_det_uhf_batch_chunked(hamiltonian, walker_batch, trial): +def local_energy_single_det_uhf_batch_chunked(system, hamiltonian, walker_batch, trial): """Compute local energy for walker batch (all walkers at once). Single determinant UHF case. Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walker_batch : WalkerBatch @@ -233,7 +235,7 @@ def exx_kernel_batch_rchol_gpu_low_mem(rchola_chunk, Ghalfa, buff): def local_energy_single_det_uhf_batch_chunked_gpu( - hamiltonian, walker_batch, trial, max_mem=2.0 + system, hamiltonian, walker_batch, trial, max_mem=2.0 ): """Compute local energy for walker batch (all walkers at once). @@ -241,6 +243,8 @@ def local_energy_single_det_uhf_batch_chunked_gpu( Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walker_batch : WalkerBatch diff --git a/ipie/estimators/local_energy_wicks.py b/ipie/estimators/local_energy_wicks.py index eacb8b7b..b16d6d99 100644 --- a/ipie/estimators/local_energy_wicks.py +++ b/ipie/estimators/local_energy_wicks.py @@ -32,13 +32,15 @@ from ipie.utils.linalg import minor_mask, minor_mask4 -def local_energy_multi_det_trial_wicks_batch(hamiltonian, walkers, trial): +def local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walkers, trial): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -75,7 +77,7 @@ def local_energy_multi_det_trial_wicks_batch(hamiltonian, walkers, trial): G0 = [G0a, G0b] # contribution 1 (disconnected) - cont1 = local_energy_generic_cholesky(hamiltonian, G0)[2] + cont1 = local_energy_generic_cholesky(system, hamiltonian, G0)[2] # contribution 2 (half-connected, two-leg, one-body-like) # First, Coulomb-like term @@ -547,7 +549,7 @@ def build_contributions12( return cont1_J + cont1_K, cont2_J + cont2_K -def local_energy_multi_det_trial_wicks_batch_opt_chunked(hamiltonian, walkers, trial, max_mem=2.0): +def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, hamiltonian, walkers, trial, max_mem=2.0): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. @@ -559,6 +561,8 @@ def local_energy_multi_det_trial_wicks_batch_opt_chunked(hamiltonian, walkers, t Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch @@ -857,7 +861,7 @@ def local_energy_multi_det_trial_wicks_batch_opt_chunked(hamiltonian, walkers, t return walker_energies -def local_energy_multi_det_trial_wicks_batch_opt(hamiltonian, walkers, trial, max_mem=2.0): +def local_energy_multi_det_trial_wicks_batch_opt(system, hamiltonian, walkers, trial, max_mem=2.0): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. @@ -870,6 +874,8 @@ def local_energy_multi_det_trial_wicks_batch_opt(hamiltonian, walkers, trial, ma Parameters ---------- + system : system object + System being studied. hamiltonian : hamiltonian object Hamiltonian being studied. walkers : WalkerBatch diff --git a/ipie/estimators/tests/test_estimators.py b/ipie/estimators/tests/test_estimators.py index 79c7465e..9ea3f75f 100644 --- a/ipie/estimators/tests/test_estimators.py +++ b/ipie/estimators/tests/test_estimators.py @@ -30,9 +30,9 @@ def test_energy_estimator(): nocc = 8 naux = 30 nwalker = 10 - system, ham, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) - estim = EnergyEstimator(hamiltonian=ham, trial=trial) - estim.compute_estimator(walker_batch, ham, trial) + system, hamiltonian, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) + estim = EnergyEstimator(system=system, hamiltonian=hamiltonian, trial=trial) + estim.compute_estimator(system, walker_batch, hamiltonian, trial) assert len(estim.names) == 5 assert estim["ENumer"].real == pytest.approx(-754.0373585215561) assert estim["ETotal"] == pytest.approx(0.0) @@ -54,15 +54,16 @@ def test_estimator_handler(): nocc = 8 naux = 30 nwalker = 10 - system, ham, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) - estim = EnergyEstimator(hamiltonian=ham, trial=trial, filename=tmp1.name) + system, hamiltonian, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) + estim = EnergyEstimator(system=system, hamiltonian=hamiltonian, trial=trial, filename=tmp1.name) estim.print_to_stdout = False from ipie.config import MPI comm = MPI.COMM_WORLD handler = EstimatorHandler( comm, - ham, + system, + hamiltonian, trial, block_size=10, observables=("energy",), @@ -71,8 +72,8 @@ def test_estimator_handler(): handler["energy1"] = estim handler.json_string = "" handler.initialize(comm) - handler.compute_estimators(ham, trial, walker_batch) - handler.compute_estimators(ham, trial, walker_batch) + handler.compute_estimators(comm, system, hamiltonian, trial, walker_batch) + handler.compute_estimators(comm, system, hamiltonian, trial, walker_batch) if __name__ == "__main__": diff --git a/ipie/estimators/tests/test_generic.py b/ipie/estimators/tests/test_generic.py index 0f2b28ce..95a42120 100644 --- a/ipie/estimators/tests/test_generic.py +++ b/ipie/estimators/tests/test_generic.py @@ -33,16 +33,16 @@ def test_local_energy_cholesky(): numpy.random.seed(7) nmo = 24 nelec = (4, 2) - nup, ndown = nelec h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=enuc, ) - ci, wfn = get_random_nomsd(nup, ndown, ham.nbasis, ndet=1, cplx=False) + ci, wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - e = local_energy_generic_cholesky(ham, trial.G, Ghalf=trial.Ghalf) + e = local_energy_generic_cholesky(system, hamiltonian, trial.G, Ghalf=trial.Ghalf) assert e[0] == pytest.approx(20.6826247016273) assert e[1] == pytest.approx(23.0173528796140) assert e[2] == pytest.approx(-2.3347281779866) @@ -53,17 +53,17 @@ def test_local_energy_cholesky_opt(): numpy.random.seed(7) nmo = 24 nelec = (4, 2) - nup, ndown = nelec h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=enuc, ) - ci, wfn = get_random_nomsd(nup, ndown, ham.nbasis, ndet=1, cplx=False) + ci, wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - trial.half_rotate(ham) - e = local_energy_cholesky_opt(ham.ecore, trial.Ghalf[0], trial.Ghalf[1], trial) + trial.half_rotate(hamiltonian) + e = local_energy_cholesky_opt(system, hamiltonian.ecore, trial.Ghalf[0], trial.Ghalf[1], trial) assert e[0] == pytest.approx(20.6826247016273) assert e[1] == pytest.approx(23.0173528796140) assert e[2] == pytest.approx(-2.3347281779866) @@ -76,20 +76,21 @@ def test_local_energy_cholesky_opt_batched(): nelec = (4, 2) h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - ham = HamGeneric( + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=enuc, ) - wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) - trial = MultiSlater(system, ham, wfn) - trial.half_rotate(ham) + wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) + trial = MultiSlater(system, hamiltonian, wfn) + trial.half_rotate(hamiltonian) Ga_batched = numpy.array([trial.G[0], trial.G[0], trial.G[0]]) Gb_batched = numpy.array([trial.G[1], trial.G[1], trial.G[1]]) Gahalf_batched = numpy.array([trial.Ghalf[0], trial.Ghalf[0], trial.Ghalf[0]]) Gbhalf_batched = numpy.array([trial.Ghalf[1], trial.Ghalf[1], trial.Ghalf[1]]) res = local_energy_generic_cholesky_opt_batched( - ham, + system, + hamiltonian, Ga_batched, Gb_batched, Gahalf_batched, diff --git a/ipie/estimators/tests/test_generic_batch.py b/ipie/estimators/tests/test_generic_batch.py index 73232e99..9fdb4abf 100644 --- a/ipie/estimators/tests/test_generic_batch.py +++ b/ipie/estimators/tests/test_generic_batch.py @@ -43,34 +43,33 @@ def test_greens_function_batch(): numpy.random.seed(7) nmo = 10 nelec = (6, 5) - nup, ndown = nelec nwalkers = 12 nsteps = 25 dt = 0.005 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) trial = ParticleHole(wfn, nelec, nmo) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) from ipie.legacy.hamiltonians.generic import Generic as LegacyHamGeneric - legacy_ham = LegacyHamGeneric( + legacy_hamiltonian = LegacyHamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) - system = Generic(nelec=nelec) - legacy_walkers = build_legacy_test_case(wfn, init, system, legacy_ham, nsteps, nwalkers, dt) + legacy_walkers = build_legacy_test_case(wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) numpy.random.seed(7) - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) for iw in range(nwalkers): walkers.phia[iw] = legacy_walkers[iw].phi[:, : nelec[0]].copy() @@ -92,18 +91,18 @@ def test_local_energy_single_det_batch(): numpy.random.seed(7) nmo = 10 nelec = (5, 5) - nup, ndown = nelec nwalkers = 10 nsteps = 25 dt = 0.005 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - ci_wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -112,34 +111,33 @@ def test_local_energy_single_det_batch(): wfn[:, nelec[0] :] = I[:, occb0] trial = SingleDet(wfn, nelec, nmo) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) from ipie.legacy.hamiltonians.generic import Generic as LegacyHamGeneric - legacy_ham = LegacyHamGeneric( + legacy_hamiltonian = LegacyHamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, options={"symmetry": False}, ) numpy.random.seed(7) - system = Generic(nelec=nelec) - legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) - etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) + legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) + etots, e1s, e2s = get_legacy_walker_energies(system, legacy_hamiltonian, trial, legacy_walkers) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": 10}) prop = PhaselessGeneric(time_step=qmc["dt"]) - prop.build(ham, trial) - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + prop.build(hamiltonian, trial) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) for i in range(nsteps): - prop.propagate_walkers(walkers, ham, trial, 0) + prop.propagate_walkers(walkers, hamiltonian, trial, 0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_batch(ham, walkers, trial) - energies_uhf = local_energy_single_det_uhf(ham, walkers, trial) + energies = local_energy_single_det_batch(system, hamiltonian, walkers, trial) + energies_uhf = local_energy_single_det_uhf(system, hamiltonian, walkers, trial) assert numpy.allclose(energies, energies_uhf) @@ -156,7 +154,6 @@ def test_local_energy_single_det_batch_packed(): numpy.random.seed(7) nmo = 10 nelec = (5, 5) - nup, ndown = nelec nwalkers = 10 nsteps = 25 dt = 0.005 @@ -171,7 +168,9 @@ def test_local_energy_single_det_batch_packed(): pack_cholesky(idx[0], idx[1], chol_packed, chol) chol = chol.reshape((nmo * nmo, nchol)) - ham = HamGeneric( + system = Generic(nelec=nelec) + + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol, ecore=0, @@ -179,7 +178,7 @@ def test_local_energy_single_det_batch_packed(): # options={"symmetry": True}, ) - legacy_ham = HamGenericRef( + legacy_hamiltonian = HamGenericRef( h1e=numpy.array([h1e, h1e]), chol=chol, ecore=0, @@ -188,7 +187,7 @@ def test_local_energy_single_det_batch_packed(): ) # Test PH type wavefunction. - ci_wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -197,29 +196,28 @@ def test_local_energy_single_det_batch_packed(): wfn[:, nelec[0] :] = I[:, occb0] trial = SingleDet(wfn, nelec, nmo) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) numpy.random.seed(7) - system = Generic(nelec=nelec) - legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) - etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) + legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) + etots, e1s, e2s = get_legacy_walker_energies(system, legacy_hamiltonian, trial, legacy_walkers) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(time_step=qmc["dt"]) - prop.build(ham, trial) - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + prop.build(hamiltonian, trial) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) for i in range(nsteps): - prop.propagate_walkers(walkers, ham, trial, 0.0) + prop.propagate_walkers(walkers, hamiltonian, trial, 0.0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_batch(ham, walkers, trial) + energies = local_energy_single_det_batch(system, hamiltonian, walkers, trial) for iw in range(nwalkers): # unnecessary test - # energy = local_energy_single_det_batch(ham, walkers, trial, iw = iw) + # energy = local_energy_single_det_batch(system, hamiltonian, walkers, trial, iw = iw) # assert numpy.allclose(energy, energies[iw]) assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) assert numpy.allclose(walkers.phib[iw], legacy_walkers[iw].phi[:, nelec[0] :]) @@ -233,15 +231,16 @@ def test_local_energy_single_det_batch_rhf(): numpy.random.seed(7) nmo = 10 nelec = (5, 5) - nup, ndown = nelec nwalkers = 10 nsteps = 25 dt = 0.005 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0 ) - ci_wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -250,38 +249,37 @@ def test_local_energy_single_det_batch_rhf(): wfn[:, nelec[0] :] = I[:, occb0] trial = SingleDet(wfn, nelec, nmo) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) init[:, : nelec[0]] = init[:, nelec[0] :].copy() numpy.random.seed(7) - legacy_ham = HamGenericRef( + legacy_hamiltonian = HamGenericRef( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, options={"symmetry": False}, ) - system = Generic(nelec=nelec) - legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) - etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) + legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) + etots, e1s, e2s = get_legacy_walker_energies(system, legacy_hamiltonian, trial, legacy_walkers) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": 10}) prop = PhaselessGeneric(time_step=qmc["dt"]) - prop.build(ham, trial) + prop.build(hamiltonian, trial) walker_opts = dotdict({"rhf": True}) # walkers = SingleDetWalkerBatch( - # system, ham, trial, nwalkers, init, walker_opts={"rhf": True} + # system, hamiltonian, trial, nwalkers, init, walker_opts={"rhf": True} # ) - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) walkers.rhf = True for i in range(nsteps): - prop.propagate_walkers(walkers, ham, trial, 0.0) + prop.propagate_walkers(walkers, hamiltonian, trial, 0.0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_rhf_batch(ham, walkers, trial) + energies = local_energy_single_det_rhf_batch(system, hamiltonian, walkers, trial) for iw in range(nwalkers): assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) @@ -296,7 +294,6 @@ def test_local_energy_single_det_batch_rhf_packed(): numpy.random.seed(7) nmo = 10 nelec = (5, 5) - nup, ndown = nelec nwalkers = 10 nsteps = 25 dt = 0.005 @@ -313,13 +310,14 @@ def test_local_energy_single_det_batch_rhf_packed(): pack_cholesky(idx[0], idx[1], chol_packed, chol) chol = chol.reshape((nmo * nmo, nchol)) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol, ecore=0, ) - legacy_ham = HamGenericRef( + legacy_hamiltonian = HamGenericRef( h1e=numpy.array([h1e, h1e]), chol=chol, ecore=0, @@ -327,7 +325,7 @@ def test_local_energy_single_det_batch_rhf_packed(): options={"symmetry": True}, ) - ci_wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -336,32 +334,31 @@ def test_local_energy_single_det_batch_rhf_packed(): wfn[:, nelec[0] :] = I[:, occb0] trial = SingleDet(wfn, nelec, nmo) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) init[:, : nelec[0]] = init[:, nelec[0] :].copy() numpy.random.seed(7) - system = Generic(nelec=nelec) - legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) - etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) + legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) + etots, e1s, e2s = get_legacy_walker_energies(system, legacy_hamiltonian, trial, legacy_walkers) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": 10}) prop = PhaselessGeneric(time_step=qmc["dt"]) - prop.build(ham, trial) + prop.build(hamiltonian, trial) walker_opts = dotdict({"rhf": True}) # walkers = SingleDetWalkerBatch( - # system, ham, trial, nwalkers, init, walker_opts=walker_opts + # system, hamiltonian, trial, nwalkers, init, walker_opts=walker_opts # ) - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) walkers.rhf = True for i in range(nsteps): - prop.propagate_walkers(walkers, ham, trial, 0.0) + prop.propagate_walkers(walkers, hamiltonian, trial, 0.0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_rhf_batch(ham, walkers, trial) + energies = local_energy_single_det_rhf_batch(system, hamiltonian, walkers, trial) for iw in range(nwalkers): assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) diff --git a/ipie/estimators/tests/test_generic_chunked.py b/ipie/estimators/tests/test_generic_chunked.py index 022b5be5..732d02aa 100644 --- a/ipie/estimators/tests/test_generic_chunked.py +++ b/ipie/estimators/tests/test_generic_chunked.py @@ -48,7 +48,6 @@ def test_generic_chunked(): numpy.random.seed(7) nmo = 24 nelec = (4, 2) - nup, ndown = nelec h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) h1e = comm.bcast(h1e) @@ -71,40 +70,40 @@ def test_generic_chunked(): chol = chol.reshape((nmo * nmo, nchol)) - ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, ecore=enuc) - _, wfn = get_random_nomsd(nup, ndown, ham.nbasis, ndet=1, cplx=False) + system = Generic(nelec=nelec) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, ecore=enuc) + _, wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) - system = Generic(nelec=nelec) - trial.calculate_energy(system, ham) + trial.calculate_energy(system, hamiltonian) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) mpi_handler = MPIHandler(nmembers=3, verbose=(rank == 0)) if comm.rank == 0: print("# Chunking hamiltonian.") - ham.chunk(mpi_handler) + hamiltonian.chunk(mpi_handler) if comm.rank == 0: print("# Chunking trial.") trial.chunk(mpi_handler) prop = PhaselessGenericChunked(time_step=qmc["dt"]) - prop.build(ham, trial, mpi_handler=mpi_handler) + prop.build(hamiltonian, trial, mpi_handler=mpi_handler) init_walker = numpy.hstack([trial.psi0a, trial.psi0b]) walkers = UHFWalkersTrial( - trial, init_walker, nup, ndown, ham.nbasis, nwalkers, mpi_handler=mpi_handler + trial, init_walker, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, mpi_handler=mpi_handler ) walkers.build(trial) for i in range(nsteps): - prop.propagate_walkers(walkers, ham, trial, trial.energy) + prop.propagate_walkers(walkers, hamiltonian, trial, trial.energy) walkers.reortho() - energies = local_energy_single_det_batch(ham, walkers, trial) + energies = local_energy_single_det_batch(system, hamiltonian, walkers, trial) - energies_chunked = local_energy_single_det_uhf_batch_chunked(ham, walkers, trial) + energies_chunked = local_energy_single_det_uhf_batch_chunked(system, hamiltonian, walkers, trial) assert numpy.allclose(energies, energies_chunked) diff --git a/ipie/estimators/tests/test_generic_chunked_gpu.py b/ipie/estimators/tests/test_generic_chunked_gpu.py index 8b3722d5..7305f1e3 100644 --- a/ipie/estimators/tests/test_generic_chunked_gpu.py +++ b/ipie/estimators/tests/test_generic_chunked_gpu.py @@ -55,7 +55,6 @@ def test_generic_chunked_gpu(): numpy.random.seed(7) nmo = 24 nelec = (4, 2) - nup, ndown = nelec h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) h1e = comm.bcast(h1e) @@ -78,46 +77,48 @@ def test_generic_chunked_gpu(): chol = chol.reshape((nmo * nmo, nchol)) - ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, chol_packed=chol_packed, ecore=enuc) - wfn = get_random_nomsd(nup, ndown, ham.nbasis, ndet=1, cplx=False) + system = Generic(nelec=nelec) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, chol_packed=chol_packed, ecore=enuc) + wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) - system = Generic(nelec=nelec) - trial.calculate_energy(system, ham) + trial.calculate_energy(system, hamiltonian) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) mpi_handler = MPIHandler(comm, options={"nmembers": 2}, verbose=(rank == 0)) if comm.rank == 0: print("# Chunking hamiltonian.") - ham.chunk(mpi_handler) + hamiltonian.chunk(mpi_handler) if comm.rank == 0: print("# Chunking trial.") trial.chunk(mpi_handler) prop = PhaselessGenericChunked(time_step=qmc["dt"]) - prop.build(ham, trial, mpi_handler=mpi_handler) + prop.build(hamiltonian, trial, mpi_handler=mpi_handler) walkers = UHFWalkersTrial( - trial, init, nup, ndown, ham.nbasis, nwalkers, mpi_handler=mpi_handler) + trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, mpi_handler=mpi_handler + ) walkers.build(trial) if not no_gpu: prop.cast_to_cupy() - ham.cast_to_cupy() + hamiltonian.cast_to_cupy() trial.cast_to_cupy() walkers.cast_to_cupy() for i in range(nsteps): - prop.propagate_walker_batch(walkers, system, ham, trial, trial.energy) + prop.propagate_walker_batch(walkers, system, hamiltonian, trial, trial.energy) walkers.reortho() trial._rchola = cupy.asarray(trial._rchola) trial._rcholb = cupy.asarray(trial._rcholb) - energies_einsum = local_energy_single_det_batch_gpu(ham, walkers, trial) - energies_chunked = local_energy_single_det_uhf_batch_chunked_gpu(ham, walkers, trial) + energies_einsum = local_energy_single_det_batch_gpu(system, hamiltonian, walkers, trial) + energies_chunked = local_energy_single_det_uhf_batch_chunked_gpu(system, hamiltonian, walkers, trial) energies_chunked_low_mem = local_energy_single_det_uhf_batch_chunked_gpu( - ham, walkers, trial, max_mem=1e-6) + system, hamiltonian, walkers, trial, max_mem=1e-6 + ) assert numpy.allclose(energies_einsum, energies_chunked) assert numpy.allclose(energies_einsum, energies_chunked_low_mem) diff --git a/ipie/estimators/tests/test_generic_complex.py b/ipie/estimators/tests/test_generic_complex.py index 5a5d630f..014716f7 100644 --- a/ipie/estimators/tests/test_generic_complex.py +++ b/ipie/estimators/tests/test_generic_complex.py @@ -22,6 +22,7 @@ from ipie.estimators.energy import local_energy from ipie.utils.testing import build_test_case_handlers +from ipie.systems.generic import Generic from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.utils.misc import dotdict @@ -54,21 +55,22 @@ def test_local_energy_single_det_vs_real(): trial_type="single_det", ) - ham = test_handler.hamiltonian + hamiltonian = test_handler.hamiltonian walkers = test_handler.walkers + system = Generic(nelec) trial = test_handler.trial - chol = ham.chol + chol = hamiltonian.chol cx_chol = numpy.array(chol, dtype=numpy.complex128) - cx_ham = HamGeneric( - numpy.array(ham.H1, dtype=numpy.complex128), cx_chol, ham.ecore, verbose=False + cx_hamiltonian = HamGeneric( + numpy.array(hamiltonian.H1, dtype=numpy.complex128), cx_chol, hamiltonian.ecore, verbose=False ) - energy = local_energy(ham, walkers, trial) + energy = local_energy(system, hamiltonian, walkers, trial) - trial.half_rotate(cx_ham) - cx_energy = local_energy(cx_ham, walkers, trial) + trial.half_rotate(cx_hamiltonian) + cx_energy = local_energy(system, cx_hamiltonian, walkers, trial) numpy.testing.assert_allclose(energy, cx_energy, atol=1e-10) @@ -102,20 +104,21 @@ def test_local_energy_single_det_vs_eri(): choltol=1e-10, ) - ham = test_handler.hamiltonian + hamiltonian = test_handler.hamiltonian walkers = test_handler.walkers + system = Generic(nelec) trial = test_handler.trial walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) - energy = local_energy(ham, walkers, trial) + energy = local_energy(system, hamiltonian, walkers, trial) etot = energy[:, 0] e1 = energy[:, 1] e2 = energy[:, 2] - nbasis = ham.nbasis - eri = ham.eri.reshape(nbasis, nbasis, nbasis, nbasis) - h1e = ham.H1[0] + nbasis = hamiltonian.nbasis + eri = hamiltonian.eri.reshape(nbasis, nbasis, nbasis, nbasis) + h1e = hamiltonian.H1[0] e1ref = numpy.einsum("ij,wij->w", h1e, walkers.Ga + walkers.Gb) @@ -123,7 +126,7 @@ def test_local_energy_single_det_vs_eri(): # testing 2-body term - chol = ham.chol.copy() + chol = hamiltonian.chol.copy() nchol = chol.shape[1] chol = chol.reshape(nbasis, nbasis, nchol) diff --git a/ipie/estimators/tests/test_generic_noci.py b/ipie/estimators/tests/test_generic_noci.py index 2732faf9..7bce2e44 100644 --- a/ipie/estimators/tests/test_generic_noci.py +++ b/ipie/estimators/tests/test_generic_noci.py @@ -22,6 +22,7 @@ from ipie.estimators.energy import local_energy from ipie.estimators.local_energy_wicks import local_energy_multi_det_trial_wicks_batch_opt_chunked from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.systems.generic import Generic from ipie.trial_wavefunction.noci import NOCI from ipie.trial_wavefunction.particle_hole import ParticleHole from ipie.trial_wavefunction.single_det import SingleDet @@ -34,28 +35,29 @@ def test_greens_function_noci(): np.random.seed(7) nmo = 12 nelec = (7, 7) - nup, ndown = nelec nwalkers = 10 nsteps = 100 ndets = 11 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) + system = Generic(nelec=nelec) + hamiltonian = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. coeffs, wfn, init = get_random_nomsd( - nup, ndown, ham.nbasis, ndet=ndets, init=True) + system.nup, system.ndown, hamiltonian.nbasis, ndet=ndets, init=True + ) trial = NOCI((coeffs, wfn), nelec, nmo) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) g = trial.build_one_rdm() assert np.isclose(g[0].trace(), nelec[0]) assert np.isclose(g[1].trace(), nelec[0]) - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) assert walkers.Gia.shape == (ndets, nwalkers, nmo, nmo) assert walkers.Ghalfa.shape == (ndets, nwalkers, nelec[0], nmo) assert walkers.Ga.shape == (nwalkers, nmo, nmo) assert walkers.Gb.shape == (nwalkers, nmo, nmo) - trial.calc_force_bias(ham, walkers) + trial.calc_force_bias(hamiltonian, walkers) ovlp_gf = trial.calc_greens_function(walkers) ovlp_ov = trial.calc_overlap(walkers) assert np.allclose(ovlp_gf, ovlp_ov) @@ -66,15 +68,15 @@ def test_local_energy_noci(): np.random.seed(7) nmo = 12 nelec = (7, 7) - nup, ndown = nelec nwalkers = 10 nsteps = 100 ndets = 11 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) + system = Generic(nelec=nelec) + hamiltonian = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. coeffs, wfn, init = get_random_nomsd( - nup, ndown, ham.nbasis, ndet=ndets, init=True, cplx=False + system.nup, system.ndown, hamiltonian.nbasis, ndet=ndets, init=True, cplx=False ) wfn0 = wfn[0].copy() for i in range(len(wfn)): @@ -82,36 +84,36 @@ def test_local_energy_noci(): coeffs[i] = coeffs[0] trial = NOCI((coeffs, wfn), nelec, nmo) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) g = trial.build_one_rdm() - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) - energy = local_energy(ham, walkers, trial) + energy = local_energy(system, hamiltonian, walkers, trial) trial_sd = SingleDet(wfn[0], nelec, nmo) - walkers_sd = UHFWalkersTrial(trial_sd, init, nup, ndown, ham.nbasis, nwalkers) + walkers_sd = UHFWalkersTrial(trial_sd, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) - energy_sd = local_energy(ham, walkers, trial) + energy_sd = local_energy(system, hamiltonian, walkers, trial) assert np.allclose(energy, energy_sd) coeffs, wfn, init = get_random_nomsd( - nup, ndown, ham.nbasis, ndet=ndets, init=True, cplx=False + system.nup, system.ndown, hamiltonian.nbasis, ndet=ndets, init=True, cplx=False ) trial = NOCI((coeffs, wfn), nelec, nmo) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) g = trial.build_one_rdm() - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) - energy = local_energy(ham, walkers, trial) + energy = local_energy(system, hamiltonian, walkers, trial) assert not np.allclose(energy, energy_sd) # Test against PHMSD - wfn, init = get_random_phmsd_opt(nup, ndown, ham.nbasis, ndet=11, init=True) + wfn, init = get_random_phmsd_opt(system.nup, system.ndown, hamiltonian.nbasis, ndet=11, init=True) trial_phmsd = ParticleHole( wfn, nelec, nmo, ) trial_phmsd.build() - trial_phmsd.half_rotate(ham) + trial_phmsd.half_rotate(hamiltonian) noci = np.zeros((ndets, nmo, sum(nelec))) for idet, (occa, occb) in enumerate(zip(wfn[1], wfn[2])): for iorb, occ in enumerate(occa): @@ -121,27 +123,23 @@ def test_local_energy_noci(): trial = NOCI((wfn[0], noci), nelec, nmo) trial.build() - trial.half_rotate(ham) - walkers = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + trial.half_rotate(hamiltonian) + walkers = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers.build(trial) ovlp_noci = trial.calc_overlap(walkers) trial.calc_greens_function(walkers) - fb_noci = trial.calc_force_bias(ham, walkers) - energy = local_energy(ham, walkers, trial) + fb_noci = trial.calc_force_bias(hamiltonian, walkers) + energy = local_energy(system, hamiltonian, walkers, trial) walkers_phmsd = UHFWalkersTrial( - trial_phmsd, init, nup, ndown, ham.nbasis, nwalkers + trial_phmsd, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walkers_phmsd.build(trial_phmsd) trial_phmsd.calc_greens_function(walkers_phmsd) assert np.allclose(ovlp_noci, trial_phmsd.calc_overlap(walkers_phmsd)) assert np.allclose(walkers_phmsd.Ga, walkers.Ga) assert np.allclose(walkers_phmsd.Gb, walkers.Gb) - assert np.allclose(fb_noci, trial_phmsd.calc_force_bias(ham, walkers)) + assert np.allclose(fb_noci, trial_phmsd.calc_force_bias(hamiltonian, walkers)) e_phmsd = local_energy_multi_det_trial_wicks_batch_opt_chunked( - ham, walkers_phmsd, trial_phmsd) + system, hamiltonian, walkers_phmsd, trial_phmsd + ) assert np.allclose(energy, e_phmsd) - - -if __name__ == '__main__': - test_greens_function_noci() - test_local_energy_noci() diff --git a/ipie/estimators/tests/test_generic_phmsd.py b/ipie/estimators/tests/test_generic_phmsd.py index 440c53a8..a6638f67 100644 --- a/ipie/estimators/tests/test_generic_phmsd.py +++ b/ipie/estimators/tests/test_generic_phmsd.py @@ -55,16 +55,16 @@ def test_greens_function_wicks_opt(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) - nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=3000, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=3000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # wfn_2 = (ci[:100], oa[:100], ob[:100]) @@ -84,28 +84,28 @@ def test_greens_function_wicks_opt(): trial_opt.build() numpy.random.seed(7) - walkers_wick = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walkers_wick = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers_wick.build(trial) - walkers_slow = UHFWalkersTrial(trial_slow, init, nup, ndown, ham.nbasis, nwalkers) + walkers_slow = UHFWalkersTrial(trial_slow, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers_slow.build(trial_slow) - walkers_opt = UHFWalkersTrial(trial_opt, init, nup, ndown, ham.nbasis, nwalkers) + walkers_opt = UHFWalkersTrial(trial_opt, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers_opt.build(trial_opt) options = {"hybrid": True} qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial) + prop.build(hamiltonian, trial) for i in range(nsteps): - prop.propagate_walkers(walkers_wick, ham, trial, 0) + prop.propagate_walkers(walkers_wick, hamiltonian, trial, 0) walkers_wick.reortho() numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_opt) + prop.build(hamiltonian, trial_opt) for i in range(nsteps): - prop.propagate_walkers(walkers_opt, ham, trial_opt, 0) + prop.propagate_walkers(walkers_opt, hamiltonian, trial_opt, 0) walkers_opt.reortho() numpy.random.seed(7) walkers_slow.phia = walkers_wick.phia @@ -139,15 +139,15 @@ def test_greens_function_edge_cases(): numpy.random.seed(7) nmo = 12 nelec = (1, 1) - nup, ndown = nelec nwalkers = 10 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) + system = Generic(nelec=nelec) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. - wfn, init = get_random_phmsd_opt(nup, ndown, ham.nbasis, ndet=1, init=True) + wfn, init = get_random_phmsd_opt(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) trial = ParticleHole(wfn, nelec, nmo, verbose=False) trial.build() - walkers_wick = UHFWalkersParticleHole(init, nup, ndown, ham.nbasis, nwalkers) + walkers_wick = UHFWalkersParticleHole(init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers_wick.build(trial) ovlps_ref_wick = greens_function_multi_det_wicks_opt(walkers_wick, trial) @@ -249,17 +249,17 @@ def test_det_matrix(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) - nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=3000, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=3000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -268,19 +268,19 @@ def test_det_matrix(): nmo, ) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial) + prop.build(hamiltonian, trial) - walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walker_batch.build(trial) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch, ham, trial, 0) + prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) walker_batch.reortho() nexcit = 4 @@ -314,19 +314,19 @@ def test_phmsd_local_energy(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) - nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - # wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=5, init=True) + # wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=5, init=True) wfn, init = get_random_phmsd( - nup, ndown, ham.nbasis, ndet=3000, init=True, cmplx=False + system.nup, system.ndown, hamiltonian.nbasis, ndet=3000, init=True, cmplx=False ) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too @@ -342,39 +342,39 @@ def test_phmsd_local_energy(): nmo, ) trial_slow.build() - trial_slow.half_rotate(ham) + trial_slow.half_rotate(hamiltonian) trial_test = ParticleHoleNonChunked( wfn_2, nelec, nmo, ) trial_test.build() - trial_test.half_rotate(ham) + trial_test.half_rotate(hamiltonian) numpy.random.seed(7) - walkers_wick = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walkers_wick = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walkers_wick.build(trial) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) options = {"hybrid": True} - walker_batch = UHFWalkersTrial(trial_slow, init, nup, ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial_slow, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walker_batch.build(trial_slow) walker_batch_test = UHFWalkersTrial( - trial_test, init, nup, ndown, ham.nbasis, nwalkers + trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_test.build(trial_test) walker_batch_test2 = UHFWalkersTrial( - trial, init, nup, ndown, ham.nbasis, nwalkers + trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_test2.build(trial) numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_slow) + prop.build(hamiltonian, trial_slow) for i in range(nsteps): - prop.propagate_walkers(walker_batch, ham, trial_slow, 0) + prop.propagate_walkers(walker_batch, hamiltonian, trial_slow, 0) walker_batch.reortho() import copy @@ -396,10 +396,11 @@ def test_phmsd_local_energy(): assert numpy.allclose(walker_batch_test2.Gb, walker_batch.Gb) assert numpy.allclose(walker_batch_test.det_ovlpas, walker_batch_test2.det_ovlpas) assert numpy.allclose(walker_batch_test.det_ovlpbs, walker_batch_test2.det_ovlpbs) - e_simple = local_energy_multi_det_trial_batch(ham, walker_batch, trial) - e_wicks = local_energy_multi_det_trial_wicks_batch(ham, walker_batch_test2, trial) + e_simple = local_energy_multi_det_trial_batch(system, hamiltonian, walker_batch, trial) + e_wicks = local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walker_batch_test2, trial) e_wicks_opt = local_energy_multi_det_trial_wicks_batch_opt( - ham, walker_batch_test, trial_test) + system, hamiltonian, walker_batch_test, trial_test + ) assert numpy.allclose(e_simple, e_wicks) assert numpy.allclose(e_simple, e_wicks_opt) @@ -411,16 +412,16 @@ def test_kernels_energy(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) - nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) - wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=5000, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=5000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -433,13 +434,13 @@ def test_kernels_energy(): numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial) + prop.build(hamiltonian, trial) - walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walker_batch.build(trial) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch, ham, trial, 0) + prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) walker_batch.reortho() greens_function_multi_det_wicks_opt(walker_batch, trial) @@ -453,15 +454,15 @@ def test_kernels_energy(): ) ndets = trial.num_dets - nchol = ham.nchol + nchol = hamiltonian.nchol ref = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) test = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) slices_alpha, slices_beta = trial.slices_alpha, trial.slices_beta - nbasis = ham.nbasis + nbasis = hamiltonian.nbasis from ipie.utils.testing import shaped_normal - Laa = shaped_normal((nwalkers, nbasis, nup, nchol)) - Lbb = shaped_normal((nwalkers, nbasis, ndown, nchol)) + Laa = shaped_normal((nwalkers, nbasis, system.nup, nchol)) + Lbb = shaped_normal((nwalkers, nbasis, system.ndown, nchol)) # 1. fill_opp_spin_factors_batched_singles( trial.cre_ex_b[1], @@ -628,17 +629,17 @@ def test_kernels_gf(): numpy.random.seed(7) nmo = 12 nelec = (7, 7) - nup, ndown = nelec nwalkers = 10 nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, # options={"symmetry": False}, ) - wfn, init = get_random_phmsd(nup, ndown, ham.nbasis, ndet=5000, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=5000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -651,14 +652,14 @@ def test_kernels_gf(): numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial) + prop.build(hamiltonian, trial) - walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walker_batch.build(trial) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch, ham, trial, 0) + prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) walker_batch.reortho() trial.calc_greens_function(walker_batch) @@ -666,7 +667,7 @@ def test_kernels_gf(): from ipie.estimators.kernels.cpu import wicks as wk ndets = trial.num_dets - nchol = ham.nchol + nchol = hamiltonian.nchol ref = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) test = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) ovlpa = walker_batch.det_ovlpas @@ -745,13 +746,13 @@ def test_kernels_gf_active_space(): numpy.random.seed(7) nmo = 30 nelec = (9, 9) - nup, ndown = nelec nwalkers = 1 nsteps = 100 nact = 12 ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -798,24 +799,24 @@ def test_kernels_gf_active_space(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_ref) + prop.build(hamiltonian, trial_ref) I = numpy.eye(nmo) init = numpy.hstack([I[:, : nelec[0]], I[:, : nelec[1]]]) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, nup, ndown, ham.nbasis, nwalkers + trial_ref, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, nup, ndown, ham.nbasis, nwalkers + trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_test.build(trial_test) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch_ref, ham, trial_ref, 0) + prop.propagate_walkers(walker_batch_ref, hamiltonian, trial_ref, 0) walker_batch_ref.reortho() walker_batch_test.phia = walker_batch_ref.phia.copy() @@ -831,7 +832,7 @@ def test_kernels_gf_active_space(): from ipie.estimators.kernels.cpu import wicks as wk ndets = trial_ref.num_dets - nchol = ham.nchol + nchol = hamiltonian.nchol ref = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) test = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) ovlpa = walker_batch_ref.det_ovlpas @@ -933,13 +934,13 @@ def test_kernels_energy_active_space(): numpy.random.seed(7) nmo = 30 nelec = (9, 9) - nup, ndown = nelec nwalkers = 1 nsteps = 100 nact = 12 ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -993,21 +994,21 @@ def test_kernels_energy_active_space(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_ref) + prop.build(hamiltonian, trial_ref) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, nup, ndown, ham.nbasis, nwalkers + trial_ref, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, nup, ndown, ham.nbasis, nwalkers + trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_test.build(trial_test) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch_ref, ham, trial_ref, 0) + prop.propagate_walkers(walker_batch_ref, hamiltonian, trial_ref, 0) walker_batch_ref.reortho() walker_batch_test.phia = walker_batch_ref.phia.copy() @@ -1023,7 +1024,7 @@ def test_kernels_energy_active_space(): from ipie.estimators.kernels.cpu import wicks as wk ndets = trial_ref.num_dets - nchol = ham.nchol + nchol = hamiltonian.nchol ref = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) test = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) ovlpa = walker_batch_ref.det_ovlpas @@ -1039,7 +1040,7 @@ def test_kernels_energy_active_space(): walker_batch_ref.CIb.fill(0.0 + 0.0j) from ipie.utils.testing import shaped_normal - Lbb = shaped_normal((nwalkers, nmo, ndown, nchol)) + Lbb = shaped_normal((nwalkers, nmo, system.ndown, nchol)) slices_alpha, slices_beta = trial_test.slices_alpha, trial_test.slices_beta assert trial_ref.nfrozen != trial_test.nfrozen # 1. @@ -1216,14 +1217,14 @@ def test_phmsd_local_energy_active_space(): numpy.random.seed(7) nmo = 30 nelec = (9, 9) - nup, ndown = nelec nwalkers = 1 nsteps = 100 nact = 12 ncore = 2 core = [0, 1] h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -1250,7 +1251,7 @@ def test_phmsd_local_energy_active_space(): nmo, ) trial_ref.build() - trial_ref.half_rotate(ham) + trial_ref.half_rotate(hamiltonian) trial_test = ParticleHoleNonChunked( wfn_2, @@ -1258,28 +1259,28 @@ def test_phmsd_local_energy_active_space(): nmo, ) trial_test.build() - trial_test.half_rotate(ham) + trial_test.half_rotate(hamiltonian) I = numpy.eye(nmo) init = numpy.hstack([I[:, : nelec[0]], I[:, : nelec[1]]]) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_ref) + prop.build(hamiltonian, trial_ref) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, nup, ndown, ham.nbasis, nwalkers + trial_ref, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, nup, ndown, ham.nbasis, nwalkers + trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_test.build(trial_test) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch_ref, ham, trial_ref, 0) + prop.propagate_walkers(walker_batch_ref, hamiltonian, trial_ref, 0) walker_batch_ref.reortho() import copy @@ -1299,9 +1300,10 @@ def test_phmsd_local_energy_active_space(): # assert numpy.allclose(walker_batch_test.CIa, walker_batch_ref.CIa) # assert numpy.allclose(walker_batch_test.CIb, walker_batch_ref.CIb) assert trial_ref.nfrozen != trial_test.nfrozen - e_wicks_opt = local_energy_multi_det_trial_wicks_batch(ham, walker_batch_ref, trial_ref) + e_wicks_opt = local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walker_batch_ref, trial_ref) e_wicks_opt_act = local_energy_multi_det_trial_wicks_batch_opt( - ham, walker_batch_test, trial_test) + system, hamiltonian, walker_batch_test, trial_test + ) assert numpy.allclose(e_wicks_opt, e_wicks_opt_act) @@ -1310,15 +1312,14 @@ def test_phmsd_local_energy_active_space(): def test_phmsd_local_energy_active_space_polarised(): numpy.random.seed(7) nelec = (9, 7) - nup, ndown = nelec - ne = numpy.sum(nelec) nwalkers = 1 nsteps = 10 nact = 12 nmo = 20 ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -1327,7 +1328,7 @@ def test_phmsd_local_energy_active_space_polarised(): from ipie.utils.testing import get_random_phmsd_opt, shaped_normal wfn, init = get_random_phmsd_opt(7, 5, nact, ndet=100, init=True) - init = shaped_normal((nmo, ne)) + init = shaped_normal((nmo, system.ne)) ci, occa, occb = wfn core = [0, 1] with_core_a = numpy.array( @@ -1343,14 +1344,14 @@ def test_phmsd_local_energy_active_space_polarised(): nmo, ) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) trial_test = ParticleHoleNonChunked( wfn, nelec, nmo, ) trial_test.build() - trial_test.half_rotate(ham) + trial_test.half_rotate(hamiltonian) trial_test_chunked = ParticleHole( wfn, nelec, @@ -1358,41 +1359,41 @@ def test_phmsd_local_energy_active_space_polarised(): num_det_chunks=4, ) trial_test_chunked.build() - trial_test_chunked.half_rotate(ham) + trial_test_chunked.half_rotate(hamiltonian) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) options = {"hybrid": True} - walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walker_batch.build(trial) walker_batch_test = UHFWalkersTrial( - trial_test, init, nup, ndown, ham.nbasis, nwalkers + trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_test.build(trial_test) walker_batch_test_chunked = UHFWalkersTrial( - trial_test_chunked, init, nup, ndown, ham.nbasis, nwalkers + trial_test_chunked, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_test_chunked.build(trial_test_chunked) numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial) + prop.build(hamiltonian, trial) for i in range(nsteps): - prop.propagate_walkers(walker_batch, ham, trial, 0) + prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) walker_batch.reortho() numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_test) + prop.build(hamiltonian, trial_test) for i in range(nsteps): - prop.propagate_walkers(walker_batch_test, ham, trial_test, 0) + prop.propagate_walkers(walker_batch_test, hamiltonian, trial_test, 0) walker_batch_test.reortho() numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_test_chunked) + prop.build(hamiltonian, trial_test_chunked) for i in range(nsteps): - prop.propagate_walkers(walker_batch_test_chunked, ham, trial_test_chunked, 0) + prop.propagate_walkers(walker_batch_test_chunked, hamiltonian, trial_test_chunked, 0) walker_batch_test_chunked.reortho() greens_function_multi_det(walker_batch, trial, build_full=True) @@ -1404,27 +1405,28 @@ def test_phmsd_local_energy_active_space_polarised(): assert numpy.allclose(walker_batch.Gb, walker_batch_test.Gb) assert numpy.allclose(walker_batch.Ga, walker_batch_test_chunked.Ga) assert numpy.allclose(walker_batch.Gb, walker_batch_test_chunked.Gb) - e_ref = local_energy_multi_det_trial_batch(ham, walker_batch, trial) + e_ref = local_energy_multi_det_trial_batch(system, hamiltonian, walker_batch, trial) e_wicks = local_energy_multi_det_trial_wicks_batch_opt( - ham, walker_batch_test, trial_test) + system, hamiltonian, walker_batch_test, trial_test + ) assert numpy.allclose(e_ref, e_wicks) e_wicks_chunked = local_energy_multi_det_trial_wicks_batch_opt_chunked( - ham, walker_batch_test_chunked, trial_test_chunked) + system, hamiltonian, walker_batch_test_chunked, trial_test_chunked + ) @pytest.mark.unit def test_phmsd_local_energy_active_space_non_aufbau(): numpy.random.seed(7) nelec = (9, 9) - nup, ndown = nelec - ne = numpy.sum(nelec) nwalkers = 4 nsteps = 10 nact = 12 nmo = 20 ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) - ham = HamGeneric( + system = Generic(nelec=nelec) + hamiltonian = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -1433,7 +1435,7 @@ def test_phmsd_local_energy_active_space_non_aufbau(): from ipie.utils.testing import get_random_phmsd_opt, shaped_normal wfn, init = get_random_phmsd_opt(7, 7, nact, ndet=100, init=True, cmplx_coeffs=False) - init = shaped_normal((nmo, ne)) + init = shaped_normal((nmo, system.ne)) ci, occa, occb = wfn tmp = occa[0] occa[0] = occa[2] @@ -1468,7 +1470,7 @@ def test_phmsd_local_energy_active_space_non_aufbau(): nmo, ) trial.build() - trial.half_rotate(ham) + trial.half_rotate(hamiltonian) trial_tmp = ParticleHoleNonChunked(wfn_2_no_act, nelec, nmo, use_active_space=False) trial_tmp.build() # Original implementation @@ -1478,7 +1480,7 @@ def test_phmsd_local_energy_active_space_non_aufbau(): nmo, ) trial_ref.build() - trial_ref.half_rotate(ham) + trial_ref.half_rotate(hamiltonian) # Hack to ensure cre_ex_a structures are present for testing. trial_ref.__dict__.update(trial_tmp.__dict__) trial_ref.optimized = False @@ -1487,46 +1489,46 @@ def test_phmsd_local_energy_active_space_non_aufbau(): trial_tmp.build() trial_test = ParticleHole(wfn_2, nelec, nmo, num_det_chunks=10) trial_test.build() - trial_test.half_rotate(ham) + trial_test.half_rotate(hamiltonian) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) options = {"hybrid": True} - walker_batch = UHFWalkersTrial(trial, init, nup, ndown, ham.nbasis, nwalkers) + walker_batch = UHFWalkersTrial(trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers) walker_batch.build(trial) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, nup, ndown, ham.nbasis, nwalkers + trial_ref, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, nup, ndown, ham.nbasis, nwalkers + trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers ) walker_batch_test.build(trial_test) # Naive numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_ref) + prop.build(hamiltonian, trial_ref) for i in range(nsteps): - prop.propagate_walkers(walker_batch_ref, ham, trial_ref, 0) + prop.propagate_walkers(walker_batch_ref, hamiltonian, trial_ref, 0) walker_batch_ref.reortho() # No optimization numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial) + prop.build(hamiltonian, trial) for i in range(nsteps): - prop.propagate_walkers(walker_batch, ham, trial, 0) + prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) walker_batch.reortho() # chunked numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(ham, trial_test) + prop.build(hamiltonian, trial_test) for i in range(nsteps): - prop.propagate_walkers(walker_batch_test, ham, trial_test, 0) + prop.propagate_walkers(walker_batch_test, hamiltonian, trial_test, 0) walker_batch_test.reortho() import copy @@ -1551,12 +1553,14 @@ def test_phmsd_local_energy_active_space_non_aufbau(): assert numpy.allclose(walker_batch_test.det_ovlpas, walker_batch_ref.det_ovlpas) assert numpy.allclose(walker_batch_test.det_ovlpbs, walker_batch_ref.det_ovlpbs) assert trial_ref.nfrozen != trial_test.nfrozen - e_wicks = local_energy_multi_det_trial_batch(ham, walker_batch, trial) - e_wicks_opt = local_energy_multi_det_trial_wicks_batch(ham, walker_batch_ref, trial_ref) + e_wicks = local_energy_multi_det_trial_batch(system, hamiltonian, walker_batch, trial) + e_wicks_opt = local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walker_batch_ref, trial_ref) e_wicks_opt_act = local_energy_multi_det_trial_wicks_batch_opt( - ham, walker_batch_test, trial_test) + system, hamiltonian, walker_batch_test, trial_test + ) e_wicks_opt_chunk = local_energy_multi_det_trial_wicks_batch_opt_chunked( - ham, walker_batch_test, trial_test) + system, hamiltonian, walker_batch_test, trial_test + ) assert numpy.allclose(e_wicks, e_wicks_opt) assert numpy.allclose(e_wicks_opt, e_wicks_opt_act) diff --git a/ipie/legacy/thermal_propagation/continuous.py b/ipie/legacy/thermal_propagation/continuous.py index 68653baf..cfc6dc7e 100644 --- a/ipie/legacy/thermal_propagation/continuous.py +++ b/ipie/legacy/thermal_propagation/continuous.py @@ -159,7 +159,7 @@ def exponentiate(self, VHS, debug=False): print(f"DIFF: {(c2 - phi).sum() / c2.size: 10.8e}") return phi - def propagate_walker_free(self, system, walker, trial, eshift=0): + def propagate_walker_free(self, system, walker, trial, eshift=0, xi=None): r"""Free projection for continuous HS transformation. .. Warning:: @@ -175,7 +175,7 @@ def propagate_walker_free(self, system, walker, trial, eshift=0): state : :class:`state.State` Simulation state. """ - (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, system, trial) + (cmf, cfb, xmxbar, VHS) = self.two_body_propagator(walker, system, trial, xi=xi) BV = self.exponentiate(VHS) B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) diff --git a/ipie/qmc/afqmc.py b/ipie/qmc/afqmc.py index f7a9ec9d..560fcfa6 100644 --- a/ipie/qmc/afqmc.py +++ b/ipie/qmc/afqmc.py @@ -236,6 +236,7 @@ def setup_estimators( comm = self.mpi_handler.comm self.estimators = EstimatorHandler( self.mpi_handler.comm, + self.system, self.hamiltonian, self.trial, walker_state=self.accumulators, @@ -253,6 +254,8 @@ def setup_estimators( self.estimators.initialize(comm) # Calculate estimates for initial distribution of walkers. self.estimators.compute_estimators( + comm, + self.system, self.hamiltonian, self.trial, self.walkers, @@ -393,6 +396,8 @@ def run( start = time.time() if step % self.params.num_steps_per_block == 0: self.estimators.compute_estimators( + comm, + self.system, self.hamiltonian, self.trial, self.walkers, diff --git a/ipie/qmc/tests/test_afqmc_multi_det_batch.py b/ipie/qmc/tests/test_afqmc_multi_det_batch.py index 8ba18da6..34a462e2 100644 --- a/ipie/qmc/tests/test_afqmc_multi_det_batch.py +++ b/ipie/qmc/tests/test_afqmc_multi_det_batch.py @@ -78,6 +78,8 @@ def test_generic_multi_det_batch(): afqmc.run(verbose=0, estimator_filename=tmpf.name) afqmc.finalise(verbose=0) afqmc.estimators.compute_estimators( + comm, + afqmc.system, afqmc.hamiltonian, afqmc.trial, afqmc.walkers, diff --git a/ipie/qmc/tests/test_afqmc_single_det_batch.py b/ipie/qmc/tests/test_afqmc_single_det_batch.py index 658c0ae0..d401310b 100644 --- a/ipie/qmc/tests/test_afqmc_single_det_batch.py +++ b/ipie/qmc/tests/test_afqmc_single_det_batch.py @@ -81,6 +81,8 @@ def test_generic_single_det_batch(): afqmc.run(verbose=False, estimator_filename=tmpf.name) afqmc.finalise(verbose=0) afqmc.estimators.compute_estimators( + comm, + afqmc.system, afqmc.hamiltonian, afqmc.trial, afqmc.walkers, @@ -185,6 +187,8 @@ def test_generic_single_det_batch_density_diff(): afqmc.run(verbose=False, estimator_filename=tmpf.name) afqmc.finalise(verbose=0) afqmc.estimators.compute_estimators( + comm, + afqmc.system, afqmc.hamiltonian, afqmc.trial, afqmc.walkers, diff --git a/ipie/thermal/estimators/local_energy.py b/ipie/thermal/estimators/local_energy.py index 8003fbb9..c97cac24 100644 --- a/ipie/thermal/estimators/local_energy.py +++ b/ipie/thermal/estimators/local_energy.py @@ -1,8 +1,3 @@ - -try: - from ipie.thermal.estimators.ueg import local_energy_ueg -except ImportError as e: - print(e) from ipie.thermal.estimators.generic import local_energy_generic_opt from ipie.thermal.estimators.generic import ( local_energy_generic_cholesky, @@ -15,82 +10,65 @@ def local_energy_G(hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): assert len(G) == 2 - ghf = G[0].shape[-1] == 2 * hamiltonian.nbasis - # unfortunate interfacial problem for the HH model - if hamiltonian.name in ["Hubbard", "HubbardHolstein", "PW_FFT"]: - raise NotImplementedError - elif hamiltonian.name == "UEG": - return local_energy_ueg(hamiltonian, G) - else: - if Ghalf is not None: - if hamiltonian.stochastic_ri and hamiltonian.control_variate: - return local_energy_generic_cholesky_opt_stochastic( - hamiltonian, - trial.nelec, - hamiltonian.nsamples, - G, - Ghalf=Ghalf, - rchol=trial._rchol, - C0=trial.psi, - ecoul0=trial.ecoul0, - exxa0=trial.exxa0, - exxb0=trial.exxb0, - ) - elif hamiltonian.stochastic_ri and not hamiltonian.control_variate: - return local_energy_generic_cholesky_opt_stochastic( - hamiltonian, - trial.nelec, - hamiltonian.nsamples, - G, - Ghalf=Ghalf, - rchol=trial._rchol, - ) - elif hamiltonian.exact_eri and not hamiltonian.pno: - return local_energy_generic_opt( - hamiltonian, - trial.nelec, - G, - Ghalf=Ghalf, - eri=trial._eri) - elif hamiltonian.pno: - assert hamiltonian.exact_eri and hamiltonian.control_variate - return local_energy_generic_pno( - hamiltonian, - trial.nelec, - G, - Ghalf=Ghalf, - eri=trial._eri, - C0=trial.C0, - ecoul0=trial.ecoul0, - exxa0=trial.exxa0, - exxb0=trial.exxb0, - UVT=trial.UVT, - ) - else: - return local_energy_generic_cholesky_opt( - hamiltonian, - trial.nelec, - G[0], - G[1], - Ghalfa=Ghalf[0], - Ghalfb=Ghalf[1], - rchola=trial._rchola, - rcholb=trial._rcholb, - ) + + if Ghalf is not None: + if hamiltonian.stochastic_ri and hamiltonian.control_variate: + return local_energy_generic_cholesky_opt_stochastic( + hamiltonian, + trial.nelec, + hamiltonian.nsamples, + G, + Ghalf=Ghalf, + rchol=trial._rchol, + C0=trial.psi, + ecoul0=trial.ecoul0, + exxa0=trial.exxa0, + exxb0=trial.exxb0, + ) + elif hamiltonian.stochastic_ri and not hamiltonian.control_variate: + return local_energy_generic_cholesky_opt_stochastic( + hamiltonian, + trial.nelec, + hamiltonian.nsamples, + G, + Ghalf=Ghalf, + rchol=trial._rchol, + ) + elif hamiltonian.exact_eri and not hamiltonian.pno: + return local_energy_generic_opt( + hamiltonian, + trial.nelec, + G, + Ghalf=Ghalf, + eri=trial._eri) + elif hamiltonian.pno: + assert hamiltonian.exact_eri and hamiltonian.control_variate + return local_energy_generic_pno( + hamiltonian, + trial.nelec, + G, + Ghalf=Ghalf, + eri=trial._eri, + C0=trial.C0, + ecoul0=trial.ecoul0, + exxa0=trial.exxa0, + exxb0=trial.exxb0, + UVT=trial.UVT, + ) else: - return local_energy_generic_cholesky(hamiltonian, G) + return local_energy_generic_cholesky_opt( + hamiltonian, + trial.nelec, + G[0], + G[1], + Ghalfa=Ghalf[0], + Ghalfb=Ghalf[1], + rchola=trial._rchola, + rcholb=trial._rcholb, + ) + else: + return local_energy_generic_cholesky(hamiltonian, G) -# TODO: should pass hamiltonian here and make it work for all possible types -# this is a generic local_energy handler. So many possible combinations of local energy strategies... def local_energy(hamiltonian, walker, trial): - if walker.name == "MultiDetWalker": - raise NotImplementedError - elif walker.name == "ThermalWalker": - return local_energy_G(hamiltonian, trial, one_rdm_from_G(walker.G), None) - else: - if hamiltonian.name == "HubbardHolstein": - raise NotImplementedError - else: - return local_energy_G(hamiltonian, trial, walker.G, walker.Ghalf) - + return local_energy_G(hamiltonian, trial, one_rdm_from_G(walker.G), None) diff --git a/ipie/thermal/estimators/tests/test_estimators.py b/ipie/thermal/estimators/tests/test_estimators.py index 2e32048e..5d450109 100644 --- a/ipie/thermal/estimators/tests/test_estimators.py +++ b/ipie/thermal/estimators/tests/test_estimators.py @@ -1,98 +1,79 @@ import pytest import tempfile import numpy -from pyscf import gto from typing import Tuple, Union -from ipie.systems.generic import Generic -from ipie.utils.testing import generate_hamiltonian -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.config import MPI from ipie.thermal.estimators.energy import ThermalEnergyEstimator from ipie.thermal.estimators.handler import ThermalEstimatorHandler -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric - - -def build_test_case_handlers(nelec: Tuple[int, int], - options: Union[dict, None] = None, - seed: Union[int, None] = None, - choltol: float = 1e-3, - complex_integrals: bool = False, - verbose: bool = False): - if seed is not None: - numpy.random.seed(seed) - - # Unpack options - mu = options['mu'] - nbasis = options['nbasis'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - lowrank = options['lowrank'] +from ipie.thermal.utils.testing import build_generic_test_case_handlers + +# System params. +nup = 5 +ndown = 5 +nelec = (nup, ndown) +nbasis = 10 + +# Thermal AFQMC params. +mu = -10. +beta = 0.1 +timestep = 0.01 +nwalkers = 12 +# Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! +nsteps_per_block = 1 +nblocks = 12 +stabilize_freq = 10 +pop_control_freq = 1 +pop_control_method = 'pair_branch' +#pop_control_method = 'comb' +lowrank = False + +verbose = True +complex_integrals = False +debug = True +mf_trial = True +propagate = False +seed = 7 +numpy.random.seed(seed) + +options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, - sym = 8 - if complex_integrals: sym = 4 - h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, - sym=sym, tol=choltol) - - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nbasis**2)).T.copy(), - ecore=0) - hamiltonian.name = options['hamiltonian']['name'] - hamiltonian._alt_convention = options['hamiltonian']['_alt_convention'] - hamiltonian.sparse = options['hamiltonian']['sparse'] - - trial = MeanField(hamiltonian, nelec, beta, timestep) - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank) - propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) - - for t in range(walkers.stack[0].nslice): - propagator.propagate_walkers(walkers, hamiltonian, trial) - - objs = {'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers, - 'propagator': propagator} - return objs - + "propagator": { + "optimised": False, + "free_projection": False + }, + } @pytest.mark.unit def test_energy_estimator(): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) - nbasis = 10 - - mu = -10.0 - beta = 0.1 - timestep = 0.01 - nwalkers = 1 - seed = 7 - lowrank = False - verbose = True - - options = { - 'mu': mu, - 'nbasis': nbasis, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': 7, - 'lowrank': lowrank, - - 'hamiltonian': { - 'name': 'Generic', - '_alt_convention': False, - 'sparse': False, - 'mu': mu - } - } - - objs = build_test_case_handlers(nelec, options, seed, choltol=1e-10, - complex_integrals=False, verbose=verbose) + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] @@ -100,11 +81,8 @@ def test_energy_estimator(): estim = ThermalEnergyEstimator(hamiltonian=hamiltonian, trial=trial) estim.compute_estimator(walkers, hamiltonian, trial) assert len(estim.names) == 5 - #assert estim["ENumer"].real == pytest.approx(-754.0373585215561) - #assert estim["ETotal"] == pytest.approx(0.0) tmp = estim.data.copy() estim.post_reduce_hook(tmp) - #assert tmp[estim.get_index("ETotal")] == pytest.approx(-75.40373585215562) assert estim.print_to_stdout assert estim.ascii_filename == None assert estim.shape == (5,) @@ -115,39 +93,12 @@ def test_energy_estimator(): @pytest.mark.unit def test_estimator_handler(): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) - nbasis = 10 - - mu = -10.0 - beta = 0.1 - timestep = 0.01 - nwalkers = 1 - seed = 7 - lowrank = False - verbose = True - - options = { - 'mu': mu, - 'nbasis': nbasis, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': 7, - 'lowrank': lowrank, - - 'hamiltonian': { - 'name': 'Generic', - '_alt_convention': False, - 'sparse': False, - 'mu': mu - } - } - with tempfile.NamedTemporaryFile() as tmp1, tempfile.NamedTemporaryFile() as tmp2: - objs = build_test_case_handlers(nelec, options, seed, choltol=1e-10, - complex_integrals=False, verbose=verbose) + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] @@ -155,7 +106,6 @@ def test_estimator_handler(): estim = ThermalEnergyEstimator(hamiltonian=hamiltonian, trial=trial, filename=tmp1.name) estim.print_to_stdout = False - from ipie.config import MPI comm = MPI.COMM_WORLD handler = ThermalEstimatorHandler( diff --git a/ipie/thermal/estimators/tests/test_generic.py b/ipie/thermal/estimators/tests/test_generic.py new file mode 100644 index 00000000..827f961a --- /dev/null +++ b/ipie/thermal/estimators/tests/test_generic.py @@ -0,0 +1,112 @@ +import numpy +import pytest +from typing import Tuple, Union + +from ipie.config import MPI +from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.thermal.estimators.generic import local_energy_generic_cholesky + +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G +from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky + +from ipie.thermal.utils.testing import build_generic_test_case_handlers +from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers + +comm = MPI.COMM_WORLD + +@pytest.mark.unit +def test_local_energy_cholesky(mf_trial=False): + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + + # Thermal AFQMC params. + mu = -10. + beta = 0.1 + timestep = 0.01 + nwalkers = 12 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 12 + stabilize_freq = 10 + pop_control_freq = 1 + pop_control_method = 'pair_branch' + #pop_control_method = 'comb' + lowrank = False + + verbose = True + complex_integrals = False + debug = True + mf_trial = True + propagate = False + seed = 7 + numpy.random.seed(seed) + + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + P = one_rdm_from_G(trial.G) + eloc = local_energy_generic_cholesky(hamiltonian, P) + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_generic_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + + legacy_P = legacy_one_rdm_from_G(legacy_trial.G) + legacy_eloc = legacy_local_energy_generic_cholesky( + legacy_system, legacy_hamiltonian, legacy_P) + + if verbose: + print(f'\neloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') + + numpy.testing.assert_allclose(trial.G, legacy_trial.G, atol=1e-10) + numpy.testing.assert_allclose(P, legacy_P, atol=1e-10) + numpy.testing.assert_allclose(eloc, legacy_eloc, atol=1e-10) + + +if __name__ == '__main__': + test_local_energy_cholesky(mf_trial=True) diff --git a/ipie/thermal/estimators/tests/test_generic_complex.py b/ipie/thermal/estimators/tests/test_generic_complex.py index 2e20fcc3..2e2e859a 100644 --- a/ipie/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/thermal/estimators/tests/test_generic_complex.py @@ -3,102 +3,86 @@ from typing import Tuple, Union from ipie.utils.misc import dotdict -from ipie.utils.testing import generate_hamiltonian from ipie.utils.testing import build_test_case_handlers as build_test_case_handlers_0T +from ipie.systems.generic import Generic +from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.estimators.energy import local_energy -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.hamiltonians.utils import get_hamiltonian -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.utils.testing import build_generic_test_case_handlers from ipie.thermal.estimators.generic import local_energy_generic_cholesky from ipie.thermal.estimators.thermal import one_rdm_from_G - -def build_test_case_handlers(nelec: Tuple[int, int], - options: Union[dict, None] = None, - seed: Union[int, None] = None, - choltol: float = 1e-3, - complex_integrals: bool = False, - verbose: bool = False): - if seed is not None: - numpy.random.seed(seed) - - # Unpack options - mu = options['mu'] - nbasis = options['nbasis'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - lowrank = options['lowrank'] +# System params. +nup = 5 +ndown = 5 +nelec = (nup, ndown) +nbasis = 10 + +# Thermal AFQMC params. +mu = -10. +beta = 0.1 +timestep = 0.01 +nwalkers = 12 +# Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! +nsteps_per_block = 1 +nblocks = 12 +stabilize_freq = 10 +pop_control_freq = 1 +pop_control_method = 'pair_branch' +#pop_control_method = 'comb' +lowrank = False + +verbose = True +complex_integrals = False +debug = True +mf_trial = True +propagate = False +seed = 7 +numpy.random.seed(seed) + +options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, - sym = 8 - if complex_integrals: sym = 4 - h1e, chol, _, eri = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, - sym=sym, tol=choltol) - - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nbasis**2)).T.copy(), - ecore=0) - hamiltonian.name = options['hamiltonian']['name'] - hamiltonian._alt_convention = options['hamiltonian']['_alt_convention'] - hamiltonian.sparse = options['hamiltonian']['sparse'] - hamiltonian.eri = eri.copy() - - trial = MeanField(hamiltonian, nelec, beta, timestep) - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank) - propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) - - for t in range(walkers.stack[0].nslice): - propagator.propagate_walkers(walkers, hamiltonian, trial) - - objs = {'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers, - 'propagator': propagator} - return objs + "propagator": { + "optimised": False, + "free_projection": False + }, + } @pytest.mark.unit def test_local_energy_vs_real(): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) - nbasis = 10 - - mu = -10.0 - beta = 0.1 - timestep = 0.01 - nwalkers = 1 - seed = 7 - lowrank = False - verbose = True - - options = { - 'mu': mu, - 'nbasis': nbasis, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': 7, - 'lowrank': lowrank, - - 'hamiltonian': { - 'name': 'Generic', - '_alt_convention': False, - 'sparse': False, - 'mu': mu - } - } - - objs = build_test_case_handlers(nelec, options, seed, choltol=1e-10, - complex_integrals=False, verbose=verbose) + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) trial = objs['trial'] - hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] - + hamiltonian = objs['hamiltonian'] + chol = hamiltonian.chol cx_chol = numpy.array(chol, dtype=numpy.complex128) cx_hamiltonian = HamGeneric( @@ -114,43 +98,17 @@ def test_local_energy_vs_real(): @pytest.mark.unit def test_local_energy_vs_eri(): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) - nbasis = 10 - - mu = -10.0 - beta = 0.1 - timestep = 0.01 - nwalkers = 1 - seed = 7 - lowrank = False - verbose = True - - options = { - 'mu': mu, - 'nbasis': nbasis, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': 7, - 'lowrank': lowrank, - - 'hamiltonian': { - 'name': 'Generic', - '_alt_convention': False, - 'sparse': False, - 'mu': mu - } - } - - objs = build_test_case_handlers(nelec, options, seed, choltol=1e-10, - complex_integrals=False, verbose=verbose) + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, with_eri=True, + verbose=verbose) trial = objs['trial'] - hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] - - eri = hamiltonian.eri.reshape(nbasis, nbasis, nbasis, nbasis) + hamiltonian = objs['hamiltonian'] + eri = objs['eri'].reshape(nbasis, nbasis, nbasis, nbasis) + chol = hamiltonian.chol.copy() nchol = chol.shape[1] chol = chol.reshape(nbasis, nbasis, nchol) @@ -209,12 +167,13 @@ def test_local_energy_0T_single_det(): trial_type="single_det", choltol=1e-10, ) - + + system = Generic(nelec=nelec) hamiltonian = handler_0T.hamiltonian walkers = handler_0T.walkers trial = handler_0T.trial walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) - energy = local_energy(hamiltonian, walkers, trial) + energy = local_energy(system, hamiltonian, walkers, trial) test_energy = numpy.array( [local_energy_generic_cholesky( hamiltonian, diff --git a/ipie/thermal/propagation/phaseless_base.py b/ipie/thermal/propagation/phaseless_base.py index 34502ec4..9b80229f 100644 --- a/ipie/thermal/propagation/phaseless_base.py +++ b/ipie/thermal/propagation/phaseless_base.py @@ -56,8 +56,8 @@ def construct_mean_field_shift(hamiltonian: GenericComplexChol, trial): class PhaselessBase(ContinuousBase): """A base class for generic continuous HS transform FT-AFQMC propagators.""" - def __init__(self, time_step, mu, lowrank=False, verbose=False): - super().__init__(time_step, verbose=verbose) + def __init__(self, timestep, mu, lowrank=False, verbose=False): + super().__init__(timestep, verbose=verbose) self.mu = mu self.sqrt_dt = self.dt**0.5 self.isqrt_dt = 1j * self.sqrt_dt diff --git a/ipie/thermal/propagation/tests/test_generic_propagation.py b/ipie/thermal/propagation/tests/test_generic_propagation.py deleted file mode 100644 index 9262dfa2..00000000 --- a/ipie/thermal/propagation/tests/test_generic_propagation.py +++ /dev/null @@ -1,294 +0,0 @@ -import numpy -import pytest - -from ipie.qmc.options import QMCOpts - -from ipie.systems.generic import Generic -from ipie.utils.testing import generate_hamiltonian -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.hamiltonians.utils import get_hamiltonian -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric -from ipie.thermal.estimators.generic import local_energy_generic_cholesky -from ipie.thermal.estimators.thermal import one_rdm_from_G - -from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.thermal import ThermalWalker -from ipie.legacy.thermal_propagation.continuous import Continuous -from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky -from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G - - -def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator, xi=None): - if xi is None: - xi = [None] * legacy_walkers.nwalker - - for iw, walker in enumerate(legacy_walkers): - legacy_propagator.propagate_walker_phaseless( - legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) - - return legacy_walkers - - -def setup_objs(mf_trial=False, seed=None): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) - nbasis = 10 - - mu = -10. - beta = 0.02 - dt = 0.01 - nwalkers = 10 - blocks = 10 - stabilise_freq = 10 - pop_control_freq = 1 - nsteps = 1 - - lowrank = False - verbose = True - complex_integrals = False - sym = 8 - if complex_integrals: sym = 4 - numpy.random.seed(seed) - - options = { - "qmc": { - "dt": dt, - "nwalkers": nwalkers, - "blocks": blocks, - "nsteps": nsteps, - "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, - "stabilise_freq": stabilise_freq, - "batched": False - }, - - "propagator": { - "optimised": False - }, - - "walkers": { - "low_rank": lowrank - }, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - } - } - - # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, - sym=sym, tol=1e-10) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nbasis**2)).T.copy(), - ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - - trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) - - if mf_trial: - trial = MeanField(hamiltonian, nelec, beta, dt, verbose=verbose) - - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) - propagator = PhaselessGeneric(dt, mu, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) - - # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_system = Generic(nelec, verbose=verbose) - legacy_system.mu = mu - legacy_hamiltonian = LegacyHamGeneric( - h1e=hamiltonian.H1, - chol=hamiltonian.chol, - ecore=hamiltonian.ecore) - legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) - legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, dt, - verbose=verbose) - if mf_trial: - legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, dt, - verbose=verbose) - - legacy_walkers = [ - ThermalWalker( - legacy_system, legacy_hamiltonian, legacy_trial, - walker_opts=options, verbose=i == 0) for i in range(nwalkers)] - - qmc_opts = QMCOpts() - qmc_opts.nwalkers = nwalkers - qmc_opts.ntot_walkers = nwalkers - qmc_opts.beta = beta - qmc_opts.nsteps = nsteps - qmc_opts.dt = dt - qmc_opts.seed = seed - - legacy_propagator = Continuous( - options["propagator"], qmc_opts, legacy_system, - legacy_hamiltonian, legacy_trial, verbose=verbose, - lowrank=lowrank) - - objs = {'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers, - 'propagator': propagator} - - legacy_objs = {'system': legacy_system, - 'trial': legacy_trial, - 'hamiltonian': legacy_hamiltonian, - 'walkers': legacy_walkers, - 'propagator': legacy_propagator} - - return objs, legacy_objs - - -@pytest.mark.unit -def test_mf_shift(verbose=False): - seed = 7 - objs, legacy_objs = setup_objs(seed=seed) - propagator = objs['propagator'] - legacy_propagator = legacy_objs['propagator'] - - if verbose: - print(f'\nlegacy_mf_shift = \n{legacy_propagator.propagator.mf_shift}\n') - print(f'mf_shift = \n{propagator.mf_shift}\n') - - numpy.testing.assert_almost_equal(legacy_propagator.propagator.mf_shift, - propagator.mf_shift, decimal=10) - -@pytest.mark.unit -def test_BH1(verbose=False): - seed = 7 - objs, legacy_objs = setup_objs(seed=seed) - propagator = objs['propagator'] - legacy_propagator = legacy_objs['propagator'] - - if verbose: - print(f'\nlegacy_BH1 = \n{legacy_propagator.propagator.BH1}\n') - print(f'BH1 = \n{propagator.BH1}\n') - - numpy.testing.assert_almost_equal(legacy_propagator.propagator.BH1, - propagator.BH1, decimal=10) - - -@pytest.mark.unit -def test_construct_two_body_propagator(verbose=False): - seed = 7 - objs, legacy_objs = setup_objs(seed=seed) - trial = objs['trial'] - hamiltonian = objs['hamiltonian'] - walkers = objs['walkers'] - propagator = objs['propagator'] - - legacy_trial = legacy_objs['trial'] - legacy_hamiltonian = legacy_objs['hamiltonian'] - legacy_walkers = legacy_objs['walkers'] - legacy_propagator = legacy_objs['propagator'] - - cmf, cfb, xshifted, VHS = propagator.construct_two_body_propagator( - walkers, hamiltonian, trial, debug=True) - - legacy_cmf = [] - legacy_cfb = [] - legacy_xshifted = [] - legacy_VHS = [] - - for iw in range(walkers.nwalkers): - _cmf, _cfb, _xshifted, _VHS = legacy_propagator.two_body_propagator( - legacy_walkers[iw], legacy_hamiltonian, - legacy_trial, xi=propagator.xi[iw]) - legacy_cmf.append(_cmf) - legacy_cfb.append(_cfb) - legacy_xshifted.append(_xshifted) - legacy_VHS.append(_VHS) - - legacy_xshifted = numpy.array(legacy_xshifted).T - - if verbose: - print(f'\nlegacy_cmf = {legacy_cmf}') - print(f'cmf = {cmf}') - - print(f'\nlegacy_cfb = {legacy_cfb}') - print(f'cfb = {cfb}') - - print(f'\nlegacy_xshifted = \n{legacy_xshifted}\n') - print(f'xshifted = \n{xshifted}\n') - - print(f'legacy_VHS = \n{legacy_VHS}\n') - print(f'VHS = \n{VHS}\n') - - numpy.testing.assert_almost_equal(legacy_cmf, cmf, decimal=10) - numpy.testing.assert_almost_equal(legacy_cfb, cfb, decimal=10) - numpy.testing.assert_almost_equal(legacy_xshifted, xshifted, decimal=10) - numpy.testing.assert_almost_equal(legacy_VHS, VHS, decimal=10) - - -@pytest.mark.unit -def test_phaseless_generic_propagator(mf_trial=False, verbose=False): - seed = 7 - objs, legacy_objs = setup_objs(mf_trial=mf_trial, seed=seed) - trial = objs['trial'] - hamiltonian = objs['hamiltonian'] - walkers = objs['walkers'] - propagator = objs['propagator'] - - legacy_system = legacy_objs['system'] - legacy_trial = legacy_objs['trial'] - legacy_hamiltonian = legacy_objs['hamiltonian'] - legacy_walkers = legacy_objs['walkers'] - legacy_propagator = legacy_objs['propagator'] - - for t in range(walkers.stack[0].nslice): - for iw in range(walkers.nwalkers): - P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) - eloc = local_energy_generic_cholesky(hamiltonian, P) - - legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers[iw].G)) - legacy_eloc = legacy_local_energy_generic_cholesky( - legacy_system, legacy_hamiltonian, legacy_P) - - if verbose: - print(f'\nt = {t}') - print(f'iw = {iw}') - print(f'eloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') - print(f'walkers.weight = \n{walkers.weight[iw]}\n') - print(f'legacy_walkers.weight = \n{legacy_walkers[iw].weight}\n') - - numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) - numpy.testing.assert_almost_equal(legacy_P, P, decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) - - propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) - legacy_walkers = legacy_propagate_walkers( - legacy_hamiltonian, legacy_trial, legacy_walkers, - legacy_propagator, xi=propagator.xi) - - -if __name__ == "__main__": - test_mf_shift(verbose=True) - test_BH1(verbose=True) - test_construct_two_body_propagator(verbose=True) - test_phaseless_generic_propagator(mf_trial=True, verbose=True) diff --git a/ipie/thermal/propagation/tests/test_operations.py b/ipie/thermal/propagation/tests/test_operations.py index ca525253..f9fda82c 100644 --- a/ipie/thermal/propagation/tests/test_operations.py +++ b/ipie/thermal/propagation/tests/test_operations.py @@ -1,165 +1,92 @@ import numpy import pytest -from pyscf import gto, scf, lo -from ipie.qmc.options import QMCOpts - -from ipie.systems.generic import Generic -from ipie.utils.testing import generate_hamiltonian -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.config import MPI from ipie.thermal.propagation.operations import apply_exponential -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric - -from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.thermal import ThermalWalker -from ipie.legacy.thermal_propagation.continuous import Continuous +from ipie.thermal.utils.testing import build_generic_test_case_handlers +from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers +from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers +comm = MPI.COMM_WORLD -def setup_objs(mf_trial=False, seed=None): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) +@pytest.mark.unit +def test_apply_exponential(): + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) nbasis = 10 + # Thermal AFQMC params. mu = -10. beta = 0.1 - dt = 0.01 - nwalkers = 5 - numpy.random.seed(seed) - blocks = 10 - stabilise_freq = 10 + timestep = 0.01 + nwalkers = 12 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 12 + stabilize_freq = 10 pop_control_freq = 1 - nsteps = 1 - + pop_control_method = 'pair_branch' + #pop_control_method = 'comb' lowrank = False + verbose = True complex_integrals = False - sym = 8 - if complex_integrals: sym = 4 + debug = True + mf_trial = True + propagate = False + seed = 7 + numpy.random.seed(seed) options = { - "qmc": { - "dt": dt, - "nwalkers": nwalkers, - "blocks": blocks, - "nsteps": nsteps, - "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, - "stabilise_freq": stabilise_freq, - "batched": False - }, - - "propagator": { - "optimised": False - }, - - "walkers": { - "low_rank": lowrank - - }, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - } + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } # Test. print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, - sym=sym, tol=1e-10) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nbasis**2)).T.copy(), - ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - - trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) - - if mf_trial: - trial = MeanField(hamiltonian, nelec, beta, dt, verbose=verbose) + objs = build_generic_test_case_handlers(options, seed, debug, verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) - propagator = PhaselessGeneric(dt, mu, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) - # Legacy. print('\n------------------------------') print('Constructing legacy objects...') print('------------------------------') - legacy_system = Generic(nelec, verbose=verbose) - legacy_system.mu = mu - legacy_hamiltonian = LegacyHamGeneric( - h1e=hamiltonian.H1, - chol=hamiltonian.chol, - ecore=hamiltonian.ecore, - options=options["hamiltonian"]) - legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) - legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, dt, - verbose=verbose) - if mf_trial: - legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, dt, - verbose=verbose) - - legacy_walkers = [ - ThermalWalker( - legacy_system, legacy_hamiltonian, legacy_trial, - walker_opts=options, verbose=i == 0) for i in range(nwalkers)] - - qmc_opts = QMCOpts() - qmc_opts.nwalkers = nwalkers - qmc_opts.ntot_walkers = nwalkers - qmc_opts.beta = beta - qmc_opts.nsteps = nsteps - qmc_opts.dt = dt - qmc_opts.seed = seed - - #legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( - # (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_propagator = Continuous( - options["propagator"], qmc_opts, legacy_system, - legacy_hamiltonian, legacy_trial, verbose=verbose, - lowrank=lowrank) - - objs = {'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers, - 'propagator': propagator} - - legacy_objs = {'system': legacy_system, - 'trial': legacy_trial, - 'hamiltonian': legacy_hamiltonian, - 'walkers': legacy_walkers, - 'propagator': legacy_propagator} - - return objs, legacy_objs - - -@pytest.mark.unit -def test_apply_exponential(verbose=False): - seed = 7 - objs, legacy_objs = setup_objs(seed=seed) - trial = objs['trial'] - hamiltonian = objs['hamiltonian'] - walkers = objs['walkers'] - propagator = objs['propagator'] - + legacy_objs = build_legacy_generic_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) + legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] legacy_walkers = legacy_objs['walkers'] @@ -171,7 +98,7 @@ def test_apply_exponential(verbose=False): legacy_exp = [] for iw in range(walkers.nwalkers): _, _, _, _VHS = legacy_propagator.two_body_propagator( - legacy_walkers[iw], legacy_hamiltonian, + legacy_walkers.walkers[iw], legacy_hamiltonian, legacy_trial, xi=propagator.xi[iw]) _exp = apply_exponential(VHS[iw], propagator.exp_nmax) _legacy_exp = legacy_propagator.exponentiate(_VHS, debug=True) @@ -191,4 +118,4 @@ def test_apply_exponential(verbose=False): if __name__ == "__main__": - test_apply_exponential(verbose=True) + test_apply_exponential() diff --git a/ipie/thermal/propagation/tests/test_prop_generic.py b/ipie/thermal/propagation/tests/test_prop_generic.py new file mode 100644 index 00000000..f11d319e --- /dev/null +++ b/ipie/thermal/propagation/tests/test_prop_generic.py @@ -0,0 +1,247 @@ +import numpy +import pytest + +from ipie.config import MPI +from ipie.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.thermal.estimators.thermal import one_rdm_from_G + +from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G + +from ipie.thermal.utils.testing import build_generic_test_case_handlers +from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers +from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers + +comm = MPI.COMM_WORLD + +# System params. +nup = 5 +ndown = 5 +nelec = (nup, ndown) +nbasis = 10 + +# Thermal AFQMC params. +mu = -10. +beta = 0.1 +timestep = 0.01 +nwalkers = 12 +# Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! +nsteps_per_block = 1 +nblocks = 12 +stabilize_freq = 10 +pop_control_freq = 1 +pop_control_method = 'pair_branch' +#pop_control_method = 'comb' +lowrank = False + +verbose = True +complex_integrals = False +debug = True +mf_trial = True +propagate = False +seed = 7 +numpy.random.seed(seed) + +options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } + + +@pytest.mark.unit +def test_mf_shift(): + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) + hamiltonian = objs['hamiltonian'] + propagator = objs['propagator'] + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_generic_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) + legacy_propagator = legacy_objs['propagator'] + + if verbose: + print(f'\nlegacy_mf_shift = \n{legacy_propagator.propagator.mf_shift}\n') + print(f'mf_shift = \n{propagator.mf_shift}\n') + + numpy.testing.assert_almost_equal(legacy_propagator.propagator.mf_shift, + propagator.mf_shift, decimal=10) + +@pytest.mark.unit +def test_BH1(): + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) + hamiltonian = objs['hamiltonian'] + propagator = objs['propagator'] + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_generic_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) + legacy_propagator = legacy_objs['propagator'] + + if verbose: + print(f'\nlegacy_BH1 = \n{legacy_propagator.propagator.BH1}\n') + print(f'BH1 = \n{propagator.BH1}\n') + + numpy.testing.assert_almost_equal(legacy_propagator.propagator.BH1, + propagator.BH1, decimal=10) + + +@pytest.mark.unit +def test_construct_two_body_propagator(): + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_generic_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + cmf, cfb, xshifted, VHS = propagator.construct_two_body_propagator( + walkers, hamiltonian, trial, debug=True) + + legacy_cmf = [] + legacy_cfb = [] + legacy_xshifted = [] + legacy_VHS = [] + + for iw in range(walkers.nwalkers): + _cmf, _cfb, _xshifted, _VHS = legacy_propagator.two_body_propagator( + legacy_walkers.walkers[iw], legacy_hamiltonian, + legacy_trial, xi=propagator.xi[iw]) + legacy_cmf.append(_cmf) + legacy_cfb.append(_cfb) + legacy_xshifted.append(_xshifted) + legacy_VHS.append(_VHS) + + legacy_xshifted = numpy.array(legacy_xshifted).T + + if verbose: + print(f'\nlegacy_cmf = {legacy_cmf}') + print(f'cmf = {cmf}') + + print(f'\nlegacy_cfb = {legacy_cfb}') + print(f'cfb = {cfb}') + + print(f'\nlegacy_xshifted = \n{legacy_xshifted}\n') + print(f'xshifted = \n{xshifted}\n') + + print(f'legacy_VHS = \n{legacy_VHS}\n') + print(f'VHS = \n{VHS}\n') + + numpy.testing.assert_almost_equal(legacy_cmf, cmf, decimal=10) + numpy.testing.assert_almost_equal(legacy_cfb, cfb, decimal=10) + numpy.testing.assert_almost_equal(legacy_xshifted, xshifted, decimal=10) + numpy.testing.assert_almost_equal(legacy_VHS, VHS, decimal=10) + + +@pytest.mark.unit +def test_phaseless_generic_propagator(): + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_generic_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + for t in range(walkers.stack[0].nslice): + for iw in range(walkers.nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + eloc = local_energy_generic_cholesky(hamiltonian, P) + + legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers.walkers[iw].G)) + legacy_eloc = legacy_local_energy_generic_cholesky( + legacy_system, legacy_hamiltonian, legacy_P) + + if verbose: + print(f'\nt = {t}') + print(f'iw = {iw}') + print(f'eloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') + print(f'walkers.weight = \n{walkers.weight[iw]}\n') + print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') + + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + numpy.testing.assert_allclose(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw]) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_P, P, decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) + + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, xi=propagator.xi) + + +if __name__ == "__main__": + test_mf_shift() + test_BH1() + test_construct_two_body_propagator() + test_phaseless_generic_propagator() diff --git a/ipie/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/thermal/propagation/tests/ueg/test_prop_ueg.py new file mode 100644 index 00000000..1e0156a8 --- /dev/null +++ b/ipie/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -0,0 +1,155 @@ +import pytest +import numpy + +from ipie.config import MPI +from ipie.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.thermal.estimators.thermal import one_rdm_from_G + +from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg +from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G + +from ipie.thermal.utils.testing import build_ueg_test_case_handlers +from ipie.thermal.utils.legacy_testing import build_legacy_ueg_test_case_handlers +from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers + +comm = MPI.COMM_WORLD + +@pytest.mark.unit +def test_phaseless_generic_propagator(): + # UEG params. + nup = 7 + ndown = 7 + nelec = (nup, ndown) + rs = 1. + ecut = 1. + + # Thermal AFQMC params. + mu = -1. + beta = 0.1 + timestep = 0.01 + nwalkers = 1 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 11 + stabilize_freq = 10 + pop_control_freq = 1 + + # `pop_control_method` doesn't matter for 1 walker. + pop_control_method = "pair_branch" + #pop_control_method = "comb" + lowrank = False + propagate = False + + verbose = False if (comm.rank != 0) else True + debug = True + seed = 7 + numpy.random.seed(seed) + + options = { + 'nelec': nelec, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'propagate': propagate, + + "ueg_opts": { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + }, + + "hamiltonian": { + "name": "UEG", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_ueg_test_case_handlers(options, seed, debug, verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_ueg_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + + h1e = legacy_hamiltonian.H1[0] + eri = legacy_hamiltonian.eri_4() + + for t in range(walkers.stack[0].nslice): + for iw in range(walkers.nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + eloc = local_energy_generic_cholesky(hamiltonian, P) + + legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers.walkers[iw].G)) + legacy_eloc = legacy_local_energy_ueg(legacy_system, legacy_hamiltonian, legacy_P) + + legacy_Pa, legacy_Pb = legacy_P + legacy_Ptot = legacy_Pa + legacy_Pb + ref_e1 = numpy.einsum('ij,ij->', h1e, legacy_Ptot) + + Ptot = legacy_Ptot + Pa = legacy_Pa + Pb = legacy_Pb + + ecoul = 0.5 * numpy.einsum('ijkl,ij,kl->', eri, Ptot, Ptot) + exx = -0.5 * numpy.einsum('ijkl,il,kj->', eri, Pa, Pa) + exx -= 0.5 * numpy.einsum('ijkl,il,kj->', eri, Pb, Pb) + ref_e2 = ecoul + exx + ref_eloc = (ref_e1 + ref_e2, ref_e1, ref_e2) + + if verbose: + print(f'\nt = {t}') + print(f'iw = {iw}') + print(f'eloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') + print(f'ref_eloc = \n{ref_eloc}\n') + print(f'walkers.weight = \n{walkers.weight[iw]}\n') + print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') + + numpy.testing.assert_almost_equal(legacy_P, P, decimal=10) + numpy.testing.assert_almost_equal(legacy_trial.dmat, trial.dmat, decimal=10) + numpy.testing.assert_allclose(eloc, ref_eloc, atol=1e-10) + numpy.testing.assert_allclose(legacy_eloc, ref_eloc, atol=1e-10) + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) + + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, xi=propagator.xi) + + +if __name__ == "__main__": + test_phaseless_generic_propagator() diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py b/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py index 3c63b8d0..904169d5 100644 --- a/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py +++ b/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py @@ -107,7 +107,7 @@ def setup_objs(seed=None): psi0 = numpy.zeros((nbasis, numpy.sum(nelec)), dtype=numpy.complex128) psi0[:, :nup] = psia psi0[:, nup:] = psib - numpy.save('ueg_trial', psi0) + #numpy.save('ueg_trial', psi0) if verbose: print(numpy.amax(numpy.absolute(chol.imag))) @@ -188,7 +188,8 @@ def setup_objs(seed=None): legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, qmc_opts, verbose=verbose) - objs = {'trial': trial, + objs = {'system': system, + 'trial': trial, 'hamiltonian': hamiltonian, 'walkers': walkers} @@ -204,6 +205,7 @@ def setup_objs(seed=None): def test_ueg_0T(verbose=False): seed = 7 objs, legacy_objs = setup_objs(seed=seed) + system = objs['system'] trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] @@ -219,10 +221,9 @@ def test_ueg_0T(verbose=False): for iw in range(walkers.nwalkers): G = numpy.array([walkers.Ga[iw], walkers.Gb[iw]]) Ghalf = numpy.array([walkers.Ghalfa[iw], walkers.Ghalfb[iw]]) - eloc = local_energy_G(hamiltonian, trial, G, Ghalf) + eloc = local_energy_G(system, hamiltonian, trial, G, Ghalf) legacy_eloc = legacy_local_energy_ueg(legacy_system, legacy_hamiltonian, legacy_walkers.walkers[iw].G) - legacy_Ga, legacy_Gb = legacy_walkers.walkers[iw].G legacy_Gtot = legacy_Ga + legacy_Gb ref_e1 = numpy.einsum('ij,ij->', h1e, legacy_Gtot) diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py b/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py deleted file mode 100644 index c39e1654..00000000 --- a/ipie/thermal/propagation/tests/ueg/test_ueg_propagation.py +++ /dev/null @@ -1,260 +0,0 @@ -import pytest -import numpy - -from ueg import UEG -from pyscf import gto, scf, ao2mo -from ipie.qmc.options import QMCOpts - -from ipie.systems.generic import Generic -from ipie.utils.testing import generate_hamiltonian -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric -from ipie.thermal.estimators.generic import local_energy_generic_cholesky -from ipie.thermal.estimators.thermal import one_rdm_from_G - -from ipie.legacy.systems.ueg import UEG as LegacyUEG -from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.thermal import ThermalWalker -from ipie.legacy.thermal_propagation.planewave import PlaneWave -from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg -from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G - - -def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, - legacy_propagator, lowrank=False, xi=None): - if xi is None: - xi = [None] * legacy_walkers.nwalker - - for iw, walker in enumerate(legacy_walkers): - if lowrank: - legacy_propagator.propagate_walker_phaseless_low_rank( - legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) - - else: - legacy_propagator.propagate_walker_phaseless_full_rank( - legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) - - - return legacy_walkers - - -def setup_objs(seed=None): - mu = -10. - beta = 0.01 - timestep = 0.002 - nwalkers = 3 - nblocks = 2 - stabilise_freq = 10 - pop_control_freq = 1 - nsteps_per_block = 1 - - lowrank = False - verbose = True - numpy.random.seed(seed) - - options = { - "qmc": { - "dt": timestep, - "nwalkers": nwalkers, - "blocks": nblocks, - "nsteps": nsteps_per_block, - "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, - "stabilise_freq": stabilise_freq, - "batched": False - }, - - "propagator": { - "optimised": False - }, - - "walkers": { - "low_rank": lowrank - }, - - "hamiltonian": { - "name": "UEG", - "_alt_convention": False, - "sparse": False, - "mu": mu - } - } - - # Generate UEG integrals. - ueg_opts = { - "nup": 7, - "ndown": 7, - "rs": 1., - "ecut": 2.5, - "thermal": True, - "write_integrals": False, - "low_rank": lowrank - } - - ueg = UEG(ueg_opts, verbose=verbose) - ueg.build(verbose=verbose) - nbasis = ueg.nbasis - nchol = ueg.nchol - nelec = (ueg.nup, ueg.ndown) - nup, ndown = nelec - - h1 = ueg.H1[0] - chol = 2. * ueg.chol_vecs.toarray().copy() - #ecore = ueg.ecore - ecore = 0. - - if verbose: - print(numpy.amax(numpy.absolute(chol.imag))) - print(f"# nbasis = {nbasis}") - print(f"# nchol = {nchol}") - print(f"# nup = {nup}") - print(f"# ndown = {ndown}") - - # ------------------------------------------------------------------------- - # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - - # 1. Build Hamiltonian. - hamiltonian = HamGeneric( - numpy.array([h1, h1], dtype=numpy.complex128), - numpy.array(chol, dtype=numpy.complex128), - ecore, - verbose=verbose) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - - # 2. Build trial. - trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) - - # 3. Build walkers. - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) - - # 4. Build propagator. - propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) - - # ------------------------------------------------------------------------- - # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - - # 1. Build out system. - legacy_system = LegacyUEG(options=ueg_opts) - - # 2. Build Hamiltonian. - legacy_hamiltonian = LegacyHamUEG(legacy_system, options=ueg_opts) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] - - # 3. Build trial. - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) - - # 4. Build walkers. - legacy_walkers = [ - ThermalWalker( - legacy_system, legacy_hamiltonian, legacy_trial, - walker_opts=options, verbose=i == 0) for i in range(nwalkers)] - - # 5. Build propagator. - qmc_opts = QMCOpts() - qmc_opts.nwalkers = nwalkers - qmc_opts.ntot_walkers = nwalkers - qmc_opts.beta = beta - qmc_opts.nsteps = nsteps_per_block - qmc_opts.dt = timestep - qmc_opts.seed = seed - - legacy_propagator = PlaneWave(legacy_system, legacy_hamiltonian, legacy_trial, qmc_opts, - options=options["propagator"], lowrank=lowrank, verbose=verbose) - - objs = {'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers, - 'propagator': propagator} - - legacy_objs = {'system': legacy_system, - 'trial': legacy_trial, - 'hamiltonian': legacy_hamiltonian, - 'walkers': legacy_walkers, - 'propagator': legacy_propagator} - - return objs, legacy_objs - - -@pytest.mark.unit -def test_phaseless_generic_propagator(verbose=False): - seed = 7 - objs, legacy_objs = setup_objs(seed=seed) - trial = objs['trial'] - hamiltonian = objs['hamiltonian'] - walkers = objs['walkers'] - propagator = objs['propagator'] - - legacy_system = legacy_objs['system'] - legacy_trial = legacy_objs['trial'] - legacy_hamiltonian = legacy_objs['hamiltonian'] - legacy_walkers = legacy_objs['walkers'] - legacy_propagator = legacy_objs['propagator'] - - h1e = legacy_hamiltonian.H1[0] - eri = legacy_hamiltonian.eri_4() - - for t in range(walkers.stack[0].nslice): - for iw in range(walkers.nwalkers): - P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) - eloc = local_energy_generic_cholesky(hamiltonian, P) - - legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers[iw].G)) - legacy_eloc = legacy_local_energy_ueg(legacy_system, legacy_hamiltonian, legacy_P) - - legacy_Pa, legacy_Pb = legacy_P - legacy_Ptot = legacy_Pa + legacy_Pb - ref_e1 = numpy.einsum('ij,ij->', h1e, legacy_Ptot) - - Ptot = legacy_Ptot - Pa = legacy_Pa - Pb = legacy_Pb - - ecoul = 0.5 * numpy.einsum('ijkl,ij,kl->', eri, Ptot, Ptot) - exx = -0.5 * numpy.einsum('ijkl,il,kj->', eri, Pa, Pa) - exx -= 0.5 * numpy.einsum('ijkl,il,kj->', eri, Pb, Pb) - ref_e2 = ecoul + exx - ref_eloc = (ref_e1 + ref_e2, ref_e1, ref_e2) - - if verbose: - print(f'\nt = {t}') - print(f'iw = {iw}') - print(f'eloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') - print(f'ref_eloc = \n{ref_eloc}\n') - print(f'walkers.weight = \n{walkers.weight[iw]}\n') - print(f'legacy_walkers.weight = \n{legacy_walkers[iw].weight}\n') - - numpy.testing.assert_almost_equal(legacy_P, P, decimal=10) - numpy.testing.assert_almost_equal(legacy_trial.dmat, trial.dmat, decimal=10) - numpy.testing.assert_allclose(eloc, ref_eloc, atol=1e-10) - numpy.testing.assert_allclose(legacy_eloc, ref_eloc, atol=1e-10) - numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) - - numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) - - propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) - legacy_walkers = legacy_propagate_walkers( - legacy_hamiltonian, legacy_trial, legacy_walkers, - legacy_propagator, xi=propagator.xi) - - -if __name__ == "__main__": - test_phaseless_generic_propagator(verbose=True) diff --git a/ipie/thermal/propagation/tests/ueg/ueg_trial.npy b/ipie/thermal/propagation/tests/ueg/ueg_trial.npy deleted file mode 100644 index 7cfba666c941ee47d15768d16c502137b443892b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12896 zcmeH{F>1pw7)I5#r_iPryadt~LZDl=mMk4Q6_Yq*2uZO+mk{V3a-d!*M~ItP;;W!b z9BT+qgRS2Nee(0uzk7Xq8Nc6{FSBveqMDR$VBK)idvuv~vsJk+^X12?oEEgUxw|19eI?%^r3z5ab>xAweoYmQ_8e7cA0cbJ_f7p_z1nP~s1^Hb-=-`l!wblCqi zlZa>Q_2czg=B4JHI`2Q;VIMKij_TBTjTR>4`Uf3-pI`n`d10N7_v`&go#%P^eCmck zqW=wVcpnMiTQ~~vs0rW$J}3cvP#T;Me82}KfDcN8{(ukopak$iY0w|=0UwkAJ}3?P z13ut`62J$gL4Uvpd{6@Tpfue03VbF{Q)2FK?&f4(x5-!13oALd{7$nhrcwg Gs5$_5)38YZ diff --git a/ipie/thermal/qmc/tests/reference_data/ueg/note b/ipie/thermal/qmc/tests/reference_data/ueg/note new file mode 100644 index 00000000..d8220d22 --- /dev/null +++ b/ipie/thermal/qmc/tests/reference_data/ueg/note @@ -0,0 +1 @@ +`reference_nompi.json` and `reference.json` results were generated using weight updates in the legacy code. diff --git a/ipie/thermal/qmc/tests/test_afqmc_generic.py b/ipie/thermal/qmc/tests/test_afqmc_generic.py new file mode 100644 index 00000000..10c6608e --- /dev/null +++ b/ipie/thermal/qmc/tests/test_afqmc_generic.py @@ -0,0 +1,180 @@ +import json +import tempfile +import h5py +import uuid +import pytest +import numpy +from typing import Union + +from ipie.config import MPI +from ipie.analysis.extraction import ( + extract_test_data_hdf5, + extract_data, + extract_observable, + extract_mixed_estimates) +from ipie.thermal.utils.testing import build_driver_generic_test_instance +from ipie.thermal.utils.legacy_testing import build_legacy_driver_generic_test_instance + + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 + +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) + +else: + test_id = None + +test_id = comm.bcast(test_id, root=0) + + +@pytest.mark.unit +def test_thermal_afqmc(): + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + + # Thermal AFQMC params. + mu = -10.0 + beta = 0.1 + timestep = 0.01 + nwalkers = 32 // comm.size + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 12 + stabilize_freq = 10 + pop_control_freq = 1 + pop_control_method = 'pair_branch' + #pop_control_method = 'comb' + lowrank = False + + verbose = False if (comm.rank != 0) else True + complex_integrals = False + debug = True + seed = 7 + numpy.random.seed(seed) + + with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "estimators": { + "filename": tmpf2.name, # For legacy. + }, + } + + # --------------------------------------------------------------------- + # Test. + # --------------------------------------------------------------------- + if verbose: + print('\n-----------------------') + print('Running ThermalAFQMC...') + print('-----------------------') + + afqmc = build_driver_generic_test_instance(options, seed, debug, verbose) + afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) + afqmc.finalise() + afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + + test_energy_data = None + test_energy_numer = None + test_energy_denom = None + test_number_data = None + + if comm.rank == 0: + test_energy_data = extract_observable(afqmc.estimators.filename, "energy") + test_energy_numer = afqmc.estimators["energy"]["ENumer"] + test_energy_denom = afqmc.estimators["energy"]["EDenom"] + test_number_data = extract_observable(afqmc.estimators.filename, "nav") + + # --------------------------------------------------------------------- + # Legacy. + # --------------------------------------------------------------------- + if verbose: + print('\n------------------------------') + print('Running Legacy ThermalAFQMC...') + print('------------------------------') + + legacy_afqmc = build_legacy_driver_generic_test_instance( + afqmc.hamiltonian, comm, options, seed, verbose) + legacy_afqmc.run(comm=comm) + legacy_afqmc.finalise(verbose=False) + legacy_afqmc.estimators.estimators["mixed"].update( + legacy_afqmc.qmc, + legacy_afqmc.system, + legacy_afqmc.hamiltonian, + legacy_afqmc.trial, + legacy_afqmc.walk, + 0, + legacy_afqmc.propagators.free_projection) + + legacy_mixed_data = None + enum = None + legacy_energy_numer = None + legacy_energy_denom = None + + if comm.rank == 0: + legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) + enum = legacy_afqmc.estimators.estimators["mixed"].names + legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] + legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] + + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(f'test filename: {afqmc.estimators.filename}') + print(f'legacy filename: {legacy_afqmc.estimators.filename}') + print(f'\ntest_energy_data: \n{test_energy_data}\n') + print(f'test_number_data: \n{test_number_data}\n') + print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') + + # Check. + assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) + assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) + assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) + assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) + + assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) + assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) + assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) + assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) + assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) + assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) + assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) + assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) + assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) + + +if __name__ == '__main__': + test_thermal_afqmc() + diff --git a/ipie/thermal/qmc/tests/test_generic.py b/ipie/thermal/qmc/tests/test_generic.py deleted file mode 100644 index d1209acb..00000000 --- a/ipie/thermal/qmc/tests/test_generic.py +++ /dev/null @@ -1,309 +0,0 @@ -import json -import tempfile -import h5py -import uuid -import pytest -import numpy -from typing import Union - -from ipie.config import MPI -from ipie.utils.testing import generate_hamiltonian -from ipie.systems.generic import Generic -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.qmc.options import QMCOpts - -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric -from ipie.thermal.qmc.options import ThermalQMCParams -from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC -from ipie.thermal.estimators.energy import local_energy -from ipie.analysis.extraction import ( - extract_test_data_hdf5, - extract_data, - extract_observable, - extract_mixed_estimates) - -from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.handler import Walkers -from ipie.legacy.walkers.thermal import ThermalWalker -from ipie.legacy.thermal_propagation.continuous import Continuous -from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky -from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC - - -comm = MPI.COMM_WORLD -serial_test = comm.size == 1 - -# Unique filename to avoid name collision when running through CI. -if comm.rank == 0: - test_id = str(uuid.uuid1()) - -else: - test_id = None - -test_id = comm.bcast(test_id, root=0) - - -def build_driver_test_instance(options: Union[dict, None], - seed: Union[int, None], - debug: bool = False, - verbose: bool = False): - # Unpack options - nelec = options['nelec'] - nbasis = options['nbasis'] - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] - numpy.random.seed(seed) - - complex_integrals = False - sym = 8 - if complex_integrals: sym = 4 - - params = ThermalQMCParams( - num_walkers=nwalkers, - total_num_walkers=nwalkers * comm.size, - num_blocks=nblocks, - timestep=timestep, - beta=beta, - num_stblz=stabilize_freq, - pop_control_freq=pop_control_freq, - pop_control_method=pop_control_method, - rng_seed=seed) - - system = Generic(nelec=nelec) - h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, - sym=sym, tol=1e-10) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nbasis**2)).T.copy(), - ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - trial = MeanField(hamiltonian, nelec, beta, timestep) - - nbasis = trial.dmat.shape[-1] - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank) - propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank) - propagator.build(hamiltonian, trial=trial, walkers=walkers) - - eloc = local_energy(hamiltonian, walkers) - print(f'# Initial energy = {eloc[0]}') - - afqmc = ThermalAFQMC(system, hamiltonian, trial, walkers, propagator, - params, debug=debug, verbose=verbose) - return afqmc, hamiltonian, walkers - - -def build_legacy_driver_instance(hamiltonian, - options: Union[dict, None], - seed: Union[int, None], - verbose: bool = False): - # Unpack options - nelec = options['nelec'] - nup, ndown = nelec - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] - numpy.random.seed(seed) - - legacy_options = { - "qmc": { - "dt": timestep, - "nwalkers": nwalkers, - "blocks": nblocks, - "nsteps": nsteps_per_block, - "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, - "stabilise_freq": stabilize_freq, - "batched": False - }, - - "propagator": { - "optimised": False - }, - - "walkers": { - "low_rank": lowrank, - "pop_control_freq": pop_control_freq, - "pop_control": pop_control_method - }, - - "system": { - "name": "Generic", - "nup": nup, - "ndown": ndown, - "mu": mu - }, - - "hamiltonian": options["hamiltonian"], - "estimators": options["estimators"] - } - - legacy_system = Generic(nelec) - legacy_system.mu = mu - legacy_hamiltonian = LegacyHamGeneric( - h1e=hamiltonian.H1, - chol=hamiltonian.chol, - ecore=hamiltonian.ecore, - options=legacy_options["hamiltonian"]) - legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) - legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] - legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep) - - afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, - legacy_hamiltonian, legacy_trial, verbose=verbose) - return afqmc - - -@pytest.mark.unit -def test_thermal_afqmc(): - # Thermal AFQMC params. - nup = 5 - ndown = 5 - nelec = (nup, ndown) - nbasis = 20 - - mu = -10.0 - beta = 0.1 - timestep = 0.01 - nwalkers = 10 - seed = 7 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 12 - stabilize_freq = 10 - pop_control_freq = 1 - pop_control_method = 'pair_branch' - #pop_control_method = 'comb' - lowrank = False - verbose = True - debug = True - - with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "estimators": { - "filename": tmpf2.name, # For legacy. - }, - } - - # --------------------------------------------------------------------- - # Test. - # --------------------------------------------------------------------- - print('\n-----------------------') - print('Running ThermalAFQMC...') - print('-----------------------') - afqmc, hamiltonian, walkers = build_driver_test_instance(options, seed, debug, verbose) - afqmc.run(walkers, verbose, estimator_filename=tmpf1.name) - afqmc.finalise() - afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) - - test_energy_data = extract_observable(afqmc.estimators.filename, "energy") - test_energy_numer = afqmc.estimators["energy"]["ENumer"] - test_energy_denom = afqmc.estimators["energy"]["EDenom"] - test_number_data = extract_observable(afqmc.estimators.filename, "nav") - - # --------------------------------------------------------------------- - # Legacy. - # --------------------------------------------------------------------- - print('\n------------------------------') - print('Running Legacy ThermalAFQMC...') - print('------------------------------') - legacy_afqmc = build_legacy_driver_instance(hamiltonian, options, seed, verbose) - legacy_afqmc.run(comm=comm) - legacy_afqmc.finalise(verbose=False) - legacy_afqmc.estimators.estimators["mixed"].update( - legacy_afqmc.qmc, - legacy_afqmc.system, - legacy_afqmc.hamiltonian, - legacy_afqmc.trial, - legacy_afqmc.walk, - 0, - legacy_afqmc.propagators.free_projection) - legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) - - enum = legacy_afqmc.estimators.estimators["mixed"].names - legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] - legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - - if verbose: - print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - print(f'test filename: {afqmc.estimators.filename}') - print(f'legacy filename: {legacy_afqmc.estimators.filename}') - print(f'\ntest_energy_data: \n{test_energy_data}\n') - print(f'test_number_data: \n{test_number_data}\n') - print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') - - # Check. - assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) - assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) - assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) - assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) - - assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) - assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) - assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) - assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) - assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) - assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) - assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) - assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) - assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) - - -if __name__ == '__main__': - test_thermal_afqmc() - diff --git a/ipie/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/thermal/qmc/tests/ueg/test_afqmc_ueg.py new file mode 100644 index 00000000..c5a33319 --- /dev/null +++ b/ipie/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -0,0 +1,460 @@ +import os +import sys +import json +import pprint +import tempfile +import h5py +import uuid +import pytest +import numpy +from typing import Union + +from ipie.config import MPI +from ipie.analysis.extraction import ( + get_metadata, + extract_test_data_hdf5, + extract_data, + extract_observable, + extract_mixed_estimates) +from ipie.thermal.utils.testing import build_driver_ueg_test_instance +from ipie.thermal.utils.legacy_testing import build_legacy_driver_ueg_test_instance + + +comm = MPI.COMM_WORLD +serial_test = comm.size == 1 + +# Unique filename to avoid name collision when running through CI. +if comm.rank == 0: + test_id = str(uuid.uuid1()) + +else: + test_id = None + +test_id = comm.bcast(test_id, root=0) + + +def compare_test_data(ref_data, test_data): + comparison = {} + + for k, v in ref_data.items(): + alias = [k] + + if k == "sys_info": + continue + + elif k == "EHybrid": + alias.append("HybridEnergy") + + err = 0 + ref = ref_data[k] + + for a in alias: + try: + test = test_data[a] + comparison[k] = ( + numpy.array(ref), + numpy.array(test), + numpy.max(numpy.abs(numpy.array(ref) - numpy.array(test))) < 1e-10) + + except KeyError: + err += 1 + + if err == len(alias): + print(f"# Issue with test data key {k}") + + return comparison + + +@pytest.mark.unit +def test_thermal_afqmc_1walker(against_ref=False): + # UEG params. + nup = 7 + ndown = 7 + nelec = (nup, ndown) + rs = 1. + ecut = 1. + + # Thermal AFQMC params. + mu = -1. + beta = 0.1 + timestep = 0.01 + nwalkers = 1 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 11 + stabilize_freq = 10 + pop_control_freq = 1 + + # `pop_control_method` doesn't matter for 1 walker. + pop_control_method = "pair_branch" + #pop_control_method = "comb" + lowrank = False + + verbose = False if (comm.rank != 0) else True + debug = True + seed = 7 + numpy.random.seed(seed) + + with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: + options = { + 'nelec': nelec, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + + "ueg_opts": { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + }, + + "hamiltonian": { + "name": "UEG", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "estimators": { + "filename": tmpf2.name, # For legacy. + }, + } + + # --------------------------------------------------------------------- + # Test. + # --------------------------------------------------------------------- + if verbose: + print('\n-----------------------') + print('Running ThermalAFQMC...') + print('-----------------------') + + afqmc = build_driver_ueg_test_instance(options, seed, debug, verbose) + afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) + afqmc.finalise() + afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + + test_energy_data = None + test_energy_numer = None + test_energy_denom = None + test_number_data = None + + if comm.rank == 0: + test_energy_data = extract_observable(afqmc.estimators.filename, "energy") + test_energy_numer = afqmc.estimators["energy"]["ENumer"] + test_energy_denom = afqmc.estimators["energy"]["EDenom"] + test_number_data = extract_observable(afqmc.estimators.filename, "nav") + + # --------------------------------------------------------------------- + # Legacy. + # --------------------------------------------------------------------- + if verbose: + print('\n------------------------------') + print('Running Legacy ThermalAFQMC...') + print('------------------------------') + + legacy_afqmc = build_legacy_driver_ueg_test_instance( + afqmc.hamiltonian, comm, options, seed, verbose) + legacy_afqmc.run(comm=comm) + legacy_afqmc.finalise(verbose=False) + legacy_afqmc.estimators.estimators["mixed"].update( + legacy_afqmc.qmc, + legacy_afqmc.system, + legacy_afqmc.hamiltonian, + legacy_afqmc.trial, + legacy_afqmc.walk, + 0, + legacy_afqmc.propagators.free_projection) + + legacy_mixed_data = None + enum = None + legacy_energy_numer = None + legacy_energy_denom = None + + if comm.rank == 0: + legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) + enum = legacy_afqmc.estimators.estimators["mixed"].names + legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] + legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] + + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(f'test filename: {afqmc.estimators.filename}') + print(f'legacy filename: {legacy_afqmc.estimators.filename}') + print(f'\ntest_energy_data: \n{test_energy_data}\n') + print(f'test_number_data: \n{test_number_data}\n') + print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') + + # Check. + assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) + assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) + assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) + assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) + + assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) + assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) + assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) + assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) + assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) + assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) + assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) + assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) + assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) + + # --------------------------------------------------------------------- + # Test against reference data. + if against_ref: + _data_dir = os.path.abspath(os.path.dirname(__file__)).split("ueg")[0] + "/reference_data/" + _legacy_test_dir = "ueg" + _legacy_test = _data_dir + _legacy_test_dir + "/reference_1walker.json" + + test_name = _legacy_test_dir + with open(_legacy_test, "r") as f: + ref_data = json.load(f) + + skip_val = ref_data.get("extract_skip_value", 10) + _test_energy_data = test_energy_data[::skip_val].to_dict(orient="list") + _test_number_data = test_number_data[::skip_val].to_dict(orient="list") + energy_comparison = compare_test_data(ref_data, _test_energy_data) + number_comparison = compare_test_data(ref_data, _test_number_data) + + print('\nenergy comparison:') + pprint.pprint(energy_comparison) + print('\nnumber comparison:') + pprint.pprint(number_comparison) + + local_err_count = 0 + + for k, v in energy_comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + + for k, v in number_comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + + if local_err_count == 0: + print(f"\n*** PASSED : {test_name} ***\n") + +@pytest.mark.unit +def test_thermal_afqmc(against_ref=False): + # UEG params. + nup = 7 + ndown = 7 + nelec = (nup, ndown) + rs = 1. + ecut = 1. + + # Thermal AFQMC params. + mu = -1. + beta = 0.1 + timestep = 0.01 + nwalkers = 32 // comm.size + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 11 + stabilize_freq = 10 + pop_control_freq = 1 + + # `pop_control_method` doesn't matter for 1 walker. + pop_control_method = "pair_branch" + #pop_control_method = "comb" + lowrank = False + + verbose = False if (comm.rank != 0) else True + debug = True + seed = 7 + numpy.random.seed(seed) + + with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: + options = { + 'nelec': nelec, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + + "ueg_opts": { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + }, + + "hamiltonian": { + "name": "UEG", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "estimators": { + "filename": tmpf2.name, # For legacy. + }, + } + + # --------------------------------------------------------------------- + # Test. + # --------------------------------------------------------------------- + if verbose: + print('\n-----------------------') + print('Running ThermalAFQMC...') + print('-----------------------') + + afqmc = build_driver_ueg_test_instance(options, seed, debug, verbose) + afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) + afqmc.finalise() + afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + + test_energy_data = None + test_energy_numer = None + test_energy_denom = None + test_number_data = None + + if comm.rank == 0: + test_energy_data = extract_observable(afqmc.estimators.filename, "energy") + test_energy_numer = afqmc.estimators["energy"]["ENumer"] + test_energy_denom = afqmc.estimators["energy"]["EDenom"] + test_number_data = extract_observable(afqmc.estimators.filename, "nav") + + # --------------------------------------------------------------------- + # Legacy. + # --------------------------------------------------------------------- + if verbose: + print('\n------------------------------') + print('Running Legacy ThermalAFQMC...') + print('------------------------------') + + legacy_afqmc = build_legacy_driver_ueg_test_instance( + afqmc.hamiltonian, comm, options, seed, verbose) + legacy_afqmc.run(comm=comm) + legacy_afqmc.finalise(verbose=False) + legacy_afqmc.estimators.estimators["mixed"].update( + legacy_afqmc.qmc, + legacy_afqmc.system, + legacy_afqmc.hamiltonian, + legacy_afqmc.trial, + legacy_afqmc.walk, + 0, + legacy_afqmc.propagators.free_projection) + + legacy_mixed_data = None + enum = None + legacy_energy_numer = None + legacy_energy_denom = None + + if comm.rank == 0: + legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) + enum = legacy_afqmc.estimators.estimators["mixed"].names + legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] + legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] + + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(f'test filename: {afqmc.estimators.filename}') + print(f'legacy filename: {legacy_afqmc.estimators.filename}') + print(f'\ntest_energy_data: \n{test_energy_data}\n') + print(f'test_number_data: \n{test_number_data}\n') + print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') + + # Check. + assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) + assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) + assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) + assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) + + assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) + assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) + assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) + assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) + assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) + assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) + assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) + assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) + assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) + + # --------------------------------------------------------------------- + # Test against reference data. + if against_ref: + _data_dir = os.path.abspath(os.path.dirname(__file__)).split("ueg")[0] + "/reference_data/" + _legacy_test_dir = "ueg" + _legacy_test = _data_dir + _legacy_test_dir + "/reference.json" + + test_name = _legacy_test_dir + with open(_legacy_test, "r") as f: + ref_data = json.load(f) + + skip_val = ref_data.get("extract_skip_value", 10) + _test_energy_data = test_energy_data[::skip_val].to_dict(orient="list") + _test_number_data = test_number_data[::skip_val].to_dict(orient="list") + energy_comparison = compare_test_data(ref_data, _test_energy_data) + number_comparison = compare_test_data(ref_data, _test_number_data) + + print('\nenergy comparison:') + pprint.pprint(energy_comparison) + print('\nnumber comparison:') + pprint.pprint(number_comparison) + + local_err_count = 0 + + for k, v in energy_comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + + for k, v in number_comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + + if local_err_count == 0: + print(f"\n*** PASSED : {test_name} ***\n") + + +if __name__ == '__main__': + test_thermal_afqmc_1walker(against_ref=False) + test_thermal_afqmc() + diff --git a/ipie/thermal/qmc/tests/ueg/test_ueg.py b/ipie/thermal/qmc/tests/ueg/test_ueg.py deleted file mode 100644 index f29745b5..00000000 --- a/ipie/thermal/qmc/tests/ueg/test_ueg.py +++ /dev/null @@ -1,563 +0,0 @@ -import os -import sys -import json -import pprint -import tempfile -import h5py -import uuid -import pytest -import numpy -from typing import Union - -from ueg import UEG -from ipie.config import MPI -from ipie.systems.generic import Generic -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.qmc.options import QMCOpts - -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric -from ipie.thermal.qmc.options import ThermalQMCParams -from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC -from ipie.thermal.estimators.energy import local_energy -from ipie.analysis.extraction import ( - get_metadata, - extract_test_data_hdf5, - extract_data, - extract_observable, - extract_mixed_estimates) - -from ipie.legacy.systems.ueg import UEG as LegacyUEG -from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.thermal import ThermalWalker -from ipie.legacy.thermal_propagation.planewave import PlaneWave -from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg -from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC - - -comm = MPI.COMM_WORLD -serial_test = comm.size == 1 - -# Unique filename to avoid name collision when running through CI. -if comm.rank == 0: - test_id = str(uuid.uuid1()) - -else: - test_id = None - -test_id = comm.bcast(test_id, root=0) - - -def compare_test_data(ref_data, test_data): - comparison = {} - - for k, v in ref_data.items(): - alias = [k] - - if k == "sys_info": - continue - - elif k == "EHybrid": - alias.append("HybridEnergy") - - err = 0 - ref = ref_data[k] - - for a in alias: - try: - test = test_data[a] - comparison[k] = ( - numpy.array(ref), - numpy.array(test), - numpy.max(numpy.abs(numpy.array(ref) - numpy.array(test))) < 1e-10) - - except KeyError: - err += 1 - - if err == len(alias): - print(f"# Issue with test data key {k}") - - return comparison - - -def build_driver_test_instance(ueg: UEG, - options: Union[dict, None], - seed: Union[int, None], - debug: bool = False, - verbose: bool = False): - # Unpack options - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] - numpy.random.seed(seed) - - nbasis = ueg.nbasis - nchol = ueg.nchol - nelec = (ueg.nup, ueg.ndown) - nup, ndown = nelec - - h1 = ueg.H1[0] - chol = 2. * ueg.chol_vecs.toarray().copy() - #ecore = ueg.ecore - ecore = 0. - - params = ThermalQMCParams( - num_walkers=nwalkers, - total_num_walkers=nwalkers * comm.size, - num_blocks=nblocks, - timestep=timestep, - beta=beta, - num_stblz=stabilize_freq, - pop_control_freq=pop_control_freq, - pop_control_method=pop_control_method, - rng_seed=seed) - - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - - # 1. Build Hamiltonian. - hamiltonian = HamGeneric( - numpy.array([h1, h1], dtype=numpy.complex128), - numpy.array(chol, dtype=numpy.complex128), - ecore, - verbose=verbose) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - - # 2. Build trial. - trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) - - # 3. Build walkers. - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) - - # 4. Build propagator. - propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) - - eloc = local_energy(hamiltonian, walkers) - print(f'# Initial energy = {eloc[0]}') - - # 5. Build Thermal AFQMC driver. - # Dummy system. - system = None - afqmc = ThermalAFQMC(system, hamiltonian, trial, walkers, propagator, - params, debug=debug, verbose=verbose) - return afqmc, hamiltonian, walkers - - -def build_legacy_driver_instance(hamiltonian, - options: Union[dict, None], - seed: Union[int, None], - verbose: bool = False): - # Unpack options - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] - numpy.random.seed(seed) - - legacy_options = { - "qmc": { - "dt": timestep, - "nwalkers": nwalkers, - "blocks": nblocks, - "nsteps": nsteps_per_block, - "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, - "stabilise_freq": stabilize_freq, - "batched": False - }, - - "propagator": { - "optimised": False - }, - - "walkers": { - "low_rank": lowrank, - "pop_control_freq": pop_control_freq, - "pop_control": pop_control_method - }, - - "ueg_opts": options["ueg_opts"], - "hamiltonian": options["hamiltonian"], - "estimators": options["estimators"] - } - - # 1. Build out system. - legacy_system = LegacyUEG(options=legacy_options["ueg_opts"]) - legacy_system.mu = mu - - # 2. Build Hamiltonian. - legacy_hamiltonian = LegacyHamUEG(legacy_system, options=legacy_options["ueg_opts"]) - legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] - - # 3. Build trial. - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) - - # 4. Build Thermal AFQMC. - afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, - legacy_hamiltonian, legacy_trial, verbose=verbose) - return afqmc - - -@pytest.mark.unit -def test_thermal_afqmc_1walker(against_ref=False): - # Thermal AFQMC params. - seed = 7 - mu = -1. - beta = 0.1 - timestep = 0.01 - nwalkers = 1 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 11 - stabilize_freq = 10 - pop_control_freq = 1 - - # `pop_control_method` doesn't matter for 1 walker. - pop_control_method = "pair_branch" - #pop_control_method = "comb" - lowrank = False - verbose = True - debug = True - numpy.random.seed(seed) - - with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: - ueg_opts = { - "nup": 7, - "ndown": 7, - "rs": 1., - "ecut": 1., - "thermal": True, - "write_integrals": False, - "low_rank": lowrank - } - - # Generate UEG integrals. - ueg = UEG(ueg_opts, verbose=verbose) - ueg.build(verbose=verbose) - nbasis = ueg.nbasis - nchol = ueg.nchol - nelec = (ueg.nup, ueg.ndown) - nup, ndown = nelec - - if verbose: - print(f"# nbasis = {nbasis}") - print(f"# nchol = {nchol}") - print(f"# nup = {nup}") - print(f"# ndown = {ndown}") - - # --------------------------------------------------------------------- - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - - "hamiltonian": { - "name": "UEG", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "estimators": { - "filename": tmpf2.name, # For legacy. - }, - - "ueg_opts": ueg_opts - } - - # --------------------------------------------------------------------- - # Test. - # --------------------------------------------------------------------- - print('\n-----------------------') - print('Running ThermalAFQMC...') - print('-----------------------') - afqmc, hamiltonian, walkers = build_driver_test_instance(ueg, options, seed, debug, verbose) - afqmc.run(walkers, verbose, estimator_filename=tmpf1.name) - afqmc.finalise() - afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) - - test_energy_data = extract_observable(afqmc.estimators.filename, "energy") - test_energy_numer = afqmc.estimators["energy"]["ENumer"] - test_energy_denom = afqmc.estimators["energy"]["EDenom"] - test_number_data = extract_observable(afqmc.estimators.filename, "nav") - - # --------------------------------------------------------------------- - # Legacy. - # --------------------------------------------------------------------- - print('\n------------------------------') - print('Running Legacy ThermalAFQMC...') - print('------------------------------') - legacy_afqmc = build_legacy_driver_instance(hamiltonian, options, seed, verbose) - legacy_afqmc.run(comm=comm) - legacy_afqmc.finalise(verbose=False) - legacy_afqmc.estimators.estimators["mixed"].update( - legacy_afqmc.qmc, - legacy_afqmc.system, - legacy_afqmc.hamiltonian, - legacy_afqmc.trial, - legacy_afqmc.walk, - 0, - legacy_afqmc.propagators.free_projection) - legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) - - enum = legacy_afqmc.estimators.estimators["mixed"].names - legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] - legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - - # --------------------------------------------------------------------- - if verbose: - print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - print(f'test filename: {afqmc.estimators.filename}') - print(f'legacy filename: {legacy_afqmc.estimators.filename}') - print(f'\ntest_energy_data: \n{test_energy_data}\n') - print(f'test_number_data: \n{test_number_data}\n') - print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') - - # Check. - assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) - assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) - assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) - assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) - - assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) - assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) - assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) - assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) - assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) - assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) - assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) - assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) - assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) - - # --------------------------------------------------------------------- - # Test against reference data. - if against_ref: - _data_dir = os.path.abspath(os.path.dirname(__file__)).split("ueg")[0] + "/reference_data/" - _legacy_test_dir = "ueg" - _legacy_test = _data_dir + _legacy_test_dir + "/reference_1walker.json" - - test_name = _legacy_test_dir - with open(_legacy_test, "r") as f: - ref_data = json.load(f) - - skip_val = ref_data.get("extract_skip_value", 10) - _test_energy_data = test_energy_data[::skip_val].to_dict(orient="list") - _test_number_data = test_number_data[::skip_val].to_dict(orient="list") - energy_comparison = compare_test_data(ref_data, _test_energy_data) - number_comparison = compare_test_data(ref_data, _test_number_data) - - print('\nenergy comparison:') - pprint.pprint(energy_comparison) - print('\nnumber comparison:') - pprint.pprint(number_comparison) - - local_err_count = 0 - - for k, v in energy_comparison.items(): - if not v[-1]: - local_err_count += 1 - print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") - print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") - - for k, v in number_comparison.items(): - if not v[-1]: - local_err_count += 1 - print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") - print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") - - if local_err_count == 0: - print(f"\n*** PASSED : {test_name} ***\n") - -@pytest.mark.unit -def test_thermal_afqmc(): - # Thermal AFQMC params. - seed = 7 - mu = -1. - beta = 0.1 - timestep = 0.01 - nwalkers = 32 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 11 - stabilize_freq = 10 - pop_control_freq = 1 - pop_control_method = "pair_branch" - #pop_control_method = "comb" - lowrank = False - verbose = True - debug = True - numpy.random.seed(seed) - - with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: - ueg_opts = { - "nup": 7, - "ndown": 7, - "rs": 1., - "ecut": 1., - "thermal": True, - "write_integrals": False, - "low_rank": lowrank - } - - # Generate UEG integrals. - ueg = UEG(ueg_opts, verbose=verbose) - ueg.build(verbose=verbose) - nbasis = ueg.nbasis - nchol = ueg.nchol - nelec = (ueg.nup, ueg.ndown) - nup, ndown = nelec - - if verbose: - print(f"# nbasis = {nbasis}") - print(f"# nchol = {nchol}") - print(f"# nup = {nup}") - print(f"# ndown = {ndown}") - - # --------------------------------------------------------------------- - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - - "hamiltonian": { - "name": "UEG", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "estimators": { - "filename": tmpf2.name, # For legacy. - }, - - "ueg_opts": ueg_opts - } - - # --------------------------------------------------------------------- - # Test. - # --------------------------------------------------------------------- - print('\n-----------------------') - print('Running ThermalAFQMC...') - print('-----------------------') - afqmc, hamiltonian, walkers = build_driver_test_instance(ueg, options, seed, debug, verbose) - afqmc.run(walkers, verbose, estimator_filename=tmpf1.name) - afqmc.finalise() - afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) - - test_energy_data = extract_observable(afqmc.estimators.filename, "energy") - test_energy_numer = afqmc.estimators["energy"]["ENumer"] - test_energy_denom = afqmc.estimators["energy"]["EDenom"] - test_number_data = extract_observable(afqmc.estimators.filename, "nav") - - # --------------------------------------------------------------------- - # Legacy. - # --------------------------------------------------------------------- - print('\n------------------------------') - print('Running Legacy ThermalAFQMC...') - print('------------------------------') - legacy_afqmc = build_legacy_driver_instance(hamiltonian, options, seed, verbose) - legacy_afqmc.run(comm=comm) - legacy_afqmc.finalise(verbose=False) - legacy_afqmc.estimators.estimators["mixed"].update( - legacy_afqmc.qmc, - legacy_afqmc.system, - legacy_afqmc.hamiltonian, - legacy_afqmc.trial, - legacy_afqmc.walk, - 0, - legacy_afqmc.propagators.free_projection) - legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) - - enum = legacy_afqmc.estimators.estimators["mixed"].names - legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] - legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - - # --------------------------------------------------------------------- - if verbose: - print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - print(f'test filename: {afqmc.estimators.filename}') - print(f'legacy filename: {legacy_afqmc.estimators.filename}') - print(f'\ntest_energy_data: \n{test_energy_data}\n') - print(f'test_number_data: \n{test_number_data}\n') - print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') - - assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) - assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) - assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) - - assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) - assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) - assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) - assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) - assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) - assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) - assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) - assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) - assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( - numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) - - -if __name__ == '__main__': - test_thermal_afqmc_1walker(against_ref=True) - test_thermal_afqmc() - diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/thermal/qmc/thermal_afqmc.py index f7f38dbe..72a34749 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/thermal/qmc/thermal_afqmc.py @@ -1,4 +1,4 @@ -"""Driver to perform AFQMC calculation""" +"""Driver to perform Thermal AFQMC calculation""" import numpy import time import json @@ -12,7 +12,7 @@ from ipie.utils.io import to_json from ipie.utils.backend import arraylib as xp -from ipie.utils.backend import get_host_memory +from ipie.utils.backend import get_host_memory, synchronize from ipie.utils.misc import get_git_info, print_env_info from ipie.utils.mpi import MPIHandler from ipie.systems.generic import Generic @@ -23,9 +23,6 @@ from ipie.qmc.utils import set_rng_seed -## This is now only applicable to the Generic case! -## See test_generic.py for example. - class ThermalAFQMC(AFQMC): """Thermal AFQMC driver. @@ -61,7 +58,8 @@ def __init__(self, verbose: bool = False): super().__init__(system, hamiltonian, trial, walkers, propagator, params, verbose) self.debug = debug - + + @staticmethod def build( nelec: Tuple[int, int], mu: float, @@ -70,13 +68,15 @@ def build( trial, nwalkers: int = 100, seed: int = None, - nsteps_per_block: int = 25, nblocks: int = 100, timestep: float = 0.005, stabilize_freq: int = 5, pop_control_freq: int = 5, + pop_control_method: str = 'pair_branch', lowrank: bool = False, - verbose: bool = True) -> "Thermal AFQMC": + debug: bool = False, + verbose: bool = True, + mpi_handler=None,) -> "Thermal AFQMC": """Factory method to build thermal AFQMC driver from hamiltonian and trial density matrix. Parameters @@ -113,24 +113,32 @@ def build( verbose : bool Log verbosity. Default True i.e. print information to stdout. """ - mpi_handler = MPIHandler() - comm = mpi_handler.comm + if mpi_handler is None: + mpi_handler = MPIHandler() + comm = mpi_handler.comm + + else: + comm = mpi_handler.comm + params = ThermalQMCParams( beta=beta, num_walkers=nwalkers, total_num_walkers=nwalkers * comm.size, num_blocks=nblocks, - num_steps_per_block=nsteps_per_block, timestep=timestep, num_stblz=stabilize_freq, pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, rng_seed=seed) - + + system = Generic(nelec) walkers = UHFThermalWalkers(trial, hamiltonian.nbasis, nwalkers, - lowrank=lowrank, verbose=verbose) + lowrank=lowrank, mpi_handler=mpi_handler, + verbose=verbose) propagator = Propagator[type(hamiltonian)]( - timestep, beta, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, + mpi_handler=mpi_handler, verbose=verbose) return ThermalAFQMC( system, hamiltonian, @@ -138,6 +146,7 @@ def build( walkers, propagator, params, + debug=debug, verbose=(verbose and comm.rank == 0)) @@ -180,6 +189,7 @@ def run(self, self.get_env_info() self.setup_estimators(estimator_filename, additional_estimators=additional_estimators) + synchronize() comm = self.mpi_handler.comm self.tsetup += time.time() - ft_setup @@ -193,6 +203,7 @@ def run(self, nslices = numpy.rint(self.params.beta / self.params.timestep).astype(int) for step in range(1, total_steps + 1): + synchronize() start_path = time.time() for t in range(nslices): @@ -214,6 +225,7 @@ def run(self, xp.clip(self.walkers.weight, a_min=-wbound, a_max=wbound, out=self.walkers.weight) # In-place clipping. + synchronize() self.tprop_clip += time.time() - start_clip start_barrier = time.time() @@ -227,6 +239,7 @@ def run(self, if (t > 0) and (t % self.params.pop_control_freq == 0): start = time.time() self.pcontrol.pop_control(self.walkers, comm) + synchronize() self.tpopc += time.time() - start self.tpopc_send = self.pcontrol.timer.send_time self.tpopc_recv = self.pcontrol.timer.recv_time @@ -248,6 +261,7 @@ def run(self, comm, step // self.params.num_steps_per_block, self.accumulators) self.accumulators.zero() + synchronize() self.testim += time.time() - start if step < neqlb_steps: @@ -257,6 +271,8 @@ def run(self, eshift += self.accumulators.eshift - eshift self.walkers.reset(self.trial) # Reset stack, weights, phase. + + synchronize() self.tpath += time.time() - start_path diff --git a/ipie/thermal/trial/chem_pot.py b/ipie/thermal/trial/chem_pot.py index 29946327..8af3a870 100644 --- a/ipie/thermal/trial/chem_pot.py +++ b/ipie/thermal/trial/chem_pot.py @@ -4,10 +4,11 @@ from ipie.utils.io import format_fixed_width_floats, format_fixed_width_strings -def find_chemical_potential( - alt_convention, rho, beta, num_bins, target, deps=1e-6, max_it=1000, verbose=False -): - # Todo: some sort of generic starting point independent of +def find_chemical_potential(alt_convention, rho, beta, num_bins, target, + deps=1e-6, max_it=1000, verbose=False): + """Find the chemical potential to match . + """ + # TODO: some sort of generic starting point independent of # system/temperature dmu1 = dmu2 = 1 mu1 = -1 @@ -63,4 +64,5 @@ def delta_nav(dm, nav): def compute_rho(rho, mu, beta, sign=1): - return numpy.einsum("ijk,k->ijk", rho, numpy.exp(sign * beta * mu * numpy.ones(rho.shape[-1]))) + return numpy.einsum( + "ijk,k->ijk", rho, numpy.exp(sign * beta * mu * numpy.ones(rho.shape[-1]))) diff --git a/ipie/thermal/trial/one_body.py b/ipie/thermal/trial/one_body.py index b471b635..f57b48fa 100644 --- a/ipie/thermal/trial/one_body.py +++ b/ipie/thermal/trial/one_body.py @@ -12,6 +12,7 @@ class OneBody(object): def __init__(self, hamiltonian, nelec, beta, dt, options={}, nav=None, H1=None, verbose=False): self.name = "thermal" + self.compute_trial_energy = False self.verbose = verbose if H1 is None: diff --git a/ipie/thermal/trial/tests/test_chem_pot.py b/ipie/thermal/trial/tests/test_chem_pot.py new file mode 100644 index 00000000..7bfc979d --- /dev/null +++ b/ipie/thermal/trial/tests/test_chem_pot.py @@ -0,0 +1,34 @@ +import numpy +import scipy.linalg +import pytest + +from ipie.thermal.trial.chem_pot import find_chemical_potential +from ipie.legacy.trial_density_matrices.chem_pot import find_chemical_potential as legacy_find_chemical_potential + + +@pytest.mark.unit +def test_find_chemical_potential(): + dt = 0.01 + beta = 1 + nstack = 3 + stack_length = 20 + nav = 7 + nbsf = 14 + _alt_convention = False + + dtau = dt * nstack + h1e = numpy.random.random((nbsf, nbsf)) + rho = numpy.array([scipy.linalg.expm(-dtau * h1e), + scipy.linalg.expm(-dtau * h1e)]) + + mu = find_chemical_potential(_alt_convention, rho, dt, stack_length, nav) + legacy_mu = legacy_find_chemical_potential(_alt_convention, rho, dt, stack_length, nav) + + numpy.testing.assert_allclose(mu, legacy_mu) + + +if __name__ == '__main__': + test_find_chemical_potential() + + + diff --git a/ipie/thermal/trial/tests/test_mean_field.py b/ipie/thermal/trial/tests/test_mean_field.py index d5a4a04b..03e0a61e 100644 --- a/ipie/thermal/trial/tests/test_mean_field.py +++ b/ipie/thermal/trial/tests/test_mean_field.py @@ -38,6 +38,8 @@ def setup_objs(): print('----------------------------') system = Generic(mol.nelec) hamiltonian = get_hamiltonian(system, options["hamiltonian"]) + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] objs = {'mol': mol, 'hamiltonian': hamiltonian} diff --git a/ipie/thermal/trial/tests/test_one_body.py b/ipie/thermal/trial/tests/test_one_body.py index 9237180c..4ffc94c3 100644 --- a/ipie/thermal/trial/tests/test_one_body.py +++ b/ipie/thermal/trial/tests/test_one_body.py @@ -38,6 +38,7 @@ def setup_objs(): print('----------------------------') system = Generic(mol.nelec) hamiltonian = get_hamiltonian(system, options["hamiltonian"]) + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] objs = {'mol': mol, 'hamiltonian': hamiltonian} diff --git a/ipie/thermal/utils/legacy_testing.py b/ipie/thermal/utils/legacy_testing.py new file mode 100644 index 00000000..b38eeddd --- /dev/null +++ b/ipie/thermal/utils/legacy_testing.py @@ -0,0 +1,425 @@ +import numpy +import pytest +from typing import Union + +from ipie.systems.generic import Generic +from ipie.qmc.options import QMCOpts +from ipie.utils.mpi import MPIHandler + +from ipie.legacy.systems.ueg import UEG as LegacyUEG +from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField +from ipie.legacy.walkers.thermal import ThermalWalker +from ipie.legacy.walkers.handler import Walkers +from ipie.legacy.thermal_propagation.continuous import Continuous +from ipie.legacy.thermal_propagation.planewave import PlaneWave +from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC + + +def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator, xi=None): + if xi is None: + xi = [None] * len(legacy_walkers) + + for iw, walker in enumerate(legacy_walkers.walkers): + legacy_propagator.propagate_walker( + legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) + + return legacy_walkers + + +def build_legacy_generic_test_case_handlers(hamiltonian, + comm, + options: dict, + seed: Union[int, None], + verbose: bool = False): + # Unpack options + nelec = options['nelec'] + nbasis = options['nbasis'] + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + + mf_trial = options.get('mf_trial', True) + propagate = options.get('propagate', False) + numpy.random.seed(seed) + + legacy_options = { + "walkers": { + "low_rank": lowrank, + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method + }, + + "propagator": { + "optimised": False + }, + } + + # 1. Build system. + legacy_system = Generic(nelec, verbose=verbose) + legacy_system.mu = mu + + # 2. Build Hamiltonian. + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + + # 3. Build trial. + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, + verbose=verbose) + if mf_trial: + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep, + verbose=verbose) + # 4. Build walkers. + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps_per_block + qmc_opts.dt = timestep + qmc_opts.seed = seed + + legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, + qmc_opts, walker_opts=legacy_options['walkers'], + verbose=verbose, comm=comm) + + # 5. Build propagator. + legacy_propagator = Continuous( + options["propagator"], qmc_opts, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose, + lowrank=lowrank) + + if propagate: + for t in range(legacy_walkers[0].stack.ntime_slices): + for iw, walker in enumerate(legacy_walkers): + legacy_propagator.propagate_walker( + legacy_hamiltonian, walker, legacy_trial) + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers, + 'propagator': legacy_propagator} + return legacy_objs + + +def build_legacy_generic_test_case_handlers_mpi(hamiltonian, + mpi_handler: MPIHandler, + options: dict, + seed: Union[int, None], + verbose: bool = False): + # Unpack options + nelec = options['nelec'] + nbasis = options['nbasis'] + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + + mf_trial = options.get('mf_trial', True) + propagate = options.get('propagate', False) + numpy.random.seed(seed) + comm = mpi_handler.comm + + legacy_options = { + "walkers": { + "low_rank": lowrank, + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method + }, + + "propagator": { + "optimised": False + }, + } + + # 1. Build system. + legacy_system = Generic(nelec, verbose=verbose) + legacy_system.mu = mu + + # 2. Build Hamiltonian. + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + + # 3. Build trial. + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, + verbose=verbose) + if mf_trial: + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep, + verbose=verbose) + # 4. Build walkers. + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers * comm.size + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps_per_block + qmc_opts.dt = timestep + qmc_opts.seed = seed + + legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, + qmc_opts, walker_opts=legacy_options['walkers'], + verbose=verbose, comm=comm) + + # 5. Build propagator. + legacy_propagator = Continuous( + options["propagator"], qmc_opts, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose, + lowrank=lowrank) + + if propagate: + for t in range(legacy_walkers[0].stack.ntime_slices): + for iw, walker in enumerate(legacy_walkers): + legacy_propagator.propagate_walker( + legacy_hamiltonian, walker, legacy_trial) + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers, + 'propagator': legacy_propagator} + return legacy_objs + + +def build_legacy_driver_generic_test_instance(hamiltonian, + comm, + options: Union[dict, None], + seed: Union[int, None], + verbose: bool = False): + # Unpack options + nelec = options['nelec'] + nup, ndown = nelec + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + numpy.random.seed(seed) + + legacy_options = { + "qmc": { + "dt": timestep, + # Input of `nwalkers` refers to the total number of walkers in + # legacy `ThermalAFQMC`. + "nwalkers": nwalkers * comm.size, + "blocks": nblocks, + "nsteps": nsteps_per_block, + "beta": beta, + "rng_seed": seed, + "pop_control_freq": pop_control_freq, + "stabilise_freq": stabilize_freq, + "batched": False + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank, + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method + }, + + "system": { + "name": "Generic", + "nup": nup, + "ndown": ndown, + "mu": mu + }, + + "hamiltonian": options["hamiltonian"], + "estimators": options["estimators"] + } + + legacy_system = Generic(nelec) + legacy_system.mu = mu + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore, + options=legacy_options["hamiltonian"]) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep) + + afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose) + return afqmc + + +def build_legacy_ueg_test_case_handlers(hamiltonian, + comm, + options: dict, + seed: Union[int, None], + verbose: bool = False): + # Unpack options + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + + lowrank = options['lowrank'] + propagate = options.get('propagate', False) + numpy.random.seed(seed) + + legacy_options = { + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank, + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method + }, + } + + # 1. Build out system. + legacy_system = LegacyUEG(options=options["ueg_opts"]) + legacy_system.mu = mu + + # 2. Build Hamiltonian. + legacy_hamiltonian = LegacyHamUEG(legacy_system, options=options["ueg_opts"]) + legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + + # 3. Build trial. + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) + + # 4. Build walkers. + qmc_opts = QMCOpts() + qmc_opts.nwalkers = nwalkers + qmc_opts.ntot_walkers = nwalkers * comm.size + qmc_opts.beta = beta + qmc_opts.nsteps = nsteps_per_block + qmc_opts.dt = timestep + qmc_opts.seed = seed + + legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, + qmc_opts, walker_opts=legacy_options['walkers'], + verbose=verbose, comm=comm) + + # 5. Build propagator. + legacy_propagator = PlaneWave(legacy_system, legacy_hamiltonian, legacy_trial, qmc_opts, + options=legacy_options["propagator"], lowrank=lowrank, verbose=verbose) + + if propagate: + for t in range(legacy_walkers[0].stack.ntime_slices): + for iw, walker in enumerate(legacy_walkers): + legacy_propagator.propagate_walker( + legacy_hamiltonian, walker, legacy_trial) + + legacy_objs = {'system': legacy_system, + 'trial': legacy_trial, + 'hamiltonian': legacy_hamiltonian, + 'walkers': legacy_walkers, + 'propagator': legacy_propagator} + return legacy_objs + + +def build_legacy_driver_ueg_test_instance(hamiltonian, + comm, + options: Union[dict, None], + seed: Union[int, None], + verbose: bool = False): + # Unpack options + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + numpy.random.seed(seed) + + legacy_options = { + "qmc": { + "dt": timestep, + # Input of `nwalkers` refers to the total number of walkers in + # legacy `ThermalAFQMC`. + "nwalkers": nwalkers * comm.size, + "blocks": nblocks, + "nsteps": nsteps_per_block, + "beta": beta, + "rng_seed": seed, + "pop_control_freq": pop_control_freq, + "stabilise_freq": stabilize_freq, + "batched": False + }, + + "propagator": { + "optimised": False + }, + + "walkers": { + "low_rank": lowrank, + "pop_control_freq": pop_control_freq, + "pop_control": pop_control_method + }, + + "ueg_opts": options["ueg_opts"], + "hamiltonian": options["hamiltonian"], + "estimators": options["estimators"] + } + + # 1. Build out system. + legacy_system = LegacyUEG(options=legacy_options["ueg_opts"]) + legacy_system.mu = mu + + # 2. Build Hamiltonian. + legacy_hamiltonian = LegacyHamUEG(legacy_system, options=legacy_options["ueg_opts"]) + legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] + legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] + + # 3. Build trial. + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) + + # 4. Build Thermal AFQMC. + afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, + legacy_hamiltonian, legacy_trial, verbose=verbose) + return afqmc + diff --git a/ipie/thermal/utils/testing.py b/ipie/thermal/utils/testing.py new file mode 100644 index 00000000..d328e805 --- /dev/null +++ b/ipie/thermal/utils/testing.py @@ -0,0 +1,340 @@ +import numpy +import pytest +from typing import Union + +from ipie.qmc.options import QMCOpts +from ipie.systems.generic import Generic +from ipie.utils.mpi import MPIHandler +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric + +from ipie.thermal.utils.ueg import UEG +from ipie.thermal.trial.one_body import OneBody +from ipie.thermal.trial.mean_field import MeanField +from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.thermal.qmc.options import ThermalQMCParams +from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC + + +def build_generic_test_case_handlers(options: dict, + seed: Union[int, None], + debug: bool = False, + with_eri: bool = False, + verbose: bool = False): + # Unpack options + nelec = options['nelec'] + nbasis = options['nbasis'] + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + + complex_integrals = options.get('complex_integrals', True) + mf_trial = options.get('mf_trial', True) + propagate = options.get('propagate', False) + diagonal = options.get('diagonal', False) + + sym = 8 + if complex_integrals: sym = 4 + numpy.random.seed(seed) + + # 1. Generate random integrals. + h1e, chol, _, eri = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + + if diagonal: + h1e = numpy.diag(numpy.diag(h1e)) + + # 2. Build Hamiltonian. + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + # 3. Build trial. + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + + if mf_trial: + trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) + + # 4. Build walkers. + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + + # 5. Build propagator. + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + if propagate: + for t in range(walkers.stack[0].nslice): + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=debug) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator} + + if with_eri: + objs['eri'] = eri + + return objs + + +def build_generic_test_case_handlers_mpi(options: dict, + mpi_handler: MPIHandler, + seed: Union[int, None], + debug: bool = False, + verbose: bool = False): + # Unpack options + nelec = options['nelec'] + nbasis = options['nbasis'] + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + + complex_integrals = options.get('complex_integrals', True) + mf_trial = options.get('mf_trial', True) + propagate = options.get('propagate', False) + diagonal = options.get('diagonal', False) + + sym = 8 + if complex_integrals: sym = 4 + numpy.random.seed(seed) + + # 1. Generate random integrals. + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + + if diagonal: + h1e = numpy.diag(numpy.diag(h1e)) + + # 2. Build Hamiltonian. + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + # 3. Build trial. + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + + if mf_trial: + trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) + + # 4. Build walkers. + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + mpi_handler=mpi_handler, verbose=verbose) + + # 5. Build propagator. + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, + mpi_handler=mpi_handler, verbose=verbose) + + if propagate: + for t in range(walkers.stack[0].nslice): + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=debug) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator} + return objs + + +def build_driver_generic_test_instance(options: Union[dict, None], + seed: Union[int, None], + debug: bool = False, + verbose: bool = False): + # Unpack options + nelec = options['nelec'] + nbasis = options['nbasis'] + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + complex_integrals = options['complex_integrals'] + diagonal = options.get('diagonal', False) + + sym = 8 + if complex_integrals: sym = 4 + numpy.random.seed(seed) + + # 1. Generate random integrals. + h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + + if diagonal: + h1e = numpy.diag(numpy.diag(h1e)) + + # 2. Build Hamiltonian. + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + # 3. Build trial. + trial = MeanField(hamiltonian, nelec, beta, timestep) + + # 4. Build Thermal AFQMC driver. + afqmc = ThermalAFQMC.build( + nelec, mu, beta, hamiltonian, trial, nwalkers, seed, + nblocks=nblocks, timestep=timestep, stabilize_freq=stabilize_freq, + pop_control_freq=pop_control_freq, pop_control_method=pop_control_method, + lowrank=lowrank, debug=debug, verbose=verbose) + return afqmc + + +def build_ueg_test_case_handlers(options: dict, + seed: Union[int, None], + debug: bool = False, + verbose: bool = False): + # Unpack options + ueg_opts = options['ueg_opts'] + nelec = options['nelec'] + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + + lowrank = options['lowrank'] + propagate = options.get('propagate', False) + numpy.random.seed(seed) + + # 1. Generate UEG integrals. + ueg = UEG(ueg_opts, verbose=verbose) + ueg.build(verbose=verbose) + nbasis = ueg.nbasis + nchol = ueg.nchol + nup, ndown = nelec + + if verbose: + print(f"# nbasis = {nbasis}") + print(f"# nchol = {nchol}") + print(f"# nup = {nup}") + print(f"# ndown = {ndown}") + + h1 = ueg.H1[0] + chol = 2. * ueg.chol_vecs.toarray().copy() + #ecore = ueg.ecore + ecore = 0. + + # 2. Build Hamiltonian. + hamiltonian = HamGeneric( + numpy.array([h1, h1], dtype=numpy.complex128), + numpy.array(chol, dtype=numpy.complex128), + ecore, + verbose=verbose) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + # 3. Build trial. + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + + # 4. Build walkers. + walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, + verbose=verbose) + + # 5. Build propagator. + propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) + propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) + + if propagate: + for t in range(walkers.stack[0].nslice): + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=debug) + + objs = {'trial': trial, + 'hamiltonian': hamiltonian, + 'walkers': walkers, + 'propagator': propagator} + return objs + + +def build_driver_ueg_test_instance(options: Union[dict, None], + seed: Union[int, None], + debug: bool = False, + verbose: bool = False): + # Unpack options + ueg_opts = options['ueg_opts'] + nelec = options['nelec'] + mu = options['mu'] + beta = options['beta'] + timestep = options['timestep'] + nwalkers = options['nwalkers'] + nsteps_per_block = options['nsteps_per_block'] + nblocks = options['nblocks'] + stabilize_freq = options['stabilize_freq'] + pop_control_freq = options['pop_control_freq'] + pop_control_method = options['pop_control_method'] + lowrank = options['lowrank'] + numpy.random.seed(seed) + + # 1. Generate UEG integrals. + ueg = UEG(ueg_opts, verbose=verbose) + ueg.build(verbose=verbose) + nbasis = ueg.nbasis + nchol = ueg.nchol + nup, ndown = nelec + + if verbose: + print(f"# nbasis = {nbasis}") + print(f"# nchol = {nchol}") + print(f"# nup = {nup}") + print(f"# ndown = {ndown}") + + h1 = ueg.H1[0] + chol = 2. * ueg.chol_vecs.toarray().copy() + #ecore = ueg.ecore + ecore = 0. + + # 2. Build Hamiltonian. + hamiltonian = HamGeneric( + numpy.array([h1, h1], dtype=numpy.complex128), + numpy.array(chol, dtype=numpy.complex128), + ecore, + verbose=verbose) + hamiltonian.name = options["hamiltonian"]["name"] + hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] + hamiltonian.sparse = options["hamiltonian"]["sparse"] + + # 3. Build trial. + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + + # 4. Build Thermal AFQMC driver. + afqmc = ThermalAFQMC.build( + nelec, mu, beta, hamiltonian, trial, nwalkers, seed, + nblocks=nblocks, timestep=timestep, stabilize_freq=stabilize_freq, + pop_control_freq=pop_control_freq, pop_control_method=pop_control_method, + lowrank=lowrank, debug=debug, verbose=verbose) + return afqmc + diff --git a/ipie/thermal/qmc/tests/ueg/ueg.py b/ipie/thermal/utils/ueg.py similarity index 100% rename from ipie/thermal/qmc/tests/ueg/ueg.py rename to ipie/thermal/utils/ueg.py diff --git a/ipie/thermal/walkers/tests/test_population_control.py b/ipie/thermal/walkers/tests/test_population_control.py index 03be42d9..de3bc84b 100644 --- a/ipie/thermal/walkers/tests/test_population_control.py +++ b/ipie/thermal/walkers/tests/test_population_control.py @@ -4,196 +4,239 @@ from ipie.config import MPI from ipie.utils.mpi import MPIHandler -from ipie.utils.testing import generate_hamiltonian from ipie.walkers.pop_controller import PopController -from ipie.systems.generic import Generic -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.qmc.options import QMCOpts -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric - -from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.handler import Walkers -from ipie.legacy.thermal_propagation.continuous import Continuous - - -def legacy_propagate_walkers(legacy_hamiltonian, - legacy_trial, - legacy_walkers, - legacy_propagator, - xi=None): - if xi is None: - xi = [None] * legacy_walkers.nwalkers - - for iw, walker in enumerate(legacy_walkers.walkers): - legacy_propagator.propagate_walker_phaseless( - legacy_hamiltonian, walker, legacy_trial, xi=xi[iw]) - - return legacy_walkers +from ipie.thermal.utils.testing import build_generic_test_case_handlers_mpi +from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers_mpi +from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers + +comm = MPI.COMM_WORLD +@pytest.mark.unit +def test_pair_branch_batch(): + mpi_handler = MPIHandler() -def setup_objs(mpi_handler, pop_control_method, seed=None): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) nbasis = 10 + # Thermal AFQMC params. mu = -10. beta = 0.1 timestep = 0.01 - nwalkers = 10 + nwalkers = 12 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 nblocks = 3 stabilize_freq = 10 pop_control_freq = 1 - nsteps = 1 - + pop_control_method = 'pair_branch' lowrank = False - verbose = True + + verbose = False if (comm.rank != 0) else True complex_integrals = False - sym = 8 - if complex_integrals: sym = 4 + debug = True + mf_trial = True + propagate = False + seed = 7 numpy.random.seed(seed) options = { - "qmc": { - "dt": timestep, - "nwalkers": nwalkers, - "blocks": nblocks, - "nsteps": nsteps, - "beta": beta, - "rng_seed": seed, - "stabilize_freq": stabilize_freq, - "batched": False, - }, - - "propagator": { - "optimised": False - }, - - "walkers": { - "pop_control_freq": pop_control_freq, - "pop_control": pop_control_method, - "low_rank": lowrank - }, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - } - } - + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } + # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, - sym=sym, tol=1e-10) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nbasis**2)).T.copy(), - ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - - trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) - #trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) - - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) - propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) - pcontrol = PopController(nwalkers, nsteps, mpi_handler, pop_control_method, verbose=verbose) - + if verbose: + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + objs = build_generic_test_case_handlers_mpi( + options, mpi_handler, seed, debug, verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + propagator = objs['propagator'] + pcontrol = PopController(nwalkers, nsteps_per_block, mpi_handler, + pop_control_method, verbose=verbose) # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_system = Generic(nelec, verbose=verbose) - legacy_system.mu = mu - legacy_hamiltonian = LegacyHamGeneric( - h1e=hamiltonian.H1, - chol=hamiltonian.chol, - ecore=hamiltonian.ecore) - legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) - legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, - verbose=verbose) - #legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep, - # verbose=verbose) - - qmc_opts = QMCOpts() - qmc_opts.nwalkers = nwalkers - qmc_opts.ntot_walkers = nwalkers - qmc_opts.beta = beta - qmc_opts.nsteps = nsteps - qmc_opts.dt = timestep - qmc_opts.seed = seed - - legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, - qmc_opts, walker_opts=options['walkers'], - verbose=verbose, comm=mpi_handler.comm) - - legacy_propagator = Continuous( - options["propagator"], qmc_opts, legacy_system, - legacy_hamiltonian, legacy_trial, verbose=verbose, - lowrank=lowrank) - - objs = {'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers, - 'propagator': propagator, - 'pcontrol': pcontrol, - 'nblocks': nblocks} - - legacy_objs = {'system': legacy_system, - 'trial': legacy_trial, - 'hamiltonian': legacy_hamiltonian, - 'walkers': legacy_walkers, - 'propagator': legacy_propagator} - - return objs, legacy_objs + if verbose: + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + + legacy_objs = build_legacy_generic_test_case_handlers_mpi( + hamiltonian, mpi_handler, options, seed=seed, verbose=verbose) + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + legacy_propagator = legacy_objs['propagator'] + for block in range(nblocks): + for t in range(walkers.stack[0].nslice): + if verbose: + print('\n------------------------------------------') + print(f'block = {block}, t = {t}') + print(f'walkers.weight[0] = {walkers.weight[0]}') + print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') + print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') + print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') + print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') + print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') -@pytest.mark.unit -def test_pair_branch_batch(): + propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) + legacy_walkers = legacy_propagate_walkers( + legacy_hamiltonian, legacy_trial, legacy_walkers, + legacy_propagator, xi=propagator.xi) + + if t > 0: + pcontrol.pop_control(walkers, mpi_handler.comm) + legacy_walkers.pop_control(mpi_handler.comm) + + walkers.reset(trial) # Reset stack, weights, phase. + legacy_walkers.reset(legacy_trial) + + for iw in range(walkers.nwalkers): + assert numpy.allclose(walkers.Ga[iw], legacy_walkers.walkers[iw].G[0]) + assert numpy.allclose(walkers.Gb[iw], legacy_walkers.walkers[iw].G[1]) + assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) + assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) + + +#@pytest.mark.unit +def test_pair_branch_batch_lowrank(): mpi_handler = MPIHandler() + + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + + # Thermal AFQMC params. + mu = -10. + beta = 0.1 + timestep = 0.01 + nwalkers = 12 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 3 + stabilize_freq = 10 + pop_control_freq = 1 pop_control_method = 'pair_branch' + lowrank = True + + verbose = False if (comm.rank != 0) else True + complex_integrals = False + debug = True + mf_trial = False + propagate = False + diagonal = True seed = 7 - objs, legacy_objs = setup_objs(mpi_handler, pop_control_method, seed=seed) + numpy.random.seed(seed) + + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + 'diagonal': diagonal, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } + + # Test. + if verbose: + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + objs = build_generic_test_case_handlers_mpi(options, mpi_handler, seed, debug, verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] propagator = objs['propagator'] - pcontrol = objs['pcontrol'] - nblocks = objs['nblocks'] + pcontrol = PopController(nwalkers, nsteps_per_block, mpi_handler, + pop_control_method=pop_control_method, verbose=verbose) + # Legacy. + if verbose: + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + + legacy_objs = build_legacy_generic_test_case_handlers_mpi( + hamiltonian, mpi_handler, options, seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] legacy_walkers = legacy_objs['walkers'] legacy_propagator = legacy_objs['propagator'] - + for block in range(nblocks): for t in range(walkers.stack[0].nslice): - print('\n------------------------------------------') - print(f'block = {block}, t = {t}') - print(f'walkers.weight[0] = {walkers.weight[0]}') - print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') - print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') - print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') - print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') - print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') + if verbose: + print('\n------------------------------------------') + print(f'block = {block}, t = {t}') + print(f'walkers.weight[0] = {walkers.weight[0]}') + print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') + print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') + print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') + print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') + print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) legacy_walkers = legacy_propagate_walkers( @@ -213,35 +256,107 @@ def test_pair_branch_batch(): assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) -#@pytest.mark.unit + +@pytest.mark.unit def test_comb_batch(): mpi_handler = MPIHandler() + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + + # Thermal AFQMC params. + mu = -10. + beta = 0.1 + timestep = 0.01 + nwalkers = 12 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 3 + stabilize_freq = 10 + pop_control_freq = 1 pop_control_method = 'comb' + lowrank = False + + verbose = False if (comm.rank != 0) else True + complex_integrals = False + debug = True + mf_trial = True + propagate = False seed = 7 - objs, legacy_objs = setup_objs(mpi_handler, pop_control_method, seed=seed) + numpy.random.seed(seed) + + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } + + # Test. + if verbose: + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + objs = build_generic_test_case_handlers_mpi(options, mpi_handler, seed, debug, verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] propagator = objs['propagator'] - pcontrol = objs['pcontrol'] - nblocks = objs['nblocks'] + pcontrol = PopController(nwalkers, nsteps_per_block, mpi_handler, + pop_control_method=pop_control_method, verbose=verbose) + # Legacy. + if verbose: + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + + legacy_objs = build_legacy_generic_test_case_handlers_mpi( + hamiltonian, mpi_handler, options, seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] legacy_walkers = legacy_objs['walkers'] legacy_propagator = legacy_objs['propagator'] - + for block in range(nblocks): for t in range(walkers.stack[0].nslice): - print('\n------------------------------------------') - print(f'block = {block}, t = {t}') - print(f'walkers.weight[0] = {walkers.weight[0]}') - print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') - print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') - print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') - print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') - print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') + if verbose: + print('\n------------------------------------------') + print(f'block = {block}, t = {t}') + print(f'walkers.weight[0] = {walkers.weight[0]}') + print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') + print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') + print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') + print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') + print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) legacy_walkers = legacy_propagate_walkers( @@ -261,35 +376,110 @@ def test_comb_batch(): assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) + #@pytest.mark.unit -def test_stochastic_reconfiguration_batch(): +def test_comb_batch_lowrank(): mpi_handler = MPIHandler() - pop_control_method = 'stochastic_reconfiguration' + + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + + # Thermal AFQMC params. + mu = -10. + beta = 0.1 + timestep = 0.01 + nwalkers = 12 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 3 + stabilize_freq = 10 + pop_control_freq = 1 + pop_control_method = 'comb' + lowrank = True + + verbose = False if (comm.rank != 0) else True + complex_integrals = False + debug = True + mf_trial = False + propagate = False + diagonal = True seed = 7 - objs, legacy_objs = setup_objs(mpi_handler, pop_control_method, seed=seed) + numpy.random.seed(seed) + + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + 'diagonal': diagonal, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } + + # Test. + if verbose: + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + objs = build_generic_test_case_handlers_mpi(options, mpi_handler, seed, debug, verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] propagator = objs['propagator'] - pcontrol = objs['pcontrol'] - nblocks = objs['nblocks'] + pcontrol = PopController(nwalkers, nsteps_per_block, mpi_handler, + pop_control_method=pop_control_method, verbose=verbose) + # Legacy. + if verbose: + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + + legacy_objs = build_legacy_generic_test_case_handlers_mpi( + hamiltonian, mpi_handler, options, seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] legacy_walkers = legacy_objs['walkers'] legacy_propagator = legacy_objs['propagator'] - + for block in range(nblocks): for t in range(walkers.stack[0].nslice): - print('\n------------------------------------------') - print(f'block = {block}, t = {t}') - print(f'walkers.weight[0] = {walkers.weight[0]}') - print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') - print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') - print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') - print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') - print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') + if verbose: + print('\n------------------------------------------') + print(f'block = {block}, t = {t}') + print(f'walkers.weight[0] = {walkers.weight[0]}') + print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') + print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') + print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') + print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') + print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) legacy_walkers = legacy_propagate_walkers( @@ -309,7 +499,10 @@ def test_stochastic_reconfiguration_batch(): assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) + if __name__ == "__main__": test_pair_branch_batch() - #test_comb_batch() - #test_stochastic_reconfiguration_batch() + test_comb_batch() + + #test_pair_branch_batch_lowrank() + #test_comb_batch_lowrank() diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/thermal/walkers/tests/test_thermal_walkers.py index bdd28f54..eb8c47f5 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/thermal/walkers/tests/test_thermal_walkers.py @@ -1,123 +1,201 @@ import numpy import pytest +from typing import Union -from ipie.systems.generic import Generic -from ipie.utils.testing import generate_hamiltonian -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.hamiltonians.utils import get_hamiltonian -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.config import MPI from ipie.thermal.estimators.generic import local_energy_generic_cholesky from ipie.thermal.estimators.thermal import one_rdm_from_G -from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.thermal import ThermalWalker from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G +from ipie.thermal.utils.testing import build_generic_test_case_handlers +from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers +from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers -def setup_objs(mf_trial=False, seed=None): - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) +comm = MPI.COMM_WORLD + +@pytest.mark.unit +def test_thermal_walkers_fullrank(): + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) nbasis = 10 + # Thermal AFQMC params. mu = -10. - beta = 0.02 - dt = 0.01 - nwalkers = 2 - numpy.random.seed(seed) - + beta = 0.1 + timestep = 0.01 + nwalkers = 10 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 12 + stabilize_freq = 10 + pop_control_freq = 1 + pop_control_method = 'pair_branch' + #pop_control_method = 'comb' lowrank = False + verbose = True complex_integrals = False - sym = 8 - if complex_integrals: sym = 4 + debug = True + mf_trial = True + propagate = False + seed = 7 + numpy.random.seed(seed) options = { - "walkers": { - "low_rank": lowrank - }, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - } - } - + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } + # Test. print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - h1e, chol, _, _ = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, - sym=sym, tol=1e-10) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), - chol=chol.reshape((-1, nbasis**2)).T.copy(), - ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - - trial = OneBody(hamiltonian, nelec, beta, dt, verbose=verbose) - - if mf_trial: - trial = MeanField(hamiltonian, nelec, beta, dt, verbose=verbose) - - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) + objs = build_generic_test_case_handlers(options, seed, debug, verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] # Legacy. print('\n------------------------------') print('Constructing legacy objects...') print('------------------------------') - legacy_system = Generic(nelec, verbose=verbose) - legacy_system.mu = mu - legacy_hamiltonian = LegacyHamGeneric( - h1e=hamiltonian.H1, - chol=hamiltonian.chol, - ecore=hamiltonian.ecore) - legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) - legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, dt, - verbose=verbose) - if mf_trial: - legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, dt, - verbose=verbose) - - legacy_walkers = [ - ThermalWalker( - legacy_system, legacy_hamiltonian, legacy_trial, - walker_opts=options, verbose=i == 0) for i in range(nwalkers)] + legacy_objs = build_legacy_generic_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) + legacy_system = legacy_objs['system'] + legacy_trial = legacy_objs['trial'] + legacy_hamiltonian = legacy_objs['hamiltonian'] + legacy_walkers = legacy_objs['walkers'] + + for iw in range(walkers.nwalkers): + P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + eloc = local_energy_generic_cholesky(hamiltonian, P) - objs = {'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers} + legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers.walkers[iw].G)) + legacy_eloc = legacy_local_energy_generic_cholesky( + legacy_system, legacy_hamiltonian, legacy_P) - legacy_objs = {'system': legacy_system, - 'trial': legacy_trial, - 'hamiltonian': legacy_hamiltonian, - 'walkers': legacy_walkers} + if verbose: + print(f'\niw = {iw}') + print(f'eloc = \n{eloc}\n') + print(f'legacy_eloc = \n{legacy_eloc}\n') + print(f'walkers.weight = \n{walkers.weight[iw]}\n') + print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') + + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) - return objs, legacy_objs - @pytest.mark.unit -def test_thermal_walkers(): +def test_thermal_walkers_lowrank(): + # System params. + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + + # Thermal AFQMC params. + mu = -10. + beta = 0.1 + timestep = 0.01 + nwalkers = 10 + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 12 + stabilize_freq = 10 + pop_control_freq = 1 + pop_control_method = 'pair_branch' + #pop_control_method = 'comb' + lowrank = True + verbose = True + complex_integrals = False + debug = True + mf_trial = False + propagate = False + diagonal = True seed = 7 - objs, legacy_objs = setup_objs(seed=seed) + numpy.random.seed(seed) + + options = { + 'nelec': nelec, + 'nbasis': nbasis, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, + 'complex_integrals': complex_integrals, + 'mf_trial': mf_trial, + 'propagate': propagate, + 'diagonal': diagonal, + + "hamiltonian": { + "name": "Generic", + "_alt_convention": False, + "sparse": False, + "mu": mu + }, + + "propagator": { + "optimised": False, + "free_projection": False + }, + } + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers(options, seed, debug, verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] + # Legacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_generic_test_case_handlers( + hamiltonian, comm, options, seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] @@ -127,7 +205,7 @@ def test_thermal_walkers(): P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) eloc = local_energy_generic_cholesky(hamiltonian, P) - legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers[iw].G)) + legacy_P = legacy_one_rdm_from_G(numpy.array(legacy_walkers.walkers[iw].G)) legacy_eloc = legacy_local_energy_generic_cholesky( legacy_system, legacy_hamiltonian, legacy_P) @@ -136,14 +214,14 @@ def test_thermal_walkers(): print(f'eloc = \n{eloc}\n') print(f'legacy_eloc = \n{legacy_eloc}\n') print(f'walkers.weight = \n{walkers.weight[iw]}\n') - print(f'legacy_walkers.weight = \n{legacy_walkers[iw].weight}\n') + print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].G[0], walkers.Ga[iw], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].G[1], walkers.Gb[iw], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) - + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) + numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) if __name__ == "__main__": - test_thermal_walkers() + test_thermal_walkers_fullrank() + test_thermal_walkers_lowrank() diff --git a/ipie/trial_wavefunction/noci.py b/ipie/trial_wavefunction/noci.py index 28dc3668..b369fef6 100644 --- a/ipie/trial_wavefunction/noci.py +++ b/ipie/trial_wavefunction/noci.py @@ -35,7 +35,7 @@ def build(self) -> None: ... def calculate_energy(self, system, hamiltonian): - return variational_energy_noci(hamiltonian, self) + return variational_energy_noci(system, hamiltonian, self) def half_rotate(self, hamiltonian, comm=None): orbsa = self.psi[: self.num_dets, :, : self.nalpha] diff --git a/ipie/trial_wavefunction/particle_hole.py b/ipie/trial_wavefunction/particle_hole.py index 22ba161a..fd891b24 100644 --- a/ipie/trial_wavefunction/particle_hole.py +++ b/ipie/trial_wavefunction/particle_hole.py @@ -399,7 +399,7 @@ def calculate_energy(self, system, hamiltonian): print("# Computing trial wavefunction energy.") # Cannot use usual energy evaluation routines if trial is orthogonal. self.energy, self.e1b, self.e2b = variational_energy_ortho_det( - system.nelec, hamiltonian, self.spin_occs, self.coeffs + system, hamiltonian, self.spin_occs, self.coeffs ) if self.verbose: print(f"# Variational energy of trial wavefunction: {self.energy.real}") diff --git a/ipie/trial_wavefunction/single_det.py b/ipie/trial_wavefunction/single_det.py index 052f0c39..46d07763 100644 --- a/ipie/trial_wavefunction/single_det.py +++ b/ipie/trial_wavefunction/single_det.py @@ -65,7 +65,7 @@ def calculate_energy(self, system, hamiltonian) -> numpy.ndarray: + hamiltonian.ecore ) self.ej, self.ek = half_rotated_cholesky_jk( - self.Ghalf[0], self.Ghalf[1], trial=self + system, self.Ghalf[0], self.Ghalf[1], trial=self ) self.e2b = self.ej + self.ek self.energy = self.e1b + self.e2b diff --git a/ipie/walkers/tests/test_multi_det_batch.py b/ipie/walkers/tests/test_multi_det_batch.py index b2c6cd0f..f526a4d8 100644 --- a/ipie/walkers/tests/test_multi_det_batch.py +++ b/ipie/walkers/tests/test_multi_det_batch.py @@ -220,16 +220,16 @@ def test_walker_energy(): greens_function_multi_det_wicks_opt( walkers_opt, trial_opt ) # compute green's function using Wick's theorem - e_wicks = local_energy_multi_det_trial_wicks_batch(ham, walkers0, trial) - e_wicks_opt = local_energy_multi_det_trial_wicks_batch_opt(ham, walkers_opt, trial_opt) + e_wicks = local_energy_multi_det_trial_wicks_batch(system, ham, walkers0, trial) + e_wicks_opt = local_energy_multi_det_trial_wicks_batch_opt(system, ham, walkers_opt, trial_opt) greens_function_multi_det(walkers, trial_slow) - e_simple = local_energy_multi_det_trial_batch(ham, walkers, trial_slow) + e_simple = local_energy_multi_det_trial_batch(system, ham, walkers, trial_slow) assert e_simple[:, 0] == pytest.approx(energies) assert e_wicks_opt[:, 0] == pytest.approx(e_wicks[:, 0]) assert e_wicks[:, 0] == pytest.approx(energies) - # e = local_energy_batch(ham, walkers, trial, iw=0) + # e = local_energy_batch(system, ham, walkers, trial, iw=0) # assert e[:,0] == pytest.approx(energies[0]) From 13e09781f58107e2171f3f0a3cb7f4fb94f6d77e Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Fri, 8 Mar 2024 18:07:07 -0500 Subject: [PATCH 51/84] Moved `ipie.thermal` to `ipie.addons.thermal` --- ipie/{ => addons}/thermal/__init__.py | 0 .../thermal/estimators/__init__.py | 0 .../{ => addons}/thermal/estimators/energy.py | 6 +- .../thermal/estimators/generic.py | 0 .../thermal/estimators/greens_function.py | 0 .../thermal/estimators/handler.py | 4 +- .../thermal/estimators/local_energy.py | 6 +- .../thermal/estimators/particle_number.py | 2 +- .../estimators/tests/test_estimators.py | 6 +- .../thermal/estimators/tests/test_generic.py | 8 +- .../estimators/tests/test_generic_complex.py | 6 +- .../thermal/estimators/thermal.py | 0 .../thermal/propagation/__init__.py | 0 .../thermal/propagation/force_bias.py | 2 +- .../thermal/propagation/operations.py | 0 .../thermal/propagation/phaseless_base.py | 6 +- .../thermal/propagation/phaseless_generic.py | 6 +- .../thermal/propagation/propagator.py | 2 +- .../propagation/tests/test_operations.py | 8 +- .../propagation/tests/test_prop_generic.py | 10 +- .../propagation/tests/ueg/test_prop_ueg.py | 10 +- .../propagation/tests/ueg/test_ueg_0T.py | 0 .../thermal/propagation/tests/ueg/ueg.py | 0 ipie/{ => addons}/thermal/qmc/__init__.py | 0 ipie/{ => addons}/thermal/qmc/options.py | 0 .../thermal/qmc/tests/run_legacy.py | 0 .../thermal/qmc/tests/test_afqmc_generic.py | 4 +- .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 8 +- .../{ => addons}/thermal/qmc/thermal_afqmc.py | 8 +- .../thermal}/reference_data/ueg/note | 0 ipie/{ => addons}/thermal/trial/__init__.py | 0 ipie/{ => addons}/thermal/trial/chem_pot.py | 2 +- ipie/{ => addons}/thermal/trial/mean_field.py | 10 +- ipie/{ => addons}/thermal/trial/one_body.py | 6 +- .../thermal/trial/tests/test_chem_pot.py | 2 +- .../thermal/trial/tests/test_mean_field.py | 7 +- .../thermal/trial/tests/test_one_body.py | 7 +- ipie/{ => addons}/thermal/trial/utils.py | 4 +- .../thermal/utils/legacy_testing.py | 0 ipie/{ => addons}/thermal/utils/testing.py | 14 +- ipie/{ => addons}/thermal/utils/ueg.py | 0 ipie/{ => addons}/thermal/walkers/__init__.py | 0 ipie/{ => addons}/thermal/walkers/stack.py | 0 .../walkers/tests/test_population_control.py | 6 +- .../walkers/tests/test_thermal_walkers.py | 10 +- .../thermal/walkers/uhf_walkers.py | 8 +- ipie/thermal/qmc/tests/test_run.py | 147 -------------- ipie/thermal/tests/__init__.py | 16 -- .../ft_4x4_hubbard_discrete/input.json | 32 ---- .../ft_4x4_hubbard_discrete/reference.json | 1 - .../reference_1walker.json | 1 - .../reference_nompi.json | 1 - .../ft_ueg_ecut1.0_rs1.0/input.json | 32 ---- .../ft_ueg_ecut1.0_rs1.0/input_1walker.json | 32 ---- .../ft_ueg_ecut1.0_rs1.0/reference.json | 1 - .../reference_1walker.json | 1 - .../ft_ueg_ecut1.0_rs1.0/reference_nompi.json | 1 - .../tests/reference_data/generic_integrals.h5 | Bin 30056 -> 0 bytes .../tests/reference_data/generic_ref.json | 1 - ipie/thermal/tests/test_ft_integration.py | 113 ----------- ipie/thermal/tests/test_generic.py | 181 ------------------ ipie/walkers/pop_controller.py | 2 +- 62 files changed, 91 insertions(+), 649 deletions(-) rename ipie/{ => addons}/thermal/__init__.py (100%) rename ipie/{ => addons}/thermal/estimators/__init__.py (100%) rename ipie/{ => addons}/thermal/estimators/energy.py (93%) rename ipie/{ => addons}/thermal/estimators/generic.py (100%) rename ipie/{ => addons}/thermal/estimators/greens_function.py (100%) rename ipie/{ => addons}/thermal/estimators/handler.py (98%) rename ipie/{ => addons}/thermal/estimators/local_energy.py (92%) rename ipie/{ => addons}/thermal/estimators/particle_number.py (96%) rename ipie/{ => addons}/thermal/estimators/tests/test_estimators.py (93%) rename ipie/{ => addons}/thermal/estimators/tests/test_generic.py (91%) rename ipie/{ => addons}/thermal/estimators/tests/test_generic_complex.py (96%) rename ipie/{ => addons}/thermal/estimators/thermal.py (100%) rename ipie/{ => addons}/thermal/propagation/__init__.py (100%) rename ipie/{ => addons}/thermal/propagation/force_bias.py (95%) rename ipie/{ => addons}/thermal/propagation/operations.py (100%) rename ipie/{ => addons}/thermal/propagation/phaseless_base.py (98%) rename ipie/{ => addons}/thermal/propagation/phaseless_generic.py (87%) rename ipie/{ => addons}/thermal/propagation/propagator.py (67%) rename ipie/{ => addons}/thermal/propagation/tests/test_operations.py (91%) rename ipie/{ => addons}/thermal/propagation/tests/test_prop_generic.py (95%) rename ipie/{ => addons}/thermal/propagation/tests/ueg/test_prop_ueg.py (93%) rename ipie/{ => addons}/thermal/propagation/tests/ueg/test_ueg_0T.py (100%) rename ipie/{ => addons}/thermal/propagation/tests/ueg/ueg.py (100%) rename ipie/{ => addons}/thermal/qmc/__init__.py (100%) rename ipie/{ => addons}/thermal/qmc/options.py (100%) rename ipie/{ => addons}/thermal/qmc/tests/run_legacy.py (100%) rename ipie/{ => addons}/thermal/qmc/tests/test_afqmc_generic.py (97%) rename ipie/{ => addons}/thermal/qmc/tests/ueg/test_afqmc_ueg.py (98%) rename ipie/{ => addons}/thermal/qmc/thermal_afqmc.py (98%) rename ipie/{thermal/qmc/tests => addons/thermal}/reference_data/ueg/note (100%) rename ipie/{ => addons}/thermal/trial/__init__.py (100%) rename ipie/{ => addons}/thermal/trial/chem_pot.py (96%) rename ipie/{ => addons}/thermal/trial/mean_field.py (90%) rename ipie/{ => addons}/thermal/trial/one_body.py (94%) rename ipie/{ => addons}/thermal/trial/tests/test_chem_pot.py (91%) rename ipie/{ => addons}/thermal/trial/tests/test_mean_field.py (88%) rename ipie/{ => addons}/thermal/trial/tests/test_one_body.py (88%) rename ipie/{ => addons}/thermal/trial/utils.py (90%) rename ipie/{ => addons}/thermal/utils/legacy_testing.py (100%) rename ipie/{ => addons}/thermal/utils/testing.py (96%) rename ipie/{ => addons}/thermal/utils/ueg.py (100%) rename ipie/{ => addons}/thermal/walkers/__init__.py (100%) rename ipie/{ => addons}/thermal/walkers/stack.py (100%) rename ipie/{ => addons}/thermal/walkers/tests/test_population_control.py (98%) rename ipie/{ => addons}/thermal/walkers/tests/test_thermal_walkers.py (95%) rename ipie/{ => addons}/thermal/walkers/uhf_walkers.py (94%) delete mode 100644 ipie/thermal/qmc/tests/test_run.py delete mode 100644 ipie/thermal/tests/__init__.py delete mode 100644 ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/input.json delete mode 100644 ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference.json delete mode 100644 ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_1walker.json delete mode 100644 ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json delete mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json delete mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input_1walker.json delete mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json delete mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_1walker.json delete mode 100644 ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json delete mode 100644 ipie/thermal/tests/reference_data/generic_integrals.h5 delete mode 100644 ipie/thermal/tests/reference_data/generic_ref.json delete mode 100644 ipie/thermal/tests/test_ft_integration.py delete mode 100644 ipie/thermal/tests/test_generic.py diff --git a/ipie/thermal/__init__.py b/ipie/addons/thermal/__init__.py similarity index 100% rename from ipie/thermal/__init__.py rename to ipie/addons/thermal/__init__.py diff --git a/ipie/thermal/estimators/__init__.py b/ipie/addons/thermal/estimators/__init__.py similarity index 100% rename from ipie/thermal/estimators/__init__.py rename to ipie/addons/thermal/estimators/__init__.py diff --git a/ipie/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py similarity index 93% rename from ipie/thermal/estimators/energy.py rename to ipie/addons/thermal/estimators/energy.py index 99db8b03..f449ebbf 100644 --- a/ipie/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -22,9 +22,9 @@ from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol from ipie.estimators.estimator_base import EstimatorBase -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.estimators.thermal import one_rdm_from_G -from ipie.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky def local_energy( diff --git a/ipie/thermal/estimators/generic.py b/ipie/addons/thermal/estimators/generic.py similarity index 100% rename from ipie/thermal/estimators/generic.py rename to ipie/addons/thermal/estimators/generic.py diff --git a/ipie/thermal/estimators/greens_function.py b/ipie/addons/thermal/estimators/greens_function.py similarity index 100% rename from ipie/thermal/estimators/greens_function.py rename to ipie/addons/thermal/estimators/greens_function.py diff --git a/ipie/thermal/estimators/handler.py b/ipie/addons/thermal/estimators/handler.py similarity index 98% rename from ipie/thermal/estimators/handler.py rename to ipie/addons/thermal/estimators/handler.py index f1b57410..3b1bb4c8 100644 --- a/ipie/thermal/estimators/handler.py +++ b/ipie/addons/thermal/estimators/handler.py @@ -9,8 +9,8 @@ import numpy from ipie.config import config, MPI -from ipie.thermal.estimators.energy import ThermalEnergyEstimator -from ipie.thermal.estimators.particle_number import ThermalNumberEstimator +from ipie.addons.thermal.estimators.energy import ThermalEnergyEstimator +from ipie.addons.thermal.estimators.particle_number import ThermalNumberEstimator from ipie.estimators.estimator_base import EstimatorBase from ipie.estimators.utils import H5EstimatorHelper from ipie.utils.io import format_fixed_width_strings diff --git a/ipie/thermal/estimators/local_energy.py b/ipie/addons/thermal/estimators/local_energy.py similarity index 92% rename from ipie/thermal/estimators/local_energy.py rename to ipie/addons/thermal/estimators/local_energy.py index c97cac24..7c4a478f 100644 --- a/ipie/thermal/estimators/local_energy.py +++ b/ipie/addons/thermal/estimators/local_energy.py @@ -1,11 +1,11 @@ -from ipie.thermal.estimators.generic import local_energy_generic_opt -from ipie.thermal.estimators.generic import ( +from ipie.addons.thermal.estimators.generic import local_energy_generic_opt +from ipie.addons.thermal.estimators.generic import ( local_energy_generic_cholesky, local_energy_generic_cholesky_opt, local_energy_generic_cholesky_opt_stochastic, local_energy_generic_pno, ) -from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G def local_energy_G(hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): diff --git a/ipie/thermal/estimators/particle_number.py b/ipie/addons/thermal/estimators/particle_number.py similarity index 96% rename from ipie/thermal/estimators/particle_number.py rename to ipie/addons/thermal/estimators/particle_number.py index f246d830..ef8b0829 100644 --- a/ipie/thermal/estimators/particle_number.py +++ b/ipie/addons/thermal/estimators/particle_number.py @@ -4,7 +4,7 @@ from ipie.utils.backend import arraylib as xp from ipie.estimators.estimator_base import EstimatorBase -from ipie.thermal.estimators.thermal import particle_number, one_rdm_from_G +from ipie.addons.thermal.estimators.thermal import particle_number, one_rdm_from_G class ThermalNumberEstimator(EstimatorBase): diff --git a/ipie/thermal/estimators/tests/test_estimators.py b/ipie/addons/thermal/estimators/tests/test_estimators.py similarity index 93% rename from ipie/thermal/estimators/tests/test_estimators.py rename to ipie/addons/thermal/estimators/tests/test_estimators.py index 5d450109..2af752b6 100644 --- a/ipie/thermal/estimators/tests/test_estimators.py +++ b/ipie/addons/thermal/estimators/tests/test_estimators.py @@ -4,9 +4,9 @@ from typing import Tuple, Union from ipie.config import MPI -from ipie.thermal.estimators.energy import ThermalEnergyEstimator -from ipie.thermal.estimators.handler import ThermalEstimatorHandler -from ipie.thermal.utils.testing import build_generic_test_case_handlers +from ipie.addons.thermal.estimators.energy import ThermalEnergyEstimator +from ipie.addons.thermal.estimators.handler import ThermalEstimatorHandler +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers # System params. nup = 5 diff --git a/ipie/thermal/estimators/tests/test_generic.py b/ipie/addons/thermal/estimators/tests/test_generic.py similarity index 91% rename from ipie/thermal/estimators/tests/test_generic.py rename to ipie/addons/thermal/estimators/tests/test_generic.py index 827f961a..9e7741ae 100644 --- a/ipie/thermal/estimators/tests/test_generic.py +++ b/ipie/addons/thermal/estimators/tests/test_generic.py @@ -3,14 +3,14 @@ from typing import Tuple, Union from ipie.config import MPI -from ipie.thermal.estimators.thermal import one_rdm_from_G -from ipie.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky -from ipie.thermal.utils.testing import build_generic_test_case_handlers -from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers comm = MPI.COMM_WORLD diff --git a/ipie/thermal/estimators/tests/test_generic_complex.py b/ipie/addons/thermal/estimators/tests/test_generic_complex.py similarity index 96% rename from ipie/thermal/estimators/tests/test_generic_complex.py rename to ipie/addons/thermal/estimators/tests/test_generic_complex.py index 2e2e859a..d78f8d1d 100644 --- a/ipie/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/addons/thermal/estimators/tests/test_generic_complex.py @@ -8,9 +8,9 @@ from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.estimators.energy import local_energy -from ipie.thermal.utils.testing import build_generic_test_case_handlers -from ipie.thermal.estimators.generic import local_energy_generic_cholesky -from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers +from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G # System params. nup = 5 diff --git a/ipie/thermal/estimators/thermal.py b/ipie/addons/thermal/estimators/thermal.py similarity index 100% rename from ipie/thermal/estimators/thermal.py rename to ipie/addons/thermal/estimators/thermal.py diff --git a/ipie/thermal/propagation/__init__.py b/ipie/addons/thermal/propagation/__init__.py similarity index 100% rename from ipie/thermal/propagation/__init__.py rename to ipie/addons/thermal/propagation/__init__.py diff --git a/ipie/thermal/propagation/force_bias.py b/ipie/addons/thermal/propagation/force_bias.py similarity index 95% rename from ipie/thermal/propagation/force_bias.py rename to ipie/addons/thermal/propagation/force_bias.py index 69cbdd9f..af8a0c00 100644 --- a/ipie/thermal/propagation/force_bias.py +++ b/ipie/addons/thermal/propagation/force_bias.py @@ -2,7 +2,7 @@ import numpy from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol -from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.utils.backend import arraylib as xp from ipie.utils.backend import synchronize diff --git a/ipie/thermal/propagation/operations.py b/ipie/addons/thermal/propagation/operations.py similarity index 100% rename from ipie/thermal/propagation/operations.py rename to ipie/addons/thermal/propagation/operations.py diff --git a/ipie/thermal/propagation/phaseless_base.py b/ipie/addons/thermal/propagation/phaseless_base.py similarity index 98% rename from ipie/thermal/propagation/phaseless_base.py rename to ipie/addons/thermal/propagation/phaseless_base.py index 9b80229f..54c63ace 100644 --- a/ipie/thermal/propagation/phaseless_base.py +++ b/ipie/addons/thermal/propagation/phaseless_base.py @@ -7,9 +7,9 @@ from abc import abstractmethod from ipie.propagation.continuous_base import ContinuousBase -from ipie.thermal.estimators.thermal import one_rdm_from_G -from ipie.thermal.propagation.force_bias import construct_force_bias -from ipie.thermal.propagation.operations import apply_exponential +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.propagation.force_bias import construct_force_bias +from ipie.addons.thermal.propagation.operations import apply_exponential from ipie.utils.backend import arraylib as xp from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol diff --git a/ipie/thermal/propagation/phaseless_generic.py b/ipie/addons/thermal/propagation/phaseless_generic.py similarity index 87% rename from ipie/thermal/propagation/phaseless_generic.py rename to ipie/addons/thermal/propagation/phaseless_generic.py index b602b23a..2f2eb40b 100644 --- a/ipie/thermal/propagation/phaseless_generic.py +++ b/ipie/addons/thermal/propagation/phaseless_generic.py @@ -6,11 +6,11 @@ from ipie.config import config from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol from ipie.hamiltonians.generic_base import GenericBase -from ipie.thermal.propagation.operations import apply_exponential -from ipie.thermal.propagation.phaseless_base import PhaselessBase +from ipie.addons.thermal.propagation.operations import apply_exponential +from ipie.addons.thermal.propagation.phaseless_base import PhaselessBase from ipie.utils.backend import arraylib as xp from ipie.utils.backend import synchronize -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers class PhaselessGeneric(PhaselessBase): diff --git a/ipie/thermal/propagation/propagator.py b/ipie/addons/thermal/propagation/propagator.py similarity index 67% rename from ipie/thermal/propagation/propagator.py rename to ipie/addons/thermal/propagation/propagator.py index 298b2190..80836ee5 100644 --- a/ipie/thermal/propagation/propagator.py +++ b/ipie/addons/thermal/propagation/propagator.py @@ -1,4 +1,4 @@ from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.addons.thermal.propagation.phaseless_generic import PhaselessGeneric Propagator = {GenericRealChol: PhaselessGeneric, GenericComplexChol: PhaselessGeneric} diff --git a/ipie/thermal/propagation/tests/test_operations.py b/ipie/addons/thermal/propagation/tests/test_operations.py similarity index 91% rename from ipie/thermal/propagation/tests/test_operations.py rename to ipie/addons/thermal/propagation/tests/test_operations.py index f9fda82c..86b3e039 100644 --- a/ipie/thermal/propagation/tests/test_operations.py +++ b/ipie/addons/thermal/propagation/tests/test_operations.py @@ -2,10 +2,10 @@ import pytest from ipie.config import MPI -from ipie.thermal.propagation.operations import apply_exponential -from ipie.thermal.utils.testing import build_generic_test_case_handlers -from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers -from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers +from ipie.addons.thermal.propagation.operations import apply_exponential +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers comm = MPI.COMM_WORLD diff --git a/ipie/thermal/propagation/tests/test_prop_generic.py b/ipie/addons/thermal/propagation/tests/test_prop_generic.py similarity index 95% rename from ipie/thermal/propagation/tests/test_prop_generic.py rename to ipie/addons/thermal/propagation/tests/test_prop_generic.py index f11d319e..8fc6bf23 100644 --- a/ipie/thermal/propagation/tests/test_prop_generic.py +++ b/ipie/addons/thermal/propagation/tests/test_prop_generic.py @@ -2,15 +2,15 @@ import pytest from ipie.config import MPI -from ipie.thermal.estimators.generic import local_energy_generic_cholesky -from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.thermal.utils.testing import build_generic_test_case_handlers -from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers -from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers comm = MPI.COMM_WORLD diff --git a/ipie/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py similarity index 93% rename from ipie/thermal/propagation/tests/ueg/test_prop_ueg.py rename to ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index 1e0156a8..fd460553 100644 --- a/ipie/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -2,15 +2,15 @@ import numpy from ipie.config import MPI -from ipie.thermal.estimators.generic import local_energy_generic_cholesky -from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.thermal.utils.testing import build_ueg_test_case_handlers -from ipie.thermal.utils.legacy_testing import build_legacy_ueg_test_case_handlers -from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers +from ipie.addons.thermal.utils.testing import build_ueg_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import build_legacy_ueg_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers comm = MPI.COMM_WORLD diff --git a/ipie/thermal/propagation/tests/ueg/test_ueg_0T.py b/ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py similarity index 100% rename from ipie/thermal/propagation/tests/ueg/test_ueg_0T.py rename to ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py diff --git a/ipie/thermal/propagation/tests/ueg/ueg.py b/ipie/addons/thermal/propagation/tests/ueg/ueg.py similarity index 100% rename from ipie/thermal/propagation/tests/ueg/ueg.py rename to ipie/addons/thermal/propagation/tests/ueg/ueg.py diff --git a/ipie/thermal/qmc/__init__.py b/ipie/addons/thermal/qmc/__init__.py similarity index 100% rename from ipie/thermal/qmc/__init__.py rename to ipie/addons/thermal/qmc/__init__.py diff --git a/ipie/thermal/qmc/options.py b/ipie/addons/thermal/qmc/options.py similarity index 100% rename from ipie/thermal/qmc/options.py rename to ipie/addons/thermal/qmc/options.py diff --git a/ipie/thermal/qmc/tests/run_legacy.py b/ipie/addons/thermal/qmc/tests/run_legacy.py similarity index 100% rename from ipie/thermal/qmc/tests/run_legacy.py rename to ipie/addons/thermal/qmc/tests/run_legacy.py diff --git a/ipie/thermal/qmc/tests/test_afqmc_generic.py b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py similarity index 97% rename from ipie/thermal/qmc/tests/test_afqmc_generic.py rename to ipie/addons/thermal/qmc/tests/test_afqmc_generic.py index 10c6608e..5ef7415f 100644 --- a/ipie/thermal/qmc/tests/test_afqmc_generic.py +++ b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py @@ -12,8 +12,8 @@ extract_data, extract_observable, extract_mixed_estimates) -from ipie.thermal.utils.testing import build_driver_generic_test_instance -from ipie.thermal.utils.legacy_testing import build_legacy_driver_generic_test_instance +from ipie.addons.thermal.utils.testing import build_driver_generic_test_instance +from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_generic_test_instance comm = MPI.COMM_WORLD diff --git a/ipie/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py similarity index 98% rename from ipie/thermal/qmc/tests/ueg/test_afqmc_ueg.py rename to ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index c5a33319..b577117f 100644 --- a/ipie/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -16,8 +16,8 @@ extract_data, extract_observable, extract_mixed_estimates) -from ipie.thermal.utils.testing import build_driver_ueg_test_instance -from ipie.thermal.utils.legacy_testing import build_legacy_driver_ueg_test_instance +from ipie.addons.thermal.utils.testing import build_driver_ueg_test_instance +from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_ueg_test_instance comm = MPI.COMM_WORLD @@ -223,7 +223,7 @@ def test_thermal_afqmc_1walker(against_ref=False): # --------------------------------------------------------------------- # Test against reference data. if against_ref: - _data_dir = os.path.abspath(os.path.dirname(__file__)).split("ueg")[0] + "/reference_data/" + _data_dir = os.path.abspath(os.path.dirname(__file__)).split("qmc")[0] + "/reference_data/" _legacy_test_dir = "ueg" _legacy_test = _data_dir + _legacy_test_dir + "/reference_1walker.json" @@ -456,5 +456,5 @@ def test_thermal_afqmc(against_ref=False): if __name__ == '__main__': test_thermal_afqmc_1walker(against_ref=False) - test_thermal_afqmc() + #test_thermal_afqmc() diff --git a/ipie/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py similarity index 98% rename from ipie/thermal/qmc/thermal_afqmc.py rename to ipie/addons/thermal/qmc/thermal_afqmc.py index 72a34749..1f6b515b 100644 --- a/ipie/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -5,10 +5,10 @@ import uuid from typing import Dict, Optional, Tuple -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.propagator import Propagator -from ipie.thermal.estimators.handler import ThermalEstimatorHandler -from ipie.thermal.qmc.options import ThermalQMCParams +from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.addons.thermal.propagation.propagator import Propagator +from ipie.addons.thermal.estimators.handler import ThermalEstimatorHandler +from ipie.addons.thermal.qmc.options import ThermalQMCParams from ipie.utils.io import to_json from ipie.utils.backend import arraylib as xp diff --git a/ipie/thermal/qmc/tests/reference_data/ueg/note b/ipie/addons/thermal/reference_data/ueg/note similarity index 100% rename from ipie/thermal/qmc/tests/reference_data/ueg/note rename to ipie/addons/thermal/reference_data/ueg/note diff --git a/ipie/thermal/trial/__init__.py b/ipie/addons/thermal/trial/__init__.py similarity index 100% rename from ipie/thermal/trial/__init__.py rename to ipie/addons/thermal/trial/__init__.py diff --git a/ipie/thermal/trial/chem_pot.py b/ipie/addons/thermal/trial/chem_pot.py similarity index 96% rename from ipie/thermal/trial/chem_pot.py rename to ipie/addons/thermal/trial/chem_pot.py index 8af3a870..37705edf 100644 --- a/ipie/thermal/trial/chem_pot.py +++ b/ipie/addons/thermal/trial/chem_pot.py @@ -1,6 +1,6 @@ import numpy -from ipie.thermal.estimators.thermal import one_rdm_stable, particle_number +from ipie.addons.thermal.estimators.thermal import one_rdm_stable, particle_number from ipie.utils.io import format_fixed_width_floats, format_fixed_width_strings diff --git a/ipie/thermal/trial/mean_field.py b/ipie/addons/thermal/trial/mean_field.py similarity index 90% rename from ipie/thermal/trial/mean_field.py rename to ipie/addons/thermal/trial/mean_field.py index f9d81076..7350a234 100644 --- a/ipie/thermal/trial/mean_field.py +++ b/ipie/addons/thermal/trial/mean_field.py @@ -1,11 +1,11 @@ import numpy import scipy.linalg -from ipie.thermal.estimators.generic import fock_generic -from ipie.thermal.estimators.greens_function import greens_function -from ipie.thermal.estimators.thermal import one_rdm_stable, particle_number -from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential -from ipie.thermal.trial.one_body import OneBody +from ipie.addons.thermal.estimators.generic import fock_generic +from ipie.addons.thermal.estimators.greens_function import greens_function +from ipie.addons.thermal.estimators.thermal import one_rdm_stable, particle_number +from ipie.addons.thermal.trial.chem_pot import compute_rho, find_chemical_potential +from ipie.addons.thermal.trial.one_body import OneBody class MeanField(OneBody): def __init__(self, hamiltonian, nelec, beta, dt, options={}, H1=None, verbose=False): diff --git a/ipie/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py similarity index 94% rename from ipie/thermal/trial/one_body.py rename to ipie/addons/thermal/trial/one_body.py index f57b48fa..d16f0dca 100644 --- a/ipie/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -2,9 +2,9 @@ import numpy import scipy.linalg -from ipie.thermal.estimators.greens_function import greens_function -from ipie.thermal.estimators.thermal import one_rdm_stable, particle_number -from ipie.thermal.trial.chem_pot import compute_rho, find_chemical_potential +from ipie.addons.thermal.estimators.greens_function import greens_function +from ipie.addons.thermal.estimators.thermal import one_rdm_stable, particle_number +from ipie.addons.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.utils.misc import update_stack diff --git a/ipie/thermal/trial/tests/test_chem_pot.py b/ipie/addons/thermal/trial/tests/test_chem_pot.py similarity index 91% rename from ipie/thermal/trial/tests/test_chem_pot.py rename to ipie/addons/thermal/trial/tests/test_chem_pot.py index 7bfc979d..e0c4c243 100644 --- a/ipie/thermal/trial/tests/test_chem_pot.py +++ b/ipie/addons/thermal/trial/tests/test_chem_pot.py @@ -2,7 +2,7 @@ import scipy.linalg import pytest -from ipie.thermal.trial.chem_pot import find_chemical_potential +from ipie.addons.thermal.trial.chem_pot import find_chemical_potential from ipie.legacy.trial_density_matrices.chem_pot import find_chemical_potential as legacy_find_chemical_potential diff --git a/ipie/thermal/trial/tests/test_mean_field.py b/ipie/addons/thermal/trial/tests/test_mean_field.py similarity index 88% rename from ipie/thermal/trial/tests/test_mean_field.py rename to ipie/addons/thermal/trial/tests/test_mean_field.py index 03e0a61e..843b81ac 100644 --- a/ipie/thermal/trial/tests/test_mean_field.py +++ b/ipie/addons/thermal/trial/tests/test_mean_field.py @@ -1,3 +1,4 @@ +import os import numpy import pytest @@ -5,7 +6,7 @@ from ipie.systems.generic import Generic from ipie.hamiltonians.utils import get_hamiltonian -from ipie.thermal.trial.mean_field import MeanField +from ipie.addons.thermal.trial.mean_field import MeanField def setup_objs(): @@ -20,11 +21,11 @@ def setup_objs(): verbose=5) mu = -10. - path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" + path = os.path.abspath(os.path.dirname(__file__)).split("trial")[0] + "/reference_data/generic/" options = { "hamiltonian": { "name": "Generic", - "integrals": path + "reference_data/generic_integrals.h5", + "integrals": path + "generic_integrals.h5", "_alt_convention": False, "symmetry": False, "sparse": False, diff --git a/ipie/thermal/trial/tests/test_one_body.py b/ipie/addons/thermal/trial/tests/test_one_body.py similarity index 88% rename from ipie/thermal/trial/tests/test_one_body.py rename to ipie/addons/thermal/trial/tests/test_one_body.py index 4ffc94c3..4c27f6d7 100644 --- a/ipie/thermal/trial/tests/test_one_body.py +++ b/ipie/addons/thermal/trial/tests/test_one_body.py @@ -1,3 +1,4 @@ +import os import numpy import pytest @@ -5,7 +6,7 @@ from ipie.systems.generic import Generic from ipie.hamiltonians.utils import get_hamiltonian -from ipie.thermal.trial.one_body import OneBody +from ipie.addons.thermal.trial.one_body import OneBody def setup_objs(): @@ -20,11 +21,11 @@ def setup_objs(): verbose=5) mu = -10. - path = "/Users/shufay/Documents/in_prep/ft_moire/ipie/ipie/thermal/tests/" + path = os.path.abspath(os.path.dirname(__file__)).split("trial")[0] + "/reference_data/generic/" options = { "hamiltonian": { "name": "Generic", - "integrals": path + "reference_data/generic_integrals.h5", + "integrals": path + "generic_integrals.h5", "_alt_convention": False, "symmetry": False, "sparse": False, diff --git a/ipie/thermal/trial/utils.py b/ipie/addons/thermal/trial/utils.py similarity index 90% rename from ipie/thermal/trial/utils.py rename to ipie/addons/thermal/trial/utils.py index 1b94697e..d9c47638 100644 --- a/ipie/thermal/trial/utils.py +++ b/ipie/addons/thermal/trial/utils.py @@ -1,5 +1,5 @@ -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody +from ipie.addons.thermal.trial.mean_field import MeanField +from ipie.addons.thermal.trial.one_body import OneBody def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, comm=None, verbose=False): diff --git a/ipie/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py similarity index 100% rename from ipie/thermal/utils/legacy_testing.py rename to ipie/addons/thermal/utils/legacy_testing.py diff --git a/ipie/thermal/utils/testing.py b/ipie/addons/thermal/utils/testing.py similarity index 96% rename from ipie/thermal/utils/testing.py rename to ipie/addons/thermal/utils/testing.py index d328e805..8bda8eff 100644 --- a/ipie/thermal/utils/testing.py +++ b/ipie/addons/thermal/utils/testing.py @@ -8,13 +8,13 @@ from ipie.utils.testing import generate_hamiltonian from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.thermal.utils.ueg import UEG -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric -from ipie.thermal.qmc.options import ThermalQMCParams -from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC +from ipie.addons.thermal.utils.ueg import UEG +from ipie.addons.thermal.trial.one_body import OneBody +from ipie.addons.thermal.trial.mean_field import MeanField +from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.addons.thermal.propagation.phaseless_generic import PhaselessGeneric +from ipie.addons.thermal.qmc.options import ThermalQMCParams +from ipie.addons.thermal.qmc.thermal_afqmc import ThermalAFQMC def build_generic_test_case_handlers(options: dict, diff --git a/ipie/thermal/utils/ueg.py b/ipie/addons/thermal/utils/ueg.py similarity index 100% rename from ipie/thermal/utils/ueg.py rename to ipie/addons/thermal/utils/ueg.py diff --git a/ipie/thermal/walkers/__init__.py b/ipie/addons/thermal/walkers/__init__.py similarity index 100% rename from ipie/thermal/walkers/__init__.py rename to ipie/addons/thermal/walkers/__init__.py diff --git a/ipie/thermal/walkers/stack.py b/ipie/addons/thermal/walkers/stack.py similarity index 100% rename from ipie/thermal/walkers/stack.py rename to ipie/addons/thermal/walkers/stack.py diff --git a/ipie/thermal/walkers/tests/test_population_control.py b/ipie/addons/thermal/walkers/tests/test_population_control.py similarity index 98% rename from ipie/thermal/walkers/tests/test_population_control.py rename to ipie/addons/thermal/walkers/tests/test_population_control.py index de3bc84b..94217b21 100644 --- a/ipie/thermal/walkers/tests/test_population_control.py +++ b/ipie/addons/thermal/walkers/tests/test_population_control.py @@ -6,9 +6,9 @@ from ipie.utils.mpi import MPIHandler from ipie.walkers.pop_controller import PopController -from ipie.thermal.utils.testing import build_generic_test_case_handlers_mpi -from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers_mpi -from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers_mpi +from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers_mpi +from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers comm = MPI.COMM_WORLD diff --git a/ipie/thermal/walkers/tests/test_thermal_walkers.py b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py similarity index 95% rename from ipie/thermal/walkers/tests/test_thermal_walkers.py rename to ipie/addons/thermal/walkers/tests/test_thermal_walkers.py index eb8c47f5..36ac5952 100644 --- a/ipie/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py @@ -3,15 +3,15 @@ from typing import Union from ipie.config import MPI -from ipie.thermal.estimators.generic import local_energy_generic_cholesky -from ipie.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.thermal.utils.testing import build_generic_test_case_handlers -from ipie.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers -from ipie.thermal.utils.legacy_testing import legacy_propagate_walkers +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers +from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers comm = MPI.COMM_WORLD diff --git a/ipie/thermal/walkers/uhf_walkers.py b/ipie/addons/thermal/walkers/uhf_walkers.py similarity index 94% rename from ipie/thermal/walkers/uhf_walkers.py rename to ipie/addons/thermal/walkers/uhf_walkers.py index 7eeedc9a..640a8eaf 100644 --- a/ipie/thermal/walkers/uhf_walkers.py +++ b/ipie/addons/thermal/walkers/uhf_walkers.py @@ -1,12 +1,12 @@ import numpy import scipy.linalg -from ipie.thermal.estimators.thermal import one_rdm_from_G, particle_number -from ipie.thermal.estimators.greens_function import greens_function_qr_strat -from ipie.thermal.walkers.stack import PropagatorStack +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G, particle_number +from ipie.addons.thermal.estimators.greens_function import greens_function_qr_strat +from ipie.addons.thermal.walkers.stack import PropagatorStack from ipie.utils.misc import get_numeric_names, update_stack from ipie.walkers.base_walkers import BaseWalkers -from ipie.thermal.trial.one_body import OneBody +from ipie.addons.thermal.trial.one_body import OneBody class UHFThermalWalkers(BaseWalkers): def __init__( diff --git a/ipie/thermal/qmc/tests/test_run.py b/ipie/thermal/qmc/tests/test_run.py deleted file mode 100644 index 6f1b3640..00000000 --- a/ipie/thermal/qmc/tests/test_run.py +++ /dev/null @@ -1,147 +0,0 @@ -# Copyright 2022 The ipie Developers. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Authors: Fionn Malone -# Joonho Lee -# - -import os -import sys -import tempfile -import uuid -import json -import h5py -import numpy - -from pyscf import gto, scf, lo -from ipie.config import MPI -from ipie.systems.generic import Generic -from ipie.hamiltonians.utils import get_hamiltonian - -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric -from ipie.thermal.qmc.options import ThermalQMCParams -from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC -from ipie.thermal.estimators.energy import local_energy -from ipie.analysis.extraction import extract_test_data_hdf5, extract_observable - -comm = MPI.COMM_WORLD -serial_test = comm.size == 1 - -# Unique filename to avoid name collision when running through CI. -if comm.rank == 0: - test_id = str(uuid.uuid1()) - -else: - test_id = None - -test_id = comm.bcast(test_id, root=0) - - -def test_thermal_afqmc(): - ref_path = "reference_data/generic/" - - # Build `mol` object. - nocca = 5 - noccb = 5 - nelec = nocca + noccb - r0 = 1.75 - mol = gto.M( - atom=[("H", i * r0, 0, 0) for i in range(nelec)], - basis='sto-6g', - unit='Bohr', - verbose=5) - - # Build `scf` object. - mf = scf.UHF(mol).run() - mf.chkfile = 'scf.chk' - mo1 = mf.stability()[0] - dm1 = mf.make_rdm1(mo1, mf.mo_occ) - mf = mf.run(dm1) - mf.stability(return_status=True) - s1e = mol.intor("int1e_ovlp_sph") - ao_coeff = lo.orth.lowdin(s1e) - - with h5py.File(ref_path + "generic_integrals.h5", "r") as fa: - Lxmn = fa["LXmn"][:] - nchol = Lxmn.shape[0] - nbasis = Lxmn.shape[1] - - # Thermal AFQMC params. - mu = -10.0 - beta = 0.1 - timestep = 0.01 - nwalkers = 2 - seed = 7 - nsteps_per_block = 1 - nblocks = 10 - stabilize_freq = 10 - pop_control_freq = 1 - lowrank = False - verbose = True - - params = ThermalQMCParams( - num_walkers=nwalkers, - total_num_walkers=nwalkers * comm.size, - num_blocks=nblocks, - num_steps_per_block=nsteps_per_block, - timestep=timestep, - beta=beta, - num_stblz=stabilize_freq, - pop_control_freq=pop_control_freq, - rng_seed=seed) - - options = { - "hamiltonian": { - "name": "Generic", - "integrals": ref_path + "generic_integrals.h5", - "_alt_convention": False, - "symmetry": False, - "sparse": False, - "mu": mu - }, - } - - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - - system = Generic(mol.nelec, verbose=verbose) - hamiltonian = get_hamiltonian(system, options["hamiltonian"]) - trial = MeanField(hamiltonian, mol.nelec, beta, timestep, verbose=verbose) - - nbasis = trial.dmat.shape[-1] - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) - propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) - propagator.build(hamiltonian, trial=trial, walkers=walkers, verbose=verbose) - - eloc = local_energy(hamiltonian, walkers) - print(f'# Initial energy = {eloc[0]}') - - afqmc = ThermalAFQMC(system, hamiltonian, trial, walkers, propagator, params, verbose) - afqmc.run(walkers, verbose) - afqmc.finalise() - afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) - #numer_batch = afqmc.estimators["energy"]["ENumer"] - #denom_batch = afqmc.estimators["energy"]["EDenom"] - data_batch = extract_observable(afqmc.estimators.filename, "energy") - print(data_batch) - - -if __name__ == '__main__': - test_thermal_afqmc() - diff --git a/ipie/thermal/tests/__init__.py b/ipie/thermal/tests/__init__.py deleted file mode 100644 index 32298b95..00000000 --- a/ipie/thermal/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright 2022 The ipie Developers. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Author: Joonho Lee -# diff --git a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/input.json b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/input.json deleted file mode 100644 index 5e6ab9ef..00000000 --- a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/input.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "system": { - "name": "Hubbard", - "nx": 4, - "ny": 4, - "nup": 7, - "ndown": 7, - "mu": 0.1, - "U": 4 - }, - "qmc": { - "dt": 0.01, - "nwalkers": 1, - "blocks": 10, - "nsteps": 10, - "rng_seed": 7, - "beta": 0.25, - "pop_control_freq": 5, - "stabilise_freq": 10, - "batched": false - }, - "trial": { - "name": "one_body" - }, - "walkers": { - "pop_control": "comb" - }, - "propagator": { - "hubbard_stratonovich": "discrete" - }, - "estimators": {} -} diff --git a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference.json b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference.json deleted file mode 100644 index 904b376c..00000000 --- a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [32.0, 44.98447572409485], "Weight": [32.0, 42.93486118721573], "ENumer": [152.0047418107582, 24.59220437157029], "EDenom": [32.0, 42.93486118721573], "ETotal": [4.7501481815861935, 0.5727794079579522], "E1Body": [-7.499853241434115, -7.179410491868211], "E2Body": [12.250001423020308, 7.752189899826164], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154433, 13.205553548235017], "sys_info": {"nranks": 4, "branch": "develop", "sha1": "5de52c915d59fc1e026bb3b42812f6daa4d1010b", "numpy": {"version": "1.18.4", "path": "/usr/local/lib/python3.7/site-packages/numpy", "BLAS": {"lib": "openblas openblas", "path": "/usr/local/lib"}}, "scipy": {"version": "1.4.1", "path": "/usr/local/lib/python3.7/site-packages/scipy"}, "h5py": {"version": "2.10.0", "path": "/usr/local/lib/python3.7/site-packages/h5py"}, "mpi4py": {"version": "3.0.1", "path": "/usr/local/lib/python3.7/site-packages/mpi4py", "mpicc": "/usr/local/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_1walker.json b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_1walker.json deleted file mode 100644 index 11509601..00000000 --- a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_1walker.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [1.0, 1.0], "Weight": [1.0, 0.1], "ENumer": [4.750148181586211, 0.004372991515192037], "EDenom": [1.0, 0.1], "ETotal": [4.750148181586211, 0.04372991515192037], "E1Body": [-7.499853241434114, -7.797076838398823], "E2Body": [12.250001423020326, 7.840806753550744], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154449, 13.195457786831575], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "3e25fb5948014be236679907b176cb8087863e3e-dirty", "numpy": {"version": "1.24.4", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json b/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json deleted file mode 100644 index 0fbf7b3e..00000000 --- a/ipie/thermal/tests/reference_data/ft_4x4_hubbard_discrete/reference_nompi.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [32.0, 44.98645457011622], "Weight": [32.0, 43.034282083027925], "ENumer": [152.0047418107588, 20.184762894579933], "EDenom": [32.0, 43.034282083027925], "ETotal": [4.750148181586212, 0.4690391454802612], "E1Body": [-7.499853241434117, -7.214851781729806], "E2Body": [12.250001423020322, 7.683890927210067], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154442, 13.233641168838517], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "a67b7598397a8e99b75d50bc67fd18ec2ee20b76-dirty", "numpy": {"version": "1.24.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}, "mpi4py": {"version": "3.1.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/mpi4py", "mpicc": "/sw/spack/delta-2022-03/apps/openmpi/4.1.4-gcc-11.2.0-7ooytax/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json deleted file mode 100644 index 65f888c9..00000000 --- a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "system": { - "name": "UEG", - "nup": 7, - "ndown": 7, - "rs": 1.0, - "mu": -1.0, - "ecut": 1.0 - }, - "qmc": { - "dt": 0.01, - "nwalkers": 32, - "blocks": 10, - "nsteps": 10, - "beta": 0.1, - "rng_seed": 7, - "pop_control_freq": 1, - "stabilise_freq": 10, - "batched": false - }, - "trial": { - "name": "one_body" - }, - "walkers": { - "population_control": "pair_branch" - }, - "estimators": { - "mixed": { - "one_rdm": true - } - } -} diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input_1walker.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input_1walker.json deleted file mode 100644 index 7f7aa195..00000000 --- a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input_1walker.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "system": { - "name": "UEG", - "nup": 7, - "ndown": 7, - "rs": 1.0, - "mu": -1.0, - "ecut": 1.0 - }, - "qmc": { - "dt": 0.01, - "nwalkers": 1, - "blocks": 10, - "nsteps": 10, - "beta": 0.1, - "rng_seed": 7, - "pop_control_freq": 1, - "stabilise_freq": 10, - "batched": false - }, - "trial": { - "name": "one_body" - }, - "walkers": { - "population_control": "pair_branch" - }, - "estimators": { - "mixed": { - "one_rdm": true - } - } -} diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json deleted file mode 100644 index c278179f..00000000 --- a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [32.0, 47.94831398616111], "Weight": [32.0, 31.999999999999996], "ENumer": [853.4128425513718, 986.7912119123343], "EDenom": [32.0, 31.999999999999996], "ETotal": [26.66915132973037, 30.837225372260455], "E1Body": [28.374994808285745, 33.21707786343164], "E2Body": [-1.705843478555375, -2.379852491171182], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209672, 16.375812925843057], "sys_info": {"nranks": 4, "branch": "hubbard_updates", "sha1": "618262bc7511a252e2f2bb3f23cc96fa4e8b9eb5", "numpy": {"version": "1.18.4", "path": "/usr/local/lib/python3.7/site-packages/numpy", "BLAS": {"lib": "openblas openblas", "path": "/usr/local/lib"}}, "scipy": {"version": "1.4.1", "path": "/usr/local/lib/python3.7/site-packages/scipy"}, "h5py": {"version": "2.10.0", "path": "/usr/local/lib/python3.7/site-packages/h5py"}, "mpi4py": {"version": "3.0.1", "path": "/usr/local/lib/python3.7/site-packages/mpi4py", "mpicc": "/usr/local/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_1walker.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_1walker.json deleted file mode 100644 index 46a6ca8f..00000000 --- a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_1walker.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [1.0, 1.0], "Weight": [1.0, 0.1], "ENumer": [26.669151329730372, 3.0880611634447632], "EDenom": [1.0, 0.1], "ETotal": [26.669151329730372, 30.880611634447632], "E1Body": [28.374994808285745, 33.2449965368494], "E2Body": [-1.7058434785553742, -2.364384902401771], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209672, 16.388846234869657], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "3e25fb5948014be236679907b176cb8087863e3e-dirty", "numpy": {"version": "1.24.4", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/Users/jiang/opt/anaconda3/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json b/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json deleted file mode 100644 index 553a1533..00000000 --- a/ipie/thermal/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference_nompi.json +++ /dev/null @@ -1 +0,0 @@ -{"WeightFactor": [32.0, 47.79071285048463], "Weight": [32.0, 31.999999999999996], "ENumer": [853.4128425513711, 986.9792326724249], "EDenom": [32.0, 31.999999999999996], "ETotal": [26.669151329730347, 30.843101021013286], "E1Body": [28.374994808285724, 33.221059734849845], "E2Body": [-1.7058434785553744, -2.3779587138365548], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209661, 16.377795476555466], "sys_info": {"nranks": 1, "branch": "ft_cleanup", "sha1": "a67b7598397a8e99b75d50bc67fd18ec2ee20b76-dirty", "numpy": {"version": "1.24.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/numpy", "BLAS": {"lib": "openblas64_ openblas64_", "path": "/usr/local/lib"}}, "scipy": {"version": "1.10.1", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/scipy"}, "h5py": {"version": "3.9.0", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/h5py"}, "mpi4py": {"version": "3.1.4", "path": "/u/tjiang1/.conda/envs/ipie_ftclean/lib/python3.8/site-packages/mpi4py", "mpicc": "/sw/spack/delta-2022-03/apps/openmpi/4.1.4-gcc-11.2.0-7ooytax/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/thermal/tests/reference_data/generic_integrals.h5 b/ipie/thermal/tests/reference_data/generic_integrals.h5 deleted file mode 100644 index cd0fa383c3589e3ac847d0d975ef0f1c73bbf214..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 30056 zcmeF32{4!K|L<+dQVPiu*_TRolI6baOCf7fWXTrF79|Olr9z<;?Z_TNWV}v_FmN=gKx}P(1{%6jA&YYPuXU?4S{ANPw)%*Q=f4+A;&-is+PfKSj0~Z6uKmX9t zQP5CqC*J+{n|1OZS3mSU|9<@MkK2*&P?B#W$+sC)=p9OmfBr{7!9jjMGs*vtpJ#5W ztxd7Wuel8^yBBB=#1;zj9E%nCb|MQv5 ze1HPot{R0LBZb^LHHxrl<9q-4aVjbVq$6J`)Rg3>Q}B_Wi9Vl#;=;f0{2zI1W^_c0 zl7jlbJ|!+}`p;wh`?`;${m(z|-`DkjZ2O=8tp9s|^uNC=beWVJ!~gS-09oxn-qru; z`~TPPjE@ohQfhAGFG;>}{ck_~-~7>k?*m-~vO%$NasR8YBRleUu75A=-y-+_edqt_ zw*{J~_HyHYVaZ#@Xe+yqF#g*5-Ii}f00tyavC7_q)BUA-4b6c-tl=4mNVJ1eQFl{{ z0yV)S&C?C_n?&K@sY=!W3Pz9|MZ4%fK8yd$dEU^vOSgxz>hjgCR};EAVV>EWTu!kP zVBP6CN zZztKSoXo>da{5Aw0xC3Vs=}@EUyn3&LiNjcyFwL9K-{gfmptneVKm7d>mc(ULmt{l zKT2e;Kr&Ad$>}`nzWaJAO_hbPN2)nuMQ{j&`^*3ijba5Nk403FC#L~ zzno!`n@avV0j$VF^atcOW*Y6LMD8_7dVWauh$4GkAoJWOId!B54$_O3Iod7hBD#lk za`!LfUO}X1ACh~U>}5yh`FE#PayK1vM+0)#QSyGilDqF9_ZlEQ8<2i{$X*zk$B^V? zlXq4@-fu2>hkoS!u#vmZkbC{>`5NixG1<$A%=2G484d+ucv= zZ!n6NbKAr1pW)02h?C!SpW5T<2%rEBI|6>k!n2IEm{)&mahVp> ztB}k?L2@3~nfE&0e+TMM&>YjaZwF)d{0^7a0pMIv;>*AH#bEDh&N0^CTYza{HEnms zJU*20z|MSc8^#)f{5&9g^*NzDK_tidz0qvzhdR`>`oC!v~<}Fbko@B&H`fQ(Ao>>m4 zco|!KspO!?1p8O%6&9f8i$yBOF5>#+?keP7sibGiHRNZPKkB73jq(`pMjXDvMkVW# z5}>vi>yv#-6jInZFho?BV@c%w6qCCTlY7mQp6ybQpM0_x-4x1m{|Dmy)VNVjQ&|Kk zFu5F!FPniRd53A_{j8F^pS*|m@?k}udrFa?DnHbVA_L{2&_bN60WS;ps}+D#;%iOJ z&K__o-9O2sRvW1LfB51P(2hG_jTljSu@!tAZ!s$Oo53|hoQ6#YpJ8kgn^&uBDlqG) z-8Ub_LcHv=N2mNiIo1|0(pN|I6qn0DoCmfqqt9wR1MT#|eJ2adf!OWns-z`x$b8NH zwJ=}+*cpdsS!XkGQRab@HLr$nc4dP@sb_~Vb9Py!-+u=1p~Nc+`=nQ$m5xRab?yln^MH-5hmSZ@rrexd-Q3Cc=iCxyOQ8Rh6vPY zRB|6P-~$XtSih9-PGk9~Mhz`85R)xoMFrP=6yV!!H`Hq~2j$UF zwE|bq)PPar*03SLFoo&rNya}(`8poI34B0c|Z zKz=yMUQ9<(oKVSjZ$oml@cc=JwFC*mHj`VYb z>@`B>IY4si>bk}Htw%sem`nj+h^{P6L@;q%o zoM%dNa}K+{g6q*sFV7iYgPY%ux@!x`gFeYT_&f9vurGda?&+7qus0jG^hlKfdJMKY zw6;4z;>yv?6Ey4iP~HGV*r!j}$tTZBByw^5MdI^Qvsn+Z;d;b*AQko|#iAT&;JV7X zcWR_){-;pKvS`@K;M>FE<9RJ0G5`IBO3QweR*wYimNP za}k3Jt9+ojYJz%~0wpy4Yq96vxj{^v>}5&jaUwZG(NaCi`oqA?^l-Xu%?)^Oj3#2U z-xYXKddHf%s6EImVc|`UKL|Ur*E32OIY24bFw<4TAGitWCxq;^^&HCMY=Sr{<-e;6 z=;pvlIyWWGEjM8&|F*%~bY_6fB}Y5W(j1=JRafJgbO89rtHD1jY|w=CoJIQaAbSOo zdF1F3$0>J-+2zJCILi0E=zdQu%&#cB+AQn={<<-53x8z-c~uXYrUyuY7;-N+(sKss z$A;|XAc*p4lbr8Tr-~}q+5tRkZ#|vi3v;bw_V#G&f~_fEC#6cn;g)=~yA!#W5a~Ib z^ixXq>L&ACBRTs|o^_GER||xy{tPGks)ERV?a7*ADG*NHk6<6#{VTaw7wNf;^uyqe zdM%tldGf0f$IjDVcRjoS%rU-sWFVvqa>+ZS`iAbujNCn&+-rpNY)tymBYW9>LV4^M z5Qmr6`{C1)OHi?7c;KtkNjRgnBVeje9cZ_z?EgE(2XiDYDsM^`10&Re!3@VXL6yq7 zQlDZPxRY=5$H!HxSS?fd;M~jz-m{J2o(^9LesuAY=Uwk)j8z?R>Q_{9Rh46b(mk`} zNEu6T*7mHwE`<)1z!e$XH3UF@hD6h+U1H$Lk`0gd#BP|Q@F<3#o(43rW8ooJda-lt zjK8g_Yw+*yQJ!Lw6VzVaQ=swyuzxpfDOhs>4ibHJj-J9m8x#h}RUL+GZ#Lh#{S5=D zyE3oOE%QS!KjU|J${+mvb_PmHj}gpI67@2+LwQn3&QCn^%F^EuKzX?@;mAFGFnV{q zWJjMXI3x7aDVoU|a@5xhy6*x&>kODV26ll_{#li_A}aWi^utT`YL!BH<^m8Ww!S%5 zBQzFTYQ1g9YIT8K<6~p%Iv#+a-WWQIG`M$Z~uBjoM{Bt ztRMi^*C`u()xHk9osEh;OHKp7sqdl!Qp&I_HOz)xd?(2NT_v0~_Y3d3>|;L4--$hb z@ipbw#RB|91j=K%hB)|#)9ZdIv!KK9mj;7i5VXz%mOJCsfv)lO(NR`AXwD;bOY*cP z(7xZJWg;a6Uk4mw`xLnuJeW&$m$jV0E684TWS&?f#Oc|YdB}KA4@fR*6bes^hIS3l zwfSBI0+!JaS9sO!;PFi(35?MIgqASq4%hR+>Fw59vmWah$64g(3)$<@OO)qd&SqJE zk%Qw8VN`DJHREbCIQXGue`bY#b~t?l}Wc^O~4p2iV^S<&3SUi%;oZy-HCCjFcw zd+j6hbY>yWa*^tnV{fj*BCjQ7`XfGI;N$SYKe_raKC7gAwn7Zlt(-bCuSW}ccc8s~ zke*#gKSLv^*Y5Wy&pvO&X}d8eMiR^@q;fnaX=N-KR0A2F;J7mE~}qfVOq-GTizCK&fy0i8Gi5ys$kc*(yU9hPW;q&mLq2LA|W@i=EwgCJ*wn zdoSw6`V-|*vqzlPgFE`CNAJV>xdXkKr*6T`gZ*x)T~^Saz98rFiWgw1eO2uISOZpS zXm1K+Vgp&EXED-G6WMDYndb({xm)NF%niH1QPx6BnHSUo@m zc|U@ZX!nogUa6$#{iGiQvX?!X=Ml;AR7<`S>Q@NYXbd)|`T2wS4s?ffN74O=$)Mf0 z_oKbUHIe5WdgMnu67_N>^ZeL^I5Vtzvz`GSpa%E8tUH_wFHHK}TT%@Ksb5k(&c2O? zSLi~ImTNkK6yLvRc8aUQlwF4HR?m3>Yr==$cTZ75S)=7$b>bt~W$LIj=a3p)PqQUr z^++=2FpW4#C#ds-cZ>u3@p9>-whln6o*}pM(FMSe(7&?+cY-`$%eJO%(gr_2F;&I} z3&Rsl`my2hbRe=U;qA5OGx$r(h}~_S4OkkPhjAEjIJ@8b%SmLy)vkfmtxVBSy?@4r zGR6~}4A6TQpRWn!lncwZ-sJ3Q-%>&)(czpUWy4si{(W7CV2Edsz21^}(nyXS zXU!NrTM^t|?5p`X{XF>fc<_3zpe5WE4fgUL1>l=S@hy3JUU=oT!sk1V>ljbRx30z4 z19&#+$C2zc(1-FEksMWn)R>np8-ETQNjzHq>=>Zy%{)G)ssNi)F?$!v?ZDne@?+qo zFL;L0srS;EO;|4J*@*Pxb^-O8d4lr%9z~o@JayV1{{(`<6ZX3YZ0GJaQate!FBECfEk zyI4jW+=01bMf+;4K4JRg?vKd5-nAmnb)=sWve$|b%9E&vI4=6z&-8qhh3|OMEZcX> z0=WR>I$jXoruWm#-NFv5eyLyP z;SdE6{v36D7gL3aSzkzS>Y2c<@AqAi2&=@0`zl+lP5N+8^DBILBaQg^OT$})3v=+r zh+ysn%?2#cGybrtYcjTP32`1;+>Yl9l7`IBzEoL+%7Xy@(`jC%bTB0ScJWfn1ZJ=l zR3-Lj1rxI>?kU5+Vx4qs*Tw+-bajl6!ProeFS9-?dIobw6nT>utE?bP%-VR%I>mNP;!5b*u7+ zOdzqfFu;C?^y-17(d;TJ`{@D-Ft_X6UakI;~L z@hK6g_{eFmQU(ClF0(feB?aRk=asZwq_xeS8UigXpl;@#d|K>SO za`M`;w;eaS2sEer<40zq;hYH5Z19;&;K#+D_IJbf;8-x)U78W?1&Wbpj&sP5OEKzo ziOkbMas@pg0%WgNGLP3u z#2H}@TG;-547h%}Dv`Au1Wd>~tR?Sfg4}%{xtA;H*_HJ3g6vgK=Ar0E9B(zQ`)@~c zp+FSx<93^!fOhEG(5CVgoUY|&7sV-V__l>YpYyaL*rUWat|-I-emULcWF1|E_`3$%4+`ui|Do)) z*$Qqy=awhRrvVQrn`K42YJs1vpSyfBc|ntrB<0ovJ$P&!`wczod~5)oYojO%#}(eA zJeN-+4(__;@z{Ge;21k$Lfv`+WO^@zYJEEk?q)pvsaWm>=Scmd_y^T10We@3pRun?j&2yG}2vxLe2BIfb3ha^!_5P;8O>1Y^UxJo~s6bH7QuA?B)idq-ROePbAsvG?~W- zAkNU2w%TV5<6!b)kg0n3LC_=k!D(l}B{2ItUb>3?6s+{xF_kQ<4&EO^dsUI1-AF%k zWUmM^kBtlBWH=uWxbrOshR81Yc6voYzdc!Fv|ZL9;XTC>zbKsxX8Wmp+qhN3SzWXPbZNS}uzDRZtX{aJ;>sk%AgI9q?>v`PY@Sq;# zxv?JknIU@(ka_e;j#d4Qdm2nv0JCqOK$U6$C^lDh_`$9XZ=D>V3p5u1<Lqdv<^jT_gPvxZ1UKbCHLFiKXgO714hVXEwhWai4nt>5jdcYs5UkFYdBq3cGdTlX>2Ug3Tg;*{WXR5H%fi zri%m_{gYUJ=<_o`p%Kr@Soaiw7g{Qyu4AQ^ERL-MbxCP3yjpR)3 zIZDx(cL^pnbNW~~7(?D7!&1Iqg5d6I#PJ!+5!`M0`io1O%PR$tv(;Ng7?hb7R`U$hiTqHyPu>*dl_9to`qW@2|vE_sMl&`9Fb?66yo@I z8A{|`l!upoeNP#TMPSYZ;7Z^B=?#DC)?Y_+p?e%&)^87^)`MLW7^`cxuc{XVv zj*`F+rEl?jp}51-3+IFQK$Zx)!;|Uge!N}L?(`Ks#9qtPoP=j*&H=)Y+__ky7llIu zktg#k;#e}M+b(Nwhh|c-5jSURF@3f|OTVa3n4G`F-a)ll%xJN`RQc>XOwdN!nuRL| z7fUX^03N-HT52Z2M68ZRH6z?Y8bOwTY-fF{qUY z{}CDBl3FyE*T@Ykdak;Kn~mUaELC(nH(qzuq1zo4H(t-eVP{6WHl7o;!pM(h6Y90* z@{q`5Xn{B}$YV7tDYeV-f3#WkEnwK%ZL1AkVhi$j>i!)JsAhGEzx0}*lSKKh48GKGeY?3TDwN{N{~T$ijxuNmszf&=f-oQ_ty`>k!=y+ zU{tq%|HgC8WXEgq<&EbhBRAUJUI6WdeL|k8jv_x#@=-53Zj?uW7#!|9k`OHAs54CjGd@qh2>+P@WNzb6<4774OD#IPi99 z4BU9W=QN=^Ol3j$(;J6&54?u<5+gmooj`tuSx~Q89h66p-gkN9_YKCK!FSZy zMPX2Clh3|+Gq9iO-L{RdMS{BD-ruq?SA$oNeUue=s0G7S=g-?M{KeoK@6|sKCh>gc zLkrQ?jTp0xpTyj&EWA!^OTk)4IF^%)I8N3-RCAI;;Ml>}Z;DF7LB!}a=1bOR0Nkw3 zr}M!H2wnQl=V`?aukJ76E2h~Dvaax7vOGJDCzxl+E(*TGehAUhwymb&bId4@kuu_Z zgJ8gNA_CY78yi2JPlOZJbf+X8!{EfV1x>yNd0^9J&UWVq4-9yr(=#Ja0Z!_lQ?M`` z#%Y4*#-oeMu%QLiD{lhjp%6u!(~mDarcFtQrcZCDt5Q~gtDyz8nJ2>F-qR&}cB(l8 z$FTQfi$8SX^cOyzU0Pz`v4Z4ng|JP~=qU0NK#O{9CG%vHoTlrwOnK4iaBFaVPT0OA z=wg0~-fPVRyo|JKy}seKTJw9<(tAN5NpYSkoyo3quUK@h;n#e((ox_oz z*l^VAiZ;rldKhtDvBvDzy1NTRu&c03@mhjzE{9Z8+O2SlB)XpjQ?$E{9@^{GSL8WN z1Nkv|j(P!hlt*kA;ymfOqxC542z;E?l601P7oZkJcgR5APv2#ym$1h}QJFa`^VqTK)tO)K zhp-E=SGAJ-M{$e#aSpD`ZQ zz4>}=?b^_@)UW=V-%*g2bRZ}Bpe4*0+?O4`LlagGx99_FJs2gJEo1P725{R{|Juj@ z5qFC~er`9TUXm&(PcTHB)Vbl0+JzzTHiegeK*q*%!o)ggsPGIZoD~^3xz!n%%krgY zD)YnCS8(Cao*68y4tZ{nMt*w9UZxLGp7SIpa)fX4@y4G?CC*XbGGYg&nWvWIC{e%n?ARR# z>b2H~RQ|d{K1FngPesuEnB!=7EiJUypK#=vA|;XVqq2f}?I!bZYak9!%bncom$X4^ zjH|Hrk~y3yz#gm&TmkJ8qOVWoT!-F{*OSNIngP>rip0%B63}#y6$b@78z`&3m+UzH z6CbyKyYunYE^JMK&SuBA*SP0vpWAAp_pqJ$h;!w4VtK7lKHR;4M`zNNgGRjf}qhWFRN62XxHmhvEao=QJXktXJnRM^OBB+051g zY&#%lXQ}v+`|DU+Uhmq>&rkTK?t501^OacQUF4@K1NC~xi1Hj!N1V1HMRr3vb0~Im z=?wRf8;}-qv9XX-fjd;VV&cEDfjdvEwAC7yafcY|@w}-H?3fJl%$SP&2r!^tGqosB zb`;|5T2#z8jj)BOdrFw?)x-eB-p(jC`Q6|G|C>v)M>;WGu1?P&)k-X)3GF3)A9)V< zLVjlQQ7>;{lqZZ8al8Y=)py&{03O4-g0$01xI^AC?t5Ybm~X@Ly1dX&_|wy9_lVbM zuS{FyndTkx6QhrMvF}28-e0XHI2HQ>ZF)47pyyE6wKYCnz_&?FbFW4;Zi%7$2~I(~ zM|GgR!m^QPwG8AZ_D2=b%Ujfv$b)}E9LDdA47LxI;oF@T4vDr?g2Onv!{%4$eyljr z?(2hSuManoXM+*s$K5}T=ta@SLFDnNI8SiA#VzYrXD!#(#a{ig7>4zZdXK56jUsymfyj|zNW%(u)ASYb`eud0zw zK``qg+{blT6nHL)m8!h?gNF$9@MV;}$HvNQMSuLv#uLAyJi;#!CoW%E-Qbfge3EIS zoe<>)oS#rXD!eNUuKM)EYMs`CF|yQlvHH5O@3~z3{2mSvsdWC`diXc|`M2$7FYju` zk}slO97jyA{x-r+3Kxw$& zOjIe^loF(DnTS-a`HaWkLVmO|Q7;gR^4uml2TMP+yC&WS%XR$xo2Bl+hWy=h)@ETa zXSqlE+tH)o!75BonHGf|YG&=%ztVs{U*y^BJ@RwI5A}M_hw{w7MI7prMYQ${=}^u~ zwS7ju94K@53R`4F!`HXyvRk-a!8G+XTr5u;UN%O1RX8EfEmFwOsyOPE`vT>e@ z2Dg1G!?s-vUYKm{#7YOU%Eg+~FsZguccI~Ytd?u(t!&;qT=PhVa`ZwX_DvRXLf%&x z%Op|&4<gu0jE|OZtHUPG zl9c&@>VZE#F_UE&jqnxwwu4gd9`ztYD;$-_Ud;s-Q+=cRBCWyn`zB(L0 za~Pgvq6~3yPyz0?4;O3rlws4w#%AAYU{o2UqrxjmqN4C z8Tv50!1zOY8ap`Pf;12amII>7IgTm30uw? z13!$bM9bS5M1C8&f4NTczd%^GjQsmAXQ?ydCYedo7gk+`1r3_+d^)y>=|3JiF}>$DUbl z5_OCh@qFbo;gdT~cWNp^HUXa*o^WplbrWE zy!293^Put8RqMYsp`b?(-C=kwx*ww-X!k#JXs?)Tzz4t_V@z^<=`O!L z*y#;_y}TCvJ?$J&JHtU0f0zOcB%P1Jw`~IQEt~p8=;!f*A8zGO?W!@3CgjFt`(*H5zsieppr}iCzp2D9-~{#NlwYZ^=rY$24u9p54B@j2++ml74I0 zP8e`&XH@#QB$zdPU2DFN2L^?`kDB(Sg8RzerJcIB@#h$0xrXZQU%1j_$Wb5mW^Cpf zHLF*39$sUeFZlCjG`1xhae6FtohNeyLC;kHgPPz2GqutTU|5B} z+1Wx5Cfx^5v6~!VsURa=ar+!z5L{fBD%g%Oo<`gqS5Y3$O2l#D-?q}=qz;~qew^{m zHHNP(jSOBf8G+@DoGvWh8HCbX=KgrB03Gl5_^KPwgLINR*NpOJYNKAGy(o|V0OC;h zv#Q1j9D>URCR>ssu7CzRjmZMRDEN0<#?@O*c3=l1;vP&wc~9yf4-$8gAGtEr>%bwD zN5B|y@)rMQ9(K!vd=oF4dg{x-BPYadd4ck_YakE8#mKJ)>G>h)$CB*DPUZ<8N1XB> zhCh}}Wi@0k!s8`x{l!rSOaURn%5xez%i6ZXdWDOf}XQd%% z=bM+%?!#G#JAM!4eMI`nA4I+26O?CS9dSM{Xb^XXeaR*6*W(1bLmg+t9cw^&pJ^ix zr%BHyIml1k7IY5@9VidaBH~PZMz0G~o@cT0_e=o&i85Z>i*6A2H9KFecNP3$Uhoj! zd~)OK-07{-HonfJ`tc#3kY60|+@>w5^H-KI`hK|{rldZ+V9O($(%Ti-n@_nx64^=k zcU{EEjHB?l9_a{zb(oGh?)8Oq$K8LW@A3sBZu>8=S!+W(V;}cE=k5bG_O>-?^^0!V!J`wE0o48|3n@q|vj9O2H=1UUJOpkieS)n`vY(tw%n`=6^rM)1h7i=x?#Lzr5`kkhrNwfHeMajjz~ zpJOu7$dCI))T@W*F_9;HHl5%+-}8cfP?Qz0#DBGWe1QdO?my$ay78R3l3%FwY2)iW ztxEd&)qhN2>3m7|46ZifN7Iq#QG4X)H#_RJd$$IWC&&hIF6R`?9dBa-C0gdOhDN&~ zO~G}qA1tCk$=kc|z7`dHIjr@K=i384{0pi|;WtMeU3=tJIN^+$9+*orQ(J5R(uVy{dd1W%0(K*!W9x}kd#syrAO8440baMc)oW`&5%%m{qPbL{Y9=RN?Ea6v9zf}@}i z|3>D~I2Jj2)xPZW8lGv%cVSwC4a6&T)_-`uga_)(>Ll=uU_DK#16)Owc(>-y9yXWP z*x1o=!4{dfczsgAtIduTSSf7}ktd$!8o_DrD%61`OG`-wd6T`2^I3cO1- zq1{cg&|YcU$a5DH@?)cj zdhs!!Je)j;bK^d%OL&AM`0AnS7!cqFDcaE;Ui3rv6JCXOPgX{IIUGQqrS>8}j|)++ z%U&o?F+buQd1Uh}Il%-BiE2JOwLF8}`I+WTm`_o>)OOejnbxa)!-8~?$ zuAu;)Eo2SP_p-rZ*_{5M0}I%(GqwRo7TfSERWWz=#l6J*@@@BL?YV{fW#tka+r7p& zGmxZ41Gc_Q1TMdC$x_Uzot_vrS<4H6WVwz3J>B zJIG3V4HQNwftywxC0Ip@O zo(Aka2_N1i`9cZ#%`EJczF<4;AOD?V8(-J-s<1-&o&X3b+!v{qxe0nu2EI2qIf8|G zBR|p@>UEX{<++uKI66Q2@{_Xd0Yj_T&!Y7c(D03TJspiAc(`dK^H<3nev?J}$npGP z>~>}K_;go2ZqR}}e@sDs{321WdI6N@nHS=mk$#liv!V&!#GjeA-@y-`q+qv3bm-t{ zPzdGZk$J4NprgA&wi++nj`osRzDRhkAG=EU+4K1~(Tkf4) zQbeze=vPD@iUtk6e>gu6qzhJRT*XrZbLXS@yzypkDXrf647|`Y#aY4&QWjzb)n65safV!(6we8>hQ0+<4HZ1oM`9seg!ntLI^Q9c;+uxR+P;N zOB{q=2RkJhn~W2##yl*u_VM z_Q1iVS+??lFQj7F`Dw?-bE0``zly-d^GBsf&jC|`OdTEHEJiqe#2~G(A+*gJa4bYw1@?Aoc9R_yaAns5*1>Mh)cU8phSNEX3 z%oUL5shh};KM(4aqH9UyQL#ZBj_^?%#*N=Mwm6u=$=!wc>lMM@&!u}YX-1*9!L;A- zZ`LzcTy!@9Dz>L%&1I$dd8H3+A6u#5lbcK`H1R*M)uq@P_RURr;vvV&wW3cj$9*5W z(m#aYN~;*bk(Xbi@`E?=;#C+maXh`zz))7d?r-c80PV)qbvayKDPLGVP)_jw9vK~wUA`q*Dw zqVir<+5rhrIQP-rmQn{gS8Frx_EQ8}YTK@IWi!E@l6gXoNu$`*nq2>pceS`KE$X#$ z-I2(X^|XTE+#9WNii^|)R&o#7nr~Y}tx`&2XJ7 zzG@r1%C!81VQmhZ%e+JQk?&C^dj0XZPvptGi8y;V1z*>+}qA4u1|_*3^y zD2QXH>=M#3hr0)&-mNX|1D@FPM>hnw!YDiBxs_`d;b(-Ylj!xc3FS%ri#U!?6yv(3(DdU3v*EZSH02OXxq)2U*!^cc7$3JoO6R6T2Gv;K+FvdCjM|o zIQxu^6U0h`U*DWAybO{C`-I{u7h`Ckr}uPRMngNci{tgH)g7;K=RYB9xxxvU!5!3V zNfG6te}p(DI(&Lbw{<~IJOBE19W|h36ZqTgku5ab<(t8KQwBsc`{v94+y?6=E#_`* zS;S(3r^6^TTJa*~0>Y1d2kPb2xRb~;u+B$t*sf{6<6csPnMS{dZ~WB;42dGLEKCX$%yHuE5kYhHmm+o}|N zs5rqF|BD`!=qT1E@J-{4wEN6fif1s#1J~|zuUF$YvRH_{T%IG(j>fTspL5GTM6dKB zl;_fiaf0J~YXPrPUc}QY7#YuUFJo4U$G-;uW`>h*DLqg7jbJf;O2qDk`gX)#p3f!; z&pyzH@N=Pen&?F(Cq?90N!vY(PAK9v;lv?-)Yk25s^m(-r|3vYgxSx10 zw7b>yVq!1Xx5%@~AP?cE*nKb2>yE?;BF~hO8o?QE1sxBoNAN@E>l&#XUt`a6(H$0F zMfcNP5lrkZWQO)~JdHflRwF+?U#W>+>-5)%JP9h_2#!taYYtV-7~ID1o!JvbKV0D^ z2Q9l)47TL$`N7pC7vJ(_?y2|VT5K%5aDnw*6#ns&I>%6dFFy8aJG1*j4(8SJ-gDc} zMEt&}>~B7)d~A8$a?m*_6sO8Er6)Md2lX}Y+{Sz9Xe%j?-^MC_4^NiFBx9xKnkv~c zMHu`2;`UC46)e7dMU15_7`^L_r!1@(+KWzwCSh% z!39i!ah5TJvj(5tJW2Gb5OtmUC(oAtbb_<_%k+(E3m#B#z^df5uq>=D>y^x{KMdaH zow4=|;DZl+J-2+jLjguE@r_>ZV}^0NsBEjkMzM6kbixlWn>x|U#~S5nkw6@}_3b^) z)}o-;hax2YxGZG1EQn&`-45#K&7|d=zT>AxzRyxdNq~g0_Eqtab-a8Dc`n&gLimwO zDJOdE6YL}MBvVikoUGT&;zE}N0GIyiJR|)cI7GcUAYSX^955x^xb+rO^q2-$?{WVMe5 zfs;9VUpa*uL1*qZV)u*c*2G?3a+8GTTS>^z+drt+yF(~XzBA&avwYI|P-zJy9=Kg_ z)Nq8$%CnPrwmf*iitZ8$vFPM!;02 z$}2`#2rdkuJFK%n_v0}&L+q~olakoWJPdjMXn_3GUq`*Jw9F8BcJbB_oSz4Uu$#(D zSZR)z;xk%Ld@Gh0YWN`%qd0#&_I#ot)<444>*imFvjuwCtrgc|ie>^gpH$Gp$H~96 za~uY+`v%nsWihWe{vJ0shcWj=?4fZ&l2^Vzp4pfe_75lEqW^U2mIt_O_fzr5x2o~q zAk#DBhkgW?rkwu-aA3O~-5pwXHDB?{s5j`YsP1dWEK(IBpCdJUz>i zKQ9Pgh;8GUyGH>9g<}%cxQ4O6>reL;mg2aPxGB+VOMWqtr|FUj!Ff6ck|lBs!PgNz z4kOD`kVfpd=}o#z;9hCxA#rPC*j-TMp2of(1ggd?!}+c7NIZvo%KS8@P!~Y>5n{+D zddVMkC-PjA)+ac&3J-0Jl8ynh$mECO8{9O8q?W`5`HjD)(eBod&9nHTnEhPqVk7pd zv~D7);XSUYjXXO)Mt(X>P_Oe0C=buqX9VX>?~O|HY(rqn>mhyXs4#2|n;Psswup&I z@?=s4Bw&kUOxfc<3o#lww3ooJ0^vDI82M4Vf_i0m+$Zv!ZgnF#){`-7?0Tyh=upG9 z9WTIbuKo4B*Yg2qJpZS{!gm}K8Gb|Tes@3G>qj0F;knKb`7y6HA$n2W=pyno+j}bi z!;w=cGkkaOCH`FC?X-_+IcB)8Lg)9_X1wb#x*w6qoy6|NmC?jroL`~|&pk)Y2|sZ1 zeAYj`G#jyV|Kzcx0|e*r!_qeb2cP3<67GGkO)@bJ0d$8Idgy*EY|-vFEYMzmf@=uR zhm|M^KZ+@TiC$E(1w@|DMMwJo;V>vT{|;A+!^c8XE}u4plA$ zc+v+`{<2o|565g;E>YZi1#gc7iQ5#If$p;-HHy#nL(4&<=DtN)Fzm+OgPOBF}G&yuxVZAfaKilpe?)!v? zj8Uv}^;Kf!`$Zmp=YNcE`fEh^N!nvV^t$M>g~&tugpc3|Ul>_<&oGZ)d~_^C-~J0W zJQX&UU%PpFb-fi$sKnZqpM z8G2qM{K)J)K=fKa7)0c`xX+Z})ZWR-D4eOoh1VFBly!iT2U{_%Wa4>RE>cxMdJ>sM%Z-9LGb(EOK@ z&O03IJq+VUhm=`LNLKbSB7}V3WMzbsGC~yItc+3_B_Uf%h@z~NgAkSReeKl{8QGDM zmFvHjV@B4EdMB zUfBJ$5-aT0+nxoU>C_iZ2|vTFDqFq8W*mt;Z|)AU5S%J?l@r?wV(^QsL`N%qDQufO z;xcS&iL8vmt{tj&#t)|^)hmbZA@0oXR^{YWyibW-D1Y?{s`lkwtdEYv#xABZkKf)$ zK}=y}|wZxZi zNX*G(Sbn@3Yut@L{5AAF8WL&qQy415(>+P4BBn3V!^D%usgEAw$z%Wd5qW;}?TREg zhVF_EL1iznA@!NGg=ma?CnpvaKlfsLQ_Y#tvRO1uZ|hJy-i^Kf$l6}_Y(bvC68hX~ z8*$c)=C_&7g=l5KSBvNsrknwJO8qM{2u`(Nz7WeZ3ZAhs%}ZJMip;z6L%b7aF+I0H zYTX4IQcJcmtAE)7uKl*XyKiG;^Er_G!|zXj#Y`*wUkN{?G(YH-HDSI){)4&3yqk9@493bLYU13>4aTN*Qz9^C;#=ICw@X z4&cWw;Ux5$(V{?}_>0mz368t_qAu0P8T=W={my8mA?>Z7iB4GKqeQS?R~-E%M{;vz zDrP>rhoZkE340kr$kc)RN%{T(cBh%jfxXhN%Y)~HwC&*M zNW2jA!uRVSk8gnra7H}hbhGqFaksqJRK=%f*GtaiL?LPjQFLbb7#u5F!vD1U# z{C?KaNSOE;-XEO=37L(CRCno zyq(yPf#067yb#%D&jI(p=N;Tco~52VX@bLPsKtA-+MYkc(mCP34WG?TuG4fl- zv$M0MOZ>Y?wM`~x)_bKWLINzG4ZT%Kj1MtzH+24jycO)X!2@;nPw=B2Y6HE}=-)t| zJ#(YL8PMwPPNAox#J^Mia#)>%B=Pb*aP7n|Ltd*SPw-&3|1tR0R(=E@7g$~3^Sq+= z@O8B8r{VihwIpzg_YDKr+G-tM$IYW2UYEwp1#;|}T!viHN4EAF(WHUg#aw03W6**b zdRax90{4;E+!p8Hp9_SC1C&+p!sVnY3J~|;e|2m3X3B;Ku~(?A19%qywdFn5 zhYWd{`>G*Noc9QDxOCjbiQNKK737E=zc+;O5WDKSZtbkl$_u+!H*ax2O>NypmY*AV zm@apKUK}_J@{CgP$`Tx}AXN?G&am~EKXG@@G!DWY2A-XT`$>1Jhuwwawmh6K+VY!d zKLLKyZL8oOwh2z|C-QvgxOtc0L>Mh;R&M@W=uyAWH~6BDxK5hPyRmy=_VX9=Uy6sK zJFdg2D7Hp#YS)3{8sHBB2QI=K5#^tBgajIE72~pOI(*< z8=i?0aE(b^M1sOD)Fz?ZDQ3Ye+G@EU(6OAPk87b{(J%4FiTyN^1m{cepWnkr+Hnt0RzNWA=KIcq zk_^rbuv4NKD#gY~G9)TJzOupwHj0sye#IyrL)=1=;MvEj68t3neGz&IQ$!$7zuZ&c z9BZ7`Fq2!rR2PEI@X9lg>L&uupRyI9kfY5$lKT&nIu}}8862o70ld1fSA~uQc(!=M z2Ywz1YCtb3(E!LZ!l?%wxz6pPp*<^j&)<)AWd?ST%=h2c<=MwgQJz1Zo_~H6_2rhs z?mnR-u$Mz@6nHkMRRKQ=F=fze(Z(6_Tv4O~POjOQch0*dY#RM<*Hq>TD)X|qDqB#8 zH?~Q^{g^T>!0rzfDX`ZX69qhfY32k!@|Vs)FR@U4$P=r)1333*o7D#n4C4gBsAzZ2 z5~SuA4tE%OD**0?bfg+~uU~D2y}0U*gJ;v+Ch#-=ay^ac<<%ACN#v<|JqjGh%E6eo z){%Hu$8NDZrz0_AOM1K(YY8&2lnd|AsKd$sW?XuFdK7tV8B%K#P9Zqgb{mbp-#3gWR?5N`D9DOz$E$56SOwX6a>(a1e^Z$N$czWrIP_D*=b~y0KkjBT#4e7_% zadJ)L3rEj3wE5>;R^e#Z{4+76Ty%CNN#2i{XM{-AYmRxW@L)zP5_uPi#u$T65KX}#+tOq|~ z)-16^FRewDBMWnDUfL-u;X9mZOZ!~O8to`u~}{oEw6 zmxd#oGT}K`rU3jf%g3D~dSz=={U-8g?by-qVw00DurRjou_RL0xzM>zeFWj-@?xqo zrnr@QuHTq+7ir(r3=i;nfG;tOv5+aJVREsa#38N+Tx+S&v@^I zUbXw-F+{l~^1UFq0kjep%IdP&XGM-h4c{ICH|fw)h|KzJ+4v#g3UJTi*s8frd?$WxOzFFv@Z zG}MGL>W$?hw*SWZ!Zr-Phg*>39UtnN(o|e&!3};?-7hW>y?z^3UMBJw1T8-zIA?|t z)tvBK?0AdbMzXORIoZn%1Lsm`8P~|82+KlH|)?>q|(1b=gPqH7kXQX~?ob`a3%5R;!*G zQ-r^EYQSC&dMx01|5_*bDLAMbO7v>#GKM@kL*IdO&~G>{?fxLPj+HEm(VIpVPo5V2 z>y7ctc+dFcQ?W>hP7ik1`@@Z*sX1HA@6{0DjVyI8*=IJVQvhTQwQ zaL6Ubk)m$}XqIc&HD$>t?BYm*`#D+G1iQxy+@L-l0(*rpYJz8n zh(ry-&zJQR&xu~Cbm){ zLWFtxPc-A2BXfkCk)nT6q3E9*o9~B}V3M0RU&8&1?bJ)S4V_Im^=Blv7^~?nCNtJO zM7bY#Bcj*q{Wu!bEUv}Xt{)RRb z#|b}HB{a~>Z1Ec8dDr7zL2w+Jn59>K_TkvC z<7D=fpGe90$C0L{cQ_;}^XA_C1f)~4FOWP~g)h~M_eQGcpwF@a;JHft7Wj#$mWEz; zd}|@k;ptl76klU_X|TT?n@&5d?%wtqy)QbcFqRd~o1$ z;V5n19jv3j2X_BVZwz}KN2TD|#ZWVV@Iy99@g#cPxEahu -# Joonho Lee -# - -import json -import os -import sys -import tempfile -import uuid - -import numpy as np - -from ipie.analysis.extraction import extract_test_data_hdf5 -from ipie.config import MPI -from ipie.qmc.calc import get_driver, read_input -from ipie.utils.io import get_input_value -from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC - -_built_legacy = True - - -comm = MPI.COMM_WORLD -serial_test = comm.size == 1 -# Unique filename to avoid name collision when running through CI. -if comm.rank == 0: - test_id = str(uuid.uuid1()) -else: - test_id = None -test_id = comm.bcast(test_id, root=0) - -_data_dir = os.path.abspath(os.path.dirname(__file__)) + "/reference_data/" -_legacy_test_dirs = [ - #"ft_4x4_hubbard_discrete", - "ft_ueg_ecut1.0_rs1.0", -] - - -_legacy_tests = [ - (_data_dir + d + "/input.json", _data_dir + d + "/reference_1walker.json") for d in _legacy_test_dirs -] - - -def compare_test_data(ref, test): - comparison = {} - for k, v in ref.items(): - if k == "sys_info": - continue - try: - comparison[k] = ( - np.array(ref[k]), - np.array(test[k]), - np.max(np.abs(np.array(ref[k]) - np.array(test[k]))) < 1e-10, - ) - except KeyError: - print(f"# Issue with test data key {k}") - return comparison - - -def run_test_system(input_file, benchmark_file, legacy_job=False): - comm = MPI.COMM_WORLD - input_dict = read_input(input_file, comm) - if input_dict["system"].get("integrals") is not None: - input_dict["system"]["integrals"] = input_file[:-10] + "afqmc.h5" - input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" - elif ("hamiltonian" in input_dict) and (input_dict["hamiltonian"].get("integrals") is not None): - input_dict["hamiltonian"]["integrals"] = input_file[:-10] + "afqmc.h5" - input_dict["trial"]["filename"] = input_file[:-10] + "afqmc.h5" - with tempfile.NamedTemporaryFile() as tmpf: - input_dict["estimators"]["filename"] = tmpf.name - if _built_legacy and legacy_job: - input_dict["qmc"]["batched"] = False - verbosity = input_dict.get("verbosity", 1) - afqmc = ThermalAFQMC(comm, options=input_dict, parallel=comm.size > 1, verbose=verbosity) - afqmc.run(comm=comm) - afqmc.finalise(comm) - with open(benchmark_file, "r") as f: - ref_data = json.load(f) - skip_val = ref_data.get("extract_skip_value", 10) - test_data = extract_test_data_hdf5(tmpf.name, skip=skip_val) - comparison = compare_test_data(ref_data, test_data) - - return comparison - - -if __name__ == "__main__": - err_count = 0 - for test_name, (ind, outd) in zip(_legacy_test_dirs, _legacy_tests): - comparison = run_test_system(ind, outd, legacy_job=True) - local_err_count = 0 - for k, v in comparison.items(): - if not v[-1]: - local_err_count += 1 - print(f" *** FAILED *** : mismatch between benchmark and test run: {test_name}") - err_count += 1 - print(f"name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") - if local_err_count == 0: - print(f"*** PASSED : {test_name} ***") - err_count = comm.bcast(err_count) - sys.exit(err_count) diff --git a/ipie/thermal/tests/test_generic.py b/ipie/thermal/tests/test_generic.py deleted file mode 100644 index 63b672a1..00000000 --- a/ipie/thermal/tests/test_generic.py +++ /dev/null @@ -1,181 +0,0 @@ -from ipie.systems.generic import Generic -from pyscf import gto, scf, lo -from ipie.utils.from_pyscf import generate_hamiltonian -from ipie.thermal.trial.utils import get_trial_density_matrix -import numpy -import mpi4py.MPI as MPI -import h5py -from ipie.thermal.estimators.estimators import Estimators -from ipie.qmc.options import QMCOpts -from ipie.utils.io import to_json - -comm = MPI.COMM_WORLD - -nocca = 5 -noccb = 5 -nelec = nocca + noccb -r0 = 1.75 -mol = gto.M( - atom=[("H", i * r0, 0, 0) for i in range(nelec)], - basis='sto-6g', - unit='Bohr', - verbose=5 -) - -mf = scf.UHF(mol).run() -mf.chkfile = 'scf.chk' - -mo1 = mf.stability()[0] -dm1 = mf.make_rdm1(mo1, mf.mo_occ) -mf = mf.run(dm1) -mf.stability(return_status=True) - -s1e = mol.intor("int1e_ovlp_sph") -ao_coeff = lo.orth.lowdin(s1e) - -# integrals = generate_hamiltonian( -# mol, -# mf.mo_coeff, -# mf.get_hcore(), -# ao_coeff, -# ortho_ao=True, -# chol_cut=1.e-8 -# ) -# num_chol = integrals.chol.shape[1] -# num_basis = integrals.nbasis -# with h5py.File("reference_data/generic_integrals.h5", "w") as fa: -# fa["hcore"] = integrals.H1[0] -# fa["LXmn"] = integrals.chol.T.reshape(num_chol, num_basis, num_basis) -# fa["e0"] = integrals.ecore - -with h5py.File("reference_data/generic_integrals.h5", "r") as fa: - Lxmn = fa["LXmn"][:] - num_chol = Lxmn.shape[0] - num_basis = Lxmn.shape[1] - -mu = -10.0 -beta = 0.1 -dt = 0.01 -num_walkers = 1 -seed = 7 -num_steps_per_block = 1 -blocks = 10 -stabilise_freq = 10 -pop_control_freq = 1 - -options = { - "qmc": { - "dt": dt, - "nwalkers": num_walkers, - "blocks": blocks, - "nsteps": 10, - "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, - "stabilise_freq": stabilise_freq, - "batched": False - }, - "walkers": { - "population_control": "pair_branch" - }, - "estimators": { - "mixed": { - "one_rdm": True - } - }, - "trial": { - "name": "thermal_hartree_fock" - }, - "hamiltonian": { - "name": "Generic", - "integrals": "reference_data/generic_integrals.h5", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - "system": { - "name": "Generic", - "nup": nocca, - "ndown": noccb, - "mu": mu - } -} - -def compare_test_data(ref, test): - comparison = {} - for k, v in ref.items(): - if k == "sys_info": - continue - try: - comparison[k] = ( - numpy.array(ref[k]), - numpy.array(test[k]), - numpy.max(numpy.abs(numpy.array(ref[k]) - numpy.array(test[k]))) < 1e-10, - ) - except KeyError: - print(f"# Issue with test data key {k}") - return comparison - - -from ipie.thermal.qmc.thermal_afqmc_clean import ThermalAFQMC -from ipie.hamiltonians.utils import get_hamiltonian - -system = Generic(mol.nelec) -system.mu = mu -hamiltonian = get_hamiltonian(system, options["hamiltonian"]) -trial = get_trial_density_matrix(hamiltonian, mol.nelec, beta, dt, comm=comm, options=options["trial"]) - -qmc = QMCOpts() # should be removed later after walker is cleaned up -qmc.nwalkers = num_walkers -qmc.ntot_walkers = num_walkers * comm.size -qmc.beta = beta -qmc.nsteps = 1 - - -afqmc = ThermalAFQMC(mol.nelec, mu, beta, - hamiltonian, - trial, - num_walkers, - seed, - num_steps_per_block, - blocks, - dt, - stabilise_freq, - pop_control_freq - ) - -test_name = "generic" -import tempfile -import json -from ipie.analysis.extraction import extract_test_data_hdf5 -with tempfile.NamedTemporaryFile() as tmpf: - options["estimators"]["filename"] = tmpf.name - estimators = Estimators( - options["estimators"], - comm.rank == 0, - qmc, - hamiltonian, - trial, - None - ) - afqmc.estimators = estimators - if comm.rank == 0: - json_string = to_json(afqmc) - afqmc.estimators.json_string = json_string - afqmc.estimators.dump_metadata() - afqmc.estimators.estimators["mixed"].print_key() - afqmc.estimators.estimators["mixed"].print_header() - afqmc.run(comm=comm) - afqmc.finalise(comm) - test_data = extract_test_data_hdf5(tmpf.name) - with open("reference_data/generic_ref.json", "r") as fa: - ref_data = json.load(fa) - comparison = compare_test_data(ref_data, test_data) - local_err_count = 0 - for k, v in comparison.items(): - if not v[-1]: - local_err_count += 1 - print(f" *** FAILED *** : mismatch between benchmark and test run: {test_name}") - print(f"name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0] - v[1]}\n") - if local_err_count == 0: - print(f"*** PASSED : {test_name} ***") diff --git a/ipie/walkers/pop_controller.py b/ipie/walkers/pop_controller.py index 9754e678..769b6a0f 100644 --- a/ipie/walkers/pop_controller.py +++ b/ipie/walkers/pop_controller.py @@ -4,7 +4,7 @@ from ipie.config import MPI from ipie.utils.backend import arraylib as xp -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers class PopControllerTimer: def __init__(self): From b34884b2c3dfcc01ea6e789260e5250d9c2df8ce Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Fri, 8 Mar 2024 20:21:56 -0500 Subject: [PATCH 52/84] fix merge error --- ipie/estimators/tests/test_generic_batch.py | 68 ++++++++++++++++++++- 1 file changed, 66 insertions(+), 2 deletions(-) diff --git a/ipie/estimators/tests/test_generic_batch.py b/ipie/estimators/tests/test_generic_batch.py index cbc0e58a..ee8c18c5 100644 --- a/ipie/estimators/tests/test_generic_batch.py +++ b/ipie/estimators/tests/test_generic_batch.py @@ -215,13 +215,77 @@ def test_local_energy_single_det_batch_packed(): trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) - walkers.rhf = True for i in range(nsteps): prop.propagate_walkers(walkers, hamiltonian, trial, 0.0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_rhf_batch(system, hamiltonian, walkers, trial) + energies = local_energy_single_det_batch(system, hamiltonian, walkers, trial) + + for iw in range(nwalkers): + assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) + # assert numpy.allclose(energy, energies[iw]) + assert numpy.allclose(etots[iw], energies[iw, 0]) + assert numpy.allclose(e1s[iw], energies[iw, 1]) + assert numpy.allclose(e2s[iw], energies[iw, 2]) + + +@pytest.mark.unit +def test_local_energy_single_det_batch_rhf(): + numpy.random.seed(7) + nmo = 10 + nelec = (5, 5) + nwalkers = 10 + nsteps = 25 + dt = 0.005 + h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) + system = Generic(nelec=nelec) + ham = HamGeneric( + h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0 + ) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) + I = numpy.eye(nmo) + wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) + occa0 = ci_wfn[1][0] + occb0 = ci_wfn[2][0] + wfn[:, : nelec[0]] = I[:, occa0] + wfn[:, nelec[0] :] = I[:, occb0] + trial = SingleDet(wfn, nelec, nmo) + trial.build() + trial.half_rotate(ham) + init[:, : nelec[0]] = init[:, nelec[0] :].copy() + + numpy.random.seed(7) + legacy_ham = HamGenericRef( + h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nmo * nmo)).T.copy(), + ecore=0, + options={"symmetry": False}, + ) + + legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) + etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) + + numpy.random.seed(7) + qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": 10}) + prop = PhaselessGeneric(time_step=qmc["dt"]) + prop.build(ham, trial) + walker_opts = dotdict({"rhf": True}) + # walkers = SingleDetWalkerBatch( + # system, ham, trial, nwalkers, init, walker_opts={"rhf": True} + # ) + walkers = UHFWalkersTrial( + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() + ) + walkers.build(trial) + walkers.rhf = True + for i in range(nsteps): + prop.propagate_walkers(walkers, ham, trial, 0.0) + walkers.reortho() + + ovlp = greens_function_single_det_batch(walkers, trial) + energies = local_energy_single_det_rhf_batch(system, ham, walkers, trial) for iw in range(nwalkers): assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) From 682dd7f91877a053468f0a048217a7ee27a48717 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 10 Mar 2024 21:22:00 -0400 Subject: [PATCH 53/84] Added `calc.py` with `build_thermal_afqmc_driver` and example. --- examples/14-ft_afqmc/run_afqmc.py | 91 +++ examples/14-ft_afqmc/ueg.py | 564 ++++++++++++++++++ ipie/addons/thermal/estimators/generic.py | 14 +- .../estimators/tests/test_estimators.py | 12 - .../thermal/estimators/tests/test_generic.py | 12 - .../estimators/tests/test_generic_complex.py | 12 - .../propagation/tests/test_operations.py | 12 - .../propagation/tests/test_prop_generic.py | 12 - .../propagation/tests/ueg/test_prop_ueg.py | 7 - .../propagation/tests/ueg/test_ueg_0T.py | 15 +- ipie/addons/thermal/qmc/calc.py | 181 ++++++ ipie/addons/thermal/qmc/options.py | 6 +- .../thermal/qmc/tests/test_afqmc_generic.py | 7 - .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 14 - ipie/addons/thermal/qmc/thermal_afqmc.py | 20 +- ipie/addons/thermal/trial/mean_field.py | 6 +- ipie/addons/thermal/trial/one_body.py | 33 +- .../thermal/trial/tests/test_chem_pot.py | 6 +- .../thermal/trial/tests/test_mean_field.py | 76 +-- .../thermal/trial/tests/test_one_body.py | 77 +-- ipie/addons/thermal/trial/utils.py | 10 +- ipie/addons/thermal/utils/legacy_testing.py | 132 ++-- ipie/addons/thermal/utils/testing.py | 130 ++-- .../walkers/tests/test_population_control.py | 48 -- .../walkers/tests/test_thermal_walkers.py | 26 +- ipie/addons/thermal/walkers/uhf_walkers.py | 2 +- ipie/qmc/options.py | 15 + ipie/walkers/pop_controller.py | 12 +- 28 files changed, 1107 insertions(+), 445 deletions(-) create mode 100644 examples/14-ft_afqmc/run_afqmc.py create mode 100644 examples/14-ft_afqmc/ueg.py create mode 100644 ipie/addons/thermal/qmc/calc.py diff --git a/examples/14-ft_afqmc/run_afqmc.py b/examples/14-ft_afqmc/run_afqmc.py new file mode 100644 index 00000000..7bbab293 --- /dev/null +++ b/examples/14-ft_afqmc/run_afqmc.py @@ -0,0 +1,91 @@ +import json +import numpy + +from ueg import UEG +from ipie.config import MPI +from ipie.addons.thermal.qmc.calc import build_thermal_afqmc_driver +from ipie.analysis.extraction import extract_observable +from ipie.analysis.autocorr import reblock_by_autocorr + +comm = MPI.COMM_WORLD + +verbose = False if (comm.rank != 0) else True + +# 1. Generate UEG integrals. +ueg_opts = { + "nup": 1, + "ndown": 1, + "rs": 3, + "ecut": 0.5, + "thermal": True, + "write_integrals": True + } + +ueg = UEG(ueg_opts, verbose=verbose) + +if comm.rank == 0: + ueg.build(verbose=verbose) + +comm.barrier() + +# 2. Build thermal AFQMC driver. +options = { + 'trial': { + 'name': 'one_body', + }, + + 'walkers': { + 'lowrank': False, + }, + + 'qmc': { + #'mu': 0.211636, + 'mu': 0.133579, + 'beta': 10, + 'timestep': 0.05, + 'nwalkers': 12 // comm.size, + 'nstack': 10, + 'seed': 7, + 'nblocks': 30, + }, + } + +afqmc = build_thermal_afqmc_driver( + comm, + nelec=ueg.nelec, + hamiltonian_file='ueg_integrals.h5', + seed=7, + options=options, + verbosity=verbose + ) + +if verbose: + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(afqmc.params) # Inspect the qmc options. + +# 3. Run thermal AFQMC calculation. +afqmc.run(verbose=verbose) +afqmc.finalise() +afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + +energy_data = None +number_data = None + +if comm.rank == 0: + energy_data = extract_observable(afqmc.estimators.filename, "energy") + number_data = extract_observable(afqmc.estimators.filename, "nav") + + print(f'filename: {afqmc.estimators.filename}') + print(f'\nenergy_data: \n{energy_data}\n') + print(f'number_data: \n{number_data}\n') + + y = energy_data["ETotal"] + y = y[1:] # Discard first 1 block. + df = reblock_by_autocorr(y, verbose=verbose) + print(df) + print() + + y = number_data["Nav"] + y = y[1:] # Discard first 1 block. + df = reblock_by_autocorr(y, verbose=verbose) + print(df) diff --git a/examples/14-ft_afqmc/ueg.py b/examples/14-ft_afqmc/ueg.py new file mode 100644 index 00000000..8c08db48 --- /dev/null +++ b/examples/14-ft_afqmc/ueg.py @@ -0,0 +1,564 @@ +import numpy +import scipy.sparse +from ipie.utils.io import write_qmcpack_sparse + + +class UEG(object): + """UEG system class (integrals read from fcidump) + + Parameters + ---------- + nup : int + Number of up electrons. + + ndown : int + Number of down electrons. + + rs : float + Density parameter. + + ecut : float + Scaled cutoff energy. + + ktwist : :class:`numpy.ndarray` + Twist vector. + + verbose : bool + Print extra information. + + Attributes + ---------- + T : :class:`numpy.ndarray` + One-body part of the Hamiltonian. This is diagonal in plane wave basis. + + ecore : float + Madelung contribution to the total energy. + + h1e_mod : :class:`numpy.ndarray` + Modified one-body Hamiltonian. + + nfields : int + Number of field configurations per walker for back propagation. + + basis : :class:`numpy.ndarray` + Basis vectors within a cutoff. + + kfac : float + Scale factor (2pi/L). + """ + + def __init__(self, options, verbose=False): + if verbose: + print("# Parsing input options.") + + self.name = "UEG" + self.nup = options.get("nup") + self.ndown = options.get("ndown") + self.nelec = (self.nup, self.ndown) + self.rs = options.get("rs") + self.ecut = options.get("ecut") + self.ktwist = numpy.array(options.get("ktwist", [0, 0, 0])).reshape(3) + + self.thermal = options.get("thermal", False) + self._alt_convention = options.get("alt_convention", False) + self.write_ints = options.get("write_integrals", False) + + self.sparse = True + self.control_variate = False + self.diagH1 = True + + # Total # of electrons. + self.ne = self.nup + self.ndown + # Spin polarisation. + self.zeta = (self.nup - self.ndown) / self.ne + # Density. + self.rho = ((4.0 * numpy.pi) / 3.0 * self.rs**3.0) ** (-1.0) + # Box Length. + self.L = self.rs * (4.0 * self.ne * numpy.pi / 3.0) ** (1 / 3.0) + # Volume + self.vol = self.L**3.0 + # k-space grid spacing. + self.kfac = 2 * numpy.pi / self.L + # Fermi Wavevector (infinite system). + self.kf = (3 * (self.zeta + 1) * numpy.pi**2 * self.ne / self.L**3) ** (1 / 3.0) + # Fermi energy (inifinite systems). + self.ef = 0.5 * self.kf**2 + # Core energy. + self.ecore = 0.5 * self.ne * self.madelung() + + if verbose: + if self.thermal: + print("# Thermal UEG activated.") + + print(f"# Number of spin-up electrons: {self.nup:d}") + print(f"# Number of spin-down electrons: {self.ndown:d}") + print(f"# rs: {self.rs:6.4e}") + print(f"# Spin polarisation (zeta): {self.zeta:6.4e}") + print(f"# Electron density (rho): {self.rho:13.8e}") + print(f"# Box Length (L): {self.L:13.8e}") + print(f"# Volume: {self.vol:13.8e}") + print(f"# k-space factor (2pi/L): {self.kfac:13.8e}") + + + def build(self, verbose=False): + # Get plane wave basis vectors and corresponding eigenvalues. + self.sp_eigv, self.basis, self.nmax = self.sp_energies( + self.ktwist, self.kfac, self.ecut) + self.shifted_nmax = 2 * self.nmax + self.imax_sq = numpy.dot(self.basis[-1], self.basis[-1]) + self.create_lookup_table() + + for i, k in enumerate(self.basis): + assert i == self.lookup_basis(k) + + # Number of plane waves. + self.nbasis = len(self.sp_eigv) + self.nactive = self.nbasis + self.ncore = 0 + self.nfv = 0 + self.mo_coeff = None + + # --------------------------------------------------------------------- + T = numpy.diag(self.sp_eigv) + h1e_mod = self.mod_one_body(T) + self.H1 = numpy.array([T, T]) # Making alpha and beta. + self.h1e_mod = numpy.array([h1e_mod, h1e_mod]) + + # --------------------------------------------------------------------- + # Allowed momentum transfers (4*ecut). + eigs, qvecs, self.qnmax = self.sp_energies(self.ktwist, self.kfac, 4 * self.ecut) + + # Omit Q = 0 term. + self.qvecs = numpy.copy(qvecs[1:]) + self.vqvec = numpy.array([self.vq(self.kfac * q) for q in self.qvecs]) + + # Number of momentum transfer vectors / auxiliary fields. + # Can reduce by symmetry but be stupid for the moment. + self.nchol = len(self.qvecs) + self.nfields = 2 * len(self.qvecs) + self.get_momentum_transfers() + + if verbose: + print(f"# Number of plane waves: {self.nbasis:d}") + print(f"# Number of Cholesky vectors: {self.nchol:d}.") + print(f"# Number of auxiliary fields: {self.nfields:d}.") + print("# Constructing two-body potentials incore.") + + # --------------------------------------------------------------------- + self.chol_vecs, self.iA, self.iB = self.two_body_potentials_incore() + + if self.write_ints: + self.write_integrals() + + if verbose: + print("# Approximate memory required for " + "two-body potentials: {:13.8e} GB.".format((3 * self.iA.nnz * 16 / (1024**3)))) + print("# Finished constructing two-body potentials.") + print("# Finished building UEG object.") + + + def sp_energies(self, ks, kfac, ecut): + """Calculate the allowed kvectors and resulting single particle eigenvalues (basically kinetic energy) + which can fit in the sphere in kspace determined by ecut. + + Parameters + ---------- + kfac : float + kspace grid spacing. + + ecut : float + energy cutoff. + + Returns + ------- + spval : :class:`numpy.ndarray` + Array containing sorted single particle eigenvalues. + + kval : :class:`numpy.ndarray` + Array containing basis vectors, sorted according to their + corresponding single-particle energy. + """ + + # Scaled Units to match with HANDE. + # So ecut is measured in units of 1/kfac^2. + nmax = int(numpy.ceil(numpy.sqrt((2 * ecut)))) + + spval = [] + vec = [] + kval = [] + + for ni in range(-nmax, nmax + 1): + for nj in range(-nmax, nmax + 1): + for nk in range(-nmax, nmax + 1): + spe = 0.5 * (ni**2 + nj**2 + nk**2) + + if spe <= ecut: + kijk = [ni, nj, nk] + + # Reintroduce 2 \pi / L factor. + ek = 0.5 * numpy.dot(numpy.array(kijk) + ks, numpy.array(kijk) + ks) + kval.append(kijk) + spval.append(kfac**2 * ek) + + # Sort the arrays in terms of increasing energy. + spval = numpy.array(spval) + ix = numpy.argsort(spval, kind="mergesort") + spval = spval[ix] + kval = numpy.array(kval)[ix] + return spval, kval, nmax + + + def create_lookup_table(self): + basis_ix = [] + for k in self.basis: + basis_ix.append(self.map_basis_to_index(k)) + + self.lookup = numpy.zeros(max(basis_ix) + 1, dtype=int) + + for i, b in enumerate(basis_ix): + self.lookup[b] = i + + self.max_ix = max(basis_ix) + + + def lookup_basis(self, vec): + if numpy.dot(vec, vec) <= self.imax_sq: + ix = self.map_basis_to_index(vec) + + if ix >= len(self.lookup): + ib = None + + else: + ib = self.lookup[ix] + + return ib + + else: + ib = None + + + def map_basis_to_index(self, k): + return ((k[0] + self.nmax) + + self.shifted_nmax * (k[1] + self.nmax) + + self.shifted_nmax * self.shifted_nmax * (k[2] + self.nmax)) + + + def get_momentum_transfers(self): + """Get arrays of plane wave basis vectors connected by momentum transfers Q.""" + nlimit = self.nup + if self.thermal: + nlimit = self.nbasis + + self.ikpq_i = [] + self.ikpq_kpq = [] + + for iq, q in enumerate(self.qvecs): + idxkpq_list_i = [] + idxkpq_list_kpq = [] + + for i, k in enumerate(self.basis[0:nlimit]): + kpq = k + q + idxkpq = self.lookup_basis(kpq) + + if idxkpq is not None: + idxkpq_list_i += [i] + idxkpq_list_kpq += [idxkpq] + + self.ikpq_i += [idxkpq_list_i] + self.ikpq_kpq += [idxkpq_list_kpq] + + # --------------------------------------------------------------------- + self.ipmq_i = [] + self.ipmq_pmq = [] + + for iq, q in enumerate(self.qvecs): + idxpmq_list_i = [] + idxpmq_list_pmq = [] + + for i, p in enumerate(self.basis[0:nlimit]): + pmq = p - q + idxpmq = self.lookup_basis(pmq) + + if idxpmq is not None: + idxpmq_list_i += [i] + idxpmq_list_pmq += [idxpmq] + + self.ipmq_i += [idxpmq_list_i] + self.ipmq_pmq += [idxpmq_list_pmq] + + for iq, q in enumerate(self.qvecs): + self.ikpq_i[iq] = numpy.array(self.ikpq_i[iq], dtype=numpy.int64) + self.ikpq_kpq[iq] = numpy.array(self.ikpq_kpq[iq], dtype=numpy.int64) + self.ipmq_i[iq] = numpy.array(self.ipmq_i[iq], dtype=numpy.int64) + self.ipmq_pmq[iq] = numpy.array(self.ipmq_pmq[iq], dtype=numpy.int64) + + + def madelung(self): + """Use expression in Schoof et al. (PhysRevLett.115.130402) for the + Madelung contribution to the total energy fitted to L.M. Fraser et al. + Phys. Rev. B 53, 1814. + + Parameters + ---------- + rs : float + Wigner-Seitz radius. + + ne : int + Number of electrons. + + Returns + ------- + v_M: float + Madelung potential (in Hartrees). + """ + c1 = -2.837297 + c2 = (3.0 / (4.0 * numpy.pi)) ** (1.0 / 3.0) + return c1 * c2 / (self.ne ** (1.0 / 3.0) * self.rs) + + + def mod_one_body(self, T): + """Absorb the diagonal term of the two-body Hamiltonian to the one-body term. + Essentially adding the third term in Eq.(11b) of Phys. Rev. B 75, 245123. + + Parameters + ---------- + T : float + one-body Hamiltonian (i.e. kinetic energy) + + Returns + ------- + h1e_mod: float + modified one-body Hamiltonian + """ + h1e_mod = numpy.copy(T) + + fac = 1.0 / (2.0 * self.vol) + for i, ki in enumerate(self.basis): + for j, kj in enumerate(self.basis): + if i != j: + q = self.kfac * (ki - kj) + h1e_mod[i, i] = h1e_mod[i, i] - fac * self.vq(q) + + return h1e_mod + + + def vq(self, q): + """The typical 3D Coulomb kernel + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + v_M: float + 3D Coulomb kernel (in Hartrees) + """ + return 4 * numpy.pi / numpy.dot(q, q) + + + def density_operator(self, iq): + """Density operator as defined in Eq.(6) of Phys. Rev. B 75, 245123. + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + rho_q: float + density operator + """ + nnz = self.rho_ikpq_kpq[iq].shape[0] # Number of non-zeros + ones = numpy.ones((nnz), dtype=numpy.complex128) + rho_q = scipy.sparse.csc_matrix( + (ones, (self.rho_ikpq_kpq[iq], self.rho_ikpq_i[iq])), + shape=(self.nbasis, self.nbasis), + dtype=numpy.complex128) + return rho_q + + + def scaled_density_operator_incore(self, transpose): + """Density operator as defined in Eq.(6) of PRB(75)245123 + + Parameters + ---------- + q : float + a plane-wave vector + + Returns + ------- + rho_q: float + density operator + """ + rho_ikpq_i = [] + rho_ikpq_kpq = [] + + for iq, q in enumerate(self.qvecs): + idxkpq_list_i = [] + idxkpq_list_kpq = [] + + for i, k in enumerate(self.basis): + kpq = k + q + idxkpq = self.lookup_basis(kpq) + + if idxkpq is not None: + idxkpq_list_i += [i] + idxkpq_list_kpq += [idxkpq] + + rho_ikpq_i += [idxkpq_list_i] + rho_ikpq_kpq += [idxkpq_list_kpq] + + for iq, q in enumerate(self.qvecs): + rho_ikpq_i[iq] = numpy.array(rho_ikpq_i[iq], dtype=numpy.int64) + rho_ikpq_kpq[iq] = numpy.array(rho_ikpq_kpq[iq], dtype=numpy.int64) + + nq = len(self.qvecs) + nnz = 0 + for iq in range(nq): + nnz += rho_ikpq_kpq[iq].shape[0] + + col_index = [] + row_index = [] + values = [] + + if transpose: + for iq in range(nq): + qscaled = self.kfac * self.qvecs[iq] + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = numpy.pi / (self.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + for innz, kpq in enumerate(rho_ikpq_kpq[iq]): + row_index += [rho_ikpq_kpq[iq][innz] + rho_ikpq_i[iq][innz] * self.nbasis] + col_index += [iq] + values += [factor] + + else: + for iq in range(nq): + qscaled = self.kfac * self.qvecs[iq] + # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol + piovol = numpy.pi / (self.vol) + factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 + + for innz, kpq in enumerate(rho_ikpq_kpq[iq]): + row_index += [rho_ikpq_kpq[iq][innz] * self.nbasis + rho_ikpq_i[iq][innz]] + col_index += [iq] + values += [factor] + + rho_q = scipy.sparse.csc_matrix( + (values, (row_index, col_index)), + shape=(self.nbasis * self.nbasis, nq), + dtype=numpy.complex128) + return rho_q + + + def two_body_potentials_incore(self): + """Calculate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q + + Returns + ------- + iA : numpy array + Eq.(13a) + + iB : numpy array + Eq.(13b) + """ + rho_q = self.scaled_density_operator_incore(False) + rho_qH = self.scaled_density_operator_incore(True) + iA = 1j * (rho_q + rho_qH) + iB = -(rho_q - rho_qH) + return (rho_q, iA, iB) + + + def hijkl(self, i, j, k, l): + """Compute = (ik|jl) = 1/Omega * 4pi/(kk-ki)**2 + + Checks for momentum conservation k_i + k_j = k_k + k_k, or + k_k - k_i = k_j - k_l. + + Parameters + ---------- + i, j, k, l : int + Orbital indices for integral (ik|jl) = . + + Returns + ------- + integral : float + (ik|jl) + """ + q1 = self.basis[k] - self.basis[i] + q2 = self.basis[j] - self.basis[l] + + if numpy.dot(q1, q1) > 1e-12 and numpy.dot(q1 - q2, q1 - q2) < 1e-12: + return 1.0 / self.vol * self.vq(self.kfac * q1) + + else: + return 0.0 + + + def compute_real_transformation(self): + U22 = numpy.zeros((2, 2), dtype=numpy.complex128) + U22[0, 0] = 1.0 / numpy.sqrt(2.0) + U22[0, 1] = 1.0 / numpy.sqrt(2.0) + U22[1, 0] = -1.0j / numpy.sqrt(2.0) + U22[1, 1] = 1.0j / numpy.sqrt(2.0) + + U = numpy.zeros((self.nbasis, self.nbasis), dtype=numpy.complex128) + + for i, b in enumerate(self.basis): + if numpy.sum(b * b) == 0: + U[i, i] = 1.0 + + else: + mb = -b + diff = numpy.einsum("ij->i", (self.basis - mb) ** 2) + idx = numpy.argwhere(diff == 0) + assert idx.ravel().shape[0] == 1 + + if i < idx: + idx = idx.ravel()[0] + U[i, i] = U22[0, 0] + U[i, idx] = U22[0, 1] + U[idx, i] = U22[1, 0] + U[idx, idx] = U22[1, 1] + + else: + continue + + U = U.T.copy() + return U + + + def eri_4(self): + eri_chol = 4 * self.chol_vecs.dot(self.chol_vecs.T) + eri_chol = ( + eri_chol.toarray().reshape((self.nbasis, self.nbasis, self.nbasis, self.nbasis)).real) + eri_chol = eri_chol.transpose(0, 1, 3, 2) + return eri_chol + + + def eri_8(self): + """Compute 8-fold symmetric integrals. Useful for running standard + quantum chemistry methods,""" + eri = self.eri_4() + U = self.compute_real_transformation() + eri0 = numpy.einsum("mp,mnls->pnls", U.conj(), eri, optimize=True) + eri1 = numpy.einsum("nq,pnls->pqls", U, eri0, optimize=True) + eri2 = numpy.einsum("lr,pqls->pqrs", U.conj(), eri1, optimize=True) + eri3 = numpy.einsum("st,pqrs->pqrt", U, eri2, optimize=True).real + return eri3 + + + def write_integrals(self, filename="ueg_integrals.h5"): + write_qmcpack_sparse( + self.H1[0], + 2 * self.chol_vecs.toarray(), + self.nelec, + self.nbasis, + #enuc=self.ecore, + enuc=0., + filename=filename) + diff --git a/ipie/addons/thermal/estimators/generic.py b/ipie/addons/thermal/estimators/generic.py index 8d87fb8e..82d763d9 100644 --- a/ipie/addons/thermal/estimators/generic.py +++ b/ipie/addons/thermal/estimators/generic.py @@ -367,10 +367,7 @@ def local_energy_generic_cholesky_opt_stochastic( ecoul = numpy.dot(Xa, Xa) ecoul += numpy.dot(Xb, Xb) ecoul += 2 * numpy.dot(Xa, Xb) - if hamiltonian.sparse: - rchol_a, rchol_b = [rchol[0].toarray(), rchol[1].toarray()] - else: - rchol_a, rchol_b = rchol[0], rchol[1] + rchol_a, rchol_b = rchol[0], rchol[1] # T_{abn} = \sum_k Theta_{ak} LL_{ak,n} # LL_{ak,n} = \sum_i L_{ik,n} A^*_{ia} @@ -562,11 +559,6 @@ def fock_generic(hamiltonian, P): nbasis = hamiltonian.nbasis nchol = hamiltonian.nchol hs_pot = hamiltonian.chol.T.reshape(nchol, nbasis, nbasis) - if hamiltonian.sparse: - mf_shift = 1j * P[0].ravel() * hs_pot - mf_shift += 1j * P[1].ravel() * hs_pot - VMF = 1j * hs_pot.dot(mf_shift).reshape(nbasis, nbasis) - else: - mf_shift = 1j * numpy.einsum("lpq,spq->l", hs_pot, P) - VMF = 1j * numpy.einsum("lpq,l->pq", hs_pot, mf_shift) + mf_shift = 1j * numpy.einsum("lpq,spq->l", hs_pot, P) + VMF = 1j * numpy.einsum("lpq,l->pq", hs_pot, mf_shift) return hamiltonian.h1e_mod - VMF diff --git a/ipie/addons/thermal/estimators/tests/test_estimators.py b/ipie/addons/thermal/estimators/tests/test_estimators.py index 2af752b6..9c47c5e9 100644 --- a/ipie/addons/thermal/estimators/tests/test_estimators.py +++ b/ipie/addons/thermal/estimators/tests/test_estimators.py @@ -53,18 +53,6 @@ 'complex_integrals': complex_integrals, 'mf_trial': mf_trial, 'propagate': propagate, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } @pytest.mark.unit diff --git a/ipie/addons/thermal/estimators/tests/test_generic.py b/ipie/addons/thermal/estimators/tests/test_generic.py index 9e7741ae..acd8ae1a 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic.py +++ b/ipie/addons/thermal/estimators/tests/test_generic.py @@ -61,18 +61,6 @@ def test_local_energy_cholesky(mf_trial=False): 'complex_integrals': complex_integrals, 'mf_trial': mf_trial, 'propagate': propagate, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } # Test. diff --git a/ipie/addons/thermal/estimators/tests/test_generic_complex.py b/ipie/addons/thermal/estimators/tests/test_generic_complex.py index d78f8d1d..a47f8bd3 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/addons/thermal/estimators/tests/test_generic_complex.py @@ -57,18 +57,6 @@ 'complex_integrals': complex_integrals, 'mf_trial': mf_trial, 'propagate': propagate, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } diff --git a/ipie/addons/thermal/propagation/tests/test_operations.py b/ipie/addons/thermal/propagation/tests/test_operations.py index 86b3e039..8d2ab633 100644 --- a/ipie/addons/thermal/propagation/tests/test_operations.py +++ b/ipie/addons/thermal/propagation/tests/test_operations.py @@ -56,18 +56,6 @@ def test_apply_exponential(): 'complex_integrals': complex_integrals, 'mf_trial': mf_trial, 'propagate': propagate, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } # Test. diff --git a/ipie/addons/thermal/propagation/tests/test_prop_generic.py b/ipie/addons/thermal/propagation/tests/test_prop_generic.py index 8fc6bf23..eb6d7714 100644 --- a/ipie/addons/thermal/propagation/tests/test_prop_generic.py +++ b/ipie/addons/thermal/propagation/tests/test_prop_generic.py @@ -59,18 +59,6 @@ 'complex_integrals': complex_integrals, 'mf_trial': mf_trial, 'propagate': propagate, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index fd460553..78396438 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -69,13 +69,6 @@ def test_phaseless_generic_propagator(): "write_integrals": False, "low_rank": lowrank }, - - "hamiltonian": { - "name": "UEG", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, } # Test. diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py b/ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py index 904169d5..1d9e2c59 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py @@ -1,10 +1,11 @@ import numpy import pytest +from ueg import UEG from pyscf import gto, scf, ao2mo + +from ipie.utils.mpi import MPIHandler from ipie.qmc.options import QMCOpts -from ipie.utils.linalg import diagonalise_sorted -from ueg import UEG from ipie.systems.generic import Generic from ipie.utils.testing import generate_hamiltonian @@ -41,13 +42,6 @@ def setup_objs(seed=None): "rng_seed": seed, "batched": False }, - - "hamiltonian": { - "name": "UEG", - "_alt_convention": False, - "sparse": False, - "mu": mu - } } # Generate UEG integrals. @@ -145,7 +139,7 @@ def setup_objs(seed=None): # 4. Build walkers. walkers = UHFWalkersTrial(trial, psi0, system.nup, system.ndown, hamiltonian.nbasis, - nwalkers, verbose=verbose) + nwalkers, MPIHandler(), verbose=verbose) walkers.build(trial) walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) @@ -157,7 +151,6 @@ def setup_objs(seed=None): }, "qmc": options["qmc"], - "hamiltonian": options["hamiltonian"], } print('\n------------------------------') diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py new file mode 100644 index 00000000..bcea879b --- /dev/null +++ b/ipie/addons/thermal/qmc/calc.py @@ -0,0 +1,181 @@ +"""Helper Routines for setting up a calculation""" +import json + +from ipie.config import MPI +from ipie.utils.mpi import MPIHandler +from ipie.utils.io import get_input_value + +from ipie.systems.utils import get_system +from ipie.hamiltonians.utils import get_hamiltonian + +from ipie.addons.thermal.trial.utils import get_trial_density_matrix +from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers +from ipie.addons.thermal.propagation.propagator import Propagator +from ipie.addons.thermal.qmc.options import ThermalQMCParams +from ipie.addons.thermal.qmc.thermal_afqmc import ThermalAFQMC + + +def init_communicator(): + return MPI.COMM_WORLD + + +def setup_calculation(input_options): + comm = init_communicator() + if isinstance(input_options, str): + options = read_input(input_options, comm, verbose=True) + else: + options = input_options + afqmc = get_driver(options, comm) + return (afqmc, comm) + + +def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: + verbosity = options.get("verbosity", 1) + qmc_opts = get_input_value(options, "qmc", default={}, alias=["qmc_options"]) + + sys_opts = get_input_value( + options, "system", default={}, alias=["model"], verbose=verbosity > 1 + ) + ham_opts = get_input_value(options, "hamiltonian", default={}, verbose=verbosity > 1) + # backward compatibility with previous code (to be removed) + for item in sys_opts.items(): + if item[0].lower() == "name" and "name" in ham_opts.keys(): + continue + ham_opts[item[0]] = item[1] + + tdm_opts = get_input_value( + options, "trial", default={}, alias=["trial_density_matrix"], verbose=verbosity > 1 + ) + + wlk_opts = get_input_value( + options, "walkers", default={}, alias=["walker", "walker_opts"], verbose=verbosity > 1 + ) + + if comm.rank != 0: + verbosity = 0 + lowrank = get_input_value(wlk_opts, "lowrank", default=False, alias=["low_rank"], verbose=verbosity) + batched = get_input_value(qmc_opts, "batched", default=False, verbose=verbosity) + + if (lowrank == True) or (batched == True): + raise ValueError("Option not supported in thermal code.") + else: + from ipie.qmc.options import QMCOpts + + qmc = QMCOpts(qmc_opts, verbose=0) + mpi_handler = MPIHandler(nmembers=qmc_opts.get("nmembers", 1), verbose=verbosity) + system = get_system( + sys_opts, verbose=verbosity, comm=comm + ) # Have to deal with shared comm in the future. I think we will remove this... + ham_file = get_input_value(ham_opts, "integrals", None, verbose=verbosity) + if ham_file is None: + raise ValueError("Hamiltonian filename not specified.") + pack_chol = get_input_value( + ham_opts, "symmetry", True, alias=["pack_chol", "pack_cholesky"], verbose=verbosity + ) + hamiltonian = get_hamiltonian( + ham_file, mpi_handler.scomm, pack_chol=pack_chol, verbose=verbosity + ) + num_elec = (system.nup, system.ndown) + trial = get_trial_density_matrix( + hamiltonian, + num_elec, + qmc.beta, + qmc.dt, + options=tdm_opts, + comm=comm, + verbose=verbosity, + ) + nstack = get_input_value(wlk_opts, 'nstack', default=10, alias=["stack_size"], verbose=verbosity) + lowrank_thresh = get_input_value(wlk_opts, 'lowrank_thresh', default=1e-6, alias=["low_rank_thresh"], verbose=verbosity) + walkers = UHFThermalWalkers( + trial, hamiltonian.nbasis, qmc.nwalkers, nstack=nstack, + lowrank=lowrank, lowrank_thresh=lowrank_thresh, verbose=verbosity) + + if (comm.rank == 0) and (qmc.nsteps > 1): + print("Only num_steps_per_block = 1 allowed in thermal code! Resetting to value of 1.") + + params = ThermalQMCParams( + mu=qmc.mu, + beta=qmc.beta, + num_walkers=qmc.nwalkers, + total_num_walkers=qmc.nwalkers * comm.size, + num_blocks=qmc.nblocks, + timestep=qmc.dt, + num_stblz=qmc.nstblz, + pop_control_freq=qmc.npop_control, + pop_control_method=qmc.pop_control_method, + rng_seed=qmc.rng_seed, + ) + propagator = Propagator[type(hamiltonian)](params.timestep, params.mu) + propagator.build(hamiltonian, trial, walkers, mpi_handler) + afqmc = ThermalAFQMC( + system, + hamiltonian, + trial, + walkers, + propagator, + params, + verbose=(verbosity and comm.rank == 0), + ) + + return afqmc + + +def build_thermal_afqmc_driver( + comm, + nelec: tuple, + hamiltonian_file: str = "hamiltonian.h5", + estimator_filename: str = "estimates.0.h5", + seed: int = None, + options: dict = None, + verbosity: int = 0, +): + if comm.rank != 0: + verbosity = 0 + + sys_opts = {"nup": nelec[0], "ndown": nelec[1]} + ham_opts = {"integrals": hamiltonian_file} + qmc_opts = {"rng_seed": seed} + est_opts = {"overwrite": True, "filename": estimator_filename} + + options["system"] = sys_opts + options["estimators"] = est_opts + options["hamiltonian"] = ham_opts + options["qmc"].update(qmc_opts) + + return get_driver(options, comm) + + +def read_input(input_file, comm, verbose=False): + """Helper function to parse input file and setup parallel calculation. + + Parameters + ---------- + input_file : string + Input filename. + verbose : bool + If true print out set up information. + + Returns + ------- + options : dict + Python dict of input options. + comm : MPI communicator + Communicator object. If mpi4py is not installed then we return a fake + communicator. + """ + if comm.rank == 0: + if verbose: + print(f"# Initialising pie simulation from {input_file}") + try: + with open(input_file) as inp: + options = json.load(inp) + except FileNotFoundError: + options = None + else: + options = None + options = comm.bcast(options, root=0) + if options == None: + raise FileNotFoundError + + return options diff --git a/ipie/addons/thermal/qmc/options.py b/ipie/addons/thermal/qmc/options.py index dd5c2d1d..d9bb548f 100644 --- a/ipie/addons/thermal/qmc/options.py +++ b/ipie/addons/thermal/qmc/options.py @@ -10,6 +10,7 @@ class ThermalQMCParams(QMCParams): r"""Input options and certain constants / parameters derived from them. Args: + mu: chemical potential. beta: inverse temperature. num_walkers: number of walkers **per** core / task / computational unit. total_num_walkers: The total number of walkers in the simulation. @@ -26,16 +27,19 @@ class ThermalQMCParams(QMCParams): # Due to structure of FT algorithm, `num_steps_per_block` is fixed at 1. # Overide whatever input for backward compatibility. num_steps_per_block: ClassVar[float] = 1 + mu: float = _no_default beta: float = _no_default pop_control_method: str = 'pair_branch' # This is a hack to get around the error: # - # TypeError: non-default argument 'beta' follows default argument + # TypeError: non-default argument follows default argument # # due to inheritance from the QMCParams dataclass which has default attributes. # Ref: https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses def __post_init__(self): + if self.mu is _no_default: + raise TypeError("__init__ missing 1 required argument: 'mu'") if self.beta is _no_default: raise TypeError("__init__ missing 1 required argument: 'beta'") diff --git a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py index 5ef7415f..b455121d 100644 --- a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py +++ b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py @@ -74,13 +74,6 @@ def test_thermal_afqmc(): 'lowrank': lowrank, 'complex_integrals': complex_integrals, - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - "estimators": { "filename": tmpf2.name, # For legacy. }, diff --git a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index b577117f..ac3a2e3c 100644 --- a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -120,13 +120,6 @@ def test_thermal_afqmc_1walker(against_ref=False): "low_rank": lowrank }, - "hamiltonian": { - "name": "UEG", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - "estimators": { "filename": tmpf2.name, # For legacy. }, @@ -314,13 +307,6 @@ def test_thermal_afqmc(against_ref=False): "low_rank": lowrank }, - "hamiltonian": { - "name": "UEG", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - "estimators": { "filename": tmpf2.name, # For legacy. }, diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 1f6b515b..7ec70529 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -67,6 +67,7 @@ def build( hamiltonian, trial, nwalkers: int = 100, + nstack: int = 10, seed: int = None, nblocks: int = 100, timestep: float = 0.005, @@ -74,6 +75,7 @@ def build( pop_control_freq: int = 5, pop_control_method: str = 'pair_branch', lowrank: bool = False, + lowrank_thresh: float = 1e-6, debug: bool = False, verbose: bool = True, mpi_handler=None,) -> "Thermal AFQMC": @@ -94,12 +96,8 @@ def build( nwalkers : int Number of walkers per MPI process used in the simulation. The TOTAL number of walkers is nwalkers * number of processes. - nsteps_per_block : int - Number of Monte Carlo steps before estimators are evaluated. - Default 25. nblocks : int - Number of blocks to perform. Total number of steps = nblocks * - nsteps_per_block. + Number of blocks to perform. timestep : float Imaginary timestep. Default 0.005. stabilize_freq : float @@ -109,7 +107,9 @@ def build( Frequency at which to perform population control (in units of steps.) Default 25. lowrank : bool - Low-rank algorithm for thermal propagation. + Low-rank algorithm for thermal propagation. Doesn't work for now! + lowrank_thresh : bool + Threshold for low-rank algorithm. verbose : bool Log verbosity. Default True i.e. print information to stdout. """ @@ -121,6 +121,7 @@ def build( comm = mpi_handler.comm params = ThermalQMCParams( + mu=mu, beta=beta, num_walkers=nwalkers, total_num_walkers=nwalkers * comm.size, @@ -132,9 +133,10 @@ def build( rng_seed=seed) system = Generic(nelec) - walkers = UHFThermalWalkers(trial, hamiltonian.nbasis, nwalkers, - lowrank=lowrank, mpi_handler=mpi_handler, - verbose=verbose) + walkers = UHFThermalWalkers( + trial, hamiltonian.nbasis, nwalkers, nstack=nstack, + lowrank=lowrank, lowrank_thresh=lowrank_thresh, + mpi_handler=mpi_handler, verbose=verbose) propagator = Propagator[type(hamiltonian)]( timestep, mu, lowrank=lowrank, verbose=verbose) propagator.build(hamiltonian, trial=trial, walkers=walkers, diff --git a/ipie/addons/thermal/trial/mean_field.py b/ipie/addons/thermal/trial/mean_field.py index 7350a234..86fc508f 100644 --- a/ipie/addons/thermal/trial/mean_field.py +++ b/ipie/addons/thermal/trial/mean_field.py @@ -8,9 +8,9 @@ from ipie.addons.thermal.trial.one_body import OneBody class MeanField(OneBody): - def __init__(self, hamiltonian, nelec, beta, dt, options={}, H1=None, verbose=False): + def __init__(self, hamiltonian, nelec, beta, dt, options={}, alt_convention=False, H1=None, verbose=False): OneBody.__init__(self, hamiltonian, nelec, beta, dt, options=options, - H1=H1, verbose=verbose) + alt_convention=alt_convention, H1=H1, verbose=verbose) if verbose: print(" # Building THF density matrix.") @@ -45,7 +45,7 @@ def thermal_hartree_fock(self, hamiltonian, beta): scipy.linalg.expm(-dt * HMF[1])]) if self.find_mu: mu = find_chemical_potential( - hamiltonian._alt_convention, rho, dt, self.stack_length, self.nav, + self.alt_convention, rho, dt, self.stack_length, self.nav, deps=self.deps, max_it=self.max_it, verbose=self.verbose) else: diff --git a/ipie/addons/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py index d16f0dca..5ecb04c8 100644 --- a/ipie/addons/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -9,11 +9,12 @@ class OneBody(object): - def __init__(self, hamiltonian, nelec, beta, dt, options={}, nav=None, - H1=None, verbose=False): + def __init__(self, hamiltonian, nelec, beta, dt, options={}, + alt_convention=False, H1=None, verbose=False): self.name = "thermal" self.compute_trial_energy = False self.verbose = verbose + self.alt_convention = alt_convention if H1 is None: try: @@ -39,15 +40,10 @@ def __init__(self, hamiltonian, nelec, beta, dt, options={}, nav=None, print(f"# condition number of BT: {cond: 10e}") self.nelec = nelec + self.nav = options.get("nav", None) - if nav is not None: - self.nav = nav - - else: - self.nav = options.get("nav", None) - - if self.nav is None: - self.nav = numpy.sum(nelec) + if self.nav is None: + self.nav = numpy.sum(self.nelec) if verbose: print(f"# Target average electron number: {self.nav}") @@ -86,30 +82,29 @@ def __init__(self, hamiltonian, nelec, beta, dt, options={}, nav=None, print(f"# Number of stacks: {self.stack_length}") sign = 1 - if hamiltonian._alt_convention: + if self.alt_convention: if verbose: print("# Using alternate sign convention for chemical potential.") sign = -1 - dtau = self.nstack * dt - self.dtau = dtau + self.dtau = self.nstack * dt if self.mu is None: - self.rho = numpy.array([scipy.linalg.expm(-dtau * (self.H1[0])), - scipy.linalg.expm(-dtau * (self.H1[1]))]) + self.rho = numpy.array([scipy.linalg.expm(-self.dtau * (self.H1[0])), + scipy.linalg.expm(-self.dtau * (self.H1[1]))]) self.mu = find_chemical_potential( - hamiltonian._alt_convention, self.rho, dtau, self.stack_length, + self.alt_convention, self.rho, self.dtau, self.stack_length, self.nav, deps=self.deps, max_it=self.max_it, verbose=verbose) else: - self.rho = numpy.array([scipy.linalg.expm(-dtau * (self.H1[0])), - scipy.linalg.expm(-dtau * (self.H1[1]))]) + self.rho = numpy.array([scipy.linalg.expm(-self.dtau * (self.H1[0])), + scipy.linalg.expm(-self.dtau * (self.H1[1]))]) if self.verbose: print(f"# Chemical potential in trial density matrix: {self.mu: .10e}") - self.P = one_rdm_stable(compute_rho(self.rho, self.mu, dtau, sign=sign), self.stack_length) + self.P = one_rdm_stable(compute_rho(self.rho, self.mu, self.dtau, sign=sign), self.stack_length) self.nav = particle_number(self.P).real if self.verbose: diff --git a/ipie/addons/thermal/trial/tests/test_chem_pot.py b/ipie/addons/thermal/trial/tests/test_chem_pot.py index e0c4c243..749e9544 100644 --- a/ipie/addons/thermal/trial/tests/test_chem_pot.py +++ b/ipie/addons/thermal/trial/tests/test_chem_pot.py @@ -14,15 +14,15 @@ def test_find_chemical_potential(): stack_length = 20 nav = 7 nbsf = 14 - _alt_convention = False + alt_convention = False dtau = dt * nstack h1e = numpy.random.random((nbsf, nbsf)) rho = numpy.array([scipy.linalg.expm(-dtau * h1e), scipy.linalg.expm(-dtau * h1e)]) - mu = find_chemical_potential(_alt_convention, rho, dt, stack_length, nav) - legacy_mu = legacy_find_chemical_potential(_alt_convention, rho, dt, stack_length, nav) + mu = find_chemical_potential(alt_convention, rho, dt, stack_length, nav) + legacy_mu = legacy_find_chemical_potential(alt_convention, rho, dt, stack_length, nav) numpy.testing.assert_allclose(mu, legacy_mu) diff --git a/ipie/addons/thermal/trial/tests/test_mean_field.py b/ipie/addons/thermal/trial/tests/test_mean_field.py index 843b81ac..8d63056f 100644 --- a/ipie/addons/thermal/trial/tests/test_mean_field.py +++ b/ipie/addons/thermal/trial/tests/test_mean_field.py @@ -1,65 +1,43 @@ -import os import numpy import pytest -from pyscf import gto, scf, lo - from ipie.systems.generic import Generic -from ipie.hamiltonians.utils import get_hamiltonian +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.addons.thermal.trial.mean_field import MeanField -def setup_objs(): - nocca = 5 - noccb = 5 - nelec = nocca + noccb - r0 = 1.75 - mol = gto.M( - atom=[("H", i * r0, 0, 0) for i in range(nelec)], - basis='sto-6g', - unit='Bohr', - verbose=5) - +@pytest.mark.unit +def test_mean_field(): + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + mu = -10. - path = os.path.abspath(os.path.dirname(__file__)).split("trial")[0] + "/reference_data/generic/" - options = { - "hamiltonian": { - "name": "Generic", - "integrals": path + "generic_integrals.h5", - "_alt_convention": False, - "symmetry": False, - "sparse": False, - "mu": mu - }, - } + beta = 0.1 + timestep = 0.01 + + complex_integrals = True + verbose = True + sym = 8 + if complex_integrals: sym = 4 + # Test. print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - system = Generic(mol.nelec) - hamiltonian = get_hamiltonian(system, options["hamiltonian"]) - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] - objs = {'mol': mol, - 'hamiltonian': hamiltonian} - - return objs - - -@pytest.mark.unit -def test_mean_field(): - beta = 0.1 - dt = 0.01 - verbose = True - objs = setup_objs() - mol = objs['mol'] - hamiltonian = objs['hamiltonian'] - nbasis = hamiltonian.nbasis - trial = MeanField(hamiltonian, mol.nelec, beta, dt, verbose=verbose) - - assert trial.nelec == mol.nelec - numpy.testing.assert_almost_equal(trial.nav, numpy.sum(mol.nelec), decimal=6) + system = Generic(nelec) + h1e, chol, _, eri = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) + + assert trial.nelec == nelec + numpy.testing.assert_almost_equal(trial.nav, numpy.sum(nelec), decimal=6) assert trial.rho.shape == (2, nbasis, nbasis) assert trial.dmat.shape == (2, nbasis, nbasis) assert trial.P.shape == (2, nbasis, nbasis) diff --git a/ipie/addons/thermal/trial/tests/test_one_body.py b/ipie/addons/thermal/trial/tests/test_one_body.py index 4c27f6d7..4dd5b994 100644 --- a/ipie/addons/thermal/trial/tests/test_one_body.py +++ b/ipie/addons/thermal/trial/tests/test_one_body.py @@ -1,64 +1,43 @@ -import os import numpy import pytest -from pyscf import gto, scf, lo - from ipie.systems.generic import Generic -from ipie.hamiltonians.utils import get_hamiltonian +from ipie.utils.testing import generate_hamiltonian +from ipie.hamiltonians.generic import Generic as HamGeneric from ipie.addons.thermal.trial.one_body import OneBody -def setup_objs(): - nocca = 5 - noccb = 5 - nelec = nocca + noccb - r0 = 1.75 - mol = gto.M( - atom=[("H", i * r0, 0, 0) for i in range(nelec)], - basis='sto-6g', - unit='Bohr', - verbose=5) - - mu = -10. - path = os.path.abspath(os.path.dirname(__file__)).split("trial")[0] + "/reference_data/generic/" - options = { - "hamiltonian": { - "name": "Generic", - "integrals": path + "generic_integrals.h5", - "_alt_convention": False, - "symmetry": False, - "sparse": False, - "mu": mu - }, - } - - # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - system = Generic(mol.nelec) - hamiltonian = get_hamiltonian(system, options["hamiltonian"]) - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - objs = {'mol': mol, - 'hamiltonian': hamiltonian} - - return objs - - @pytest.mark.unit def test_one_body(): + nup = 5 + ndown = 5 + nelec = (nup, ndown) + nbasis = 10 + + mu = -1. beta = 0.1 - dt = 0.01 + timestep = 0.01 + + complex_integrals = True verbose = True - objs = setup_objs() - mol = objs['mol'] - hamiltonian = objs['hamiltonian'] - nbasis = hamiltonian.nbasis - trial = OneBody(hamiltonian, mol.nelec, beta, dt, verbose=verbose) - assert trial.nelec == mol.nelec - numpy.testing.assert_almost_equal(trial.nav, numpy.sum(mol.nelec), decimal=6) + sym = 8 + if complex_integrals: sym = 4 + + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + system = Generic(nelec) + h1e, chol, _, eri = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, + sym=sym, tol=1e-10) + hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), + chol=chol.reshape((-1, nbasis**2)).T.copy(), + ecore=0) + trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) + + assert trial.nelec == nelec + numpy.testing.assert_almost_equal(trial.nav, numpy.sum(nelec), decimal=6) assert trial.rho.shape == (2, nbasis, nbasis) assert trial.dmat.shape == (2, nbasis, nbasis) assert trial.P.shape == (2, nbasis, nbasis) diff --git a/ipie/addons/thermal/trial/utils.py b/ipie/addons/thermal/trial/utils.py index d9c47638..4ee3b6b6 100644 --- a/ipie/addons/thermal/trial/utils.py +++ b/ipie/addons/thermal/trial/utils.py @@ -2,7 +2,8 @@ from ipie.addons.thermal.trial.one_body import OneBody -def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, comm=None, verbose=False): +def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, + comm=None, verbose=False): """Wrapper to select trial wavefunction class. Parameters @@ -14,6 +15,7 @@ def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, comm=None Trial density matrix class. """ trial_type = options.get("name", "one_body") + alt_convention = options.get("alt_convention", False) if comm is None or comm.rank == 0: if trial_type == "one_body_mod": trial = OneBody( @@ -27,10 +29,12 @@ def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, comm=None ) elif trial_type == "one_body": - trial = OneBody(hamiltonian, nelec, beta, dt, options=options, verbose=verbose) + trial = OneBody(hamiltonian, nelec, beta, dt, options=options, + alt_convention=alt_convention, verbose=verbose) elif trial_type == "thermal_hartree_fock": - trial = MeanField(hamiltonian, nelec, beta, dt, options=options, verbose=verbose) + trial = MeanField(hamiltonian, nelec, beta, dt, options=options, + alt_convention=alt_convention, verbose=verbose) else: trial = None diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index b38eeddd..42939a49 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -40,13 +40,17 @@ def build_legacy_generic_test_case_handlers(hamiltonian, mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + nsteps_per_block = 1 + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) + alt_convention = options.get('alt_convention', False) + sparse = options.get('sparse', False) mf_trial = options.get('mf_trial', True) propagate = options.get('propagate', False) @@ -54,7 +58,9 @@ def build_legacy_generic_test_case_handlers(hamiltonian, legacy_options = { "walkers": { + "stack_size": nstack, "low_rank": lowrank, + "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, @@ -76,8 +82,9 @@ def build_legacy_generic_test_case_handlers(hamiltonian, legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + legacy_hamiltonian.mu = mu + legacy_hamiltonian._alt_convention = alt_convention + legacy_hamiltonian.sparse = sparse # 3. Build trial. legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, @@ -100,7 +107,7 @@ def build_legacy_generic_test_case_handlers(hamiltonian, # 5. Build propagator. legacy_propagator = Continuous( - options["propagator"], qmc_opts, legacy_system, + legacy_options["propagator"], qmc_opts, legacy_system, legacy_hamiltonian, legacy_trial, verbose=verbose, lowrank=lowrank) @@ -129,22 +136,28 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + nsteps_per_block = 1 + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) + alt_convention = options.get('alt_convention', False) + sparse = options.get('sparse', False) mf_trial = options.get('mf_trial', True) propagate = options.get('propagate', False) numpy.random.seed(seed) comm = mpi_handler.comm - + legacy_options = { "walkers": { + "stack_size": nstack, "low_rank": lowrank, + "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, @@ -153,7 +166,7 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, "optimised": False }, } - + # 1. Build system. legacy_system = Generic(nelec, verbose=verbose) legacy_system.mu = mu @@ -166,8 +179,9 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + legacy_hamiltonian.mu = mu + legacy_hamiltonian._alt_convention = alt_convention + legacy_hamiltonian.sparse = sparse # 3. Build trial. legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, @@ -190,7 +204,7 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, # 5. Build propagator. legacy_propagator = Continuous( - options["propagator"], qmc_opts, legacy_system, + legacy_options["propagator"], qmc_opts, legacy_system, legacy_hamiltonian, legacy_trial, verbose=verbose, lowrank=lowrank) @@ -220,12 +234,16 @@ def build_legacy_driver_generic_test_instance(hamiltonian, beta = options['beta'] timestep = options['timestep'] nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + nsteps_per_block = 1 + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) + alt_convention = options.get('alt_convention', False) + sparse = options.get('sparse', False) numpy.random.seed(seed) legacy_options = { @@ -248,7 +266,9 @@ def build_legacy_driver_generic_test_instance(hamiltonian, }, "walkers": { + "stack_size": nstack, "low_rank": lowrank, + "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, @@ -260,7 +280,6 @@ def build_legacy_driver_generic_test_instance(hamiltonian, "mu": mu }, - "hamiltonian": options["hamiltonian"], "estimators": options["estimators"] } @@ -269,13 +288,13 @@ def build_legacy_driver_generic_test_instance(hamiltonian, legacy_hamiltonian = LegacyHamGeneric( h1e=hamiltonian.H1, chol=hamiltonian.chol, - ecore=hamiltonian.ecore, - options=legacy_options["hamiltonian"]) + ecore=hamiltonian.ecore) legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] + legacy_hamiltonian.mu = mu + legacy_hamiltonian._alt_convention = alt_convention + legacy_hamiltonian.sparse = sparse legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep) afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, @@ -292,14 +311,17 @@ def build_legacy_ueg_test_case_handlers(hamiltonian, mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + nsteps_per_block = 1 + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) + alt_convention = options.get('alt_convention', False) - lowrank = options['lowrank'] propagate = options.get('propagate', False) numpy.random.seed(seed) @@ -309,7 +331,9 @@ def build_legacy_ueg_test_case_handlers(hamiltonian, }, "walkers": { + "stack_size": nstack, "low_rank": lowrank, + "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, @@ -321,8 +345,8 @@ def build_legacy_ueg_test_case_handlers(hamiltonian, # 2. Build Hamiltonian. legacy_hamiltonian = LegacyHamUEG(legacy_system, options=options["ueg_opts"]) - legacy_hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = options["hamiltonian"]["mu"] + legacy_hamiltonian.mu = mu + legacy_hamiltonian._alt_convention = alt_convention # 3. Build trial. legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) @@ -367,13 +391,16 @@ def build_legacy_driver_ueg_test_instance(hamiltonian, mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + nsteps_per_block = 1 + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) + alt_convention = options.get('alt_convention', False) numpy.random.seed(seed) legacy_options = { @@ -396,13 +423,14 @@ def build_legacy_driver_ueg_test_instance(hamiltonian, }, "walkers": { + "stack_size": nstack, "low_rank": lowrank, + "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, "ueg_opts": options["ueg_opts"], - "hamiltonian": options["hamiltonian"], "estimators": options["estimators"] } @@ -412,8 +440,8 @@ def build_legacy_driver_ueg_test_instance(hamiltonian, # 2. Build Hamiltonian. legacy_hamiltonian = LegacyHamUEG(legacy_system, options=legacy_options["ueg_opts"]) - legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] + legacy_hamiltonian.mu = mu + legacy_hamiltonian._alt_convention = alt_convention # 3. Build trial. legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) diff --git a/ipie/addons/thermal/utils/testing.py b/ipie/addons/thermal/utils/testing.py index 8bda8eff..8cfabe76 100644 --- a/ipie/addons/thermal/utils/testing.py +++ b/ipie/addons/thermal/utils/testing.py @@ -2,8 +2,6 @@ import pytest from typing import Union -from ipie.qmc.options import QMCOpts -from ipie.systems.generic import Generic from ipie.utils.mpi import MPIHandler from ipie.utils.testing import generate_hamiltonian from ipie.hamiltonians.generic import Generic as HamGeneric @@ -28,13 +26,14 @@ def build_generic_test_case_handlers(options: dict, mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) complex_integrals = options.get('complex_integrals', True) mf_trial = options.get('mf_trial', True) @@ -56,9 +55,6 @@ def build_generic_test_case_handlers(options: dict, hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nbasis**2)).T.copy(), ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] # 3. Build trial. trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) @@ -67,8 +63,9 @@ def build_generic_test_case_handlers(options: dict, trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) # 4. Build walkers. - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) + walkers = UHFThermalWalkers( + trial, nbasis, nwalkers, nstack=nstack, lowrank=lowrank, + lowrank_thresh=lowrank_thresh, verbose=verbose) # 5. Build propagator. propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) @@ -100,13 +97,14 @@ def build_generic_test_case_handlers_mpi(options: dict, mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) complex_integrals = options.get('complex_integrals', True) mf_trial = options.get('mf_trial', True) @@ -128,9 +126,6 @@ def build_generic_test_case_handlers_mpi(options: dict, hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nbasis**2)).T.copy(), ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] # 3. Build trial. trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) @@ -139,8 +134,9 @@ def build_generic_test_case_handlers_mpi(options: dict, trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) # 4. Build walkers. - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - mpi_handler=mpi_handler, verbose=verbose) + walkers = UHFThermalWalkers( + trial, nbasis, nwalkers, nstack=nstack, lowrank=lowrank, + lowrank_thresh=lowrank_thresh, mpi_handler=mpi_handler, verbose=verbose) # 5. Build propagator. propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) @@ -168,14 +164,16 @@ def build_driver_generic_test_instance(options: Union[dict, None], mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] - complex_integrals = options['complex_integrals'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) + + complex_integrals = options.get('complex_integrals', True) diagonal = options.get('diagonal', False) sym = 8 @@ -193,19 +191,17 @@ def build_driver_generic_test_instance(options: Union[dict, None], hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nbasis**2)).T.copy(), ecore=0) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] # 3. Build trial. trial = MeanField(hamiltonian, nelec, beta, timestep) # 4. Build Thermal AFQMC driver. afqmc = ThermalAFQMC.build( - nelec, mu, beta, hamiltonian, trial, nwalkers, seed, - nblocks=nblocks, timestep=timestep, stabilize_freq=stabilize_freq, - pop_control_freq=pop_control_freq, pop_control_method=pop_control_method, - lowrank=lowrank, debug=debug, verbose=verbose) + nelec, mu, beta, hamiltonian, trial, nwalkers=nwalkers, + nstack=nstack, seed=seed, nblocks=nblocks, timestep=timestep, + stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, lowrank=lowrank, + lowrank_thresh=lowrank_thresh, debug=debug, verbose=verbose) return afqmc @@ -219,14 +215,15 @@ def build_ueg_test_case_handlers(options: dict, mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - - lowrank = options['lowrank'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 101) + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) + propagate = options.get('propagate', False) numpy.random.seed(seed) @@ -254,16 +251,14 @@ def build_ueg_test_case_handlers(options: dict, numpy.array(chol, dtype=numpy.complex128), ecore, verbose=verbose) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] # 3. Build trial. trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) # 4. Build walkers. - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank, - verbose=verbose) + walkers = UHFThermalWalkers( + trial, nbasis, nwalkers, nstack=nstack, lowrank=lowrank, + lowrank_thresh=lowrank_thresh, verbose=verbose) # 5. Build propagator. propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank, verbose=verbose) @@ -290,13 +285,14 @@ def build_driver_ueg_test_instance(options: Union[dict, None], mu = options['mu'] beta = options['beta'] timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] + nwalkers = options.get('nwalkers', 100) + nstack = options.get('nstack', 10) + nblocks = options.get('nblocks', 100) + stabilize_freq = options.get('stabilize_freq', 5) + pop_control_freq = options.get('pop_control_freq', 1) + pop_control_method = options.get('pop_control_method', 'pair_branch') + lowrank = options.get('lowrank', False) + lowrank_thresh = options.get('lowrank_thresh', 1e-6) numpy.random.seed(seed) # 1. Generate UEG integrals. @@ -323,18 +319,16 @@ def build_driver_ueg_test_instance(options: Union[dict, None], numpy.array(chol, dtype=numpy.complex128), ecore, verbose=verbose) - hamiltonian.name = options["hamiltonian"]["name"] - hamiltonian._alt_convention = options["hamiltonian"]["_alt_convention"] - hamiltonian.sparse = options["hamiltonian"]["sparse"] # 3. Build trial. trial = OneBody(hamiltonian, nelec, beta, timestep, verbose=verbose) # 4. Build Thermal AFQMC driver. afqmc = ThermalAFQMC.build( - nelec, mu, beta, hamiltonian, trial, nwalkers, seed, - nblocks=nblocks, timestep=timestep, stabilize_freq=stabilize_freq, - pop_control_freq=pop_control_freq, pop_control_method=pop_control_method, - lowrank=lowrank, debug=debug, verbose=verbose) + nelec, mu, beta, hamiltonian, trial, nwalkers=nwalkers, + nstack=nstack, seed=seed, nblocks=nblocks, timestep=timestep, + stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, lowrank=lowrank, + lowrank_thresh=lowrank_thresh, debug=debug, verbose=verbose) return afqmc diff --git a/ipie/addons/thermal/walkers/tests/test_population_control.py b/ipie/addons/thermal/walkers/tests/test_population_control.py index 94217b21..ab03416a 100644 --- a/ipie/addons/thermal/walkers/tests/test_population_control.py +++ b/ipie/addons/thermal/walkers/tests/test_population_control.py @@ -60,18 +60,6 @@ def test_pair_branch_batch(): 'complex_integrals': complex_integrals, 'mf_trial': mf_trial, 'propagate': propagate, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } # Test. @@ -184,18 +172,6 @@ def test_pair_branch_batch_lowrank(): 'mf_trial': mf_trial, 'propagate': propagate, 'diagonal': diagonal, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } # Test. @@ -304,18 +280,6 @@ def test_comb_batch(): 'complex_integrals': complex_integrals, 'mf_trial': mf_trial, 'propagate': propagate, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } # Test. @@ -427,18 +391,6 @@ def test_comb_batch_lowrank(): 'mf_trial': mf_trial, 'propagate': propagate, 'diagonal': diagonal, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } # Test. diff --git a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py index 36ac5952..b8bf759a 100644 --- a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py @@ -62,18 +62,6 @@ def test_thermal_walkers_fullrank(): 'complex_integrals': complex_integrals, 'mf_trial': mf_trial, 'propagate': propagate, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } # Test. @@ -167,18 +155,6 @@ def test_thermal_walkers_lowrank(): 'mf_trial': mf_trial, 'propagate': propagate, 'diagonal': diagonal, - - "hamiltonian": { - "name": "Generic", - "_alt_convention": False, - "sparse": False, - "mu": mu - }, - - "propagator": { - "optimised": False, - "free_projection": False - }, } # Test. @@ -224,4 +200,4 @@ def test_thermal_walkers_lowrank(): if __name__ == "__main__": test_thermal_walkers_fullrank() - test_thermal_walkers_lowrank() + #test_thermal_walkers_lowrank() diff --git a/ipie/addons/thermal/walkers/uhf_walkers.py b/ipie/addons/thermal/walkers/uhf_walkers.py index 640a8eaf..51932fcb 100644 --- a/ipie/addons/thermal/walkers/uhf_walkers.py +++ b/ipie/addons/thermal/walkers/uhf_walkers.py @@ -40,7 +40,7 @@ def __init__( if self.nstack > trial.nstack: if verbose: - print("# Walker stack size differs from that estimated from " "Trial density matrix.") + print("# Walker stack size differs from that estimated from trial density matrix.") print(f"# Be careful. cond(BT)**nstack: {trial.cond ** self.nstack:10.3e}.") self.stack_length = self.nslice // self.nstack diff --git a/ipie/qmc/options.py b/ipie/qmc/options.py index 245231bb..d77dee31 100644 --- a/ipie/qmc/options.py +++ b/ipie/qmc/options.py @@ -62,6 +62,8 @@ class QMCOpts(object): Frequency of Gram-Schmidt orthogonalisation steps. npop_control : int Frequency of population control. + pop_control_method : int + Population control method. temp : float Temperature. Currently not used. nequilibrate : int @@ -133,6 +135,13 @@ def __init__(self, inputs={}, verbose=False): alias=["npop_control", "pop_control"], verbose=verbose, ) + self.pop_control_method = get_input_value( + inputs, + "pop_control_method", + default="pair_branch", + alias=["pop_control", "population_control"], + verbose=verbose, + ) self.eqlb_time = get_input_value( inputs, "equilibration_time", @@ -148,6 +157,12 @@ def __init__(self, inputs={}, verbose=False): alias=["random_seed", "seed"], verbose=verbose, ) + self.mu = get_input_value( + inputs, + "mu", + default=None, + verbose=verbose, + ) self.beta = get_input_value( inputs, "beta", diff --git a/ipie/walkers/pop_controller.py b/ipie/walkers/pop_controller.py index 0a961c73..f69bc021 100644 --- a/ipie/walkers/pop_controller.py +++ b/ipie/walkers/pop_controller.py @@ -281,14 +281,11 @@ def comb(walkers, comm, weights, target_weight, timer=PopControllerTimer()): buffer = walkers.walker_buffer timer.add_non_communication() timer.start_time() - if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): buffer = numpy.concatenate((walkers.walker_buffer, walkers.stack[0].stack_buffer)) comm.Recv(buffer, source=source_proc, tag=i) - else: comm.Recv(buffer, source=source_proc, tag=i) - # with h5py.File('walkers_recv.h5', 'w') as fh5: # fh5['walk_{}'.format(k)] = walkers.walker_buffer.copy() timer.add_recv_time() @@ -424,12 +421,17 @@ def pair_branch(walkers, comm, max_weight, min_weight, timer=PopControllerTimer( if walker[1] == 0: timer.start_time() tag = walker[3] * walkers.nwalkers + comm.rank + buffer = walkers.walker_buffer timer.add_non_communication() timer.start_time() - comm.Recv(walkers.walker_buffer, source=int(round(walker[3])), tag=tag) + if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): + buffer = numpy.concatenate((walkers.walker_buffer, walkers.stack[0].stack_buffer)) + comm.Recv(buffer, source=int(round(walker[3])), tag=tag) + else: + comm.Recv(buffer, source=int(round(walker[3])), tag=tag) timer.add_recv_time() timer.start_time() - set_buffer(walkers, iw, walkers.walker_buffer) + set_buffer(walkers, iw, buffer) timer.add_non_communication() timer.start_time() for r in reqs: From 1518800af72015dbabceb6cef37d069c1e5d60db Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Mon, 11 Mar 2024 20:56:05 -0400 Subject: [PATCH 54/84] Add thermal AFQMC example and analysis code. --- examples/14-ft_afqmc/run_afqmc.py | 8 +- ipie/addons/thermal/analysis/extraction.py | 51 ++++++ .../thermal/analysis/thermal_analysis.py | 150 ++++++++++++++++++ ipie/addons/thermal/qmc/calc.py | 3 - 4 files changed, 203 insertions(+), 9 deletions(-) create mode 100644 ipie/addons/thermal/analysis/extraction.py create mode 100644 ipie/addons/thermal/analysis/thermal_analysis.py diff --git a/examples/14-ft_afqmc/run_afqmc.py b/examples/14-ft_afqmc/run_afqmc.py index 7bbab293..e4279413 100644 --- a/examples/14-ft_afqmc/run_afqmc.py +++ b/examples/14-ft_afqmc/run_afqmc.py @@ -39,14 +39,13 @@ }, 'qmc': { - #'mu': 0.211636, 'mu': 0.133579, 'beta': 10, 'timestep': 0.05, - 'nwalkers': 12 // comm.size, + 'nwalkers': 576 // comm.size, 'nstack': 10, 'seed': 7, - 'nblocks': 30, + 'nblocks': 200, }, } @@ -68,9 +67,6 @@ afqmc.finalise() afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) -energy_data = None -number_data = None - if comm.rank == 0: energy_data = extract_observable(afqmc.estimators.filename, "energy") number_data = extract_observable(afqmc.estimators.filename, "nav") diff --git a/ipie/addons/thermal/analysis/extraction.py b/ipie/addons/thermal/analysis/extraction.py new file mode 100644 index 00000000..ef327ff3 --- /dev/null +++ b/ipie/addons/thermal/analysis/extraction.py @@ -0,0 +1,51 @@ +import json + +import h5py +import numpy +import pandas as pd + +from ipie.utils.misc import get_from_dict +def set_info(frame, md): + ncols = len(frame.columns) + system = md.get("system") + hamiltonian = md.get("hamiltonian") + trial = md.get("trial") + qmc = md.get("params") + fp = get_from_dict(md, ["propagators", "free_projection"]) + bp = get_from_dict(md, ["estimates", "estimates", "back_prop"]) + + beta = qmc.get("beta") + br = qmc.get("beta_scaled") + + ints = system.get("integral_file") + chol = system.get("threshold") + + frame["nup"] = system.get("nup") + frame["ndown"] = system.get("ndown") + frame["mu"] = qmc.get("mu") + frame["beta"] = qmc.get("beta") + frame["dt"] = qmc.get("timestep") + frame["ntot_walkers"] = qmc.get("total_num_walkers", 0) + frame["nbasis"] = hamiltonian.get("nbasis", 0) + + if trial is not None: + frame["mu_T"] = trial.get("mu") + frame["Nav_T"] = trial.get("nav") + + if fp is not None: + frame["free_projection"] = fp + + if bp is not None: + frame["tau_bp"] = bp["tau_bp"] + + if br is not None: + frame["beta_red"] = br + + if ints is not None: + frame["integrals"] = ints + + if chol is not None: + frame["cholesky_treshold"] = chol + + return list(frame.columns[ncols:]) + diff --git a/ipie/addons/thermal/analysis/thermal_analysis.py b/ipie/addons/thermal/analysis/thermal_analysis.py new file mode 100644 index 00000000..01f2e12e --- /dev/null +++ b/ipie/addons/thermal/analysis/thermal_analysis.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python + +import sys +import argparse +import pprint + +import json +import glob +import numpy +import scipy.optimize +import pandas as pd + +from ipie.analysis.blocking import ( + average_ratio + ) +from ipie.analysis.extraction import ( + extract_observable, + get_metadata, + get_sys_param + ) + +from ipie.addons.thermal.analysis.extraction import set_info + + +def parse_args(args): + """Parse command-line arguments. + + Parameters + ---------- + args : list of strings + command-line arguments. + + Returns + ------- + options : :class:`argparse.ArgumentParser` + Command line arguments. + """ + + parser = argparse.ArgumentParser(description = __doc__) + parser.add_argument('-c', '--chem-pot', dest='fit_chem_pot', + action='store_true', default=False, + help='Estimate optimal chemical potential') + parser.add_argument('-n', '--nav', dest='nav', type=float, + help='Target electron density.') + parser.add_argument('-o', '--order', dest='order', type=int, + default=3, help='Order polynomial to fit.') + parser.add_argument('-p', '--plot', dest='plot', action='store_true', + help='Plot density vs. mu.') + parser.add_argument('-f', nargs='+', dest='filenames', + help='Space-separated list of files to analyse.') + + options = parser.parse_args(args) + + if not options.filenames: + parser.print_help() + sys.exit(1) + + return options + + +def analyse(files, block_idx=1): + sims = [] + files = sorted(files) + + for f in files: + data_energy = extract_observable(f, name='energy', block_idx=block_idx) + data_nav = extract_observable(f, name='nav', block_idx=block_idx) + data = pd.concat([data_energy, data_nav['Nav']], axis=1) + md = get_metadata(f) + keys = set_info(data, md) + sims.append(data[1:]) + + full = pd.concat(sims).groupby(keys, sort=False) + + analysed = [] + for i, g in full: + cols = ["ETotal", "E1Body", "E2Body", "Nav"] + averaged = pd.DataFrame(index=[0]) + + for c in cols: + mean = numpy.real(g[c].values).mean() + error = scipy.stats.sem(numpy.real(g[c].values), ddof=1) + averaged[c] = [mean] + averaged[c + "_error"] = [error] + + for k, v in zip(full.keys, i): + averaged[k] = v + + analysed.append(averaged) + + return pd.concat(analysed).reset_index(drop=True).sort_values(by=keys) + + +def nav_mu(mu, coeffs): + return numpy.polyval(coeffs, mu) + + +def find_chem_pot(data, target, vol, order=3, plot=False): + print(f"# System volume: {vol}.") + print(f"# Target number of electrons: {vol * target}.") + nav = data.Nav.values / vol + nav_error = data.Nav_error.values / vol + # Half filling special case where error bar is zero. + zeros = numpy.where(nav_error == 0)[0] + nav_error[zeros] = 1e-8 + mus = data.mu.values + delta = nav - target + s = 0 + e = len(delta) + rmin = None + +def main(args): + """Run reblocking and data analysis on PAUXY output. + + Parameters + ---------- + args : list of strings + command-line arguments. + + Returns + ------- + None. + """ + + options = parse_args(args) + if '*' in options.filenames[0]: + files = glob.glob(options.filenames[0]) + + else: + files = options.filenames + + data = analyse(files) + + if options.fit_chem_pot: + name = get_sys_param(files[0], 'name') + vol = 1. + mu = find_chem_pot(data, options.nav, vol, + order=options.order, plot=options.plot) + + if mu is not None: + print("# Optimal chemical potential found to be: {}.".format(mu)) + + else: + print("# Failed to find chemical potential.") + + print(data.to_string(index=False)) + + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index bcea879b..0a1d35ab 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -125,7 +125,6 @@ def build_thermal_afqmc_driver( comm, nelec: tuple, hamiltonian_file: str = "hamiltonian.h5", - estimator_filename: str = "estimates.0.h5", seed: int = None, options: dict = None, verbosity: int = 0, @@ -136,10 +135,8 @@ def build_thermal_afqmc_driver( sys_opts = {"nup": nelec[0], "ndown": nelec[1]} ham_opts = {"integrals": hamiltonian_file} qmc_opts = {"rng_seed": seed} - est_opts = {"overwrite": True, "filename": estimator_filename} options["system"] = sys_opts - options["estimators"] = est_opts options["hamiltonian"] = ham_opts options["qmc"].update(qmc_opts) From 21d6876b1eaa19bd6fc33e1d48b84693c69da568 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Tue, 12 Mar 2024 12:36:09 -0400 Subject: [PATCH 55/84] Fix `pylint` errors --- ipie/addons/thermal/estimators/generic.py | 6 +----- ipie/addons/thermal/estimators/thermal.py | 3 +++ ipie/addons/thermal/propagation/phaseless_base.py | 5 +++-- ipie/addons/thermal/propagation/phaseless_generic.py | 3 +-- ipie/addons/thermal/qmc/calc.py | 2 ++ ipie/addons/thermal/qmc/thermal_afqmc.py | 2 ++ ipie/addons/thermal/trial/one_body.py | 4 +--- 7 files changed, 13 insertions(+), 12 deletions(-) diff --git a/ipie/addons/thermal/estimators/generic.py b/ipie/addons/thermal/estimators/generic.py index 82d763d9..179cbcf5 100644 --- a/ipie/addons/thermal/estimators/generic.py +++ b/ipie/addons/thermal/estimators/generic.py @@ -17,7 +17,6 @@ def local_energy_generic_pno( UVT=None, ): na, nb = nelec - M = hamiltonian.nbasis UVT_aa = UVT[0] UVT_bb = UVT[1] @@ -199,10 +198,6 @@ def local_energy_generic_cholesky_opt_batched( for widx in range(nwalker): e1b = numpy.sum(hamiltonian.H1[0] * Ga_batch[widx]) + numpy.sum(hamiltonian.H1[1] * Gb_batch[widx]) e1_vec[widx] = e1b - nbasis = hamiltonian.nbasis - if rchola is not None: - naux = rchola.shape[0] - Xa = rchola.dot(Ghalfa_batch[widx].ravel()) Xb = rcholb.dot(Ghalfb_batch[widx].ravel()) ecoul = numpy.dot(Xa, Xa) @@ -458,6 +453,7 @@ def local_energy_generic_cholesky_opt(hamiltonian, nelec, Ga, Gb, Ghalfa=None, G if is_cupy( rchola ): # if even one array is a cupy array we should assume the rest is done with cupy + # pylint: disable=import-error import cupy assert cupy.is_available() diff --git a/ipie/addons/thermal/estimators/thermal.py b/ipie/addons/thermal/estimators/thermal.py index a7e8c4e7..89bda7d2 100644 --- a/ipie/addons/thermal/estimators/thermal.py +++ b/ipie/addons/thermal/estimators/thermal.py @@ -1,6 +1,9 @@ import numpy import scipy.linalg +def fermi_factor(ek, beta, mu): + return 1.0 / (numpy.exp(beta * (ek - mu)) + 1.0) + def one_rdm_from_G(G): r"""Compute one-particle reduced density matrix from Green's function. diff --git a/ipie/addons/thermal/propagation/phaseless_base.py b/ipie/addons/thermal/propagation/phaseless_base.py index 54c63ace..ed3fad1d 100644 --- a/ipie/addons/thermal/propagation/phaseless_base.py +++ b/ipie/addons/thermal/propagation/phaseless_base.py @@ -56,7 +56,7 @@ def construct_mean_field_shift(hamiltonian: GenericComplexChol, trial): class PhaselessBase(ContinuousBase): """A base class for generic continuous HS transform FT-AFQMC propagators.""" - def __init__(self, timestep, mu, lowrank=False, verbose=False): + def __init__(self, timestep, mu, lowrank=False, exp_nmax=6, verbose=False): super().__init__(timestep, verbose=verbose) self.mu = mu self.sqrt_dt = self.dt**0.5 @@ -67,6 +67,7 @@ def __init__(self, timestep, mu, lowrank=False, verbose=False): self.fbbound = 1.0 self.mpi_handler = None self.lowrank = lowrank + self.exp_nmax = exp_nmax def build(self, hamiltonian, trial=None, walkers=None, mpi_handler=None, verbose=False): @@ -275,7 +276,7 @@ def update_weight_legacy(self, walkers, iw, G, cfb, cmf, eshift): try: # Could save M0 rather than recompute. oratio = (M0a * M0b) / (Mnewa * Mnewb) - # Might want to cap this at some point + # Might want to cap this at some point. hybrid_energy = cmath.log(oratio) + _cfb + _cmf Q = cmath.exp(hybrid_energy) #hybrid_energy = -(cmath.log(oratio) + _cfb + _cmf) / self.dt diff --git a/ipie/addons/thermal/propagation/phaseless_generic.py b/ipie/addons/thermal/propagation/phaseless_generic.py index 2f2eb40b..994c0bc6 100644 --- a/ipie/addons/thermal/propagation/phaseless_generic.py +++ b/ipie/addons/thermal/propagation/phaseless_generic.py @@ -17,8 +17,7 @@ class PhaselessGeneric(PhaselessBase): """A class for performing phaseless propagation with real, generic, hamiltonian.""" def __init__(self, time_step, mu, exp_nmax=6, lowrank=False, verbose=False): - super().__init__(time_step, mu, lowrank=lowrank, verbose=verbose) - self.exp_nmax = exp_nmax + super().__init__(time_step, mu, lowrank=lowrank, exp_nmax=exp_nmax, verbose=verbose) @plum.dispatch def construct_VHS(self, hamiltonian: GenericRealChol, xshifted: xp.ndarray): diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index 0a1d35ab..eb59a26e 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -55,6 +55,7 @@ def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: verbosity = 0 lowrank = get_input_value(wlk_opts, "lowrank", default=False, alias=["low_rank"], verbose=verbosity) batched = get_input_value(qmc_opts, "batched", default=False, verbose=verbosity) + debug = get_input_value(qmc_opts, "debug", default=False, verbose=verbosity) if (lowrank == True) or (batched == True): raise ValueError("Option not supported in thermal code.") @@ -115,6 +116,7 @@ def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: walkers, propagator, params, + debug=debug, verbose=(verbosity and comm.rank == 0), ) diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 7ec70529..98be0421 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -58,6 +58,8 @@ def __init__(self, verbose: bool = False): super().__init__(system, hamiltonian, trial, walkers, propagator, params, verbose) self.debug = debug + if self.debug: + print('# Using legacy `update_weights`.') @staticmethod def build( diff --git a/ipie/addons/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py index 5ecb04c8..ba30f2ec 100644 --- a/ipie/addons/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -59,9 +59,7 @@ def __init__(self, hamiltonian, nelec, beta, dt, options={}, if verbose: print("# Estimating stack size from BT.") - eigs, ev = scipy.linalg.eigh(self.dmat[0]) - emax = numpy.max(eigs) - emin = numpy.min(eigs) + eigs, _ = scipy.linalg.eigh(self.dmat[0]) self.cond = numpy.linalg.cond(self.dmat[0]) # We will end up multiplying many BTs together. Can roughly determine # safe stack size from condition number of BT as the condition number of From 5816762c2f7012f81c4d6030f677e84e11a57f1f Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Tue, 12 Mar 2024 16:56:23 -0400 Subject: [PATCH 56/84] Restore `ipie/estimators` to `develop` --- ipie/addons/thermal/estimators/energy.py | 1 - ipie/addons/thermal/estimators/generic.py | 495 +----------------- .../addons/thermal/estimators/local_energy.py | 87 +-- .../thermal/estimators/particle_number.py | 1 - .../estimators/tests/test_estimators.py | 2 +- .../estimators/tests/test_generic_complex.py | 11 +- .../thermal/trial/tests/test_mean_field.py | 2 +- ipie/estimators/energy.py | 4 +- ipie/estimators/estimator_base.py | 10 +- ipie/estimators/generic.py | 146 +++--- ipie/estimators/handler.py | 6 +- ipie/estimators/local_energy.py | 4 +- ipie/estimators/local_energy_wicks.py | 40 +- ipie/estimators/tests/test_estimators.py | 21 +- ipie/estimators/tests/test_generic.py | 24 +- ipie/estimators/tests/test_generic_batch.py | 81 +-- ipie/estimators/tests/test_generic_chunked.py | 20 +- .../tests/test_generic_chunked_gpu.py | 24 +- ipie/estimators/tests/test_generic_complex.py | 26 +- ipie/estimators/tests/test_generic_noci.py | 50 +- ipie/estimators/tests/test_generic_phmsd.py | 217 ++++---- ipie/utils/testing.py | 27 +- 22 files changed, 410 insertions(+), 889 deletions(-) diff --git a/ipie/addons/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py index f449ebbf..9321ef28 100644 --- a/ipie/addons/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -15,7 +15,6 @@ # Author: Fionn Malone # -import plum import numpy from ipie.utils.backend import arraylib as xp diff --git a/ipie/addons/thermal/estimators/generic.py b/ipie/addons/thermal/estimators/generic.py index 179cbcf5..45c99c92 100644 --- a/ipie/addons/thermal/estimators/generic.py +++ b/ipie/addons/thermal/estimators/generic.py @@ -4,224 +4,8 @@ from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol -def local_energy_generic_pno( - hamiltonian, - nelec, - G, - Ghalf=None, - eri=None, - C0=None, - ecoul0=None, - exxa0=None, - exxb0=None, - UVT=None, -): - na, nb = nelec - - UVT_aa = UVT[0] - UVT_bb = UVT[1] - UVT_ab = UVT[2] - - Ga, Gb = Ghalf[0], Ghalf[1] - - # Element wise multiplication. - e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) - - eJaa = 0.0 - eKaa = 0.0 - - if len(C0.shape) == 3: - CT = C0[0, :, :].T - else: - CT = C0[:, :].T - - GTa = CT[:na, :] # hard-coded to do single slater - GTb = CT[na:, :] # hard-coded to do single slater - - for (i, j), (U, VT) in zip(hamiltonian.ij_list_aa, UVT_aa): - if i == j: - c = 0.5 - else: - c = 1.0 - - theta_i = Ga[i, :] - theta_j = Ga[j, :] - - thetaT_i = GTa[i, :] - thetaT_j = GTa[j, :] - - thetaU = numpy.einsum("p,pk->k", theta_i, U) - thetaV = numpy.einsum("p,kp->k", theta_j, VT) - - thetaTU = numpy.einsum("p,pk->k", thetaT_i, U) - thetaTV = numpy.einsum("p,kp->k", thetaT_j, VT) - - eJaa += c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) - - thetaU = numpy.einsum("p,pk->k", theta_j, U) - thetaV = numpy.einsum("p,kp->k", theta_i, VT) - thetaTU = numpy.einsum("p,pk->k", thetaT_j, U) - thetaTV = numpy.einsum("p,kp->k", thetaT_i, VT) - eKaa -= c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) - - eJbb = 0.0 - eKbb = 0.0 - - for (i, j), (U, VT) in zip(hamiltonian.ij_list_bb, UVT_bb): - if i == j: - c = 0.5 - else: - c = 1.0 - - theta_i = Gb[i, :] - theta_j = Gb[j, :] - thetaT_i = GTb[i, :] - thetaT_j = GTb[j, :] - - thetaU = numpy.einsum("p,pk->k", theta_i, U) - thetaV = numpy.einsum("p,kp->k", theta_j, VT) - thetaTU = numpy.einsum("p,pk->k", thetaT_i, U) - thetaTV = numpy.einsum("p,kp->k", thetaT_j, VT) - eJbb += c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) - - thetaU = numpy.einsum("p,pk->k", theta_j, U) - thetaV = numpy.einsum("p,kp->k", theta_i, VT) - thetaTU = numpy.einsum("p,pk->k", thetaT_j, U) - thetaTV = numpy.einsum("p,kp->k", thetaT_i, VT) - eKbb -= c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV)) - - eJab = 0.0 - for (i, j), (U, VT) in zip(hamiltonian.ij_list_ab, UVT_ab): - theta_i = Ga[i, :] - theta_j = Gb[j, :] - thetaT_i = GTa[i, :] - thetaT_j = GTb[j, :] - thetaU = numpy.einsum("p,pk->k", theta_i, U) - thetaV = numpy.einsum("p,kp->k", theta_j, VT) - thetaTU = numpy.einsum("p,pk->k", thetaT_i, U) - thetaTV = numpy.einsum("p,kp->k", thetaT_j, VT) - eJab += numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV) - - e2b = 0.5 * (ecoul0 - exxa0 - exxb0) + eJaa + eJbb + eJab + eKaa + eKbb - return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) - - -def _exx_compute_batch(rchol_a, rchol_b, GaT_stacked, GbT_stacked, lwalker): - """ - Internal function for computing exchange two-electron integral energy - of batched walkers. The stacked batching ends up being about 30% faster - than simple loop over walkers. - - Parameters - ---------- - rchol_a: :class:`numpy.ndarray` - alpha-spin half-rotated cholesky vectors that are (naux, nalpha, nbasis) - rchol_b: :class:`numpy.ndarray` - beta-spin half-rotated cholesky vectors that are (naux, nbeta, nbasis) - GaT_stacked: :class:`numpy.ndarray` - alpha-spin half-rotated Greens function of size (nbasis, nalpha * nwalker) - GbT_stacked: :class:`numpy.ndarray` - beta-spin half-rotated Greens function of size (nbasis, nbeta * nwalker) - Returns - ------- - exx: numpy.ndarary - vector of exchange contributions for each walker - """ - naux = rchol_a.shape[0] - nbasis = GaT_stacked.shape[0] - nalpha = GaT_stacked.shape[1] // lwalker - nbeta = GbT_stacked.shape[1] // lwalker - - exx_vec_a = numpy.zeros(lwalker, dtype=numpy.complex128) - exx_vec_b = numpy.zeros(lwalker, dtype=numpy.complex128) - - # Ta = numpy.zeros((nalpha, nalpha * lwalker), dtype=numpy.complex128) - # Tb = numpy.zeros((nbeta, nbeta * lwalker), dtype=numpy.complex128) - - # Writing this way so in the future we can vmap of naux index of rchol_a - for x in range(naux): - rmi_a = rchol_a[x].reshape((nalpha, nbasis)) # can we get rid of this? - Ta = rmi_a.dot(GaT_stacked) # (na, na x nwalker) - # Ta = rmi_a.real.dot(GaT_stacked.real) + 1j * rmi_a.real.dot(GaT_stacked.imag) - rmi_b = rchol_b[x].reshape((nbeta, nbasis)) - Tb = rmi_b.dot(GbT_stacked) # (nb, nb x nwalker) - # Tb = rmi_b.real.dot(GbT_stacked.real) + 1j * rmi_b.real.dot(GbT_stacked.imag) - Ta = Ta.reshape((nalpha, lwalker, nalpha)) # reshape into 3-tensor for tdot - Tb = Tb.reshape((nbeta, lwalker, nbeta)) - exx_vec_a += numpy.einsum("ikj,jki->k", Ta, Ta, optimize=True) - exx_vec_b += numpy.einsum("ikj,jki->k", Tb, Tb, optimize=True) - return exx_vec_b + exx_vec_a - - -def local_energy_generic_cholesky_opt_batched( - hamiltonian, - Ga_batch: numpy.ndarray, - Gb_batch: numpy.ndarray, - Ghalfa_batch: numpy.ndarray, - Ghalfb_batch: numpy.ndarray, - rchola: numpy.ndarray, - rcholb: numpy.ndarray, -): - r"""Calculate local for generic two-body hamiltonian. - - This uses the cholesky decomposed two-electron integrals. and batched - walkers. The intended use is CPU batching where walker G functions are - stacked so we can use gemm on bigger arrays. - - Parameters - ---------- - hamiltonian : :class:`Abinitio` - Contains necessary hamiltonian information - Ga_batched : :class:`numpy.ndarray` - alpha-spin Walker's "green's function" 3-tensor (nwalker, nbasis, nbasis) - Gb_batched : :class:`numpy.ndarray` - beta-spin Walker's "green's function" 3-tensor (nwalker, nbasis, nbasis) - Ghalfa_batched : :class:`numpy.ndarray` - alpha-spin Walker's half-rotated "green's function" 3-tensor (nwalker, nalpha, nbasis) - Ghalfb_batched : :class:`numpy.ndarray` - beta-spin Walker's half-rotated "green's function" 3-tensor (nwalker, nbeta, nbasis) - rchola : :class:`numpy.ndarray` - alpha-spin trial's half-rotated choleksy vectors (naux, nalpha * nbasis) - rcholb : :class:`numpy.ndarray` - beta-spin trial's half-rotated choleksy vectors (naux, nbeta * nbasis) - - Returns - ------- - (E, T, V): tuple of vectors - vectors of Local, kinetic and potential energies for each walker - """ - # Element wise multiplication. - nwalker = Ga_batch.shape[0] - e1_vec = numpy.zeros(nwalker, dtype=numpy.complex128) - ecoul_vec = numpy.zeros(nwalker, dtype=numpy.complex128) - # simple loop because this part isn't the slow bit - for widx in range(nwalker): - e1b = numpy.sum(hamiltonian.H1[0] * Ga_batch[widx]) + numpy.sum(hamiltonian.H1[1] * Gb_batch[widx]) - e1_vec[widx] = e1b - Xa = rchola.dot(Ghalfa_batch[widx].ravel()) - Xb = rcholb.dot(Ghalfb_batch[widx].ravel()) - ecoul = numpy.dot(Xa, Xa) - ecoul += numpy.dot(Xb, Xb) - ecoul += 2 * numpy.dot(Xa, Xb) - ecoul_vec[widx] = ecoul - - # transpose batch of walkers as exx prep - GhalfaT_stacked = numpy.hstack([*Ghalfa_batch.transpose((0, 2, 1)).copy()]) - GhalfbT_stacked = numpy.hstack([*Ghalfb_batch.transpose((0, 2, 1)).copy()]) - # call batched exx computation - exx_vec = _exx_compute_batch( - rchol_a=rchola, - rchol_b=rcholb, - GaT_stacked=GhalfaT_stacked, - GbT_stacked=GhalfbT_stacked, - lwalker=nwalker, - ) - e2b_vec = 0.5 * (ecoul_vec - exx_vec) - return (e1_vec + e2b_vec + hamiltonian.ecore, e1_vec + hamiltonian.ecore, e2b_vec) - - @plum.dispatch -def local_energy_generic_cholesky(hamiltonian: GenericRealChol, G): +def local_energy_generic_cholesky(hamiltonian: GenericRealChol, P): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. @@ -230,8 +14,8 @@ def local_energy_generic_cholesky(hamiltonian: GenericRealChol, G): ---------- hamiltonian : :class:`Generic` ab-initio hamiltonian information - G : :class:`numpy.ndarray` - Walker's "green's function" + P : :class:`numpy.ndarray` + Walker's density matrix. Returns ------- @@ -239,30 +23,30 @@ def local_energy_generic_cholesky(hamiltonian: GenericRealChol, G): Local, kinetic and potential energies. """ # Element wise multiplication. - e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) + e1b = numpy.sum(hamiltonian.H1[0] * P[0]) + numpy.sum(hamiltonian.H1[1] * P[1]) nbasis = hamiltonian.nbasis nchol = hamiltonian.nchol - Ga, Gb = G[0], G[1] + Pa, Pb = P[0], P[1] # Ecoul. - Xa = hamiltonian.chol.T.dot(Ga.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Ga.imag.ravel()) - Xb = hamiltonian.chol.T.dot(Gb.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Gb.imag.ravel()) + Xa = hamiltonian.chol.T.dot(Pa.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Pa.imag.ravel()) + Xb = hamiltonian.chol.T.dot(Pb.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Pb.imag.ravel()) X = Xa + Xb ecoul = 0.5 * numpy.dot(X, X) # Ex. - GaT = Ga.T.copy() - GbT = Gb.T.copy() + PaT = Pa.T.copy() + PbT = Pb.T.copy() T = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta for x in range(nchol): # write a cython function that calls blas for this. Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) - T[:, :].real = GaT.real.dot(Lmn) - T[:, :].imag = GaT.imag.dot(Lmn) + T[:, :].real = PaT.real.dot(Lmn) + T[:, :].imag = PaT.imag.dot(Lmn) exx += numpy.trace(T.dot(T)) - T[:, :].real = GbT.real.dot(Lmn) - T[:, :].imag = GbT.imag.dot(Lmn) + T[:, :].real = PbT.real.dot(Lmn) + T[:, :].imag = PbT.imag.dot(Lmn) exx += numpy.trace(T.dot(T)) exx *= 0.5 @@ -271,7 +55,7 @@ def local_energy_generic_cholesky(hamiltonian: GenericRealChol, G): @plum.dispatch -def local_energy_generic_cholesky(hamiltonian: GenericComplexChol, G): +def local_energy_generic_cholesky(hamiltonian: GenericComplexChol, P): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. @@ -280,8 +64,8 @@ def local_energy_generic_cholesky(hamiltonian: GenericComplexChol, G): ---------- hamiltonian : :class:`Generic` ab-initio hamiltonian information - G : :class:`numpy.ndarray` - Walker's "green's function" + P : :class:`numpy.ndarray` + Walker's density matrix. Returns ------- @@ -289,25 +73,25 @@ def local_energy_generic_cholesky(hamiltonian: GenericComplexChol, G): Local, kinetic and potential energies. """ # Element wise multiplication. - e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) + e1b = numpy.sum(hamiltonian.H1[0] * P[0]) + numpy.sum(hamiltonian.H1[1] * P[1]) nbasis = hamiltonian.nbasis nchol = hamiltonian.nchol - Ga, Gb = G[0], G[1] + Pa, Pb = P[0], P[1] # Ecoul. - XAa = hamiltonian.A.T.dot(Ga.ravel()) - XAb = hamiltonian.A.T.dot(Gb.ravel()) + XAa = hamiltonian.A.T.dot(Pa.ravel()) + XAb = hamiltonian.A.T.dot(Pb.ravel()) XA = XAa + XAb - XBa = hamiltonian.B.T.dot(Ga.ravel()) - XBb = hamiltonian.B.T.dot(Gb.ravel()) + XBa = hamiltonian.B.T.dot(Pa.ravel()) + XBb = hamiltonian.B.T.dot(Pb.ravel()) XB = XBa + XBb ecoul = 0.5 * (numpy.dot(XA, XA) + numpy.dot(XB, XB)) # Ex. - GaT = Ga.T.copy() - GbT = Gb.T.copy() + PaT = Pa.T.copy() + PbT = Pb.T.copy() TA = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) TB = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta @@ -315,12 +99,12 @@ def local_energy_generic_cholesky(hamiltonian: GenericComplexChol, G): for x in range(nchol): # write a cython function that calls blas for this. Amn = hamiltonian.A[:, x].reshape((nbasis, nbasis)) Bmn = hamiltonian.B[:, x].reshape((nbasis, nbasis)) - TA[:, :] = GaT.dot(Amn) - TB[:, :] = GaT.dot(Bmn) + TA[:, :] = PaT.dot(Amn) + TB[:, :] = PaT.dot(Bmn) exx += numpy.trace(TA.dot(TA)) + numpy.trace(TB.dot(TB)) - TA[:, :] = GbT.dot(Amn) - TB[:, :] = GbT.dot(Bmn) + TA[:, :] = PbT.dot(Amn) + TB[:, :] = PbT.dot(Bmn) exx += numpy.trace(TA.dot(TA)) + numpy.trace(TB.dot(TB)) exx *= 0.5 @@ -328,229 +112,6 @@ def local_energy_generic_cholesky(hamiltonian: GenericComplexChol, G): return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) -def local_energy_generic_cholesky_opt_stochastic( - hamiltonian, nelec, nsamples, G, Ghalf=None, rchol=None, C0=None, ecoul0=None, exxa0=None, exxb0=None): - r"""Calculate local for generic two-body hamiltonian. - This uses the cholesky decomposed two-electron integrals. - Parameters - ---------- - G : :class:`numpy.ndarray` - Walker's "green's function" - Returns - ------- - (E, T, V): tuple - Local, kinetic and potential energies. - """ - # import cProfile - # pr = cProfile.Profile() - # pr.enable() - - if type(C0) == numpy.ndarray: - control = True - else: - control = False - - # Element wise multiplication. - e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) - if rchol is None: - rchol = hamiltonian.rchol - nalpha, nbeta = nelec - nbasis = hamiltonian.nbasis - Ga, Gb = Ghalf[0], Ghalf[1] - Xa = rchol[0].T.dot(Ga.ravel()) - Xb = rchol[1].T.dot(Gb.ravel()) - ecoul = numpy.dot(Xa, Xa) - ecoul += numpy.dot(Xb, Xb) - ecoul += 2 * numpy.dot(Xa, Xb) - rchol_a, rchol_b = rchol[0], rchol[1] - - # T_{abn} = \sum_k Theta_{ak} LL_{ak,n} - # LL_{ak,n} = \sum_i L_{ik,n} A^*_{ia} - - naux = rchol_a.shape[-1] - - theta = numpy.zeros((naux, nsamples), dtype=numpy.int64) - for i in range(nsamples): - theta[:, i] = 2 * numpy.random.randint(0, 2, size=(naux)) - 1 - - if control: - ra = rchol_a.dot(theta).T * numpy.sqrt(1.0 / nsamples) - rb = rchol_b.dot(theta).T * numpy.sqrt(1.0 / nsamples) - - Ta0 = numpy.zeros((nsamples, nalpha, nalpha), dtype=rchol_a.dtype) - Tb0 = numpy.zeros((nsamples, nbeta, nbeta), dtype=rchol_b.dtype) - - Ta = numpy.zeros((nsamples, nalpha, nalpha), dtype=rchol_a.dtype) - Tb = numpy.zeros((nsamples, nbeta, nbeta), dtype=rchol_b.dtype) - - G0aT = C0[:, :nalpha] - G0bT = C0[:, nalpha:] - - GaT = Ga.T - GbT = Gb.T - - for x in range(nsamples): - rmi_a = ra[x].reshape((nalpha, nbasis)) - rmi_b = rb[x].reshape((nbeta, nbasis)) - - Ta0[x] = rmi_a.dot(G0aT) - Tb0[x] = rmi_b.dot(G0bT) - Ta[x] = rmi_a.dot(GaT) - Tb[x] = rmi_b.dot(GbT) - - exxa_hf = numpy.tensordot(Ta0, Ta0, axes=((0, 1, 2), (0, 2, 1))) - exxb_hf = numpy.tensordot(Tb0, Tb0, axes=((0, 1, 2), (0, 2, 1))) - - exxa_corr = numpy.tensordot(Ta, Ta, axes=((0, 1, 2), (0, 2, 1))) - exxb_corr = numpy.tensordot(Tb, Tb, axes=((0, 1, 2), (0, 2, 1))) - - exxa = exxa0 + (exxa_corr - exxa_hf) - exxb = exxb0 + (exxb_corr - exxb_hf) - - else: - rchol_a = rchol_a.reshape((nalpha, nbasis, naux)) - rchol_b = rchol_b.reshape((nbeta, nbasis, naux)) - - ra = numpy.einsum("ipX,Xs->ips", rchol_a, theta, optimize=True) * numpy.sqrt(1.0 / nsamples) - Gra = numpy.einsum("kq,lqx->lkx", Ga, ra, optimize=True) - exxa = numpy.tensordot(Gra, Gra, axes=((0, 1, 2), (1, 0, 2))) - - rb = numpy.einsum("ipX,Xs->ips", rchol_b, theta, optimize=True) * numpy.sqrt(1.0 / nsamples) - Grb = numpy.einsum("kq,lqx->lkx", Gb, rb, optimize=True) - exxb = numpy.tensordot(Grb, Grb, axes=((0, 1, 2), (1, 0, 2))) - - exx = exxa + exxb - e2b = 0.5 * (ecoul - exx) - - # pr.disable() - # pr.print_stats(sort='tottime') - - return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) - - -def local_energy_generic_cholesky_opt(hamiltonian, nelec, Ga, Gb, Ghalfa=None, Ghalfb=None, rchola=None, rcholb=None): - r"""Calculate local for generic two-body hamiltonian. - - This uses the cholesky decomposed two-electron integrals. - - Parameters - ---------- - hamiltonian : :class:`Abinitio` - Contains necessary hamiltonian information - G : :class:`numpy.ndarray` - Walker's "green's function" - Ghalf : :class:`numpy.ndarray` - Walker's half-rotated "green's function" shape is nocc x nbasis - rchol : :class:`numpy.ndarray` - trial's half-rotated choleksy vectors - - Returns - ------- - (E, T, V): tuple - Local, kinetic and potential energies. - """ - # Element wise multiplication. - if is_cupy( - rchola - ): # if even one array is a cupy array we should assume the rest is done with cupy - # pylint: disable=import-error - import cupy - - assert cupy.is_available() - array = cupy.array - zeros = cupy.zeros - sum = cupy.sum - dot = cupy.dot - trace = cupy.trace - einsum = cupy.einsum - isrealobj = cupy.isrealobj - else: - array = numpy.array - zeros = numpy.zeros - einsum = numpy.einsum - trace = numpy.trace - sum = numpy.sum - dot = numpy.dot - isrealobj = numpy.isrealobj - - complex128 = numpy.complex128 - - e1b = sum(hamiltonian.H1[0] * Ga) + sum(hamiltonian.H1[1] * Gb) - nalpha, nbeta = nelec - nbasis = hamiltonian.nbasis - - if rchola is not None: - naux = rchola.shape[0] - - if isrealobj(rchola) and isrealobj(rcholb): - Xa = rchola.dot(Ghalfa.real.ravel()) + 1.0j * rchola.dot(Ghalfa.imag.ravel()) - Xb = rcholb.dot(Ghalfb.real.ravel()) + 1.0j * rcholb.dot(Ghalfb.imag.ravel()) - else: - Xa = rchola.dot(Ghalfa.ravel()) - Xb = rcholb.dot(Ghalfb.ravel()) - - ecoul = dot(Xa, Xa) - ecoul += dot(Xb, Xb) - ecoul += 2 * dot(Xa, Xb) - - GhalfaT = Ghalfa.T.copy() # nbasis x nocc - GhalfbT = Ghalfb.T.copy() - - Ta = zeros((nalpha, nalpha), dtype=complex128) - Tb = zeros((nbeta, nbeta), dtype=complex128) - - exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - if isrealobj(rchola) and isrealobj(rcholb): - for x in range(naux): # write a cython function that calls blas for this. - rmi_a = rchola[x].reshape((nalpha, nbasis)) - rmi_b = rcholb[x].reshape((nbeta, nbasis)) - Ta[:, :].real = rmi_a.dot(GhalfaT.real) - Ta[:, :].imag = rmi_a.dot(GhalfaT.imag) # this is a (nalpha, nalpha) - Tb[:, :].real = rmi_b.dot(GhalfbT.real) - Tb[:, :].imag = rmi_b.dot(GhalfbT.imag) # this is (nbeta, nbeta) - exx += trace(Ta.dot(Ta)) + trace(Tb.dot(Tb)) - else: - for x in range(naux): # write a cython function that calls blas for this. - rmi_a = rchola[x].reshape((nalpha, nbasis)) - rmi_b = rcholb[x].reshape((nbeta, nbasis)) - Ta[:, :] = rmi_a.dot(GhalfaT) # this is a (nalpha, nalpha) - Tb[:, :] = rmi_b.dot(GhalfbT) # this is (nbeta, nbeta) - exx += trace(Ta.dot(Ta)) + trace(Tb.dot(Tb)) - - e2b = 0.5 * (ecoul - exx) - - return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) - - -# FDM: deprecated remove? -def local_energy_generic_opt(hamiltonian, nelec, G, Ghalf=None, eri=None): - """Compute local energy using half-rotated eri tensor.""" - na, nb = nelec - M = hamiltonian.nbasis - assert eri is not None - - vipjq_aa = eri[0, : na**2 * M**2].reshape((na, M, na, M)) - vipjq_bb = eri[0, na**2 * M**2 : na**2 * M**2 + nb**2 * M**2].reshape( - (nb, M, nb, M) - ) - vipjq_ab = eri[0, na**2 * M**2 + nb**2 * M**2 :].reshape((na, M, nb, M)) - - Ga, Gb = Ghalf[0], Ghalf[1] - # Element wise multiplication. - e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) - # Coulomb - eJaa = 0.5 * numpy.einsum("irjs,ir,js", vipjq_aa, Ga, Ga) - eJbb = 0.5 * numpy.einsum("irjs,ir,js", vipjq_bb, Gb, Gb) - eJab = numpy.einsum("irjs,ir,js", vipjq_ab, Ga, Gb) - - eKaa = -0.5 * numpy.einsum("irjs,is,jr", vipjq_aa, Ga, Ga) - eKbb = -0.5 * numpy.einsum("irjs,is,jr", vipjq_bb, Gb, Gb) - - e2b = eJaa + eJbb + eJab + eKaa + eKbb - - return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) - - def fock_generic(hamiltonian, P): nbasis = hamiltonian.nbasis nchol = hamiltonian.nchol diff --git a/ipie/addons/thermal/estimators/local_energy.py b/ipie/addons/thermal/estimators/local_energy.py index 7c4a478f..b79fd1c1 100644 --- a/ipie/addons/thermal/estimators/local_energy.py +++ b/ipie/addons/thermal/estimators/local_energy.py @@ -1,74 +1,25 @@ -from ipie.addons.thermal.estimators.generic import local_energy_generic_opt -from ipie.addons.thermal.estimators.generic import ( - local_energy_generic_cholesky, - local_energy_generic_cholesky_opt, - local_energy_generic_cholesky_opt_stochastic, - local_energy_generic_pno, -) +from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G +def local_energy_P(hamiltonian, trial, P): + """Compute local energy from a given density matrix P. -def local_energy_G(hamiltonian, trial, G, Ghalf=None, X=None, Lap=None): - assert len(G) == 2 - - if Ghalf is not None: - if hamiltonian.stochastic_ri and hamiltonian.control_variate: - return local_energy_generic_cholesky_opt_stochastic( - hamiltonian, - trial.nelec, - hamiltonian.nsamples, - G, - Ghalf=Ghalf, - rchol=trial._rchol, - C0=trial.psi, - ecoul0=trial.ecoul0, - exxa0=trial.exxa0, - exxb0=trial.exxb0, - ) - elif hamiltonian.stochastic_ri and not hamiltonian.control_variate: - return local_energy_generic_cholesky_opt_stochastic( - hamiltonian, - trial.nelec, - hamiltonian.nsamples, - G, - Ghalf=Ghalf, - rchol=trial._rchol, - ) - elif hamiltonian.exact_eri and not hamiltonian.pno: - return local_energy_generic_opt( - hamiltonian, - trial.nelec, - G, - Ghalf=Ghalf, - eri=trial._eri) - elif hamiltonian.pno: - assert hamiltonian.exact_eri and hamiltonian.control_variate - return local_energy_generic_pno( - hamiltonian, - trial.nelec, - G, - Ghalf=Ghalf, - eri=trial._eri, - C0=trial.C0, - ecoul0=trial.ecoul0, - exxa0=trial.exxa0, - exxb0=trial.exxb0, - UVT=trial.UVT, - ) - else: - return local_energy_generic_cholesky_opt( - hamiltonian, - trial.nelec, - G[0], - G[1], - Ghalfa=Ghalf[0], - Ghalfb=Ghalf[1], - rchola=trial._rchola, - rcholb=trial._rcholb, - ) - else: - return local_energy_generic_cholesky(hamiltonian, G) + Parameters + ---------- + hamiltonian : hamiltonian object + Hamiltonian being studied. + trial : trial wavefunction object + Trial wavefunction. + P : np.ndarray + Walker density matrix. + Returns: + ------- + local_energy : tuple / array + Total, one-body and two-body energies. + """ + assert len(P) == 2 + return local_energy_generic_cholesky(hamiltonian, P) def local_energy(hamiltonian, walker, trial): - return local_energy_G(hamiltonian, trial, one_rdm_from_G(walker.G), None) + return local_energy_P(hamiltonian, trial, one_rdm_from_G(walker.G)) diff --git a/ipie/addons/thermal/estimators/particle_number.py b/ipie/addons/thermal/estimators/particle_number.py index ef8b0829..83343397 100644 --- a/ipie/addons/thermal/estimators/particle_number.py +++ b/ipie/addons/thermal/estimators/particle_number.py @@ -1,5 +1,4 @@ from ipie.estimators.estimator_base import EstimatorBase -import plum import numpy from ipie.utils.backend import arraylib as xp diff --git a/ipie/addons/thermal/estimators/tests/test_estimators.py b/ipie/addons/thermal/estimators/tests/test_estimators.py index 9c47c5e9..2c43c59e 100644 --- a/ipie/addons/thermal/estimators/tests/test_estimators.py +++ b/ipie/addons/thermal/estimators/tests/test_estimators.py @@ -29,7 +29,7 @@ lowrank = False verbose = True -complex_integrals = False +complex_integrals = True debug = True mf_trial = True propagate = False diff --git a/ipie/addons/thermal/estimators/tests/test_generic_complex.py b/ipie/addons/thermal/estimators/tests/test_generic_complex.py index a47f8bd3..11e19902 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/addons/thermal/estimators/tests/test_generic_complex.py @@ -90,6 +90,7 @@ def test_local_energy_vs_eri(): print('\n----------------------------') print('Constructing test objects...') print('----------------------------') + options['complex_integrals'] = True objs = build_generic_test_case_handlers(options, seed, debug, with_eri=True, verbose=verbose) trial = objs['trial'] @@ -106,6 +107,7 @@ def test_local_energy_vs_eri(): numpy.testing.assert_allclose(eri, eri_chol, atol=1e-10) for iw in range(walkers.nwalkers): + print(iw) P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) Pa, Pb = P Ptot = Pa + Pb @@ -132,7 +134,7 @@ def test_local_energy_0T_single_det(): numpy.random.seed(7) nmo = 10 nelec = (6, 5) - nwalkers = 1 + nwalkers = 12 nsteps = 25 qmc = dotdict( { @@ -144,13 +146,14 @@ def test_local_energy_0T_single_det(): } ) + print('test_local_energy_0T_single_det: here') handler_0T = build_test_case_handlers_0T( nelec, nmo, num_dets=1, options=qmc, seed=7, - complex_integrals=True, + complex_integrals=False, complex_trial=True, trial_type="single_det", choltol=1e-10, @@ -174,6 +177,6 @@ def test_local_energy_0T_single_det(): if __name__ == '__main__': - test_local_energy_vs_real() - test_local_energy_vs_eri() + #test_local_energy_vs_real() + #test_local_energy_vs_eri() test_local_energy_0T_single_det() diff --git a/ipie/addons/thermal/trial/tests/test_mean_field.py b/ipie/addons/thermal/trial/tests/test_mean_field.py index 8d63056f..61bbd158 100644 --- a/ipie/addons/thermal/trial/tests/test_mean_field.py +++ b/ipie/addons/thermal/trial/tests/test_mean_field.py @@ -37,7 +37,7 @@ def test_mean_field(): trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) assert trial.nelec == nelec - numpy.testing.assert_almost_equal(trial.nav, numpy.sum(nelec), decimal=6) + numpy.testing.assert_almost_equal(trial.nav, numpy.sum(nelec), decimal=5) assert trial.rho.shape == (2, nbasis, nbasis) assert trial.dmat.shape == (2, nbasis, nbasis) assert trial.P.shape == (2, nbasis, nbasis) diff --git a/ipie/estimators/energy.py b/ipie/estimators/energy.py index 2ba5b50f..d8a6936b 100644 --- a/ipie/estimators/energy.py +++ b/ipie/estimators/energy.py @@ -109,12 +109,12 @@ class EnergyEstimator(EstimatorBase): def __init__( self, system=None, - hamiltonian=None, + ham=None, trial=None, filename=None, ): assert system is not None - assert hamiltonian is not None + assert ham is not None assert trial is not None super().__init__() self._eshift = 0.0 diff --git a/ipie/estimators/estimator_base.py b/ipie/estimators/estimator_base.py index 13a9e12c..c78c9322 100644 --- a/ipie/estimators/estimator_base.py +++ b/ipie/estimators/estimator_base.py @@ -15,13 +15,13 @@ # Author: Fionn Malone # -from abc import ABCMeta, abstractmethod +from abc import abstractmethod, ABCMeta import numpy as np +from ipie.utils.io import format_fixed_width_strings, format_fixed_width_floats from ipie.utils.backend import arraylib as xp from ipie.utils.backend import to_host -from ipie.utils.io import format_fixed_width_floats, format_fixed_width_strings class EstimatorBase(metaclass=ABCMeta): @@ -89,7 +89,8 @@ def shape(self, shape) -> tuple: self._shape = shape @abstractmethod - def compute_estimator(self, system, walkers, hamiltonian, trial) -> np.ndarray: ... + def compute_estimator(self, system, walkers, hamiltonian, trial) -> np.ndarray: + ... @property def names(self): @@ -141,4 +142,5 @@ def zero(self): else: self._data[k] = 0.0j - def post_reduce_hook(self, data) -> None: ... + def post_reduce_hook(self, data) -> None: + ... diff --git a/ipie/estimators/generic.py b/ipie/estimators/generic.py index bda07b13..6f69d085 100644 --- a/ipie/estimators/generic.py +++ b/ipie/estimators/generic.py @@ -23,7 +23,38 @@ from ipie.utils.backend import synchronize -def local_energy_generic_cholesky(system, hamiltonian, G, Ghalf=None): +# FDM: deprecated remove? +def local_energy_generic_opt(system, G, Ghalf=None, eri=None): + """Compute local energy using half-rotated eri tensor.""" + + na = system.nup + nb = system.ndown + M = system.nbasis + assert eri is not None + + vipjq_aa = eri[0, : na**2 * M**2].reshape((na, M, na, M)) + vipjq_bb = eri[0, na**2 * M**2 : na**2 * M**2 + nb**2 * M**2].reshape( + (nb, M, nb, M) + ) + vipjq_ab = eri[0, na**2 * M**2 + nb**2 * M**2 :].reshape((na, M, nb, M)) + + Ga, Gb = Ghalf[0], Ghalf[1] + # Element wise multiplication. + e1b = numpy.sum(system.H1[0] * G[0]) + numpy.sum(system.H1[1] * G[1]) + # Coulomb + eJaa = 0.5 * numpy.einsum("irjs,ir,js", vipjq_aa, Ga, Ga) + eJbb = 0.5 * numpy.einsum("irjs,ir,js", vipjq_bb, Gb, Gb) + eJab = numpy.einsum("irjs,ir,js", vipjq_ab, Ga, Gb) + + eKaa = -0.5 * numpy.einsum("irjs,is,jr", vipjq_aa, Ga, Ga) + eKbb = -0.5 * numpy.einsum("irjs,is,jr", vipjq_bb, Gb, Gb) + + e2b = eJaa + eJbb + eJab + eKaa + eKbb + + return (e1b + e2b + system.ecore, e1b + system.ecore, e2b) + + +def local_energy_generic_cholesky(system, ham, G, Ghalf=None): r"""Calculate local for generic two-body hamiltonian. This uses the cholesky decomposed two-electron integrals. @@ -31,8 +62,8 @@ def local_energy_generic_cholesky(system, hamiltonian, G, Ghalf=None): Parameters ---------- system : :class:`Generic` - System information for Generic. - hamiltonian : :class:`Generic` + generic system information + ham : :class:`Generic` ab-initio hamiltonian information G : :class:`numpy.ndarray` Walker's "green's function" @@ -45,17 +76,17 @@ def local_energy_generic_cholesky(system, hamiltonian, G, Ghalf=None): Total , one and two-body energies. """ # Element wise multiplication. - e1b = numpy.sum(hamiltonian.H1[0] * G[0]) + numpy.sum(hamiltonian.H1[1] * G[1]) - nbasis = hamiltonian.nbasis - nchol = hamiltonian.nchol + e1b = numpy.sum(ham.H1[0] * G[0]) + numpy.sum(ham.H1[1] * G[1]) + nbasis = ham.nbasis + nchol = ham.nchol Ga, Gb = G[0], G[1] - if numpy.isrealobj(hamiltonian.chol): - Xa = hamiltonian.chol.T.dot(Ga.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Ga.imag.ravel()) - Xb = hamiltonian.chol.T.dot(Gb.real.ravel()) + 1.0j * hamiltonian.chol.T.dot(Gb.imag.ravel()) + if numpy.isrealobj(ham.chol): + Xa = ham.chol.T.dot(Ga.real.ravel()) + 1.0j * ham.chol.T.dot(Ga.imag.ravel()) + Xb = ham.chol.T.dot(Gb.real.ravel()) + 1.0j * ham.chol.T.dot(Gb.imag.ravel()) else: - Xa = hamiltonian.chol.T.dot(Ga.ravel()) - Xb = hamiltonian.chol.T.dot(Gb.ravel()) + Xa = ham.chol.T.dot(Ga.ravel()) + Xb = ham.chol.T.dot(Gb.ravel()) ecoul = numpy.dot(Xa, Xa) ecoul += numpy.dot(Xb, Xb) @@ -67,9 +98,9 @@ def local_energy_generic_cholesky(system, hamiltonian, G, Ghalf=None): GbT = Gb.T.copy() exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - if numpy.isrealobj(hamiltonian.chol): + if numpy.isrealobj(ham.chol): for x in range(nchol): # write a cython function that calls blas for this. - Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) + Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) T[:, :].real = GaT.real.dot(Lmn) T[:, :].imag = GaT.imag.dot(Lmn) exx += numpy.trace(T.dot(T)) @@ -78,7 +109,7 @@ def local_energy_generic_cholesky(system, hamiltonian, G, Ghalf=None): exx += numpy.trace(T.dot(T)) else: for x in range(nchol): # write a cython function that calls blas for this. - Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) + Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) T[:, :] = GaT.dot(Lmn) exx += numpy.trace(T.dot(T)) T[:, :] = GbT.dot(Lmn) @@ -86,7 +117,7 @@ def local_energy_generic_cholesky(system, hamiltonian, G, Ghalf=None): e2b = 0.5 * (ecoul - exx) - return (e1b + e2b + hamiltonian.ecore, e1b + hamiltonian.ecore, e2b) + return (e1b + e2b + ham.ecore, e1b + ham.ecore, e2b) def local_energy_cholesky_opt_dG(system, ecore, Ghalfa, Ghalfb, trial): @@ -97,7 +128,7 @@ def local_energy_cholesky_opt_dG(system, ecore, Ghalfa, Ghalfb, trial): Parameters ---------- system : :class:`Generic` - System information for Generic. + generic system information ecore : float Core energy Ghalfa : :class:`numpy.ndarray` @@ -226,18 +257,7 @@ def exx_kernel_rchol_real(rchol, Ghalf): @jit(nopython=True, fastmath=True) -def ecoul_kernel_rchol_complex(rchola, rcholb, rcholbara, rcholbarb, Ghalfa, Ghalfb): - X1 = rchola.dot(Ghalfa.ravel()) - X1 += rcholb.dot(Ghalfb.ravel()) - X2 = rcholbara.dot(Ghalfa.ravel()) - X2 += rcholbarb.dot(Ghalfb.ravel()) - ecoul = xp.dot(X1, X2) - ecoul *= 0.5 - return ecoul - - -@jit(nopython=True, fastmath=True) -def exx_kernel_rchol_complex(rchol, rcholbar, Ghalf): +def exx_kernel_rchol_complex(rchol, Ghalf): """Compute exchange contribution for complex rchol. Parameters @@ -250,22 +270,19 @@ def exx_kernel_rchol_complex(rchol, rcholbar, Ghalf): Returns ------- exx : :class:`numpy.ndarray` - exchange contribution for all walkers. + exchange contribution for given green's function. """ naux = rchol.shape[0] nocc = Ghalf.shape[0] - nbsf = Ghalf.shape[1] - T1 = xp.zeros((nocc, nocc), dtype=numpy.complex128) - T2 = xp.zeros((nocc, nocc), dtype=numpy.complex128) - exx = 0. + 0.j + nbasis = Ghalf.shape[1] + + exx = 0 + 0j + GhalfT = Ghalf.T.copy() # Fix this with gpu env for jx in range(naux): - rcholx = rchol[jx].reshape(nocc, nbsf) - rcholbarx = rcholbar[jx].reshape(nocc, nbsf) - T1 = rcholx.dot(Ghalf.T) - T2 = rcholbarx.dot(Ghalf.T) - exx += xp.dot(T1.ravel(), T2.T.ravel()) - exx *= 0.5 + rmi = rchol[jx].reshape((nocc, nbasis)) + T = rmi.dot(GhalfT) + exx += numpy.dot(T.ravel(), T.T.ravel()) return exx @@ -310,6 +327,8 @@ def half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial): Parameters ---------- + system : :class:`Generic` + System information for Generic. Ghalfa : :class:`numpy.ndarray` Walker's half-rotated "green's function" shape is nalpha x nbasis Ghalfa : :class:`numpy.ndarray` @@ -324,6 +343,7 @@ def half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial): exx : :class:`numpy.ndarray` Exchange energy. """ + rchola = trial._rchola rcholb = trial._rcholb @@ -331,28 +351,34 @@ def half_rotated_cholesky_jk(system, Ghalfa, Ghalfb, trial): if xp.isrealobj(rchola) and xp.isrealobj(rcholb): Xa = rchola.dot(Ghalfa.real.ravel()) + 1.0j * rchola.dot(Ghalfa.imag.ravel()) Xb = rcholb.dot(Ghalfb.real.ravel()) + 1.0j * rcholb.dot(Ghalfb.imag.ravel()) - ecoul = xp.dot(Xa, Xa) - ecoul += xp.dot(Xb, Xb) - ecoul += 2 * xp.dot(Xa, Xb) else: - rcholbara = trial._rcholbara - rcholbarb = trial._rcholbarb - ecoul = 2.0 * ecoul_kernel_rchol_complex( - rchola, rcholb, rcholbara, rcholbarb, Ghalfa, Ghalfb - ) + Xa = rchola.dot(Ghalfa.ravel()) + Xb = rcholb.dot(Ghalfb.ravel()) + ecoul = xp.dot(Xa, Xa) + ecoul += xp.dot(Xb, Xb) + ecoul += 2 * xp.dot(Xa, Xb) + exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta if xp.isrealobj(rchola) and xp.isrealobj(rcholb): exx = exx_kernel_rchol_real(rchola, Ghalfa) + exx_kernel_rchol_real(rcholb, Ghalfb) else: - rcholbara = trial._rcholbara - rcholbarb = trial._rcholbarb - exx = exx_kernel_rchol_complex(rchola, rcholbara, Ghalfa) - exx += exx_kernel_rchol_complex(rcholb, rcholbarb, Ghalfb) - exx *= 2.0 + exx = exx_kernel_rchol_complex(rchola, Ghalfa) + exx_kernel_rchol_complex(rcholb, Ghalfb) + synchronize() return 0.5 * ecoul, -0.5 * exx # JK energy +# FDM: Mark for deletion +def core_contribution(system, Gcore): + hc_a = numpy.einsum("pqrs,pq->rs", system.h2e, Gcore[0]) - 0.5 * numpy.einsum( + "prsq,pq->rs", system.h2e, Gcore[0] + ) + hc_b = numpy.einsum("pqrs,pq->rs", system.h2e, Gcore[1]) - 0.5 * numpy.einsum( + "prsq,pq->rs", system.h2e, Gcore[1] + ) + return (hc_a, hc_b) + + def core_contribution_cholesky(chol, G): nb = G[0].shape[-1] cmat = chol.reshape((-1, nb * nb)) @@ -369,12 +395,12 @@ def core_contribution_cholesky(chol, G): return (hca, hcb) -def fock_generic(hamiltonian, P): - if hamiltonian.sparse: - mf_shift = 1j * P[0].ravel() * hamiltonian.hs_pot - mf_shift += 1j * P[1].ravel() * hamiltonian.hs_pot - VMF = 1j * hamiltonian.hs_pot.dot(mf_shift).reshape(hamiltonian.nbasis, hamiltonian.nbasis) +def fock_generic(system, P): + if system.sparse: + mf_shift = 1j * P[0].ravel() * system.hs_pot + mf_shift += 1j * P[1].ravel() * system.hs_pot + VMF = 1j * system.hs_pot.dot(mf_shift).reshape(system.nbasis, system.nbasis) else: - mf_shift = 1j * numpy.einsum("lpq,spq->l", hamiltonian.hs_pot, P) - VMF = 1j * numpy.einsum("lpq,l->pq", hamiltonian.hs_pot, mf_shift) - return hamiltonian.h1e_mod - VMF + mf_shift = 1j * numpy.einsum("lpq,spq->l", system.hs_pot, P) + VMF = 1j * numpy.einsum("lpq,l->pq", system.hs_pot, mf_shift) + return system.h1e_mod - VMF diff --git a/ipie/estimators/handler.py b/ipie/estimators/handler.py index ab9fc2da..a35dbfe1 100644 --- a/ipie/estimators/handler.py +++ b/ipie/estimators/handler.py @@ -43,10 +43,10 @@ class EstimatorHandler(object): Parameters ---------- - system : :class:`ipie.hubbard.Hubbard` / system object in general. - Container for model input options. comm : MPI.COMM_WORLD MPI Communicator + system : :class:`ipie.hubbard.Hubbard` / system object in general. + Container for model input options. trial : :class:`ipie.trial_wavefunction.X' object Trial wavefunction class. verbose : bool @@ -108,7 +108,7 @@ def __init__( try: est = _predefined_estimators[obs]( system=system, - hamiltonian=hamiltonian, + ham=hamiltonian, trial=trial, ) self[obs] = est diff --git a/ipie/estimators/local_energy.py b/ipie/estimators/local_energy.py index db032a20..1129c684 100644 --- a/ipie/estimators/local_energy.py +++ b/ipie/estimators/local_energy.py @@ -68,7 +68,7 @@ def variational_energy(system, hamiltonian, trial): return local_energy(system, hamiltonian, trial, trial) -def variational_energy_ortho_det(system, hamiltonian, occs, coeffs): +def variational_energy_ortho_det(system, ham, occs, coeffs): """Compute variational energy for CI-like multi-determinant expansion. Parameters @@ -95,7 +95,7 @@ def variational_energy_ortho_det(system, hamiltonian, occs, coeffs): for j in range(0, i + 1): cj = coeffs[j] occj = occs[j] - etot, e1b, e2b = ci.conj() * cj * get_hmatel(hamiltonian, nel, occi, occj) + etot, e1b, e2b = ci.conj() * cj * get_hmatel(ham, nel, occi, occj) evar += etot one_body += e1b two_body += e2b diff --git a/ipie/estimators/local_energy_wicks.py b/ipie/estimators/local_energy_wicks.py index b16d6d99..7aa158df 100644 --- a/ipie/estimators/local_energy_wicks.py +++ b/ipie/estimators/local_energy_wicks.py @@ -32,7 +32,7 @@ from ipie.utils.linalg import minor_mask, minor_mask4 -def local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walkers, trial): +def local_energy_multi_det_trial_wicks_batch(system, ham, walkers, trial): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. @@ -54,11 +54,11 @@ def local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walkers, trial Total, one-body and two-body energies. """ nwalkers = walkers.nwalkers - nbasis = hamiltonian.nbasis - nchol = hamiltonian.nchol + nbasis = ham.nbasis + nchol = ham.nchol Ga = walkers.Ga.reshape((nwalkers, nbasis * nbasis)) Gb = walkers.Gb.reshape((nwalkers, nbasis * nbasis)) - e1bs = Ga.dot(hamiltonian.H1[0].ravel()) + Gb.dot(hamiltonian.H1[1].ravel()) + hamiltonian.ecore + e1bs = Ga.dot(ham.H1[0].ravel()) + Gb.dot(ham.H1[1].ravel()) + ham.ecore e2bs = [] for iwalker in range(nwalkers): @@ -77,15 +77,15 @@ def local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walkers, trial G0 = [G0a, G0b] # contribution 1 (disconnected) - cont1 = local_energy_generic_cholesky(system, hamiltonian, G0)[2] + cont1 = local_energy_generic_cholesky(system, ham, G0)[2] # contribution 2 (half-connected, two-leg, one-body-like) # First, Coulomb-like term - Xa = hamiltonian.chol.T.dot(G0[0].ravel()) # numpy.einsum("m,xm->x", G0[0].ravel(), hamiltonian.chol) - Xb = hamiltonian.chol.T.dot(G0[1].ravel()) # numpy.einsum("m,xm->x", G0[1].ravel(), hamiltonian.chol) + Xa = ham.chol.T.dot(G0[0].ravel()) # numpy.einsum("m,xm->x", G0[0].ravel(), ham.chol) + Xb = ham.chol.T.dot(G0[1].ravel()) # numpy.einsum("m,xm->x", G0[1].ravel(), ham.chol) - LXa = numpy.einsum("mx,x->m", hamiltonian.chol, Xa, optimize=True) - LXb = numpy.einsum("mx,x->m", hamiltonian.chol, Xb, optimize=True) + LXa = numpy.einsum("mx,x->m", ham.chol, Xa, optimize=True) + LXb = numpy.einsum("mx,x->m", ham.chol, Xb, optimize=True) LXa = LXa.reshape((nbasis, nbasis)) LXb = LXb.reshape((nbasis, nbasis)) @@ -103,7 +103,7 @@ def local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walkers, trial cont2_Kaa = 0.0 + 0.0j cont2_Kbb = 0.0 + 0.0j for x in range(nchol): - Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) + Lmn = ham.chol[:, x].reshape((nbasis, nbasis)) LGL = Lmn.dot(G0a.T).dot(Lmn) cont2_Kaa -= numpy.sum(LGL * QCIGa) @@ -119,14 +119,14 @@ def local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walkers, trial "iq,pj,ijx->qpx", Q0a, G0a, - hamiltonian.chol.reshape((nbasis, nbasis, nchol)), + ham.chol.reshape((nbasis, nbasis, nchol)), optimize=True, ) Lbb = numpy.einsum( "iq,pj,ijx->qpx", Q0b, G0b, - hamiltonian.chol.reshape((nbasis, nbasis, nchol)), + ham.chol.reshape((nbasis, nbasis, nchol)), optimize=True, ) @@ -549,7 +549,7 @@ def build_contributions12( return cont1_J + cont1_K, cont2_J + cont2_K -def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, hamiltonian, walkers, trial, max_mem=2.0): +def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, ham, walkers, trial, max_mem=2.0): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. @@ -578,11 +578,11 @@ def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, hamiltonian, wa Total, one-body and two-body energies. """ nwalkers = walkers.nwalkers - nbasis = hamiltonian.nbasis - nchol = hamiltonian.nchol + nbasis = ham.nbasis + nchol = ham.nchol Ga = walkers.Ga.reshape((nwalkers, nbasis * nbasis)) Gb = walkers.Gb.reshape((nwalkers, nbasis * nbasis)) - e1b = Ga.dot(hamiltonian.H1[0].ravel()) + Gb.dot(hamiltonian.H1[1].ravel()) + hamiltonian.ecore + e1b = Ga.dot(ham.H1[0].ravel()) + Gb.dot(ham.H1[1].ravel()) + ham.ecore ovlpa0 = walkers.det_ovlpas[:, 0] ovlpb0 = walkers.det_ovlpbs[:, 0] @@ -861,7 +861,7 @@ def local_energy_multi_det_trial_wicks_batch_opt_chunked(system, hamiltonian, wa return walker_energies -def local_energy_multi_det_trial_wicks_batch_opt(system, hamiltonian, walkers, trial, max_mem=2.0): +def local_energy_multi_det_trial_wicks_batch_opt(system, ham, walkers, trial, max_mem=2.0): """Compute local energy for walker batch (all walkers at once). Multi determinant case (particle-hole) using Wick's theorem algorithm. @@ -891,11 +891,11 @@ def local_energy_multi_det_trial_wicks_batch_opt(system, hamiltonian, walkers, t Total, one-body and two-body energies. """ nwalkers = walkers.nwalkers - nbasis = hamiltonian.nbasis - nchol = hamiltonian.nchol + nbasis = ham.nbasis + nchol = ham.nchol Ga = walkers.Ga.reshape((nwalkers, nbasis * nbasis)) Gb = walkers.Gb.reshape((nwalkers, nbasis * nbasis)) - e1b = Ga.dot(hamiltonian.H1[0].ravel()) + Gb.dot(hamiltonian.H1[1].ravel()) + hamiltonian.ecore + e1b = Ga.dot(ham.H1[0].ravel()) + Gb.dot(ham.H1[1].ravel()) + ham.ecore ovlpa0 = walkers.det_ovlpas[:, 0] ovlpb0 = walkers.det_ovlpbs[:, 0] diff --git a/ipie/estimators/tests/test_estimators.py b/ipie/estimators/tests/test_estimators.py index 9ea3f75f..59adc89f 100644 --- a/ipie/estimators/tests/test_estimators.py +++ b/ipie/estimators/tests/test_estimators.py @@ -30,9 +30,9 @@ def test_energy_estimator(): nocc = 8 naux = 30 nwalker = 10 - system, hamiltonian, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) - estim = EnergyEstimator(system=system, hamiltonian=hamiltonian, trial=trial) - estim.compute_estimator(system, walker_batch, hamiltonian, trial) + system, ham, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) + estim = EnergyEstimator(system=system, ham=ham, trial=trial) + estim.compute_estimator(system, walker_batch, ham, trial) assert len(estim.names) == 5 assert estim["ENumer"].real == pytest.approx(-754.0373585215561) assert estim["ETotal"] == pytest.approx(0.0) @@ -54,8 +54,8 @@ def test_estimator_handler(): nocc = 8 naux = 30 nwalker = 10 - system, hamiltonian, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) - estim = EnergyEstimator(system=system, hamiltonian=hamiltonian, trial=trial, filename=tmp1.name) + system, ham, walker_batch, trial = gen_random_test_instances(nmo, nocc, naux, nwalker) + estim = EnergyEstimator(system=system, ham=ham, trial=trial, filename=tmp1.name) estim.print_to_stdout = False from ipie.config import MPI @@ -63,7 +63,7 @@ def test_estimator_handler(): handler = EstimatorHandler( comm, system, - hamiltonian, + ham, trial, block_size=10, observables=("energy",), @@ -72,10 +72,5 @@ def test_estimator_handler(): handler["energy1"] = estim handler.json_string = "" handler.initialize(comm) - handler.compute_estimators(comm, system, hamiltonian, trial, walker_batch) - handler.compute_estimators(comm, system, hamiltonian, trial, walker_batch) - - -if __name__ == "__main__": - test_energy_estimator() - test_estimator_handler() + handler.compute_estimators(comm, system, ham, trial, walker_batch) + handler.compute_estimators(comm, system, ham, trial, walker_batch) diff --git a/ipie/estimators/tests/test_generic.py b/ipie/estimators/tests/test_generic.py index 95a42120..4e9af561 100644 --- a/ipie/estimators/tests/test_generic.py +++ b/ipie/estimators/tests/test_generic.py @@ -35,14 +35,14 @@ def test_local_energy_cholesky(): nelec = (4, 2) h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=enuc, ) - ci, wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) + ci, wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - e = local_energy_generic_cholesky(system, hamiltonian, trial.G, Ghalf=trial.Ghalf) + e = local_energy_generic_cholesky(system, ham, trial.G, Ghalf=trial.Ghalf) assert e[0] == pytest.approx(20.6826247016273) assert e[1] == pytest.approx(23.0173528796140) assert e[2] == pytest.approx(-2.3347281779866) @@ -55,15 +55,15 @@ def test_local_energy_cholesky_opt(): nelec = (4, 2) h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=enuc, ) - ci, wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) + ci, wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - trial.half_rotate(hamiltonian) - e = local_energy_cholesky_opt(system, hamiltonian.ecore, trial.Ghalf[0], trial.Ghalf[1], trial) + trial.half_rotate(ham) + e = local_energy_cholesky_opt(system, ham.ecore, trial.Ghalf[0], trial.Ghalf[1], trial) assert e[0] == pytest.approx(20.6826247016273) assert e[1] == pytest.approx(23.0173528796140) assert e[2] == pytest.approx(-2.3347281779866) @@ -76,21 +76,21 @@ def test_local_energy_cholesky_opt_batched(): nelec = (4, 2) h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=enuc, ) - wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) - trial = MultiSlater(system, hamiltonian, wfn) - trial.half_rotate(hamiltonian) + wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) + trial = MultiSlater(system, ham, wfn) + trial.half_rotate(ham) Ga_batched = numpy.array([trial.G[0], trial.G[0], trial.G[0]]) Gb_batched = numpy.array([trial.G[1], trial.G[1], trial.G[1]]) Gahalf_batched = numpy.array([trial.Ghalf[0], trial.Ghalf[0], trial.Ghalf[0]]) Gbhalf_batched = numpy.array([trial.Ghalf[1], trial.Ghalf[1], trial.Ghalf[1]]) res = local_energy_generic_cholesky_opt_batched( system, - hamiltonian, + ham, Ga_batched, Gb_batched, Gahalf_batched, diff --git a/ipie/estimators/tests/test_generic_batch.py b/ipie/estimators/tests/test_generic_batch.py index ee8c18c5..e26d809c 100644 --- a/ipie/estimators/tests/test_generic_batch.py +++ b/ipie/estimators/tests/test_generic_batch.py @@ -49,29 +49,29 @@ def test_greens_function_batch(): dt = 0.005 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) trial = ParticleHole(wfn, nelec, nmo) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) from ipie.legacy.hamiltonians.generic import Generic as LegacyHamGeneric - legacy_hamiltonian = LegacyHamGeneric( + legacy_ham = LegacyHamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) - legacy_walkers = build_legacy_test_case(wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) + legacy_walkers = build_legacy_test_case(wfn, init, system, legacy_ham, nsteps, nwalkers, dt) numpy.random.seed(7) walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) for iw in range(nwalkers): @@ -99,13 +99,13 @@ def test_local_energy_single_det_batch(): dt = 0.005 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - ci_wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -114,35 +114,35 @@ def test_local_energy_single_det_batch(): wfn[:, nelec[0] :] = I[:, occb0] trial = SingleDet(wfn, nelec, nmo) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) from ipie.legacy.hamiltonians.generic import Generic as LegacyHamGeneric - legacy_hamiltonian = LegacyHamGeneric( + legacy_ham = LegacyHamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, options={"symmetry": False}, ) numpy.random.seed(7) - legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) - etots, e1s, e2s = get_legacy_walker_energies(system, legacy_hamiltonian, trial, legacy_walkers) + legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) + etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": 10}) prop = PhaselessGeneric(time_step=qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) for i in range(nsteps): - prop.propagate_walkers(walkers, hamiltonian, trial, 0) + prop.propagate_walkers(walkers, ham, trial, 0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_batch(system, hamiltonian, walkers, trial) - energies_uhf = local_energy_single_det_uhf(system, hamiltonian, walkers, trial) + energies = local_energy_single_det_batch(system, ham, walkers, trial) + energies_uhf = local_energy_single_det_uhf(system, ham, walkers, trial) assert numpy.allclose(energies, energies_uhf) @@ -175,7 +175,7 @@ def test_local_energy_single_det_batch_packed(): system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol, ecore=0, @@ -183,7 +183,7 @@ def test_local_energy_single_det_batch_packed(): # options={"symmetry": True}, ) - legacy_hamiltonian = HamGenericRef( + legacy_ham = HamGenericRef( h1e=numpy.array([h1e, h1e]), chol=chol, ecore=0, @@ -192,7 +192,7 @@ def test_local_energy_single_det_batch_packed(): ) # Test PH type wavefunction. - ci_wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -201,30 +201,33 @@ def test_local_energy_single_det_batch_packed(): wfn[:, nelec[0] :] = I[:, occb0] trial = SingleDet(wfn, nelec, nmo) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) numpy.random.seed(7) - legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) - etots, e1s, e2s = get_legacy_walker_energies(system, legacy_hamiltonian, trial, legacy_walkers) + legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) + etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(time_step=qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) for i in range(nsteps): - prop.propagate_walkers(walkers, hamiltonian, trial, 0.0) + prop.propagate_walkers(walkers, ham, trial, 0.0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_batch(system, hamiltonian, walkers, trial) + energies = local_energy_single_det_batch(system, ham, walkers, trial) for iw in range(nwalkers): - assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) + # unnecessary test + # energy = local_energy_single_det_batch(system, ham, walkers, trial, iw = iw) # assert numpy.allclose(energy, energies[iw]) + assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) + assert numpy.allclose(walkers.phib[iw], legacy_walkers[iw].phi[:, nelec[0] :]) assert numpy.allclose(etots[iw], energies[iw, 0]) assert numpy.allclose(e1s[iw], energies[iw, 1]) assert numpy.allclose(e2s[iw], energies[iw, 2]) @@ -317,13 +320,13 @@ def test_local_energy_single_det_batch_rhf_packed(): chol = chol.reshape((nmo * nmo, nchol)) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol, ecore=0, ) - legacy_hamiltonian = HamGenericRef( + legacy_ham = HamGenericRef( h1e=numpy.array([h1e, h1e]), chol=chol, ecore=0, @@ -331,7 +334,7 @@ def test_local_energy_single_det_batch_rhf_packed(): options={"symmetry": True}, ) - ci_wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) + ci_wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) I = numpy.eye(nmo) wfn = numpy.zeros((nmo, sum(nelec)), dtype=numpy.complex128) occa0 = ci_wfn[1][0] @@ -340,33 +343,33 @@ def test_local_energy_single_det_batch_rhf_packed(): wfn[:, nelec[0] :] = I[:, occb0] trial = SingleDet(wfn, nelec, nmo) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) init[:, : nelec[0]] = init[:, nelec[0] :].copy() numpy.random.seed(7) - legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_hamiltonian, nsteps, nwalkers, dt) - etots, e1s, e2s = get_legacy_walker_energies(system, legacy_hamiltonian, trial, legacy_walkers) + legacy_walkers = build_legacy_test_case(ci_wfn, init, system, legacy_ham, nsteps, nwalkers, dt) + etots, e1s, e2s = get_legacy_walker_energies(system, legacy_ham, trial, legacy_walkers) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": 10}) prop = PhaselessGeneric(time_step=qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) walker_opts = dotdict({"rhf": True}) # walkers = SingleDetWalkerBatch( - # system, hamiltonian, trial, nwalkers, init, walker_opts=walker_opts + # system, ham, trial, nwalkers, init, walker_opts=walker_opts # ) walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) walkers.rhf = True for i in range(nsteps): - prop.propagate_walkers(walkers, hamiltonian, trial, 0.0) + prop.propagate_walkers(walkers, ham, trial, 0.0) walkers.reortho() ovlp = greens_function_single_det_batch(walkers, trial) - energies = local_energy_single_det_rhf_batch(system, hamiltonian, walkers, trial) + energies = local_energy_single_det_rhf_batch(system, ham, walkers, trial) for iw in range(nwalkers): assert numpy.allclose(walkers.phia[iw], legacy_walkers[iw].phi[:, : nelec[0]]) diff --git a/ipie/estimators/tests/test_generic_chunked.py b/ipie/estimators/tests/test_generic_chunked.py index 5d62d386..1e2ddcbe 100644 --- a/ipie/estimators/tests/test_generic_chunked.py +++ b/ipie/estimators/tests/test_generic_chunked.py @@ -71,39 +71,39 @@ def test_generic_chunked(): chol = chol.reshape((nmo * nmo, nchol)) system = Generic(nelec=nelec) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, ecore=enuc) - _, wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) + ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, ecore=enuc) + _, wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) - trial.calculate_energy(system, hamiltonian) + trial.calculate_energy(system, ham) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) mpi_handler = MPIHandler(nmembers=3, verbose=(rank == 0)) if comm.rank == 0: print("# Chunking hamiltonian.") - hamiltonian.chunk(mpi_handler) + ham.chunk(mpi_handler) if comm.rank == 0: print("# Chunking trial.") trial.chunk(mpi_handler) prop = PhaselessGenericChunked(time_step=qmc["dt"]) - prop.build(hamiltonian, trial, mpi_handler=mpi_handler) + prop.build(ham, trial, mpi_handler=mpi_handler) init_walker = numpy.hstack([trial.psi0a, trial.psi0b]) walkers = UHFWalkersTrial( - trial, init_walker, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, mpi_handler + trial, init_walker, system.nup, system.ndown, ham.nbasis, nwalkers, mpi_handler ) walkers.build(trial) for i in range(nsteps): - prop.propagate_walkers(walkers, hamiltonian, trial, trial.energy) + prop.propagate_walkers(walkers, ham, trial, trial.energy) walkers.reortho() - energies = local_energy_single_det_batch(system, hamiltonian, walkers, trial) + energies = local_energy_single_det_batch(system, ham, walkers, trial) - energies_chunked = local_energy_single_det_uhf_batch_chunked(system, hamiltonian, walkers, trial) + energies_chunked = local_energy_single_det_uhf_batch_chunked(system, ham, walkers, trial) assert numpy.allclose(energies, energies_chunked) diff --git a/ipie/estimators/tests/test_generic_chunked_gpu.py b/ipie/estimators/tests/test_generic_chunked_gpu.py index 7305f1e3..3e36a90e 100644 --- a/ipie/estimators/tests/test_generic_chunked_gpu.py +++ b/ipie/estimators/tests/test_generic_chunked_gpu.py @@ -78,46 +78,46 @@ def test_generic_chunked_gpu(): chol = chol.reshape((nmo * nmo, nchol)) system = Generic(nelec=nelec) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, chol_packed=chol_packed, ecore=enuc) - wfn = get_random_nomsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, cplx=False) + ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol, chol_packed=chol_packed, ecore=enuc) + wfn = get_random_nomsd(system.nup, system.ndown, ham.nbasis, ndet=1, cplx=False) trial = SingleDet(wfn[0], nelec, nmo) - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) - trial.calculate_energy(system, hamiltonian) + trial.calculate_energy(system, ham) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) mpi_handler = MPIHandler(comm, options={"nmembers": 2}, verbose=(rank == 0)) if comm.rank == 0: print("# Chunking hamiltonian.") - hamiltonian.chunk(mpi_handler) + ham.chunk(mpi_handler) if comm.rank == 0: print("# Chunking trial.") trial.chunk(mpi_handler) prop = PhaselessGenericChunked(time_step=qmc["dt"]) - prop.build(hamiltonian, trial, mpi_handler=mpi_handler) + prop.build(ham, trial, mpi_handler=mpi_handler) walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, mpi_handler=mpi_handler + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, mpi_handler=mpi_handler ) walkers.build(trial) if not no_gpu: prop.cast_to_cupy() - hamiltonian.cast_to_cupy() + ham.cast_to_cupy() trial.cast_to_cupy() walkers.cast_to_cupy() for i in range(nsteps): - prop.propagate_walker_batch(walkers, system, hamiltonian, trial, trial.energy) + prop.propagate_walker_batch(walkers, system, ham, trial, trial.energy) walkers.reortho() trial._rchola = cupy.asarray(trial._rchola) trial._rcholb = cupy.asarray(trial._rcholb) - energies_einsum = local_energy_single_det_batch_gpu(system, hamiltonian, walkers, trial) - energies_chunked = local_energy_single_det_uhf_batch_chunked_gpu(system, hamiltonian, walkers, trial) + energies_einsum = local_energy_single_det_batch_gpu(system, ham, walkers, trial) + energies_chunked = local_energy_single_det_uhf_batch_chunked_gpu(system, ham, walkers, trial) energies_chunked_low_mem = local_energy_single_det_uhf_batch_chunked_gpu( - system, hamiltonian, walkers, trial, max_mem=1e-6 + system, ham, walkers, trial, max_mem=1e-6 ) assert numpy.allclose(energies_einsum, energies_chunked) diff --git a/ipie/estimators/tests/test_generic_complex.py b/ipie/estimators/tests/test_generic_complex.py index 014716f7..105dca02 100644 --- a/ipie/estimators/tests/test_generic_complex.py +++ b/ipie/estimators/tests/test_generic_complex.py @@ -55,22 +55,22 @@ def test_local_energy_single_det_vs_real(): trial_type="single_det", ) - hamiltonian = test_handler.hamiltonian + ham = test_handler.hamiltonian walkers = test_handler.walkers system = Generic(nelec) trial = test_handler.trial - chol = hamiltonian.chol + chol = ham.chol cx_chol = numpy.array(chol, dtype=numpy.complex128) - cx_hamiltonian = HamGeneric( - numpy.array(hamiltonian.H1, dtype=numpy.complex128), cx_chol, hamiltonian.ecore, verbose=False + cx_ham = HamGeneric( + numpy.array(ham.H1, dtype=numpy.complex128), cx_chol, ham.ecore, verbose=False ) - energy = local_energy(system, hamiltonian, walkers, trial) + energy = local_energy(system, ham, walkers, trial) - trial.half_rotate(cx_hamiltonian) - cx_energy = local_energy(system, cx_hamiltonian, walkers, trial) + trial.half_rotate(cx_ham) + cx_energy = local_energy(system, cx_ham, walkers, trial) numpy.testing.assert_allclose(energy, cx_energy, atol=1e-10) @@ -104,21 +104,21 @@ def test_local_energy_single_det_vs_eri(): choltol=1e-10, ) - hamiltonian = test_handler.hamiltonian + ham = test_handler.hamiltonian walkers = test_handler.walkers system = Generic(nelec) trial = test_handler.trial walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) - energy = local_energy(system, hamiltonian, walkers, trial) + energy = local_energy(system, ham, walkers, trial) etot = energy[:, 0] e1 = energy[:, 1] e2 = energy[:, 2] - nbasis = hamiltonian.nbasis - eri = hamiltonian.eri.reshape(nbasis, nbasis, nbasis, nbasis) - h1e = hamiltonian.H1[0] + nbasis = ham.nbasis + eri = ham.eri.reshape(nbasis, nbasis, nbasis, nbasis) + h1e = ham.H1[0] e1ref = numpy.einsum("ij,wij->w", h1e, walkers.Ga + walkers.Gb) @@ -126,7 +126,7 @@ def test_local_energy_single_det_vs_eri(): # testing 2-body term - chol = hamiltonian.chol.copy() + chol = ham.chol.copy() nchol = chol.shape[1] chol = chol.reshape(nbasis, nbasis, nchol) diff --git a/ipie/estimators/tests/test_generic_noci.py b/ipie/estimators/tests/test_generic_noci.py index 226451f0..e2ef046f 100644 --- a/ipie/estimators/tests/test_generic_noci.py +++ b/ipie/estimators/tests/test_generic_noci.py @@ -41,26 +41,26 @@ def test_greens_function_noci(): ndets = 11 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) + ham = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. coeffs, wfn, init = get_random_nomsd( - system.nup, system.ndown, hamiltonian.nbasis, ndet=ndets, init=True + system.nup, system.ndown, ham.nbasis, ndet=ndets, init=True ) trial = NOCI((coeffs, wfn), nelec, nmo) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) g = trial.build_one_rdm() assert np.isclose(g[0].trace(), nelec[0]) assert np.isclose(g[1].trace(), nelec[0]) walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) assert walkers.Gia.shape == (ndets, nwalkers, nmo, nmo) assert walkers.Ghalfa.shape == (ndets, nwalkers, nelec[0], nmo) assert walkers.Ga.shape == (nwalkers, nmo, nmo) assert walkers.Gb.shape == (nwalkers, nmo, nmo) - trial.calc_force_bias(hamiltonian, walkers) + trial.calc_force_bias(ham, walkers) ovlp_gf = trial.calc_greens_function(walkers) ovlp_ov = trial.calc_overlap(walkers) assert np.allclose(ovlp_gf, ovlp_ov) @@ -76,10 +76,10 @@ def test_local_energy_noci(): ndets = 11 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) + ham = HamGeneric(h1e=np.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. coeffs, wfn, init = get_random_nomsd( - system.nup, system.ndown, hamiltonian.nbasis, ndet=ndets, init=True, cplx=False + system.nup, system.ndown, ham.nbasis, ndet=ndets, init=True, cplx=False ) wfn0 = wfn[0].copy() for i in range(len(wfn)): @@ -87,42 +87,42 @@ def test_local_energy_noci(): coeffs[i] = coeffs[0] trial = NOCI((coeffs, wfn), nelec, nmo) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) g = trial.build_one_rdm() walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) - energy = local_energy(system, hamiltonian, walkers, trial) + energy = local_energy(system, ham, walkers, trial) trial_sd = SingleDet(wfn[0], nelec, nmo) walkers_sd = UHFWalkersTrial( - trial_sd, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_sd, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) - energy_sd = local_energy(system, hamiltonian, walkers, trial) + energy_sd = local_energy(system, ham, walkers, trial) assert np.allclose(energy, energy_sd) coeffs, wfn, init = get_random_nomsd( - system.nup, system.ndown, hamiltonian.nbasis, ndet=ndets, init=True, cplx=False + system.nup, system.ndown, ham.nbasis, ndet=ndets, init=True, cplx=False ) trial = NOCI((coeffs, wfn), nelec, nmo) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) g = trial.build_one_rdm() walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) - energy = local_energy(system, hamiltonian, walkers, trial) + energy = local_energy(system, ham, walkers, trial) assert not np.allclose(energy, energy_sd) # Test against PHMSD - wfn, init = get_random_phmsd_opt(system.nup, system.ndown, hamiltonian.nbasis, ndet=11, init=True) + wfn, init = get_random_phmsd_opt(system.nup, system.ndown, ham.nbasis, ndet=11, init=True) trial_phmsd = ParticleHole( wfn, nelec, nmo, ) trial_phmsd.build() - trial_phmsd.half_rotate(hamiltonian) + trial_phmsd.half_rotate(ham) noci = np.zeros((ndets, nmo, sum(nelec))) for idet, (occa, occb) in enumerate(zip(wfn[1], wfn[2])): for iorb, occ in enumerate(occa): @@ -132,25 +132,25 @@ def test_local_energy_noci(): trial = NOCI((wfn[0], noci), nelec, nmo) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) walkers = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers.build(trial) ovlp_noci = trial.calc_overlap(walkers) trial.calc_greens_function(walkers) - fb_noci = trial.calc_force_bias(hamiltonian, walkers) - energy = local_energy(system, hamiltonian, walkers, trial) + fb_noci = trial.calc_force_bias(ham, walkers) + energy = local_energy(system, ham, walkers, trial) walkers_phmsd = UHFWalkersTrial( - trial_phmsd, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_phmsd, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers_phmsd.build(trial_phmsd) trial_phmsd.calc_greens_function(walkers_phmsd) assert np.allclose(ovlp_noci, trial_phmsd.calc_overlap(walkers_phmsd)) assert np.allclose(walkers_phmsd.Ga, walkers.Ga) assert np.allclose(walkers_phmsd.Gb, walkers.Gb) - assert np.allclose(fb_noci, trial_phmsd.calc_force_bias(hamiltonian, walkers)) + assert np.allclose(fb_noci, trial_phmsd.calc_force_bias(ham, walkers)) e_phmsd = local_energy_multi_det_trial_wicks_batch_opt_chunked( - system, hamiltonian, walkers_phmsd, trial_phmsd + system, ham, walkers_phmsd, trial_phmsd ) assert np.allclose(energy, e_phmsd) diff --git a/ipie/estimators/tests/test_generic_phmsd.py b/ipie/estimators/tests/test_generic_phmsd.py index b0b5cc59..3774ca46 100644 --- a/ipie/estimators/tests/test_generic_phmsd.py +++ b/ipie/estimators/tests/test_generic_phmsd.py @@ -65,12 +65,12 @@ def test_greens_function_wicks_opt(): nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=3000, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=3000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # wfn_2 = (ci[:100], oa[:100], ob[:100]) @@ -91,17 +91,17 @@ def test_greens_function_wicks_opt(): numpy.random.seed(7) walkers_wick = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers_wick.build(trial) walkers_slow = UHFWalkersTrial( - trial_slow, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_slow, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers_slow.build(trial_slow) walkers_opt = UHFWalkersTrial( - trial_opt, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_opt, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers_opt.build(trial_opt) @@ -109,15 +109,15 @@ def test_greens_function_wicks_opt(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) for i in range(nsteps): - prop.propagate_walkers(walkers_wick, hamiltonian, trial, 0) + prop.propagate_walkers(walkers_wick, ham, trial, 0) walkers_wick.reortho() numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_opt) + prop.build(ham, trial_opt) for i in range(nsteps): - prop.propagate_walkers(walkers_opt, hamiltonian, trial_opt, 0) + prop.propagate_walkers(walkers_opt, ham, trial_opt, 0) walkers_opt.reortho() numpy.random.seed(7) walkers_slow.phia = walkers_wick.phia @@ -154,13 +154,13 @@ def test_greens_function_edge_cases(): nwalkers = 10 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) + ham = HamGeneric(h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy()) # Test PH type wavefunction. - wfn, init = get_random_phmsd_opt(system.nup, system.ndown, hamiltonian.nbasis, ndet=1, init=True) + wfn, init = get_random_phmsd_opt(system.nup, system.ndown, ham.nbasis, ndet=1, init=True) trial = ParticleHole(wfn, nelec, nmo, verbose=False) trial.build() walkers_wick = UHFWalkersParticleHole( - init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers_wick.build(trial) ovlps_ref_wick = greens_function_multi_det_wicks_opt(walkers_wick, trial) @@ -267,13 +267,13 @@ def test_det_matrix(): nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=3000, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=3000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -282,21 +282,21 @@ def test_det_matrix(): nmo, ) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) walker_batch = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch.build(trial) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) + prop.propagate_walkers(walker_batch, ham, trial, 0) walker_batch.reortho() nexcit = 4 @@ -334,15 +334,15 @@ def test_phmsd_local_energy(): nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) # Test PH type wavefunction. - # wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=5, init=True) + # wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=5, init=True) wfn, init = get_random_phmsd( - system.nup, system.ndown, hamiltonian.nbasis, ndet=3000, init=True, cmplx=True + system.nup, system.ndown, ham.nbasis, ndet=3000, init=True, cmplx=True ) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too @@ -358,17 +358,17 @@ def test_phmsd_local_energy(): nmo, ) trial_slow.build() - trial_slow.half_rotate(hamiltonian) + trial_slow.half_rotate(ham) trial_test = ParticleHoleNonChunked( wfn_2, nelec, nmo, ) trial_test.build() - trial_test.half_rotate(hamiltonian) + trial_test.half_rotate(ham) numpy.random.seed(7) walkers_wick = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walkers_wick.build(trial) @@ -377,24 +377,24 @@ def test_phmsd_local_energy(): options = {"hybrid": True} walker_batch = UHFWalkersTrial( - trial_slow, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_slow, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch.build(trial_slow) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_test.build(trial_test) walker_batch_test2 = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_test2.build(trial) numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_slow) + prop.build(ham, trial_slow) for i in range(nsteps): - prop.propagate_walkers(walker_batch, hamiltonian, trial_slow, 0) + prop.propagate_walkers(walker_batch, ham, trial_slow, 0) walker_batch.reortho() import copy @@ -416,10 +416,10 @@ def test_phmsd_local_energy(): assert numpy.allclose(walker_batch_test2.Gb, walker_batch.Gb) assert numpy.allclose(walker_batch_test.det_ovlpas, walker_batch_test2.det_ovlpas) assert numpy.allclose(walker_batch_test.det_ovlpbs, walker_batch_test2.det_ovlpbs) - e_simple = local_energy_multi_det_trial_batch(system, hamiltonian, walker_batch, trial) - e_wicks = local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walker_batch_test2, trial) + e_simple = local_energy_multi_det_trial_batch(system, ham, walker_batch, trial) + e_wicks = local_energy_multi_det_trial_wicks_batch(system, ham, walker_batch_test2, trial) e_wicks_opt = local_energy_multi_det_trial_wicks_batch_opt( - system, hamiltonian, walker_batch_test, trial_test + system, ham, walker_batch_test, trial_test ) assert numpy.allclose(e_simple, e_wicks) @@ -436,12 +436,12 @@ def test_kernels_energy(): nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, ) - wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=5000, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=5000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -454,15 +454,15 @@ def test_kernels_energy(): numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) walker_batch = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch.build(trial) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) + prop.propagate_walkers(walker_batch, ham, trial, 0) walker_batch.reortho() greens_function_multi_det_wicks_opt(walker_batch, trial) @@ -476,11 +476,11 @@ def test_kernels_energy(): ) ndets = trial.num_dets - nchol = hamiltonian.nchol + nchol = ham.nchol ref = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) test = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) slices_alpha, slices_beta = trial.slices_alpha, trial.slices_beta - nbasis = hamiltonian.nbasis + nbasis = ham.nbasis Laa = shaped_normal((nwalkers, nbasis, system.nup, nchol), cmplx=True) Lbb = shaped_normal((nwalkers, nbasis, system.ndown, nchol), cmplx=True) @@ -654,13 +654,13 @@ def test_kernels_gf(): nsteps = 100 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, # options={"symmetry": False}, ) - wfn, init = get_random_phmsd(system.nup, system.ndown, hamiltonian.nbasis, ndet=5000, init=True) + wfn, init = get_random_phmsd(system.nup, system.ndown, ham.nbasis, ndet=5000, init=True) ci, oa, ob = wfn wfn_2 = (ci[::50], oa[::50], ob[::50]) # Get high excitation determinants too trial = ParticleHoleNonChunked( @@ -673,16 +673,16 @@ def test_kernels_gf(): numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) walker_batch = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch.build(trial) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) + prop.propagate_walkers(walker_batch, ham, trial, 0) walker_batch.reortho() trial.calc_greens_function(walker_batch) @@ -690,7 +690,7 @@ def test_kernels_gf(): from ipie.estimators.kernels.cpu import wicks as wk ndets = trial.num_dets - nchol = hamiltonian.nchol + nchol = ham.nchol ref = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) test = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) ovlpa = walker_batch.det_ovlpas @@ -775,7 +775,7 @@ def test_kernels_gf_active_space(): ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -822,23 +822,23 @@ def test_kernels_gf_active_space(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_ref) + prop.build(ham, trial_ref) init = shaped_normal((nmo, system.ne), cmplx=True) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_ref, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_test.build(trial_test) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch_ref, hamiltonian, trial_ref, 0) + prop.propagate_walkers(walker_batch_ref, ham, trial_ref, 0) walker_batch_ref.reortho() walker_batch_test.phia = walker_batch_ref.phia.copy() @@ -854,7 +854,7 @@ def test_kernels_gf_active_space(): from ipie.estimators.kernels.cpu import wicks as wk ndets = trial_ref.num_dets - nchol = hamiltonian.nchol + nchol = ham.nchol ref = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) test = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) ovlpa = walker_batch_ref.det_ovlpas @@ -962,7 +962,7 @@ def test_kernels_energy_active_space(): ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -1016,21 +1016,21 @@ def test_kernels_energy_active_space(): qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_ref) + prop.build(ham, trial_ref) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_ref, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_test.build(trial_test) numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch_ref, hamiltonian, trial_ref, 0) + prop.propagate_walkers(walker_batch_ref, ham, trial_ref, 0) walker_batch_ref.reortho() walker_batch_test.phia = walker_batch_ref.phia.copy() @@ -1046,7 +1046,7 @@ def test_kernels_energy_active_space(): from ipie.estimators.kernels.cpu import wicks as wk ndets = trial_ref.num_dets - nchol = hamiltonian.nchol + nchol = ham.nchol ref = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) test = numpy.zeros((nwalkers, ndets, nchol), dtype=numpy.complex128) ovlpa = walker_batch_ref.det_ovlpas @@ -1245,7 +1245,7 @@ def test_phmsd_local_energy_active_space(): core = [0, 1] h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -1272,7 +1272,7 @@ def test_phmsd_local_energy_active_space(): nmo, ) trial_ref.build() - trial_ref.half_rotate(hamiltonian) + trial_ref.half_rotate(ham) trial_test = ParticleHoleNonChunked( wfn_2, @@ -1280,21 +1280,21 @@ def test_phmsd_local_energy_active_space(): nmo, ) trial_test.build() - trial_test.half_rotate(hamiltonian) + trial_test.half_rotate(ham) I = numpy.eye(nmo) init = numpy.hstack([I[:, : nelec[0]], I[:, : nelec[1]]]) numpy.random.seed(7) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_ref) + prop.build(ham, trial_ref) walker_batch_ref = UHFWalkersTrial( trial_ref, init, system.nup, system.ndown, - hamiltonian.nbasis, + ham.nbasis, nwalkers, MPIHandler(), ) @@ -1305,7 +1305,7 @@ def test_phmsd_local_energy_active_space(): init, system.nup, system.ndown, - hamiltonian.nbasis, + ham.nbasis, nwalkers, MPIHandler(), ) @@ -1313,7 +1313,7 @@ def test_phmsd_local_energy_active_space(): numpy.random.seed(7) for i in range(nsteps): - prop.propagate_walkers(walker_batch_ref, hamiltonian, trial_ref, 0) + prop.propagate_walkers(walker_batch_ref, ham, trial_ref, 0) walker_batch_ref.reortho() import copy @@ -1333,9 +1333,9 @@ def test_phmsd_local_energy_active_space(): # assert numpy.allclose(walker_batch_test.CIa, walker_batch_ref.CIa) # assert numpy.allclose(walker_batch_test.CIb, walker_batch_ref.CIb) assert trial_ref.nfrozen != trial_test.nfrozen - e_wicks_opt = local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walker_batch_ref, trial_ref) + e_wicks_opt = local_energy_multi_det_trial_wicks_batch(system, ham, walker_batch_ref, trial_ref) e_wicks_opt_act = local_energy_multi_det_trial_wicks_batch_opt( - system, hamiltonian, walker_batch_test, trial_test + system, ham, walker_batch_test, trial_test ) assert numpy.allclose(e_wicks_opt, e_wicks_opt_act) @@ -1352,7 +1352,7 @@ def test_phmsd_local_energy_active_space_polarised(): ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -1376,14 +1376,14 @@ def test_phmsd_local_energy_active_space_polarised(): nmo, ) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) trial_test = ParticleHoleNonChunked( wfn, nelec, nmo, ) trial_test.build() - trial_test.half_rotate(hamiltonian) + trial_test.half_rotate(ham) trial_test_chunked = ParticleHole( wfn, nelec, @@ -1391,43 +1391,43 @@ def test_phmsd_local_energy_active_space_polarised(): num_det_chunks=4, ) trial_test_chunked.build() - trial_test_chunked.half_rotate(hamiltonian) + trial_test_chunked.half_rotate(ham) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) options = {"hybrid": True} walker_batch = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch.build(trial) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_test.build(trial_test) walker_batch_test_chunked = UHFWalkersTrial( - trial_test_chunked, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_test_chunked, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_test_chunked.build(trial_test_chunked) numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) for i in range(nsteps): - prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) + prop.propagate_walkers(walker_batch, ham, trial, 0) walker_batch.reortho() numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_test) + prop.build(ham, trial_test) for i in range(nsteps): - prop.propagate_walkers(walker_batch_test, hamiltonian, trial_test, 0) + prop.propagate_walkers(walker_batch_test, ham, trial_test, 0) walker_batch_test.reortho() numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_test_chunked) + prop.build(ham, trial_test_chunked) for i in range(nsteps): - prop.propagate_walkers(walker_batch_test_chunked, hamiltonian, trial_test_chunked, 0) + prop.propagate_walkers(walker_batch_test_chunked, ham, trial_test_chunked, 0) walker_batch_test_chunked.reortho() greens_function_multi_det(walker_batch, trial, build_full=True) @@ -1439,13 +1439,13 @@ def test_phmsd_local_energy_active_space_polarised(): assert numpy.allclose(walker_batch.Gb, walker_batch_test.Gb) assert numpy.allclose(walker_batch.Ga, walker_batch_test_chunked.Ga) assert numpy.allclose(walker_batch.Gb, walker_batch_test_chunked.Gb) - e_ref = local_energy_multi_det_trial_batch(system, hamiltonian, walker_batch, trial) + e_ref = local_energy_multi_det_trial_batch(system, ham, walker_batch, trial) e_wicks = local_energy_multi_det_trial_wicks_batch_opt( - system, hamiltonian, walker_batch_test, trial_test + system, ham, walker_batch_test, trial_test ) assert numpy.allclose(e_ref, e_wicks) e_wicks_chunked = local_energy_multi_det_trial_wicks_batch_opt_chunked( - system, hamiltonian, walker_batch_test_chunked, trial_test_chunked + system, ham, walker_batch_test_chunked, trial_test_chunked ) @@ -1460,7 +1460,7 @@ def test_phmsd_local_energy_active_space_non_aufbau(): ncore = 2 h1e, chol, enuc, eri = generate_hamiltonian(nmo, nelec, cplx=False) system = Generic(nelec=nelec) - hamiltonian = HamGeneric( + ham = HamGeneric( h1e=numpy.array([h1e, h1e]), chol=chol.reshape((-1, nmo * nmo)).T.copy(), ecore=0, @@ -1503,7 +1503,7 @@ def test_phmsd_local_energy_active_space_non_aufbau(): nmo, ) trial.build() - trial.half_rotate(hamiltonian) + trial.half_rotate(ham) trial_tmp = ParticleHoleNonChunked(wfn_2_no_act, nelec, nmo, use_active_space=False) trial_tmp.build() # Original implementation @@ -1513,7 +1513,7 @@ def test_phmsd_local_energy_active_space_non_aufbau(): nmo, ) trial_ref.build() - trial_ref.half_rotate(hamiltonian) + trial_ref.half_rotate(ham) # Hack to ensure cre_ex_a structures are present for testing. trial_ref.__dict__.update(trial_tmp.__dict__) trial_ref.optimized = False @@ -1522,48 +1522,48 @@ def test_phmsd_local_energy_active_space_non_aufbau(): trial_tmp.build() trial_test = ParticleHole(wfn_2, nelec, nmo, num_det_chunks=10) trial_test.build() - trial_test.half_rotate(hamiltonian) + trial_test.half_rotate(ham) qmc = dotdict({"dt": 0.005, "nstblz": 5, "batched": True, "nwalkers": nwalkers}) options = {"hybrid": True} walker_batch = UHFWalkersTrial( - trial, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch.build(trial) walker_batch_ref = UHFWalkersTrial( - trial_ref, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_ref, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_ref.build(trial_ref) walker_batch_test = UHFWalkersTrial( - trial_test, init, system.nup, system.ndown, hamiltonian.nbasis, nwalkers, MPIHandler() + trial_test, init, system.nup, system.ndown, ham.nbasis, nwalkers, MPIHandler() ) walker_batch_test.build(trial_test) # Naive numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_ref) + prop.build(ham, trial_ref) for i in range(nsteps): - prop.propagate_walkers(walker_batch_ref, hamiltonian, trial_ref, 0) + prop.propagate_walkers(walker_batch_ref, ham, trial_ref, 0) walker_batch_ref.reortho() # No optimization numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial) + prop.build(ham, trial) for i in range(nsteps): - prop.propagate_walkers(walker_batch, hamiltonian, trial, 0) + prop.propagate_walkers(walker_batch, ham, trial, 0) walker_batch.reortho() # chunked numpy.random.seed(7) prop = PhaselessGeneric(qmc["dt"]) - prop.build(hamiltonian, trial_test) + prop.build(ham, trial_test) for i in range(nsteps): - prop.propagate_walkers(walker_batch_test, hamiltonian, trial_test, 0) + prop.propagate_walkers(walker_batch_test, ham, trial_test, 0) walker_batch_test.reortho() import copy @@ -1588,13 +1588,13 @@ def test_phmsd_local_energy_active_space_non_aufbau(): assert numpy.allclose(walker_batch_test.det_ovlpas, walker_batch_ref.det_ovlpas) assert numpy.allclose(walker_batch_test.det_ovlpbs, walker_batch_ref.det_ovlpbs) assert trial_ref.nfrozen != trial_test.nfrozen - e_wicks = local_energy_multi_det_trial_batch(system, hamiltonian, walker_batch, trial) - e_wicks_opt = local_energy_multi_det_trial_wicks_batch(system, hamiltonian, walker_batch_ref, trial_ref) + e_wicks = local_energy_multi_det_trial_batch(system, ham, walker_batch, trial) + e_wicks_opt = local_energy_multi_det_trial_wicks_batch(system, ham, walker_batch_ref, trial_ref) e_wicks_opt_act = local_energy_multi_det_trial_wicks_batch_opt( - system, hamiltonian, walker_batch_test, trial_test + system, ham, walker_batch_test, trial_test ) e_wicks_opt_chunk = local_energy_multi_det_trial_wicks_batch_opt_chunked( - system, hamiltonian, walker_batch_test, trial_test + system, ham, walker_batch_test, trial_test ) assert numpy.allclose(e_wicks, e_wicks_opt) @@ -1604,15 +1604,10 @@ def test_phmsd_local_energy_active_space_non_aufbau(): if __name__ == "__main__": test_greens_function_wicks_opt() - test_greens_function_edge_cases() - test_cofactor_matrix() - test_cofactor_matrix_4() - test_det_matrix() - test_phmsd_local_energy() - test_kernels_energy() - test_kernels_gf() - test_kernels_gf_active_space() - test_kernels_energy_active_space() - test_phmsd_local_energy_active_space() - test_phmsd_local_energy_active_space_polarised() - test_phmsd_local_energy_active_space_non_aufbau() + # test_cofactor_matrix() + # test_cofactor_matrix_4() + # test_det_matrix() + # test_phmsd_local_energy() + # test_kernels_energy() + # test_kernels_gf() + # test_kernels_gf_active_space() diff --git a/ipie/utils/testing.py b/ipie/utils/testing.py index 8b3bb926..941e2d9e 100644 --- a/ipie/utils/testing.py +++ b/ipie/utils/testing.py @@ -46,27 +46,14 @@ from ipie.walkers.walkers_dispatch import UHFWalkersTrial -def generate_hamiltonian(nmo, nelec, cplx=False, sym=8, sparse=False, tol=1e-3): - h1e, eri = None, None - if sparse: - h1e = scipy.sparse.random(nmo, nmo).toarray() - if cplx: - h1e = h1e + 1j * scipy.sparse.random(nmo, nmo).toarray() - - rvs = scipy.stats.norm(scale=0.01).rvs - eri = scipy.sparse.random(nmo**2, nmo**2, data_rvs=rvs).toarray() - if cplx: - eri = eri + 1j * scipy.sparse.random(nmo**2, nmo**2, data_rvs=rvs).toarray() - eri = eri.reshape((nmo, nmo, nmo, nmo)) - - else: - h1e = numpy.random.random((nmo, nmo)) - if cplx: - h1e = h1e + 1j * numpy.random.random((nmo, nmo)) +def generate_hamiltonian(nmo, nelec, cplx=False, sym=8, tol=1e-3): + h1e = numpy.random.random((nmo, nmo)) + if cplx: + h1e = h1e + 1j * numpy.random.random((nmo, nmo)) - eri = numpy.random.normal(scale=0.01, size=(nmo, nmo, nmo, nmo)) - if cplx: - eri = eri + 1j * numpy.random.normal(scale=0.01, size=(nmo, nmo, nmo, nmo)) + eri = numpy.random.normal(scale=0.01, size=(nmo, nmo, nmo, nmo)) + if cplx: + eri = eri + 1j * numpy.random.normal(scale=0.01, size=(nmo, nmo, nmo, nmo)) # Restore symmetry to the integrals. if sym >= 4: From 81171a4d1b5a2b8d5000e86bd89eac324ad2876f Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Tue, 12 Mar 2024 21:28:11 -0400 Subject: [PATCH 57/84] Remove 0T tests. --- examples/14-ft_afqmc/run_afqmc.py | 4 +- .../estimators/tests/test_generic_complex.py | 57 +--- .../propagation/tests/ueg/test_ueg_0T.py | 250 ------------------ 3 files changed, 4 insertions(+), 307 deletions(-) delete mode 100644 ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py diff --git a/examples/14-ft_afqmc/run_afqmc.py b/examples/14-ft_afqmc/run_afqmc.py index e4279413..5448b07a 100644 --- a/examples/14-ft_afqmc/run_afqmc.py +++ b/examples/14-ft_afqmc/run_afqmc.py @@ -42,10 +42,10 @@ 'mu': 0.133579, 'beta': 10, 'timestep': 0.05, - 'nwalkers': 576 // comm.size, + 'nwalkers': 12 // comm.size, 'nstack': 10, 'seed': 7, - 'nblocks': 200, + 'nblocks': 30, }, } diff --git a/ipie/addons/thermal/estimators/tests/test_generic_complex.py b/ipie/addons/thermal/estimators/tests/test_generic_complex.py index 11e19902..50d23a53 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/addons/thermal/estimators/tests/test_generic_complex.py @@ -2,12 +2,7 @@ import pytest from typing import Tuple, Union -from ipie.utils.misc import dotdict -from ipie.utils.testing import build_test_case_handlers as build_test_case_handlers_0T -from ipie.systems.generic import Generic from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.estimators.energy import local_energy - from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G @@ -129,54 +124,6 @@ def test_local_energy_vs_eri(): numpy.testing.assert_allclose(etot, etotref, atol=1e-10) -@pytest.mark.unit -def test_local_energy_0T_single_det(): - numpy.random.seed(7) - nmo = 10 - nelec = (6, 5) - nwalkers = 12 - nsteps = 25 - qmc = dotdict( - { - "dt": 0.005, - "nstblz": 5, - "nwalkers": nwalkers, - "hybrid": True, - "num_steps": nsteps, - } - ) - - print('test_local_energy_0T_single_det: here') - handler_0T = build_test_case_handlers_0T( - nelec, - nmo, - num_dets=1, - options=qmc, - seed=7, - complex_integrals=False, - complex_trial=True, - trial_type="single_det", - choltol=1e-10, - ) - - system = Generic(nelec=nelec) - hamiltonian = handler_0T.hamiltonian - walkers = handler_0T.walkers - trial = handler_0T.trial - walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) - energy = local_energy(system, hamiltonian, walkers, trial) - test_energy = numpy.array( - [local_energy_generic_cholesky( - hamiltonian, - numpy.array([walkers.Ga[0], walkers.Gb[0]]))]) - - print(f'\n0T energy = \n{energy}\n') - print(f'test_energy = \n{test_energy}\n') - - numpy.testing.assert_allclose(energy, test_energy, atol=1e-10) - - if __name__ == '__main__': - #test_local_energy_vs_real() - #test_local_energy_vs_eri() - test_local_energy_0T_single_det() + test_local_energy_vs_real() + test_local_energy_vs_eri() diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py b/ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py deleted file mode 100644 index 1d9e2c59..00000000 --- a/ipie/addons/thermal/propagation/tests/ueg/test_ueg_0T.py +++ /dev/null @@ -1,250 +0,0 @@ -import numpy -import pytest - -from ueg import UEG -from pyscf import gto, scf, ao2mo - -from ipie.utils.mpi import MPIHandler -from ipie.qmc.options import QMCOpts - -from ipie.systems.generic import Generic -from ipie.utils.testing import generate_hamiltonian -from ipie.hamiltonians.generic import Generic as HamGeneric -from ipie.hamiltonians.utils import get_hamiltonian -from ipie.trial_wavefunction.single_det import SingleDet -from ipie.walkers.walkers_dispatch import UHFWalkersTrial -from ipie.estimators.local_energy import local_energy_G - -from ipie.legacy.systems.ueg import UEG as LegacyUEG -from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG -from ipie.legacy.trial_wavefunction.free_electron import FreeElectron -from ipie.legacy.trial_wavefunction.multi_slater import MultiSlater -from ipie.legacy.walkers.handler import Walkers -from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg -from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G - - -def setup_objs(seed=None): - mu = -10. - nwalkers = 1 - nblocks = 10 - nsteps_per_block = 1 - timestep = 0.005 - verbose = True - numpy.random.seed(seed) - - options = { - "qmc": { - "nwalkers": nwalkers, - "blocks": nblocks, - "nsteps": nsteps_per_block, - "timestep": timestep, - "rng_seed": seed, - "batched": False - }, - } - - # Generate UEG integrals. - ueg_opts = { - "nup": 7, - "ndown": 7, - "rs": 1., - "ecut": 2.5, - "thermal": False, - "write_integrals": False, - } - - ueg = UEG(ueg_opts, verbose=verbose) - ueg.build() - nbasis = ueg.nbasis - nchol = ueg.nchol - nelec = (ueg.nup, ueg.ndown) - nup, ndown = nelec - - h1 = ueg.H1[0] - chol = 2. * ueg.chol_vecs.toarray() - #ecore = ueg.ecore - ecore = 0. - - # ------------------------------------------------------------------------- - # Build trial wavefunction. - # For pyscf. - U = ueg.compute_real_transformation() - h1_8 = U.T.conj() @ h1 @ U - eri_8 = ueg.eri_8() # 8-fold eri - eri_8 = ao2mo.restore(8, eri_8, nbasis) - - mol = gto.M() - mol.nelectron = numpy.sum(nelec) - mol.spin = nup - ndown - mol.max_memory = 60000 # MB - mol.incore_anyway = True - - # PW guess. - dm0a = numpy.zeros(nbasis) - dm0b = numpy.zeros(nbasis) - dm0a[:nup] = 1 - dm0b[:ndown] = 1 - dm0 = numpy.array([numpy.diag(dm0a), numpy.diag(dm0b)]) - - mf = scf.UHF(mol) - #mf.level_shift = 0.5 - mf.max_cycle = 5000 - mf.get_hcore = lambda *args: h1_8 - mf.get_ovlp = lambda *args: numpy.eye(nbasis) - mf._eri = eri_8 - e = mf.kernel(dm0) - - Ca, Cb = mf.mo_coeff - psia = Ca[:, :nup] - psib = Cb[:, :ndown] - psi0 = numpy.zeros((nbasis, numpy.sum(nelec)), dtype=numpy.complex128) - psi0[:, :nup] = psia - psi0[:, nup:] = psib - #numpy.save('ueg_trial', psi0) - - if verbose: - print(numpy.amax(numpy.absolute(chol.imag))) - print(f"# nbasis = {nbasis}") - print(f"# nchol = {nchol}") - print(f"# nup = {nup}") - print(f"# ndown = {ndown}") - - # ------------------------------------------------------------------------- - # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - - # 1. Build out system. - system = Generic(nelec=nelec, verbose=verbose) - - # 2. Build Hamiltonian. - hamiltonian = HamGeneric( - numpy.array([h1, h1], dtype=numpy.complex128), - numpy.array(chol, dtype=numpy.complex128), - ecore, - verbose=verbose) - - # 3. Build trial. - trial = SingleDet(psi0, nelec, nbasis, cplx=True, verbose=verbose) - trial.build() - trial.half_rotate(hamiltonian) - trial.calculate_energy(system, hamiltonian) - if verbose: print(f"\n# trial.energy = {trial.energy}\n") - - # Check against RHF solutions of 10.1063/1.5109572 - assert numpy.allclose(numpy.around(trial.energy, 6), 13.603557) # rs = 1, nbasis = 57 - assert numpy.allclose(trial.energy, e) - - # 4. Build walkers. - walkers = UHFWalkersTrial(trial, psi0, system.nup, system.ndown, hamiltonian.nbasis, - nwalkers, MPIHandler(), verbose=verbose) - walkers.build(trial) - walkers.ovlp = trial.calc_greens_function(walkers, build_full=True) - - # ------------------------------------------------------------------------- - # Legacy. - legacy_opts = { - "trial": { - "read_in": "ueg_trial.npy" - }, - - "qmc": options["qmc"], - } - - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - - # 1. Build out system. - legacy_system = LegacyUEG(options=ueg_opts) - - # 2. Build Hamiltonian. - legacy_hamiltonian = LegacyHamUEG(legacy_system, options=ueg_opts) - - # 3. Build trial. - coeffs = numpy.array([1]) - psi = numpy.array([psi0]) - wfn = [coeffs, psi] - legacy_trial = MultiSlater(legacy_system, legacy_hamiltonian, wfn, - nbasis=nbasis, cplx=True, verbose=verbose) - - # 4. Build walkers. - qmc_opts = QMCOpts() - qmc_opts.nwalkers = nwalkers - qmc_opts.ntot_walkers = nwalkers - qmc_opts.nsteps = nsteps_per_block - qmc_opts.dt = timestep - qmc_opts.seed = seed - - legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, - qmc_opts, verbose=verbose) - - objs = {'system': system, - 'trial': trial, - 'hamiltonian': hamiltonian, - 'walkers': walkers} - - legacy_objs = {'system': legacy_system, - 'trial': legacy_trial, - 'hamiltonian': legacy_hamiltonian, - 'walkers': legacy_walkers} - - return objs, legacy_objs - - -@pytest.mark.unit -def test_ueg_0T(verbose=False): - seed = 7 - objs, legacy_objs = setup_objs(seed=seed) - system = objs['system'] - trial = objs['trial'] - hamiltonian = objs['hamiltonian'] - walkers = objs['walkers'] - - legacy_system = legacy_objs['system'] - legacy_trial = legacy_objs['trial'] - legacy_hamiltonian = legacy_objs['hamiltonian'] - legacy_walkers = legacy_objs['walkers'] - - h1e = legacy_hamiltonian.H1[0] - eri = legacy_hamiltonian.eri_4() - - for iw in range(walkers.nwalkers): - G = numpy.array([walkers.Ga[iw], walkers.Gb[iw]]) - Ghalf = numpy.array([walkers.Ghalfa[iw], walkers.Ghalfb[iw]]) - eloc = local_energy_G(system, hamiltonian, trial, G, Ghalf) - - legacy_eloc = legacy_local_energy_ueg(legacy_system, legacy_hamiltonian, legacy_walkers.walkers[iw].G) - legacy_Ga, legacy_Gb = legacy_walkers.walkers[iw].G - legacy_Gtot = legacy_Ga + legacy_Gb - ref_e1 = numpy.einsum('ij,ij->', h1e, legacy_Gtot) - - Gtot = legacy_Gtot - Ga = legacy_Ga - Gb = legacy_Gb - - ecoul = 0.5 * numpy.einsum('ijkl,ij,kl->', eri, Gtot, Gtot) - exx = -0.5 * numpy.einsum('ijkl,il,kj->', eri, Ga, Ga) - exx -= 0.5 * numpy.einsum('ijkl,il,kj->', eri, Gb, Gb) - ref_e2 = ecoul + exx - ref_eloc = (ref_e1 + ref_e2, ref_e1, ref_e2) - - if verbose: - print(f'\niw = {iw}') - print(f'eloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') - print(f'ref_eloc = \n{ref_eloc}\n') - print(f'walkers.weight = \n{walkers.weight[iw]}\n') - print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') - - numpy.testing.assert_allclose(eloc, ref_eloc, atol=1e-10) - numpy.testing.assert_allclose(legacy_eloc, ref_eloc, atol=1e-10) - numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw], decimal=10) - numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) - - -if __name__ == "__main__": - test_ueg_0T(verbose=True) From b5e32e19cb8cc884b90c46caf46624c7ed2fcaff Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Tue, 12 Mar 2024 22:22:38 -0400 Subject: [PATCH 58/84] Add FT MPI integration test reference files. --- .../ft_4x4_hubbard_discrete/input.json | 32 +++++++++++++++++++ .../ft_4x4_hubbard_discrete/reference.json | 1 + .../ft_ueg_ecut1.0_rs1.0/input.json | 32 +++++++++++++++++++ .../ft_ueg_ecut1.0_rs1.0/reference.json | 1 + 4 files changed, 66 insertions(+) create mode 100644 ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/input.json create mode 100644 ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference.json create mode 100644 ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json create mode 100644 ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json diff --git a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/input.json b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/input.json new file mode 100644 index 00000000..3a3b9be6 --- /dev/null +++ b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/input.json @@ -0,0 +1,32 @@ +{ + "system": { + "name": "Hubbard", + "nx": 4, + "ny": 4, + "nup": 7, + "ndown": 7, + "mu": 0.1, + "U": 4 + }, + "qmc": { + "dt": 0.01, + "nwalkers": 32, + "blocks": 10, + "nsteps": 10, + "rng_seed": 7, + "beta": 0.25, + "pop_control_freq": 5, + "stabilise_freq": 10, + "batched": false + }, + "trial": { + "name": "one_body" + }, + "walkers": { + "pop_control": "comb" + }, + "propagator": { + "hubbard_stratonovich": "discrete" + }, + "estimators": {} +} diff --git a/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference.json b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference.json new file mode 100644 index 00000000..904b376c --- /dev/null +++ b/ipie/qmc/tests/reference_data/ft_4x4_hubbard_discrete/reference.json @@ -0,0 +1 @@ +{"WeightFactor": [32.0, 44.98447572409485], "Weight": [32.0, 42.93486118721573], "ENumer": [152.0047418107582, 24.59220437157029], "EDenom": [32.0, 42.93486118721573], "ETotal": [4.7501481815861935, 0.5727794079579522], "E1Body": [-7.499853241434115, -7.179410491868211], "E2Body": [12.250001423020308, 7.752189899826164], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000813154433, 13.205553548235017], "sys_info": {"nranks": 4, "branch": "develop", "sha1": "5de52c915d59fc1e026bb3b42812f6daa4d1010b", "numpy": {"version": "1.18.4", "path": "/usr/local/lib/python3.7/site-packages/numpy", "BLAS": {"lib": "openblas openblas", "path": "/usr/local/lib"}}, "scipy": {"version": "1.4.1", "path": "/usr/local/lib/python3.7/site-packages/scipy"}, "h5py": {"version": "2.10.0", "path": "/usr/local/lib/python3.7/site-packages/h5py"}, "mpi4py": {"version": "3.0.1", "path": "/usr/local/lib/python3.7/site-packages/mpi4py", "mpicc": "/usr/local/bin/mpicc"}}} \ No newline at end of file diff --git a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json new file mode 100644 index 00000000..65f888c9 --- /dev/null +++ b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/input.json @@ -0,0 +1,32 @@ +{ + "system": { + "name": "UEG", + "nup": 7, + "ndown": 7, + "rs": 1.0, + "mu": -1.0, + "ecut": 1.0 + }, + "qmc": { + "dt": 0.01, + "nwalkers": 32, + "blocks": 10, + "nsteps": 10, + "beta": 0.1, + "rng_seed": 7, + "pop_control_freq": 1, + "stabilise_freq": 10, + "batched": false + }, + "trial": { + "name": "one_body" + }, + "walkers": { + "population_control": "pair_branch" + }, + "estimators": { + "mixed": { + "one_rdm": true + } + } +} diff --git a/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json new file mode 100644 index 00000000..d1cfd38b --- /dev/null +++ b/ipie/qmc/tests/reference_data/ft_ueg_ecut1.0_rs1.0/reference.json @@ -0,0 +1 @@ +{"WeightFactor": [32.0, 47.947639102045635], "Weight": [32.0, 31.999999999999993], "ENumer": [853.4128425513718, 986.7978362646822], "EDenom": [32.0, 31.999999999999993], "ETotal": [26.66915132973037, 30.837432383271327], "E1Body": [28.374994808285745, 33.217171356971804], "E2Body": [-1.705843478555375, -2.379738973700476], "EHybrid": [0.0, 0.0], "Overlap": [1.0, 1.0], "Nav": [14.000000381209672, 16.37587194751124]} \ No newline at end of file From 11db442291901c856e03aec0a7381fbdee9ac965 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 13 Mar 2024 15:22:50 -0400 Subject: [PATCH 59/84] Edit example to be less computationally expensive. --- examples/14-ft_afqmc/run_afqmc.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/14-ft_afqmc/run_afqmc.py b/examples/14-ft_afqmc/run_afqmc.py index 5448b07a..c2dbd017 100644 --- a/examples/14-ft_afqmc/run_afqmc.py +++ b/examples/14-ft_afqmc/run_afqmc.py @@ -40,8 +40,8 @@ 'qmc': { 'mu': 0.133579, - 'beta': 10, - 'timestep': 0.05, + 'beta': 0.1, + 'timestep': 0.01, 'nwalkers': 12 // comm.size, 'nstack': 10, 'seed': 7, From 598b023ac9d7cb3cfc410520c8dd2726197d327e Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 13 Mar 2024 15:25:11 -0400 Subject: [PATCH 60/84] Fix `pylint` error and update tests. --- ipie/addons/thermal/qmc/calc.py | 1 + .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 197 +++++++++++++++++- ipie/addons/thermal/qmc/thermal_afqmc.py | 3 +- ipie/addons/thermal/reference_data/ueg/note | 1 - .../walkers/tests/test_thermal_walkers.py | 2 +- 5 files changed, 195 insertions(+), 9 deletions(-) delete mode 100644 ipie/addons/thermal/reference_data/ueg/note diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index eb59a26e..656e2573 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -95,6 +95,7 @@ def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: if (comm.rank == 0) and (qmc.nsteps > 1): print("Only num_steps_per_block = 1 allowed in thermal code! Resetting to value of 1.") + # pylint: disable = no-value-for-parameter params = ThermalQMCParams( mu=qmc.mu, beta=qmc.beta, diff --git a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index ac3a2e3c..c32af276 100644 --- a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -265,14 +265,198 @@ def test_thermal_afqmc(against_ref=False): mu = -1. beta = 0.1 timestep = 0.01 - nwalkers = 32 // comm.size + nwalkers = 32 # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! nsteps_per_block = 1 - nblocks = 11 + nblocks = 10 stabilize_freq = 10 pop_control_freq = 1 + pop_control_method = "pair_branch" + #pop_control_method = "comb" + lowrank = False + + verbose = False if (comm.rank != 0) else True + debug = True + seed = 7 + numpy.random.seed(seed) + + with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: + options = { + 'nelec': nelec, + 'mu': mu, + 'beta': beta, + 'timestep': timestep, + 'nwalkers': nwalkers, + 'seed': seed, + 'nsteps_per_block': nsteps_per_block, + 'nblocks': nblocks, + 'stabilize_freq': stabilize_freq, + 'pop_control_freq': pop_control_freq, + 'pop_control_method': pop_control_method, + 'lowrank': lowrank, - # `pop_control_method` doesn't matter for 1 walker. + "ueg_opts": { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + }, + + "estimators": { + "filename": tmpf2.name, # For legacy. + }, + } + + # --------------------------------------------------------------------- + # Test. + # --------------------------------------------------------------------- + if verbose: + print('\n-----------------------') + print('Running ThermalAFQMC...') + print('-----------------------') + + afqmc = build_driver_ueg_test_instance(options, seed, debug, verbose) + afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) + afqmc.finalise() + afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) + + test_energy_data = None + test_energy_numer = None + test_energy_denom = None + test_number_data = None + + if comm.rank == 0: + test_energy_data = extract_observable(afqmc.estimators.filename, "energy") + test_energy_numer = afqmc.estimators["energy"]["ENumer"] + test_energy_denom = afqmc.estimators["energy"]["EDenom"] + test_number_data = extract_observable(afqmc.estimators.filename, "nav") + + # --------------------------------------------------------------------- + # Legacy. + # --------------------------------------------------------------------- + if verbose: + print('\n------------------------------') + print('Running Legacy ThermalAFQMC...') + print('------------------------------') + + legacy_afqmc = build_legacy_driver_ueg_test_instance( + afqmc.hamiltonian, comm, options, seed, verbose) + legacy_afqmc.run(comm=comm) + legacy_afqmc.finalise(verbose=False) + legacy_afqmc.estimators.estimators["mixed"].update( + legacy_afqmc.qmc, + legacy_afqmc.system, + legacy_afqmc.hamiltonian, + legacy_afqmc.trial, + legacy_afqmc.walk, + 0, + legacy_afqmc.propagators.free_projection) + + legacy_mixed_data = None + enum = None + legacy_energy_numer = None + legacy_energy_denom = None + + if comm.rank == 0: + legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) + enum = legacy_afqmc.estimators.estimators["mixed"].names + legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] + legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] + + print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') + print(f'test filename: {afqmc.estimators.filename}') + print(f'legacy filename: {legacy_afqmc.estimators.filename}') + print(f'\ntest_energy_data: \n{test_energy_data}\n') + print(f'test_number_data: \n{test_number_data}\n') + print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') + + # Check. + assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) + assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) + assert test_energy_numer.imag == pytest.approx(legacy_energy_numer.imag) + assert test_energy_denom.imag == pytest.approx(legacy_energy_denom.imag) + + assert numpy.mean(test_energy_data.WeightFactor.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.WeightFactor.values[1:-1].real)) + assert numpy.mean(test_energy_data.Weight.values[1:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Weight.values[1:-1].real)) + assert numpy.mean(test_energy_data.ENumer.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ENumer.values[:-1].real)) + assert numpy.mean(test_energy_data.EDenom.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EDenom.values[:-1].real)) + assert numpy.mean(test_energy_data.ETotal.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.ETotal.values[:-1].real)) + assert numpy.mean(test_energy_data.E1Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E1Body.values[:-1].real)) + assert numpy.mean(test_energy_data.E2Body.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.E2Body.values[:-1].real)) + assert numpy.mean(test_energy_data.HybridEnergy.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.EHybrid.values[:-1].real)) + assert numpy.mean(test_number_data.Nav.values[:-1].real) == pytest.approx( + numpy.mean(legacy_mixed_data.Nav.values[:-1].real)) + + # --------------------------------------------------------------------- + # Test against reference data. + if against_ref: + _data_dir = os.path.abspath(os.path.dirname(__file__)).split("qmc")[0] + "/reference_data/" + _legacy_test_dir = "ueg" + _legacy_test = _data_dir + _legacy_test_dir + "/reference_nompi.json" + + test_name = _legacy_test_dir + with open(_legacy_test, "r") as f: + ref_data = json.load(f) + + skip_val = ref_data.get("extract_skip_value", 10) + _test_energy_data = test_energy_data[::skip_val].to_dict(orient="list") + _test_number_data = test_number_data[::skip_val].to_dict(orient="list") + energy_comparison = compare_test_data(ref_data, _test_energy_data) + number_comparison = compare_test_data(ref_data, _test_number_data) + + print('\nenergy comparison:') + pprint.pprint(energy_comparison) + print('\nnumber comparison:') + pprint.pprint(number_comparison) + + local_err_count = 0 + + for k, v in energy_comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + + for k, v in number_comparison.items(): + if not v[-1]: + local_err_count += 1 + print(f"\n *** FAILED *** : mismatch between benchmark and test run: {test_name}") + print(f" name = {k}\n ref = {v[0]}\n test = {v[1]}\n delta = {v[0]-v[1]}\n") + + if local_err_count == 0: + print(f"\n*** PASSED : {test_name} ***\n") + + +@pytest.mark.mpi +def test_thermal_afqmc_mpi(against_ref=False): + # UEG params. + nup = 7 + ndown = 7 + nelec = (nup, ndown) + rs = 1. + ecut = 1. + + # Thermal AFQMC params. + mu = -1. + beta = 0.1 + timestep = 0.01 + nwalkers = 32 // comm.size + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 + nblocks = 10 + stabilize_freq = 10 + pop_control_freq = 1 pop_control_method = "pair_branch" #pop_control_method = "comb" lowrank = False @@ -403,7 +587,7 @@ def test_thermal_afqmc(against_ref=False): # --------------------------------------------------------------------- # Test against reference data. if against_ref: - _data_dir = os.path.abspath(os.path.dirname(__file__)).split("ueg")[0] + "/reference_data/" + _data_dir = os.path.abspath(os.path.dirname(__file__)).split("qmc")[0] + "/reference_data/" _legacy_test_dir = "ueg" _legacy_test = _data_dir + _legacy_test_dir + "/reference.json" @@ -441,6 +625,7 @@ def test_thermal_afqmc(against_ref=False): if __name__ == '__main__': - test_thermal_afqmc_1walker(against_ref=False) - #test_thermal_afqmc() + #test_thermal_afqmc_1walker(against_ref=True) + #test_thermal_afqmc(against_ref=True) + test_thermal_afqmc_mpi(against_ref=True) diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 98be0421..9808a2e8 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -121,7 +121,8 @@ def build( else: comm = mpi_handler.comm - + + # pylint: disable = no-value-for-parameter params = ThermalQMCParams( mu=mu, beta=beta, diff --git a/ipie/addons/thermal/reference_data/ueg/note b/ipie/addons/thermal/reference_data/ueg/note deleted file mode 100644 index d8220d22..00000000 --- a/ipie/addons/thermal/reference_data/ueg/note +++ /dev/null @@ -1 +0,0 @@ -`reference_nompi.json` and `reference.json` results were generated using weight updates in the legacy code. diff --git a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py index b8bf759a..86ba3d6f 100644 --- a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py @@ -106,7 +106,7 @@ def test_thermal_walkers_fullrank(): numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) -@pytest.mark.unit +#@pytest.mark.unit def test_thermal_walkers_lowrank(): # System params. nup = 5 From 3ad8b766f5cfd691e9bb3f0c8d5d04ce8b52a9a8 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 13 Mar 2024 15:47:23 -0400 Subject: [PATCH 61/84] Update example --- examples/14-ft_afqmc/run_afqmc.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/14-ft_afqmc/run_afqmc.py b/examples/14-ft_afqmc/run_afqmc.py index c2dbd017..73063a12 100644 --- a/examples/14-ft_afqmc/run_afqmc.py +++ b/examples/14-ft_afqmc/run_afqmc.py @@ -40,12 +40,12 @@ 'qmc': { 'mu': 0.133579, - 'beta': 0.1, - 'timestep': 0.01, + 'beta': 10., + 'timestep': 1., 'nwalkers': 12 // comm.size, 'nstack': 10, 'seed': 7, - 'nblocks': 30, + 'nblocks': 50, }, } From c3749868dca542b8f78c646e90b7b0bb7aca007a Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 13 Mar 2024 15:49:00 -0400 Subject: [PATCH 62/84] Add `__init__.py` file for `pytest`. --- ipie/addons/thermal/estimators/tests/__init__.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 ipie/addons/thermal/estimators/tests/__init__.py diff --git a/ipie/addons/thermal/estimators/tests/__init__.py b/ipie/addons/thermal/estimators/tests/__init__.py new file mode 100644 index 00000000..381108b3 --- /dev/null +++ b/ipie/addons/thermal/estimators/tests/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + From 63a0d3c8e054d0046470065a9611f2af3b33603d Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 16 Mar 2024 13:56:30 -0400 Subject: [PATCH 63/84] Remove `ueg_kernels` import. Use legacy's `update_weight` in propagation.`` --- .../thermal/propagation/phaseless_base.py | 14 +-- .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 6 +- ipie/addons/thermal/utils/legacy_fock.py | 8 ++ .../addons/thermal/utils/legacy_mean_field.py | 114 ++++++++++++++++++ ipie/addons/thermal/utils/legacy_testing.py | 3 +- ipie/addons/thermal/utils/ueg.py | 4 +- 6 files changed, 134 insertions(+), 15 deletions(-) create mode 100644 ipie/addons/thermal/utils/legacy_fock.py create mode 100644 ipie/addons/thermal/utils/legacy_mean_field.py diff --git a/ipie/addons/thermal/propagation/phaseless_base.py b/ipie/addons/thermal/propagation/phaseless_base.py index ed3fad1d..2508d2e5 100644 --- a/ipie/addons/thermal/propagation/phaseless_base.py +++ b/ipie/addons/thermal/propagation/phaseless_base.py @@ -227,12 +227,10 @@ def propagate_walkers(self, walkers, hamiltonian, trial, eshift=0., debug=False) walkers.calc_greens_function(iw, slice_ix=tix, inplace=True) # 3. Compute det(G/G') - # Now apply phaseless approximation - if debug: - self.update_weight_legacy(walkers, iw, G, cfb, cmf, eshift) - - else: - self.update_weight(walkers, iw, G, cfb, cmf, eshift) + # Now apply phaseless approximation. + # Use legacy thermal weight update for now. + self.update_weight_legacy(walkers, iw, G, cfb, cmf, eshift) + #self.update_weight(walkers, iw, G, cfb, cmf, eshift) self.timer.tupdate += time.time() - start_time @@ -279,10 +277,6 @@ def update_weight_legacy(self, walkers, iw, G, cfb, cmf, eshift): # Might want to cap this at some point. hybrid_energy = cmath.log(oratio) + _cfb + _cmf Q = cmath.exp(hybrid_energy) - #hybrid_energy = -(cmath.log(oratio) + _cfb + _cmf) / self.dt - #walkers.hybrid_energy = hybrid_energy + self.mf_core - #Q = cmath.exp(-self.dt * hybrid_energy) - #hybrid_energy = cmath.log(oratio) + _cfb + _cmf expQ = self.mf_const_fac * Q (magn, phase) = cmath.polar(expQ) diff --git a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index c32af276..1bd168dd 100644 --- a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -625,7 +625,7 @@ def test_thermal_afqmc_mpi(against_ref=False): if __name__ == '__main__': - #test_thermal_afqmc_1walker(against_ref=True) - #test_thermal_afqmc(against_ref=True) - test_thermal_afqmc_mpi(against_ref=True) + test_thermal_afqmc_1walker(against_ref=True) + test_thermal_afqmc(against_ref=True) + #test_thermal_afqmc_mpi(against_ref=True) diff --git a/ipie/addons/thermal/utils/legacy_fock.py b/ipie/addons/thermal/utils/legacy_fock.py new file mode 100644 index 00000000..f78116a1 --- /dev/null +++ b/ipie/addons/thermal/utils/legacy_fock.py @@ -0,0 +1,8 @@ +from ipie.estimators.generic import fock_generic + +def fock_matrix(system, G): + if system.name == "Generic": + return fock_generic(system, G) + else: + print(f"# Fock matrix not implemented for {system.name}") + return None diff --git a/ipie/addons/thermal/utils/legacy_mean_field.py b/ipie/addons/thermal/utils/legacy_mean_field.py new file mode 100644 index 00000000..79e5c932 --- /dev/null +++ b/ipie/addons/thermal/utils/legacy_mean_field.py @@ -0,0 +1,114 @@ +import numpy +import scipy.linalg + +from ipie.addons.thermal.utils.legacy_fock import fock_matrix + +from ipie.legacy.estimators.local_energy import local_energy +from ipie.legacy.estimators.thermal import entropy, greens_function, one_rdm_stable, particle_number +from ipie.legacy.trial_density_matrices.chem_pot import compute_rho, find_chemical_potential +from ipie.legacy.trial_density_matrices.onebody import OneBody + + +class MeanField(OneBody): + def __init__(self, system, hamiltonian, beta, dt, options={}, H1=None, verbose=False): + OneBody.__init__( + self, system, hamiltonian, beta, dt, options=options, H1=H1, verbose=verbose + ) + if verbose: + print(" # Building THF density matrix.") + self.alpha = options.get("alpha", 0.75) + self.max_scf_it = options.get("max_scf_it", self.max_it) + self.max_macro_it = options.get("max_macro_it", self.max_it) + self.find_mu = options.get("find_mu", True) + self.P, HMF, self.mu = self.thermal_hartree_fock(hamiltonian, beta) + muN = self.mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) + self.dmat = numpy.array( + [ + scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN)), + ] + ) + self.dmat_inv = numpy.array( + [ + scipy.linalg.inv(self.dmat[0], check_finite=False), + scipy.linalg.inv(self.dmat[1], check_finite=False), + ] + ) + self.G = numpy.array([greens_function(self.dmat[0]), greens_function(self.dmat[1])]) + self.nav = particle_number(self.P).real + + def thermal_hartree_fock(self, system, beta): + dt = self.dtau + mu_old = self.mu + P = self.P.copy() + if self.verbose: + print("# Determining Thermal Hartree-Fock Density Matrix.") + for it in range(self.max_macro_it): + if self.verbose: + print(f"# Macro iteration: {it}") + HMF = self.scf(system, beta, mu_old, P) + rho = numpy.array([scipy.linalg.expm(-dt * HMF[0]), scipy.linalg.expm(-dt * HMF[1])]) + if self.find_mu: + mu = find_chemical_potential( + system._alt_convention, + rho, + dt, + self.num_bins, + self.nav, + deps=self.deps, + max_it=self.max_it, + verbose=self.verbose, + ) + else: + mu = self.mu + rho_mu = compute_rho(rho, mu_old, dt) + P = one_rdm_stable(rho_mu, self.num_bins) + dmu = abs(mu - mu_old) + if self.verbose: + print(f"# New mu: {mu:13.8e} Old mu: {mu_old:13.8e} Dmu: {dmu:13.8e}") + if dmu < self.deps: + break + mu_old = mu + return P, HMF, mu + + def scf(self, system, beta, mu, P): + # 1. Compute HMF + HMF = fock_matrix(system, P) + dt = self.dtau + muN = mu * numpy.eye(system.nbasis, dtype=self.G.dtype) + rho = numpy.array( + [ + scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN)), + ] + ) + Pold = one_rdm_stable(rho, self.num_bins) + if self.verbose: + print(" # Running Thermal SCF.") + for it in range(self.max_scf_it): + HMF = fock_matrix(system, Pold) + rho = numpy.array( + [ + scipy.linalg.expm(-dt * (HMF[0] - muN)), + scipy.linalg.expm(-dt * (HMF[1] - muN)), + ] + ) + Pnew = (1 - self.alpha) * one_rdm_stable(rho, self.num_bins) + self.alpha * Pold + change = numpy.linalg.norm(Pnew - Pold) + if change < self.deps: + break + #if self.verbose: + # N = particle_number(P).real + # E = local_energy(system, P)[0].real + # S = entropy(beta, mu, HMF) + # omega = E - mu * N - 1.0 / beta * S + # print( + # " # Iteration: {:4d} dP: {:13.8e} Omega: {:13.8e}".format( + # it, change, omega.real + # ) + # ) + Pold = Pnew.copy() + if self.verbose: + N = particle_number(P).real + print(f" # Average particle number: {N:13.8e}") + return HMF diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index 42939a49..4c30d8ce 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -10,13 +10,14 @@ from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField from ipie.legacy.walkers.thermal import ThermalWalker from ipie.legacy.walkers.handler import Walkers from ipie.legacy.thermal_propagation.continuous import Continuous from ipie.legacy.thermal_propagation.planewave import PlaneWave from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC +from ipie.addons.thermal.utils.legacy_mean_field import MeanField as LegacyMeanField + def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator, xi=None): if xi is None: diff --git a/ipie/addons/thermal/utils/ueg.py b/ipie/addons/thermal/utils/ueg.py index fa0d8d7d..c1eff342 100644 --- a/ipie/addons/thermal/utils/ueg.py +++ b/ipie/addons/thermal/utils/ueg.py @@ -2,7 +2,9 @@ import scipy.sparse from ipie.utils.io import write_qmcpack_sparse - +# ----------------------------------------------------------------------------- +# System class. +# ----------------------------------------------------------------------------- class UEG(object): """UEG system class (integrals read from fcidump) From 7994a1ffb146675c356b0bdda86d3ffa2b7b9685 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 16 Mar 2024 15:34:25 -0400 Subject: [PATCH 64/84] Try adding cythonized `ueg_kernels` to `thermal/utils` --- .../propagation/tests/ueg/test_prop_ueg.py | 3 +- .../thermal/propagation/tests/ueg/ueg.py | 563 - .../thermal/utils/{ => legacy}/legacy_fock.py | 0 .../utils/{ => legacy}/legacy_mean_field.py | 2 +- .../utils/legacy/legacy_thermal_afqmc.py | 383 + .../utils/legacy/legacy_trial_utils.py | 39 + ipie/addons/thermal/utils/legacy_testing.py | 4 +- ipie/addons/thermal/utils/ueg.py | 303 + ipie/addons/thermal/utils/ueg_kernels.c | 28372 ++++++++++++++++ ipie/addons/thermal/utils/ueg_kernels.pyx | 169 + 10 files changed, 29271 insertions(+), 567 deletions(-) delete mode 100644 ipie/addons/thermal/propagation/tests/ueg/ueg.py rename ipie/addons/thermal/utils/{ => legacy}/legacy_fock.py (100%) rename ipie/addons/thermal/utils/{ => legacy}/legacy_mean_field.py (98%) create mode 100644 ipie/addons/thermal/utils/legacy/legacy_thermal_afqmc.py create mode 100644 ipie/addons/thermal/utils/legacy/legacy_trial_utils.py create mode 100644 ipie/addons/thermal/utils/ueg_kernels.c create mode 100644 ipie/addons/thermal/utils/ueg_kernels.pyx diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index 78396438..4920ab6d 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -5,13 +5,14 @@ from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G -from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G from ipie.addons.thermal.utils.testing import build_ueg_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import build_legacy_ueg_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers +from ipie.addons.thermal.utils.ueg import local_energy_ueg as legacy_local_energy_ueg + comm = MPI.COMM_WORLD @pytest.mark.unit diff --git a/ipie/addons/thermal/propagation/tests/ueg/ueg.py b/ipie/addons/thermal/propagation/tests/ueg/ueg.py deleted file mode 100644 index fa0d8d7d..00000000 --- a/ipie/addons/thermal/propagation/tests/ueg/ueg.py +++ /dev/null @@ -1,563 +0,0 @@ -import numpy -import scipy.sparse -from ipie.utils.io import write_qmcpack_sparse - - -class UEG(object): - """UEG system class (integrals read from fcidump) - - Parameters - ---------- - nup : int - Number of up electrons. - - ndown : int - Number of down electrons. - - rs : float - Density parameter. - - ecut : float - Scaled cutoff energy. - - ktwist : :class:`numpy.ndarray` - Twist vector. - - verbose : bool - Print extra information. - - Attributes - ---------- - T : :class:`numpy.ndarray` - One-body part of the Hamiltonian. This is diagonal in plane wave basis. - - ecore : float - Madelung contribution to the total energy. - - h1e_mod : :class:`numpy.ndarray` - Modified one-body Hamiltonian. - - nfields : int - Number of field configurations per walker for back propagation. - - basis : :class:`numpy.ndarray` - Basis vectors within a cutoff. - - kfac : float - Scale factor (2pi/L). - """ - - def __init__(self, options, verbose=False): - if verbose: - print("# Parsing input options.") - - self.name = "UEG" - self.nup = options.get("nup") - self.ndown = options.get("ndown") - self.nelec = (self.nup, self.ndown) - self.rs = options.get("rs") - self.ecut = options.get("ecut") - self.ktwist = numpy.array(options.get("ktwist", [0, 0, 0])).reshape(3) - - self.thermal = options.get("thermal", False) - self._alt_convention = options.get("alt_convention", False) - self.write_ints = options.get("write_integrals", False) - - self.sparse = True - self.control_variate = False - self.diagH1 = True - - # Total # of electrons. - self.ne = self.nup + self.ndown - # Spin polarisation. - self.zeta = (self.nup - self.ndown) / self.ne - # Density. - self.rho = ((4.0 * numpy.pi) / 3.0 * self.rs**3.0) ** (-1.0) - # Box Length. - self.L = self.rs * (4.0 * self.ne * numpy.pi / 3.0) ** (1 / 3.0) - # Volume - self.vol = self.L**3.0 - # k-space grid spacing. - self.kfac = 2 * numpy.pi / self.L - # Fermi Wavevector (infinite system). - self.kf = (3 * (self.zeta + 1) * numpy.pi**2 * self.ne / self.L**3) ** (1 / 3.0) - # Fermi energy (inifinite systems). - self.ef = 0.5 * self.kf**2 - # Core energy. - self.ecore = 0.5 * self.ne * self.madelung() - - if verbose: - if self.thermal: - print("# Thermal UEG activated.") - - print(f"# Number of spin-up electrons: {self.nup:d}") - print(f"# Number of spin-down electrons: {self.ndown:d}") - print(f"# rs: {self.rs:6.4e}") - print(f"# Spin polarisation (zeta): {self.zeta:6.4e}") - print(f"# Electron density (rho): {self.rho:13.8e}") - print(f"# Box Length (L): {self.L:13.8e}") - print(f"# Volume: {self.vol:13.8e}") - print(f"# k-space factor (2pi/L): {self.kfac:13.8e}") - - - def build(self, verbose=False): - # Get plane wave basis vectors and corresponding eigenvalues. - self.sp_eigv, self.basis, self.nmax = self.sp_energies( - self.ktwist, self.kfac, self.ecut) - self.shifted_nmax = 2 * self.nmax - self.imax_sq = numpy.dot(self.basis[-1], self.basis[-1]) - self.create_lookup_table() - - for i, k in enumerate(self.basis): - assert i == self.lookup_basis(k) - - # Number of plane waves. - self.nbasis = len(self.sp_eigv) - self.nactive = self.nbasis - self.ncore = 0 - self.nfv = 0 - self.mo_coeff = None - - # --------------------------------------------------------------------- - T = numpy.diag(self.sp_eigv) - h1e_mod = self.mod_one_body(T) - self.H1 = numpy.array([T, T]) # Making alpha and beta. - self.h1e_mod = numpy.array([h1e_mod, h1e_mod]) - - # --------------------------------------------------------------------- - # Allowed momentum transfers (4*ecut). - eigs, qvecs, self.qnmax = self.sp_energies(self.ktwist, self.kfac, 4 * self.ecut) - - # Omit Q = 0 term. - self.qvecs = numpy.copy(qvecs[1:]) - self.vqvec = numpy.array([self.vq(self.kfac * q) for q in self.qvecs]) - - # Number of momentum transfer vectors / auxiliary fields. - # Can reduce by symmetry but be stupid for the moment. - self.nchol = len(self.qvecs) - self.nfields = 2 * len(self.qvecs) - self.get_momentum_transfers() - - if verbose: - print(f"# Number of plane waves: {self.nbasis:d}") - print(f"# Number of Cholesky vectors: {self.nchol:d}.") - print(f"# Number of auxiliary fields: {self.nfields:d}.") - print("# Constructing two-body potentials incore.") - - # --------------------------------------------------------------------- - self.chol_vecs, self.iA, self.iB = self.two_body_potentials_incore() - - if self.write_ints: - self.write_integrals() - - if verbose: - print("# Approximate memory required for " - "two-body potentials: {:13.8e} GB.".format((3 * self.iA.nnz * 16 / (1024**3)))) - print("# Finished constructing two-body potentials.") - print("# Finished building UEG object.") - - - def sp_energies(self, ks, kfac, ecut): - """Calculate the allowed kvectors and resulting single particle eigenvalues (basically kinetic energy) - which can fit in the sphere in kspace determined by ecut. - - Parameters - ---------- - kfac : float - kspace grid spacing. - - ecut : float - energy cutoff. - - Returns - ------- - spval : :class:`numpy.ndarray` - Array containing sorted single particle eigenvalues. - - kval : :class:`numpy.ndarray` - Array containing basis vectors, sorted according to their - corresponding single-particle energy. - """ - - # Scaled Units to match with HANDE. - # So ecut is measured in units of 1/kfac^2. - nmax = int(numpy.ceil(numpy.sqrt((2 * ecut)))) - - spval = [] - vec = [] - kval = [] - - for ni in range(-nmax, nmax + 1): - for nj in range(-nmax, nmax + 1): - for nk in range(-nmax, nmax + 1): - spe = 0.5 * (ni**2 + nj**2 + nk**2) - - if spe <= ecut: - kijk = [ni, nj, nk] - - # Reintroduce 2 \pi / L factor. - ek = 0.5 * numpy.dot(numpy.array(kijk) + ks, numpy.array(kijk) + ks) - kval.append(kijk) - spval.append(kfac**2 * ek) - - # Sort the arrays in terms of increasing energy. - spval = numpy.array(spval) - ix = numpy.argsort(spval, kind="mergesort") - spval = spval[ix] - kval = numpy.array(kval)[ix] - return spval, kval, nmax - - - def create_lookup_table(self): - basis_ix = [] - for k in self.basis: - basis_ix.append(self.map_basis_to_index(k)) - - self.lookup = numpy.zeros(max(basis_ix) + 1, dtype=int) - - for i, b in enumerate(basis_ix): - self.lookup[b] = i - - self.max_ix = max(basis_ix) - - - def lookup_basis(self, vec): - if numpy.dot(vec, vec) <= self.imax_sq: - ix = self.map_basis_to_index(vec) - - if ix >= len(self.lookup): - ib = None - - else: - ib = self.lookup[ix] - - return ib - - else: - ib = None - - - def map_basis_to_index(self, k): - return ((k[0] + self.nmax) - + self.shifted_nmax * (k[1] + self.nmax) - + self.shifted_nmax * self.shifted_nmax * (k[2] + self.nmax)) - - - def get_momentum_transfers(self): - """Get arrays of plane wave basis vectors connected by momentum transfers Q.""" - nlimit = self.nup - if self.thermal: - nlimit = self.nbasis - - self.ikpq_i = [] - self.ikpq_kpq = [] - - for iq, q in enumerate(self.qvecs): - idxkpq_list_i = [] - idxkpq_list_kpq = [] - - for i, k in enumerate(self.basis[0:nlimit]): - kpq = k + q - idxkpq = self.lookup_basis(kpq) - - if idxkpq is not None: - idxkpq_list_i += [i] - idxkpq_list_kpq += [idxkpq] - - self.ikpq_i += [idxkpq_list_i] - self.ikpq_kpq += [idxkpq_list_kpq] - - # --------------------------------------------------------------------- - self.ipmq_i = [] - self.ipmq_pmq = [] - - for iq, q in enumerate(self.qvecs): - idxpmq_list_i = [] - idxpmq_list_pmq = [] - - for i, p in enumerate(self.basis[0:nlimit]): - pmq = p - q - idxpmq = self.lookup_basis(pmq) - - if idxpmq is not None: - idxpmq_list_i += [i] - idxpmq_list_pmq += [idxpmq] - - self.ipmq_i += [idxpmq_list_i] - self.ipmq_pmq += [idxpmq_list_pmq] - - for iq, q in enumerate(self.qvecs): - self.ikpq_i[iq] = numpy.array(self.ikpq_i[iq], dtype=numpy.int64) - self.ikpq_kpq[iq] = numpy.array(self.ikpq_kpq[iq], dtype=numpy.int64) - self.ipmq_i[iq] = numpy.array(self.ipmq_i[iq], dtype=numpy.int64) - self.ipmq_pmq[iq] = numpy.array(self.ipmq_pmq[iq], dtype=numpy.int64) - - - def madelung(self): - """Use expression in Schoof et al. (PhysRevLett.115.130402) for the - Madelung contribution to the total energy fitted to L.M. Fraser et al. - Phys. Rev. B 53, 1814. - - Parameters - ---------- - rs : float - Wigner-Seitz radius. - - ne : int - Number of electrons. - - Returns - ------- - v_M: float - Madelung potential (in Hartrees). - """ - c1 = -2.837297 - c2 = (3.0 / (4.0 * numpy.pi)) ** (1.0 / 3.0) - return c1 * c2 / (self.ne ** (1.0 / 3.0) * self.rs) - - - def mod_one_body(self, T): - """Absorb the diagonal term of the two-body Hamiltonian to the one-body term. - Essentially adding the third term in Eq.(11b) of Phys. Rev. B 75, 245123. - - Parameters - ---------- - T : float - one-body Hamiltonian (i.e. kinetic energy) - - Returns - ------- - h1e_mod: float - modified one-body Hamiltonian - """ - h1e_mod = numpy.copy(T) - - fac = 1.0 / (2.0 * self.vol) - for i, ki in enumerate(self.basis): - for j, kj in enumerate(self.basis): - if i != j: - q = self.kfac * (ki - kj) - h1e_mod[i, i] = h1e_mod[i, i] - fac * self.vq(q) - - return h1e_mod - - - def vq(self, q): - """The typical 3D Coulomb kernel - - Parameters - ---------- - q : float - a plane-wave vector - - Returns - ------- - v_M: float - 3D Coulomb kernel (in Hartrees) - """ - return 4 * numpy.pi / numpy.dot(q, q) - - - def density_operator(self, iq): - """Density operator as defined in Eq.(6) of Phys. Rev. B 75, 245123. - - Parameters - ---------- - q : float - a plane-wave vector - - Returns - ------- - rho_q: float - density operator - """ - nnz = self.rho_ikpq_kpq[iq].shape[0] # Number of non-zeros - ones = numpy.ones((nnz), dtype=numpy.complex128) - rho_q = scipy.sparse.csc_matrix( - (ones, (self.rho_ikpq_kpq[iq], self.rho_ikpq_i[iq])), - shape=(self.nbasis, self.nbasis), - dtype=numpy.complex128) - return rho_q - - - def scaled_density_operator_incore(self, transpose): - """Density operator as defined in Eq.(6) of PRB(75)245123 - - Parameters - ---------- - q : float - a plane-wave vector - - Returns - ------- - rho_q: float - density operator - """ - rho_ikpq_i = [] - rho_ikpq_kpq = [] - - for iq, q in enumerate(self.qvecs): - idxkpq_list_i = [] - idxkpq_list_kpq = [] - - for i, k in enumerate(self.basis): - kpq = k + q - idxkpq = self.lookup_basis(kpq) - - if idxkpq is not None: - idxkpq_list_i += [i] - idxkpq_list_kpq += [idxkpq] - - rho_ikpq_i += [idxkpq_list_i] - rho_ikpq_kpq += [idxkpq_list_kpq] - - for iq, q in enumerate(self.qvecs): - rho_ikpq_i[iq] = numpy.array(rho_ikpq_i[iq], dtype=numpy.int64) - rho_ikpq_kpq[iq] = numpy.array(rho_ikpq_kpq[iq], dtype=numpy.int64) - - nq = len(self.qvecs) - nnz = 0 - for iq in range(nq): - nnz += rho_ikpq_kpq[iq].shape[0] - - col_index = [] - row_index = [] - values = [] - - if transpose: - for iq in range(nq): - qscaled = self.kfac * self.qvecs[iq] - # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol - piovol = numpy.pi / (self.vol) - factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 - - for innz, kpq in enumerate(rho_ikpq_kpq[iq]): - row_index += [rho_ikpq_kpq[iq][innz] + rho_ikpq_i[iq][innz] * self.nbasis] - col_index += [iq] - values += [factor] - - else: - for iq in range(nq): - qscaled = self.kfac * self.qvecs[iq] - # Due to the HS transformation, we have to do pi / 2*vol as opposed to 2*pi / vol - piovol = numpy.pi / (self.vol) - factor = (piovol / numpy.dot(qscaled, qscaled)) ** 0.5 - - for innz, kpq in enumerate(rho_ikpq_kpq[iq]): - row_index += [rho_ikpq_kpq[iq][innz] * self.nbasis + rho_ikpq_i[iq][innz]] - col_index += [iq] - values += [factor] - - rho_q = scipy.sparse.csc_matrix( - (values, (row_index, col_index)), - shape=(self.nbasis * self.nbasis, nq), - dtype=numpy.complex128) - return rho_q - - - def two_body_potentials_incore(self): - """Calculate A and B of Eq.(13) of PRB(75)245123 for a given plane-wave vector q - - Returns - ------- - iA : numpy array - Eq.(13a) - - iB : numpy array - Eq.(13b) - """ - rho_q = self.scaled_density_operator_incore(False) - rho_qH = self.scaled_density_operator_incore(True) - iA = 1j * (rho_q + rho_qH) - iB = -(rho_q - rho_qH) - return (rho_q, iA, iB) - - - def hijkl(self, i, j, k, l): - """Compute = (ik|jl) = 1/Omega * 4pi/(kk-ki)**2 - - Checks for momentum conservation k_i + k_j = k_k + k_k, or - k_k - k_i = k_j - k_l. - - Parameters - ---------- - i, j, k, l : int - Orbital indices for integral (ik|jl) = . - - Returns - ------- - integral : float - (ik|jl) - """ - q1 = self.basis[k] - self.basis[i] - q2 = self.basis[j] - self.basis[l] - - if numpy.dot(q1, q1) > 1e-12 and numpy.dot(q1 - q2, q1 - q2) < 1e-12: - return 1.0 / self.vol * self.vq(self.kfac * q1) - - else: - return 0.0 - - - def compute_real_transformation(self): - U22 = numpy.zeros((2, 2), dtype=numpy.complex128) - U22[0, 0] = 1.0 / numpy.sqrt(2.0) - U22[0, 1] = 1.0 / numpy.sqrt(2.0) - U22[1, 0] = -1.0j / numpy.sqrt(2.0) - U22[1, 1] = 1.0j / numpy.sqrt(2.0) - - U = numpy.zeros((self.nbasis, self.nbasis), dtype=numpy.complex128) - - for i, b in enumerate(self.basis): - if numpy.sum(b * b) == 0: - U[i, i] = 1.0 - - else: - mb = -b - diff = numpy.einsum("ij->i", (self.basis - mb) ** 2) - idx = numpy.argwhere(diff == 0) - assert idx.ravel().shape[0] == 1 - - if i < idx: - idx = idx.ravel()[0] - U[i, i] = U22[0, 0] - U[i, idx] = U22[0, 1] - U[idx, i] = U22[1, 0] - U[idx, idx] = U22[1, 1] - - else: - continue - - U = U.T.copy() - return U - - - def eri_4(self): - eri_chol = 4 * self.chol_vecs.dot(self.chol_vecs.T) - eri_chol = ( - eri_chol.toarray().reshape((self.nbasis, self.nbasis, self.nbasis, self.nbasis)).real) - eri_chol = eri_chol.transpose(0, 1, 3, 2) - return eri_chol - - - def eri_8(self): - """Compute 8-fold symmetric integrals. Useful for running standard - quantum chemistry methods,""" - eri = self.eri_4() - U = self.compute_real_transformation() - eri0 = numpy.einsum("mp,mnls->pnls", U.conj(), eri, optimize=True) - eri1 = numpy.einsum("nq,pnls->pqls", U, eri0, optimize=True) - eri2 = numpy.einsum("lr,pqls->pqrs", U.conj(), eri1, optimize=True) - eri3 = numpy.einsum("st,pqrs->pqrt", U, eri2, optimize=True).real - return eri3 - - - def write_integrals(self, filename="ueg_integrals.h5"): - write_qmcpack_sparse( - self.H1[0], - 2 * self.chol_vecs.toarray(), - self.nelec, - self.nbasis, - enuc=0.0, - filename=filename) - diff --git a/ipie/addons/thermal/utils/legacy_fock.py b/ipie/addons/thermal/utils/legacy/legacy_fock.py similarity index 100% rename from ipie/addons/thermal/utils/legacy_fock.py rename to ipie/addons/thermal/utils/legacy/legacy_fock.py diff --git a/ipie/addons/thermal/utils/legacy_mean_field.py b/ipie/addons/thermal/utils/legacy/legacy_mean_field.py similarity index 98% rename from ipie/addons/thermal/utils/legacy_mean_field.py rename to ipie/addons/thermal/utils/legacy/legacy_mean_field.py index 79e5c932..5a0927b4 100644 --- a/ipie/addons/thermal/utils/legacy_mean_field.py +++ b/ipie/addons/thermal/utils/legacy/legacy_mean_field.py @@ -1,7 +1,7 @@ import numpy import scipy.linalg -from ipie.addons.thermal.utils.legacy_fock import fock_matrix +from ipie.addons.thermal.utils.legacy.legacy_fock import fock_matrix from ipie.legacy.estimators.local_energy import local_energy from ipie.legacy.estimators.thermal import entropy, greens_function, one_rdm_stable, particle_number diff --git a/ipie/addons/thermal/utils/legacy/legacy_thermal_afqmc.py b/ipie/addons/thermal/utils/legacy/legacy_thermal_afqmc.py new file mode 100644 index 00000000..f1ab65b8 --- /dev/null +++ b/ipie/addons/thermal/utils/legacy/legacy_thermal_afqmc.py @@ -0,0 +1,383 @@ +"""Driver to perform AFQMC calculation""" +import copy +import json +import sys +import time +import uuid +import warnings +from math import exp + +import h5py +import numpy + +from ipie.addons.thermal.utils.legacy.legacy_trial_utils import get_trial_density_matrix + +from ipie.legacy.estimators.handler import Estimators +from ipie.legacy.estimators.local_energy import local_energy +from ipie.legacy.hamiltonians.utils import get_hamiltonian +from ipie.legacy.thermal_propagation.utils import get_propagator +from ipie.legacy.walkers.handler import Walkers +from ipie.legacy.qmc.options import QMCOpts +from ipie.qmc.utils import set_rng_seed +from ipie.legacy.systems.utils import get_system +from ipie.utils.io import get_input_value, to_json +from ipie.utils.misc import get_git_info, print_env_info +from ipie.utils.mpi import get_shared_comm + + +class ThermalAFQMC(object): + """AFQMC driver. + + Non-zero temperature AFQMC using open ended random walk. + + Parameters + ---------- + model : dict + Input parameters for model system. + qmc_opts : dict + Input options relating to qmc parameters. + estimates : dict + Input options relating to what estimator to calculate. + trial : dict + Input options relating to trial wavefunction. + propagator : dict + Input options relating to propagator. + parallel : bool + If true we are running in parallel. + verbose : bool + If true we print out additional setup information. + + Attributes + ---------- + uuid : string + Simulation state uuid. + sha1 : string + Git hash. + seed : int + RNG seed. This is set during initialisation in calc. + root : bool + If true we are on the root / master processor. + nprocs : int + Number of processors. + rank : int + Processor id. + cplx : bool + If true then most numpy arrays are complex valued. + init_time : float + Calculation initialisation (cpu) time. + init_time : float + Human readable initialisation time. + system : system object. + Container for model input options. + qmc : :class:`pie.state.QMCOpts` object. + Container for qmc input options. + trial : :class:`pie.trial_wavefunction.X' object + Trial wavefunction class. + propagators : :class:`pie.propagation.Projectors` object + Container for system specific propagation routines. + estimators : :class:`pie.estimators.Estimators` object + Estimator handler. + walk : :class:`pie.walkers.Walkers` object + Stores walkers which sample the partition function. + """ + + def __init__( + self, + comm, + options=None, + system=None, + hamiltonian=None, + trial=None, + parallel=False, + verbose=None, + ): + if verbose is not None: + self.verbosity = verbose + if comm.rank != 0: + self.verbosity = 0 + verbose = verbose > 0 and comm.rank == 0 + else: + self.verbosity = 0 + verbose = False + qmc_opts = get_input_value( + options, + "qmc", + default={}, + alias=["qmc_options"], + verbose=self.verbosity > 1, + ) + if qmc_opts.get("beta") is None: + print("Shouldn't call ThermalAFQMC without specifying beta") + exit() + # 1. Environment attributes + if comm.rank == 0: + self.uuid = str(uuid.uuid1()) + get_sha1 = options.get("get_sha1", True) + if get_sha1: + self.sha1, self.branch, self.local_mods = get_git_info() + else: + self.sha1 = "None" + #if verbose: + # self.sys_info = print_env_info( + # self.sha1, self.branch, self.local_mods, self.uuid, comm.size + # ) + # Hack - this is modified later if running in parallel on + # initialisation. + self.root = comm.rank == 0 + self.nprocs = comm.size + self.rank = comm.rank + self._init_time = time.time() + self.run_time = (time.asctime(),) + self.shared_comm = get_shared_comm(comm, verbose=verbose) + + # 2. Calculation objects. + sys_opts = options.get("system") + if system is not None: + self.system = system + else: + sys_opts = get_input_value( + options, + "system", + default={}, + alias=["model"], + verbose=self.verbosity > 1, + ) + sys_opts["thermal"] = True + self.system = get_system(sys_opts=sys_opts, verbose=verbose) + + if hamiltonian is not None: + self.hamiltonian = hamiltonian + else: + ham_opts = get_input_value( + options, "hamiltonian", default={}, verbose=self.verbosity > 1 + ) + # backward compatibility with previous code (to be removed) + for item in sys_opts.items(): + if item[0].lower() == "name" and "name" in ham_opts.keys(): + continue + ham_opts[item[0]] = item[1] + self.hamiltonian = get_hamiltonian( + self.system, ham_opts, verbose=verbose, comm=self.shared_comm + ) + + self.qmc = QMCOpts(qmc_opts, self.system, verbose) + self.qmc.rng_seed = set_rng_seed(self.qmc.rng_seed, comm) + self.qmc.ntime_slices = int(round(self.qmc.beta / self.qmc.dt)) + # Overide whatever's in the input file due to structure of FT algorithm. + self.qmc.nsteps = 1 + self.qmc.total_steps = self.qmc.nblocks + if verbose: + print("# Number of time slices = %i" % self.qmc.ntime_slices) + self.cplx = True + if trial is not None: + self.trial = trial + if verbose: + print( + "# Trial density matrix passed from input: {} ".format( + self.trial.__class__.__name__ + ) + ) + else: + trial_opts = get_input_value( + options, + "trial", + default={}, + alias=["trial_density"], + verbose=self.verbosity > 1, + ) + self.trial = get_trial_density_matrix( + self.system, + self.hamiltonian, + self.qmc.beta, + self.qmc.dt, + comm=comm, + options=trial_opts, + verbose=verbose, + ) + + self.qmc.ntot_walkers = self.qmc.nwalkers + # Number of walkers per core/rank. + self.qmc.nwalkers = int(self.qmc.nwalkers / comm.size) + # Total number of walkers. + self.qmc.ntot_walkers = self.qmc.nwalkers * self.nprocs + if self.qmc.nwalkers == 0: + if comm.rank == 0 and verbose: + print("# WARNING: Not enough walkers for selected core count.") + print( + "# There must be at least one walker per core set in the " + "input file." + ) + print("# Setting one walker per core.") + self.qmc.nwalkers = 1 + self.qmc.ntot_walkers = self.qmc.nwalkers * self.nprocs + wlk_opts = get_input_value( + options, + "walkers", + default={}, + alias=["walker", "walker_opts"], + verbose=self.verbosity > 1, + ) + self.walk = Walkers( + self.system, + self.hamiltonian, + self.trial, + self.qmc, + walker_opts=wlk_opts, + verbose=verbose, + ) + lowrank = self.walk.walkers[0].lowrank + prop_opts = get_input_value( + options, + "propagator", + default={}, + alias=["prop", "propagation"], + verbose=self.verbosity > 1, + ) + self.propagators = get_propagator( + prop_opts, + self.qmc, + self.system, + self.hamiltonian, + self.trial, + verbose=verbose, + lowrank=lowrank, + ) + + self.tsetup = time.time() - self._init_time + est_opts = get_input_value( + options, + "estimators", + default={}, + alias=["estimates"], + verbose=self.verbosity > 1, + ) + self.estimators = Estimators( + est_opts, + self.root, + self.qmc, + self.system, + self.hamiltonian, + self.trial, + self.propagators.BT_BP, + verbose, + ) + # stabilization frequency might be updated due to wrong user input + if self.qmc.nstblz != self.propagators.nstblz: + self.propagators.nstblz = self.qmc.nstblz + if comm.rank == 0: + json_string = to_json(self) + self.estimators.json_string = json_string + self.estimators.dump_metadata() + if verbose: + self.estimators.estimators["mixed"].print_key() + self.estimators.estimators["mixed"].print_header() + + def run(self, walk=None, comm=None, verbose=None): + """Perform AFQMC simulation on state object using open-ended random walk. + + Parameters + ---------- + state : :class:`pie.state.State` object + Model and qmc parameters. + walk: :class:`pie.walker.Walkers` object + Initial wavefunction / distribution of walkers. + comm : MPI communicator + """ + if walk is not None: + self.walk = walk + self.setup_timers() + # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) + (E_T, ke, pe) = local_energy( + self.system, self.hamiltonian, self.walk.walkers[0], self.trial + ) + # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) + # Calculate estimates for initial distribution of walkers. + self.estimators.estimators["mixed"].update( + self.qmc, + self.system, + self.hamiltonian, + self.trial, + self.walk, + 0, + self.propagators.free_projection, + ) + # Print out zeroth step for convenience. + self.estimators.estimators["mixed"].print_step(comm, self.nprocs, 0, 1) + + for step in range(1, self.qmc.total_steps + 1): + start_path = time.time() + for ts in range(0, self.qmc.ntime_slices): + if self.verbosity >= 2 and comm.rank == 0: + print(" # Timeslice %d of %d." % (ts, self.qmc.ntime_slices)) + start = time.time() + for w in self.walk.walkers: + self.propagators.propagate_walker(self.hamiltonian, w, ts, 0) + if (abs(w.weight) > w.total_weight * 0.10) and ts > 0: + w.weight = w.total_weight * 0.10 + self.tprop += time.time() - start + start = time.time() + if ts % self.qmc.npop_control == 0 and ts != 0: + self.walk.pop_control(comm) + self.tpopc += time.time() - start + self.tpath += time.time() - start_path + start = time.time() + self.estimators.update( + self.qmc, + self.system, + self.hamiltonian, + self.trial, + self.walk, + step, + self.propagators.free_projection, + ) + self.testim += time.time() - start + self.estimators.print_step( + comm, + self.nprocs, + step, + free_projection=self.propagators.free_projection, + ) + self.walk.reset(self.trial) + + def finalise(self, verbose): + """Tidy up. + + Parameters + ---------- + verbose : bool + If true print out some information to stdout. + """ + if self.root: + if verbose: + print(f"# End Time: {time.asctime()}") + print(f"# Running time : {time.time() - self._init_time:.6f} seconds") + print("# Timing breakdown (per processor, per path/slice):") + print(f"# - Setup: {self.tsetup:f} s") + nsteps = self.qmc.nsteps + nslice = nsteps * self.qmc.ntime_slices + npcon = nslice // self.qmc.npop_control + print(f"# - Path update: {self.tpath / nsteps:f} s") + print(f"# - Propagation: {self.tprop / nslice:f} s") + print(f"# - Estimators: {self.testim / nsteps:f} s") + print(f"# - Population control: {self.tpopc / npcon:f} s") + + def determine_dtype(self, propagator, system): + """Determine dtype for trial wavefunction and walkers. + + Parameters + ---------- + propagator : dict + Propagator input options. + system : object + System object. + """ + hs_type = propagator.get("hubbard_stratonovich", "discrete") + continuous = "continuous" in hs_type + twist = system.ktwist.all() is not None + return continuous or twist + + def setup_timers(self): + self.tpath = 0 + self.tprop = 0 + self.testim = 0 + self.tpopc = 0 diff --git a/ipie/addons/thermal/utils/legacy/legacy_trial_utils.py b/ipie/addons/thermal/utils/legacy/legacy_trial_utils.py new file mode 100644 index 00000000..f96fffa3 --- /dev/null +++ b/ipie/addons/thermal/utils/legacy/legacy_trial_utils.py @@ -0,0 +1,39 @@ +from ipie.addons.thermal.utils.legacy.legacy_mean_field import MeanField +from ipie.legacy.trial_density_matrices.onebody import OneBody + + +def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=None, verbose=False): + """Wrapper to select trial wavefunction class. + + Parameters + ---------- + + Returns + ------- + trial : class or None + Trial density matrix class. + """ + trial_type = options.get("name", "one_body") + if comm is None or comm.rank == 0: + if trial_type == "one_body_mod": + trial = OneBody( + system, + hamiltonian, + beta, + dt, + options=options, + H1=hamiltonian.h1e_mod, + verbose=verbose, + ) + elif trial_type == "one_body": + trial = OneBody(system, hamiltonian, beta, dt, options=options, verbose=verbose) + elif trial_type == "thermal_hartree_fock": + trial = MeanField(system, hamiltonian, beta, dt, options=options, verbose=verbose) + else: + trial = None + else: + trial = None + if comm is not None: + trial = comm.bcast(trial) + + return trial diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index 4c30d8ce..9e9ec737 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -14,9 +14,9 @@ from ipie.legacy.walkers.handler import Walkers from ipie.legacy.thermal_propagation.continuous import Continuous from ipie.legacy.thermal_propagation.planewave import PlaneWave -from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC -from ipie.addons.thermal.utils.legacy_mean_field import MeanField as LegacyMeanField +from ipie.addons.thermal.utils.legacy.legacy_mean_field import MeanField as LegacyMeanField +from ipie.addons.thermal.utils.legacy.legacy_thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator, xi=None): diff --git a/ipie/addons/thermal/utils/ueg.py b/ipie/addons/thermal/utils/ueg.py index c1eff342..3c895e00 100644 --- a/ipie/addons/thermal/utils/ueg.py +++ b/ipie/addons/thermal/utils/ueg.py @@ -2,6 +2,306 @@ import scipy.sparse from ipie.utils.io import write_qmcpack_sparse +# ----------------------------------------------------------------------------- +# Functions +# ----------------------------------------------------------------------------- +from ipie.addons.thermal.utils.ueg_kernels import ( + build_J_opt, + build_K_opt, + coulomb_greens_function_per_qvec, + exchange_greens_function_per_qvec, +) + + +def exchange_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gprod, G): + for iq in range(nq): + for idxkpq, i in zip(kpq[iq], kpq_i[iq]): + for idxpmq, j in zip(pmq[iq], pmq_i[iq]): + Gprod[iq] += G[j, idxkpq] * G[i, idxpmq] + + +def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): + for iq in range(nq): + for idxkpq, i in zip(kpq[iq], kpq_i[iq]): + Gkpq[iq] += G[i, idxkpq] + for idxpmq, i in zip(pmq[iq], pmq_i[iq]): + Gpmq[iq] += G[i, idxpmq] + + +def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None, debug=False): + """Local energy computation for uniform electron gas + Parameters + ---------- + system : + system class + ham : + hamiltonian class + G : + Green's function + Returns + ------- + etot : float + total energy + ke : float + kinetic energy + pe : float + potential energy + """ + if ham.diagH1: + ke = numpy.einsum("sii,sii->", ham.H1, G) + else: + ke = numpy.einsum("sij,sij->", ham.H1, G) + + Gkpq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + Gpmq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + Gprod = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) + + ne = [system.nup, system.ndown] + nq = numpy.shape(ham.qvecs)[0] + + for s in [0, 1]: + # exchange_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i,ham.ipmq_pmq, Gprod[s],G[s]) + # coulomb_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i, ham.ipmq_pmq,Gkpq[s], Gpmq[s],G[s]) + for iq in range(nq): + Gkpq[s, iq], Gpmq[s, iq] = coulomb_greens_function_per_qvec( + ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] + ) + Gprod[s, iq] = exchange_greens_function_per_qvec( + ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] + ) + + if two_rdm is None: + two_rdm = numpy.zeros((2, 2, len(ham.qvecs)), dtype=numpy.complex128) + + two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] + two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] + two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) + two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) + + essa = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 0]) + essb = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[1, 1]) + eos = (1.0 / (2.0 * ham.vol)) * ( + ham.vqvec.dot(two_rdm[0, 1]) + ham.vqvec.dot(two_rdm[1, 0])) + pe = essa + essb + eos + + if debug: + ecoul, exx = 0., 0. + + for s1 in range(2): + exx -= (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(Gprod[s1]) + + for s2 in range(2): + ecoul += (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(numpy.multiply(Gkpq[s1], Gpmq[s2])) + + print(f'\n# ueg ecoul = {ecoul}') + print(f'# ueg exx = {exx}') + print(f'# ueg e2 = {(ecoul + exx)}') + + return (ke + pe, ke, pe) + + +# JHLFML +def build_J(system, Gpmq, Gkpq): + J = [ + numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), + numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), + ] + + for iq, q in enumerate(system.qvecs): + for idxi, i in enumerate(system.basis): + for idxj, j in enumerate(system.basis): + jpq = j + q + idxjpq = system.lookup_basis(jpq) + if (idxjpq is not None) and (idxjpq == idxi): + J[0][idxj, idxi] += ( + (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + ) + + for iq, q in enumerate(system.qvecs): + for idxi, i in enumerate(system.basis): + for idxj, j in enumerate(system.basis): + jpq = j - q + idxjmq = system.lookup_basis(jpq) + if (idxjmq is not None) and (idxjmq == idxi): + J[0][idxj, idxi] += ( + (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + ) + + J[1] = J[0] + + return J + + +def build_K(system, G): + K = numpy.zeros((2, system.nbasis, system.nbasis), dtype=numpy.complex128) + for s in [0, 1]: + for iq in range(len(system.vqvec)): + for idxjmq, idxj in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): + for idxkpq, idxk in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): + K[s, idxj, idxkpq] += ( + -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjmq, idxk] + ) + for iq in range(len(system.vqvec)): + for idxjpq, idxj in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): + for idxpmq, idxp in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): + K[s, idxj, idxpmq] += ( + -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjpq, idxp] + ) + return K + + +def fock_ueg(ham, G): + """Fock matrix computation for uniform electron gas + + Parameters + ---------- + ham : :class`ipie.legacy.hamiltonians.ueg` + UEG hamiltonian class. + G : :class:`numpy.ndarray` + Green's function. + Returns + ------- + F : :class:`numpy.ndarray` + Fock matrix (2, nbasis, nbasis). + """ + nbsf = ham.nbasis + nq = len(ham.qvecs) + assert nq == len(ham.vqvec) + + Fock = numpy.zeros((2, nbsf, nbsf), dtype=numpy.complex128) + Gkpq = numpy.zeros((2, nq), dtype=numpy.complex128) + Gpmq = numpy.zeros((2, nq), dtype=numpy.complex128) + + for s in [0, 1]: + coulomb_greens_function( + nq, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + Gkpq[s], + Gpmq[s], + G[s], + ) + + J = build_J_opt( + nq, + ham.vqvec, + ham.vol, + ham.nbasis, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + Gkpq, + Gpmq, + ) + + K = build_K_opt( + nq, + ham.vqvec, + ham.vol, + ham.nbasis, + ham.ikpq_i, + ham.ikpq_kpq, + ham.ipmq_i, + ham.ipmq_pmq, + G, + ) + + for s in [0, 1]: + Fock[s] = ham.H1[s] + J[s] + K[s] + + return Fock + + +def unit_test(): + import numpy as np + + from ipie.legacy.systems.ueg import UEG + + inputs = {"nup": 7, "ndown": 7, "rs": 1.0, "ecut": 2.0} + system = UEG(inputs, True) + system.build() + nbsf = system.nbasis + Pa = np.zeros([nbsf, nbsf], dtype=np.complex128) + Pb = np.zeros([nbsf, nbsf], dtype=np.complex128) + na = system.nup + nb = system.ndown + for i in range(na): + Pa[i, i] = 1.0 + for i in range(nb): + Pb[i, i] = 1.0 + P = np.array([Pa, Pb]) + etot, ekin, epot = local_energy_ueg(system, G=P) + print(f"ERHF = {etot}, {ekin}, {epot}") + + from ipie.legacy.estimators.greens_function import gab + from ipie.utils.linalg import exponentiate_matrix, reortho + + # numpy.random.seed() + rCa = numpy.random.randn(nbsf, na) + zCa = numpy.random.randn(nbsf, na) + rCb = numpy.random.randn(nbsf, nb) + zCb = numpy.random.randn(nbsf, nb) + + Ca = rCa + 1j * zCa + Cb = rCb + 1j * zCb + + Ca, detR = reortho(Ca) + Cb, detR = reortho(Cb) + # S = print(Ca.dot(Cb.T)) + # print(S) + # exit() + Ca = numpy.array(Ca, dtype=numpy.complex128) + Cb = numpy.array(Cb, dtype=numpy.complex128) + P = [gab(Ca, Ca), gab(Cb, Cb)] + # diff = P[0] - P[1] + # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) + + # solver = lib.diis.DIIS() + + # dt = 0.1 + # for i in range(100): + # # Compute Fock matrix + # Fock = fock_ueg(system, G=P) + # # Compute DIIS Errvec + # PFmFPa = P[0].dot(Fock[0]) - Fock[0].dot(P[0]) + # PFmFPb = P[1].dot(Fock[1]) - Fock[1].dot(P[1]) + # errvec = numpy.append(numpy.reshape(PFmFPa, nbsf*nbsf),numpy.reshape(PFmFPb, nbsf*nbsf)) + # RMS = np.sqrt(np.dot(errvec, errvec)) + # print ("{} {} {}".format(i,numpy.real(local_energy_ueg(system, P)), numpy.real(RMS))) + # # Form Fockvec + # Fock[0] = numpy.array(Fock[0]) + # Fock[1] = numpy.array(Fock[1]) + # Fockvec = numpy.append(numpy.reshape(Fock[0],nbsf*nbsf), numpy.reshape(Fock[1],nbsf*nbsf)) + # # Extrapolate Fockvec + # # Fockvec = solver.update(Fockvec, xerr=errvec) + + # # Apply Propagator + # Fock = numpy.reshape(Fockvec, (2, nbsf, nbsf)) + # ea, Ca = numpy.linalg.eig(Fock[0]) + # eb, Cb = numpy.linalg.eig(Fock[1]) + # sort_perm = ea.argsort() + # ea.sort() + # Ca = Ca[:, sort_perm] + # sort_perm = eb.argsort() + # eb.sort() + # Cb = Cb[:, sort_perm] + + # Ca = Ca[:,:na] + # Cb = Cb[:,:nb] + # Ca, detR = reortho(Ca) + # Cb, detR = reortho(Cb) + + # P = [gab(Ca, Ca), gab(Cb, Cb)] + # # expF = [exponentiate_matrix(-dt*Fock[0]), exponentiate_matrix(-dt*Fock[1])] + # # Ca = expF[0].dot(Ca) + # # Cb = expF[1].dot(Cb) + # # diff = P[0] - P[1] + # # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) + + # ----------------------------------------------------------------------------- # System class. # ----------------------------------------------------------------------------- @@ -563,3 +863,6 @@ def write_integrals(self, filename="ueg_integrals.h5"): enuc=0.0, filename=filename) + +if __name__ == "__main__": + unit_test() diff --git a/ipie/addons/thermal/utils/ueg_kernels.c b/ipie/addons/thermal/utils/ueg_kernels.c new file mode 100644 index 00000000..428b8d9a --- /dev/null +++ b/ipie/addons/thermal/utils/ueg_kernels.c @@ -0,0 +1,28372 @@ +/* Generated by Cython 0.29.35 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [ + "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/arrayobject.h", + "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/arrayscalars.h", + "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/ndarrayobject.h", + "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/ndarraytypes.h", + "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/ufuncobject.h" + ], + "extra_compile_args": [ + "-O3" + ], + "include_dirs": [ + "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include" + ], + "name": "ueg_kernels", + "sources": [ + "ueg_kernels.pyx" + ] + }, + "module_name": "ueg_kernels" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) + #error Cython requires Python 2.6+ or Python 3.3+. +#else +#define CYTHON_ABI "0_29_35" +#define CYTHON_HEX_VERSION 0x001D23F0 +#define CYTHON_FUTURE_DIVISION 1 +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef HAVE_LONG_LONG + #if PY_VERSION_HEX >= 0x02070000 + #define HAVE_LONG_LONG + #endif +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#ifdef PYPY_VERSION + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_PYSTON 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(PYSTON_VERSION) + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_PYSTON 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(PY_NOGIL) + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_PYSTON 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_NOGIL 1 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #ifndef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_PYSTON 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_NOGIL 0 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #if PY_VERSION_HEX < 0x02070000 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #if PY_MAJOR_VERSION < 3 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #if PY_VERSION_HEX < 0x02070000 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLONG_INTERNALS) + #define CYTHON_USE_PYLONG_INTERNALS (PY_VERSION_HEX < 0x030C00A5) + #endif + #ifndef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if PY_VERSION_HEX < 0x030300F0 || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #if PY_VERSION_HEX >= 0x030B00A4 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #elif !defined(CYTHON_FAST_THREAD_STATE) + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL (PY_VERSION_HEX < 0x030A0000) + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) + #endif + #ifndef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS ((PY_VERSION_HEX >= 0x030600B1) && (PY_VERSION_HEX < 0x030C00A5)) + #endif + #if PY_VERSION_HEX >= 0x030B00A4 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #elif !defined(CYTHON_USE_EXC_INFO_STACK) + #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif +#endif +#if !defined(CYTHON_FAST_PYCCALL) +#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_MAJOR_VERSION < 3 + #include "longintrepr.h" + #endif + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#ifdef _MSC_VER + #ifndef _MSC_STDINT_H_ + #if _MSC_VER < 1300 + typedef unsigned char uint8_t; + typedef unsigned int uint32_t; + #else + typedef unsigned __int8 uint8_t; + typedef unsigned __int32 uint32_t; + #endif + #endif +#else + #include +#endif +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) && __cplusplus >= 201103L + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #elif __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__ ) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif + +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) + #define Py_OptimizeFlag 0 +#endif +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) + #define __Pyx_DefaultClassType PyClass_Type +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_DefaultClassType PyType_Type +#if PY_VERSION_HEX >= 0x030B00A1 + static CYTHON_INLINE PyCodeObject* __Pyx_PyCode_New(int a, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *kwds=NULL, *argcount=NULL, *posonlyargcount=NULL, *kwonlyargcount=NULL; + PyObject *nlocals=NULL, *stacksize=NULL, *flags=NULL, *replace=NULL, *call_result=NULL, *empty=NULL; + const char *fn_cstr=NULL; + const char *name_cstr=NULL; + PyCodeObject* co=NULL; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + if (!(kwds=PyDict_New())) goto end; + if (!(argcount=PyLong_FromLong(a))) goto end; + if (PyDict_SetItemString(kwds, "co_argcount", argcount) != 0) goto end; + if (!(posonlyargcount=PyLong_FromLong(0))) goto end; + if (PyDict_SetItemString(kwds, "co_posonlyargcount", posonlyargcount) != 0) goto end; + if (!(kwonlyargcount=PyLong_FromLong(k))) goto end; + if (PyDict_SetItemString(kwds, "co_kwonlyargcount", kwonlyargcount) != 0) goto end; + if (!(nlocals=PyLong_FromLong(l))) goto end; + if (PyDict_SetItemString(kwds, "co_nlocals", nlocals) != 0) goto end; + if (!(stacksize=PyLong_FromLong(s))) goto end; + if (PyDict_SetItemString(kwds, "co_stacksize", stacksize) != 0) goto end; + if (!(flags=PyLong_FromLong(f))) goto end; + if (PyDict_SetItemString(kwds, "co_flags", flags) != 0) goto end; + if (PyDict_SetItemString(kwds, "co_code", code) != 0) goto end; + if (PyDict_SetItemString(kwds, "co_consts", c) != 0) goto end; + if (PyDict_SetItemString(kwds, "co_names", n) != 0) goto end; + if (PyDict_SetItemString(kwds, "co_varnames", v) != 0) goto end; + if (PyDict_SetItemString(kwds, "co_freevars", fv) != 0) goto end; + if (PyDict_SetItemString(kwds, "co_cellvars", cell) != 0) goto end; + if (PyDict_SetItemString(kwds, "co_linetable", lnos) != 0) goto end; + if (!(fn_cstr=PyUnicode_AsUTF8AndSize(fn, NULL))) goto end; + if (!(name_cstr=PyUnicode_AsUTF8AndSize(name, NULL))) goto end; + if (!(co = PyCode_NewEmpty(fn_cstr, name_cstr, fline))) goto end; + if (!(replace = PyObject_GetAttrString((PyObject*)co, "replace"))) goto cleanup_code_too; + if (!(empty = PyTuple_New(0))) goto cleanup_code_too; // unfortunately __pyx_empty_tuple isn't available here + if (!(call_result = PyObject_Call(replace, empty, kwds))) goto cleanup_code_too; + Py_XDECREF((PyObject*)co); + co = (PyCodeObject*)call_result; + call_result = NULL; + if (0) { + cleanup_code_too: + Py_XDECREF((PyObject*)co); + co = NULL; + } + end: + Py_XDECREF(kwds); + Py_XDECREF(argcount); + Py_XDECREF(posonlyargcount); + Py_XDECREF(kwonlyargcount); + Py_XDECREF(nlocals); + Py_XDECREF(stacksize); + Py_XDECREF(replace); + Py_XDECREF(call_result); + Py_XDECREF(empty); + if (type) { + PyErr_Restore(type, value, traceback); + } + return co; + } +#else + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif + #define __Pyx_DefaultClassType PyType_Type +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #define __Pyx_PyCFunctionFast _PyCFunctionFast + #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords +#endif +#if CYTHON_FAST_PYCCALL +#define __Pyx_PyFastCFunction_Check(func)\ + ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) +#else +#define __Pyx_PyFastCFunction_Check(func) 0 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 + #define PyMem_RawMalloc(n) PyMem_Malloc(n) + #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) + #define PyMem_RawFree(p) PyMem_Free(p) +#endif +#if CYTHON_COMPILING_IN_PYSTON + #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x03060000 + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#elif PY_VERSION_HEX >= 0x03000000 + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_Current +#endif +#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) +#include "pythread.h" +#define Py_tss_NEEDS_INIT 0 +typedef int Py_tss_t; +static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { + *key = PyThread_create_key(); + return 0; +} +static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { + Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); + *key = Py_tss_NEEDS_INIT; + return key; +} +static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { + PyObject_Free(key); +} +static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { + return *key != Py_tss_NEEDS_INIT; +} +static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { + PyThread_delete_key(*key); + *key = Py_tss_NEEDS_INIT; +} +static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { + return PyThread_set_key_value(*key, value); +} +static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { + return PyThread_get_key_value(*key); +} +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +#else +#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) +#endif +#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#else + #define CYTHON_PEP393_ENABLED 0 + #define PyUnicode_1BYTE_KIND 1 + #define PyUnicode_2BYTE_KIND 2 + #define PyUnicode_4BYTE_KIND 4 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) + #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) + #define PyObject_ASCII(o) PyObject_Repr(o) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#ifndef PyObject_Unicode + #define PyObject_Unicode PyObject_Str +#endif +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) +#else + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsHash_t +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsSsize_t +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) +#else + #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) +#endif +#if CYTHON_USE_ASYNC_SLOTS + #if PY_VERSION_HEX >= 0x030500B1 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods + #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) + #else + #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) + #endif +#else + #define __Pyx_PyType_AsAsync(obj) NULL +#endif +#ifndef __Pyx_PyAsyncMethodsStruct + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + } __Pyx_PyAsyncMethodsStruct; +#endif + +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #if !defined(_USE_MATH_DEFINES) + #define _USE_MATH_DEFINES + #endif +#endif +#include +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#define __PYX_MARK_ERR_POS(f_index, lineno) \ + { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifndef __PYX_EXTERN_C + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__ueg_kernels +#define __PYX_HAVE_API__ueg_kernels +/* Early includes */ +#include +#include +#include "numpy/arrayobject.h" +#include "numpy/ndarrayobject.h" +#include "numpy/ndarraytypes.h" +#include "numpy/arrayscalars.h" +#include "numpy/ufuncobject.h" + + /* NumPy API declarations from "numpy/__init__.pxd" */ + +#include "pythread.h" +#include +#include "pystate.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) +#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#else +#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) +#endif +#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } + +static PyObject *__pyx_m = NULL; +static PyObject *__pyx_d; +static PyObject *__pyx_b; +static PyObject *__pyx_cython_runtime = NULL; +static PyObject *__pyx_empty_tuple; +static PyObject *__pyx_empty_bytes; +static PyObject *__pyx_empty_unicode; +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm= __FILE__; +static const char *__pyx_filename; + +/* Header.proto */ +#if !defined(CYTHON_CCOMPLEX) + #if defined(__cplusplus) + #define CYTHON_CCOMPLEX 1 + #elif defined(_Complex_I) + #define CYTHON_CCOMPLEX 1 + #else + #define CYTHON_CCOMPLEX 0 + #endif +#endif +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #include + #else + #include + #endif +#endif +#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) + #undef _Complex_I + #define _Complex_I 1.0fj +#endif + + +static const char *__pyx_f[] = { + "ueg_kernels.pyx", + "__init__.pxd", + "stringsource", + "type.pxd", +}; +/* MemviewSliceStruct.proto */ +struct __pyx_memoryview_obj; +typedef struct { + struct __pyx_memoryview_obj *memview; + char *data; + Py_ssize_t shape[8]; + Py_ssize_t strides[8]; + Py_ssize_t suboffsets[8]; +} __Pyx_memviewslice; +#define __Pyx_MemoryView_Len(m) (m.shape[0]) + +/* Atomics.proto */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __pyx_atomic_int_type int +#if CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_incr_aligned(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) && CYTHON_COMPILING_IN_NOGIL + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #pragma intrinsic (_InterlockedExchangeAdd) + #define __pyx_atomic_incr_aligned(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_aligned(value) _InterlockedExchangeAdd(value, -1) + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +typedef volatile __pyx_atomic_int_type __pyx_atomic_int; +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview)\ + __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview)) + #define __pyx_sub_acquisition_count(memview)\ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview)) +#else + #define __pyx_add_acquisition_count(memview)\ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview)\ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + +/* ForceInitThreads.proto */ +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +/* NoFastGil.proto */ +#define __Pyx_PyGILState_Ensure PyGILState_Ensure +#define __Pyx_PyGILState_Release PyGILState_Release +#define __Pyx_FastGIL_Remember() +#define __Pyx_FastGIL_Forget() +#define __Pyx_FastGilFuncInit() + +/* BufferFormatStructs.proto */ +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; + struct __Pyx_StructField_* fields; + size_t size; + size_t arraysize[8]; + int ndim; + char typegroup; + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":689 + * # in Cython to enable them only on the right systems. + * + * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + */ +typedef npy_int8 __pyx_t_5numpy_int8_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":690 + * + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t + */ +typedef npy_int16 __pyx_t_5numpy_int16_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":691 + * ctypedef npy_int8 int8_t + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< + * ctypedef npy_int64 int64_t + * #ctypedef npy_int96 int96_t + */ +typedef npy_int32 __pyx_t_5numpy_int32_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":692 + * ctypedef npy_int16 int16_t + * ctypedef npy_int32 int32_t + * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< + * #ctypedef npy_int96 int96_t + * #ctypedef npy_int128 int128_t + */ +typedef npy_int64 __pyx_t_5numpy_int64_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":696 + * #ctypedef npy_int128 int128_t + * + * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + */ +typedef npy_uint8 __pyx_t_5numpy_uint8_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":697 + * + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t + */ +typedef npy_uint16 __pyx_t_5numpy_uint16_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":698 + * ctypedef npy_uint8 uint8_t + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< + * ctypedef npy_uint64 uint64_t + * #ctypedef npy_uint96 uint96_t + */ +typedef npy_uint32 __pyx_t_5numpy_uint32_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":699 + * ctypedef npy_uint16 uint16_t + * ctypedef npy_uint32 uint32_t + * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< + * #ctypedef npy_uint96 uint96_t + * #ctypedef npy_uint128 uint128_t + */ +typedef npy_uint64 __pyx_t_5numpy_uint64_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":703 + * #ctypedef npy_uint128 uint128_t + * + * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< + * ctypedef npy_float64 float64_t + * #ctypedef npy_float80 float80_t + */ +typedef npy_float32 __pyx_t_5numpy_float32_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":704 + * + * ctypedef npy_float32 float32_t + * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< + * #ctypedef npy_float80 float80_t + * #ctypedef npy_float128 float128_t + */ +typedef npy_float64 __pyx_t_5numpy_float64_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":713 + * # The int types are mapped a bit surprising -- + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t + */ +typedef npy_long __pyx_t_5numpy_int_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":714 + * # numpy.int corresponds to 'l' and numpy.long to 'q' + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< + * ctypedef npy_longlong longlong_t + * + */ +typedef npy_longlong __pyx_t_5numpy_long_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":715 + * ctypedef npy_long int_t + * ctypedef npy_longlong long_t + * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_ulong uint_t + */ +typedef npy_longlong __pyx_t_5numpy_longlong_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":717 + * ctypedef npy_longlong longlong_t + * + * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t + */ +typedef npy_ulong __pyx_t_5numpy_uint_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":718 + * + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< + * ctypedef npy_ulonglong ulonglong_t + * + */ +typedef npy_ulonglong __pyx_t_5numpy_ulong_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":719 + * ctypedef npy_ulong uint_t + * ctypedef npy_ulonglong ulong_t + * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< + * + * ctypedef npy_intp intp_t + */ +typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":721 + * ctypedef npy_ulonglong ulonglong_t + * + * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< + * ctypedef npy_uintp uintp_t + * + */ +typedef npy_intp __pyx_t_5numpy_intp_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":722 + * + * ctypedef npy_intp intp_t + * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< + * + * ctypedef npy_double float_t + */ +typedef npy_uintp __pyx_t_5numpy_uintp_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":724 + * ctypedef npy_uintp uintp_t + * + * ctypedef npy_double float_t # <<<<<<<<<<<<<< + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t + */ +typedef npy_double __pyx_t_5numpy_float_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":725 + * + * ctypedef npy_double float_t + * ctypedef npy_double double_t # <<<<<<<<<<<<<< + * ctypedef npy_longdouble longdouble_t + * + */ +typedef npy_double __pyx_t_5numpy_double_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":726 + * ctypedef npy_double float_t + * ctypedef npy_double double_t + * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cfloat cfloat_t + */ +typedef npy_longdouble __pyx_t_5numpy_longdouble_t; +/* Declarations.proto */ +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< double > __pyx_t_double_complex; + #else + typedef double _Complex __pyx_t_double_complex; + #endif +#else + typedef struct { double real, imag; } __pyx_t_double_complex; +#endif +static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); + +/* Declarations.proto */ +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + typedef ::std::complex< float > __pyx_t_float_complex; + #else + typedef float _Complex __pyx_t_float_complex; + #endif +#else + typedef struct { float real, imag; } __pyx_t_float_complex; +#endif +static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); + + +/*--- Type declarations ---*/ +struct __pyx_array_obj; +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":728 + * ctypedef npy_longdouble longdouble_t + * + * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t + */ +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":729 + * + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< + * ctypedef npy_clongdouble clongdouble_t + * + */ +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":730 + * ctypedef npy_cfloat cfloat_t + * ctypedef npy_cdouble cdouble_t + * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< + * + * ctypedef npy_cdouble complex_t + */ +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":732 + * ctypedef npy_clongdouble clongdouble_t + * + * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew1(a): + */ +typedef npy_cdouble __pyx_t_5numpy_complex_t; + +/* "View.MemoryView":106 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ +struct __pyx_array_obj { + PyObject_HEAD + struct __pyx_vtabstruct_array *__pyx_vtab; + char *data; + Py_ssize_t len; + char *format; + int ndim; + Py_ssize_t *_shape; + Py_ssize_t *_strides; + Py_ssize_t itemsize; + PyObject *mode; + PyObject *_format; + void (*callback_free_data)(void *); + int free_data; + int dtype_is_object; +}; + + +/* "View.MemoryView":280 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "View.MemoryView":331 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ +struct __pyx_memoryview_obj { + PyObject_HEAD + struct __pyx_vtabstruct_memoryview *__pyx_vtab; + PyObject *obj; + PyObject *_size; + PyObject *_array_interface; + PyThread_type_lock lock; + __pyx_atomic_int acquisition_count[2]; + __pyx_atomic_int *acquisition_count_aligned_p; + Py_buffer view; + int flags; + int dtype_is_object; + __Pyx_TypeInfo *typeinfo; +}; + + +/* "View.MemoryView":967 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ +struct __pyx_memoryviewslice_obj { + struct __pyx_memoryview_obj __pyx_base; + __Pyx_memviewslice from_slice; + PyObject *from_object; + PyObject *(*to_object_func)(char *); + int (*to_dtype_func)(char *, PyObject *); +}; + + + +/* "View.MemoryView":106 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ + +struct __pyx_vtabstruct_array { + PyObject *(*get_memview)(struct __pyx_array_obj *); +}; +static struct __pyx_vtabstruct_array *__pyx_vtabptr_array; + + +/* "View.MemoryView":331 + * + * @cname('__pyx_memoryview') + * cdef class memoryview(object): # <<<<<<<<<<<<<< + * + * cdef object obj + */ + +struct __pyx_vtabstruct_memoryview { + char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); + PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); + PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); + PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); +}; +static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; + + +/* "View.MemoryView":967 + * + * @cname('__pyx_memoryviewslice') + * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< + * "Internal class for passing memoryview slices to Python" + * + */ + +struct __pyx_vtabstruct__memoryviewslice { + struct __pyx_vtabstruct_memoryview __pyx_base; +}; +static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, int); + void (*DECREF)(void*, PyObject*, int); + void (*GOTREF)(void*, PyObject*, int); + void (*GIVEREF)(void*, PyObject*, int); + void* (*SetupContext)(const char*, int, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) +#endif + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) + #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* PyObjectGetAttrStr.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* PyDictVersioning.proto */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __pyx_dict_cached_value;\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* PyFunctionFastCall.proto */ +#if CYTHON_FAST_PYCALL +#define __Pyx_PyFunction_FastCall(func, args, nargs)\ + __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) +#if 1 || PY_VERSION_HEX < 0x030600B1 +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); +#else +#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) +#endif +#define __Pyx_BUILD_ASSERT_EXPR(cond)\ + (sizeof(char [1 - 2*!(cond)]) - 1) +#ifndef Py_MEMBER_SIZE +#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) +#endif +#if CYTHON_FAST_PYCALL + static size_t __pyx_pyframe_localsplus_offset = 0; + #include "frameobject.h" +#if PY_VERSION_HEX >= 0x030b00a6 + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif + #define __Pxy_PyFrame_Initialize_Offsets()\ + ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ + (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) + #define __Pyx_PyFrame_GetLocalsplus(frame)\ + (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) +#endif // CYTHON_FAST_PYCALL +#endif + +/* PyCFunctionFastCall.proto */ +#if CYTHON_FAST_PYCCALL +static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); +#else +#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) +#endif + +/* PyObjectCall.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* RaiseDoubleKeywords.proto */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywords.proto */ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ + const char* function_name); + +/* PyObjectCallMethO.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectCallNoArg.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); +#else +#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) +#endif + +/* PyObjectCallOneArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +/* PyIntBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) +#endif + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +/* ObjectGetItem.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); +#else +#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) +#endif + +/* PyObjectCall2Args.proto */ +static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* RaiseTooManyValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/* RaiseNeedMoreValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* IterFinish.proto */ +static CYTHON_INLINE int __Pyx_IterFinish(void); + +/* UnpackItemEndCheck.proto */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); + +/* BufferIndexError.proto */ +static void __Pyx_RaiseBufferIndexError(int axis); + +/* MemviewSliceInit.proto */ +#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d +#define __Pyx_MEMVIEW_DIRECT 1 +#define __Pyx_MEMVIEW_PTR 2 +#define __Pyx_MEMVIEW_FULL 4 +#define __Pyx_MEMVIEW_CONTIG 8 +#define __Pyx_MEMVIEW_STRIDED 16 +#define __Pyx_MEMVIEW_FOLLOW 32 +#define __Pyx_IS_C_CONTIG 1 +#define __Pyx_IS_F_CONTIG 2 +static int __Pyx_init_memviewslice( + struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference); +static CYTHON_INLINE int __pyx_add_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( + __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); +#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) +#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) +#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) +#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) +static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); + +/* SetItemInt.proto */ +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) :\ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) +static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +/* GetTopmostException.proto */ +#if CYTHON_USE_EXC_INFO_STACK +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* PyThreadStateGet.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() PyErr_Occurred() +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* PyErrExceptionMatches.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* PyErrFetchRestore.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* RaiseException.proto */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* IncludeStringH.proto */ +#include + +/* BytesEquals.proto */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* StrEquals.proto */ +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + +/* DivInt[Py_ssize_t].proto */ +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); + +/* UnaryNegOverflows.proto */ +#define UNARY_NEG_WOULD_OVERFLOW(x)\ + (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) + +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/ +/* GetAttr.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); + +/* decode_c_string_utf16.proto */ +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 0; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = -1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} + +/* decode_c_string.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* RaiseNoneIterError.proto */ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +/* SwapException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* Import.proto */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) +#endif +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) + +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +/* ListCompAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +/* ListExtend.proto */ +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} + +/* ListAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + PyList_SET_ITEM(list, len, x); + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +/* None.proto */ +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +/* DivInt[long].proto */ +static CYTHON_INLINE long __Pyx_div_long(long, long); + +/* PySequenceContains.proto */ +static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* HasAttr.proto */ +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); + +/* PyObject_GenericGetAttrNoDict.proto */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr +#endif + +/* PyObject_GenericGetAttr.proto */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr +#endif + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyObject *dict, void *vtable); + +/* PyObjectGetAttrStrNoError.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* TypeImport.proto */ +#ifndef __PYX_HAVE_RT_ImportType_proto_0_29_35 +#define __PYX_HAVE_RT_ImportType_proto_0_29_35 +#if __STDC_VERSION__ >= 201112L +#include +#endif +#if __STDC_VERSION__ >= 201112L || __cplusplus >= 201103L +#define __PYX_GET_STRUCT_ALIGNMENT_0_29_35(s) alignof(s) +#else +#define __PYX_GET_STRUCT_ALIGNMENT_0_29_35(s) sizeof(void*) +#endif +enum __Pyx_ImportType_CheckSize_0_29_35 { + __Pyx_ImportType_CheckSize_Error_0_29_35 = 0, + __Pyx_ImportType_CheckSize_Warn_0_29_35 = 1, + __Pyx_ImportType_CheckSize_Ignore_0_29_35 = 2 +}; +static PyTypeObject *__Pyx_ImportType_0_29_35(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_0_29_35 check_size); +#endif + +/* CLineInTraceback.proto */ +#ifdef CYTHON_CLINE_IN_TRACEBACK +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#else +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#endif + +/* CodeObjectCache.proto */ +typedef struct { + PyCodeObject* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* RealImag.proto */ +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + #define __Pyx_CREAL(z) ((z).real()) + #define __Pyx_CIMAG(z) ((z).imag()) + #else + #define __Pyx_CREAL(z) (__real__(z)) + #define __Pyx_CIMAG(z) (__imag__(z)) + #endif +#else + #define __Pyx_CREAL(z) ((z).real) + #define __Pyx_CIMAG(z) ((z).imag) +#endif +#if defined(__cplusplus) && CYTHON_CCOMPLEX\ + && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) + #define __Pyx_SET_CREAL(z,x) ((z).real(x)) + #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) +#else + #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) + #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) +#endif + +/* Arithmetic.proto */ +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq_double(a, b) ((a)==(b)) + #define __Pyx_c_sum_double(a, b) ((a)+(b)) + #define __Pyx_c_diff_double(a, b) ((a)-(b)) + #define __Pyx_c_prod_double(a, b) ((a)*(b)) + #define __Pyx_c_quot_double(a, b) ((a)/(b)) + #define __Pyx_c_neg_double(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero_double(z) ((z)==(double)0) + #define __Pyx_c_conj_double(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs_double(z) (::std::abs(z)) + #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero_double(z) ((z)==0) + #define __Pyx_c_conj_double(z) (conj(z)) + #if 1 + #define __Pyx_c_abs_double(z) (cabs(z)) + #define __Pyx_c_pow_double(a, b) (cpow(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); + static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); + #if 1 + static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); + #endif +#endif + +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +/* BufferStructDeclare.proto */ +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +/* MemviewSliceIsContig.proto */ +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim); + +/* OverlappingSlices.proto */ +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); + +/* Capsule.proto */ +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +/* IsLittleEndian.proto */ +static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); + +/* BufferFormatCheck.proto */ +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type); + +/* TypeInfoCompare.proto */ +static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); + +/* MemviewSliceValidateAndInit.proto */ +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj); + +/* ObjectToMemviewSlice.proto */ +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(PyObject *, int writable_flag); + +/* ObjectToMemviewSlice.proto */ +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_long(PyObject *, int writable_flag); + +/* GCCDiagnostics.proto */ +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* ObjectToMemviewSlice.proto */ +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *, int writable_flag); + +/* ObjectToMemviewSlice.proto */ +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsdsds___pyx_t_double_complex(PyObject *, int writable_flag); + +/* ToPy.proto */ +#define __pyx_PyComplex_FromComplex(z)\ + PyComplex_FromDoubles((double)__Pyx_CREAL(z),\ + (double)__Pyx_CIMAG(z)) + +/* MemviewDtypeToObject.proto */ +static CYTHON_INLINE PyObject *__pyx_memview_get_long(const char *itemp); +static CYTHON_INLINE int __pyx_memview_set_long(const char *itemp, PyObject *obj); + +/* FromPy.proto */ +static __pyx_t_double_complex __Pyx_PyComplex_As___pyx_t_double_complex(PyObject*); + +/* MemviewDtypeToObject.proto */ +static CYTHON_INLINE PyObject *__pyx_memview_get___pyx_t_double_complex(const char *itemp); +static CYTHON_INLINE int __pyx_memview_set___pyx_t_double_complex(const char *itemp, PyObject *obj); + +/* Arithmetic.proto */ +#if CYTHON_CCOMPLEX + #define __Pyx_c_eq_float(a, b) ((a)==(b)) + #define __Pyx_c_sum_float(a, b) ((a)+(b)) + #define __Pyx_c_diff_float(a, b) ((a)-(b)) + #define __Pyx_c_prod_float(a, b) ((a)*(b)) + #define __Pyx_c_quot_float(a, b) ((a)/(b)) + #define __Pyx_c_neg_float(a) (-(a)) + #ifdef __cplusplus + #define __Pyx_c_is_zero_float(z) ((z)==(float)0) + #define __Pyx_c_conj_float(z) (::std::conj(z)) + #if 1 + #define __Pyx_c_abs_float(z) (::std::abs(z)) + #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) + #endif + #else + #define __Pyx_c_is_zero_float(z) ((z)==0) + #define __Pyx_c_conj_float(z) (conjf(z)) + #if 1 + #define __Pyx_c_abs_float(z) (cabsf(z)) + #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) + #endif + #endif +#else + static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); + static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); + #if 1 + static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); + #endif +#endif + +/* MemviewSliceCopyTemplate.proto */ +static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(void); + +/* InitStrings.proto */ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); + +static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/ +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ + +/* Module declarations from 'cpython.buffer' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from '__builtin__' */ + +/* Module declarations from 'cpython.type' */ +static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; + +/* Module declarations from 'cpython' */ + +/* Module declarations from 'cpython.object' */ + +/* Module declarations from 'cpython.ref' */ + +/* Module declarations from 'cpython.mem' */ + +/* Module declarations from 'numpy' */ + +/* Module declarations from 'numpy' */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; +static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; +static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; +static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; +static PyTypeObject *__pyx_ptype_5numpy_generic = 0; +static PyTypeObject *__pyx_ptype_5numpy_number = 0; +static PyTypeObject *__pyx_ptype_5numpy_integer = 0; +static PyTypeObject *__pyx_ptype_5numpy_signedinteger = 0; +static PyTypeObject *__pyx_ptype_5numpy_unsignedinteger = 0; +static PyTypeObject *__pyx_ptype_5numpy_inexact = 0; +static PyTypeObject *__pyx_ptype_5numpy_floating = 0; +static PyTypeObject *__pyx_ptype_5numpy_complexfloating = 0; +static PyTypeObject *__pyx_ptype_5numpy_flexible = 0; +static PyTypeObject *__pyx_ptype_5numpy_character = 0; +static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; + +/* Module declarations from 'ueg_kernels' */ +static PyTypeObject *__pyx_array_type = 0; +static PyTypeObject *__pyx_MemviewEnum_type = 0; +static PyTypeObject *__pyx_memoryview_type = 0; +static PyTypeObject *__pyx_memoryviewslice_type = 0; +static PyObject *generic = 0; +static PyObject *strided = 0; +static PyObject *indirect = 0; +static PyObject *contiguous = 0; +static PyObject *indirect_contiguous = 0; +static int __pyx_memoryview_thread_locks_used; +static PyThread_type_lock __pyx_memoryview_thread_locks[8]; +static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ +static void *__pyx_align_pointer(void *, size_t); /*proto*/ +static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ +static PyObject *_unellipsify(PyObject *, int); /*proto*/ +static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ +static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ +static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ +static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ +static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ +static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ +static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ +static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ +static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ +static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/ +static __Pyx_TypeInfo __Pyx_TypeInfo___pyx_t_double_complex = { "double complex", NULL, sizeof(__pyx_t_double_complex), { 0 }, 0, 'C', 0, 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_long = { "long", NULL, sizeof(long), { 0 }, 0, IS_UNSIGNED(long) ? 'U' : 'I', IS_UNSIGNED(long), 0 }; +static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; +#define __Pyx_MODULE_NAME "ueg_kernels" +extern int __pyx_module_is_main_ueg_kernels; +int __pyx_module_is_main_ueg_kernels = 0; + +/* Implementation of 'ueg_kernels' */ +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_zip; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ImportError; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_Ellipsis; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_IndexError; +static const char __pyx_k_G[] = "G"; +static const char __pyx_k_J[] = "J"; +static const char __pyx_k_K[] = "K"; +static const char __pyx_k_O[] = "O"; +static const char __pyx_k_T[] = "T"; +static const char __pyx_k_c[] = "c"; +static const char __pyx_k_i[] = "i"; +static const char __pyx_k_j[] = "j"; +static const char __pyx_k_q[] = "q"; +static const char __pyx_k_s[] = "s"; +static const char __pyx_k_id[] = "id"; +static const char __pyx_k_iq[] = "iq"; +static const char __pyx_k_ki[] = "ki"; +static const char __pyx_k_kj[] = "kj"; +static const char __pyx_k_nq[] = "nq"; +static const char __pyx_k_pi[] = "pi"; +static const char __pyx_k_q2[] = "q2"; +static const char __pyx_k_vq[] = "vq"; +static const char __pyx_k_dot[] = "dot"; +static const char __pyx_k_fac[] = "fac"; +static const char __pyx_k_kpq[] = "kpq"; +static const char __pyx_k_new[] = "__new__"; +static const char __pyx_k_obj[] = "obj"; +static const char __pyx_k_pmq[] = "pmq"; +static const char __pyx_k_vol[] = "vol"; +static const char __pyx_k_zip[] = "zip"; +static const char __pyx_k_Gh_i[] = "Gh_i"; +static const char __pyx_k_Gh_j[] = "Gh_j"; +static const char __pyx_k_Gkpq[] = "Gkpq"; +static const char __pyx_k_Gpmq[] = "Gpmq"; +static const char __pyx_k_base[] = "base"; +static const char __pyx_k_copy[] = "copy"; +static const char __pyx_k_dict[] = "__dict__"; +static const char __pyx_k_flip[] = "flip"; +static const char __pyx_k_gmap[] = "gmap"; +static const char __pyx_k_idxj[] = "idxj"; +static const char __pyx_k_idxk[] = "idxk"; +static const char __pyx_k_idxp[] = "idxp"; +static const char __pyx_k_kfac[] = "kfac"; +static const char __pyx_k_main[] = "__main__"; +static const char __pyx_k_math[] = "math"; +static const char __pyx_k_mesh[] = "mesh"; +static const char __pyx_k_mode[] = "mode"; +static const char __pyx_k_name[] = "name"; +static const char __pyx_k_nbsf[] = "nbsf"; +static const char __pyx_k_ndim[] = "ndim"; +static const char __pyx_k_nkpq[] = "nkpq"; +static const char __pyx_k_nocc[] = "nocc"; +static const char __pyx_k_npmq[] = "npmq"; +static const char __pyx_k_pack[] = "pack"; +static const char __pyx_k_prod[] = "prod"; +static const char __pyx_k_qmap[] = "qmap"; +static const char __pyx_k_size[] = "size"; +static const char __pyx_k_step[] = "step"; +static const char __pyx_k_stop[] = "stop"; +static const char __pyx_k_test[] = "__test__"; +static const char __pyx_k_ASCII[] = "ASCII"; +static const char __pyx_k_DTYPE[] = "DTYPE"; +static const char __pyx_k_Ghalf[] = "Ghalf"; +static const char __pyx_k_Gprod[] = "Gprod"; +static const char __pyx_k_basis[] = "basis"; +static const char __pyx_k_class[] = "__class__"; +static const char __pyx_k_dtype[] = "dtype"; +static const char __pyx_k_error[] = "error"; +static const char __pyx_k_flags[] = "flags"; +static const char __pyx_k_inkpq[] = "inkpq"; +static const char __pyx_k_jnpmq[] = "jnpmq"; +static const char __pyx_k_kpq_i[] = "kpq_i"; +static const char __pyx_k_lQ_ij[] = "lQ_ij"; +static const char __pyx_k_lQ_ji[] = "lQ_ji"; +static const char __pyx_k_ngrid[] = "ngrid"; +static const char __pyx_k_numpy[] = "numpy"; +static const char __pyx_k_pmq_i[] = "pmq_i"; +static const char __pyx_k_qmesh[] = "qmesh"; +static const char __pyx_k_range[] = "range"; +static const char __pyx_k_shape[] = "shape"; +static const char __pyx_k_start[] = "start"; +static const char __pyx_k_vqvec[] = "vqvec"; +static const char __pyx_k_zeros[] = "zeros"; +static const char __pyx_k_encode[] = "encode"; +static const char __pyx_k_format[] = "format"; +static const char __pyx_k_idxjmq[] = "idxjmq"; +static const char __pyx_k_idxjpq[] = "idxjpq"; +static const char __pyx_k_idxkpq[] = "idxkpq"; +static const char __pyx_k_idxpmq[] = "idxpmq"; +static const char __pyx_k_import[] = "__import__"; +static const char __pyx_k_name_2[] = "__name__"; +static const char __pyx_k_nqgrid[] = "nqgrid"; +static const char __pyx_k_pickle[] = "pickle"; +static const char __pyx_k_reduce[] = "__reduce__"; +static const char __pyx_k_struct[] = "struct"; +static const char __pyx_k_unpack[] = "unpack"; +static const char __pyx_k_update[] = "update"; +static const char __pyx_k_asarray[] = "asarray"; +static const char __pyx_k_float64[] = "float64"; +static const char __pyx_k_fortran[] = "fortran"; +static const char __pyx_k_h1e_mod[] = "h1e_mod"; +static const char __pyx_k_memview[] = "memview"; +static const char __pyx_k_CTdagger[] = "CTdagger"; +static const char __pyx_k_DTYPE_CX[] = "DTYPE_CX"; +static const char __pyx_k_Ellipsis[] = "Ellipsis"; +static const char __pyx_k_convolve[] = "convolve"; +static const char __pyx_k_getstate[] = "__getstate__"; +static const char __pyx_k_itemsize[] = "itemsize"; +static const char __pyx_k_pyx_type[] = "__pyx_type"; +static const char __pyx_k_setstate[] = "__setstate__"; +static const char __pyx_k_Gh_i_cube[] = "Gh_i_cube"; +static const char __pyx_k_Gh_j_cube[] = "Gh_j_cube"; +static const char __pyx_k_TypeError[] = "TypeError"; +static const char __pyx_k_enumerate[] = "enumerate"; +static const char __pyx_k_itertools[] = "itertools"; +static const char __pyx_k_pyx_state[] = "__pyx_state"; +static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; +static const char __pyx_k_CTdagger_i[] = "CTdagger_i"; +static const char __pyx_k_CTdagger_j[] = "CTdagger_j"; +static const char __pyx_k_IndexError[] = "IndexError"; +static const char __pyx_k_ValueError[] = "ValueError"; +static const char __pyx_k_complex128[] = "complex128"; +static const char __pyx_k_pyx_result[] = "__pyx_result"; +static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static const char __pyx_k_ImportError[] = "ImportError"; +static const char __pyx_k_MemoryError[] = "MemoryError"; +static const char __pyx_k_PickleError[] = "PickleError"; +static const char __pyx_k_build_J_opt[] = "build_J_opt"; +static const char __pyx_k_build_K_opt[] = "build_K_opt"; +static const char __pyx_k_ueg_kernels[] = "ueg_kernels"; +static const char __pyx_k_mod_one_body[] = "mod_one_body"; +static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; +static const char __pyx_k_stringsource[] = "stringsource"; +static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; +static const char __pyx_k_CTdagger_i_cube[] = "CTdagger_i_cube"; +static const char __pyx_k_CTdagger_j_cube[] = "CTdagger_j_cube"; +static const char __pyx_k_View_MemoryView[] = "View.MemoryView"; +static const char __pyx_k_allocate_buffer[] = "allocate_buffer"; +static const char __pyx_k_dtype_is_object[] = "dtype_is_object"; +static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; +static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; +static const char __pyx_k_ueg_kernels_pyx[] = "ueg_kernels.pyx"; +static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum"; +static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; +static const char __pyx_k_strided_and_direct[] = ""; +static const char __pyx_k_strided_and_indirect[] = ""; +static const char __pyx_k_contiguous_and_direct[] = ""; +static const char __pyx_k_MemoryView_of_r_object[] = ""; +static const char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; +static const char __pyx_k_contiguous_and_indirect[] = ""; +static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; +static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; +static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; +static const char __pyx_k_exchange_greens_function_fft[] = "exchange_greens_function_fft"; +static const char __pyx_k_ipie_legacy_estimators_utils[] = "ipie.legacy.estimators.utils"; +static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; +static const char __pyx_k_strided_and_direct_or_indirect[] = ""; +static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; +static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; +static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; +static const char __pyx_k_Cannot_assign_to_read_only_memor[] = "Cannot assign to read-only memoryview"; +static const char __pyx_k_Cannot_create_writable_memory_vi[] = "Cannot create writable memory view from read-only memoryview"; +static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; +static const char __pyx_k_Incompatible_checksums_0x_x_vs_0[] = "Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))"; +static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; +static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; +static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; +static const char __pyx_k_coulomb_greens_function_per_qvec[] = "coulomb_greens_function_per_qvec"; +static const char __pyx_k_exchange_greens_function_per_qve[] = "exchange_greens_function_per_qvec"; +static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; +static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; +static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; +static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; +static PyObject *__pyx_n_s_ASCII; +static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; +static PyObject *__pyx_n_s_CTdagger; +static PyObject *__pyx_n_s_CTdagger_i; +static PyObject *__pyx_n_s_CTdagger_i_cube; +static PyObject *__pyx_n_s_CTdagger_j; +static PyObject *__pyx_n_s_CTdagger_j_cube; +static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; +static PyObject *__pyx_kp_s_Cannot_assign_to_read_only_memor; +static PyObject *__pyx_kp_s_Cannot_create_writable_memory_vi; +static PyObject *__pyx_kp_s_Cannot_index_with_type_s; +static PyObject *__pyx_n_s_DTYPE; +static PyObject *__pyx_n_s_DTYPE_CX; +static PyObject *__pyx_n_s_Ellipsis; +static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; +static PyObject *__pyx_n_s_G; +static PyObject *__pyx_n_s_Gh_i; +static PyObject *__pyx_n_s_Gh_i_cube; +static PyObject *__pyx_n_s_Gh_j; +static PyObject *__pyx_n_s_Gh_j_cube; +static PyObject *__pyx_n_s_Ghalf; +static PyObject *__pyx_n_s_Gkpq; +static PyObject *__pyx_n_s_Gpmq; +static PyObject *__pyx_n_s_Gprod; +static PyObject *__pyx_n_s_ImportError; +static PyObject *__pyx_kp_s_Incompatible_checksums_0x_x_vs_0; +static PyObject *__pyx_n_s_IndexError; +static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; +static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; +static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; +static PyObject *__pyx_n_s_J; +static PyObject *__pyx_n_s_K; +static PyObject *__pyx_n_s_MemoryError; +static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; +static PyObject *__pyx_kp_s_MemoryView_of_r_object; +static PyObject *__pyx_n_b_O; +static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; +static PyObject *__pyx_n_s_PickleError; +static PyObject *__pyx_n_s_T; +static PyObject *__pyx_n_s_TypeError; +static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; +static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_View_MemoryView; +static PyObject *__pyx_n_s_allocate_buffer; +static PyObject *__pyx_n_s_asarray; +static PyObject *__pyx_n_s_base; +static PyObject *__pyx_n_s_basis; +static PyObject *__pyx_n_s_build_J_opt; +static PyObject *__pyx_n_s_build_K_opt; +static PyObject *__pyx_n_s_c; +static PyObject *__pyx_n_u_c; +static PyObject *__pyx_n_s_class; +static PyObject *__pyx_n_s_cline_in_traceback; +static PyObject *__pyx_n_s_complex128; +static PyObject *__pyx_kp_s_contiguous_and_direct; +static PyObject *__pyx_kp_s_contiguous_and_indirect; +static PyObject *__pyx_n_s_convolve; +static PyObject *__pyx_n_s_copy; +static PyObject *__pyx_n_s_coulomb_greens_function_per_qvec; +static PyObject *__pyx_n_s_dict; +static PyObject *__pyx_n_s_dot; +static PyObject *__pyx_n_s_dtype; +static PyObject *__pyx_n_s_dtype_is_object; +static PyObject *__pyx_n_s_encode; +static PyObject *__pyx_n_s_enumerate; +static PyObject *__pyx_n_s_error; +static PyObject *__pyx_n_s_exchange_greens_function_fft; +static PyObject *__pyx_n_s_exchange_greens_function_per_qve; +static PyObject *__pyx_n_s_fac; +static PyObject *__pyx_n_s_flags; +static PyObject *__pyx_n_s_flip; +static PyObject *__pyx_n_s_float64; +static PyObject *__pyx_n_s_format; +static PyObject *__pyx_n_s_fortran; +static PyObject *__pyx_n_u_fortran; +static PyObject *__pyx_n_s_getstate; +static PyObject *__pyx_n_s_gmap; +static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; +static PyObject *__pyx_n_s_h1e_mod; +static PyObject *__pyx_n_s_i; +static PyObject *__pyx_n_s_id; +static PyObject *__pyx_n_s_idxj; +static PyObject *__pyx_n_s_idxjmq; +static PyObject *__pyx_n_s_idxjpq; +static PyObject *__pyx_n_s_idxk; +static PyObject *__pyx_n_s_idxkpq; +static PyObject *__pyx_n_s_idxp; +static PyObject *__pyx_n_s_idxpmq; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_inkpq; +static PyObject *__pyx_n_s_ipie_legacy_estimators_utils; +static PyObject *__pyx_n_s_iq; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; +static PyObject *__pyx_n_s_itertools; +static PyObject *__pyx_n_s_j; +static PyObject *__pyx_n_s_jnpmq; +static PyObject *__pyx_n_s_kfac; +static PyObject *__pyx_n_s_ki; +static PyObject *__pyx_n_s_kj; +static PyObject *__pyx_n_s_kpq; +static PyObject *__pyx_n_s_kpq_i; +static PyObject *__pyx_n_s_lQ_ij; +static PyObject *__pyx_n_s_lQ_ji; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_math; +static PyObject *__pyx_n_s_memview; +static PyObject *__pyx_n_s_mesh; +static PyObject *__pyx_n_s_mod_one_body; +static PyObject *__pyx_n_s_mode; +static PyObject *__pyx_n_s_name; +static PyObject *__pyx_n_s_name_2; +static PyObject *__pyx_n_s_nbsf; +static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_new; +static PyObject *__pyx_n_s_ngrid; +static PyObject *__pyx_n_s_nkpq; +static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; +static PyObject *__pyx_n_s_nocc; +static PyObject *__pyx_n_s_npmq; +static PyObject *__pyx_n_s_nq; +static PyObject *__pyx_n_s_nqgrid; +static PyObject *__pyx_n_s_numpy; +static PyObject *__pyx_kp_u_numpy_core_multiarray_failed_to; +static PyObject *__pyx_kp_u_numpy_core_umath_failed_to_impor; +static PyObject *__pyx_n_s_obj; +static PyObject *__pyx_n_s_pack; +static PyObject *__pyx_n_s_pi; +static PyObject *__pyx_n_s_pickle; +static PyObject *__pyx_n_s_pmq; +static PyObject *__pyx_n_s_pmq_i; +static PyObject *__pyx_n_s_prod; +static PyObject *__pyx_n_s_pyx_PickleError; +static PyObject *__pyx_n_s_pyx_checksum; +static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_result; +static PyObject *__pyx_n_s_pyx_state; +static PyObject *__pyx_n_s_pyx_type; +static PyObject *__pyx_n_s_pyx_unpickle_Enum; +static PyObject *__pyx_n_s_pyx_vtable; +static PyObject *__pyx_n_s_q; +static PyObject *__pyx_n_s_q2; +static PyObject *__pyx_n_s_qmap; +static PyObject *__pyx_n_s_qmesh; +static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_reduce; +static PyObject *__pyx_n_s_reduce_cython; +static PyObject *__pyx_n_s_reduce_ex; +static PyObject *__pyx_n_s_s; +static PyObject *__pyx_n_s_setstate; +static PyObject *__pyx_n_s_setstate_cython; +static PyObject *__pyx_n_s_shape; +static PyObject *__pyx_n_s_size; +static PyObject *__pyx_n_s_start; +static PyObject *__pyx_n_s_step; +static PyObject *__pyx_n_s_stop; +static PyObject *__pyx_kp_s_strided_and_direct; +static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; +static PyObject *__pyx_kp_s_strided_and_indirect; +static PyObject *__pyx_kp_s_stringsource; +static PyObject *__pyx_n_s_struct; +static PyObject *__pyx_n_s_test; +static PyObject *__pyx_n_s_ueg_kernels; +static PyObject *__pyx_kp_s_ueg_kernels_pyx; +static PyObject *__pyx_kp_s_unable_to_allocate_array_data; +static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; +static PyObject *__pyx_n_s_unpack; +static PyObject *__pyx_n_s_update; +static PyObject *__pyx_n_s_vol; +static PyObject *__pyx_n_s_vq; +static PyObject *__pyx_n_s_vqvec; +static PyObject *__pyx_n_s_zeros; +static PyObject *__pyx_n_s_zip; +static PyObject *__pyx_pf_11ueg_kernels_vq(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_q); /* proto */ +static PyObject *__pyx_pf_11ueg_kernels_2mod_one_body(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T, PyArrayObject *__pyx_v_basis, double __pyx_v_vol, double __pyx_v_kfac); /* proto */ +static PyObject *__pyx_pf_11ueg_kernels_4coulomb_greens_function_per_qvec(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_kpq_i, PyArrayObject *__pyx_v_kpq, PyArrayObject *__pyx_v_pmq_i, PyArrayObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_G); /* proto */ +static PyObject *__pyx_pf_11ueg_kernels_6exchange_greens_function_per_qvec(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_kpq_i, __Pyx_memviewslice __pyx_v_kpq, __Pyx_memviewslice __pyx_v_pmq_i, __Pyx_memviewslice __pyx_v_pmq, __Pyx_memviewslice __pyx_v_G); /* proto */ +static PyObject *__pyx_pf_11ueg_kernels_8exchange_greens_function_fft(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nocc, long __pyx_v_nbsf, __Pyx_memviewslice __pyx_v_mesh, __Pyx_memviewslice __pyx_v_qmesh, __Pyx_memviewslice __pyx_v_gmap, __Pyx_memviewslice __pyx_v_qmap, __Pyx_memviewslice __pyx_v_CTdagger, __Pyx_memviewslice __pyx_v_Ghalf); /* proto */ +static PyObject *__pyx_pf_11ueg_kernels_10build_J_opt(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nq, __Pyx_memviewslice __pyx_v_vqvec, double __pyx_v_vol, long __pyx_v_nbsf, PyObject *__pyx_v_kpq_i, PyObject *__pyx_v_kpq, PyObject *__pyx_v_pmq_i, PyObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_Gkpq, __Pyx_memviewslice __pyx_v_Gpmq); /* proto */ +static PyObject *__pyx_pf_11ueg_kernels_12build_K_opt(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nq, __Pyx_memviewslice __pyx_v_vqvec, double __pyx_v_vol, long __pyx_v_nbsf, PyObject *__pyx_v_kpq_i, PyObject *__pyx_v_kpq, PyObject *__pyx_v_pmq_i, PyObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_G); /* proto */ +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_float_0_0; +static PyObject *__pyx_int_0; +static PyObject *__pyx_int_1; +static PyObject *__pyx_int_2; +static PyObject *__pyx_int_4; +static PyObject *__pyx_int_112105877; +static PyObject *__pyx_int_136983863; +static PyObject *__pyx_int_184977713; +static PyObject *__pyx_int_neg_1; +static PyObject *__pyx_tuple_; +static PyObject *__pyx_tuple__2; +static PyObject *__pyx_tuple__3; +static PyObject *__pyx_tuple__4; +static PyObject *__pyx_tuple__5; +static PyObject *__pyx_tuple__6; +static PyObject *__pyx_tuple__7; +static PyObject *__pyx_tuple__8; +static PyObject *__pyx_tuple__9; +static PyObject *__pyx_slice__17; +static PyObject *__pyx_tuple__10; +static PyObject *__pyx_tuple__11; +static PyObject *__pyx_tuple__12; +static PyObject *__pyx_tuple__13; +static PyObject *__pyx_tuple__14; +static PyObject *__pyx_tuple__15; +static PyObject *__pyx_tuple__16; +static PyObject *__pyx_tuple__18; +static PyObject *__pyx_tuple__19; +static PyObject *__pyx_tuple__20; +static PyObject *__pyx_tuple__21; +static PyObject *__pyx_tuple__22; +static PyObject *__pyx_tuple__24; +static PyObject *__pyx_tuple__26; +static PyObject *__pyx_tuple__28; +static PyObject *__pyx_tuple__30; +static PyObject *__pyx_tuple__32; +static PyObject *__pyx_tuple__34; +static PyObject *__pyx_tuple__36; +static PyObject *__pyx_tuple__37; +static PyObject *__pyx_tuple__38; +static PyObject *__pyx_tuple__39; +static PyObject *__pyx_tuple__40; +static PyObject *__pyx_tuple__41; +static PyObject *__pyx_codeobj__23; +static PyObject *__pyx_codeobj__25; +static PyObject *__pyx_codeobj__27; +static PyObject *__pyx_codeobj__29; +static PyObject *__pyx_codeobj__31; +static PyObject *__pyx_codeobj__33; +static PyObject *__pyx_codeobj__35; +static PyObject *__pyx_codeobj__42; +/* Late includes */ + +/* "ueg_kernels.pyx":14 + * + * + * def vq(numpy.ndarray q): # <<<<<<<<<<<<<< + * assert(q.shape[0] == 3) + * cdef double q2 = numpy.dot(q, q) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_11ueg_kernels_1vq(PyObject *__pyx_self, PyObject *__pyx_v_q); /*proto*/ +static PyMethodDef __pyx_mdef_11ueg_kernels_1vq = {"vq", (PyCFunction)__pyx_pw_11ueg_kernels_1vq, METH_O, 0}; +static PyObject *__pyx_pw_11ueg_kernels_1vq(PyObject *__pyx_self, PyObject *__pyx_v_q) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("vq (wrapper)", 0); + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_q), __pyx_ptype_5numpy_ndarray, 1, "q", 0))) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_r = __pyx_pf_11ueg_kernels_vq(__pyx_self, ((PyArrayObject *)__pyx_v_q)); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_11ueg_kernels_vq(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_q) { + double __pyx_v_q2; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + double __pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("vq", 0); + + /* "ueg_kernels.pyx":15 + * + * def vq(numpy.ndarray q): + * assert(q.shape[0] == 3) # <<<<<<<<<<<<<< + * cdef double q2 = numpy.dot(q, q) + * if (q2 < 1e-10): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_q->dimensions[0]) == 3) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + __PYX_ERR(0, 15, __pyx_L1_error) + } + } + #endif + + /* "ueg_kernels.pyx":16 + * def vq(numpy.ndarray q): + * assert(q.shape[0] == 3) + * cdef double q2 = numpy.dot(q, q) # <<<<<<<<<<<<<< + * if (q2 < 1e-10): + * return 0.0 + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_dot); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = NULL; + __pyx_t_4 = 0; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_4 = 1; + } + } + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_3)) { + PyObject *__pyx_temp[3] = {__pyx_t_2, ((PyObject *)__pyx_v_q), ((PyObject *)__pyx_v_q)}; + __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_4, 2+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { + PyObject *__pyx_temp[3] = {__pyx_t_2, ((PyObject *)__pyx_v_q), ((PyObject *)__pyx_v_q)}; + __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_4, 2+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else + #endif + { + __pyx_t_5 = PyTuple_New(2+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (__pyx_t_2) { + __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __pyx_t_2 = NULL; + } + __Pyx_INCREF(((PyObject *)__pyx_v_q)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_q)); + PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, ((PyObject *)__pyx_v_q)); + __Pyx_INCREF(((PyObject *)__pyx_v_q)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_q)); + PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, ((PyObject *)__pyx_v_q)); + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_q2 = __pyx_t_6; + + /* "ueg_kernels.pyx":17 + * assert(q.shape[0] == 3) + * cdef double q2 = numpy.dot(q, q) + * if (q2 < 1e-10): # <<<<<<<<<<<<<< + * return 0.0 + * else: + */ + __pyx_t_7 = ((__pyx_v_q2 < 1e-10) != 0); + if (__pyx_t_7) { + + /* "ueg_kernels.pyx":18 + * cdef double q2 = numpy.dot(q, q) + * if (q2 < 1e-10): + * return 0.0 # <<<<<<<<<<<<<< + * else: + * return 4*math.pi / q2 + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_float_0_0); + __pyx_r = __pyx_float_0_0; + goto __pyx_L0; + + /* "ueg_kernels.pyx":17 + * assert(q.shape[0] == 3) + * cdef double q2 = numpy.dot(q, q) + * if (q2 < 1e-10): # <<<<<<<<<<<<<< + * return 0.0 + * else: + */ + } + + /* "ueg_kernels.pyx":20 + * return 0.0 + * else: + * return 4*math.pi / q2 # <<<<<<<<<<<<<< + * + * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): + */ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_math); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_pi); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Multiply(__pyx_int_4, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_q2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + } + + /* "ueg_kernels.pyx":14 + * + * + * def vq(numpy.ndarray q): # <<<<<<<<<<<<<< + * assert(q.shape[0] == 3) + * cdef double q2 = numpy.dot(q, q) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("ueg_kernels.vq", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "ueg_kernels.pyx":22 + * return 4*math.pi / q2 + * + * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): # <<<<<<<<<<<<<< + * """ Add a diagonal term of two-body Hamiltonian to the one-body term + * Parameters + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_11ueg_kernels_3mod_one_body(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static char __pyx_doc_11ueg_kernels_2mod_one_body[] = " Add a diagonal term of two-body Hamiltonian to the one-body term\n Parameters\n ----------\n T : float\n one-body Hamiltonian (i.e. kinetic energy)\n Returns\n -------\n h1e_mod: float\n modified one-body Hamiltonian\n "; +static PyMethodDef __pyx_mdef_11ueg_kernels_3mod_one_body = {"mod_one_body", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_3mod_one_body, METH_VARARGS|METH_KEYWORDS, __pyx_doc_11ueg_kernels_2mod_one_body}; +static PyObject *__pyx_pw_11ueg_kernels_3mod_one_body(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_T = 0; + PyArrayObject *__pyx_v_basis = 0; + double __pyx_v_vol; + double __pyx_v_kfac; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("mod_one_body (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_T,&__pyx_n_s_basis,&__pyx_n_s_vol,&__pyx_n_s_kfac,0}; + PyObject* values[4] = {0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_T)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_basis)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("mod_one_body", 1, 4, 4, 1); __PYX_ERR(0, 22, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vol)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("mod_one_body", 1, 4, 4, 2); __PYX_ERR(0, 22, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 3: + if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kfac)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("mod_one_body", 1, 4, 4, 3); __PYX_ERR(0, 22, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "mod_one_body") < 0)) __PYX_ERR(0, 22, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + } + __pyx_v_T = ((PyArrayObject *)values[0]); + __pyx_v_basis = ((PyArrayObject *)values[1]); + __pyx_v_vol = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_vol == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 22, __pyx_L3_error) + __pyx_v_kfac = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_kfac == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 22, __pyx_L3_error) + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("mod_one_body", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 22, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("ueg_kernels.mod_one_body", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T), __pyx_ptype_5numpy_ndarray, 1, "T", 0))) __PYX_ERR(0, 22, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_basis), __pyx_ptype_5numpy_ndarray, 1, "basis", 0))) __PYX_ERR(0, 22, __pyx_L1_error) + __pyx_r = __pyx_pf_11ueg_kernels_2mod_one_body(__pyx_self, __pyx_v_T, __pyx_v_basis, __pyx_v_vol, __pyx_v_kfac); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_11ueg_kernels_2mod_one_body(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T, PyArrayObject *__pyx_v_basis, double __pyx_v_vol, double __pyx_v_kfac) { + CYTHON_UNUSED size_t __pyx_v_nbsf; + PyArrayObject *__pyx_v_h1e_mod = 0; + double __pyx_v_fac; + PyObject *__pyx_v_i = NULL; + PyObject *__pyx_v_ki = NULL; + PyObject *__pyx_v_j = NULL; + PyObject *__pyx_v_kj = NULL; + PyObject *__pyx_v_q = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + double __pyx_t_4; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + PyObject *(*__pyx_t_9)(PyObject *); + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyObject *__pyx_t_14 = NULL; + PyObject *__pyx_t_15 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("mod_one_body", 0); + + /* "ueg_kernels.pyx":34 + * """ + * + * cdef size_t nbsf = basis.shape[0] # <<<<<<<<<<<<<< + * cdef numpy.ndarray h1e_mod = T.copy() + * cdef double fac = 1.0 / (2.0 * vol) + */ + __pyx_v_nbsf = (__pyx_v_basis->dimensions[0]); + + /* "ueg_kernels.pyx":35 + * + * cdef size_t nbsf = basis.shape[0] + * cdef numpy.ndarray h1e_mod = T.copy() # <<<<<<<<<<<<<< + * cdef double fac = 1.0 / (2.0 * vol) + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_T), __pyx_n_s_copy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 35, __pyx_L1_error) + __pyx_v_h1e_mod = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":36 + * cdef size_t nbsf = basis.shape[0] + * cdef numpy.ndarray h1e_mod = T.copy() + * cdef double fac = 1.0 / (2.0 * vol) # <<<<<<<<<<<<<< + * + * for (i, ki) in enumerate(basis): + */ + __pyx_t_4 = (2.0 * __pyx_v_vol); + if (unlikely(__pyx_t_4 == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + __PYX_ERR(0, 36, __pyx_L1_error) + } + __pyx_v_fac = (1.0 / __pyx_t_4); + + /* "ueg_kernels.pyx":38 + * cdef double fac = 1.0 / (2.0 * vol) + * + * for (i, ki) in enumerate(basis): # <<<<<<<<<<<<<< + * for (j, kj) in enumerate(basis): + * if i != j: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_1 = __pyx_int_0; + if (likely(PyList_CheckExact(((PyObject *)__pyx_v_basis))) || PyTuple_CheckExact(((PyObject *)__pyx_v_basis))) { + __pyx_t_2 = ((PyObject *)__pyx_v_basis); __Pyx_INCREF(__pyx_t_2); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_2 = PyObject_GetIter(((PyObject *)__pyx_v_basis)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 38, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 38, __pyx_L1_error) + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_2, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + } else { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 38, __pyx_L1_error) + #else + __pyx_t_3 = PySequence_ITEM(__pyx_t_2, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + } + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_2); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 38, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF_SET(__pyx_v_ki, __pyx_t_3); + __pyx_t_3 = 0; + __Pyx_INCREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_t_1, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); + __pyx_t_1 = __pyx_t_3; + __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":39 + * + * for (i, ki) in enumerate(basis): + * for (j, kj) in enumerate(basis): # <<<<<<<<<<<<<< + * if i != j: + * q = kfac * (ki - kj) + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (likely(PyList_CheckExact(((PyObject *)__pyx_v_basis))) || PyTuple_CheckExact(((PyObject *)__pyx_v_basis))) { + __pyx_t_7 = ((PyObject *)__pyx_v_basis); __Pyx_INCREF(__pyx_t_7); __pyx_t_8 = 0; + __pyx_t_9 = NULL; + } else { + __pyx_t_8 = -1; __pyx_t_7 = PyObject_GetIter(((PyObject *)__pyx_v_basis)); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 39, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = Py_TYPE(__pyx_t_7)->tp_iternext; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 39, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_9)) { + if (likely(PyList_CheckExact(__pyx_t_7))) { + if (__pyx_t_8 >= PyList_GET_SIZE(__pyx_t_7)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_10 = PyList_GET_ITEM(__pyx_t_7, __pyx_t_8); __Pyx_INCREF(__pyx_t_10); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 39, __pyx_L1_error) + #else + __pyx_t_10 = PySequence_ITEM(__pyx_t_7, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 39, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + #endif + } else { + if (__pyx_t_8 >= PyTuple_GET_SIZE(__pyx_t_7)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_10 = PyTuple_GET_ITEM(__pyx_t_7, __pyx_t_8); __Pyx_INCREF(__pyx_t_10); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 39, __pyx_L1_error) + #else + __pyx_t_10 = PySequence_ITEM(__pyx_t_7, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 39, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + #endif + } + } else { + __pyx_t_10 = __pyx_t_9(__pyx_t_7); + if (unlikely(!__pyx_t_10)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 39, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_10); + } + __Pyx_XDECREF_SET(__pyx_v_kj, __pyx_t_10); + __pyx_t_10 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_j, __pyx_t_3); + __pyx_t_10 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 39, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_10; + __pyx_t_10 = 0; + + /* "ueg_kernels.pyx":40 + * for (i, ki) in enumerate(basis): + * for (j, kj) in enumerate(basis): + * if i != j: # <<<<<<<<<<<<<< + * q = kfac * (ki - kj) + * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) + */ + __pyx_t_10 = PyObject_RichCompare(__pyx_v_i, __pyx_v_j, Py_NE); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 40, __pyx_L1_error) + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely(__pyx_t_11 < 0)) __PYX_ERR(0, 40, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (__pyx_t_11) { + + /* "ueg_kernels.pyx":41 + * for (j, kj) in enumerate(basis): + * if i != j: + * q = kfac * (ki - kj) # <<<<<<<<<<<<<< + * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) + * return h1e_mod + */ + __pyx_t_10 = PyFloat_FromDouble(__pyx_v_kfac); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 41, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_12 = PyNumber_Subtract(__pyx_v_ki, __pyx_v_kj); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 41, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_13 = PyNumber_Multiply(__pyx_t_10, __pyx_t_12); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 41, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF_SET(__pyx_v_q, __pyx_t_13); + __pyx_t_13 = 0; + + /* "ueg_kernels.pyx":42 + * if i != j: + * q = kfac * (ki - kj) + * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) # <<<<<<<<<<<<<< + * return h1e_mod + * + */ + __pyx_t_13 = PyTuple_New(2); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __Pyx_INCREF(__pyx_v_i); + __Pyx_GIVEREF(__pyx_v_i); + PyTuple_SET_ITEM(__pyx_t_13, 0, __pyx_v_i); + __Pyx_INCREF(__pyx_v_i); + __Pyx_GIVEREF(__pyx_v_i); + PyTuple_SET_ITEM(__pyx_t_13, 1, __pyx_v_i); + __pyx_t_12 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_h1e_mod), __pyx_t_13); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + __pyx_t_13 = PyFloat_FromDouble(__pyx_v_fac); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __Pyx_GetModuleGlobalName(__pyx_t_14, __pyx_n_s_vq); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __pyx_t_15 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_14))) { + __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_14); + if (likely(__pyx_t_15)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_14); + __Pyx_INCREF(__pyx_t_15); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_14, function); + } + } + __pyx_t_10 = (__pyx_t_15) ? __Pyx_PyObject_Call2Args(__pyx_t_14, __pyx_t_15, __pyx_v_q) : __Pyx_PyObject_CallOneArg(__pyx_t_14, __pyx_v_q); + __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; + if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __pyx_t_14 = PyNumber_Multiply(__pyx_t_13, __pyx_t_10); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = PyNumber_Subtract(__pyx_t_12, __pyx_t_14); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __pyx_t_14 = PyTuple_New(2); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __Pyx_INCREF(__pyx_v_i); + __Pyx_GIVEREF(__pyx_v_i); + PyTuple_SET_ITEM(__pyx_t_14, 0, __pyx_v_i); + __Pyx_INCREF(__pyx_v_i); + __Pyx_GIVEREF(__pyx_v_i); + PyTuple_SET_ITEM(__pyx_t_14, 1, __pyx_v_i); + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_h1e_mod), __pyx_t_14, __pyx_t_10) < 0)) __PYX_ERR(0, 42, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "ueg_kernels.pyx":40 + * for (i, ki) in enumerate(basis): + * for (j, kj) in enumerate(basis): + * if i != j: # <<<<<<<<<<<<<< + * q = kfac * (ki - kj) + * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) + */ + } + + /* "ueg_kernels.pyx":39 + * + * for (i, ki) in enumerate(basis): + * for (j, kj) in enumerate(basis): # <<<<<<<<<<<<<< + * if i != j: + * q = kfac * (ki - kj) + */ + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":38 + * cdef double fac = 1.0 / (2.0 * vol) + * + * for (i, ki) in enumerate(basis): # <<<<<<<<<<<<<< + * for (j, kj) in enumerate(basis): + * if i != j: + */ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":43 + * q = kfac * (ki - kj) + * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) + * return h1e_mod # <<<<<<<<<<<<<< + * + * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_h1e_mod)); + __pyx_r = ((PyObject *)__pyx_v_h1e_mod); + goto __pyx_L0; + + /* "ueg_kernels.pyx":22 + * return 4*math.pi / q2 + * + * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): # <<<<<<<<<<<<<< + * """ Add a diagonal term of two-body Hamiltonian to the one-body term + * Parameters + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_XDECREF(__pyx_t_13); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_AddTraceback("ueg_kernels.mod_one_body", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_h1e_mod); + __Pyx_XDECREF(__pyx_v_i); + __Pyx_XDECREF(__pyx_v_ki); + __Pyx_XDECREF(__pyx_v_j); + __Pyx_XDECREF(__pyx_v_kj); + __Pyx_XDECREF(__pyx_v_q); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "ueg_kernels.pyx":45 + * return h1e_mod + * + * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): # <<<<<<<<<<<<<< + * + * cdef int nq = kpq_i.shape[0] + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_11ueg_kernels_5coulomb_greens_function_per_qvec(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_11ueg_kernels_5coulomb_greens_function_per_qvec = {"coulomb_greens_function_per_qvec", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_5coulomb_greens_function_per_qvec, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_11ueg_kernels_5coulomb_greens_function_per_qvec(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyArrayObject *__pyx_v_kpq_i = 0; + PyArrayObject *__pyx_v_kpq = 0; + PyArrayObject *__pyx_v_pmq_i = 0; + PyArrayObject *__pyx_v_pmq = 0; + __Pyx_memviewslice __pyx_v_G = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("coulomb_greens_function_per_qvec (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_kpq_i,&__pyx_n_s_kpq,&__pyx_n_s_pmq_i,&__pyx_n_s_pmq,&__pyx_n_s_G,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq_i)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, 1); __PYX_ERR(0, 45, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq_i)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, 2); __PYX_ERR(0, 45, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 3: + if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, 3); __PYX_ERR(0, 45, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 4: + if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_G)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, 4); __PYX_ERR(0, 45, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "coulomb_greens_function_per_qvec") < 0)) __PYX_ERR(0, 45, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + } + __pyx_v_kpq_i = ((PyArrayObject *)values[0]); + __pyx_v_kpq = ((PyArrayObject *)values[1]); + __pyx_v_pmq_i = ((PyArrayObject *)values[2]); + __pyx_v_pmq = ((PyArrayObject *)values[3]); + __pyx_v_G = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_G.memview)) __PYX_ERR(0, 45, __pyx_L3_error) + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 45, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("ueg_kernels.coulomb_greens_function_per_qvec", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq_i), __pyx_ptype_5numpy_ndarray, 1, "kpq_i", 0))) __PYX_ERR(0, 45, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq), __pyx_ptype_5numpy_ndarray, 1, "kpq", 0))) __PYX_ERR(0, 45, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq_i), __pyx_ptype_5numpy_ndarray, 1, "pmq_i", 0))) __PYX_ERR(0, 45, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq), __pyx_ptype_5numpy_ndarray, 1, "pmq", 0))) __PYX_ERR(0, 45, __pyx_L1_error) + __pyx_r = __pyx_pf_11ueg_kernels_4coulomb_greens_function_per_qvec(__pyx_self, __pyx_v_kpq_i, __pyx_v_kpq, __pyx_v_pmq_i, __pyx_v_pmq, __pyx_v_G); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_11ueg_kernels_4coulomb_greens_function_per_qvec(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_kpq_i, PyArrayObject *__pyx_v_kpq, PyArrayObject *__pyx_v_pmq_i, PyArrayObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_G) { + CYTHON_UNUSED int __pyx_v_nq; + int __pyx_v_idxkpq; + int __pyx_v_idxpmq; + int __pyx_v_i; + __pyx_t_double_complex __pyx_v_Gkpq; + __pyx_t_double_complex __pyx_v_Gpmq; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *(*__pyx_t_8)(PyObject *); + int __pyx_t_9; + int __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("coulomb_greens_function_per_qvec", 0); + + /* "ueg_kernels.pyx":47 + * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): + * + * cdef int nq = kpq_i.shape[0] # <<<<<<<<<<<<<< + * + * cdef int idxkpq, idxpmq, i, j, iq + */ + __pyx_v_nq = (__pyx_v_kpq_i->dimensions[0]); + + /* "ueg_kernels.pyx":51 + * cdef int idxkpq, idxpmq, i, j, iq + * + * cdef double complex Gkpq = 0.0 # <<<<<<<<<<<<<< + * cdef double complex Gpmq = 0.0 + * + */ + __pyx_v_Gkpq = __pyx_t_double_complex_from_parts(0.0, 0); + + /* "ueg_kernels.pyx":52 + * + * cdef double complex Gkpq = 0.0 + * cdef double complex Gpmq = 0.0 # <<<<<<<<<<<<<< + * + * for (idxkpq,i) in zip(kpq,kpq_i): + */ + __pyx_v_Gpmq = __pyx_t_double_complex_from_parts(0.0, 0); + + /* "ueg_kernels.pyx":54 + * cdef double complex Gpmq = 0.0 + * + * for (idxkpq,i) in zip(kpq,kpq_i): # <<<<<<<<<<<<<< + * Gkpq += G[i,idxkpq] + * for (idxpmq,i) in zip(pmq,pmq_i): + */ + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_kpq)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_kpq)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_kpq)); + __Pyx_INCREF(((PyObject *)__pyx_v_kpq_i)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_kpq_i)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_kpq_i)); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 54, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 54, __pyx_L1_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 54, __pyx_L1_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_4(__pyx_t_1); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 54, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 54, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_5 = PyList_GET_ITEM(sequence, 0); + __pyx_t_6 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx_t_6); + #else + __pyx_t_5 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; + index = 0; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + index = 1; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < 0) __PYX_ERR(0, 54, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 54, __pyx_L1_error) + __pyx_L6_unpacking_done:; + } + __pyx_t_9 = __Pyx_PyInt_As_int(__pyx_t_5); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_10 = __Pyx_PyInt_As_int(__pyx_t_6); if (unlikely((__pyx_t_10 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 54, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_idxkpq = __pyx_t_9; + __pyx_v_i = __pyx_t_10; + + /* "ueg_kernels.pyx":55 + * + * for (idxkpq,i) in zip(kpq,kpq_i): + * Gkpq += G[i,idxkpq] # <<<<<<<<<<<<<< + * for (idxpmq,i) in zip(pmq,pmq_i): + * Gpmq += G[i,idxpmq] + */ + __pyx_t_11 = __pyx_v_i; + __pyx_t_12 = __pyx_v_idxkpq; + __pyx_t_10 = -1; + if (__pyx_t_11 < 0) { + __pyx_t_11 += __pyx_v_G.shape[0]; + if (unlikely(__pyx_t_11 < 0)) __pyx_t_10 = 0; + } else if (unlikely(__pyx_t_11 >= __pyx_v_G.shape[0])) __pyx_t_10 = 0; + if (__pyx_t_12 < 0) { + __pyx_t_12 += __pyx_v_G.shape[1]; + if (unlikely(__pyx_t_12 < 0)) __pyx_t_10 = 1; + } else if (unlikely(__pyx_t_12 >= __pyx_v_G.shape[1])) __pyx_t_10 = 1; + if (unlikely(__pyx_t_10 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_10); + __PYX_ERR(0, 55, __pyx_L1_error) + } + __pyx_v_Gkpq = __Pyx_c_sum_double(__pyx_v_Gkpq, (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_11 * __pyx_v_G.strides[0]) ) + __pyx_t_12 * __pyx_v_G.strides[1]) )))); + + /* "ueg_kernels.pyx":54 + * cdef double complex Gpmq = 0.0 + * + * for (idxkpq,i) in zip(kpq,kpq_i): # <<<<<<<<<<<<<< + * Gkpq += G[i,idxkpq] + * for (idxpmq,i) in zip(pmq,pmq_i): + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":56 + * for (idxkpq,i) in zip(kpq,kpq_i): + * Gkpq += G[i,idxkpq] + * for (idxpmq,i) in zip(pmq,pmq_i): # <<<<<<<<<<<<<< + * Gpmq += G[i,idxpmq] + * + */ + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)__pyx_v_pmq)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_pmq)); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_pmq)); + __Pyx_INCREF(((PyObject *)__pyx_v_pmq_i)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_pmq_i)); + PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_pmq_i)); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 56, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 56, __pyx_L1_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 56, __pyx_L1_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_4(__pyx_t_1); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 56, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 56, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_6 = PyList_GET_ITEM(sequence, 0); + __pyx_t_5 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_6); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_6 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; + index = 0; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L9_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + index = 1; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L9_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < 0) __PYX_ERR(0, 56, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L10_unpacking_done; + __pyx_L9_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 56, __pyx_L1_error) + __pyx_L10_unpacking_done:; + } + __pyx_t_10 = __Pyx_PyInt_As_int(__pyx_t_6); if (unlikely((__pyx_t_10 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_9 = __Pyx_PyInt_As_int(__pyx_t_5); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_idxpmq = __pyx_t_10; + __pyx_v_i = __pyx_t_9; + + /* "ueg_kernels.pyx":57 + * Gkpq += G[i,idxkpq] + * for (idxpmq,i) in zip(pmq,pmq_i): + * Gpmq += G[i,idxpmq] # <<<<<<<<<<<<<< + * + * return Gkpq, Gpmq + */ + __pyx_t_12 = __pyx_v_i; + __pyx_t_11 = __pyx_v_idxpmq; + __pyx_t_9 = -1; + if (__pyx_t_12 < 0) { + __pyx_t_12 += __pyx_v_G.shape[0]; + if (unlikely(__pyx_t_12 < 0)) __pyx_t_9 = 0; + } else if (unlikely(__pyx_t_12 >= __pyx_v_G.shape[0])) __pyx_t_9 = 0; + if (__pyx_t_11 < 0) { + __pyx_t_11 += __pyx_v_G.shape[1]; + if (unlikely(__pyx_t_11 < 0)) __pyx_t_9 = 1; + } else if (unlikely(__pyx_t_11 >= __pyx_v_G.shape[1])) __pyx_t_9 = 1; + if (unlikely(__pyx_t_9 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_9); + __PYX_ERR(0, 57, __pyx_L1_error) + } + __pyx_v_Gpmq = __Pyx_c_sum_double(__pyx_v_Gpmq, (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_12 * __pyx_v_G.strides[0]) ) + __pyx_t_11 * __pyx_v_G.strides[1]) )))); + + /* "ueg_kernels.pyx":56 + * for (idxkpq,i) in zip(kpq,kpq_i): + * Gkpq += G[i,idxkpq] + * for (idxpmq,i) in zip(pmq,pmq_i): # <<<<<<<<<<<<<< + * Gpmq += G[i,idxpmq] + * + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":59 + * Gpmq += G[i,idxpmq] + * + * return Gkpq, Gpmq # <<<<<<<<<<<<<< + * + * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_Gkpq); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_PyComplex_FromComplex(__pyx_v_Gpmq); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "ueg_kernels.pyx":45 + * return h1e_mod + * + * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): # <<<<<<<<<<<<<< + * + * cdef int nq = kpq_i.shape[0] + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("ueg_kernels.coulomb_greens_function_per_qvec", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_G, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "ueg_kernels.pyx":61 + * return Gkpq, Gpmq + * + * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): # <<<<<<<<<<<<<< + * + * cdef int nkpq = kpq_i.shape[0] + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_11ueg_kernels_7exchange_greens_function_per_qvec(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_11ueg_kernels_7exchange_greens_function_per_qvec = {"exchange_greens_function_per_qvec", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_7exchange_greens_function_per_qvec, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_11ueg_kernels_7exchange_greens_function_per_qvec(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + __Pyx_memviewslice __pyx_v_kpq_i = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_kpq = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_pmq_i = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_pmq = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_G = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("exchange_greens_function_per_qvec (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_kpq_i,&__pyx_n_s_kpq,&__pyx_n_s_pmq_i,&__pyx_n_s_pmq,&__pyx_n_s_G,0}; + PyObject* values[5] = {0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq_i)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, 1); __PYX_ERR(0, 61, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq_i)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, 2); __PYX_ERR(0, 61, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 3: + if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, 3); __PYX_ERR(0, 61, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 4: + if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_G)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, 4); __PYX_ERR(0, 61, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "exchange_greens_function_per_qvec") < 0)) __PYX_ERR(0, 61, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + } + __pyx_v_kpq_i = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_kpq_i.memview)) __PYX_ERR(0, 61, __pyx_L3_error) + __pyx_v_kpq = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_kpq.memview)) __PYX_ERR(0, 61, __pyx_L3_error) + __pyx_v_pmq_i = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_pmq_i.memview)) __PYX_ERR(0, 61, __pyx_L3_error) + __pyx_v_pmq = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_pmq.memview)) __PYX_ERR(0, 61, __pyx_L3_error) + __pyx_v_G = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_G.memview)) __PYX_ERR(0, 61, __pyx_L3_error) + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 61, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("ueg_kernels.exchange_greens_function_per_qvec", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_11ueg_kernels_6exchange_greens_function_per_qvec(__pyx_self, __pyx_v_kpq_i, __pyx_v_kpq, __pyx_v_pmq_i, __pyx_v_pmq, __pyx_v_G); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_11ueg_kernels_6exchange_greens_function_per_qvec(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_kpq_i, __Pyx_memviewslice __pyx_v_kpq, __Pyx_memviewslice __pyx_v_pmq_i, __Pyx_memviewslice __pyx_v_pmq, __Pyx_memviewslice __pyx_v_G) { + int __pyx_v_nkpq; + int __pyx_v_npmq; + __pyx_t_double_complex __pyx_v_Gprod; + int __pyx_v_idxkpq; + int __pyx_v_idxpmq; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_v_inkpq; + int __pyx_v_jnpmq; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("exchange_greens_function_per_qvec", 0); + + /* "ueg_kernels.pyx":63 + * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): + * + * cdef int nkpq = kpq_i.shape[0] # <<<<<<<<<<<<<< + * cdef int npmq = pmq_i.shape[0] + * + */ + __pyx_v_nkpq = (__pyx_v_kpq_i.shape[0]); + + /* "ueg_kernels.pyx":64 + * + * cdef int nkpq = kpq_i.shape[0] + * cdef int npmq = pmq_i.shape[0] # <<<<<<<<<<<<<< + * + * cdef double complex Gprod = 0.0 + */ + __pyx_v_npmq = (__pyx_v_pmq_i.shape[0]); + + /* "ueg_kernels.pyx":66 + * cdef int npmq = pmq_i.shape[0] + * + * cdef double complex Gprod = 0.0 # <<<<<<<<<<<<<< + * + * cdef int idxkpq, idxpmq, i, j + */ + __pyx_v_Gprod = __pyx_t_double_complex_from_parts(0.0, 0); + + /* "ueg_kernels.pyx":70 + * cdef int idxkpq, idxpmq, i, j + * + * for inkpq in range(nkpq): # <<<<<<<<<<<<<< + * idxkpq = kpq[inkpq] + * i = kpq_i[inkpq] + */ + __pyx_t_1 = __pyx_v_nkpq; + __pyx_t_2 = __pyx_t_1; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_inkpq = __pyx_t_3; + + /* "ueg_kernels.pyx":71 + * + * for inkpq in range(nkpq): + * idxkpq = kpq[inkpq] # <<<<<<<<<<<<<< + * i = kpq_i[inkpq] + * for jnpmq in range(npmq): + */ + __pyx_t_4 = __pyx_v_inkpq; + __pyx_t_5 = -1; + if (__pyx_t_4 < 0) { + __pyx_t_4 += __pyx_v_kpq.shape[0]; + if (unlikely(__pyx_t_4 < 0)) __pyx_t_5 = 0; + } else if (unlikely(__pyx_t_4 >= __pyx_v_kpq.shape[0])) __pyx_t_5 = 0; + if (unlikely(__pyx_t_5 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_5); + __PYX_ERR(0, 71, __pyx_L1_error) + } + __pyx_v_idxkpq = (*((long *) ( /* dim=0 */ (__pyx_v_kpq.data + __pyx_t_4 * __pyx_v_kpq.strides[0]) ))); + + /* "ueg_kernels.pyx":72 + * for inkpq in range(nkpq): + * idxkpq = kpq[inkpq] + * i = kpq_i[inkpq] # <<<<<<<<<<<<<< + * for jnpmq in range(npmq): + * idxpmq = pmq[jnpmq] + */ + __pyx_t_4 = __pyx_v_inkpq; + __pyx_t_5 = -1; + if (__pyx_t_4 < 0) { + __pyx_t_4 += __pyx_v_kpq_i.shape[0]; + if (unlikely(__pyx_t_4 < 0)) __pyx_t_5 = 0; + } else if (unlikely(__pyx_t_4 >= __pyx_v_kpq_i.shape[0])) __pyx_t_5 = 0; + if (unlikely(__pyx_t_5 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_5); + __PYX_ERR(0, 72, __pyx_L1_error) + } + __pyx_v_i = (*((long *) ( /* dim=0 */ (__pyx_v_kpq_i.data + __pyx_t_4 * __pyx_v_kpq_i.strides[0]) ))); + + /* "ueg_kernels.pyx":73 + * idxkpq = kpq[inkpq] + * i = kpq_i[inkpq] + * for jnpmq in range(npmq): # <<<<<<<<<<<<<< + * idxpmq = pmq[jnpmq] + * j = pmq_i[jnpmq] + */ + __pyx_t_5 = __pyx_v_npmq; + __pyx_t_6 = __pyx_t_5; + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_jnpmq = __pyx_t_7; + + /* "ueg_kernels.pyx":74 + * i = kpq_i[inkpq] + * for jnpmq in range(npmq): + * idxpmq = pmq[jnpmq] # <<<<<<<<<<<<<< + * j = pmq_i[jnpmq] + * Gprod += G[j,idxkpq]*G[i,idxpmq] + */ + __pyx_t_4 = __pyx_v_jnpmq; + __pyx_t_8 = -1; + if (__pyx_t_4 < 0) { + __pyx_t_4 += __pyx_v_pmq.shape[0]; + if (unlikely(__pyx_t_4 < 0)) __pyx_t_8 = 0; + } else if (unlikely(__pyx_t_4 >= __pyx_v_pmq.shape[0])) __pyx_t_8 = 0; + if (unlikely(__pyx_t_8 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_8); + __PYX_ERR(0, 74, __pyx_L1_error) + } + __pyx_v_idxpmq = (*((long *) ( /* dim=0 */ (__pyx_v_pmq.data + __pyx_t_4 * __pyx_v_pmq.strides[0]) ))); + + /* "ueg_kernels.pyx":75 + * for jnpmq in range(npmq): + * idxpmq = pmq[jnpmq] + * j = pmq_i[jnpmq] # <<<<<<<<<<<<<< + * Gprod += G[j,idxkpq]*G[i,idxpmq] + * + */ + __pyx_t_4 = __pyx_v_jnpmq; + __pyx_t_8 = -1; + if (__pyx_t_4 < 0) { + __pyx_t_4 += __pyx_v_pmq_i.shape[0]; + if (unlikely(__pyx_t_4 < 0)) __pyx_t_8 = 0; + } else if (unlikely(__pyx_t_4 >= __pyx_v_pmq_i.shape[0])) __pyx_t_8 = 0; + if (unlikely(__pyx_t_8 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_8); + __PYX_ERR(0, 75, __pyx_L1_error) + } + __pyx_v_j = (*((long *) ( /* dim=0 */ (__pyx_v_pmq_i.data + __pyx_t_4 * __pyx_v_pmq_i.strides[0]) ))); + + /* "ueg_kernels.pyx":76 + * idxpmq = pmq[jnpmq] + * j = pmq_i[jnpmq] + * Gprod += G[j,idxkpq]*G[i,idxpmq] # <<<<<<<<<<<<<< + * + * return Gprod + */ + __pyx_t_4 = __pyx_v_j; + __pyx_t_9 = __pyx_v_idxkpq; + __pyx_t_8 = -1; + if (__pyx_t_4 < 0) { + __pyx_t_4 += __pyx_v_G.shape[0]; + if (unlikely(__pyx_t_4 < 0)) __pyx_t_8 = 0; + } else if (unlikely(__pyx_t_4 >= __pyx_v_G.shape[0])) __pyx_t_8 = 0; + if (__pyx_t_9 < 0) { + __pyx_t_9 += __pyx_v_G.shape[1]; + if (unlikely(__pyx_t_9 < 0)) __pyx_t_8 = 1; + } else if (unlikely(__pyx_t_9 >= __pyx_v_G.shape[1])) __pyx_t_8 = 1; + if (unlikely(__pyx_t_8 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_8); + __PYX_ERR(0, 76, __pyx_L1_error) + } + __pyx_t_10 = __pyx_v_i; + __pyx_t_11 = __pyx_v_idxpmq; + __pyx_t_8 = -1; + if (__pyx_t_10 < 0) { + __pyx_t_10 += __pyx_v_G.shape[0]; + if (unlikely(__pyx_t_10 < 0)) __pyx_t_8 = 0; + } else if (unlikely(__pyx_t_10 >= __pyx_v_G.shape[0])) __pyx_t_8 = 0; + if (__pyx_t_11 < 0) { + __pyx_t_11 += __pyx_v_G.shape[1]; + if (unlikely(__pyx_t_11 < 0)) __pyx_t_8 = 1; + } else if (unlikely(__pyx_t_11 >= __pyx_v_G.shape[1])) __pyx_t_8 = 1; + if (unlikely(__pyx_t_8 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_8); + __PYX_ERR(0, 76, __pyx_L1_error) + } + __pyx_v_Gprod = __Pyx_c_sum_double(__pyx_v_Gprod, __Pyx_c_prod_double((*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_4 * __pyx_v_G.strides[0]) ) + __pyx_t_9 * __pyx_v_G.strides[1]) ))), (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_10 * __pyx_v_G.strides[0]) ) + __pyx_t_11 * __pyx_v_G.strides[1]) ))))); + } + } + + /* "ueg_kernels.pyx":78 + * Gprod += G[j,idxkpq]*G[i,idxpmq] + * + * return Gprod # <<<<<<<<<<<<<< + * + * def exchange_greens_function_fft (long nocc, long nbsf, + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_12 = __pyx_PyComplex_FromComplex(__pyx_v_Gprod); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 78, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __pyx_r = __pyx_t_12; + __pyx_t_12 = 0; + goto __pyx_L0; + + /* "ueg_kernels.pyx":61 + * return Gkpq, Gpmq + * + * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): # <<<<<<<<<<<<<< + * + * cdef int nkpq = kpq_i.shape[0] + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("ueg_kernels.exchange_greens_function_per_qvec", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_kpq_i, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_kpq, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_pmq_i, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_pmq, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_G, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "ueg_kernels.pyx":80 + * return Gprod + * + * def exchange_greens_function_fft (long nocc, long nbsf, # <<<<<<<<<<<<<< + * long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, + * double complex[:,:] CTdagger, double complex[:,:] Ghalf): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_11ueg_kernels_9exchange_greens_function_fft(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_11ueg_kernels_9exchange_greens_function_fft = {"exchange_greens_function_fft", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_9exchange_greens_function_fft, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_11ueg_kernels_9exchange_greens_function_fft(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + long __pyx_v_nocc; + long __pyx_v_nbsf; + __Pyx_memviewslice __pyx_v_mesh = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_qmesh = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_gmap = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_qmap = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_CTdagger = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Ghalf = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("exchange_greens_function_fft (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_nocc,&__pyx_n_s_nbsf,&__pyx_n_s_mesh,&__pyx_n_s_qmesh,&__pyx_n_s_gmap,&__pyx_n_s_qmap,&__pyx_n_s_CTdagger,&__pyx_n_s_Ghalf,0}; + PyObject* values[8] = {0,0,0,0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + CYTHON_FALLTHROUGH; + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + CYTHON_FALLTHROUGH; + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + CYTHON_FALLTHROUGH; + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nocc)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nbsf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 1); __PYX_ERR(0, 80, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mesh)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 2); __PYX_ERR(0, 80, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 3: + if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_qmesh)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 3); __PYX_ERR(0, 80, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 4: + if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_gmap)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 4); __PYX_ERR(0, 80, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 5: + if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_qmap)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 5); __PYX_ERR(0, 80, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 6: + if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_CTdagger)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 6); __PYX_ERR(0, 80, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 7: + if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Ghalf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 7); __PYX_ERR(0, 80, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "exchange_greens_function_fft") < 0)) __PYX_ERR(0, 80, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 8) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + } + __pyx_v_nocc = __Pyx_PyInt_As_long(values[0]); if (unlikely((__pyx_v_nocc == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 80, __pyx_L3_error) + __pyx_v_nbsf = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v_nbsf == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 80, __pyx_L3_error) + __pyx_v_mesh = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_mesh.memview)) __PYX_ERR(0, 81, __pyx_L3_error) + __pyx_v_qmesh = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_qmesh.memview)) __PYX_ERR(0, 81, __pyx_L3_error) + __pyx_v_gmap = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_gmap.memview)) __PYX_ERR(0, 81, __pyx_L3_error) + __pyx_v_qmap = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[5], PyBUF_WRITABLE); if (unlikely(!__pyx_v_qmap.memview)) __PYX_ERR(0, 81, __pyx_L3_error) + __pyx_v_CTdagger = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[6], PyBUF_WRITABLE); if (unlikely(!__pyx_v_CTdagger.memview)) __PYX_ERR(0, 82, __pyx_L3_error) + __pyx_v_Ghalf = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[7], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Ghalf.memview)) __PYX_ERR(0, 82, __pyx_L3_error) + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 80, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("ueg_kernels.exchange_greens_function_fft", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_11ueg_kernels_8exchange_greens_function_fft(__pyx_self, __pyx_v_nocc, __pyx_v_nbsf, __pyx_v_mesh, __pyx_v_qmesh, __pyx_v_gmap, __pyx_v_qmap, __pyx_v_CTdagger, __pyx_v_Ghalf); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_11ueg_kernels_8exchange_greens_function_fft(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nocc, long __pyx_v_nbsf, __Pyx_memviewslice __pyx_v_mesh, __Pyx_memviewslice __pyx_v_qmesh, __Pyx_memviewslice __pyx_v_gmap, __Pyx_memviewslice __pyx_v_qmap, __Pyx_memviewslice __pyx_v_CTdagger, __Pyx_memviewslice __pyx_v_Ghalf) { + long __pyx_v_ngrid; + long __pyx_v_nqgrid; + long __pyx_v_nq; + PyArrayObject *__pyx_v_Gprod = 0; + PyArrayObject *__pyx_v_Gh_i = 0; + PyArrayObject *__pyx_v_CTdagger_j = 0; + PyArrayObject *__pyx_v_Gh_i_cube = 0; + PyArrayObject *__pyx_v_CTdagger_j_cube = 0; + PyArrayObject *__pyx_v_Gh_j = 0; + PyArrayObject *__pyx_v_CTdagger_i = 0; + PyArrayObject *__pyx_v_Gh_j_cube = 0; + PyArrayObject *__pyx_v_CTdagger_i_cube = 0; + PyArrayObject *__pyx_v_lQ_ji = 0; + PyArrayObject *__pyx_v_lQ_ij = 0; + long __pyx_v_i; + long __pyx_v_j; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + long __pyx_t_5; + long __pyx_t_6; + long __pyx_t_7; + long __pyx_t_8; + long __pyx_t_9; + long __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + __Pyx_memviewslice __pyx_t_12 = { 0, 0, { 0 }, { 0 }, { 0 } }; + PyObject *__pyx_t_13 = NULL; + int __pyx_t_14; + PyObject *__pyx_t_15 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("exchange_greens_function_fft", 0); + + /* "ueg_kernels.pyx":84 + * double complex[:,:] CTdagger, double complex[:,:] Ghalf): + * + * assert (mesh.shape[0] == 3) # <<<<<<<<<<<<<< + * assert (qmesh.shape[0] == 3) + * assert (Ghalf.shape[0] == nocc) + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_mesh.shape[0]) == 3) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + __PYX_ERR(0, 84, __pyx_L1_error) + } + } + #endif + + /* "ueg_kernels.pyx":85 + * + * assert (mesh.shape[0] == 3) + * assert (qmesh.shape[0] == 3) # <<<<<<<<<<<<<< + * assert (Ghalf.shape[0] == nocc) + * assert (Ghalf.shape[1] == nbsf) + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_qmesh.shape[0]) == 3) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + __PYX_ERR(0, 85, __pyx_L1_error) + } + } + #endif + + /* "ueg_kernels.pyx":86 + * assert (mesh.shape[0] == 3) + * assert (qmesh.shape[0] == 3) + * assert (Ghalf.shape[0] == nocc) # <<<<<<<<<<<<<< + * assert (Ghalf.shape[1] == nbsf) + * assert (CTdagger.shape[0] == nocc) + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_Ghalf.shape[0]) == __pyx_v_nocc) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + __PYX_ERR(0, 86, __pyx_L1_error) + } + } + #endif + + /* "ueg_kernels.pyx":87 + * assert (qmesh.shape[0] == 3) + * assert (Ghalf.shape[0] == nocc) + * assert (Ghalf.shape[1] == nbsf) # <<<<<<<<<<<<<< + * assert (CTdagger.shape[0] == nocc) + * assert (CTdagger.shape[1] == nbsf) + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_Ghalf.shape[1]) == __pyx_v_nbsf) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + __PYX_ERR(0, 87, __pyx_L1_error) + } + } + #endif + + /* "ueg_kernels.pyx":88 + * assert (Ghalf.shape[0] == nocc) + * assert (Ghalf.shape[1] == nbsf) + * assert (CTdagger.shape[0] == nocc) # <<<<<<<<<<<<<< + * assert (CTdagger.shape[1] == nbsf) + * + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_CTdagger.shape[0]) == __pyx_v_nocc) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + __PYX_ERR(0, 88, __pyx_L1_error) + } + } + #endif + + /* "ueg_kernels.pyx":89 + * assert (Ghalf.shape[1] == nbsf) + * assert (CTdagger.shape[0] == nocc) + * assert (CTdagger.shape[1] == nbsf) # <<<<<<<<<<<<<< + * + * cdef long ngrid = numpy.prod(mesh) + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!(((__pyx_v_CTdagger.shape[1]) == __pyx_v_nbsf) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + __PYX_ERR(0, 89, __pyx_L1_error) + } + } + #endif + + /* "ueg_kernels.pyx":91 + * assert (CTdagger.shape[1] == nbsf) + * + * cdef long ngrid = numpy.prod(mesh) # <<<<<<<<<<<<<< + * cdef long nqgrid = numpy.prod(qmesh) + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_prod); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_mesh, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = __Pyx_PyInt_As_long(__pyx_t_1); if (unlikely((__pyx_t_5 == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_ngrid = __pyx_t_5; + + /* "ueg_kernels.pyx":92 + * + * cdef long ngrid = numpy.prod(mesh) + * cdef long nqgrid = numpy.prod(qmesh) # <<<<<<<<<<<<<< + * + * cdef long nq = qmap.shape[0] + */ + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_numpy); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_prod); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_qmesh, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyInt_As_long(__pyx_t_1); if (unlikely((__pyx_t_5 == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_nqgrid = __pyx_t_5; + + /* "ueg_kernels.pyx":94 + * cdef long nqgrid = numpy.prod(qmesh) + * + * cdef long nq = qmap.shape[0] # <<<<<<<<<<<<<< + * cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) + * + */ + __pyx_v_nq = (__pyx_v_qmap.shape[0]); + + /* "ueg_kernels.pyx":95 + * + * cdef long nq = qmap.shape[0] + * cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * + * cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nq); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 95, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 95, __pyx_L1_error) + __pyx_v_Gprod = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "ueg_kernels.pyx":97 + * cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) + * + * cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 97, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 97, __pyx_L1_error) + __pyx_v_Gh_i = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":98 + * + * cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 98, __pyx_L1_error) + __pyx_v_CTdagger_j = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":99 + * cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 99, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 99, __pyx_L1_error) + __pyx_v_Gh_i_cube = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "ueg_kernels.pyx":100 + * cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * + * cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 100, __pyx_L1_error) + __pyx_v_CTdagger_j_cube = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":102 + * cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * + * cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 102, __pyx_L1_error) + __pyx_v_Gh_j = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":103 + * + * cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 103, __pyx_L1_error) + __pyx_v_CTdagger_i = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "ueg_kernels.pyx":104 + * cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 104, __pyx_L1_error) + __pyx_v_Gh_j_cube = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":105 + * cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + * cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * + * cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 105, __pyx_L1_error) + __pyx_v_CTdagger_i_cube = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":107 + * cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * + * cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nqgrid); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 107, __pyx_L1_error) + __pyx_v_lQ_ji = ((PyArrayObject *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "ueg_kernels.pyx":108 + * + * cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) + * cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * + * for i in range(nocc): + */ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_v_nqgrid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 108, __pyx_L1_error) + __pyx_v_lQ_ij = ((PyArrayObject *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":110 + * cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) + * + * for i in range(nocc): # <<<<<<<<<<<<<< + * for j in range(nocc): + * Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) + */ + __pyx_t_5 = __pyx_v_nocc; + __pyx_t_6 = __pyx_t_5; + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "ueg_kernels.pyx":111 + * + * for i in range(nocc): + * for j in range(nocc): # <<<<<<<<<<<<<< + * Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) + * CTdagger_j = numpy.asarray(CTdagger[j,:]) + */ + __pyx_t_8 = __pyx_v_nocc; + __pyx_t_9 = __pyx_t_8; + for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { + __pyx_v_j = __pyx_t_10; + + /* "ueg_kernels.pyx":112 + * for i in range(nocc): + * for j in range(nocc): + * Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) # <<<<<<<<<<<<<< + * CTdagger_j = numpy.asarray(CTdagger[j,:]) + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_flip); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_12.data = __pyx_v_Ghalf.data; + __pyx_t_12.memview = __pyx_v_Ghalf.memview; + __PYX_INC_MEMVIEW(&__pyx_t_12, 0); + { + Py_ssize_t __pyx_tmp_idx = __pyx_v_i; + Py_ssize_t __pyx_tmp_shape = __pyx_v_Ghalf.shape[0]; + Py_ssize_t __pyx_tmp_stride = __pyx_v_Ghalf.strides[0]; + if (__pyx_tmp_idx < 0) + __pyx_tmp_idx += __pyx_tmp_shape; + if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { + PyErr_SetString(PyExc_IndexError, + "Index out of bounds (axis 0)"); + __PYX_ERR(0, 112, __pyx_L1_error) + } + __pyx_t_12.data += __pyx_tmp_idx * __pyx_tmp_stride; +} + +__pyx_t_12.shape[0] = __pyx_v_Ghalf.shape[1]; +__pyx_t_12.strides[0] = __pyx_v_Ghalf.strides[1]; + __pyx_t_12.suboffsets[0] = -1; + +__pyx_t_1 = __pyx_memoryview_fromslice(__pyx_t_12, 1, (PyObject *(*)(char *)) __pyx_memview_get___pyx_t_double_complex, (int (*)(char *, PyObject *)) __pyx_memview_set___pyx_t_double_complex, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); + __pyx_t_12.memview = NULL; + __pyx_t_12.data = NULL; + __pyx_t_13 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_11))) { + __pyx_t_13 = PyMethod_GET_SELF(__pyx_t_11); + if (likely(__pyx_t_13)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_11); + __Pyx_INCREF(__pyx_t_13); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_11, function); + } + } + __pyx_t_4 = (__pyx_t_13) ? __Pyx_PyObject_Call2Args(__pyx_t_11, __pyx_t_13, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_11, __pyx_t_1); + __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_11 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_11)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_11); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + __pyx_t_2 = (__pyx_t_11) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_11, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_Gh_i, ((PyArrayObject *)__pyx_t_2)); + __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":113 + * for j in range(nocc): + * Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) + * CTdagger_j = numpy.asarray(CTdagger[j,:]) # <<<<<<<<<<<<<< + * + * Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_numpy); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_asarray); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_12.data = __pyx_v_CTdagger.data; + __pyx_t_12.memview = __pyx_v_CTdagger.memview; + __PYX_INC_MEMVIEW(&__pyx_t_12, 0); + { + Py_ssize_t __pyx_tmp_idx = __pyx_v_j; + Py_ssize_t __pyx_tmp_shape = __pyx_v_CTdagger.shape[0]; + Py_ssize_t __pyx_tmp_stride = __pyx_v_CTdagger.strides[0]; + if (__pyx_tmp_idx < 0) + __pyx_tmp_idx += __pyx_tmp_shape; + if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { + PyErr_SetString(PyExc_IndexError, + "Index out of bounds (axis 0)"); + __PYX_ERR(0, 113, __pyx_L1_error) + } + __pyx_t_12.data += __pyx_tmp_idx * __pyx_tmp_stride; +} + +__pyx_t_12.shape[0] = __pyx_v_CTdagger.shape[1]; +__pyx_t_12.strides[0] = __pyx_v_CTdagger.strides[1]; + __pyx_t_12.suboffsets[0] = -1; + +__pyx_t_3 = __pyx_memoryview_fromslice(__pyx_t_12, 1, (PyObject *(*)(char *)) __pyx_memview_get___pyx_t_double_complex, (int (*)(char *, PyObject *)) __pyx_memview_set___pyx_t_double_complex, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); + __pyx_t_12.memview = NULL; + __pyx_t_12.data = NULL; + __pyx_t_11 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_11)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_11); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + __pyx_t_2 = (__pyx_t_11) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_11, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_CTdagger_j, ((PyArrayObject *)__pyx_t_2)); + __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":115 + * CTdagger_j = numpy.asarray(CTdagger[j,:]) + * + * Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_11) < 0) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_Gh_i_cube, ((PyArrayObject *)__pyx_t_11)); + __pyx_t_11 = 0; + + /* "ueg_kernels.pyx":116 + * + * Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * + * Gh_i_cube[gmap] = Gh_i + */ + __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_numpy); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_11, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_11 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_11 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_11, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_11); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_CTdagger_j_cube, ((PyArrayObject *)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "ueg_kernels.pyx":118 + * CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * + * Gh_i_cube[gmap] = Gh_i # <<<<<<<<<<<<<< + * CTdagger_j_cube[gmap] = CTdagger_j + * + */ + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_gmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 118, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_Gh_i_cube), __pyx_t_4, ((PyObject *)__pyx_v_Gh_i)) < 0)) __PYX_ERR(0, 118, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "ueg_kernels.pyx":119 + * + * Gh_i_cube[gmap] = Gh_i + * CTdagger_j_cube[gmap] = CTdagger_j # <<<<<<<<<<<<<< + * + * lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] + */ + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_gmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 119, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_CTdagger_j_cube), __pyx_t_4, ((PyObject *)__pyx_v_CTdagger_j)) < 0)) __PYX_ERR(0, 119, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "ueg_kernels.pyx":121 + * CTdagger_j_cube[gmap] = CTdagger_j + * + * lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] # <<<<<<<<<<<<<< + * + * Gh_j = numpy.asarray(Ghalf[j,:]) + */ + __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_numpy); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_11, __pyx_n_s_flip); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_convolve); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_mesh, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_13 = NULL; + __pyx_t_14 = 0; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_13 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_13)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_13); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_14 = 1; + } + } + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_2)) { + PyObject *__pyx_temp[4] = {__pyx_t_13, ((PyObject *)__pyx_v_CTdagger_j_cube), ((PyObject *)__pyx_v_Gh_i_cube), __pyx_t_1}; + __pyx_t_11 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_14, 3+__pyx_t_14); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { + PyObject *__pyx_temp[4] = {__pyx_t_13, ((PyObject *)__pyx_v_CTdagger_j_cube), ((PyObject *)__pyx_v_Gh_i_cube), __pyx_t_1}; + __pyx_t_11 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_14, 3+__pyx_t_14); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else + #endif + { + __pyx_t_15 = PyTuple_New(3+__pyx_t_14); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + if (__pyx_t_13) { + __Pyx_GIVEREF(__pyx_t_13); PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_13); __pyx_t_13 = NULL; + } + __Pyx_INCREF(((PyObject *)__pyx_v_CTdagger_j_cube)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_CTdagger_j_cube)); + PyTuple_SET_ITEM(__pyx_t_15, 0+__pyx_t_14, ((PyObject *)__pyx_v_CTdagger_j_cube)); + __Pyx_INCREF(((PyObject *)__pyx_v_Gh_i_cube)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_Gh_i_cube)); + PyTuple_SET_ITEM(__pyx_t_15, 1+__pyx_t_14, ((PyObject *)__pyx_v_Gh_i_cube)); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_15, 2+__pyx_t_14, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_15, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + __pyx_t_4 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_11) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_11); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_qmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_11 = __Pyx_PyObject_GetItem(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_lQ_ji, ((PyArrayObject *)__pyx_t_11)); + __pyx_t_11 = 0; + + /* "ueg_kernels.pyx":123 + * lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] + * + * Gh_j = numpy.asarray(Ghalf[j,:]) # <<<<<<<<<<<<<< + * CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_numpy); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 123, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_asarray); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 123, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_12.data = __pyx_v_Ghalf.data; + __pyx_t_12.memview = __pyx_v_Ghalf.memview; + __PYX_INC_MEMVIEW(&__pyx_t_12, 0); + { + Py_ssize_t __pyx_tmp_idx = __pyx_v_j; + Py_ssize_t __pyx_tmp_shape = __pyx_v_Ghalf.shape[0]; + Py_ssize_t __pyx_tmp_stride = __pyx_v_Ghalf.strides[0]; + if (__pyx_tmp_idx < 0) + __pyx_tmp_idx += __pyx_tmp_shape; + if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { + PyErr_SetString(PyExc_IndexError, + "Index out of bounds (axis 0)"); + __PYX_ERR(0, 123, __pyx_L1_error) + } + __pyx_t_12.data += __pyx_tmp_idx * __pyx_tmp_stride; +} + +__pyx_t_12.shape[0] = __pyx_v_Ghalf.shape[1]; +__pyx_t_12.strides[0] = __pyx_v_Ghalf.strides[1]; + __pyx_t_12.suboffsets[0] = -1; + +__pyx_t_3 = __pyx_memoryview_fromslice(__pyx_t_12, 1, (PyObject *(*)(char *)) __pyx_memview_get___pyx_t_double_complex, (int (*)(char *, PyObject *)) __pyx_memview_set___pyx_t_double_complex, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 123, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); + __pyx_t_12.memview = NULL; + __pyx_t_12.data = NULL; + __pyx_t_2 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + __pyx_t_11 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 123, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 123, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_Gh_j, ((PyArrayObject *)__pyx_t_11)); + __pyx_t_11 = 0; + + /* "ueg_kernels.pyx":124 + * + * Gh_j = numpy.asarray(Ghalf[j,:]) + * CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) # <<<<<<<<<<<<<< + * + * Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + */ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_flip); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_15 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_asarray); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_12.data = __pyx_v_CTdagger.data; + __pyx_t_12.memview = __pyx_v_CTdagger.memview; + __PYX_INC_MEMVIEW(&__pyx_t_12, 0); + { + Py_ssize_t __pyx_tmp_idx = __pyx_v_i; + Py_ssize_t __pyx_tmp_shape = __pyx_v_CTdagger.shape[0]; + Py_ssize_t __pyx_tmp_stride = __pyx_v_CTdagger.strides[0]; + if (__pyx_tmp_idx < 0) + __pyx_tmp_idx += __pyx_tmp_shape; + if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { + PyErr_SetString(PyExc_IndexError, + "Index out of bounds (axis 0)"); + __PYX_ERR(0, 124, __pyx_L1_error) + } + __pyx_t_12.data += __pyx_tmp_idx * __pyx_tmp_stride; +} + +__pyx_t_12.shape[0] = __pyx_v_CTdagger.shape[1]; +__pyx_t_12.strides[0] = __pyx_v_CTdagger.strides[1]; + __pyx_t_12.suboffsets[0] = -1; + +__pyx_t_2 = __pyx_memoryview_fromslice(__pyx_t_12, 1, (PyObject *(*)(char *)) __pyx_memview_get___pyx_t_double_complex, (int (*)(char *, PyObject *)) __pyx_memview_set___pyx_t_double_complex, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); + __pyx_t_12.memview = NULL; + __pyx_t_12.data = NULL; + __pyx_t_1 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_15))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_15); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_15); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_15, function); + } + } + __pyx_t_4 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_15, __pyx_t_1, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_15, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_15)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_15); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + __pyx_t_11 = (__pyx_t_15) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_15, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); + __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_CTdagger_i, ((PyArrayObject *)__pyx_t_11)); + __pyx_t_11 = 0; + + /* "ueg_kernels.pyx":126 + * CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) + * + * Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_numpy); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_11, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_11 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_11 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_GetModuleGlobalName(__pyx_t_15, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + if (PyDict_SetItem(__pyx_t_11, __pyx_n_s_dtype, __pyx_t_15) < 0) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_11); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (!(likely(((__pyx_t_15) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_15, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 126, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_Gh_j_cube, ((PyArrayObject *)__pyx_t_15)); + __pyx_t_15 = 0; + + /* "ueg_kernels.pyx":127 + * + * Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * + * Gh_j_cube[gmap] = Gh_j + */ + __Pyx_GetModuleGlobalName(__pyx_t_15, __pyx_n_s_numpy); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_15, __pyx_n_s_zeros); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_15); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_15); + __pyx_t_15 = 0; + __pyx_t_15 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_15, __pyx_n_s_dtype, __pyx_t_3) < 0) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_11, __pyx_t_4, __pyx_t_15); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_CTdagger_i_cube, ((PyArrayObject *)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":129 + * CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + * + * Gh_j_cube[gmap] = Gh_j # <<<<<<<<<<<<<< + * CTdagger_i_cube[gmap] = CTdagger_i + * + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_gmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_Gh_j_cube), __pyx_t_3, ((PyObject *)__pyx_v_Gh_j)) < 0)) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":130 + * + * Gh_j_cube[gmap] = Gh_j + * CTdagger_i_cube[gmap] = CTdagger_i # <<<<<<<<<<<<<< + * + * lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_gmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_CTdagger_i_cube), __pyx_t_3, ((PyObject *)__pyx_v_CTdagger_i)) < 0)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":132 + * CTdagger_i_cube[gmap] = CTdagger_i + * + * lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] # <<<<<<<<<<<<<< + * + * Gprod += lQ_ji*lQ_ij + */ + __Pyx_GetModuleGlobalName(__pyx_t_15, __pyx_n_s_numpy); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_15, __pyx_n_s_flip); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_convolve); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_mesh, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = NULL; + __pyx_t_14 = 0; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_11))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_11); + if (likely(__pyx_t_1)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_11); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_11, function); + __pyx_t_14 = 1; + } + } + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_11)) { + PyObject *__pyx_temp[4] = {__pyx_t_1, ((PyObject *)__pyx_v_Gh_j_cube), ((PyObject *)__pyx_v_CTdagger_i_cube), __pyx_t_2}; + __pyx_t_15 = __Pyx_PyFunction_FastCall(__pyx_t_11, __pyx_temp+1-__pyx_t_14, 3+__pyx_t_14); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_11)) { + PyObject *__pyx_temp[4] = {__pyx_t_1, ((PyObject *)__pyx_v_Gh_j_cube), ((PyObject *)__pyx_v_CTdagger_i_cube), __pyx_t_2}; + __pyx_t_15 = __Pyx_PyCFunction_FastCall(__pyx_t_11, __pyx_temp+1-__pyx_t_14, 3+__pyx_t_14); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else + #endif + { + __pyx_t_13 = PyTuple_New(3+__pyx_t_14); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + if (__pyx_t_1) { + __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_13, 0, __pyx_t_1); __pyx_t_1 = NULL; + } + __Pyx_INCREF(((PyObject *)__pyx_v_Gh_j_cube)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_Gh_j_cube)); + PyTuple_SET_ITEM(__pyx_t_13, 0+__pyx_t_14, ((PyObject *)__pyx_v_Gh_j_cube)); + __Pyx_INCREF(((PyObject *)__pyx_v_CTdagger_i_cube)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_CTdagger_i_cube)); + PyTuple_SET_ITEM(__pyx_t_13, 1+__pyx_t_14, ((PyObject *)__pyx_v_CTdagger_i_cube)); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_13, 2+__pyx_t_14, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_15 = __Pyx_PyObject_Call(__pyx_t_11, __pyx_t_13, NULL); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + } + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_11 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_11)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_11); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + __pyx_t_3 = (__pyx_t_11) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_11, __pyx_t_15) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_15); + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_qmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_15 = __Pyx_PyObject_GetItem(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_15) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_15, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_lQ_ij, ((PyArrayObject *)__pyx_t_15)); + __pyx_t_15 = 0; + + /* "ueg_kernels.pyx":134 + * lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] + * + * Gprod += lQ_ji*lQ_ij # <<<<<<<<<<<<<< + * + * return Gprod + */ + __pyx_t_15 = PyNumber_Multiply(((PyObject *)__pyx_v_lQ_ji), ((PyObject *)__pyx_v_lQ_ij)); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_4 = PyNumber_InPlaceAdd(((PyObject *)__pyx_v_Gprod), __pyx_t_15); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_DECREF_SET(__pyx_v_Gprod, ((PyArrayObject *)__pyx_t_4)); + __pyx_t_4 = 0; + } + } + + /* "ueg_kernels.pyx":136 + * Gprod += lQ_ji*lQ_ij + * + * return Gprod # <<<<<<<<<<<<<< + * + * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_Gprod)); + __pyx_r = ((PyObject *)__pyx_v_Gprod); + goto __pyx_L0; + + /* "ueg_kernels.pyx":80 + * return Gprod + * + * def exchange_greens_function_fft (long nocc, long nbsf, # <<<<<<<<<<<<<< + * long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, + * double complex[:,:] CTdagger, double complex[:,:] Ghalf): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_11); + __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); + __Pyx_XDECREF(__pyx_t_13); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_AddTraceback("ueg_kernels.exchange_greens_function_fft", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_Gprod); + __Pyx_XDECREF((PyObject *)__pyx_v_Gh_i); + __Pyx_XDECREF((PyObject *)__pyx_v_CTdagger_j); + __Pyx_XDECREF((PyObject *)__pyx_v_Gh_i_cube); + __Pyx_XDECREF((PyObject *)__pyx_v_CTdagger_j_cube); + __Pyx_XDECREF((PyObject *)__pyx_v_Gh_j); + __Pyx_XDECREF((PyObject *)__pyx_v_CTdagger_i); + __Pyx_XDECREF((PyObject *)__pyx_v_Gh_j_cube); + __Pyx_XDECREF((PyObject *)__pyx_v_CTdagger_i_cube); + __Pyx_XDECREF((PyObject *)__pyx_v_lQ_ji); + __Pyx_XDECREF((PyObject *)__pyx_v_lQ_ij); + __PYX_XDEC_MEMVIEW(&__pyx_v_mesh, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_qmesh, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_gmap, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_qmap, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_CTdagger, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Ghalf, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "ueg_kernels.pyx":138 + * return Gprod + * + * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< + * list kpq, list pmq_i, list pmq, + * double complex[:,:] Gkpq, double complex[:,:] Gpmq): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_11ueg_kernels_11build_J_opt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_11ueg_kernels_11build_J_opt = {"build_J_opt", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_11build_J_opt, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_11ueg_kernels_11build_J_opt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + long __pyx_v_nq; + __Pyx_memviewslice __pyx_v_vqvec = { 0, 0, { 0 }, { 0 }, { 0 } }; + double __pyx_v_vol; + long __pyx_v_nbsf; + PyObject *__pyx_v_kpq_i = 0; + PyObject *__pyx_v_kpq = 0; + PyObject *__pyx_v_pmq_i = 0; + PyObject *__pyx_v_pmq = 0; + __Pyx_memviewslice __pyx_v_Gkpq = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_memviewslice __pyx_v_Gpmq = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("build_J_opt (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_nq,&__pyx_n_s_vqvec,&__pyx_n_s_vol,&__pyx_n_s_nbsf,&__pyx_n_s_kpq_i,&__pyx_n_s_kpq,&__pyx_n_s_pmq_i,&__pyx_n_s_pmq,&__pyx_n_s_Gkpq,&__pyx_n_s_Gpmq,0}; + PyObject* values[10] = {0,0,0,0,0,0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + CYTHON_FALLTHROUGH; + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + CYTHON_FALLTHROUGH; + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + CYTHON_FALLTHROUGH; + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + CYTHON_FALLTHROUGH; + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + CYTHON_FALLTHROUGH; + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nq)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vqvec)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 1); __PYX_ERR(0, 138, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vol)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 2); __PYX_ERR(0, 138, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 3: + if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nbsf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 3); __PYX_ERR(0, 138, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 4: + if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq_i)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 4); __PYX_ERR(0, 138, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 5: + if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 5); __PYX_ERR(0, 138, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 6: + if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq_i)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 6); __PYX_ERR(0, 138, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 7: + if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 7); __PYX_ERR(0, 138, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 8: + if (likely((values[8] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Gkpq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 8); __PYX_ERR(0, 138, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 9: + if (likely((values[9] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Gpmq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 9); __PYX_ERR(0, 138, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "build_J_opt") < 0)) __PYX_ERR(0, 138, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 10) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + values[9] = PyTuple_GET_ITEM(__pyx_args, 9); + } + __pyx_v_nq = __Pyx_PyInt_As_long(values[0]); if (unlikely((__pyx_v_nq == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 138, __pyx_L3_error) + __pyx_v_vqvec = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_vqvec.memview)) __PYX_ERR(0, 138, __pyx_L3_error) + __pyx_v_vol = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_vol == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 138, __pyx_L3_error) + __pyx_v_nbsf = __Pyx_PyInt_As_long(values[3]); if (unlikely((__pyx_v_nbsf == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 138, __pyx_L3_error) + __pyx_v_kpq_i = ((PyObject*)values[4]); + __pyx_v_kpq = ((PyObject*)values[5]); + __pyx_v_pmq_i = ((PyObject*)values[6]); + __pyx_v_pmq = ((PyObject*)values[7]); + __pyx_v_Gkpq = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[8], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Gkpq.memview)) __PYX_ERR(0, 140, __pyx_L3_error) + __pyx_v_Gpmq = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[9], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Gpmq.memview)) __PYX_ERR(0, 140, __pyx_L3_error) + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 138, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("ueg_kernels.build_J_opt", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq_i), (&PyList_Type), 1, "kpq_i", 1))) __PYX_ERR(0, 138, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq), (&PyList_Type), 1, "kpq", 1))) __PYX_ERR(0, 139, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq_i), (&PyList_Type), 1, "pmq_i", 1))) __PYX_ERR(0, 139, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq), (&PyList_Type), 1, "pmq", 1))) __PYX_ERR(0, 139, __pyx_L1_error) + __pyx_r = __pyx_pf_11ueg_kernels_10build_J_opt(__pyx_self, __pyx_v_nq, __pyx_v_vqvec, __pyx_v_vol, __pyx_v_nbsf, __pyx_v_kpq_i, __pyx_v_kpq, __pyx_v_pmq_i, __pyx_v_pmq, __pyx_v_Gkpq, __pyx_v_Gpmq); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_11ueg_kernels_10build_J_opt(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nq, __Pyx_memviewslice __pyx_v_vqvec, double __pyx_v_vol, long __pyx_v_nbsf, PyObject *__pyx_v_kpq_i, PyObject *__pyx_v_kpq, PyObject *__pyx_v_pmq_i, PyObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_Gkpq, __Pyx_memviewslice __pyx_v_Gpmq) { + PyArrayObject *__pyx_v_J = 0; + int __pyx_v_i; + int __pyx_v_j; + long __pyx_v_iq; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + long __pyx_t_5; + long __pyx_t_6; + long __pyx_t_7; + Py_ssize_t __pyx_t_8; + PyObject *(*__pyx_t_9)(PyObject *); + PyObject *__pyx_t_10 = NULL; + PyObject *(*__pyx_t_11)(PyObject *); + int __pyx_t_12; + int __pyx_t_13; + double __pyx_t_14; + Py_ssize_t __pyx_t_15; + Py_ssize_t __pyx_t_16; + Py_ssize_t __pyx_t_17; + Py_ssize_t __pyx_t_18; + Py_ssize_t __pyx_t_19; + __pyx_t_double_complex __pyx_t_20; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("build_J_opt", 0); + + /* "ueg_kernels.pyx":142 + * double complex[:,:] Gkpq, double complex[:,:] Gpmq): + * + * cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef int i, j + * for iq in range(nq): + */ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyList_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_int_2); + __Pyx_GIVEREF(__pyx_int_2); + PyList_SET_ITEM(__pyx_t_4, 0, __pyx_int_2); + __Pyx_GIVEREF(__pyx_t_1); + PyList_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 142, __pyx_L1_error) + __pyx_v_J = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":144 + * cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) + * cdef int i, j + * for iq in range(nq): # <<<<<<<<<<<<<< + * for i, j in zip(pmq_i[iq], pmq[iq]): + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + */ + __pyx_t_5 = __pyx_v_nq; + __pyx_t_6 = __pyx_t_5; + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_iq = __pyx_t_7; + + /* "ueg_kernels.pyx":145 + * cdef int i, j + * for iq in range(nq): + * for i, j in zip(pmq_i[iq], pmq[iq]): # <<<<<<<<<<<<<< + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + * for i, j in zip(kpq_i[iq], kpq[iq]): + */ + if (unlikely(__pyx_v_pmq_i == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 145, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_pmq_i, __pyx_v_iq, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(__pyx_v_pmq == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 145, __pyx_L1_error) + } + __pyx_t_4 = __Pyx_GetItemInt_List(__pyx_v_pmq, __pyx_v_iq, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); + __pyx_t_1 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (likely(PyList_CheckExact(__pyx_t_4)) || PyTuple_CheckExact(__pyx_t_4)) { + __pyx_t_3 = __pyx_t_4; __Pyx_INCREF(__pyx_t_3); __pyx_t_8 = 0; + __pyx_t_9 = NULL; + } else { + __pyx_t_8 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 145, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + for (;;) { + if (likely(!__pyx_t_9)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + if (__pyx_t_8 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_8); __Pyx_INCREF(__pyx_t_4); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 145, __pyx_L1_error) + #else + __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + if (__pyx_t_8 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_8); __Pyx_INCREF(__pyx_t_4); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 145, __pyx_L1_error) + #else + __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + } + } else { + __pyx_t_4 = __pyx_t_9(__pyx_t_3); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 145, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_4); + } + if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { + PyObject* sequence = __pyx_t_4; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 145, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_1 = PyList_GET_ITEM(sequence, 0); + __pyx_t_2 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_2); + #else + __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_10 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_11 = Py_TYPE(__pyx_t_10)->tp_iternext; + index = 0; __pyx_t_1 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_2 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_11(__pyx_t_10), 2) < 0) __PYX_ERR(0, 145, __pyx_L1_error) + __pyx_t_11 = NULL; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + goto __pyx_L8_unpacking_done; + __pyx_L7_unpacking_failed:; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_11 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 145, __pyx_L1_error) + __pyx_L8_unpacking_done:; + } + __pyx_t_12 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_12 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 145, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_i = __pyx_t_12; + __pyx_v_j = __pyx_t_13; + + /* "ueg_kernels.pyx":146 + * for iq in range(nq): + * for i, j in zip(pmq_i[iq], pmq[iq]): + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) # <<<<<<<<<<<<<< + * for i, j in zip(kpq_i[iq], kpq[iq]): + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + */ + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_j); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_int_0); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_2); + __pyx_t_4 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_J), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_14 = (2.0 * __pyx_v_vol); + if (unlikely(__pyx_t_14 == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + __PYX_ERR(0, 146, __pyx_L1_error) + } + __pyx_t_15 = __pyx_v_iq; + __pyx_t_13 = -1; + if (__pyx_t_15 < 0) { + __pyx_t_15 += __pyx_v_vqvec.shape[0]; + if (unlikely(__pyx_t_15 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_15 >= __pyx_v_vqvec.shape[0])) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + __PYX_ERR(0, 146, __pyx_L1_error) + } + __pyx_t_16 = 0; + __pyx_t_17 = __pyx_v_iq; + __pyx_t_13 = -1; + if (__pyx_t_16 < 0) { + __pyx_t_16 += __pyx_v_Gpmq.shape[0]; + if (unlikely(__pyx_t_16 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_16 >= __pyx_v_Gpmq.shape[0])) __pyx_t_13 = 0; + if (__pyx_t_17 < 0) { + __pyx_t_17 += __pyx_v_Gpmq.shape[1]; + if (unlikely(__pyx_t_17 < 0)) __pyx_t_13 = 1; + } else if (unlikely(__pyx_t_17 >= __pyx_v_Gpmq.shape[1])) __pyx_t_13 = 1; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + __PYX_ERR(0, 146, __pyx_L1_error) + } + __pyx_t_18 = 1; + __pyx_t_19 = __pyx_v_iq; + __pyx_t_13 = -1; + if (__pyx_t_18 < 0) { + __pyx_t_18 += __pyx_v_Gpmq.shape[0]; + if (unlikely(__pyx_t_18 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_18 >= __pyx_v_Gpmq.shape[0])) __pyx_t_13 = 0; + if (__pyx_t_19 < 0) { + __pyx_t_19 += __pyx_v_Gpmq.shape[1]; + if (unlikely(__pyx_t_19 < 0)) __pyx_t_13 = 1; + } else if (unlikely(__pyx_t_19 >= __pyx_v_Gpmq.shape[1])) __pyx_t_13 = 1; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + __PYX_ERR(0, 146, __pyx_L1_error) + } + __pyx_t_20 = __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(((1.0 / __pyx_t_14) * (*((double *) ( /* dim=0 */ (__pyx_v_vqvec.data + __pyx_t_15 * __pyx_v_vqvec.strides[0]) )))), 0), __Pyx_c_sum_double((*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Gpmq.data + __pyx_t_16 * __pyx_v_Gpmq.strides[0]) ) + __pyx_t_17 * __pyx_v_Gpmq.strides[1]) ))), (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Gpmq.data + __pyx_t_18 * __pyx_v_Gpmq.strides[0]) ) + __pyx_t_19 * __pyx_v_Gpmq.strides[1]) ))))); + __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_t_20); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_10 = PyNumber_InPlaceAdd(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_J), __pyx_t_1, __pyx_t_10) < 0)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":145 + * cdef int i, j + * for iq in range(nq): + * for i, j in zip(pmq_i[iq], pmq[iq]): # <<<<<<<<<<<<<< + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + * for i, j in zip(kpq_i[iq], kpq[iq]): + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":147 + * for i, j in zip(pmq_i[iq], pmq[iq]): + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + * for i, j in zip(kpq_i[iq], kpq[iq]): # <<<<<<<<<<<<<< + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + * + */ + if (unlikely(__pyx_v_kpq_i == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 147, __pyx_L1_error) + } + __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_kpq_i, __pyx_v_iq, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (unlikely(__pyx_v_kpq == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 147, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_kpq, __pyx_v_iq, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_1); + __pyx_t_3 = 0; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_10, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_10 = __pyx_t_1; __Pyx_INCREF(__pyx_t_10); __pyx_t_8 = 0; + __pyx_t_9 = NULL; + } else { + __pyx_t_8 = -1; __pyx_t_10 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_9 = Py_TYPE(__pyx_t_10)->tp_iternext; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 147, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (likely(!__pyx_t_9)) { + if (likely(PyList_CheckExact(__pyx_t_10))) { + if (__pyx_t_8 >= PyList_GET_SIZE(__pyx_t_10)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = PyList_GET_ITEM(__pyx_t_10, __pyx_t_8); __Pyx_INCREF(__pyx_t_1); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 147, __pyx_L1_error) + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_10, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + #endif + } else { + if (__pyx_t_8 >= PyTuple_GET_SIZE(__pyx_t_10)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_10, __pyx_t_8); __Pyx_INCREF(__pyx_t_1); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 147, __pyx_L1_error) + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_10, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + #endif + } + } else { + __pyx_t_1 = __pyx_t_9(__pyx_t_10); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 147, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 147, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_3 = PyList_GET_ITEM(sequence, 0); + __pyx_t_4 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_11 = Py_TYPE(__pyx_t_2)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_11(__pyx_t_2); if (unlikely(!__pyx_t_3)) goto __pyx_L11_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_4 = __pyx_t_11(__pyx_t_2); if (unlikely(!__pyx_t_4)) goto __pyx_L11_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_11(__pyx_t_2), 2) < 0) __PYX_ERR(0, 147, __pyx_L1_error) + __pyx_t_11 = NULL; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L12_unpacking_done; + __pyx_L11_unpacking_failed:; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_11 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 147, __pyx_L1_error) + __pyx_L12_unpacking_done:; + } + __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_12 = __Pyx_PyInt_As_int(__pyx_t_4); if (unlikely((__pyx_t_12 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_i = __pyx_t_13; + __pyx_v_j = __pyx_t_12; + + /* "ueg_kernels.pyx":148 + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + * for i, j in zip(kpq_i[iq], kpq[iq]): + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) # <<<<<<<<<<<<<< + * + * J[1] = J[0] + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_j); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_0); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_4); + __pyx_t_1 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_J), __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_14 = (2.0 * __pyx_v_vol); + if (unlikely(__pyx_t_14 == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + __PYX_ERR(0, 148, __pyx_L1_error) + } + __pyx_t_19 = __pyx_v_iq; + __pyx_t_12 = -1; + if (__pyx_t_19 < 0) { + __pyx_t_19 += __pyx_v_vqvec.shape[0]; + if (unlikely(__pyx_t_19 < 0)) __pyx_t_12 = 0; + } else if (unlikely(__pyx_t_19 >= __pyx_v_vqvec.shape[0])) __pyx_t_12 = 0; + if (unlikely(__pyx_t_12 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_12); + __PYX_ERR(0, 148, __pyx_L1_error) + } + __pyx_t_18 = 0; + __pyx_t_17 = __pyx_v_iq; + __pyx_t_12 = -1; + if (__pyx_t_18 < 0) { + __pyx_t_18 += __pyx_v_Gkpq.shape[0]; + if (unlikely(__pyx_t_18 < 0)) __pyx_t_12 = 0; + } else if (unlikely(__pyx_t_18 >= __pyx_v_Gkpq.shape[0])) __pyx_t_12 = 0; + if (__pyx_t_17 < 0) { + __pyx_t_17 += __pyx_v_Gkpq.shape[1]; + if (unlikely(__pyx_t_17 < 0)) __pyx_t_12 = 1; + } else if (unlikely(__pyx_t_17 >= __pyx_v_Gkpq.shape[1])) __pyx_t_12 = 1; + if (unlikely(__pyx_t_12 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_12); + __PYX_ERR(0, 148, __pyx_L1_error) + } + __pyx_t_16 = 1; + __pyx_t_15 = __pyx_v_iq; + __pyx_t_12 = -1; + if (__pyx_t_16 < 0) { + __pyx_t_16 += __pyx_v_Gkpq.shape[0]; + if (unlikely(__pyx_t_16 < 0)) __pyx_t_12 = 0; + } else if (unlikely(__pyx_t_16 >= __pyx_v_Gkpq.shape[0])) __pyx_t_12 = 0; + if (__pyx_t_15 < 0) { + __pyx_t_15 += __pyx_v_Gkpq.shape[1]; + if (unlikely(__pyx_t_15 < 0)) __pyx_t_12 = 1; + } else if (unlikely(__pyx_t_15 >= __pyx_v_Gkpq.shape[1])) __pyx_t_12 = 1; + if (unlikely(__pyx_t_12 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_12); + __PYX_ERR(0, 148, __pyx_L1_error) + } + __pyx_t_20 = __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(((1.0 / __pyx_t_14) * (*((double *) ( /* dim=0 */ (__pyx_v_vqvec.data + __pyx_t_19 * __pyx_v_vqvec.strides[0]) )))), 0), __Pyx_c_sum_double((*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Gkpq.data + __pyx_t_18 * __pyx_v_Gkpq.strides[0]) ) + __pyx_t_17 * __pyx_v_Gkpq.strides[1]) ))), (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Gkpq.data + __pyx_t_16 * __pyx_v_Gkpq.strides[0]) ) + __pyx_t_15 * __pyx_v_Gkpq.strides[1]) ))))); + __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_t_20); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_J), __pyx_t_3, __pyx_t_2) < 0)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":147 + * for i, j in zip(pmq_i[iq], pmq[iq]): + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + * for i, j in zip(kpq_i[iq], kpq[iq]): # <<<<<<<<<<<<<< + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + * + */ + } + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + + /* "ueg_kernels.pyx":150 + * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + * + * J[1] = J[0] # <<<<<<<<<<<<<< + * + * return J + */ + __pyx_t_10 = __Pyx_GetItemInt(((PyObject *)__pyx_v_J), 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + if (unlikely(__Pyx_SetItemInt(((PyObject *)__pyx_v_J), 1, __pyx_t_10, long, 1, __Pyx_PyInt_From_long, 0, 0, 1) < 0)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "ueg_kernels.pyx":152 + * J[1] = J[0] + * + * return J # <<<<<<<<<<<<<< + * + * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_J)); + __pyx_r = ((PyObject *)__pyx_v_J); + goto __pyx_L0; + + /* "ueg_kernels.pyx":138 + * return Gprod + * + * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< + * list kpq, list pmq_i, list pmq, + * double complex[:,:] Gkpq, double complex[:,:] Gpmq): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("ueg_kernels.build_J_opt", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_J); + __PYX_XDEC_MEMVIEW(&__pyx_v_vqvec, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Gkpq, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Gpmq, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "ueg_kernels.pyx":154 + * return J + * + * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< + * list kpq, list pmq_i, list pmq, + * double complex[:,:,:] G): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_11ueg_kernels_13build_K_opt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_11ueg_kernels_13build_K_opt = {"build_K_opt", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_13build_K_opt, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_11ueg_kernels_13build_K_opt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + long __pyx_v_nq; + __Pyx_memviewslice __pyx_v_vqvec = { 0, 0, { 0 }, { 0 }, { 0 } }; + double __pyx_v_vol; + long __pyx_v_nbsf; + PyObject *__pyx_v_kpq_i = 0; + PyObject *__pyx_v_kpq = 0; + PyObject *__pyx_v_pmq_i = 0; + PyObject *__pyx_v_pmq = 0; + __Pyx_memviewslice __pyx_v_G = { 0, 0, { 0 }, { 0 }, { 0 } }; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("build_K_opt (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_nq,&__pyx_n_s_vqvec,&__pyx_n_s_vol,&__pyx_n_s_nbsf,&__pyx_n_s_kpq_i,&__pyx_n_s_kpq,&__pyx_n_s_pmq_i,&__pyx_n_s_pmq,&__pyx_n_s_G,0}; + PyObject* values[9] = {0,0,0,0,0,0,0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + CYTHON_FALLTHROUGH; + case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + CYTHON_FALLTHROUGH; + case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + CYTHON_FALLTHROUGH; + case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + CYTHON_FALLTHROUGH; + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nq)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vqvec)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 1); __PYX_ERR(0, 154, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vol)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 2); __PYX_ERR(0, 154, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 3: + if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nbsf)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 3); __PYX_ERR(0, 154, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 4: + if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq_i)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 4); __PYX_ERR(0, 154, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 5: + if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 5); __PYX_ERR(0, 154, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 6: + if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq_i)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 6); __PYX_ERR(0, 154, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 7: + if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 7); __PYX_ERR(0, 154, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 8: + if (likely((values[8] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_G)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 8); __PYX_ERR(0, 154, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "build_K_opt") < 0)) __PYX_ERR(0, 154, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 9) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + values[5] = PyTuple_GET_ITEM(__pyx_args, 5); + values[6] = PyTuple_GET_ITEM(__pyx_args, 6); + values[7] = PyTuple_GET_ITEM(__pyx_args, 7); + values[8] = PyTuple_GET_ITEM(__pyx_args, 8); + } + __pyx_v_nq = __Pyx_PyInt_As_long(values[0]); if (unlikely((__pyx_v_nq == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 154, __pyx_L3_error) + __pyx_v_vqvec = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_vqvec.memview)) __PYX_ERR(0, 154, __pyx_L3_error) + __pyx_v_vol = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_vol == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 154, __pyx_L3_error) + __pyx_v_nbsf = __Pyx_PyInt_As_long(values[3]); if (unlikely((__pyx_v_nbsf == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 154, __pyx_L3_error) + __pyx_v_kpq_i = ((PyObject*)values[4]); + __pyx_v_kpq = ((PyObject*)values[5]); + __pyx_v_pmq_i = ((PyObject*)values[6]); + __pyx_v_pmq = ((PyObject*)values[7]); + __pyx_v_G = __Pyx_PyObject_to_MemoryviewSlice_dsdsds___pyx_t_double_complex(values[8], PyBUF_WRITABLE); if (unlikely(!__pyx_v_G.memview)) __PYX_ERR(0, 156, __pyx_L3_error) + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 154, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("ueg_kernels.build_K_opt", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq_i), (&PyList_Type), 1, "kpq_i", 1))) __PYX_ERR(0, 154, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq), (&PyList_Type), 1, "kpq", 1))) __PYX_ERR(0, 155, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq_i), (&PyList_Type), 1, "pmq_i", 1))) __PYX_ERR(0, 155, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq), (&PyList_Type), 1, "pmq", 1))) __PYX_ERR(0, 155, __pyx_L1_error) + __pyx_r = __pyx_pf_11ueg_kernels_12build_K_opt(__pyx_self, __pyx_v_nq, __pyx_v_vqvec, __pyx_v_vol, __pyx_v_nbsf, __pyx_v_kpq_i, __pyx_v_kpq, __pyx_v_pmq_i, __pyx_v_pmq, __pyx_v_G); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_11ueg_kernels_12build_K_opt(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nq, __Pyx_memviewslice __pyx_v_vqvec, double __pyx_v_vol, long __pyx_v_nbsf, PyObject *__pyx_v_kpq_i, PyObject *__pyx_v_kpq, PyObject *__pyx_v_pmq_i, PyObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_G) { + PyArrayObject *__pyx_v_K = 0; + int __pyx_v_iq; + int __pyx_v_s; + int __pyx_v_idxjmq; + int __pyx_v_idxkpq; + int __pyx_v_idxk; + int __pyx_v_idxjpq; + int __pyx_v_idxj; + int __pyx_v_idxpmq; + int __pyx_v_idxp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + long __pyx_t_6; + long __pyx_t_7; + int __pyx_t_8; + Py_ssize_t __pyx_t_9; + PyObject *(*__pyx_t_10)(PyObject *); + PyObject *__pyx_t_11 = NULL; + PyObject *(*__pyx_t_12)(PyObject *); + int __pyx_t_13; + int __pyx_t_14; + Py_ssize_t __pyx_t_15; + PyObject *(*__pyx_t_16)(PyObject *); + PyObject *__pyx_t_17 = NULL; + double __pyx_t_18; + Py_ssize_t __pyx_t_19; + Py_ssize_t __pyx_t_20; + Py_ssize_t __pyx_t_21; + Py_ssize_t __pyx_t_22; + __pyx_t_double_complex __pyx_t_23; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("build_K_opt", 0); + + /* "ueg_kernels.pyx":158 + * double complex[:,:,:] G): + * + * cdef numpy.ndarray K = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) # <<<<<<<<<<<<<< + * cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyList_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_int_2); + __Pyx_GIVEREF(__pyx_int_2); + PyList_SET_ITEM(__pyx_t_4, 0, __pyx_int_2); + __Pyx_GIVEREF(__pyx_t_1); + PyList_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_3); + PyList_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 158, __pyx_L1_error) + __pyx_v_K = ((PyArrayObject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":161 + * cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp + * + * for s in range(2): # <<<<<<<<<<<<<< + * for iq in range(nq): + * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): + */ + for (__pyx_t_5 = 0; __pyx_t_5 < 2; __pyx_t_5+=1) { + __pyx_v_s = __pyx_t_5; + + /* "ueg_kernels.pyx":162 + * + * for s in range(2): + * for iq in range(nq): # <<<<<<<<<<<<<< + * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): + * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + */ + __pyx_t_6 = __pyx_v_nq; + __pyx_t_7 = __pyx_t_6; + for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { + __pyx_v_iq = __pyx_t_8; + + /* "ueg_kernels.pyx":163 + * for s in range(2): + * for iq in range(nq): + * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): # <<<<<<<<<<<<<< + * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + */ + if (unlikely(__pyx_v_pmq == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 163, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_pmq, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(__pyx_v_pmq_i == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 163, __pyx_L1_error) + } + __pyx_t_4 = __Pyx_GetItemInt_List(__pyx_v_pmq_i, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); + __pyx_t_1 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (likely(PyList_CheckExact(__pyx_t_4)) || PyTuple_CheckExact(__pyx_t_4)) { + __pyx_t_3 = __pyx_t_4; __Pyx_INCREF(__pyx_t_3); __pyx_t_9 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_9 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_10 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 163, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + if (__pyx_t_9 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_9); __Pyx_INCREF(__pyx_t_4); __pyx_t_9++; if (unlikely(0 < 0)) __PYX_ERR(0, 163, __pyx_L1_error) + #else + __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + if (__pyx_t_9 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_9); __Pyx_INCREF(__pyx_t_4); __pyx_t_9++; if (unlikely(0 < 0)) __PYX_ERR(0, 163, __pyx_L1_error) + #else + __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + } + } else { + __pyx_t_4 = __pyx_t_10(__pyx_t_3); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 163, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_4); + } + if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { + PyObject* sequence = __pyx_t_4; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 163, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_1 = PyList_GET_ITEM(sequence, 0); + __pyx_t_2 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_2); + #else + __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_11 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_12 = Py_TYPE(__pyx_t_11)->tp_iternext; + index = 0; __pyx_t_1 = __pyx_t_12(__pyx_t_11); if (unlikely(!__pyx_t_1)) goto __pyx_L9_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_2 = __pyx_t_12(__pyx_t_11); if (unlikely(!__pyx_t_2)) goto __pyx_L9_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_11), 2) < 0) __PYX_ERR(0, 163, __pyx_L1_error) + __pyx_t_12 = NULL; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + goto __pyx_L10_unpacking_done; + __pyx_L9_unpacking_failed:; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_12 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 163, __pyx_L1_error) + __pyx_L10_unpacking_done:; + } + __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_idxjmq = __pyx_t_13; + __pyx_v_idxj = __pyx_t_14; + + /* "ueg_kernels.pyx":164 + * for iq in range(nq): + * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): + * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): # <<<<<<<<<<<<<< + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + */ + if (unlikely(__pyx_v_kpq == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 164, __pyx_L1_error) + } + __pyx_t_4 = __Pyx_GetItemInt_List(__pyx_v_kpq, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (unlikely(__pyx_v_kpq_i == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 164, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_v_kpq_i, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); + __pyx_t_4 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); __pyx_t_15 = 0; + __pyx_t_16 = NULL; + } else { + __pyx_t_15 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_16 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 164, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_16)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + if (__pyx_t_15 >= PyList_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_15); __Pyx_INCREF(__pyx_t_2); __pyx_t_15++; if (unlikely(0 < 0)) __PYX_ERR(0, 164, __pyx_L1_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_15); __pyx_t_15++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + if (__pyx_t_15 >= PyTuple_GET_SIZE(__pyx_t_1)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_15); __Pyx_INCREF(__pyx_t_2); __pyx_t_15++; if (unlikely(0 < 0)) __PYX_ERR(0, 164, __pyx_L1_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_15); __pyx_t_15++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_16(__pyx_t_1); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 164, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 164, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_4 = PyList_GET_ITEM(sequence, 0); + __pyx_t_11 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_11); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_11 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_17 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_17); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_12 = Py_TYPE(__pyx_t_17)->tp_iternext; + index = 0; __pyx_t_4 = __pyx_t_12(__pyx_t_17); if (unlikely(!__pyx_t_4)) goto __pyx_L13_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + index = 1; __pyx_t_11 = __pyx_t_12(__pyx_t_17); if (unlikely(!__pyx_t_11)) goto __pyx_L13_unpacking_failed; + __Pyx_GOTREF(__pyx_t_11); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_17), 2) < 0) __PYX_ERR(0, 164, __pyx_L1_error) + __pyx_t_12 = NULL; + __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; + goto __pyx_L14_unpacking_done; + __pyx_L13_unpacking_failed:; + __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; + __pyx_t_12 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 164, __pyx_L1_error) + __pyx_L14_unpacking_done:; + } + __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_t_4); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_11); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_v_idxkpq = __pyx_t_14; + __pyx_v_idxk = __pyx_t_13; + + /* "ueg_kernels.pyx":165 + * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): + * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] # <<<<<<<<<<<<<< + * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): + */ + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_s); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_11 = __Pyx_PyInt_From_int(__pyx_v_idxj); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_idxkpq); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_17 = PyTuple_New(3); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_17); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_17, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_17, 1, __pyx_t_11); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_17, 2, __pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_11 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_K), __pyx_t_17); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_18 = (2.0 * __pyx_v_vol); + if (unlikely(__pyx_t_18 == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + __PYX_ERR(0, 165, __pyx_L1_error) + } + __pyx_t_19 = __pyx_v_iq; + __pyx_t_13 = -1; + if (__pyx_t_19 < 0) { + __pyx_t_19 += __pyx_v_vqvec.shape[0]; + if (unlikely(__pyx_t_19 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_19 >= __pyx_v_vqvec.shape[0])) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + __PYX_ERR(0, 165, __pyx_L1_error) + } + __pyx_t_20 = __pyx_v_s; + __pyx_t_21 = __pyx_v_idxjmq; + __pyx_t_22 = __pyx_v_idxk; + __pyx_t_13 = -1; + if (__pyx_t_20 < 0) { + __pyx_t_20 += __pyx_v_G.shape[0]; + if (unlikely(__pyx_t_20 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_20 >= __pyx_v_G.shape[0])) __pyx_t_13 = 0; + if (__pyx_t_21 < 0) { + __pyx_t_21 += __pyx_v_G.shape[1]; + if (unlikely(__pyx_t_21 < 0)) __pyx_t_13 = 1; + } else if (unlikely(__pyx_t_21 >= __pyx_v_G.shape[1])) __pyx_t_13 = 1; + if (__pyx_t_22 < 0) { + __pyx_t_22 += __pyx_v_G.shape[2]; + if (unlikely(__pyx_t_22 < 0)) __pyx_t_13 = 2; + } else if (unlikely(__pyx_t_22 >= __pyx_v_G.shape[2])) __pyx_t_13 = 2; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + __PYX_ERR(0, 165, __pyx_L1_error) + } + __pyx_t_23 = __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(((-(1.0 / __pyx_t_18)) * (*((double *) ( /* dim=0 */ (__pyx_v_vqvec.data + __pyx_t_19 * __pyx_v_vqvec.strides[0]) )))), 0), (*((__pyx_t_double_complex *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_20 * __pyx_v_G.strides[0]) ) + __pyx_t_21 * __pyx_v_G.strides[1]) ) + __pyx_t_22 * __pyx_v_G.strides[2]) )))); + __pyx_t_11 = __pyx_PyComplex_FromComplex(__pyx_t_23); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_4, __pyx_t_11); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_K), __pyx_t_17, __pyx_t_2) < 0)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; + + /* "ueg_kernels.pyx":164 + * for iq in range(nq): + * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): + * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): # <<<<<<<<<<<<<< + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":163 + * for s in range(2): + * for iq in range(nq): + * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): # <<<<<<<<<<<<<< + * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":166 + * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): # <<<<<<<<<<<<<< + * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): + * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] + */ + if (unlikely(__pyx_v_kpq == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 166, __pyx_L1_error) + } + __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_kpq, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (unlikely(__pyx_v_kpq_i == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 166, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_kpq_i, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_17 = PyTuple_New(2); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_17); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_17, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_17, 1, __pyx_t_1); + __pyx_t_3 = 0; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_17, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; + if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_17 = __pyx_t_1; __Pyx_INCREF(__pyx_t_17); __pyx_t_9 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_9 = -1; __pyx_t_17 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_17); + __pyx_t_10 = Py_TYPE(__pyx_t_17)->tp_iternext; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 166, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_17))) { + if (__pyx_t_9 >= PyList_GET_SIZE(__pyx_t_17)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = PyList_GET_ITEM(__pyx_t_17, __pyx_t_9); __Pyx_INCREF(__pyx_t_1); __pyx_t_9++; if (unlikely(0 < 0)) __PYX_ERR(0, 166, __pyx_L1_error) + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_17, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + #endif + } else { + if (__pyx_t_9 >= PyTuple_GET_SIZE(__pyx_t_17)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_17, __pyx_t_9); __Pyx_INCREF(__pyx_t_1); __pyx_t_9++; if (unlikely(0 < 0)) __PYX_ERR(0, 166, __pyx_L1_error) + #else + __pyx_t_1 = PySequence_ITEM(__pyx_t_17, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + #endif + } + } else { + __pyx_t_1 = __pyx_t_10(__pyx_t_17); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 166, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 166, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_3 = PyList_GET_ITEM(sequence, 0); + __pyx_t_2 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_11 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_12 = Py_TYPE(__pyx_t_11)->tp_iternext; + index = 0; __pyx_t_3 = __pyx_t_12(__pyx_t_11); if (unlikely(!__pyx_t_3)) goto __pyx_L17_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_2 = __pyx_t_12(__pyx_t_11); if (unlikely(!__pyx_t_2)) goto __pyx_L17_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_11), 2) < 0) __PYX_ERR(0, 166, __pyx_L1_error) + __pyx_t_12 = NULL; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + goto __pyx_L18_unpacking_done; + __pyx_L17_unpacking_failed:; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_12 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 166, __pyx_L1_error) + __pyx_L18_unpacking_done:; + } + __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 166, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_idxjpq = __pyx_t_13; + __pyx_v_idxj = __pyx_t_14; + + /* "ueg_kernels.pyx":167 + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): # <<<<<<<<<<<<<< + * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] + * return K + */ + if (unlikely(__pyx_v_pmq == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 167, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_pmq, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(__pyx_v_pmq_i == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 167, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_v_pmq_i, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_3 = __pyx_t_2; __Pyx_INCREF(__pyx_t_3); __pyx_t_15 = 0; + __pyx_t_16 = NULL; + } else { + __pyx_t_15 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_16 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 167, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_16)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + if (__pyx_t_15 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_15); __Pyx_INCREF(__pyx_t_2); __pyx_t_15++; if (unlikely(0 < 0)) __PYX_ERR(0, 167, __pyx_L1_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_15); __pyx_t_15++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + if (__pyx_t_15 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_15); __Pyx_INCREF(__pyx_t_2); __pyx_t_15++; if (unlikely(0 < 0)) __PYX_ERR(0, 167, __pyx_L1_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_15); __pyx_t_15++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_16(__pyx_t_3); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 167, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 167, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_1 = PyList_GET_ITEM(sequence, 0); + __pyx_t_11 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_11); + #else + __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_11 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_4 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_12 = Py_TYPE(__pyx_t_4)->tp_iternext; + index = 0; __pyx_t_1 = __pyx_t_12(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L21_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_11 = __pyx_t_12(__pyx_t_4); if (unlikely(!__pyx_t_11)) goto __pyx_L21_unpacking_failed; + __Pyx_GOTREF(__pyx_t_11); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_4), 2) < 0) __PYX_ERR(0, 167, __pyx_L1_error) + __pyx_t_12 = NULL; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L22_unpacking_done; + __pyx_L21_unpacking_failed:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_12 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 167, __pyx_L1_error) + __pyx_L22_unpacking_done:; + } + __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_11); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 167, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_v_idxpmq = __pyx_t_14; + __pyx_v_idxp = __pyx_t_13; + + /* "ueg_kernels.pyx":168 + * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): + * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] # <<<<<<<<<<<<<< + * return K + */ + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_s); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_11 = __Pyx_PyInt_From_int(__pyx_v_idxj); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_idxpmq); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_11); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_11); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_11 = 0; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_K), __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_18 = (2.0 * __pyx_v_vol); + if (unlikely(__pyx_t_18 == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + __PYX_ERR(0, 168, __pyx_L1_error) + } + __pyx_t_22 = __pyx_v_iq; + __pyx_t_13 = -1; + if (__pyx_t_22 < 0) { + __pyx_t_22 += __pyx_v_vqvec.shape[0]; + if (unlikely(__pyx_t_22 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_22 >= __pyx_v_vqvec.shape[0])) __pyx_t_13 = 0; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + __PYX_ERR(0, 168, __pyx_L1_error) + } + __pyx_t_21 = __pyx_v_s; + __pyx_t_20 = __pyx_v_idxjpq; + __pyx_t_19 = __pyx_v_idxp; + __pyx_t_13 = -1; + if (__pyx_t_21 < 0) { + __pyx_t_21 += __pyx_v_G.shape[0]; + if (unlikely(__pyx_t_21 < 0)) __pyx_t_13 = 0; + } else if (unlikely(__pyx_t_21 >= __pyx_v_G.shape[0])) __pyx_t_13 = 0; + if (__pyx_t_20 < 0) { + __pyx_t_20 += __pyx_v_G.shape[1]; + if (unlikely(__pyx_t_20 < 0)) __pyx_t_13 = 1; + } else if (unlikely(__pyx_t_20 >= __pyx_v_G.shape[1])) __pyx_t_13 = 1; + if (__pyx_t_19 < 0) { + __pyx_t_19 += __pyx_v_G.shape[2]; + if (unlikely(__pyx_t_19 < 0)) __pyx_t_13 = 2; + } else if (unlikely(__pyx_t_19 >= __pyx_v_G.shape[2])) __pyx_t_13 = 2; + if (unlikely(__pyx_t_13 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_13); + __PYX_ERR(0, 168, __pyx_L1_error) + } + __pyx_t_23 = __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(((-(1.0 / __pyx_t_18)) * (*((double *) ( /* dim=0 */ (__pyx_v_vqvec.data + __pyx_t_22 * __pyx_v_vqvec.strides[0]) )))), 0), (*((__pyx_t_double_complex *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_21 * __pyx_v_G.strides[0]) ) + __pyx_t_20 * __pyx_v_G.strides[1]) ) + __pyx_t_19 * __pyx_v_G.strides[2]) )))); + __pyx_t_11 = __pyx_PyComplex_FromComplex(__pyx_t_23); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_1, __pyx_t_11); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_K), __pyx_t_4, __pyx_t_2) < 0)) __PYX_ERR(0, 168, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "ueg_kernels.pyx":167 + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): # <<<<<<<<<<<<<< + * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] + * return K + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "ueg_kernels.pyx":166 + * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): # <<<<<<<<<<<<<< + * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): + * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] + */ + } + __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; + } + } + + /* "ueg_kernels.pyx":169 + * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): + * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] + * return K # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_K)); + __pyx_r = ((PyObject *)__pyx_v_K); + goto __pyx_L0; + + /* "ueg_kernels.pyx":154 + * return J + * + * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< + * list kpq, list pmq_i, list pmq, + * double complex[:,:,:] G): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_17); + __Pyx_AddTraceback("ueg_kernels.build_K_opt", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_K); + __PYX_XDEC_MEMVIEW(&__pyx_v_vqvec, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_G, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":734 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":735 + * + * cdef inline object PyArray_MultiIterNew1(a): + * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew2(a, b): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 735, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":734 + * ctypedef npy_cdouble complex_t + * + * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(1, a) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":737 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":738 + * + * cdef inline object PyArray_MultiIterNew2(a, b): + * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 738, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":737 + * return PyArray_MultiIterNew(1, a) + * + * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(2, a, b) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":740 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":741 + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): + * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 741, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":740 + * return PyArray_MultiIterNew(2, a, b) + * + * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(3, a, b, c) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":743 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":744 + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): + * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 744, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":743 + * return PyArray_MultiIterNew(3, a, b, c) + * + * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(4, a, b, c, d) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":746 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":747 + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< + * + * cdef inline tuple PyDataType_SHAPE(dtype d): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 747, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":746 + * return PyArray_MultiIterNew(4, a, b, c, d) + * + * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":749 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< + * if PyDataType_HASSUBARRAY(d): + * return d.subarray.shape + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("PyDataType_SHAPE", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":750 + * + * cdef inline tuple PyDataType_SHAPE(dtype d): + * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< + * return d.subarray.shape + * else: + */ + __pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0); + if (__pyx_t_1) { + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":751 + * cdef inline tuple PyDataType_SHAPE(dtype d): + * if PyDataType_HASSUBARRAY(d): + * return d.subarray.shape # <<<<<<<<<<<<<< + * else: + * return () + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape)); + __pyx_r = ((PyObject*)__pyx_v_d->subarray->shape); + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":750 + * + * cdef inline tuple PyDataType_SHAPE(dtype d): + * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< + * return d.subarray.shape + * else: + */ + } + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":753 + * return d.subarray.shape + * else: + * return () # <<<<<<<<<<<<<< + * + * + */ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_empty_tuple); + __pyx_r = __pyx_empty_tuple; + goto __pyx_L0; + } + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":749 + * return PyArray_MultiIterNew(5, a, b, c, d, e) + * + * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< + * if PyDataType_HASSUBARRAY(d): + * return d.subarray.shape + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":928 + * int _import_umath() except -1 + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * Py_INCREF(base) # important to do this before stealing the reference below! + * PyArray_SetBaseObject(arr, base) + */ + +static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("set_array_base", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":929 + * + * cdef inline void set_array_base(ndarray arr, object base): + * Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<< + * PyArray_SetBaseObject(arr, base) + * + */ + Py_INCREF(__pyx_v_base); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":930 + * cdef inline void set_array_base(ndarray arr, object base): + * Py_INCREF(base) # important to do this before stealing the reference below! + * PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<< + * + * cdef inline object get_array_base(ndarray arr): + */ + (void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base)); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":928 + * int _import_umath() except -1 + * + * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< + * Py_INCREF(base) # important to do this before stealing the reference below! + * PyArray_SetBaseObject(arr, base) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":932 + * PyArray_SetBaseObject(arr, base) + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * base = PyArray_BASE(arr) + * if base is NULL: + */ + +static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { + PyObject *__pyx_v_base; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("get_array_base", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":933 + * + * cdef inline object get_array_base(ndarray arr): + * base = PyArray_BASE(arr) # <<<<<<<<<<<<<< + * if base is NULL: + * return None + */ + __pyx_v_base = PyArray_BASE(__pyx_v_arr); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":934 + * cdef inline object get_array_base(ndarray arr): + * base = PyArray_BASE(arr) + * if base is NULL: # <<<<<<<<<<<<<< + * return None + * return base + */ + __pyx_t_1 = ((__pyx_v_base == NULL) != 0); + if (__pyx_t_1) { + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":935 + * base = PyArray_BASE(arr) + * if base is NULL: + * return None # <<<<<<<<<<<<<< + * return base + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":934 + * cdef inline object get_array_base(ndarray arr): + * base = PyArray_BASE(arr) + * if base is NULL: # <<<<<<<<<<<<<< + * return None + * return base + */ + } + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":936 + * if base is NULL: + * return None + * return base # <<<<<<<<<<<<<< + * + * # Versions of the import_* functions which are more suitable for + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_base)); + __pyx_r = ((PyObject *)__pyx_v_base); + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":932 + * PyArray_SetBaseObject(arr, base) + * + * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< + * base = PyArray_BASE(arr) + * if base is NULL: + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":940 + * # Versions of the import_* functions which are more suitable for + * # Cython code. + * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< + * try: + * __pyx_import_array() + */ + +static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("import_array", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":941 + * # Cython code. + * cdef inline int import_array() except -1: + * try: # <<<<<<<<<<<<<< + * __pyx_import_array() + * except Exception: + */ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + /*try:*/ { + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":942 + * cdef inline int import_array() except -1: + * try: + * __pyx_import_array() # <<<<<<<<<<<<<< + * except Exception: + * raise ImportError("numpy.core.multiarray failed to import") + */ + __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 942, __pyx_L3_error) + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":941 + * # Cython code. + * cdef inline int import_array() except -1: + * try: # <<<<<<<<<<<<<< + * __pyx_import_array() + * except Exception: + */ + } + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L8_try_end; + __pyx_L3_error:; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":943 + * try: + * __pyx_import_array() + * except Exception: # <<<<<<<<<<<<<< + * raise ImportError("numpy.core.multiarray failed to import") + * + */ + __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); + if (__pyx_t_4) { + __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 943, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_7); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":944 + * __pyx_import_array() + * except Exception: + * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< + * + * cdef inline int import_umath() except -1: + */ + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 944, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __PYX_ERR(1, 944, __pyx_L5_except_error) + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":941 + * # Cython code. + * cdef inline int import_array() except -1: + * try: # <<<<<<<<<<<<<< + * __pyx_import_array() + * except Exception: + */ + __Pyx_XGIVEREF(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); + goto __pyx_L1_error; + __pyx_L8_try_end:; + } + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":940 + * # Versions of the import_* functions which are more suitable for + * # Cython code. + * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< + * try: + * __pyx_import_array() + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":946 + * raise ImportError("numpy.core.multiarray failed to import") + * + * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< + * try: + * _import_umath() + */ + +static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("import_umath", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":947 + * + * cdef inline int import_umath() except -1: + * try: # <<<<<<<<<<<<<< + * _import_umath() + * except Exception: + */ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + /*try:*/ { + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":948 + * cdef inline int import_umath() except -1: + * try: + * _import_umath() # <<<<<<<<<<<<<< + * except Exception: + * raise ImportError("numpy.core.umath failed to import") + */ + __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 948, __pyx_L3_error) + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":947 + * + * cdef inline int import_umath() except -1: + * try: # <<<<<<<<<<<<<< + * _import_umath() + * except Exception: + */ + } + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L8_try_end; + __pyx_L3_error:; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":949 + * try: + * _import_umath() + * except Exception: # <<<<<<<<<<<<<< + * raise ImportError("numpy.core.umath failed to import") + * + */ + __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); + if (__pyx_t_4) { + __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 949, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_7); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":950 + * _import_umath() + * except Exception: + * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< + * + * cdef inline int import_ufunc() except -1: + */ + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 950, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __PYX_ERR(1, 950, __pyx_L5_except_error) + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":947 + * + * cdef inline int import_umath() except -1: + * try: # <<<<<<<<<<<<<< + * _import_umath() + * except Exception: + */ + __Pyx_XGIVEREF(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); + goto __pyx_L1_error; + __pyx_L8_try_end:; + } + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":946 + * raise ImportError("numpy.core.multiarray failed to import") + * + * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< + * try: + * _import_umath() + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":952 + * raise ImportError("numpy.core.umath failed to import") + * + * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< + * try: + * _import_umath() + */ + +static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("import_ufunc", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":953 + * + * cdef inline int import_ufunc() except -1: + * try: # <<<<<<<<<<<<<< + * _import_umath() + * except Exception: + */ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + /*try:*/ { + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":954 + * cdef inline int import_ufunc() except -1: + * try: + * _import_umath() # <<<<<<<<<<<<<< + * except Exception: + * raise ImportError("numpy.core.umath failed to import") + */ + __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 954, __pyx_L3_error) + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":953 + * + * cdef inline int import_ufunc() except -1: + * try: # <<<<<<<<<<<<<< + * _import_umath() + * except Exception: + */ + } + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L8_try_end; + __pyx_L3_error:; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":955 + * try: + * _import_umath() + * except Exception: # <<<<<<<<<<<<<< + * raise ImportError("numpy.core.umath failed to import") + * + */ + __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); + if (__pyx_t_4) { + __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 955, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GOTREF(__pyx_t_7); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":956 + * _import_umath() + * except Exception: + * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< + * + * cdef extern from *: + */ + __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 956, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_Raise(__pyx_t_8, 0, 0, 0); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __PYX_ERR(1, 956, __pyx_L5_except_error) + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":953 + * + * cdef inline int import_ufunc() except -1: + * try: # <<<<<<<<<<<<<< + * _import_umath() + * except Exception: + */ + __Pyx_XGIVEREF(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); + goto __pyx_L1_error; + __pyx_L8_try_end:; + } + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":952 + * raise ImportError("numpy.core.umath failed to import") + * + * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< + * try: + * _import_umath() + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":966 + * + * + * cdef inline bint is_timedelta64_object(object obj): # <<<<<<<<<<<<<< + * """ + * Cython equivalent of `isinstance(obj, np.timedelta64)` + */ + +static CYTHON_INLINE int __pyx_f_5numpy_is_timedelta64_object(PyObject *__pyx_v_obj) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_timedelta64_object", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":978 + * bool + * """ + * return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = PyObject_TypeCheck(__pyx_v_obj, (&PyTimedeltaArrType_Type)); + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":966 + * + * + * cdef inline bint is_timedelta64_object(object obj): # <<<<<<<<<<<<<< + * """ + * Cython equivalent of `isinstance(obj, np.timedelta64)` + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":981 + * + * + * cdef inline bint is_datetime64_object(object obj): # <<<<<<<<<<<<<< + * """ + * Cython equivalent of `isinstance(obj, np.datetime64)` + */ + +static CYTHON_INLINE int __pyx_f_5numpy_is_datetime64_object(PyObject *__pyx_v_obj) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_datetime64_object", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":993 + * bool + * """ + * return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = PyObject_TypeCheck(__pyx_v_obj, (&PyDatetimeArrType_Type)); + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":981 + * + * + * cdef inline bint is_datetime64_object(object obj): # <<<<<<<<<<<<<< + * """ + * Cython equivalent of `isinstance(obj, np.datetime64)` + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":996 + * + * + * cdef inline npy_datetime get_datetime64_value(object obj) nogil: # <<<<<<<<<<<<<< + * """ + * returns the int64 value underlying scalar numpy datetime64 object + */ + +static CYTHON_INLINE npy_datetime __pyx_f_5numpy_get_datetime64_value(PyObject *__pyx_v_obj) { + npy_datetime __pyx_r; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1003 + * also needed. That can be found using `get_datetime64_unit`. + * """ + * return (obj).obval # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((PyDatetimeScalarObject *)__pyx_v_obj)->obval; + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":996 + * + * + * cdef inline npy_datetime get_datetime64_value(object obj) nogil: # <<<<<<<<<<<<<< + * """ + * returns the int64 value underlying scalar numpy datetime64 object + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1006 + * + * + * cdef inline npy_timedelta get_timedelta64_value(object obj) nogil: # <<<<<<<<<<<<<< + * """ + * returns the int64 value underlying scalar numpy timedelta64 object + */ + +static CYTHON_INLINE npy_timedelta __pyx_f_5numpy_get_timedelta64_value(PyObject *__pyx_v_obj) { + npy_timedelta __pyx_r; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1010 + * returns the int64 value underlying scalar numpy timedelta64 object + * """ + * return (obj).obval # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((PyTimedeltaScalarObject *)__pyx_v_obj)->obval; + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1006 + * + * + * cdef inline npy_timedelta get_timedelta64_value(object obj) nogil: # <<<<<<<<<<<<<< + * """ + * returns the int64 value underlying scalar numpy timedelta64 object + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1013 + * + * + * cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil: # <<<<<<<<<<<<<< + * """ + * returns the unit part of the dtype for a numpy datetime64 object. + */ + +static CYTHON_INLINE NPY_DATETIMEUNIT __pyx_f_5numpy_get_datetime64_unit(PyObject *__pyx_v_obj) { + NPY_DATETIMEUNIT __pyx_r; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1017 + * returns the unit part of the dtype for a numpy datetime64 object. + * """ + * return (obj).obmeta.base # <<<<<<<<<<<<<< + */ + __pyx_r = ((NPY_DATETIMEUNIT)((PyDatetimeScalarObject *)__pyx_v_obj)->obmeta.base); + goto __pyx_L0; + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1013 + * + * + * cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil: # <<<<<<<<<<<<<< + * """ + * returns the unit part of the dtype for a numpy datetime64 object. + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":123 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + +/* Python wrapper */ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_shape = 0; + Py_ssize_t __pyx_v_itemsize; + PyObject *__pyx_v_format = 0; + PyObject *__pyx_v_mode = 0; + int __pyx_v_allocate_buffer; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; + PyObject* values[5] = {0,0,0,0,0}; + values[3] = ((PyObject *)__pyx_n_s_c); + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(2, 123, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(2, 123, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 3: + if (kw_args > 0) { + PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mode); + if (value) { values[3] = value; kw_args--; } + } + CYTHON_FALLTHROUGH; + case 4: + if (kw_args > 0) { + PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_allocate_buffer); + if (value) { values[4] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(2, 123, __pyx_L3_error) + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_shape = ((PyObject*)values[0]); + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 123, __pyx_L3_error) + __pyx_v_format = values[2]; + __pyx_v_mode = values[3]; + if (values[4]) { + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 124, __pyx_L3_error) + } else { + + /* "View.MemoryView":124 + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, + * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_v_allocate_buffer = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 123, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) __PYX_ERR(2, 123, __pyx_L1_error) + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(2, 123, __pyx_L1_error) + } + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + + /* "View.MemoryView":123 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { + int __pyx_v_idx; + Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_dim; + PyObject **__pyx_v_p; + char __pyx_v_order; + int __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + char *__pyx_t_7; + int __pyx_t_8; + Py_ssize_t __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + Py_ssize_t __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + + /* "View.MemoryView":130 + * cdef PyObject **p + * + * self.ndim = len(shape) # <<<<<<<<<<<<<< + * self.itemsize = itemsize + * + */ + if (unlikely(__pyx_v_shape == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(2, 130, __pyx_L1_error) + } + __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(2, 130, __pyx_L1_error) + __pyx_v_self->ndim = ((int)__pyx_t_1); + + /* "View.MemoryView":131 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":133 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); + if (unlikely(__pyx_t_2)) { + + /* "View.MemoryView":134 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(2, 134, __pyx_L1_error) + + /* "View.MemoryView":133 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + } + + /* "View.MemoryView":136 + * raise ValueError("Empty shape tuple for cython.array") + * + * if itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); + if (unlikely(__pyx_t_2)) { + + /* "View.MemoryView":137 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if not isinstance(format, bytes): + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 137, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(2, 137, __pyx_L1_error) + + /* "View.MemoryView":136 + * raise ValueError("Empty shape tuple for cython.array") + * + * if itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + } + + /* "View.MemoryView":139 + * raise ValueError("itemsize <= 0 for cython.array") + * + * if not isinstance(format, bytes): # <<<<<<<<<<<<<< + * format = format.encode('ASCII') + * self._format = format # keep a reference to the byte string + */ + __pyx_t_2 = PyBytes_Check(__pyx_v_format); + __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":140 + * + * if not isinstance(format, bytes): + * format = format.encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format # keep a reference to the byte string + * self.format = self._format + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 140, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = NULL; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_6)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_6); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + } + } + __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_n_s_ASCII) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_n_s_ASCII); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 140, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":139 + * raise ValueError("itemsize <= 0 for cython.array") + * + * if not isinstance(format, bytes): # <<<<<<<<<<<<<< + * format = format.encode('ASCII') + * self._format = format # keep a reference to the byte string + */ + } + + /* "View.MemoryView":141 + * if not isinstance(format, bytes): + * format = format.encode('ASCII') + * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< + * self.format = self._format + * + */ + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) __PYX_ERR(2, 141, __pyx_L1_error) + __pyx_t_3 = __pyx_v_format; + __Pyx_INCREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->_format); + __Pyx_DECREF(__pyx_v_self->_format); + __pyx_v_self->_format = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":142 + * format = format.encode('ASCII') + * self._format = format # keep a reference to the byte string + * self.format = self._format # <<<<<<<<<<<<<< + * + * + */ + if (unlikely(__pyx_v_self->_format == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(2, 142, __pyx_L1_error) + } + __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(2, 142, __pyx_L1_error) + __pyx_v_self->format = __pyx_t_7; + + /* "View.MemoryView":145 + * + * + * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< + * self._strides = self._shape + self.ndim + * + */ + __pyx_v_self->_shape = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); + + /* "View.MemoryView":146 + * + * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) + * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< + * + * if not self._shape: + */ + __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); + + /* "View.MemoryView":148 + * self._strides = self._shape + self.ndim + * + * if not self._shape: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape and strides.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); + if (unlikely(__pyx_t_4)) { + + /* "View.MemoryView":149 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(2, 149, __pyx_L1_error) + + /* "View.MemoryView":148 + * self._strides = self._shape + self.ndim + * + * if not self._shape: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape and strides.") + * + */ + } + + /* "View.MemoryView":152 + * + * + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + __pyx_t_8 = 0; + __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + for (;;) { + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_5); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(2, 152, __pyx_L1_error) + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 152, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_5); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 152, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_9; + __pyx_v_idx = __pyx_t_8; + __pyx_t_8 = (__pyx_t_8 + 1); + + /* "View.MemoryView":153 + * + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim + */ + __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); + if (unlikely(__pyx_t_4)) { + + /* "View.MemoryView":154 + * for idx, dim in enumerate(shape): + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< + * self._shape[idx] = dim + * + */ + __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_6); + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __PYX_ERR(2, 154, __pyx_L1_error) + + /* "View.MemoryView":153 + * + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim + */ + } + + /* "View.MemoryView":155 + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim # <<<<<<<<<<<<<< + * + * cdef char order + */ + (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; + + /* "View.MemoryView":152 + * + * + * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< + * if dim <= 0: + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":158 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = b'F' + * self.mode = u'fortran' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(2, 158, __pyx_L1_error) + if (__pyx_t_4) { + + /* "View.MemoryView":159 + * cdef char order + * if mode == 'fortran': + * order = b'F' # <<<<<<<<<<<<<< + * self.mode = u'fortran' + * elif mode == 'c': + */ + __pyx_v_order = 'F'; + + /* "View.MemoryView":160 + * if mode == 'fortran': + * order = b'F' + * self.mode = u'fortran' # <<<<<<<<<<<<<< + * elif mode == 'c': + * order = b'C' + */ + __Pyx_INCREF(__pyx_n_u_fortran); + __Pyx_GIVEREF(__pyx_n_u_fortran); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_fortran; + + /* "View.MemoryView":158 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = b'F' + * self.mode = u'fortran' + */ + goto __pyx_L10; + } + + /* "View.MemoryView":161 + * order = b'F' + * self.mode = u'fortran' + * elif mode == 'c': # <<<<<<<<<<<<<< + * order = b'C' + * self.mode = u'c' + */ + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(2, 161, __pyx_L1_error) + if (likely(__pyx_t_4)) { + + /* "View.MemoryView":162 + * self.mode = u'fortran' + * elif mode == 'c': + * order = b'C' # <<<<<<<<<<<<<< + * self.mode = u'c' + * else: + */ + __pyx_v_order = 'C'; + + /* "View.MemoryView":163 + * elif mode == 'c': + * order = b'C' + * self.mode = u'c' # <<<<<<<<<<<<<< + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + */ + __Pyx_INCREF(__pyx_n_u_c); + __Pyx_GIVEREF(__pyx_n_u_c); + __Pyx_GOTREF(__pyx_v_self->mode); + __Pyx_DECREF(__pyx_v_self->mode); + __pyx_v_self->mode = __pyx_n_u_c; + + /* "View.MemoryView":161 + * order = b'F' + * self.mode = u'fortran' + * elif mode == 'c': # <<<<<<<<<<<<<< + * order = b'C' + * self.mode = u'c' + */ + goto __pyx_L10; + } + + /* "View.MemoryView":165 + * self.mode = u'c' + * else: + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< + * + * self.len = fill_contig_strides_array(self._shape, self._strides, + */ + /*else*/ { + __pyx_t_3 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __PYX_ERR(2, 165, __pyx_L1_error) + } + __pyx_L10:; + + /* "View.MemoryView":167 + * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) + * + * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< + * itemsize, self.ndim, order) + * + */ + __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); + + /* "View.MemoryView":170 + * itemsize, self.ndim, order) + * + * self.free_data = allocate_buffer # <<<<<<<<<<<<<< + * self.dtype_is_object = format == b'O' + * if allocate_buffer: + */ + __pyx_v_self->free_data = __pyx_v_allocate_buffer; + + /* "View.MemoryView":171 + * + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< + * if allocate_buffer: + * + */ + __pyx_t_10 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 171, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 171, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_4; + + /* "View.MemoryView":172 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_4 = (__pyx_v_allocate_buffer != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":175 + * + * + * self.data = malloc(self.len) # <<<<<<<<<<<<<< + * if not self.data: + * raise MemoryError("unable to allocate array data.") + */ + __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); + + /* "View.MemoryView":176 + * + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); + if (unlikely(__pyx_t_4)) { + + /* "View.MemoryView":177 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 177, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_Raise(__pyx_t_10, 0, 0, 0); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __PYX_ERR(2, 177, __pyx_L1_error) + + /* "View.MemoryView":176 + * + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + } + + /* "View.MemoryView":179 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":180 + * + * if self.dtype_is_object: + * p = self.data # <<<<<<<<<<<<<< + * for i in range(self.len / itemsize): + * p[i] = Py_None + */ + __pyx_v_p = ((PyObject **)__pyx_v_self->data); + + /* "View.MemoryView":181 + * if self.dtype_is_object: + * p = self.data + * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< + * p[i] = Py_None + * Py_INCREF(Py_None) + */ + if (unlikely(__pyx_v_itemsize == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + __PYX_ERR(2, 181, __pyx_L1_error) + } + else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + __PYX_ERR(2, 181, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); + __pyx_t_9 = __pyx_t_1; + for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { + __pyx_v_i = __pyx_t_11; + + /* "View.MemoryView":182 + * p = self.data + * for i in range(self.len / itemsize): + * p[i] = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + (__pyx_v_p[__pyx_v_i]) = Py_None; + + /* "View.MemoryView":183 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + + /* "View.MemoryView":179 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + } + + /* "View.MemoryView":172 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * + * + */ + } + + /* "View.MemoryView":123 + * cdef bint dtype_is_object + * + * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< + * mode="c", bint allocate_buffer=True): + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_format); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":186 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_bufmode; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + char *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + if (__pyx_v_info == NULL) { + PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); + return -1; + } + __Pyx_RefNannySetupContext("__getbuffer__", 0); + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + + /* "View.MemoryView":187 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 # <<<<<<<<<<<<<< + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = -1; + + /* "View.MemoryView":188 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == u"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + */ + __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 188, __pyx_L1_error) + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":189 + * cdef int bufmode = -1 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + */ + __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + + /* "View.MemoryView":188 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == u"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + */ + goto __pyx_L3; + } + + /* "View.MemoryView":190 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(2, 190, __pyx_L1_error) + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":191 + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + */ + __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + + /* "View.MemoryView":190 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ + } + __pyx_L3:; + + /* "View.MemoryView":192 + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); + if (unlikely(__pyx_t_1)) { + + /* "View.MemoryView":193 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 193, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(2, 193, __pyx_L1_error) + + /* "View.MemoryView":192 + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ + } + + /* "View.MemoryView":194 + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data # <<<<<<<<<<<<<< + * info.len = self.len + * info.ndim = self.ndim + */ + __pyx_t_4 = __pyx_v_self->data; + __pyx_v_info->buf = __pyx_t_4; + + /* "View.MemoryView":195 + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + * info.len = self.len # <<<<<<<<<<<<<< + * info.ndim = self.ndim + * info.shape = self._shape + */ + __pyx_t_5 = __pyx_v_self->len; + __pyx_v_info->len = __pyx_t_5; + + /* "View.MemoryView":196 + * info.buf = self.data + * info.len = self.len + * info.ndim = self.ndim # <<<<<<<<<<<<<< + * info.shape = self._shape + * info.strides = self._strides + */ + __pyx_t_6 = __pyx_v_self->ndim; + __pyx_v_info->ndim = __pyx_t_6; + + /* "View.MemoryView":197 + * info.len = self.len + * info.ndim = self.ndim + * info.shape = self._shape # <<<<<<<<<<<<<< + * info.strides = self._strides + * info.suboffsets = NULL + */ + __pyx_t_7 = __pyx_v_self->_shape; + __pyx_v_info->shape = __pyx_t_7; + + /* "View.MemoryView":198 + * info.ndim = self.ndim + * info.shape = self._shape + * info.strides = self._strides # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = self.itemsize + */ + __pyx_t_7 = __pyx_v_self->_strides; + __pyx_v_info->strides = __pyx_t_7; + + /* "View.MemoryView":199 + * info.shape = self._shape + * info.strides = self._strides + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = self.itemsize + * info.readonly = 0 + */ + __pyx_v_info->suboffsets = NULL; + + /* "View.MemoryView":200 + * info.strides = self._strides + * info.suboffsets = NULL + * info.itemsize = self.itemsize # <<<<<<<<<<<<<< + * info.readonly = 0 + * + */ + __pyx_t_5 = __pyx_v_self->itemsize; + __pyx_v_info->itemsize = __pyx_t_5; + + /* "View.MemoryView":201 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":203 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":204 + * + * if flags & PyBUF_FORMAT: + * info.format = self.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_4 = __pyx_v_self->format; + __pyx_v_info->format = __pyx_t_4; + + /* "View.MemoryView":203 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + goto __pyx_L5; + } + + /* "View.MemoryView":206 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + /*else*/ { + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":208 + * info.format = NULL + * + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":186 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * cdef int bufmode = -1 + * if self.mode == u"c": + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":212 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + +/* Python wrapper */ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":213 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":214 + * def __dealloc__(array self): + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) # <<<<<<<<<<<<<< + * elif self.free_data: + * if self.dtype_is_object: + */ + __pyx_v_self->callback_free_data(__pyx_v_self->data); + + /* "View.MemoryView":213 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":215 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + __pyx_t_1 = (__pyx_v_self->free_data != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":216 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":217 + * elif self.free_data: + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< + * self._strides, self.ndim, False) + * free(self.data) + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); + + /* "View.MemoryView":216 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ + } + + /* "View.MemoryView":219 + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + * free(self.data) # <<<<<<<<<<<<<< + * PyObject_Free(self._shape) + * + */ + free(__pyx_v_self->data); + + /* "View.MemoryView":215 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ + } + __pyx_L3:; + + /* "View.MemoryView":220 + * self._strides, self.ndim, False) + * free(self.data) + * PyObject_Free(self._shape) # <<<<<<<<<<<<<< + * + * @property + */ + PyObject_Free(__pyx_v_self->_shape); + + /* "View.MemoryView":212 + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") + * + * def __dealloc__(array self): # <<<<<<<<<<<<<< + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":223 + * + * @property + * def memview(self): # <<<<<<<<<<<<<< + * return self.get_memview() + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":224 + * @property + * def memview(self): + * return self.get_memview() # <<<<<<<<<<<<<< + * + * @cname('get_memview') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_array *)__pyx_v_self->__pyx_vtab)->get_memview(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 224, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":223 + * + * @property + * def memview(self): # <<<<<<<<<<<<<< + * return self.get_memview() + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":227 + * + * @cname('get_memview') + * cdef get_memview(self): # <<<<<<<<<<<<<< + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) + */ + +static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_memview", 0); + + /* "View.MemoryView":228 + * @cname('get_memview') + * cdef get_memview(self): + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":229 + * cdef get_memview(self): + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":227 + * + * @cname('get_memview') + * cdef get_memview(self): # <<<<<<<<<<<<<< + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.array.get_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":231 + * return memoryview(self, flags, self.dtype_is_object) + * + * def __len__(self): # <<<<<<<<<<<<<< + * return self._shape[0] + * + */ + +/* Python wrapper */ +static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":232 + * + * def __len__(self): + * return self._shape[0] # <<<<<<<<<<<<<< + * + * def __getattr__(self, attr): + */ + __pyx_r = (__pyx_v_self->_shape[0]); + goto __pyx_L0; + + /* "View.MemoryView":231 + * return memoryview(self, flags, self.dtype_is_object) + * + * def __len__(self): # <<<<<<<<<<<<<< + * return self._shape[0] + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":234 + * return self._shape[0] + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":235 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 235, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 235, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":234 + * return self._shape[0] + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":237 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ +static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":238 + * + * def __getitem__(self, item): + * return self.memview[item] # <<<<<<<<<<<<<< + * + * def __setitem__(self, item, value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 238, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 238, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":237 + * return getattr(self.memview, attr) + * + * def __getitem__(self, item): # <<<<<<<<<<<<<< + * return self.memview[item] + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":240 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + +/* Python wrapper */ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":241 + * + * def __setitem__(self, item, value): + * self.memview[item] = value # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 241, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(2, 241, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":240 + * return self.memview[item] + * + * def __setitem__(self, item, value): # <<<<<<<<<<<<<< + * self.memview[item] = value + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_array___reduce_cython__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(2, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_array_2__setstate_cython__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(2, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":245 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + +static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { + struct __pyx_array_obj *__pyx_v_result = 0; + struct __pyx_array_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":249 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":250 + * + * if buf == NULL: + * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "View.MemoryView":249 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":252 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + /*else*/ { + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 252, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 252, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 252, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 252, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_shape); + __Pyx_GIVEREF(__pyx_v_shape); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_3 = 0; + + /* "View.MemoryView":253 + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) # <<<<<<<<<<<<<< + * result.data = buf + * + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 253, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(2, 253, __pyx_L1_error) + + /* "View.MemoryView":252 + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< + * allocate_buffer=False) + * result.data = buf + */ + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 252, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":254 + * result = array(shape, itemsize, format, mode.decode('ASCII'), + * allocate_buffer=False) + * result.data = buf # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->data = __pyx_v_buf; + } + __pyx_L3:; + + /* "View.MemoryView":256 + * result.data = buf + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":245 + * + * @cname("__pyx_array_new") + * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< + * char *mode, char *buf): + * cdef array result + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":282 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + +/* Python wrapper */ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_name = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; + PyObject* values[1] = {0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(2, 282, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + } + __pyx_v_name = values[0]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 282, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__", 0); + + /* "View.MemoryView":283 + * cdef object name + * def __init__(self, name): + * self.name = name # <<<<<<<<<<<<<< + * def __repr__(self): + * return self.name + */ + __Pyx_INCREF(__pyx_v_name); + __Pyx_GIVEREF(__pyx_v_name); + __Pyx_GOTREF(__pyx_v_self->name); + __Pyx_DECREF(__pyx_v_self->name); + __pyx_v_self->name = __pyx_v_name; + + /* "View.MemoryView":282 + * cdef class Enum(object): + * cdef object name + * def __init__(self, name): # <<<<<<<<<<<<<< + * self.name = name + * def __repr__(self): + */ + + /* function exit code */ + __pyx_r = 0; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":284 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + +/* Python wrapper */ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":285 + * self.name = name + * def __repr__(self): + * return self.name # <<<<<<<<<<<<<< + * + * cdef generic = Enum("") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->name); + __pyx_r = __pyx_v_self->name; + goto __pyx_L0; + + /* "View.MemoryView":284 + * def __init__(self, name): + * self.name = name + * def __repr__(self): # <<<<<<<<<<<<<< + * return self.name + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_MemviewEnum___reduce_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; + int __pyx_v_use_setstate; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":5 + * cdef object _dict + * cdef bint use_setstate + * state = (self.name,) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: + */ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_self->name); + __Pyx_GIVEREF(__pyx_v_self->name); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); + __pyx_v_state = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "(tree fragment)":6 + * cdef bint use_setstate + * state = (self.name,) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None: + * state += (_dict,) + */ + __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v__dict = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":7 + * state = (self.name,) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True + */ + __pyx_t_2 = (__pyx_v__dict != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: + */ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); + __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "(tree fragment)":9 + * if _dict is not None: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = self.name is not None + */ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":7 + * state = (self.name,) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True + */ + goto __pyx_L3; + } + + /* "(tree fragment)":11 + * use_setstate = True + * else: + * use_setstate = self.name is not None # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state + */ + /*else*/ { + __pyx_t_3 = (__pyx_v_self->name != Py_None); + __pyx_v_use_setstate = __pyx_t_3; + } + __pyx_L3:; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.name is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state + * else: + */ + __pyx_t_3 = (__pyx_v_use_setstate != 0); + if (__pyx_t_3) { + + /* "(tree fragment)":13 + * use_setstate = self.name is not None + * if use_setstate: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_INCREF(__pyx_int_184977713); + __Pyx_GIVEREF(__pyx_int_184977713); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "(tree fragment)":12 + * else: + * use_setstate = self.name is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state + * else: + */ + } + + /* "(tree fragment)":15 + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state + * else: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_Enum__set_state(self, __pyx_state) + */ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_INCREF(__pyx_int_184977713); + __Pyx_GIVEREF(__pyx_int_184977713); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.Enum.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":16 + * else: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_Enum__set_state(self, __pyx_state) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_MemviewEnum_2__setstate_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":17 + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_Enum__set_state(self, __pyx_state) # <<<<<<<<<<<<<< + */ + if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(2, 17, __pyx_L1_error) + __pyx_t_1 = __pyx_unpickle_Enum__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_Enum__set_state(self, __pyx_state) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.Enum.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":299 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":301 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":305 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":307 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":308 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + + /* "View.MemoryView":307 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + } + + /* "View.MemoryView":310 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + /* "View.MemoryView":299 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":346 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + +/* Python wrapper */ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_obj = 0; + int __pyx_v_flags; + int __pyx_v_dtype_is_object; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(2, 346, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (kw_args > 0) { + PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_dtype_is_object); + if (value) { values[2] = value; kw_args--; } + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(2, 346, __pyx_L3_error) + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_obj = values[0]; + __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 346, __pyx_L3_error) + if (values[2]) { + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 346, __pyx_L3_error) + } else { + __pyx_v_dtype_is_object = ((int)0); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 346, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":347 + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj # <<<<<<<<<<<<<< + * self.flags = flags + * if type(self) is memoryview or obj is not None: + */ + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + __Pyx_GOTREF(__pyx_v_self->obj); + __Pyx_DECREF(__pyx_v_self->obj); + __pyx_v_self->obj = __pyx_v_obj; + + /* "View.MemoryView":348 + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): + * self.obj = obj + * self.flags = flags # <<<<<<<<<<<<<< + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":349 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)__pyx_memoryview_type)); + __pyx_t_3 = (__pyx_t_2 != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_obj != Py_None); + __pyx_t_2 = (__pyx_t_3 != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L4_bool_binop_done:; + if (__pyx_t_1) { + + /* "View.MemoryView":350 + * self.flags = flags + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + */ + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 350, __pyx_L1_error) + + /* "View.MemoryView":351 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":352 + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; + + /* "View.MemoryView":353 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * if not __PYX_CYTHON_ATOMICS_ENABLED(): + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":351 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ + } + + /* "View.MemoryView":349 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ + } + + /* "View.MemoryView":355 + * Py_INCREF(Py_None) + * + * if not __PYX_CYTHON_ATOMICS_ENABLED(): # <<<<<<<<<<<<<< + * global __pyx_memoryview_thread_locks_used + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: + */ + __pyx_t_1 = ((!(__PYX_CYTHON_ATOMICS_ENABLED() != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":357 + * if not __PYX_CYTHON_ATOMICS_ENABLED(): + * global __pyx_memoryview_thread_locks_used + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 + */ + __pyx_t_1 = ((__pyx_memoryview_thread_locks_used < 8) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":358 + * global __pyx_memoryview_thread_locks_used + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks_used += 1 + * if self.lock is NULL: + */ + __pyx_v_self->lock = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); + + /* "View.MemoryView":359 + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 # <<<<<<<<<<<<<< + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() + */ + __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used + 1); + + /* "View.MemoryView":357 + * if not __PYX_CYTHON_ATOMICS_ENABLED(): + * global __pyx_memoryview_thread_locks_used + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 + */ + } + + /* "View.MemoryView":360 + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 + * if self.lock is NULL: # <<<<<<<<<<<<<< + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: + */ + __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":361 + * __pyx_memoryview_thread_locks_used += 1 + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock is NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":362 + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); + if (unlikely(__pyx_t_1)) { + + /* "View.MemoryView":363 + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); __PYX_ERR(2, 363, __pyx_L1_error) + + /* "View.MemoryView":362 + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + } + + /* "View.MemoryView":360 + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 + * if self.lock is NULL: # <<<<<<<<<<<<<< + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: + */ + } + + /* "View.MemoryView":355 + * Py_INCREF(Py_None) + * + * if not __PYX_CYTHON_ATOMICS_ENABLED(): # <<<<<<<<<<<<<< + * global __pyx_memoryview_thread_locks_used + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: + */ + } + + /* "View.MemoryView":365 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":366 + * + * if flags & PyBUF_FORMAT: + * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') # <<<<<<<<<<<<<< + * else: + * self.dtype_is_object = dtype_is_object + */ + __pyx_t_2 = (((__pyx_v_self->view.format[0]) == 'O') != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L12_bool_binop_done; + } + __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L12_bool_binop_done:; + __pyx_v_self->dtype_is_object = __pyx_t_1; + + /* "View.MemoryView":365 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') + * else: + */ + goto __pyx_L11; + } + + /* "View.MemoryView":368 + * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') + * else: + * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + */ + /*else*/ { + __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; + } + __pyx_L11:; + + /* "View.MemoryView":370 + * self.dtype_is_object = dtype_is_object + * + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL + */ + __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); + + /* "View.MemoryView":372 + * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( + * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) + * self.typeinfo = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(memoryview self): + */ + __pyx_v_self->typeinfo = NULL; + + /* "View.MemoryView":346 + * cdef __Pyx_TypeInfo *typeinfo + * + * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< + * self.obj = obj + * self.flags = flags + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":374 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + +/* Python wrapper */ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + PyThread_type_lock __pyx_t_6; + PyThread_type_lock __pyx_t_7; + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":375 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * elif (<__pyx_buffer *> &self.view).obj == Py_None: + */ + __pyx_t_1 = (__pyx_v_self->obj != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":376 + * def __dealloc__(memoryview self): + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * elif (<__pyx_buffer *> &self.view).obj == Py_None: + * + */ + __Pyx_ReleaseBuffer((&__pyx_v_self->view)); + + /* "View.MemoryView":375 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< + * __Pyx_ReleaseBuffer(&self.view) + * elif (<__pyx_buffer *> &self.view).obj == Py_None: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":377 + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< + * + * (<__pyx_buffer *> &self.view).obj = NULL + */ + __pyx_t_2 = ((((Py_buffer *)(&__pyx_v_self->view))->obj == Py_None) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":379 + * elif (<__pyx_buffer *> &self.view).obj == Py_None: + * + * (<__pyx_buffer *> &self.view).obj = NULL # <<<<<<<<<<<<<< + * Py_DECREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_self->view))->obj = NULL; + + /* "View.MemoryView":380 + * + * (<__pyx_buffer *> &self.view).obj = NULL + * Py_DECREF(Py_None) # <<<<<<<<<<<<<< + * + * cdef int i + */ + Py_DECREF(Py_None); + + /* "View.MemoryView":377 + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< + * + * (<__pyx_buffer *> &self.view).obj = NULL + */ + } + __pyx_L3:; + + /* "View.MemoryView":384 + * cdef int i + * global __pyx_memoryview_thread_locks_used + * if self.lock != NULL: # <<<<<<<<<<<<<< + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: + */ + __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":385 + * global __pyx_memoryview_thread_locks_used + * if self.lock != NULL: + * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< + * if __pyx_memoryview_thread_locks[i] is self.lock: + * __pyx_memoryview_thread_locks_used -= 1 + */ + __pyx_t_3 = __pyx_memoryview_thread_locks_used; + __pyx_t_4 = __pyx_t_3; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_i = __pyx_t_5; + + /* "View.MemoryView":386 + * if self.lock != NULL: + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: + */ + __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":387 + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: + * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< + * if i != __pyx_memoryview_thread_locks_used: + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + */ + __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); + + /* "View.MemoryView":388 + * if __pyx_memoryview_thread_locks[i] is self.lock: + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) + */ + __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":390 + * if i != __pyx_memoryview_thread_locks_used: + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) # <<<<<<<<<<<<<< + * break + * else: + */ + __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); + __pyx_t_7 = (__pyx_memoryview_thread_locks[__pyx_v_i]); + + /* "View.MemoryView":389 + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) + * break + */ + (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_6; + (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_7; + + /* "View.MemoryView":388 + * if __pyx_memoryview_thread_locks[i] is self.lock: + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) + */ + } + + /* "View.MemoryView":391 + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) + * break # <<<<<<<<<<<<<< + * else: + * PyThread_free_lock(self.lock) + */ + goto __pyx_L6_break; + + /* "View.MemoryView":386 + * if self.lock != NULL: + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: + */ + } + } + /*else*/ { + + /* "View.MemoryView":393 + * break + * else: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + } + __pyx_L6_break:; + + /* "View.MemoryView":384 + * cdef int i + * global __pyx_memoryview_thread_locks_used + * if self.lock != NULL: # <<<<<<<<<<<<<< + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: + */ + } + + /* "View.MemoryView":374 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":395 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + char *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":397 + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< + * + * for dim, idx in enumerate(index): + */ + __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); + + /* "View.MemoryView":399 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + __pyx_t_1 = 0; + if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { + __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 399, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 399, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(2, 399, __pyx_L1_error) + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 399, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + } else { + if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(2, 399, __pyx_L1_error) + #else + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 399, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + } + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(2, 399, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_v_dim = __pyx_t_1; + __pyx_t_1 = (__pyx_t_1 + 1); + + /* "View.MemoryView":400 + * + * for dim, idx in enumerate(index): + * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< + * + * return itemp + */ + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 400, __pyx_L1_error) + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == ((char *)NULL))) __PYX_ERR(2, 400, __pyx_L1_error) + __pyx_v_itemp = __pyx_t_7; + + /* "View.MemoryView":399 + * cdef char *itemp = self.view.buf + * + * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + */ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":402 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + /* "View.MemoryView":395 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":405 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ +static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_indices = NULL; + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + char *__pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":406 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":407 + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: + * return self # <<<<<<<<<<<<<< + * + * have_slices, indices = _unellipsify(index, self.view.ndim) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __pyx_r = ((PyObject *)__pyx_v_self); + goto __pyx_L0; + + /* "View.MemoryView":406 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + } + + /* "View.MemoryView":409 + * return self + * + * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * cdef char *itemp + */ + __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 409, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (likely(__pyx_t_3 != Py_None)) { + PyObject* sequence = __pyx_t_3; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(2, 409, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 409, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 409, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 409, __pyx_L1_error) + } + __pyx_v_have_slices = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_indices = __pyx_t_5; + __pyx_t_5 = 0; + + /* "View.MemoryView":412 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(2, 412, __pyx_L1_error) + if (__pyx_t_2) { + + /* "View.MemoryView":413 + * cdef char *itemp + * if have_slices: + * return memview_slice(self, indices) # <<<<<<<<<<<<<< + * else: + * itemp = self.get_item_pointer(indices) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 413, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":412 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + } + + /* "View.MemoryView":415 + * return memview_slice(self, indices) + * else: + * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< + * return self.convert_item_to_object(itemp) + * + */ + /*else*/ { + __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == ((char *)NULL))) __PYX_ERR(2, 415, __pyx_L1_error) + __pyx_v_itemp = __pyx_t_6; + + /* "View.MemoryView":416 + * else: + * itemp = self.get_item_pointer(indices) + * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< + * + * def __setitem__(memoryview self, object index, object value): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 416, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":405 + * + * + * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< + * if index is Ellipsis: + * return self + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":418 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * if self.view.readonly: + * raise TypeError("Cannot assign to read-only memoryview") + */ + +/* Python wrapper */ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + PyObject *__pyx_v_have_slices = NULL; + PyObject *__pyx_v_obj = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":419 + * + * def __setitem__(memoryview self, object index, object value): + * if self.view.readonly: # <<<<<<<<<<<<<< + * raise TypeError("Cannot assign to read-only memoryview") + * + */ + __pyx_t_1 = (__pyx_v_self->view.readonly != 0); + if (unlikely(__pyx_t_1)) { + + /* "View.MemoryView":420 + * def __setitem__(memoryview self, object index, object value): + * if self.view.readonly: + * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< + * + * have_slices, index = _unellipsify(index, self.view.ndim) + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 420, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(2, 420, __pyx_L1_error) + + /* "View.MemoryView":419 + * + * def __setitem__(memoryview self, object index, object value): + * if self.view.readonly: # <<<<<<<<<<<<<< + * raise TypeError("Cannot assign to read-only memoryview") + * + */ + } + + /* "View.MemoryView":422 + * raise TypeError("Cannot assign to read-only memoryview") + * + * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< + * + * if have_slices: + */ + __pyx_t_2 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 422, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (likely(__pyx_t_2 != Py_None)) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(2, 422, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + #else + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 422, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 422, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 422, __pyx_L1_error) + } + __pyx_v_have_slices = __pyx_t_3; + __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_4); + __pyx_t_4 = 0; + + /* "View.MemoryView":424 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 424, __pyx_L1_error) + if (__pyx_t_1) { + + /* "View.MemoryView":425 + * + * if have_slices: + * obj = self.is_slice(value) # <<<<<<<<<<<<<< + * if obj: + * self.setitem_slice_assignment(self[index], obj) + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 425, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_obj = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":426 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 426, __pyx_L1_error) + if (__pyx_t_1) { + + /* "View.MemoryView":427 + * obj = self.is_slice(value) + * if obj: + * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< + * else: + * self.setitem_slice_assign_scalar(self[index], value) + */ + __pyx_t_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_2, __pyx_v_obj); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":426 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + goto __pyx_L5; + } + + /* "View.MemoryView":429 + * self.setitem_slice_assignment(self[index], obj) + * else: + * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< + * else: + * self.setitem_indexed(index, value) + */ + /*else*/ { + __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 429, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_memoryview_type))))) __PYX_ERR(2, 429, __pyx_L1_error) + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_4), __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 429, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L5:; + + /* "View.MemoryView":424 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + goto __pyx_L4; + } + + /* "View.MemoryView":431 + * self.setitem_slice_assign_scalar(self[index], value) + * else: + * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< + * + * cdef is_slice(self, obj): + */ + /*else*/ { + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 431, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L4:; + + /* "View.MemoryView":418 + * return self.convert_item_to_object(itemp) + * + * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< + * if self.view.readonly: + * raise TypeError("Cannot assign to read-only memoryview") + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_have_slices); + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":433 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + +static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":434 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":435 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_5); + /*try:*/ { + + /* "View.MemoryView":436 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_6 = __Pyx_PyInt_From_int(((__pyx_v_self->flags & (~PyBUF_WRITABLE)) | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 436, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":437 + * try: + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) # <<<<<<<<<<<<<< + * except TypeError: + * return None + */ + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 437, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":436 + * if not isinstance(obj, memoryview): + * try: + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< + * self.dtype_is_object) + * except TypeError: + */ + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 436, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_INCREF(__pyx_v_obj); + __Pyx_GIVEREF(__pyx_v_obj); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 436, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); + __pyx_t_7 = 0; + + /* "View.MemoryView":435 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + } + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + goto __pyx_L9_try_end; + __pyx_L4_error:; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "View.MemoryView":438 + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + * except TypeError: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_TypeError); + if (__pyx_t_9) { + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) __PYX_ERR(2, 438, __pyx_L6_except_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":439 + * self.dtype_is_object) + * except TypeError: + * return None # <<<<<<<<<<<<<< + * + * return obj + */ + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L7_except_return; + } + goto __pyx_L6_except_error; + __pyx_L6_except_error:; + + /* "View.MemoryView":435 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L1_error; + __pyx_L7_except_return:; + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); + goto __pyx_L0; + __pyx_L9_try_end:; + } + + /* "View.MemoryView":434 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, + */ + } + + /* "View.MemoryView":441 + * return None + * + * return obj # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assignment(self, dst, src): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_obj); + __pyx_r = __pyx_v_obj; + goto __pyx_L0; + + /* "View.MemoryView":433 + * self.setitem_indexed(index, value) + * + * cdef is_slice(self, obj): # <<<<<<<<<<<<<< + * if not isinstance(obj, memoryview): + * try: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_obj); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":443 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + +static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { + __Pyx_memviewslice __pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_src_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice *__pyx_t_1; + __Pyx_memviewslice *__pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":447 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) __PYX_ERR(2, 447, __pyx_L1_error) + __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 447, __pyx_L1_error) + + /* "View.MemoryView":448 + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< + * src.ndim, dst.ndim, self.dtype_is_object) + * + */ + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) __PYX_ERR(2, 448, __pyx_L1_error) + __pyx_t_2 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice)); if (unlikely(__pyx_t_2 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 448, __pyx_L1_error) + + /* "View.MemoryView":449 + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 449, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 449, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 449, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 449, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":447 + * cdef __Pyx_memviewslice src_slice + * + * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< + * get_slice_from_memview(dst, &dst_slice)[0], + * src.ndim, dst.ndim, self.dtype_is_object) + */ + __pyx_t_6 = __pyx_memoryview_copy_contents((__pyx_t_1[0]), (__pyx_t_2[0]), __pyx_t_4, __pyx_t_5, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(2, 447, __pyx_L1_error) + + /* "View.MemoryView":443 + * return obj + * + * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice dst_slice + * cdef __Pyx_memviewslice src_slice + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":451 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + +static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { + int __pyx_v_array[0x80]; + void *__pyx_v_tmp; + void *__pyx_v_item; + __Pyx_memviewslice *__pyx_v_dst_slice; + __Pyx_memviewslice __pyx_v_tmp_slice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice *__pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + char const *__pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":453 + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): + * cdef int array[128] + * cdef void *tmp = NULL # <<<<<<<<<<<<<< + * cdef void *item + * + */ + __pyx_v_tmp = NULL; + + /* "View.MemoryView":458 + * cdef __Pyx_memviewslice *dst_slice + * cdef __Pyx_memviewslice tmp_slice + * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< + * + * if self.view.itemsize > sizeof(array): + */ + __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 458, __pyx_L1_error) + __pyx_v_dst_slice = __pyx_t_1; + + /* "View.MemoryView":460 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + */ + __pyx_t_2 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":461 + * + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< + * if tmp == NULL: + * raise MemoryError + */ + __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); + + /* "View.MemoryView":462 + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + __pyx_t_2 = ((__pyx_v_tmp == NULL) != 0); + if (unlikely(__pyx_t_2)) { + + /* "View.MemoryView":463 + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); __PYX_ERR(2, 463, __pyx_L1_error) + + /* "View.MemoryView":462 + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + } + + /* "View.MemoryView":464 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + + /* "View.MemoryView":460 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":466 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * try: + */ + /*else*/ { + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":468 + * item = array + * + * try: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * ( item)[0] = value + */ + /*try:*/ { + + /* "View.MemoryView":469 + * + * try: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + __pyx_t_2 = (__pyx_v_self->dtype_is_object != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":470 + * try: + * if self.dtype_is_object: + * ( item)[0] = value # <<<<<<<<<<<<<< + * else: + * self.assign_item_from_object( item, value) + */ + (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + + /* "View.MemoryView":469 + * + * try: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + goto __pyx_L8; + } + + /* "View.MemoryView":472 + * ( item)[0] = value + * else: + * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< + * + * + */ + /*else*/ { + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 472, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L8:; + + /* "View.MemoryView":476 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + __pyx_t_2 = ((__pyx_v_self->view.suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":477 + * + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + * item, self.dtype_is_object) + */ + __pyx_t_3 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 477, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":476 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ + } + + /* "View.MemoryView":478 + * if self.view.suboffsets != NULL: + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< + * item, self.dtype_is_object) + * finally: + */ + __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); + } + + /* "View.MemoryView":481 + * item, self.dtype_is_object) + * finally: + * PyMem_Free(tmp) # <<<<<<<<<<<<<< + * + * cdef setitem_indexed(self, index, value): + */ + /*finally:*/ { + /*normal exit:*/{ + PyMem_Free(__pyx_v_tmp); + goto __pyx_L7; + } + __pyx_L6_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9) < 0)) __Pyx_ErrFetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __Pyx_XGOTREF(__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_12); + __pyx_t_4 = __pyx_lineno; __pyx_t_5 = __pyx_clineno; __pyx_t_6 = __pyx_filename; + { + PyMem_Free(__pyx_v_tmp); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_ExceptionReset(__pyx_t_10, __pyx_t_11, __pyx_t_12); + } + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ErrRestore(__pyx_t_7, __pyx_t_8, __pyx_t_9); + __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; + __pyx_lineno = __pyx_t_4; __pyx_clineno = __pyx_t_5; __pyx_filename = __pyx_t_6; + goto __pyx_L1_error; + } + __pyx_L7:; + } + + /* "View.MemoryView":451 + * src.ndim, dst.ndim, self.dtype_is_object) + * + * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< + * cdef int array[128] + * cdef void *tmp = NULL + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":483 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + +static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { + char *__pyx_v_itemp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + char *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":484 + * + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< + * self.assign_item_from_object(itemp, value) + * + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == ((char *)NULL))) __PYX_ERR(2, 484, __pyx_L1_error) + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":485 + * cdef setitem_indexed(self, index, value): + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 485, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":483 + * PyMem_Free(tmp) + * + * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< + * cdef char *itemp = self.get_item_pointer(index) + * self.assign_item_from_object(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":487 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_v_struct = NULL; + PyObject *__pyx_v_bytesitem = 0; + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":490 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef bytes bytesitem + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 490, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":493 + * cdef bytes bytesitem + * + * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< + * try: + * result = struct.unpack(self.view.format, bytesitem) + */ + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 493, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":494 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "View.MemoryView":495 + * bytesitem = itemp[:self.view.itemsize] + * try: + * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< + * except struct.error: + * raise ValueError("Unable to convert item to object") + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 495, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 495, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = NULL; + __pyx_t_8 = 0; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + __pyx_t_8 = 1; + } + } + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_5)) { + PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; + __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 495, __pyx_L3_error) + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { + PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; + __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 495, __pyx_L3_error) + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else + #endif + { + __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 495, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_9); + if (__pyx_t_7) { + __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; + } + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); + __Pyx_INCREF(__pyx_v_bytesitem); + __Pyx_GIVEREF(__pyx_v_bytesitem); + PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); + __pyx_t_6 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 495, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_result = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":494 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + } + + /* "View.MemoryView":499 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + /*else:*/ { + __pyx_t_10 = strlen(__pyx_v_self->view.format); + __pyx_t_11 = ((__pyx_t_10 == 1) != 0); + if (__pyx_t_11) { + + /* "View.MemoryView":500 + * else: + * if len(self.view.format) == 1: + * return result[0] # <<<<<<<<<<<<<< + * return result + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 500, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L6_except_return; + + /* "View.MemoryView":499 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + } + + /* "View.MemoryView":501 + * if len(self.view.format) == 1: + * return result[0] + * return result # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L6_except_return; + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "View.MemoryView":496 + * try: + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: # <<<<<<<<<<<<<< + * raise ValueError("Unable to convert item to object") + * else: + */ + __Pyx_ErrFetch(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 496, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = __Pyx_PyErr_GivenExceptionMatches(__pyx_t_1, __pyx_t_6); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_ErrRestore(__pyx_t_1, __pyx_t_5, __pyx_t_9); + __pyx_t_1 = 0; __pyx_t_5 = 0; __pyx_t_9 = 0; + if (__pyx_t_8) { + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_5, &__pyx_t_1) < 0) __PYX_ERR(2, 496, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":497 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 497, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __PYX_ERR(2, 497, __pyx_L5_except_error) + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + + /* "View.MemoryView":494 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L6_except_return:; + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); + goto __pyx_L0; + } + + /* "View.MemoryView":487 + * self.assign_item_from_object(itemp, value) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesitem); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":503 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + +static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_v_struct = NULL; + char __pyx_v_c; + PyObject *__pyx_v_bytesvalue = 0; + Py_ssize_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + Py_ssize_t __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + char *__pyx_t_11; + char *__pyx_t_12; + char *__pyx_t_13; + char *__pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":506 + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + * import struct # <<<<<<<<<<<<<< + * cdef char c + * cdef bytes bytesvalue + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 506, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":511 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + __pyx_t_2 = PyTuple_Check(__pyx_v_value); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "View.MemoryView":512 + * + * if isinstance(value, tuple): + * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< + * else: + * bytesvalue = struct.pack(self.view.format, value) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 512, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 512, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 512, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 512, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 512, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 512, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(2, 512, __pyx_L1_error) + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "View.MemoryView":511 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":514 + * bytesvalue = struct.pack(self.view.format, *value) + * else: + * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< + * + * for i, c in enumerate(bytesvalue): + */ + /*else*/ { + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 514, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 514, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = NULL; + __pyx_t_7 = 0; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + __pyx_t_7 = 1; + } + } + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_6)) { + PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; + __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 514, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { + PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; + __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 514, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else + #endif + { + __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 514, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + if (__pyx_t_5) { + __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; + } + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); + __Pyx_INCREF(__pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); + __pyx_t_1 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 514, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(2, 514, __pyx_L1_error) + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":516 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_9 = 0; + if (unlikely(__pyx_v_bytesvalue == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + __PYX_ERR(2, 516, __pyx_L1_error) + } + __Pyx_INCREF(__pyx_v_bytesvalue); + __pyx_t_10 = __pyx_v_bytesvalue; + __pyx_t_12 = PyBytes_AS_STRING(__pyx_t_10); + __pyx_t_13 = (__pyx_t_12 + PyBytes_GET_SIZE(__pyx_t_10)); + for (__pyx_t_14 = __pyx_t_12; __pyx_t_14 < __pyx_t_13; __pyx_t_14++) { + __pyx_t_11 = __pyx_t_14; + __pyx_v_c = (__pyx_t_11[0]); + + /* "View.MemoryView":517 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_9; + + /* "View.MemoryView":516 + * bytesvalue = struct.pack(self.view.format, value) + * + * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< + * itemp[i] = c + * + */ + __pyx_t_9 = (__pyx_t_9 + 1); + + /* "View.MemoryView":517 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; + } + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "View.MemoryView":503 + * return result + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * """Only used if instantiated manually by the user, or if Cython doesn't + * know how to convert the type""" + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_struct); + __Pyx_XDECREF(__pyx_v_bytesvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":520 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_WRITABLE and self.view.readonly: + * raise ValueError("Cannot create writable memory view from read-only memoryview") + */ + +/* Python wrapper */ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t *__pyx_t_4; + char *__pyx_t_5; + void *__pyx_t_6; + int __pyx_t_7; + Py_ssize_t __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + if (__pyx_v_info == NULL) { + PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); + return -1; + } + __Pyx_RefNannySetupContext("__getbuffer__", 0); + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + + /* "View.MemoryView":521 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< + * raise ValueError("Cannot create writable memory view from read-only memoryview") + * + */ + __pyx_t_2 = ((__pyx_v_flags & PyBUF_WRITABLE) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_2 = (__pyx_v_self->view.readonly != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L4_bool_binop_done:; + if (unlikely(__pyx_t_1)) { + + /* "View.MemoryView":522 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_WRITABLE and self.view.readonly: + * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< + * + * if flags & PyBUF_ND: + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 522, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(2, 522, __pyx_L1_error) + + /* "View.MemoryView":521 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< + * raise ValueError("Cannot create writable memory view from read-only memoryview") + * + */ + } + + /* "View.MemoryView":524 + * raise ValueError("Cannot create writable memory view from read-only memoryview") + * + * if flags & PyBUF_ND: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_ND) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":525 + * + * if flags & PyBUF_ND: + * info.shape = self.view.shape # <<<<<<<<<<<<<< + * else: + * info.shape = NULL + */ + __pyx_t_4 = __pyx_v_self->view.shape; + __pyx_v_info->shape = __pyx_t_4; + + /* "View.MemoryView":524 + * raise ValueError("Cannot create writable memory view from read-only memoryview") + * + * if flags & PyBUF_ND: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ + goto __pyx_L6; + } + + /* "View.MemoryView":527 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + /*else*/ { + __pyx_v_info->shape = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":529 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":530 + * + * if flags & PyBUF_STRIDES: + * info.strides = self.view.strides # <<<<<<<<<<<<<< + * else: + * info.strides = NULL + */ + __pyx_t_4 = __pyx_v_self->view.strides; + __pyx_v_info->strides = __pyx_t_4; + + /* "View.MemoryView":529 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + goto __pyx_L7; + } + + /* "View.MemoryView":532 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + /*else*/ { + __pyx_v_info->strides = NULL; + } + __pyx_L7:; + + /* "View.MemoryView":534 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":535 + * + * if flags & PyBUF_INDIRECT: + * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< + * else: + * info.suboffsets = NULL + */ + __pyx_t_4 = __pyx_v_self->view.suboffsets; + __pyx_v_info->suboffsets = __pyx_t_4; + + /* "View.MemoryView":534 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + goto __pyx_L8; + } + + /* "View.MemoryView":537 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + /*else*/ { + __pyx_v_info->suboffsets = NULL; + } + __pyx_L8:; + + /* "View.MemoryView":539 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":540 + * + * if flags & PyBUF_FORMAT: + * info.format = self.view.format # <<<<<<<<<<<<<< + * else: + * info.format = NULL + */ + __pyx_t_5 = __pyx_v_self->view.format; + __pyx_v_info->format = __pyx_t_5; + + /* "View.MemoryView":539 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + goto __pyx_L9; + } + + /* "View.MemoryView":542 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + /*else*/ { + __pyx_v_info->format = NULL; + } + __pyx_L9:; + + /* "View.MemoryView":544 + * info.format = NULL + * + * info.buf = self.view.buf # <<<<<<<<<<<<<< + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + */ + __pyx_t_6 = __pyx_v_self->view.buf; + __pyx_v_info->buf = __pyx_t_6; + + /* "View.MemoryView":545 + * + * info.buf = self.view.buf + * info.ndim = self.view.ndim # <<<<<<<<<<<<<< + * info.itemsize = self.view.itemsize + * info.len = self.view.len + */ + __pyx_t_7 = __pyx_v_self->view.ndim; + __pyx_v_info->ndim = __pyx_t_7; + + /* "View.MemoryView":546 + * info.buf = self.view.buf + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< + * info.len = self.view.len + * info.readonly = self.view.readonly + */ + __pyx_t_8 = __pyx_v_self->view.itemsize; + __pyx_v_info->itemsize = __pyx_t_8; + + /* "View.MemoryView":547 + * info.ndim = self.view.ndim + * info.itemsize = self.view.itemsize + * info.len = self.view.len # <<<<<<<<<<<<<< + * info.readonly = self.view.readonly + * info.obj = self + */ + __pyx_t_8 = __pyx_v_self->view.len; + __pyx_v_info->len = __pyx_t_8; + + /* "View.MemoryView":548 + * info.itemsize = self.view.itemsize + * info.len = self.view.len + * info.readonly = self.view.readonly # <<<<<<<<<<<<<< + * info.obj = self + * + */ + __pyx_t_1 = __pyx_v_self->view.readonly; + __pyx_v_info->readonly = __pyx_t_1; + + /* "View.MemoryView":549 + * info.len = self.view.len + * info.readonly = self.view.readonly + * info.obj = self # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_INCREF(((PyObject *)__pyx_v_self)); + __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "View.MemoryView":520 + * + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< + * if flags & PyBUF_WRITABLE and self.view.readonly: + * raise ValueError("Cannot create writable memory view from read-only memoryview") + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; + } + __pyx_L2:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":555 + * + * @property + * def T(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":556 + * @property + * def T(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result + */ + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 556, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) __PYX_ERR(2, 556, __pyx_L1_error) + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":557 + * def T(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(2, 557, __pyx_L1_error) + + /* "View.MemoryView":558 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":555 + * + * @property + * def T(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":561 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":562 + * @property + * def base(self): + * return self.obj # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->obj); + __pyx_r = __pyx_v_self->obj; + goto __pyx_L0; + + /* "View.MemoryView":561 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":565 + * + * @property + * def shape(self): # <<<<<<<<<<<<<< + * return tuple([length for length in self.view.shape[:self.view.ndim]]) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_length; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t *__pyx_t_2; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":566 + * @property + * def shape(self): + * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 566, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); + for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { + __pyx_t_2 = __pyx_t_4; + __pyx_v_length = (__pyx_t_2[0]); + __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 566, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(2, 566, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 566, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":565 + * + * @property + * def shape(self): # <<<<<<<<<<<<<< + * return tuple([length for length in self.view.shape[:self.view.ndim]]) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":569 + * + * @property + * def strides(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_stride; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":570 + * @property + * def strides(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); + if (unlikely(__pyx_t_1)) { + + /* "View.MemoryView":572 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) + */ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 572, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(2, 572, __pyx_L1_error) + + /* "View.MemoryView":570 + * @property + * def strides(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + } + + /* "View.MemoryView":574 + * raise ValueError("Buffer view does not expose strides") + * + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 574, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); + for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { + __pyx_t_3 = __pyx_t_5; + __pyx_v_stride = (__pyx_t_3[0]); + __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 574, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(2, 574, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 574, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; + goto __pyx_L0; + + /* "View.MemoryView":569 + * + * @property + * def strides(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":577 + * + * @property + * def suboffsets(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_suboffset; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + Py_ssize_t *__pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":578 + * @property + * def suboffsets(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return (-1,) * self.view.ndim + * + */ + __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":579 + * def suboffsets(self): + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 579, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__14, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 579, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":578 + * @property + * def suboffsets(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return (-1,) * self.view.ndim + * + */ + } + + /* "View.MemoryView":581 + * return (-1,) * self.view.ndim + * + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 581, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); + for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { + __pyx_t_4 = __pyx_t_6; + __pyx_v_suboffset = (__pyx_t_4[0]); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 581, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(2, 581, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 581, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":577 + * + * @property + * def suboffsets(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":584 + * + * @property + * def ndim(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":585 + * @property + * def ndim(self): + * return self.view.ndim # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 585, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":584 + * + * @property + * def ndim(self): # <<<<<<<<<<<<<< + * return self.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":588 + * + * @property + * def itemsize(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":589 + * @property + * def itemsize(self): + * return self.view.itemsize # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 589, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":588 + * + * @property + * def itemsize(self): # <<<<<<<<<<<<<< + * return self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":592 + * + * @property + * def nbytes(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":593 + * @property + * def nbytes(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 593, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 593, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 593, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":592 + * + * @property + * def nbytes(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":596 + * + * @property + * def size(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":597 + * @property + * def size(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + __pyx_t_1 = (__pyx_v_self->_size == Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":598 + * def size(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< + * + * for length in self.view.shape[:self.view.ndim]: + */ + __Pyx_INCREF(__pyx_int_1); + __pyx_v_result = __pyx_int_1; + + /* "View.MemoryView":600 + * result = 1 + * + * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< + * result *= length + * + */ + __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); + for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { + __pyx_t_3 = __pyx_t_5; + __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 600, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); + __pyx_t_6 = 0; + + /* "View.MemoryView":601 + * + * for length in self.view.shape[:self.view.ndim]: + * result *= length # <<<<<<<<<<<<<< + * + * self._size = result + */ + __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 601, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); + __pyx_t_6 = 0; + } + + /* "View.MemoryView":603 + * result *= length + * + * self._size = result # <<<<<<<<<<<<<< + * + * return self._size + */ + __Pyx_INCREF(__pyx_v_result); + __Pyx_GIVEREF(__pyx_v_result); + __Pyx_GOTREF(__pyx_v_self->_size); + __Pyx_DECREF(__pyx_v_self->_size); + __pyx_v_self->_size = __pyx_v_result; + + /* "View.MemoryView":597 + * @property + * def size(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + } + + /* "View.MemoryView":605 + * self._size = result + * + * return self._size # <<<<<<<<<<<<<< + * + * def __len__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->_size); + __pyx_r = __pyx_v_self->_size; + goto __pyx_L0; + + /* "View.MemoryView":596 + * + * @property + * def size(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":607 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + +/* Python wrapper */ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("__len__", 0); + + /* "View.MemoryView":608 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":609 + * def __len__(self): + * if self.view.ndim >= 1: + * return self.view.shape[0] # <<<<<<<<<<<<<< + * + * return 0 + */ + __pyx_r = (__pyx_v_self->view.shape[0]); + goto __pyx_L0; + + /* "View.MemoryView":608 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + } + + /* "View.MemoryView":611 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":607 + * return self._size + * + * def __len__(self): # <<<<<<<<<<<<<< + * if self.view.ndim >= 1: + * return self.view.shape[0] + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":613 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":614 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 614, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 614, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 614, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":615 + * def __repr__(self): + * return "" % (self.base.__class__.__name__, + * id(self)) # <<<<<<<<<<<<<< + * + * def __str__(self): + */ + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 615, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + /* "View.MemoryView":614 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 614, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 614, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":613 + * return 0 + * + * def __repr__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__, + * id(self)) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":617 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":618 + * + * def __str__(self): + * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 618, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 618, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 618, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 618, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 618, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":617 + * id(self)) + * + * def __str__(self): # <<<<<<<<<<<<<< + * return "" % (self.base.__class__.__name__,) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":621 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":624 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice[0], 'C', self.view.ndim) + * + */ + __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 624, __pyx_L1_error) + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":625 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice[0], 'C', self.view.ndim) # <<<<<<<<<<<<<< + * + * def is_f_contig(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 625, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":621 + * + * + * def is_c_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":627 + * return slice_is_contig(mslice[0], 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice *__pyx_v_mslice; + __Pyx_memviewslice __pyx_v_tmp; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice *__pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":630 + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice[0], 'F', self.view.ndim) + * + */ + __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 630, __pyx_L1_error) + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":631 + * cdef __Pyx_memviewslice tmp + * mslice = get_slice_from_memview(self, &tmp) + * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< + * + * def copy(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 631, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":627 + * return slice_is_contig(mslice[0], 'C', self.view.ndim) + * + * def is_f_contig(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice *mslice + * cdef __Pyx_memviewslice tmp + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":633 + * return slice_is_contig(mslice[0], 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_mslice; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":635 + * def copy(self): + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &mslice) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); + + /* "View.MemoryView":637 + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + * + * slice_copy(self, &mslice) # <<<<<<<<<<<<<< + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); + + /* "View.MemoryView":638 + * + * slice_copy(self, &mslice) + * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_C_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), ((char *)"c"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(2, 638, __pyx_L1_error) + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":643 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< + * + * def copy_fortran(self): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 643, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":633 + * return slice_is_contig(mslice[0], 'F', self.view.ndim) + * + * def copy(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice mslice + * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":645 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + +/* Python wrapper */ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_memviewslice __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":647 + * def copy_fortran(self): + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< + * + * slice_copy(self, &src) + */ + __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); + + /* "View.MemoryView":649 + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + * + * slice_copy(self, &src) # <<<<<<<<<<<<<< + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, + * self.view.itemsize, + */ + __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); + + /* "View.MemoryView":650 + * + * slice_copy(self, &src) + * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< + * self.view.itemsize, + * flags|PyBUF_F_CONTIGUOUS, + */ + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), ((char *)"fortran"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(2, 650, __pyx_L1_error) + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":655 + * self.dtype_is_object) + * + * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 655, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":645 + * return memoryview_copy_from_slice(self, &mslice) + * + * def copy_fortran(self): # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice src, dst + * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_memoryview___reduce_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(2, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_memoryview_2__setstate_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(2, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":659 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":660 + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< + * result.typeinfo = typeinfo + * return result + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 660, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 660, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 660, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_o); + __Pyx_GIVEREF(__pyx_v_o); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 660, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":661 + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_v_result->typeinfo = __pyx_v_typeinfo; + + /* "View.MemoryView":662 + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_check') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":659 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":665 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + +static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_RefNannySetupContext("memoryview_check", 0); + + /* "View.MemoryView":666 + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): + * return isinstance(o, memoryview) # <<<<<<<<<<<<<< + * + * cdef tuple _unellipsify(object index, int ndim): + */ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, __pyx_memoryview_type); + __pyx_r = __pyx_t_1; + goto __pyx_L0; + + /* "View.MemoryView":665 + * + * @cname('__pyx_memoryview_check') + * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< + * return isinstance(o, memoryview) + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":668 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + +static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { + PyObject *__pyx_v_tup = NULL; + PyObject *__pyx_v_result = NULL; + int __pyx_v_have_slices; + int __pyx_v_seen_ellipsis; + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_item = NULL; + Py_ssize_t __pyx_v_nslices; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + Py_ssize_t __pyx_t_8; + int __pyx_t_9; + int __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":673 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + __pyx_t_1 = PyTuple_Check(__pyx_v_index); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":674 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 674, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_index); + __Pyx_GIVEREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); + __pyx_v_tup = __pyx_t_3; + __pyx_t_3 = 0; + + /* "View.MemoryView":673 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":676 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + /*else*/ { + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":678 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 678, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":679 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_v_have_slices = 0; + + /* "View.MemoryView":680 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":681 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_3 = __pyx_int_0; + if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { + __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 681, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 681, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_4))) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(2, 681, __pyx_L1_error) + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 681, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #endif + } else { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(2, 681, __pyx_L1_error) + #else + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 681, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #endif + } + } else { + __pyx_t_7 = __pyx_t_6(__pyx_t_4); + if (unlikely(!__pyx_t_7)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(2, 681, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); + __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 681, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_t_7; + __pyx_t_7 = 0; + + /* "View.MemoryView":682 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":683 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":684 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == ((Py_ssize_t)-1))) __PYX_ERR(2, 684, __pyx_L1_error) + __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 684, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { + __Pyx_INCREF(__pyx_slice__17); + __Pyx_GIVEREF(__pyx_slice__17); + PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__17); + } + } + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 684, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":685 + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True # <<<<<<<<<<<<<< + * else: + * result.append(slice(None)) + */ + __pyx_v_seen_ellipsis = 1; + + /* "View.MemoryView":683 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ + goto __pyx_L7; + } + + /* "View.MemoryView":687 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + /*else*/ { + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__17); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 687, __pyx_L1_error) + } + __pyx_L7:; + + /* "View.MemoryView":688 + * else: + * result.append(slice(None)) + * have_slices = True # <<<<<<<<<<<<<< + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + */ + __pyx_v_have_slices = 1; + + /* "View.MemoryView":682 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ + goto __pyx_L6; + } + + /* "View.MemoryView":690 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + /*else*/ { + __pyx_t_2 = PySlice_Check(__pyx_v_item); + __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); + if (__pyx_t_10) { + } else { + __pyx_t_1 = __pyx_t_10; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); + __pyx_t_1 = __pyx_t_10; + __pyx_L9_bool_binop_done:; + if (unlikely(__pyx_t_1)) { + + /* "View.MemoryView":691 + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): + * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< + * + * have_slices = have_slices or isinstance(item, slice) + */ + __pyx_t_7 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 691, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_11 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(2, 691, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_Raise(__pyx_t_11, 0, 0, 0); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __PYX_ERR(2, 691, __pyx_L1_error) + + /* "View.MemoryView":690 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ + } + + /* "View.MemoryView":693 + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< + * result.append(item) + * + */ + __pyx_t_10 = (__pyx_v_have_slices != 0); + if (!__pyx_t_10) { + } else { + __pyx_t_1 = __pyx_t_10; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_10 = PySlice_Check(__pyx_v_item); + __pyx_t_2 = (__pyx_t_10 != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L11_bool_binop_done:; + __pyx_v_have_slices = __pyx_t_1; + + /* "View.MemoryView":694 + * + * have_slices = have_slices or isinstance(item, slice) + * result.append(item) # <<<<<<<<<<<<<< + * + * nslices = ndim - len(result) + */ + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 694, __pyx_L1_error) + } + __pyx_L6:; + + /* "View.MemoryView":681 + * have_slices = False + * seen_ellipsis = False + * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< + * if item is Ellipsis: + * if not seen_ellipsis: + */ + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":696 + * result.append(item) + * + * nslices = ndim - len(result) # <<<<<<<<<<<<<< + * if nslices: + * result.extend([slice(None)] * nslices) + */ + __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(2, 696, __pyx_L1_error) + __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); + + /* "View.MemoryView":697 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_1 = (__pyx_v_nslices != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":698 + * nslices = ndim - len(result) + * if nslices: + * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< + * + * return have_slices or nslices, tuple(result) + */ + __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 698, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { + __Pyx_INCREF(__pyx_slice__17); + __Pyx_GIVEREF(__pyx_slice__17); + PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__17); + } + } + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 698, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":697 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + } + + /* "View.MemoryView":700 + * result.extend([slice(None)] * nslices) + * + * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + */ + __Pyx_XDECREF(__pyx_r); + if (!__pyx_v_have_slices) { + } else { + __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 700, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L14_bool_binop_done; + } + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 700, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_L14_bool_binop_done:; + __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 700, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(2, 700, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_3); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_4); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_r = ((PyObject*)__pyx_t_11); + __pyx_t_11 = 0; + goto __pyx_L0; + + /* "View.MemoryView":668 + * return isinstance(o, memoryview) + * + * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< + * """ + * Replace all ellipses with full slices and fill incomplete indices with + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_tup); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_item); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":702 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + */ + +static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { + Py_ssize_t __pyx_v_suboffset; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + Py_ssize_t *__pyx_t_2; + Py_ssize_t *__pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":703 + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< + * if suboffset >= 0: + * raise ValueError("Indirect dimensions not supported") + */ + __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); + for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { + __pyx_t_1 = __pyx_t_3; + __pyx_v_suboffset = (__pyx_t_1[0]); + + /* "View.MemoryView":704 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); + if (unlikely(__pyx_t_4)) { + + /* "View.MemoryView":705 + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 705, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(2, 705, __pyx_L1_error) + + /* "View.MemoryView":704 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ + } + } + + /* "View.MemoryView":702 + * return have_slices or nslices, tuple(result) + * + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":712 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + +static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { + int __pyx_v_new_ndim; + int __pyx_v_suboffset_dim; + int __pyx_v_dim; + __Pyx_memviewslice __pyx_v_src; + __Pyx_memviewslice __pyx_v_dst; + __Pyx_memviewslice *__pyx_v_p_src; + struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; + __Pyx_memviewslice *__pyx_v_p_dst; + int *__pyx_v_p_suboffset_dim; + Py_ssize_t __pyx_v_start; + Py_ssize_t __pyx_v_stop; + Py_ssize_t __pyx_v_step; + int __pyx_v_have_start; + int __pyx_v_have_stop; + int __pyx_v_have_step; + PyObject *__pyx_v_index = NULL; + struct __pyx_memoryview_obj *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + struct __pyx_memoryview_obj *__pyx_t_4; + char *__pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + int __pyx_t_11; + Py_ssize_t __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":713 + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): + * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< + * cdef bint negative_step + * cdef __Pyx_memviewslice src, dst + */ + __pyx_v_new_ndim = 0; + __pyx_v_suboffset_dim = -1; + + /* "View.MemoryView":720 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); + + /* "View.MemoryView":724 + * cdef _memoryviewslice memviewsliceobj + * + * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(!Py_OptimizeFlag)) { + if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { + PyErr_SetNone(PyExc_AssertionError); + __PYX_ERR(2, 724, __pyx_L1_error) + } + } + #endif + + /* "View.MemoryView":726 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":727 + * + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview # <<<<<<<<<<<<<< + * p_src = &memviewsliceobj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(2, 727, __pyx_L1_error) + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":728 + * if isinstance(memview, _memoryviewslice): + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, &src) + */ + __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + + /* "View.MemoryView":726 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + goto __pyx_L3; + } + + /* "View.MemoryView":730 + * p_src = &memviewsliceobj.from_slice + * else: + * slice_copy(memview, &src) # <<<<<<<<<<<<<< + * p_src = &src + * + */ + /*else*/ { + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); + + /* "View.MemoryView":731 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":737 + * + * + * dst.memview = p_src.memview # <<<<<<<<<<<<<< + * dst.data = p_src.data + * + */ + __pyx_t_4 = __pyx_v_p_src->memview; + __pyx_v_dst.memview = __pyx_t_4; + + /* "View.MemoryView":738 + * + * dst.memview = p_src.memview + * dst.data = p_src.data # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_v_p_src->data; + __pyx_v_dst.data = __pyx_t_5; + + /* "View.MemoryView":743 + * + * + * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< + * cdef int *p_suboffset_dim = &suboffset_dim + * cdef Py_ssize_t start, stop, step + */ + __pyx_v_p_dst = (&__pyx_v_dst); + + /* "View.MemoryView":744 + * + * cdef __Pyx_memviewslice *p_dst = &dst + * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< + * cdef Py_ssize_t start, stop, step + * cdef bint have_start, have_stop, have_step + */ + __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); + + /* "View.MemoryView":748 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + __pyx_t_6 = 0; + if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { + __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 748, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 748, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_8)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(2, 748, __pyx_L1_error) + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 748, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + #endif + } else { + if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(2, 748, __pyx_L1_error) + #else + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 748, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + #endif + } + } else { + __pyx_t_9 = __pyx_t_8(__pyx_t_3); + if (unlikely(!__pyx_t_9)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(2, 748, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); + __pyx_t_9 = 0; + __pyx_v_dim = __pyx_t_6; + __pyx_t_6 = (__pyx_t_6 + 1); + + /* "View.MemoryView":749 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":753 + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< + * 0, 0, 0, # have_{start,stop,step} + * False) + */ + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 753, __pyx_L1_error) + + /* "View.MemoryView":750 + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(2, 750, __pyx_L1_error) + + /* "View.MemoryView":749 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ + goto __pyx_L6; + } + + /* "View.MemoryView":756 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + __pyx_t_2 = (__pyx_v_index == Py_None); + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":757 + * False) + * elif index is None: + * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + */ + (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; + + /* "View.MemoryView":758 + * elif index is None: + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 + */ + (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; + + /* "View.MemoryView":759 + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< + * new_ndim += 1 + * else: + */ + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1L; + + /* "View.MemoryView":760 + * p_dst.strides[new_ndim] = 0 + * p_dst.suboffsets[new_ndim] = -1 + * new_ndim += 1 # <<<<<<<<<<<<<< + * else: + * start = index.start or 0 + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + + /* "View.MemoryView":756 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ + goto __pyx_L6; + } + + /* "View.MemoryView":762 + * new_ndim += 1 + * else: + * start = index.start or 0 # <<<<<<<<<<<<<< + * stop = index.stop or 0 + * step = index.step or 0 + */ + /*else*/ { + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 762, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 762, __pyx_L1_error) + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 762, __pyx_L1_error) + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L7_bool_binop_done; + } + __pyx_t_10 = 0; + __pyx_L7_bool_binop_done:; + __pyx_v_start = __pyx_t_10; + + /* "View.MemoryView":763 + * else: + * start = index.start or 0 + * stop = index.stop or 0 # <<<<<<<<<<<<<< + * step = index.step or 0 + * + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 763, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 763, __pyx_L1_error) + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 763, __pyx_L1_error) + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_10 = 0; + __pyx_L9_bool_binop_done:; + __pyx_v_stop = __pyx_t_10; + + /* "View.MemoryView":764 + * start = index.start or 0 + * stop = index.stop or 0 + * step = index.step or 0 # <<<<<<<<<<<<<< + * + * have_start = index.start is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 764, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 764, __pyx_L1_error) + if (!__pyx_t_1) { + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } else { + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 764, __pyx_L1_error) + __pyx_t_10 = __pyx_t_12; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_10 = 0; + __pyx_L11_bool_binop_done:; + __pyx_v_step = __pyx_t_10; + + /* "View.MemoryView":766 + * step = index.step or 0 + * + * have_start = index.start is not None # <<<<<<<<<<<<<< + * have_stop = index.stop is not None + * have_step = index.step is not None + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 766, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_start = __pyx_t_1; + + /* "View.MemoryView":767 + * + * have_start = index.start is not None + * have_stop = index.stop is not None # <<<<<<<<<<<<<< + * have_step = index.step is not None + * + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 767, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_stop = __pyx_t_1; + + /* "View.MemoryView":768 + * have_start = index.start is not None + * have_stop = index.stop is not None + * have_step = index.step is not None # <<<<<<<<<<<<<< + * + * slice_memviewslice( + */ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 768, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_1 = (__pyx_t_9 != Py_None); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_v_have_step = __pyx_t_1; + + /* "View.MemoryView":770 + * have_step = index.step is not None + * + * slice_memviewslice( # <<<<<<<<<<<<<< + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + * dim, new_ndim, p_suboffset_dim, + */ + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(2, 770, __pyx_L1_error) + + /* "View.MemoryView":776 + * have_start, have_stop, have_step, + * True) + * new_ndim += 1 # <<<<<<<<<<<<<< + * + * if isinstance(memview, _memoryviewslice): + */ + __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + } + __pyx_L6:; + + /* "View.MemoryView":748 + * cdef bint have_start, have_stop, have_step + * + * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< + * if PyIndex_Check(index): + * slice_memviewslice( + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":778 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":779 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":780 + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< + * memviewsliceobj.to_dtype_func, + * memview.dtype_is_object) + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(2, 780, __pyx_L1_error) } + + /* "View.MemoryView":781 + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * else: + */ + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(2, 781, __pyx_L1_error) } + + /* "View.MemoryView":779 + * + * if isinstance(memview, _memoryviewslice): + * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< + * memviewsliceobj.to_object_func, + * memviewsliceobj.to_dtype_func, + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 779, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(2, 779, __pyx_L1_error) + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":778 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + } + + /* "View.MemoryView":784 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + /*else*/ { + __Pyx_XDECREF(((PyObject *)__pyx_r)); + + /* "View.MemoryView":785 + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 784, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":784 + * memview.dtype_is_object) + * else: + * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< + * memview.dtype_is_object) + * + */ + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(2, 784, __pyx_L1_error) + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":712 + * + * @cname('__pyx_memview_slice') + * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< + * cdef int new_ndim = 0, suboffset_dim = -1, dim + * cdef bint negative_step + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); + __Pyx_XDECREF(__pyx_v_index); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":809 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + +static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { + Py_ssize_t __pyx_v_new_shape; + int __pyx_v_negative_step; + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":829 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":831 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + __pyx_t_1 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":832 + * + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":831 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + } + + /* "View.MemoryView":833 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + __pyx_t_1 = (0 <= __pyx_v_start); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); + } + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":834 + * start += shape + * if not 0 <= start < shape: + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< + * else: + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"Index out of bounds (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 834, __pyx_L1_error) + + /* "View.MemoryView":833 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + } + + /* "View.MemoryView":829 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":837 + * else: + * + * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< + * + * if have_step and step == 0: + */ + /*else*/ { + __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); + if (__pyx_t_1) { + } else { + __pyx_t_2 = __pyx_t_1; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_1 = ((__pyx_v_step < 0) != 0); + __pyx_t_2 = __pyx_t_1; + __pyx_L6_bool_binop_done:; + __pyx_v_negative_step = __pyx_t_2; + + /* "View.MemoryView":839 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + __pyx_t_1 = (__pyx_v_have_step != 0); + if (__pyx_t_1) { + } else { + __pyx_t_2 = __pyx_t_1; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_1 = ((__pyx_v_step == 0) != 0); + __pyx_t_2 = __pyx_t_1; + __pyx_L9_bool_binop_done:; + if (__pyx_t_2) { + + /* "View.MemoryView":840 + * + * if have_step and step == 0: + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Step may not be zero (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 840, __pyx_L1_error) + + /* "View.MemoryView":839 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + } + + /* "View.MemoryView":843 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":844 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":845 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":846 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + __pyx_t_2 = ((__pyx_v_start < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":847 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + + /* "View.MemoryView":846 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + } + + /* "View.MemoryView":844 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + goto __pyx_L12; + } + + /* "View.MemoryView":848 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":849 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":850 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + + /* "View.MemoryView":849 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + goto __pyx_L14; + } + + /* "View.MemoryView":852 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + /*else*/ { + __pyx_v_start = __pyx_v_shape; + } + __pyx_L14:; + + /* "View.MemoryView":848 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + } + __pyx_L12:; + + /* "View.MemoryView":843 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + goto __pyx_L11; + } + + /* "View.MemoryView":854 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + /*else*/ { + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":855 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + + /* "View.MemoryView":854 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + goto __pyx_L15; + } + + /* "View.MemoryView":857 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + /*else*/ { + __pyx_v_start = 0; + } + __pyx_L15:; + } + __pyx_L11:; + + /* "View.MemoryView":859 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":860 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":861 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":862 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + __pyx_t_2 = ((__pyx_v_stop < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":863 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + + /* "View.MemoryView":862 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + } + + /* "View.MemoryView":860 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + goto __pyx_L17; + } + + /* "View.MemoryView":864 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":865 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + + /* "View.MemoryView":864 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + } + __pyx_L17:; + + /* "View.MemoryView":859 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + goto __pyx_L16; + } + + /* "View.MemoryView":867 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + /*else*/ { + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":868 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1L; + + /* "View.MemoryView":867 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + goto __pyx_L19; + } + + /* "View.MemoryView":870 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + /*else*/ { + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L19:; + } + __pyx_L16:; + + /* "View.MemoryView":872 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":873 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + + /* "View.MemoryView":872 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + } + + /* "View.MemoryView":877 + * + * with cython.cdivision(True): + * new_shape = (stop - start) // step # <<<<<<<<<<<<<< + * + * if (stop - start) - step * new_shape: + */ + __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); + + /* "View.MemoryView":879 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":880 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + + /* "View.MemoryView":879 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + } + + /* "View.MemoryView":882 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":883 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + + /* "View.MemoryView":882 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + } + + /* "View.MemoryView":886 + * + * + * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset + */ + (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); + + /* "View.MemoryView":887 + * + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< + * dst.suboffsets[new_ndim] = suboffset + * + */ + (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; + + /* "View.MemoryView":888 + * dst.strides[new_ndim] = stride * step + * dst.shape[new_ndim] = new_shape + * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; + } + __pyx_L3:; + + /* "View.MemoryView":891 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":892 + * + * if suboffset_dim[0] < 0: + * dst.data += start * stride # <<<<<<<<<<<<<< + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride + */ + __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + + /* "View.MemoryView":891 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + goto __pyx_L23; + } + + /* "View.MemoryView":894 + * dst.data += start * stride + * else: + * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< + * + * if suboffset >= 0: + */ + /*else*/ { + __pyx_t_3 = (__pyx_v_suboffset_dim[0]); + (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); + } + __pyx_L23:; + + /* "View.MemoryView":896 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":897 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":898 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":899 + * if not is_slice: + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + */ + __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + + /* "View.MemoryView":898 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + goto __pyx_L26; + } + + /* "View.MemoryView":901 + * dst.data = ( dst.data)[0] + suboffset + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< + * "must be indexed and not sliced", dim) + * else: + */ + /*else*/ { + + /* "View.MemoryView":902 + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< + * else: + * suboffset_dim[0] = new_ndim + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"All dimensions preceding dimension %d must be indexed and not sliced"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 901, __pyx_L1_error) + } + __pyx_L26:; + + /* "View.MemoryView":897 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + goto __pyx_L25; + } + + /* "View.MemoryView":904 + * "must be indexed and not sliced", dim) + * else: + * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< + * + * return 0 + */ + /*else*/ { + (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; + } + __pyx_L25:; + + /* "View.MemoryView":896 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + } + + /* "View.MemoryView":906 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":809 + * + * @cname('__pyx_memoryview_slice_memviewslice') + * cdef int slice_memviewslice( # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + __Pyx_PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":912 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + +static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_suboffset; + Py_ssize_t __pyx_v_itemsize; + char *__pyx_v_resultp; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":914 + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< + * cdef Py_ssize_t itemsize = view.itemsize + * cdef char *resultp + */ + __pyx_v_suboffset = -1L; + + /* "View.MemoryView":915 + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< + * cdef char *resultp + * + */ + __pyx_t_1 = __pyx_v_view->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":918 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":919 + * + * if view.ndim == 0: + * shape = view.len / itemsize # <<<<<<<<<<<<<< + * stride = itemsize + * else: + */ + if (unlikely(__pyx_v_itemsize == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); + __PYX_ERR(2, 919, __pyx_L1_error) + } + else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { + PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); + __PYX_ERR(2, 919, __pyx_L1_error) + } + __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); + + /* "View.MemoryView":920 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + + /* "View.MemoryView":918 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + goto __pyx_L3; + } + + /* "View.MemoryView":922 + * stride = itemsize + * else: + * shape = view.shape[dim] # <<<<<<<<<<<<<< + * stride = view.strides[dim] + * if view.suboffsets != NULL: + */ + /*else*/ { + __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); + + /* "View.MemoryView":923 + * else: + * shape = view.shape[dim] + * stride = view.strides[dim] # <<<<<<<<<<<<<< + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] + */ + __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); + + /* "View.MemoryView":924 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":925 + * stride = view.strides[dim] + * if view.suboffsets != NULL: + * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< + * + * if index < 0: + */ + __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); + + /* "View.MemoryView":924 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + } + } + __pyx_L3:; + + /* "View.MemoryView":927 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":928 + * + * if index < 0: + * index += view.shape[dim] # <<<<<<<<<<<<<< + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + */ + __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); + + /* "View.MemoryView":929 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index < 0) != 0); + if (unlikely(__pyx_t_2)) { + + /* "View.MemoryView":930 + * index += view.shape[dim] + * if index < 0: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * if index >= shape: + */ + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 930, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 930, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 930, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(2, 930, __pyx_L1_error) + + /* "View.MemoryView":929 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + } + + /* "View.MemoryView":927 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + } + + /* "View.MemoryView":932 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); + if (unlikely(__pyx_t_2)) { + + /* "View.MemoryView":933 + * + * if index >= shape: + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< + * + * resultp = bufp + index * stride + */ + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 933, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 933, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 933, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(2, 933, __pyx_L1_error) + + /* "View.MemoryView":932 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + } + + /* "View.MemoryView":935 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * resultp = bufp + index * stride # <<<<<<<<<<<<<< + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset + */ + __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); + + /* "View.MemoryView":936 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":937 + * resultp = bufp + index * stride + * if suboffset >= 0: + * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< + * + * return resultp + */ + __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); + + /* "View.MemoryView":936 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + } + + /* "View.MemoryView":939 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + /* "View.MemoryView":912 + * + * @cname('__pyx_pybuffer_index') + * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< + * Py_ssize_t dim) except NULL: + * cdef Py_ssize_t shape, stride, suboffset = -1 + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":945 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + +static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { + int __pyx_v_ndim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + int __pyx_v_i; + int __pyx_v_j; + int __pyx_r; + int __pyx_t_1; + Py_ssize_t *__pyx_t_2; + long __pyx_t_3; + long __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":946 + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: + * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< + * + * cdef Py_ssize_t *shape = memslice.shape + */ + __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; + __pyx_v_ndim = __pyx_t_1; + + /* "View.MemoryView":948 + * cdef int ndim = memslice.memview.view.ndim + * + * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< + * cdef Py_ssize_t *strides = memslice.strides + * + */ + __pyx_t_2 = __pyx_v_memslice->shape; + __pyx_v_shape = __pyx_t_2; + + /* "View.MemoryView":949 + * + * cdef Py_ssize_t *shape = memslice.shape + * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_v_memslice->strides; + __pyx_v_strides = __pyx_t_2; + + /* "View.MemoryView":953 + * + * cdef int i, j + * for i in range(ndim / 2): # <<<<<<<<<<<<<< + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + */ + __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); + __pyx_t_4 = __pyx_t_3; + for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_4; __pyx_t_1+=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":954 + * cdef int i, j + * for i in range(ndim / 2): + * j = ndim - 1 - i # <<<<<<<<<<<<<< + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] + */ + __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); + + /* "View.MemoryView":955 + * for i in range(ndim / 2): + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< + * shape[i], shape[j] = shape[j], shape[i] + * + */ + __pyx_t_5 = (__pyx_v_strides[__pyx_v_j]); + __pyx_t_6 = (__pyx_v_strides[__pyx_v_i]); + (__pyx_v_strides[__pyx_v_i]) = __pyx_t_5; + (__pyx_v_strides[__pyx_v_j]) = __pyx_t_6; + + /* "View.MemoryView":956 + * j = ndim - 1 - i + * strides[i], strides[j] = strides[j], strides[i] + * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + */ + __pyx_t_6 = (__pyx_v_shape[__pyx_v_j]); + __pyx_t_5 = (__pyx_v_shape[__pyx_v_i]); + (__pyx_v_shape[__pyx_v_i]) = __pyx_t_6; + (__pyx_v_shape[__pyx_v_j]) = __pyx_t_5; + + /* "View.MemoryView":958 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); + if (!__pyx_t_8) { + } else { + __pyx_t_7 = __pyx_t_8; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); + __pyx_t_7 = __pyx_t_8; + __pyx_L6_bool_binop_done:; + if (__pyx_t_7) { + + /* "View.MemoryView":959 + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< + * + * return 1 + */ + __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 959, __pyx_L1_error) + + /* "View.MemoryView":958 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + } + } + + /* "View.MemoryView":961 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + /* "View.MemoryView":945 + * + * @cname('__pyx_memslice_transpose') + * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< + * cdef int ndim = memslice.memview.view.ndim + * + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + __Pyx_PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = 0; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":978 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + +/* Python wrapper */ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__", 0); + + /* "View.MemoryView":979 + * + * def __dealloc__(self): + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< + * + * cdef convert_item_to_object(self, char *itemp): + */ + __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); + + /* "View.MemoryView":978 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":981 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + +static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":982 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":983 + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) # <<<<<<<<<<<<<< + * else: + * return memoryview.convert_item_to_object(self, itemp) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 983, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":982 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + } + + /* "View.MemoryView":985 + * return self.to_object_func(itemp) + * else: + * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< + * + * cdef assign_item_from_object(self, char *itemp, object value): + */ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 985, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":981 + * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) + * + * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< + * if self.to_object_func != NULL: + * return self.to_object_func(itemp) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":987 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + +static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":988 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":989 + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< + * else: + * memoryview.assign_item_from_object(self, itemp, value) + */ + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(2, 989, __pyx_L1_error) + + /* "View.MemoryView":988 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":991 + * self.to_dtype_func(itemp, value) + * else: + * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< + * + * @property + */ + /*else*/ { + __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 991, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":987 + * return memoryview.convert_item_to_object(self, itemp) + * + * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< + * if self.to_dtype_func != NULL: + * self.to_dtype_func(itemp, value) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":994 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":995 + * @property + * def base(self): + * return self.from_object # <<<<<<<<<<<<<< + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->from_object); + __pyx_r = __pyx_v_self->from_object; + goto __pyx_L0; + + /* "View.MemoryView":994 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.from_object + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_memoryviewslice___reduce_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(2, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_memoryviewslice_2__setstate_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(2, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1001 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + +static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { + struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; + Py_ssize_t __pyx_v_suboffset; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_TypeInfo *__pyx_t_4; + Py_buffer __pyx_t_5; + Py_ssize_t *__pyx_t_6; + Py_ssize_t *__pyx_t_7; + Py_ssize_t *__pyx_t_8; + Py_ssize_t __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":1009 + * cdef _memoryviewslice result + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1010 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + + /* "View.MemoryView":1009 + * cdef _memoryviewslice result + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + } + + /* "View.MemoryView":1015 + * + * + * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< + * + * result.from_slice = memviewslice + */ + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1015, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1015, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); + __Pyx_INCREF(__pyx_int_0); + __Pyx_GIVEREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1015, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":1017 + * result = _memoryviewslice(None, 0, dtype_is_object) + * + * result.from_slice = memviewslice # <<<<<<<<<<<<<< + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + */ + __pyx_v_result->from_slice = __pyx_v_memviewslice; + + /* "View.MemoryView":1018 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":1020 + * __PYX_INC_MEMVIEW(&memviewslice, 1) + * + * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< + * result.typeinfo = memviewslice.memview.typeinfo + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1020, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_GOTREF(__pyx_v_result->from_object); + __Pyx_DECREF(__pyx_v_result->from_object); + __pyx_v_result->from_object = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":1021 + * + * result.from_object = ( memviewslice.memview).base + * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< + * + * result.view = memviewslice.memview.view + */ + __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; + __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; + + /* "View.MemoryView":1023 + * result.typeinfo = memviewslice.memview.typeinfo + * + * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + */ + __pyx_t_5 = __pyx_v_memviewslice.memview->view; + __pyx_v_result->__pyx_base.view = __pyx_t_5; + + /* "View.MemoryView":1024 + * + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + */ + __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); + + /* "View.MemoryView":1025 + * result.view = memviewslice.memview.view + * result.view.buf = memviewslice.data + * result.view.ndim = ndim # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) + */ + __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; + + /* "View.MemoryView":1026 + * result.view.buf = memviewslice.data + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< + * Py_INCREF(Py_None) + * + */ + ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; + + /* "View.MemoryView":1027 + * result.view.ndim = ndim + * (<__pyx_buffer *> &result.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * if (memviewslice.memview).flags & PyBUF_WRITABLE: + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":1029 + * Py_INCREF(Py_None) + * + * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< + * result.flags = PyBUF_RECORDS + * else: + */ + __pyx_t_1 = ((((struct __pyx_memoryview_obj *)__pyx_v_memviewslice.memview)->flags & PyBUF_WRITABLE) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1030 + * + * if (memviewslice.memview).flags & PyBUF_WRITABLE: + * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< + * else: + * result.flags = PyBUF_RECORDS_RO + */ + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; + + /* "View.MemoryView":1029 + * Py_INCREF(Py_None) + * + * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< + * result.flags = PyBUF_RECORDS + * else: + */ + goto __pyx_L4; + } + + /* "View.MemoryView":1032 + * result.flags = PyBUF_RECORDS + * else: + * result.flags = PyBUF_RECORDS_RO # <<<<<<<<<<<<<< + * + * result.view.shape = result.from_slice.shape + */ + /*else*/ { + __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS_RO; + } + __pyx_L4:; + + /* "View.MemoryView":1034 + * result.flags = PyBUF_RECORDS_RO + * + * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< + * result.view.strides = result.from_slice.strides + * + */ + __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); + + /* "View.MemoryView":1035 + * + * result.view.shape = result.from_slice.shape + * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); + + /* "View.MemoryView":1038 + * + * + * result.view.suboffsets = NULL # <<<<<<<<<<<<<< + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: + */ + __pyx_v_result->__pyx_base.view.suboffsets = NULL; + + /* "View.MemoryView":1039 + * + * result.view.suboffsets = NULL + * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); + for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { + __pyx_t_6 = __pyx_t_8; + __pyx_v_suboffset = (__pyx_t_6[0]); + + /* "View.MemoryView":1040 + * result.view.suboffsets = NULL + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * break + */ + __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1041 + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":1042 + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets + * break # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + goto __pyx_L6_break; + + /* "View.MemoryView":1040 + * result.view.suboffsets = NULL + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * break + */ + } + } + __pyx_L6_break:; + + /* "View.MemoryView":1044 + * break + * + * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< + * for length in result.view.shape[:ndim]: + * result.view.len *= length + */ + __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_9; + + /* "View.MemoryView":1045 + * + * result.view.len = result.view.itemsize + * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< + * result.view.len *= length + * + */ + __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); + for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { + __pyx_t_6 = __pyx_t_8; + __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1045, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":1046 + * result.view.len = result.view.itemsize + * for length in result.view.shape[:ndim]: + * result.view.len *= length # <<<<<<<<<<<<<< + * + * result.to_object_func = to_object_func + */ + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1046, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1046, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 1046, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result->__pyx_base.view.len = __pyx_t_9; + } + + /* "View.MemoryView":1048 + * result.view.len *= length + * + * result.to_object_func = to_object_func # <<<<<<<<<<<<<< + * result.to_dtype_func = to_dtype_func + * + */ + __pyx_v_result->to_object_func = __pyx_v_to_object_func; + + /* "View.MemoryView":1049 + * + * result.to_object_func = to_object_func + * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< + * + * return result + */ + __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; + + /* "View.MemoryView":1051 + * result.to_dtype_func = to_dtype_func + * + * return result # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_result)); + __pyx_r = ((PyObject *)__pyx_v_result); + goto __pyx_L0; + + /* "View.MemoryView":1001 + * + * @cname('__pyx_memoryview_fromslice') + * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< + * int ndim, + * object (*to_object_func)(char *), + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1054 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice) except NULL: + * cdef _memoryviewslice obj + */ + +static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { + struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; + __Pyx_memviewslice *__pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1057 + * __Pyx_memviewslice *mslice) except NULL: + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1058 + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): + * obj = memview # <<<<<<<<<<<<<< + * return &obj.from_slice + * else: + */ + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(2, 1058, __pyx_L1_error) + __pyx_t_3 = ((PyObject *)__pyx_v_memview); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":1059 + * if isinstance(memview, _memoryviewslice): + * obj = memview + * return &obj.from_slice # <<<<<<<<<<<<<< + * else: + * slice_copy(memview, mslice) + */ + __pyx_r = (&__pyx_v_obj->from_slice); + goto __pyx_L0; + + /* "View.MemoryView":1057 + * __Pyx_memviewslice *mslice) except NULL: + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + } + + /* "View.MemoryView":1061 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + /*else*/ { + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1062 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + + /* "View.MemoryView":1054 + * + * @cname('__pyx_memoryview_get_slice_from_memoryview') + * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *mslice) except NULL: + * cdef _memoryviewslice obj + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_obj); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1065 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + +static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { + int __pyx_v_dim; + Py_ssize_t *__pyx_v_shape; + Py_ssize_t *__pyx_v_strides; + Py_ssize_t *__pyx_v_suboffsets; + __Pyx_RefNannyDeclarations + Py_ssize_t *__pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + __Pyx_RefNannySetupContext("slice_copy", 0); + + /* "View.MemoryView":1069 + * cdef (Py_ssize_t*) shape, strides, suboffsets + * + * shape = memview.view.shape # <<<<<<<<<<<<<< + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets + */ + __pyx_t_1 = __pyx_v_memview->view.shape; + __pyx_v_shape = __pyx_t_1; + + /* "View.MemoryView":1070 + * + * shape = memview.view.shape + * strides = memview.view.strides # <<<<<<<<<<<<<< + * suboffsets = memview.view.suboffsets + * + */ + __pyx_t_1 = __pyx_v_memview->view.strides; + __pyx_v_strides = __pyx_t_1; + + /* "View.MemoryView":1071 + * shape = memview.view.shape + * strides = memview.view.strides + * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< + * + * dst.memview = <__pyx_memoryview *> memview + */ + __pyx_t_1 = __pyx_v_memview->view.suboffsets; + __pyx_v_suboffsets = __pyx_t_1; + + /* "View.MemoryView":1073 + * suboffsets = memview.view.suboffsets + * + * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< + * dst.data = memview.view.buf + * + */ + __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); + + /* "View.MemoryView":1074 + * + * dst.memview = <__pyx_memoryview *> memview + * dst.data = memview.view.buf # <<<<<<<<<<<<<< + * + * for dim in range(memview.view.ndim): + */ + __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); + + /* "View.MemoryView":1076 + * dst.data = memview.view.buf + * + * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + */ + __pyx_t_2 = __pyx_v_memview->view.ndim; + __pyx_t_3 = __pyx_t_2; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_dim = __pyx_t_4; + + /* "View.MemoryView":1077 + * + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< + * dst.strides[dim] = strides[dim] + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 + */ + (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); + + /* "View.MemoryView":1078 + * for dim in range(memview.view.ndim): + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 + * + */ + (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); + + /* "View.MemoryView":1079 + * dst.shape[dim] = shape[dim] + * dst.strides[dim] = strides[dim] + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object') + */ + if ((__pyx_v_suboffsets != 0)) { + __pyx_t_5 = (__pyx_v_suboffsets[__pyx_v_dim]); + } else { + __pyx_t_5 = -1L; + } + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_5; + } + + /* "View.MemoryView":1065 + * + * @cname('__pyx_memoryview_slice_copy') + * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< + * cdef int dim + * cdef (Py_ssize_t*) shape, strides, suboffsets + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1082 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + +static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { + __Pyx_memviewslice __pyx_v_memviewslice; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1085 + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< + * return memoryview_copy_from_slice(memview, &memviewslice) + * + */ + __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); + + /* "View.MemoryView":1086 + * cdef __Pyx_memviewslice memviewslice + * slice_copy(memview, &memviewslice) + * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_object_from_slice') + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1086, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1082 + * + * @cname('__pyx_memoryview_copy_object') + * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< + * "Create a new memoryview object" + * cdef __Pyx_memviewslice memviewslice + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1089 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + +static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { + PyObject *(*__pyx_v_to_object_func)(char *); + int (*__pyx_v_to_dtype_func)(char *, PyObject *); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *(*__pyx_t_3)(char *); + int (*__pyx_t_4)(char *, PyObject *); + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1096 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1097 + * + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + */ + __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; + __pyx_v_to_object_func = __pyx_t_3; + + /* "View.MemoryView":1098 + * if isinstance(memview, _memoryviewslice): + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< + * else: + * to_object_func = NULL + */ + __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; + __pyx_v_to_dtype_func = __pyx_t_4; + + /* "View.MemoryView":1096 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ + goto __pyx_L3; + } + + /* "View.MemoryView":1100 + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + * else: + * to_object_func = NULL # <<<<<<<<<<<<<< + * to_dtype_func = NULL + * + */ + /*else*/ { + __pyx_v_to_object_func = NULL; + + /* "View.MemoryView":1101 + * else: + * to_object_func = NULL + * to_dtype_func = NULL # <<<<<<<<<<<<<< + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + */ + __pyx_v_to_dtype_func = NULL; + } + __pyx_L3:; + + /* "View.MemoryView":1103 + * to_dtype_func = NULL + * + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< + * to_object_func, to_dtype_func, + * memview.dtype_is_object) + */ + __Pyx_XDECREF(__pyx_r); + + /* "View.MemoryView":1105 + * return memoryview_fromslice(memviewslice[0], memview.view.ndim, + * to_object_func, to_dtype_func, + * memview.dtype_is_object) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 1103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1089 + * + * @cname('__pyx_memoryview_copy_object_from_slice') + * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< + * """ + * Create a new memoryview object from a given memoryview object and slice. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":1111 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + +static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { + Py_ssize_t __pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":1112 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + __pyx_t_1 = ((__pyx_v_arg < 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1113 + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: + * return -arg # <<<<<<<<<<<<<< + * else: + * return arg + */ + __pyx_r = (-__pyx_v_arg); + goto __pyx_L0; + + /* "View.MemoryView":1112 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + } + + /* "View.MemoryView":1115 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + /*else*/ { + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + + /* "View.MemoryView":1111 + * + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< + * if arg < 0: + * return -arg + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1118 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + +static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { + int __pyx_v_i; + Py_ssize_t __pyx_v_c_stride; + Py_ssize_t __pyx_v_f_stride; + char __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + + /* "View.MemoryView":1123 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1124 + * cdef int i + * cdef Py_ssize_t c_stride = 0 + * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_f_stride = 0; + + /* "View.MemoryView":1126 + * cdef Py_ssize_t f_stride = 0 + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1127 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1128 + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1129 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + + /* "View.MemoryView":1127 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + } + } + __pyx_L4_break:; + + /* "View.MemoryView":1131 + * break + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + */ + __pyx_t_1 = __pyx_v_ndim; + __pyx_t_3 = __pyx_t_1; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "View.MemoryView":1132 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1133 + * for i in range(ndim): + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1134 + * if mslice.shape[i] > 1: + * f_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + */ + goto __pyx_L7_break; + + /* "View.MemoryView":1132 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + } + } + __pyx_L7_break:; + + /* "View.MemoryView":1136 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1137 + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): + * return 'C' # <<<<<<<<<<<<<< + * else: + * return 'F' + */ + __pyx_r = 'C'; + goto __pyx_L0; + + /* "View.MemoryView":1136 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + } + + /* "View.MemoryView":1139 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + /*else*/ { + __pyx_r = 'F'; + goto __pyx_L0; + } + + /* "View.MemoryView":1118 + * + * @cname('__pyx_get_best_slice_order') + * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< + * """ + * Figure out the best memory access order for a given slice. + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1142 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + +static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; + Py_ssize_t __pyx_v_dst_extent; + Py_ssize_t __pyx_v_src_stride; + Py_ssize_t __pyx_v_dst_stride; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + + /* "View.MemoryView":1149 + * + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + */ + __pyx_v_src_extent = (__pyx_v_src_shape[0]); + + /* "View.MemoryView":1150 + * cdef Py_ssize_t i + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] + */ + __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); + + /* "View.MemoryView":1151 + * cdef Py_ssize_t src_extent = src_shape[0] + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + */ + __pyx_v_src_stride = (__pyx_v_src_strides[0]); + + /* "View.MemoryView":1152 + * cdef Py_ssize_t dst_extent = dst_shape[0] + * cdef Py_ssize_t src_stride = src_strides[0] + * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); + + /* "View.MemoryView":1154 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1155 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L5_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L5_bool_binop_done; + } + + /* "View.MemoryView":1156 + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + */ + __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); + if (__pyx_t_2) { + __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); + } + __pyx_t_3 = (__pyx_t_2 != 0); + __pyx_t_1 = __pyx_t_3; + __pyx_L5_bool_binop_done:; + + /* "View.MemoryView":1155 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + if (__pyx_t_1) { + + /* "View.MemoryView":1157 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent))); + + /* "View.MemoryView":1155 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + goto __pyx_L4; + } + + /* "View.MemoryView":1159 + * memcpy(dst_data, src_data, itemsize * dst_extent) + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + */ + /*else*/ { + __pyx_t_4 = __pyx_v_dst_extent; + __pyx_t_5 = __pyx_t_4; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1160 + * else: + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< + * src_data += src_stride + * dst_data += dst_stride + */ + (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize)); + + /* "View.MemoryView":1161 + * for i in range(dst_extent): + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * else: + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1162 + * memcpy(dst_data, src_data, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * else: + * for i in range(dst_extent): + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L4:; + + /* "View.MemoryView":1154 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ + goto __pyx_L3; + } + + /* "View.MemoryView":1164 + * dst_data += dst_stride + * else: + * for i in range(dst_extent): # <<<<<<<<<<<<<< + * _copy_strided_to_strided(src_data, src_strides + 1, + * dst_data, dst_strides + 1, + */ + /*else*/ { + __pyx_t_4 = __pyx_v_dst_extent; + __pyx_t_5 = __pyx_t_4; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1165 + * else: + * for i in range(dst_extent): + * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< + * dst_data, dst_strides + 1, + * src_shape + 1, dst_shape + 1, + */ + _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); + + /* "View.MemoryView":1169 + * src_shape + 1, dst_shape + 1, + * ndim - 1, itemsize) + * src_data += src_stride # <<<<<<<<<<<<<< + * dst_data += dst_stride + * + */ + __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); + + /* "View.MemoryView":1170 + * ndim - 1, itemsize) + * src_data += src_stride + * dst_data += dst_stride # <<<<<<<<<<<<<< + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, + */ + __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1142 + * + * @cython.cdivision(True) + * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< + * char *dst_data, Py_ssize_t *dst_strides, + * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, + */ + + /* function exit code */ +} + +/* "View.MemoryView":1172 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + +static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { + + /* "View.MemoryView":1175 + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< + * src.shape, dst.shape, ndim, itemsize) + * + */ + _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1172 + * dst_data += dst_stride + * + * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *dst, + * int ndim, size_t itemsize) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1179 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef Py_ssize_t shape, size = src.memview.view.itemsize + */ + +static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { + Py_ssize_t __pyx_v_shape; + Py_ssize_t __pyx_v_size; + Py_ssize_t __pyx_r; + Py_ssize_t __pyx_t_1; + Py_ssize_t *__pyx_t_2; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + + /* "View.MemoryView":1181 + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef Py_ssize_t shape, size = src.memview.view.itemsize # <<<<<<<<<<<<<< + * + * for shape in src.shape[:ndim]: + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_size = __pyx_t_1; + + /* "View.MemoryView":1183 + * cdef Py_ssize_t shape, size = src.memview.view.itemsize + * + * for shape in src.shape[:ndim]: # <<<<<<<<<<<<<< + * size *= shape + * + */ + __pyx_t_3 = (__pyx_v_src->shape + __pyx_v_ndim); + for (__pyx_t_4 = __pyx_v_src->shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { + __pyx_t_2 = __pyx_t_4; + __pyx_v_shape = (__pyx_t_2[0]); + + /* "View.MemoryView":1184 + * + * for shape in src.shape[:ndim]: + * size *= shape # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * __pyx_v_shape); + } + + /* "View.MemoryView":1186 + * size *= shape + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + /* "View.MemoryView":1179 + * + * @cname('__pyx_memoryview_slice_get_size') + * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< + * "Return the size of the memory occupied by the slice in number of bytes" + * cdef Py_ssize_t shape, size = src.memview.view.itemsize + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1189 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + +static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { + int __pyx_v_idx; + Py_ssize_t __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + + /* "View.MemoryView":1198 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + __pyx_t_1 = ((__pyx_v_order == 'F') != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1199 + * + * if order == 'F': + * for idx in range(ndim): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride *= shape[idx] + */ + __pyx_t_2 = __pyx_v_ndim; + __pyx_t_3 = __pyx_t_2; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_idx = __pyx_t_4; + + /* "View.MemoryView":1200 + * if order == 'F': + * for idx in range(ndim): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride *= shape[idx] + * else: + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1201 + * for idx in range(ndim): + * strides[idx] = stride + * stride *= shape[idx] # <<<<<<<<<<<<<< + * else: + * for idx in range(ndim - 1, -1, -1): + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + + /* "View.MemoryView":1198 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + goto __pyx_L3; + } + + /* "View.MemoryView":1203 + * stride *= shape[idx] + * else: + * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * strides[idx] = stride + * stride *= shape[idx] + */ + /*else*/ { + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + __pyx_v_idx = __pyx_t_2; + + /* "View.MemoryView":1204 + * else: + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride # <<<<<<<<<<<<<< + * stride *= shape[idx] + * + */ + (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; + + /* "View.MemoryView":1205 + * for idx in range(ndim - 1, -1, -1): + * strides[idx] = stride + * stride *= shape[idx] # <<<<<<<<<<<<<< + * + * return stride + */ + __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); + } + } + __pyx_L3:; + + /* "View.MemoryView":1207 + * stride *= shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + /* "View.MemoryView":1189 + * + * @cname('__pyx_fill_contig_strides_array') + * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< + * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, + * int ndim, char order) nogil: + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1210 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + +static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { + int __pyx_v_i; + void *__pyx_v_result; + size_t __pyx_v_itemsize; + size_t __pyx_v_size; + void *__pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_memoryview_obj *__pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1221 + * cdef void *result + * + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef size_t size = slice_get_size(src, ndim) + * + */ + __pyx_t_1 = __pyx_v_src->memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1222 + * + * cdef size_t itemsize = src.memview.view.itemsize + * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< + * + * result = malloc(size) + */ + __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); + + /* "View.MemoryView":1224 + * cdef size_t size = slice_get_size(src, ndim) + * + * result = malloc(size) # <<<<<<<<<<<<<< + * if not result: + * _err(MemoryError, NULL) + */ + __pyx_v_result = malloc(__pyx_v_size); + + /* "View.MemoryView":1225 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1226 + * result = malloc(size) + * if not result: + * _err(MemoryError, NULL) # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 1226, __pyx_L1_error) + + /* "View.MemoryView":1225 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + } + + /* "View.MemoryView":1229 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1230 + * + * tmpslice.data = result + * tmpslice.memview = src.memview # <<<<<<<<<<<<<< + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + */ + __pyx_t_4 = __pyx_v_src->memview; + __pyx_v_tmpslice->memview = __pyx_t_4; + + /* "View.MemoryView":1231 + * tmpslice.data = result + * tmpslice.memview = src.memview + * for i in range(ndim): # <<<<<<<<<<<<<< + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 + */ + __pyx_t_3 = __pyx_v_ndim; + __pyx_t_5 = __pyx_t_3; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1232 + * tmpslice.memview = src.memview + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< + * tmpslice.suboffsets[i] = -1 + * + */ + (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); + + /* "View.MemoryView":1233 + * for i in range(ndim): + * tmpslice.shape[i] = src.shape[i] + * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, + */ + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1L; + } + + /* "View.MemoryView":1235 + * tmpslice.suboffsets[i] = -1 + * + * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< + * ndim, order) + * + */ + (void)(__pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order)); + + /* "View.MemoryView":1239 + * + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 + */ + __pyx_t_3 = __pyx_v_ndim; + __pyx_t_5 = __pyx_t_3; + for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { + __pyx_v_i = __pyx_t_6; + + /* "View.MemoryView":1240 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1241 + * for i in range(ndim): + * if tmpslice.shape[i] == 1: + * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< + * + * if slice_is_contig(src[0], order, ndim): + */ + (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; + + /* "View.MemoryView":1240 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + } + } + + /* "View.MemoryView":1243 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1244 + * + * if slice_is_contig(src[0], order, ndim): + * memcpy(result, src.data, size) # <<<<<<<<<<<<<< + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + */ + (void)(memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size)); + + /* "View.MemoryView":1243 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + goto __pyx_L9; + } + + /* "View.MemoryView":1246 + * memcpy(result, src.data, size) + * else: + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< + * + * return result + */ + /*else*/ { + copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); + } + __pyx_L9:; + + /* "View.MemoryView":1248 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":1210 + * + * @cname('__pyx_memoryview_copy_data_to_temp') + * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice *tmpslice, + * char order, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + __Pyx_PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = NULL; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1253 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + +static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1256 + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + * (i, extent1, extent2)) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err_dim') + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1256, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1256, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1256, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1256, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + + /* "View.MemoryView":1255 + * cdef int _err_extents(int i, Py_ssize_t extent1, + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< + * (i, extent1, extent2)) + * + */ + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1255, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1255, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(2, 1255, __pyx_L1_error) + + /* "View.MemoryView":1253 + * + * @cname('__pyx_memoryview_err_extents') + * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< + * Py_ssize_t extent2) except -1 with gil: + * raise ValueError("got differing extents in dimension %d (got %d and %d)" % + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + __Pyx_PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1259 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + +static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1260 + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: + * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_err') + */ + __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_INCREF(__pyx_v_error); + __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + } + } + __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(2, 1260, __pyx_L1_error) + + /* "View.MemoryView":1259 + * + * @cname('__pyx_memoryview_err_dim') + * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii') % dim) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + __Pyx_PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1263 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + +static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1264 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); + if (unlikely(__pyx_t_1)) { + + /* "View.MemoryView":1265 + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: + * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< + * else: + * raise error + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1265, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_error); + __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1265, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(2, 1265, __pyx_L1_error) + + /* "View.MemoryView":1264 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ + } + + /* "View.MemoryView":1267 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + /*else*/ { + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + __PYX_ERR(2, 1267, __pyx_L1_error) + } + + /* "View.MemoryView":1263 + * + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< + * if msg != NULL: + * raise error(msg.decode('ascii')) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_XDECREF(__pyx_v_error); + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + __Pyx_PyGILState_Release(__pyx_gilstate_save); + #endif + return __pyx_r; +} + +/* "View.MemoryView":1270 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + +static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { + void *__pyx_v_tmpdata; + size_t __pyx_v_itemsize; + int __pyx_v_i; + char __pyx_v_order; + int __pyx_v_broadcasting; + int __pyx_v_direct_copy; + __Pyx_memviewslice __pyx_v_tmp; + int __pyx_v_ndim; + int __pyx_r; + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + void *__pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "View.MemoryView":1278 + * Check for overlapping memory and verify the shapes. + * """ + * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + */ + __pyx_v_tmpdata = NULL; + + /* "View.MemoryView":1279 + * """ + * cdef void *tmpdata = NULL + * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + */ + __pyx_t_1 = __pyx_v_src.memview->view.itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "View.MemoryView":1281 + * cdef size_t itemsize = src.memview.view.itemsize + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< + * cdef bint broadcasting = False + * cdef bint direct_copy = False + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); + + /* "View.MemoryView":1282 + * cdef int i + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False # <<<<<<<<<<<<<< + * cdef bint direct_copy = False + * cdef __Pyx_memviewslice tmp + */ + __pyx_v_broadcasting = 0; + + /* "View.MemoryView":1283 + * cdef char order = get_best_order(&src, src_ndim) + * cdef bint broadcasting = False + * cdef bint direct_copy = False # <<<<<<<<<<<<<< + * cdef __Pyx_memviewslice tmp + * + */ + __pyx_v_direct_copy = 0; + + /* "View.MemoryView":1286 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1287 + * + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + + /* "View.MemoryView":1286 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":1288 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1289 + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< + * + * cdef int ndim = max(src_ndim, dst_ndim) + */ + __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); + + /* "View.MemoryView":1288 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ + } + __pyx_L3:; + + /* "View.MemoryView":1291 + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + __pyx_t_3 = __pyx_v_dst_ndim; + __pyx_t_4 = __pyx_v_src_ndim; + if (((__pyx_t_3 > __pyx_t_4) != 0)) { + __pyx_t_5 = __pyx_t_3; + } else { + __pyx_t_5 = __pyx_t_4; + } + __pyx_v_ndim = __pyx_t_5; + + /* "View.MemoryView":1293 + * cdef int ndim = max(src_ndim, dst_ndim) + * + * for i in range(ndim): # <<<<<<<<<<<<<< + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + */ + __pyx_t_5 = __pyx_v_ndim; + __pyx_t_3 = __pyx_t_5; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "View.MemoryView":1294 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1295 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1296 + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: + * broadcasting = True # <<<<<<<<<<<<<< + * src.strides[i] = 0 + * else: + */ + __pyx_v_broadcasting = 1; + + /* "View.MemoryView":1297 + * if src.shape[i] == 1: + * broadcasting = True + * src.strides[i] = 0 # <<<<<<<<<<<<<< + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) + */ + (__pyx_v_src.strides[__pyx_v_i]) = 0; + + /* "View.MemoryView":1295 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ + goto __pyx_L7; + } + + /* "View.MemoryView":1299 + * src.strides[i] = 0 + * else: + * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< + * + * if src.suboffsets[i] >= 0: + */ + /*else*/ { + __pyx_t_6 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(2, 1299, __pyx_L1_error) + } + __pyx_L7:; + + /* "View.MemoryView":1294 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + } + + /* "View.MemoryView":1301 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1302 + * + * if src.suboffsets[i] >= 0: + * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< + * + * if slices_overlap(&src, &dst, ndim, itemsize): + */ + __pyx_t_6 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(2, 1302, __pyx_L1_error) + + /* "View.MemoryView":1301 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ + } + } + + /* "View.MemoryView":1304 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(src, order, ndim): + */ + __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1306 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1307 + * + * if not slice_is_contig(src, order, ndim): + * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + */ + __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); + + /* "View.MemoryView":1306 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + } + + /* "View.MemoryView":1309 + * order = get_best_order(&dst, ndim) + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< + * src = tmp + * + */ + __pyx_t_7 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_7 == ((void *)NULL))) __PYX_ERR(2, 1309, __pyx_L1_error) + __pyx_v_tmpdata = __pyx_t_7; + + /* "View.MemoryView":1310 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + + /* "View.MemoryView":1304 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(src, order, ndim): + */ + } + + /* "View.MemoryView":1312 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1315 + * + * + * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'C', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1316 + * + * if slice_is_contig(src, 'C', ndim): + * direct_copy = slice_is_contig(dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(src, 'F', ndim): + * direct_copy = slice_is_contig(dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'C', __pyx_v_ndim); + + /* "View.MemoryView":1315 + * + * + * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): + */ + goto __pyx_L12; + } + + /* "View.MemoryView":1317 + * if slice_is_contig(src, 'C', ndim): + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(dst, 'F', ndim) + * + */ + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'F', __pyx_v_ndim) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1318 + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): + * direct_copy = slice_is_contig(dst, 'F', ndim) # <<<<<<<<<<<<<< + * + * if direct_copy: + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'F', __pyx_v_ndim); + + /* "View.MemoryView":1317 + * if slice_is_contig(src, 'C', ndim): + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(dst, 'F', ndim) + * + */ + } + __pyx_L12:; + + /* "View.MemoryView":1320 + * direct_copy = slice_is_contig(dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_2 = (__pyx_v_direct_copy != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1322 + * if direct_copy: + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1323 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + */ + (void)(memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim))); + + /* "View.MemoryView":1324 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * free(tmpdata) + * return 0 + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1325 + * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1326 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * if order == 'F' == get_best_order(&dst, ndim): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":1320 + * direct_copy = slice_is_contig(dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + } + + /* "View.MemoryView":1312 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + } + + /* "View.MemoryView":1328 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = (__pyx_v_order == 'F'); + if (__pyx_t_2) { + __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); + } + __pyx_t_8 = (__pyx_t_2 != 0); + if (__pyx_t_8) { + + /* "View.MemoryView":1331 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(2, 1331, __pyx_L1_error) + + /* "View.MemoryView":1332 + * + * transpose_memslice(&src) + * transpose_memslice(&dst) # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(2, 1332, __pyx_L1_error) + + /* "View.MemoryView":1328 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + } + + /* "View.MemoryView":1334 + * transpose_memslice(&dst) + * + * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1335 + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + */ + copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); + + /* "View.MemoryView":1336 + * refcount_copying(&dst, dtype_is_object, ndim, False) + * copy_strided_to_strided(&src, &dst, ndim, itemsize) + * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * free(tmpdata) + */ + __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1338 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1339 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":1270 + * + * @cname('__pyx_memoryview_copy_contents') + * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< + * __Pyx_memviewslice dst, + * int src_ndim, int dst_ndim, + */ + + /* function exit code */ + __pyx_L1_error:; + { + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); + #ifdef WITH_THREAD + __Pyx_PyGILState_Release(__pyx_gilstate_save); + #endif + } + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":1342 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { + int __pyx_v_i; + int __pyx_v_offset; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + + /* "View.MemoryView":1346 + * int ndim_other) nogil: + * cdef int i + * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< + * + * for i in range(ndim - 1, -1, -1): + */ + __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); + + /* "View.MemoryView":1348 + * cdef int offset = ndim_other - ndim + * + * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] + */ + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + __pyx_v_i = __pyx_t_1; + + /* "View.MemoryView":1349 + * + * for i in range(ndim - 1, -1, -1): + * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< + * mslice.strides[i + offset] = mslice.strides[i] + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] + */ + (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); + + /* "View.MemoryView":1350 + * for i in range(ndim - 1, -1, -1): + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] + * + */ + (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); + + /* "View.MemoryView":1351 + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< + * + * for i in range(offset): + */ + (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); + } + + /* "View.MemoryView":1353 + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] + * + * for i in range(offset): # <<<<<<<<<<<<<< + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] + */ + __pyx_t_1 = __pyx_v_offset; + __pyx_t_2 = __pyx_t_1; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1354 + * + * for i in range(offset): + * mslice.shape[i] = 1 # <<<<<<<<<<<<<< + * mslice.strides[i] = mslice.strides[0] + * mslice.suboffsets[i] = -1 + */ + (__pyx_v_mslice->shape[__pyx_v_i]) = 1; + + /* "View.MemoryView":1355 + * for i in range(offset): + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< + * mslice.suboffsets[i] = -1 + * + */ + (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); + + /* "View.MemoryView":1356 + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] + * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; + } + + /* "View.MemoryView":1342 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1364 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + +static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { + int __pyx_t_1; + + /* "View.MemoryView":1368 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + __pyx_t_1 = (__pyx_v_dtype_is_object != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1369 + * + * if dtype_is_object: + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< + * dst.strides, ndim, inc) + * + */ + __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); + + /* "View.MemoryView":1368 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + } + + /* "View.MemoryView":1364 + * + * @cname('__pyx_memoryview_refcount_copying') + * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< + * int ndim, bint inc) nogil: + * + */ + + /* function exit code */ +} + +/* "View.MemoryView":1373 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + +static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + __Pyx_RefNannyDeclarations + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); + + /* "View.MemoryView":1376 + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); + + /* "View.MemoryView":1373 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') + * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * bint inc) with gil: + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + #ifdef WITH_THREAD + __Pyx_PyGILState_Release(__pyx_gilstate_save); + #endif +} + +/* "View.MemoryView":1379 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + +static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); + + /* "View.MemoryView":1383 + * cdef Py_ssize_t i + * + * for i in range(shape[0]): # <<<<<<<<<<<<<< + * if ndim == 1: + * if inc: + */ + __pyx_t_1 = (__pyx_v_shape[0]); + __pyx_t_2 = __pyx_t_1; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_i = __pyx_t_3; + + /* "View.MemoryView":1384 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + __pyx_t_4 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1385 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + __pyx_t_4 = (__pyx_v_inc != 0); + if (__pyx_t_4) { + + /* "View.MemoryView":1386 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + + /* "View.MemoryView":1385 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + goto __pyx_L6; + } + + /* "View.MemoryView":1388 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + */ + /*else*/ { + Py_DECREF((((PyObject **)__pyx_v_data)[0])); + } + __pyx_L6:; + + /* "View.MemoryView":1384 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + goto __pyx_L5; + } + + /* "View.MemoryView":1390 + * Py_DECREF(( data)[0]) + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, inc) + * + */ + /*else*/ { + + /* "View.MemoryView":1391 + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + * ndim - 1, inc) # <<<<<<<<<<<<<< + * + * data += strides[0] + */ + __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); + } + __pyx_L5:; + + /* "View.MemoryView":1393 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + /* "View.MemoryView":1379 + * + * @cname('__pyx_memoryview_refcount_objects_in_slice') + * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, bint inc): + * cdef Py_ssize_t i + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":1399 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + +static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { + + /* "View.MemoryView":1402 + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); + + /* "View.MemoryView":1403 + * bint dtype_is_object) nogil: + * refcount_copying(dst, dtype_is_object, ndim, False) + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1405 + * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, + * itemsize, item) + * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< + * + * + */ + __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); + + /* "View.MemoryView":1399 + * + * @cname('__pyx_memoryview_slice_assign_scalar') + * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< + * size_t itemsize, void *item, + * bint dtype_is_object) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1409 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + +static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { + CYTHON_UNUSED Py_ssize_t __pyx_v_i; + Py_ssize_t __pyx_v_stride; + Py_ssize_t __pyx_v_extent; + int __pyx_t_1; + Py_ssize_t __pyx_t_2; + Py_ssize_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + + /* "View.MemoryView":1413 + * size_t itemsize, void *item) nogil: + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< + * cdef Py_ssize_t extent = shape[0] + * + */ + __pyx_v_stride = (__pyx_v_strides[0]); + + /* "View.MemoryView":1414 + * cdef Py_ssize_t i + * cdef Py_ssize_t stride = strides[0] + * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< + * + * if ndim == 1: + */ + __pyx_v_extent = (__pyx_v_shape[0]); + + /* "View.MemoryView":1416 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1417 + * + * if ndim == 1: + * for i in range(extent): # <<<<<<<<<<<<<< + * memcpy(data, item, itemsize) + * data += stride + */ + __pyx_t_2 = __pyx_v_extent; + __pyx_t_3 = __pyx_t_2; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "View.MemoryView":1418 + * if ndim == 1: + * for i in range(extent): + * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< + * data += stride + * else: + */ + (void)(memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize)); + + /* "View.MemoryView":1419 + * for i in range(extent): + * memcpy(data, item, itemsize) + * data += stride # <<<<<<<<<<<<<< + * else: + * for i in range(extent): + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + + /* "View.MemoryView":1416 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + goto __pyx_L3; + } + + /* "View.MemoryView":1421 + * data += stride + * else: + * for i in range(extent): # <<<<<<<<<<<<<< + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + */ + /*else*/ { + __pyx_t_2 = __pyx_v_extent; + __pyx_t_3 = __pyx_t_2; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "View.MemoryView":1422 + * else: + * for i in range(extent): + * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, itemsize, item) + * data += stride + */ + __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); + + /* "View.MemoryView":1424 + * _slice_assign_scalar(data, shape + 1, strides + 1, + * ndim - 1, itemsize, item) + * data += stride # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + __pyx_v_stride); + } + } + __pyx_L3:; + + /* "View.MemoryView":1409 + * + * @cname('__pyx_memoryview__slice_assign_scalar') + * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< + * Py_ssize_t *strides, int ndim, + * size_t itemsize, void *item) nogil: + */ + + /* function exit code */ +} + +/* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum = {"__pyx_unpickle_Enum", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_Enum (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 1); __PYX_ERR(2, 1, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 2); __PYX_ERR(2, 1, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_Enum") < 0)) __PYX_ERR(2, 1, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(2, 1, __pyx_L3_error) + __pyx_v___pyx_state = values[2]; + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 1, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_PickleError = 0; + PyObject *__pyx_v___pyx_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); + + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result + * if __pyx_checksum not in (0xb068931, 0x82a3537, 0x6ae9995): # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) + */ + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = (__Pyx_PySequence_ContainsTF(__pyx_t_1, __pyx_tuple__21, Py_NE)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + + /* "(tree fragment)":5 + * cdef object __pyx_result + * if __pyx_checksum not in (0xb068931, 0x82a3537, 0x6ae9995): + * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< + * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_PickleError); + __Pyx_GIVEREF(__pyx_n_s_PickleError); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_PickleError); + __pyx_t_4 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_1, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_4, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_1); + __pyx_v___pyx_PickleError = __pyx_t_1; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "(tree fragment)":6 + * if __pyx_checksum not in (0xb068931, 0x82a3537, 0x6ae9995): + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: + */ + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_0x_x_vs_0, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_INCREF(__pyx_v___pyx_PickleError); + __pyx_t_1 = __pyx_v___pyx_PickleError; __pyx_t_6 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_6)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_6); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + } + } + __pyx_t_4 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_1, __pyx_t_6, __pyx_t_5) : __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(2, 6, __pyx_L1_error) + + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result + * if __pyx_checksum not in (0xb068931, 0x82a3537, 0x6ae9995): # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) + */ + } + + /* "(tree fragment)":7 + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = NULL; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + } + } + __pyx_t_4 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_1, __pyx_t_5, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_v___pyx_type); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result = __pyx_t_4; + __pyx_t_4 = 0; + + /* "(tree fragment)":8 + * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + */ + __pyx_t_3 = (__pyx_v___pyx_state != Py_None); + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + + /* "(tree fragment)":9 + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + */ + if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(2, 9, __pyx_L1_error) + __pyx_t_4 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "(tree fragment)":8 + * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + */ + } + + /* "(tree fragment)":10 + * if __pyx_state is not None: + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + * __pyx_result.name = __pyx_state[0] + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + goto __pyx_L0; + + /* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_PickleError); + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":11 + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + */ + +static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_unpickle_Enum__set_state", 0); + + /* "(tree fragment)":12 + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + * __pyx_result.name = __pyx_state[0] # <<<<<<<<<<<<<< + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + * __pyx_result.__dict__.update(__pyx_state[1]) + */ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(2, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->name); + __Pyx_DECREF(__pyx_v___pyx_result->name); + __pyx_v___pyx_result->name = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< + * __pyx_result.__dict__.update(__pyx_state[1]) + */ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(2, 13, __pyx_L1_error) + } + __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(2, 13, __pyx_L1_error) + __pyx_t_4 = ((__pyx_t_3 > 1) != 0); + if (__pyx_t_4) { + } else { + __pyx_t_2 = __pyx_t_4; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 13, __pyx_L1_error) + __pyx_t_5 = (__pyx_t_4 != 0); + __pyx_t_2 = __pyx_t_5; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "(tree fragment)":14 + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + * __pyx_result.__dict__.update(__pyx_state[1]) # <<<<<<<<<<<<<< + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(2, 14, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = NULL; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_8)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + } + } + __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< + * __pyx_result.__dict__.update(__pyx_state[1]) + */ + } + + /* "(tree fragment)":11 + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_array __pyx_vtable_array; + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_array; + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_array___dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = __Pyx_PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_array_1__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_array_3__setstate_cython__, METH_O, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, (char *)0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + __pyx_array___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + __pyx_array___len__, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + __pyx_array_getbuffer, /*bf_getbuffer*/ + 0, /*bf_releasebuffer*/ +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) + "ueg_kernels.array", /*tp_name*/ + sizeof(struct __pyx_array_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_array, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + __pyx_tp_getattro_array, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_array, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_array, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_array, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 + 0, /*tp_print*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; + +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_MemviewEnum_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_MemviewEnum_obj *)o); + p->name = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_Enum(PyObject *o) { + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->name); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + if (p->name) { + e = (*v)(p->name, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_Enum(PyObject *o) { + PyObject* tmp; + struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; + tmp = ((PyObject*)p->name); + p->name = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_Enum[] = { + {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_1__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_3__setstate_cython__, METH_O, 0}, + {0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_MemviewEnum = { + PyVarObject_HEAD_INIT(0, 0) + "ueg_kernels.Enum", /*tp_name*/ + sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_Enum, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ + #endif + __pyx_MemviewEnum___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_Enum, /*tp_traverse*/ + __pyx_tp_clear_Enum, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_Enum, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + __pyx_MemviewEnum___init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_Enum, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 + 0, /*tp_print*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; + +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryview_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryview_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_memoryview; + p->obj = Py_None; Py_INCREF(Py_None); + p->_size = Py_None; Py_INCREF(Py_None); + p->_array_interface = Py_None; Py_INCREF(Py_None); + p->view.obj = NULL; + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static void __pyx_tp_dealloc_memoryview(PyObject *o) { + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_memoryview___dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->obj); + Py_CLEAR(p->_size); + Py_CLEAR(p->_array_interface); + (*Py_TYPE(o)->tp_free)(o); +} + +static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + if (p->obj) { + e = (*v)(p->obj, a); if (e) return e; + } + if (p->_size) { + e = (*v)(p->_size, a); if (e) return e; + } + if (p->_array_interface) { + e = (*v)(p->_array_interface, a); if (e) return e; + } + if (p->view.obj) { + e = (*v)(p->view.obj, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_memoryview(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; + tmp = ((PyObject*)p->obj); + p->obj = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_size); + p->_size = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_array_interface); + p->_array_interface = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + Py_CLEAR(p->view.obj); + return 0; +} +static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_memoryview___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(o); +} + +static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(o); +} + +static PyMethodDef __pyx_methods_memoryview[] = { + {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, + {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, + {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, + {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, + {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_1__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_3__setstate_cython__, METH_O, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_memoryview[] = { + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, (char *)0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, (char *)0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, (char *)0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, (char *)0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, (char *)0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, (char *)0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, (char *)0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, (char *)0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, (char *)0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_memoryview = { + __pyx_memoryview___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_memoryview, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_memoryview = { + __pyx_memoryview___len__, /*mp_length*/ + __pyx_memoryview___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_memoryview = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + __pyx_memoryview_getbuffer, /*bf_getbuffer*/ + 0, /*bf_releasebuffer*/ +}; + +static PyTypeObject __pyx_type___pyx_memoryview = { + PyVarObject_HEAD_INIT(0, 0) + "ueg_kernels.memoryview", /*tp_name*/ + sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ + #endif + __pyx_memoryview___repr__, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_memoryview___str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_memoryview, /*tp_traverse*/ + __pyx_tp_clear_memoryview, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_memoryview, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_memoryview, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_memoryview, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 + 0, /*tp_print*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; + +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_memoryviewslice_obj *p; + PyObject *o = __pyx_tp_new_memoryview(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_memoryviewslice_obj *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; + p->from_object = Py_None; Py_INCREF(Py_None); + p->from_slice.memview = NULL; + return o; +} + +static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_memoryviewslice___dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->from_object); + PyObject_GC_Track(o); + __pyx_tp_dealloc_memoryview(o); +} + +static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; + if (p->from_object) { + e = (*v)(p->from_object, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear__memoryviewslice(PyObject *o) { + PyObject* tmp; + struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; + __pyx_tp_clear_memoryview(o); + tmp = ((PyObject*)p->from_object); + p->from_object = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + __PYX_XDEC_MEMVIEW(&p->from_slice, 1); + return 0; +} + +static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); +} + +static PyMethodDef __pyx_methods__memoryviewslice[] = { + {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_1__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_3__setstate_cython__, METH_O, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, (char *)0, 0}, + {0, 0, 0, 0, 0} +}; + +static PyTypeObject __pyx_type___pyx_memoryviewslice = { + PyVarObject_HEAD_INIT(0, 0) + "ueg_kernels._memoryviewslice", /*tp_name*/ + sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ + #endif + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___repr__, /*tp_repr*/ + #else + 0, /*tp_repr*/ + #endif + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + #if CYTHON_COMPILING_IN_PYPY + __pyx_memoryview___str__, /*tp_str*/ + #else + 0, /*tp_str*/ + #endif + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + "Internal class for passing memoryview slices to Python", /*tp_doc*/ + __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ + __pyx_tp_clear__memoryviewslice, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods__memoryviewslice, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets__memoryviewslice, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new__memoryviewslice, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + 0, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 + 0, /*tp_print*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; + +#if PY_MAJOR_VERSION >= 3 +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_ueg_kernels(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_ueg_kernels}, + {0, NULL} +}; +#endif + +static struct PyModuleDef __pyx_moduledef = { + PyModuleDef_HEAD_INIT, + "ueg_kernels", + 0, /* m_doc */ + #if CYTHON_PEP489_MULTI_PHASE_INIT + 0, /* m_size */ + #else + -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1}, + {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, + {&__pyx_n_s_CTdagger, __pyx_k_CTdagger, sizeof(__pyx_k_CTdagger), 0, 0, 1, 1}, + {&__pyx_n_s_CTdagger_i, __pyx_k_CTdagger_i, sizeof(__pyx_k_CTdagger_i), 0, 0, 1, 1}, + {&__pyx_n_s_CTdagger_i_cube, __pyx_k_CTdagger_i_cube, sizeof(__pyx_k_CTdagger_i_cube), 0, 0, 1, 1}, + {&__pyx_n_s_CTdagger_j, __pyx_k_CTdagger_j, sizeof(__pyx_k_CTdagger_j), 0, 0, 1, 1}, + {&__pyx_n_s_CTdagger_j_cube, __pyx_k_CTdagger_j_cube, sizeof(__pyx_k_CTdagger_j_cube), 0, 0, 1, 1}, + {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, + {&__pyx_kp_s_Cannot_assign_to_read_only_memor, __pyx_k_Cannot_assign_to_read_only_memor, sizeof(__pyx_k_Cannot_assign_to_read_only_memor), 0, 0, 1, 0}, + {&__pyx_kp_s_Cannot_create_writable_memory_vi, __pyx_k_Cannot_create_writable_memory_vi, sizeof(__pyx_k_Cannot_create_writable_memory_vi), 0, 0, 1, 0}, + {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, + {&__pyx_n_s_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, + {&__pyx_n_s_DTYPE_CX, __pyx_k_DTYPE_CX, sizeof(__pyx_k_DTYPE_CX), 0, 0, 1, 1}, + {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, + {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, + {&__pyx_n_s_G, __pyx_k_G, sizeof(__pyx_k_G), 0, 0, 1, 1}, + {&__pyx_n_s_Gh_i, __pyx_k_Gh_i, sizeof(__pyx_k_Gh_i), 0, 0, 1, 1}, + {&__pyx_n_s_Gh_i_cube, __pyx_k_Gh_i_cube, sizeof(__pyx_k_Gh_i_cube), 0, 0, 1, 1}, + {&__pyx_n_s_Gh_j, __pyx_k_Gh_j, sizeof(__pyx_k_Gh_j), 0, 0, 1, 1}, + {&__pyx_n_s_Gh_j_cube, __pyx_k_Gh_j_cube, sizeof(__pyx_k_Gh_j_cube), 0, 0, 1, 1}, + {&__pyx_n_s_Ghalf, __pyx_k_Ghalf, sizeof(__pyx_k_Ghalf), 0, 0, 1, 1}, + {&__pyx_n_s_Gkpq, __pyx_k_Gkpq, sizeof(__pyx_k_Gkpq), 0, 0, 1, 1}, + {&__pyx_n_s_Gpmq, __pyx_k_Gpmq, sizeof(__pyx_k_Gpmq), 0, 0, 1, 1}, + {&__pyx_n_s_Gprod, __pyx_k_Gprod, sizeof(__pyx_k_Gprod), 0, 0, 1, 1}, + {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, + {&__pyx_kp_s_Incompatible_checksums_0x_x_vs_0, __pyx_k_Incompatible_checksums_0x_x_vs_0, sizeof(__pyx_k_Incompatible_checksums_0x_x_vs_0), 0, 0, 1, 0}, + {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, + {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, + {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, + {&__pyx_n_s_J, __pyx_k_J, sizeof(__pyx_k_J), 0, 0, 1, 1}, + {&__pyx_n_s_K, __pyx_k_K, sizeof(__pyx_k_K), 0, 0, 1, 1}, + {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, + {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, + {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, + {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, + {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, + {&__pyx_n_s_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, + {&__pyx_n_s_T, __pyx_k_T, sizeof(__pyx_k_T), 0, 0, 1, 1}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_View_MemoryView, __pyx_k_View_MemoryView, sizeof(__pyx_k_View_MemoryView), 0, 0, 1, 1}, + {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, + {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, + {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, + {&__pyx_n_s_basis, __pyx_k_basis, sizeof(__pyx_k_basis), 0, 0, 1, 1}, + {&__pyx_n_s_build_J_opt, __pyx_k_build_J_opt, sizeof(__pyx_k_build_J_opt), 0, 0, 1, 1}, + {&__pyx_n_s_build_K_opt, __pyx_k_build_K_opt, sizeof(__pyx_k_build_K_opt), 0, 0, 1, 1}, + {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, + {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, + {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, + {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, + {&__pyx_n_s_complex128, __pyx_k_complex128, sizeof(__pyx_k_complex128), 0, 0, 1, 1}, + {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_convolve, __pyx_k_convolve, sizeof(__pyx_k_convolve), 0, 0, 1, 1}, + {&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, + {&__pyx_n_s_coulomb_greens_function_per_qvec, __pyx_k_coulomb_greens_function_per_qvec, sizeof(__pyx_k_coulomb_greens_function_per_qvec), 0, 0, 1, 1}, + {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, + {&__pyx_n_s_dot, __pyx_k_dot, sizeof(__pyx_k_dot), 0, 0, 1, 1}, + {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, + {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, + {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, + {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, + {&__pyx_n_s_exchange_greens_function_fft, __pyx_k_exchange_greens_function_fft, sizeof(__pyx_k_exchange_greens_function_fft), 0, 0, 1, 1}, + {&__pyx_n_s_exchange_greens_function_per_qve, __pyx_k_exchange_greens_function_per_qve, sizeof(__pyx_k_exchange_greens_function_per_qve), 0, 0, 1, 1}, + {&__pyx_n_s_fac, __pyx_k_fac, sizeof(__pyx_k_fac), 0, 0, 1, 1}, + {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, + {&__pyx_n_s_flip, __pyx_k_flip, sizeof(__pyx_k_flip), 0, 0, 1, 1}, + {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, + {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, + {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, + {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, + {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, + {&__pyx_n_s_gmap, __pyx_k_gmap, sizeof(__pyx_k_gmap), 0, 0, 1, 1}, + {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, + {&__pyx_n_s_h1e_mod, __pyx_k_h1e_mod, sizeof(__pyx_k_h1e_mod), 0, 0, 1, 1}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_idxj, __pyx_k_idxj, sizeof(__pyx_k_idxj), 0, 0, 1, 1}, + {&__pyx_n_s_idxjmq, __pyx_k_idxjmq, sizeof(__pyx_k_idxjmq), 0, 0, 1, 1}, + {&__pyx_n_s_idxjpq, __pyx_k_idxjpq, sizeof(__pyx_k_idxjpq), 0, 0, 1, 1}, + {&__pyx_n_s_idxk, __pyx_k_idxk, sizeof(__pyx_k_idxk), 0, 0, 1, 1}, + {&__pyx_n_s_idxkpq, __pyx_k_idxkpq, sizeof(__pyx_k_idxkpq), 0, 0, 1, 1}, + {&__pyx_n_s_idxp, __pyx_k_idxp, sizeof(__pyx_k_idxp), 0, 0, 1, 1}, + {&__pyx_n_s_idxpmq, __pyx_k_idxpmq, sizeof(__pyx_k_idxpmq), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_inkpq, __pyx_k_inkpq, sizeof(__pyx_k_inkpq), 0, 0, 1, 1}, + {&__pyx_n_s_ipie_legacy_estimators_utils, __pyx_k_ipie_legacy_estimators_utils, sizeof(__pyx_k_ipie_legacy_estimators_utils), 0, 0, 1, 1}, + {&__pyx_n_s_iq, __pyx_k_iq, sizeof(__pyx_k_iq), 0, 0, 1, 1}, + {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, + {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, + {&__pyx_n_s_itertools, __pyx_k_itertools, sizeof(__pyx_k_itertools), 0, 0, 1, 1}, + {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, + {&__pyx_n_s_jnpmq, __pyx_k_jnpmq, sizeof(__pyx_k_jnpmq), 0, 0, 1, 1}, + {&__pyx_n_s_kfac, __pyx_k_kfac, sizeof(__pyx_k_kfac), 0, 0, 1, 1}, + {&__pyx_n_s_ki, __pyx_k_ki, sizeof(__pyx_k_ki), 0, 0, 1, 1}, + {&__pyx_n_s_kj, __pyx_k_kj, sizeof(__pyx_k_kj), 0, 0, 1, 1}, + {&__pyx_n_s_kpq, __pyx_k_kpq, sizeof(__pyx_k_kpq), 0, 0, 1, 1}, + {&__pyx_n_s_kpq_i, __pyx_k_kpq_i, sizeof(__pyx_k_kpq_i), 0, 0, 1, 1}, + {&__pyx_n_s_lQ_ij, __pyx_k_lQ_ij, sizeof(__pyx_k_lQ_ij), 0, 0, 1, 1}, + {&__pyx_n_s_lQ_ji, __pyx_k_lQ_ji, sizeof(__pyx_k_lQ_ji), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_math, __pyx_k_math, sizeof(__pyx_k_math), 0, 0, 1, 1}, + {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, + {&__pyx_n_s_mesh, __pyx_k_mesh, sizeof(__pyx_k_mesh), 0, 0, 1, 1}, + {&__pyx_n_s_mod_one_body, __pyx_k_mod_one_body, sizeof(__pyx_k_mod_one_body), 0, 0, 1, 1}, + {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, + {&__pyx_n_s_nbsf, __pyx_k_nbsf, sizeof(__pyx_k_nbsf), 0, 0, 1, 1}, + {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, + {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, + {&__pyx_n_s_ngrid, __pyx_k_ngrid, sizeof(__pyx_k_ngrid), 0, 0, 1, 1}, + {&__pyx_n_s_nkpq, __pyx_k_nkpq, sizeof(__pyx_k_nkpq), 0, 0, 1, 1}, + {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, + {&__pyx_n_s_nocc, __pyx_k_nocc, sizeof(__pyx_k_nocc), 0, 0, 1, 1}, + {&__pyx_n_s_npmq, __pyx_k_npmq, sizeof(__pyx_k_npmq), 0, 0, 1, 1}, + {&__pyx_n_s_nq, __pyx_k_nq, sizeof(__pyx_k_nq), 0, 0, 1, 1}, + {&__pyx_n_s_nqgrid, __pyx_k_nqgrid, sizeof(__pyx_k_nqgrid), 0, 0, 1, 1}, + {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, + {&__pyx_kp_u_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 1, 0, 0}, + {&__pyx_kp_u_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 1, 0, 0}, + {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, + {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, + {&__pyx_n_s_pi, __pyx_k_pi, sizeof(__pyx_k_pi), 0, 0, 1, 1}, + {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, + {&__pyx_n_s_pmq, __pyx_k_pmq, sizeof(__pyx_k_pmq), 0, 0, 1, 1}, + {&__pyx_n_s_pmq_i, __pyx_k_pmq_i, sizeof(__pyx_k_pmq_i), 0, 0, 1, 1}, + {&__pyx_n_s_prod, __pyx_k_prod, sizeof(__pyx_k_prod), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_unpickle_Enum, __pyx_k_pyx_unpickle_Enum, sizeof(__pyx_k_pyx_unpickle_Enum), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_q, __pyx_k_q, sizeof(__pyx_k_q), 0, 0, 1, 1}, + {&__pyx_n_s_q2, __pyx_k_q2, sizeof(__pyx_k_q2), 0, 0, 1, 1}, + {&__pyx_n_s_qmap, __pyx_k_qmap, sizeof(__pyx_k_qmap), 0, 0, 1, 1}, + {&__pyx_n_s_qmesh, __pyx_k_qmesh, sizeof(__pyx_k_qmesh), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, + {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, + {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, + {&__pyx_n_s_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 0, 1, 1}, + {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, + {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, + {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, + {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, + {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, + {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, + {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, + {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, + {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, + {&__pyx_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, + {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_ueg_kernels, __pyx_k_ueg_kernels, sizeof(__pyx_k_ueg_kernels), 0, 0, 1, 1}, + {&__pyx_kp_s_ueg_kernels_pyx, __pyx_k_ueg_kernels_pyx, sizeof(__pyx_k_ueg_kernels_pyx), 0, 0, 1, 0}, + {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, + {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, + {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, + {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, + {&__pyx_n_s_vol, __pyx_k_vol, sizeof(__pyx_k_vol), 0, 0, 1, 1}, + {&__pyx_n_s_vq, __pyx_k_vq, sizeof(__pyx_k_vq), 0, 0, 1, 1}, + {&__pyx_n_s_vqvec, __pyx_k_vqvec, sizeof(__pyx_k_vqvec), 0, 0, 1, 1}, + {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, + {&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} +}; +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(0, 38, __pyx_L1_error) + __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 54, __pyx_L1_error) + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 70, __pyx_L1_error) + __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 944, __pyx_L1_error) + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(2, 134, __pyx_L1_error) + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(2, 149, __pyx_L1_error) + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(2, 2, __pyx_L1_error) + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(2, 406, __pyx_L1_error) + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(2, 615, __pyx_L1_error) + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(2, 834, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} + +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":944 + * __pyx_import_array() + * except Exception: + * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< + * + * cdef inline int import_umath() except -1: + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 944, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":950 + * _import_umath() + * except Exception: + * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< + * + * cdef inline int import_ufunc() except -1: + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 950, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "View.MemoryView":134 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(2, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "View.MemoryView":137 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if not isinstance(format, bytes): + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(2, 137, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "View.MemoryView":149 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(2, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "View.MemoryView":177 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(2, 177, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "View.MemoryView":193 + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< + * info.buf = self.data + * info.len = self.len + */ + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(2, 193, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(2, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + + /* "View.MemoryView":420 + * def __setitem__(memoryview self, object index, object value): + * if self.view.readonly: + * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< + * + * have_slices, index = _unellipsify(index, self.view.ndim) + */ + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(2, 420, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + + /* "View.MemoryView":497 + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< + * else: + * if len(self.view.format) == 1: + */ + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(2, 497, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + + /* "View.MemoryView":522 + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_WRITABLE and self.view.readonly: + * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< + * + * if flags & PyBUF_ND: + */ + __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(2, 522, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + + /* "View.MemoryView":572 + * if self.view.strides == NULL: + * + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) + */ + __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(2, 572, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + + /* "View.MemoryView":579 + * def suboffsets(self): + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) + */ + __pyx_tuple__14 = PyTuple_New(1); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(2, 579, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_INCREF(__pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_tuple__14, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_tuple__14); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(2, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + + /* "View.MemoryView":684 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_slice__17 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__17)) __PYX_ERR(2, 684, __pyx_L1_error) + __Pyx_GOTREF(__pyx_slice__17); + __Pyx_GIVEREF(__pyx_slice__17); + + /* "View.MemoryView":705 + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(2, 705, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__18); + __Pyx_GIVEREF(__pyx_tuple__18); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(2, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__20); + __Pyx_GIVEREF(__pyx_tuple__20); + __pyx_tuple__21 = PyTuple_Pack(3, __pyx_int_184977713, __pyx_int_136983863, __pyx_int_112105877); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(2, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); + + /* "ueg_kernels.pyx":14 + * + * + * def vq(numpy.ndarray q): # <<<<<<<<<<<<<< + * assert(q.shape[0] == 3) + * cdef double q2 = numpy.dot(q, q) + */ + __pyx_tuple__22 = PyTuple_Pack(2, __pyx_n_s_q, __pyx_n_s_q2); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__22); + __Pyx_GIVEREF(__pyx_tuple__22); + __pyx_codeobj__23 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__22, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_vq, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__23)) __PYX_ERR(0, 14, __pyx_L1_error) + + /* "ueg_kernels.pyx":22 + * return 4*math.pi / q2 + * + * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): # <<<<<<<<<<<<<< + * """ Add a diagonal term of two-body Hamiltonian to the one-body term + * Parameters + */ + __pyx_tuple__24 = PyTuple_Pack(12, __pyx_n_s_T, __pyx_n_s_basis, __pyx_n_s_vol, __pyx_n_s_kfac, __pyx_n_s_nbsf, __pyx_n_s_h1e_mod, __pyx_n_s_fac, __pyx_n_s_i, __pyx_n_s_ki, __pyx_n_s_j, __pyx_n_s_kj, __pyx_n_s_q); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(0, 22, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(4, 0, 12, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__24, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_mod_one_body, 22, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) __PYX_ERR(0, 22, __pyx_L1_error) + + /* "ueg_kernels.pyx":45 + * return h1e_mod + * + * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): # <<<<<<<<<<<<<< + * + * cdef int nq = kpq_i.shape[0] + */ + __pyx_tuple__26 = PyTuple_Pack(13, __pyx_n_s_kpq_i, __pyx_n_s_kpq, __pyx_n_s_pmq_i, __pyx_n_s_pmq, __pyx_n_s_G, __pyx_n_s_nq, __pyx_n_s_idxkpq, __pyx_n_s_idxpmq, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_iq, __pyx_n_s_Gkpq, __pyx_n_s_Gpmq); if (unlikely(!__pyx_tuple__26)) __PYX_ERR(0, 45, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__26); + __Pyx_GIVEREF(__pyx_tuple__26); + __pyx_codeobj__27 = (PyObject*)__Pyx_PyCode_New(5, 0, 13, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__26, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_coulomb_greens_function_per_qvec, 45, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__27)) __PYX_ERR(0, 45, __pyx_L1_error) + + /* "ueg_kernels.pyx":61 + * return Gkpq, Gpmq + * + * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): # <<<<<<<<<<<<<< + * + * cdef int nkpq = kpq_i.shape[0] + */ + __pyx_tuple__28 = PyTuple_Pack(14, __pyx_n_s_kpq_i, __pyx_n_s_kpq, __pyx_n_s_pmq_i, __pyx_n_s_pmq, __pyx_n_s_G, __pyx_n_s_nkpq, __pyx_n_s_npmq, __pyx_n_s_Gprod, __pyx_n_s_idxkpq, __pyx_n_s_idxpmq, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_inkpq, __pyx_n_s_jnpmq); if (unlikely(!__pyx_tuple__28)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__28); + __Pyx_GIVEREF(__pyx_tuple__28); + __pyx_codeobj__29 = (PyObject*)__Pyx_PyCode_New(5, 0, 14, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__28, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_exchange_greens_function_per_qve, 61, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__29)) __PYX_ERR(0, 61, __pyx_L1_error) + + /* "ueg_kernels.pyx":80 + * return Gprod + * + * def exchange_greens_function_fft (long nocc, long nbsf, # <<<<<<<<<<<<<< + * long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, + * double complex[:,:] CTdagger, double complex[:,:] Ghalf): + */ + __pyx_tuple__30 = PyTuple_Pack(24, __pyx_n_s_nocc, __pyx_n_s_nbsf, __pyx_n_s_mesh, __pyx_n_s_qmesh, __pyx_n_s_gmap, __pyx_n_s_qmap, __pyx_n_s_CTdagger, __pyx_n_s_Ghalf, __pyx_n_s_ngrid, __pyx_n_s_nqgrid, __pyx_n_s_nq, __pyx_n_s_Gprod, __pyx_n_s_Gh_i, __pyx_n_s_CTdagger_j, __pyx_n_s_Gh_i_cube, __pyx_n_s_CTdagger_j_cube, __pyx_n_s_Gh_j, __pyx_n_s_CTdagger_i, __pyx_n_s_Gh_j_cube, __pyx_n_s_CTdagger_i_cube, __pyx_n_s_lQ_ji, __pyx_n_s_lQ_ij, __pyx_n_s_i, __pyx_n_s_j); if (unlikely(!__pyx_tuple__30)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__30); + __Pyx_GIVEREF(__pyx_tuple__30); + __pyx_codeobj__31 = (PyObject*)__Pyx_PyCode_New(8, 0, 24, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__30, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_exchange_greens_function_fft, 80, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__31)) __PYX_ERR(0, 80, __pyx_L1_error) + + /* "ueg_kernels.pyx":138 + * return Gprod + * + * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< + * list kpq, list pmq_i, list pmq, + * double complex[:,:] Gkpq, double complex[:,:] Gpmq): + */ + __pyx_tuple__32 = PyTuple_Pack(14, __pyx_n_s_nq, __pyx_n_s_vqvec, __pyx_n_s_vol, __pyx_n_s_nbsf, __pyx_n_s_kpq_i, __pyx_n_s_kpq, __pyx_n_s_pmq_i, __pyx_n_s_pmq, __pyx_n_s_Gkpq, __pyx_n_s_Gpmq, __pyx_n_s_J, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_iq); if (unlikely(!__pyx_tuple__32)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__32); + __Pyx_GIVEREF(__pyx_tuple__32); + __pyx_codeobj__33 = (PyObject*)__Pyx_PyCode_New(10, 0, 14, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__32, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_build_J_opt, 138, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__33)) __PYX_ERR(0, 138, __pyx_L1_error) + + /* "ueg_kernels.pyx":154 + * return J + * + * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< + * list kpq, list pmq_i, list pmq, + * double complex[:,:,:] G): + */ + __pyx_tuple__34 = PyTuple_Pack(19, __pyx_n_s_nq, __pyx_n_s_vqvec, __pyx_n_s_vol, __pyx_n_s_nbsf, __pyx_n_s_kpq_i, __pyx_n_s_kpq, __pyx_n_s_pmq_i, __pyx_n_s_pmq, __pyx_n_s_G, __pyx_n_s_K, __pyx_n_s_iq, __pyx_n_s_s, __pyx_n_s_idxjmq, __pyx_n_s_idxkpq, __pyx_n_s_idxk, __pyx_n_s_idxjpq, __pyx_n_s_idxj, __pyx_n_s_idxpmq, __pyx_n_s_idxp); if (unlikely(!__pyx_tuple__34)) __PYX_ERR(0, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__34); + __Pyx_GIVEREF(__pyx_tuple__34); + __pyx_codeobj__35 = (PyObject*)__Pyx_PyCode_New(9, 0, 19, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_build_K_opt, 154, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__35)) __PYX_ERR(0, 154, __pyx_L1_error) + + /* "View.MemoryView":287 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_tuple__36 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__36)) __PYX_ERR(2, 287, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__36); + __Pyx_GIVEREF(__pyx_tuple__36); + + /* "View.MemoryView":288 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_tuple__37 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__37)) __PYX_ERR(2, 288, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__37); + __Pyx_GIVEREF(__pyx_tuple__37); + + /* "View.MemoryView":289 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__38 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__38)) __PYX_ERR(2, 289, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__38); + __Pyx_GIVEREF(__pyx_tuple__38); + + /* "View.MemoryView":292 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_tuple__39 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__39)) __PYX_ERR(2, 292, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__39); + __Pyx_GIVEREF(__pyx_tuple__39); + + /* "View.MemoryView":293 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__40 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__40)) __PYX_ERR(2, 293, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__40); + __Pyx_GIVEREF(__pyx_tuple__40); + + /* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result + */ + __pyx_tuple__41 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__41)) __PYX_ERR(2, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__41); + __Pyx_GIVEREF(__pyx_tuple__41); + __pyx_codeobj__42 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__41, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__42)) __PYX_ERR(2, 1, __pyx_L1_error) + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { + if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_float_0_0 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_float_0_0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_4 = PyInt_FromLong(4); if (unlikely(!__pyx_int_4)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_112105877 = PyInt_FromLong(112105877L); if (unlikely(!__pyx_int_112105877)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_136983863 = PyInt_FromLong(136983863L); if (unlikely(!__pyx_int_136983863)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_184977713 = PyInt_FromLong(184977713L); if (unlikely(!__pyx_int_184977713)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} + +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ + +static int __Pyx_modinit_global_init_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + generic = Py_None; Py_INCREF(Py_None); + strided = Py_None; Py_INCREF(Py_None); + indirect = Py_None; Py_INCREF(Py_None); + contiguous = Py_None; Py_INCREF(Py_None); + indirect_contiguous = Py_None; Py_INCREF(Py_None); + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(void) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + __pyx_vtabptr_array = &__pyx_vtable_array; + __pyx_vtable_array.get_memview = (PyObject *(*)(struct __pyx_array_obj *))__pyx_array_get_memview; + if (PyType_Ready(&__pyx_type___pyx_array) < 0) __PYX_ERR(2, 106, __pyx_L1_error) + #if PY_VERSION_HEX < 0x030800B1 + __pyx_type___pyx_array.tp_print = 0; + #endif + if (__Pyx_SetVtable(__pyx_type___pyx_array.tp_dict, __pyx_vtabptr_array) < 0) __PYX_ERR(2, 106, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(2, 106, __pyx_L1_error) + __pyx_array_type = &__pyx_type___pyx_array; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(2, 280, __pyx_L1_error) + #if PY_VERSION_HEX < 0x030800B1 + __pyx_type___pyx_MemviewEnum.tp_print = 0; + #endif + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_MemviewEnum.tp_dictoffset && __pyx_type___pyx_MemviewEnum.tp_getattro == PyObject_GenericGetAttr)) { + __pyx_type___pyx_MemviewEnum.tp_getattro = __Pyx_PyObject_GenericGetAttr; + } + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(2, 280, __pyx_L1_error) + __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; + __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; + __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; + __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; + __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; + __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; + __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; + __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; + __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(2, 331, __pyx_L1_error) + #if PY_VERSION_HEX < 0x030800B1 + __pyx_type___pyx_memoryview.tp_print = 0; + #endif + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryview.tp_dictoffset && __pyx_type___pyx_memoryview.tp_getattro == PyObject_GenericGetAttr)) { + __pyx_type___pyx_memoryview.tp_getattro = __Pyx_PyObject_GenericGetAttr; + } + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(2, 331, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(2, 331, __pyx_L1_error) + __pyx_memoryview_type = &__pyx_type___pyx_memoryview; + __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; + __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; + __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; + __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; + __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(2, 967, __pyx_L1_error) + #if PY_VERSION_HEX < 0x030800B1 + __pyx_type___pyx_memoryviewslice.tp_print = 0; + #endif + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryviewslice.tp_dictoffset && __pyx_type___pyx_memoryviewslice.tp_getattro == PyObject_GenericGetAttr)) { + __pyx_type___pyx_memoryviewslice.tp_getattro = __Pyx_PyObject_GenericGetAttr; + } + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(2, 967, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(2, 967, __pyx_L1_error) + __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(void) { + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_ptype_7cpython_4type_type = __Pyx_ImportType_0_29_35(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(PyTypeObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyTypeObject), + #else + sizeof(PyHeapTypeObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyHeapTypeObject), + #endif + __Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(3, 9, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule("numpy"); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 199, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_ptype_5numpy_dtype = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "dtype", sizeof(PyArray_Descr), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyArray_Descr),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_dtype) __PYX_ERR(1, 199, __pyx_L1_error) + __pyx_ptype_5numpy_flatiter = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "flatiter", sizeof(PyArrayIterObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyArrayIterObject),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_flatiter) __PYX_ERR(1, 222, __pyx_L1_error) + __pyx_ptype_5numpy_broadcast = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "broadcast", sizeof(PyArrayMultiIterObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyArrayMultiIterObject),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_broadcast) __PYX_ERR(1, 226, __pyx_L1_error) + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "ndarray", sizeof(PyArrayObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyArrayObject),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_ndarray) __PYX_ERR(1, 238, __pyx_L1_error) + __pyx_ptype_5numpy_generic = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "generic", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_generic) __PYX_ERR(1, 770, __pyx_L1_error) + __pyx_ptype_5numpy_number = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "number", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_number) __PYX_ERR(1, 772, __pyx_L1_error) + __pyx_ptype_5numpy_integer = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "integer", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_integer) __PYX_ERR(1, 774, __pyx_L1_error) + __pyx_ptype_5numpy_signedinteger = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "signedinteger", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_signedinteger) __PYX_ERR(1, 776, __pyx_L1_error) + __pyx_ptype_5numpy_unsignedinteger = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "unsignedinteger", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_unsignedinteger) __PYX_ERR(1, 778, __pyx_L1_error) + __pyx_ptype_5numpy_inexact = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "inexact", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_inexact) __PYX_ERR(1, 780, __pyx_L1_error) + __pyx_ptype_5numpy_floating = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "floating", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_floating) __PYX_ERR(1, 782, __pyx_L1_error) + __pyx_ptype_5numpy_complexfloating = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "complexfloating", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_complexfloating) __PYX_ERR(1, 784, __pyx_L1_error) + __pyx_ptype_5numpy_flexible = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "flexible", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_flexible) __PYX_ERR(1, 786, __pyx_L1_error) + __pyx_ptype_5numpy_character = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "character", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_character) __PYX_ERR(1, 788, __pyx_L1_error) + __pyx_ptype_5numpy_ufunc = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "ufunc", sizeof(PyUFuncObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyUFuncObject),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_ufunc) __PYX_ERR(1, 826, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_variable_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + + +#ifndef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#elif PY_MAJOR_VERSION < 3 +#ifdef __cplusplus +#define __Pyx_PyMODINIT_FUNC extern "C" void +#else +#define __Pyx_PyMODINIT_FUNC void +#endif +#else +#ifdef __cplusplus +#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * +#else +#define __Pyx_PyMODINIT_FUNC PyObject * +#endif +#endif + + +#if PY_MAJOR_VERSION < 3 +__Pyx_PyMODINIT_FUNC initueg_kernels(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC initueg_kernels(void) +#else +__Pyx_PyMODINIT_FUNC PyInit_ueg_kernels(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_ueg_kernels(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + #if PY_VERSION_HEX >= 0x030700A1 + static PY_INT64_T main_interpreter_id = -1; + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return (unlikely(current_id == -1)) ? -1 : 0; + } else if (unlikely(main_interpreter_id != current_id)) + #else + static PyInterpreterState *main_interpreter = NULL; + PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; + if (!main_interpreter) { + main_interpreter = current_interpreter; + } else if (unlikely(main_interpreter != current_interpreter)) + #endif + { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + if (__Pyx_check_single_interpreter()) + return NULL; + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_ueg_kernels(PyObject *__pyx_pyinit_module) +#endif +#endif +{ + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + static PyThread_type_lock __pyx_t_3[8]; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'ueg_kernels' has already been imported. Re-initialisation is not supported."); + return -1; + } + #elif PY_MAJOR_VERSION >= 3 + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + #if CYTHON_REFNANNY +__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); +if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); +} +#endif + __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_ueg_kernels(void)", 0); + if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pxy_PyFrame_Initialize_Offsets + __Pxy_PyFrame_Initialize_Offsets(); + #endif + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pyx_CyFunction_USED + if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Coroutine_USED + if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_StopAsyncIteration_USED + if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + PyEval_InitThreads(); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_m = __pyx_pyinit_module; + Py_INCREF(__pyx_m); + #else + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("ueg_kernels", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + #endif + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_d); + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_b); + __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_cython_runtime); + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + if (__pyx_module_is_main_ueg_kernels) { + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name_2, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "ueg_kernels")) { + if (unlikely(PyDict_SetItemString(modules, "ueg_kernels", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #endif + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(); + (void)__Pyx_modinit_variable_export_code(); + (void)__Pyx_modinit_function_export_code(); + if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely(__Pyx_modinit_type_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_variable_import_code(); + (void)__Pyx_modinit_function_import_code(); + /*--- Execution code ---*/ + #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) + if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + + /* "ueg_kernels.pyx":1 + * import numpy # <<<<<<<<<<<<<< + * + * cimport numpy + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_numpy, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":5 + * cimport numpy + * + * import itertools # <<<<<<<<<<<<<< + * import math + * + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_itertools, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_itertools, __pyx_t_1) < 0) __PYX_ERR(0, 5, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":6 + * + * import itertools + * import math # <<<<<<<<<<<<<< + * + * from ipie.legacy.estimators.utils import convolve + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_math, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_math, __pyx_t_1) < 0) __PYX_ERR(0, 6, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":8 + * import math + * + * from ipie.legacy.estimators.utils import convolve # <<<<<<<<<<<<<< + * + * DTYPE_CX = numpy.complex128 + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_convolve); + __Pyx_GIVEREF(__pyx_n_s_convolve); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_convolve); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_ipie_legacy_estimators_utils, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_convolve); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_convolve, __pyx_t_1) < 0) __PYX_ERR(0, 8, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":10 + * from ipie.legacy.estimators.utils import convolve + * + * DTYPE_CX = numpy.complex128 # <<<<<<<<<<<<<< + * DTYPE = numpy.float64 + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 10, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_complex128); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE_CX, __pyx_t_1) < 0) __PYX_ERR(0, 10, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "ueg_kernels.pyx":11 + * + * DTYPE_CX = numpy.complex128 + * DTYPE = numpy.float64 # <<<<<<<<<<<<<< + * + * + */ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 11, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_float64); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 11, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_2) < 0) __PYX_ERR(0, 11, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":14 + * + * + * def vq(numpy.ndarray q): # <<<<<<<<<<<<<< + * assert(q.shape[0] == 3) + * cdef double q2 = numpy.dot(q, q) + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_1vq, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_vq, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":22 + * return 4*math.pi / q2 + * + * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): # <<<<<<<<<<<<<< + * """ Add a diagonal term of two-body Hamiltonian to the one-body term + * Parameters + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_3mod_one_body, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 22, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_mod_one_body, __pyx_t_2) < 0) __PYX_ERR(0, 22, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":45 + * return h1e_mod + * + * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): # <<<<<<<<<<<<<< + * + * cdef int nq = kpq_i.shape[0] + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_5coulomb_greens_function_per_qvec, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 45, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_coulomb_greens_function_per_qvec, __pyx_t_2) < 0) __PYX_ERR(0, 45, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":61 + * return Gkpq, Gpmq + * + * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): # <<<<<<<<<<<<<< + * + * cdef int nkpq = kpq_i.shape[0] + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_7exchange_greens_function_per_qvec, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_exchange_greens_function_per_qve, __pyx_t_2) < 0) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":80 + * return Gprod + * + * def exchange_greens_function_fft (long nocc, long nbsf, # <<<<<<<<<<<<<< + * long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, + * double complex[:,:] CTdagger, double complex[:,:] Ghalf): + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_9exchange_greens_function_fft, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_exchange_greens_function_fft, __pyx_t_2) < 0) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":138 + * return Gprod + * + * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< + * list kpq, list pmq_i, list pmq, + * double complex[:,:] Gkpq, double complex[:,:] Gpmq): + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_11build_J_opt, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_build_J_opt, __pyx_t_2) < 0) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":154 + * return J + * + * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< + * list kpq, list pmq_i, list pmq, + * double complex[:,:,:] G): + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_13build_K_opt, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_build_K_opt, __pyx_t_2) < 0) __PYX_ERR(0, 154, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "ueg_kernels.pyx":1 + * import numpy # <<<<<<<<<<<<<< + * + * cimport numpy + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":210 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 210, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) __PYX_ERR(2, 210, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":287 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 287, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(generic); + __Pyx_DECREF_SET(generic, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":288 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__37, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 288, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(strided); + __Pyx_DECREF_SET(strided, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":289 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__38, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 289, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF_SET(indirect, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":292 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 292, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF_SET(contiguous, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":293 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 293, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":317 + * + * DEF THREAD_LOCKS_PREALLOCATED = 8 + * cdef int __pyx_memoryview_thread_locks_used = 0 # <<<<<<<<<<<<<< + * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ + * PyThread_allocate_lock(), + */ + __pyx_memoryview_thread_locks_used = 0; + + /* "View.MemoryView":318 + * DEF THREAD_LOCKS_PREALLOCATED = 8 + * cdef int __pyx_memoryview_thread_locks_used = 0 + * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ # <<<<<<<<<<<<<< + * PyThread_allocate_lock(), + * PyThread_allocate_lock(), + */ + __pyx_t_3[0] = PyThread_allocate_lock(); + __pyx_t_3[1] = PyThread_allocate_lock(); + __pyx_t_3[2] = PyThread_allocate_lock(); + __pyx_t_3[3] = PyThread_allocate_lock(); + __pyx_t_3[4] = PyThread_allocate_lock(); + __pyx_t_3[5] = PyThread_allocate_lock(); + __pyx_t_3[6] = PyThread_allocate_lock(); + __pyx_t_3[7] = PyThread_allocate_lock(); + memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_3, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); + + /* "View.MemoryView":551 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 551, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) __PYX_ERR(2, 551, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":997 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 997, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) __PYX_ERR(2, 997, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_memoryviewslice_type); + + /* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result + */ + __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_2) < 0) __PYX_ERR(2, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":11 + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + */ + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + if (__pyx_m) { + if (__pyx_d) { + __Pyx_AddTraceback("init ueg_kernels", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + Py_CLEAR(__pyx_m); + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init ueg_kernels"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #elif PY_MAJOR_VERSION >= 3 + return __pyx_m; + #else + return; + #endif +} + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* PyObjectGetAttrStr */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); + if (unlikely(!result)) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +/* ArgTypeTest */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (exact) { + #if PY_MAJOR_VERSION == 2 + if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", + name, type->tp_name, Py_TYPE(obj)->tp_name); + return 0; +} + +/* PyDictVersioning */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if !CYTHON_AVOID_BORROWED_REFS +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 + result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } else if (unlikely(PyErr_Occurred())) { + return NULL; + } +#else + result = PyDict_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } +#endif +#else + result = PyObject_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* PyFunctionFastCall */ +#if CYTHON_FAST_PYCALL +static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, + PyObject *globals) { + PyFrameObject *f; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject **fastlocals; + Py_ssize_t i; + PyObject *result; + assert(globals != NULL); + /* XXX Perhaps we should create a specialized + PyFrame_New() that doesn't take locals, but does + take builtins without sanity checking them. + */ + assert(tstate != NULL); + f = PyFrame_New(tstate, co, globals, NULL); + if (f == NULL) { + return NULL; + } + fastlocals = __Pyx_PyFrame_GetLocalsplus(f); + for (i = 0; i < na; i++) { + Py_INCREF(*args); + fastlocals[i] = *args++; + } + result = PyEval_EvalFrameEx(f,0); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return result; +} +#if 1 || PY_VERSION_HEX < 0x030600B1 +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *closure; +#if PY_MAJOR_VERSION >= 3 + PyObject *kwdefs; +#endif + PyObject *kwtuple, **k; + PyObject **d; + Py_ssize_t nd; + Py_ssize_t nk; + PyObject *result; + assert(kwargs == NULL || PyDict_Check(kwargs)); + nk = kwargs ? PyDict_Size(kwargs) : 0; + if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { + return NULL; + } + if ( +#if PY_MAJOR_VERSION >= 3 + co->co_kwonlyargcount == 0 && +#endif + likely(kwargs == NULL || nk == 0) && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + if (argdefs == NULL && co->co_argcount == nargs) { + result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); + goto done; + } + else if (nargs == 0 && argdefs != NULL + && co->co_argcount == Py_SIZE(argdefs)) { + /* function called with no arguments, but all parameters have + a default value: use default values as arguments .*/ + args = &PyTuple_GET_ITEM(argdefs, 0); + result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); + goto done; + } + } + if (kwargs != NULL) { + Py_ssize_t pos, i; + kwtuple = PyTuple_New(2 * nk); + if (kwtuple == NULL) { + result = NULL; + goto done; + } + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i / 2; + } + else { + kwtuple = NULL; + k = NULL; + } + closure = PyFunction_GET_CLOSURE(func); +#if PY_MAJOR_VERSION >= 3 + kwdefs = PyFunction_GET_KW_DEFAULTS(func); +#endif + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } +#if PY_MAJOR_VERSION >= 3 + result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, kwdefs, closure); +#else + result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, closure); +#endif + Py_XDECREF(kwtuple); +done: + Py_LeaveRecursiveCall(); + return result; +} +#endif +#endif + +/* PyCFunctionFastCall */ +#if CYTHON_FAST_PYCCALL +static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { + PyCFunctionObject *func = (PyCFunctionObject*)func_obj; + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + int flags = PyCFunction_GET_FLAGS(func); + assert(PyCFunction_Check(func)); + assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); + assert(nargs >= 0); + assert(nargs == 0 || args != NULL); + /* _PyCFunction_FastCallDict() must not be called with an exception set, + because it may clear it (directly or indirectly) and so the + caller loses its exception */ + assert(!PyErr_Occurred()); + if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { + return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); + } else { + return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); + } +} +#endif + +/* PyObjectCall */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = Py_TYPE(func)->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* RaiseDoubleKeywords */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +/* ParseKeywords */ +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + while (PyDict_Next(kwds, &pos, &key, &value)) { + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; + continue; + } + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = (**name == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +/* PyObjectCallMethO */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = PyCFunction_GET_FUNCTION(func); + self = PyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallNoArg */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { +#if CYTHON_FAST_PYCALL + if (PyFunction_Check(func)) { + return __Pyx_PyFunction_FastCall(func, NULL, 0); + } +#endif +#if defined(__Pyx_CyFunction_USED) && defined(NDEBUG) + if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) +#else + if (likely(PyCFunction_Check(func))) +#endif + { + if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { + return __Pyx_PyObject_CallMethO(func, NULL); + } + } + return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); +} +#endif + +/* PyObjectCallOneArg */ +#if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { +#if CYTHON_FAST_PYCALL + if (PyFunction_Check(func)) { + return __Pyx_PyFunction_FastCall(func, &arg, 1); + } +#endif + if (likely(PyCFunction_Check(func))) { + if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { + return __Pyx_PyObject_CallMethO(func, arg); +#if CYTHON_FAST_PYCCALL + } else if (__Pyx_PyFastCFunction_Check(func)) { + return __Pyx_PyCFunction_FastCall(func, &arg, 1); +#endif + } + } + return __Pyx__PyObject_CallOneArg(func, arg); +} +#else +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_Pack(1, arg); + if (unlikely(!args)) return NULL; + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; +} +#endif + +/* ExtTypeTest */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(__Pyx_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; +} + +/* PyIntBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) { + (void)inplace; + (void)zerodivision_check; + #if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(op1))) { + const long b = intval; + long x; + long a = PyInt_AS_LONG(op1); + x = (long)((unsigned long)a + b); + if (likely((x^a) >= 0 || (x^b) >= 0)) + return PyInt_FromLong(x); + return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + const long b = intval; + long a, x; +#ifdef HAVE_LONG_LONG + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla, llx; +#endif + const digit* digits = ((PyLongObject*)op1)->ob_digit; + const Py_ssize_t size = Py_SIZE(op1); + if (likely(__Pyx_sst_abs(size) <= 1)) { + a = likely(size) ? digits[0] : 0; + if (size == -1) a = -a; + } else { + switch (size) { + case -2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + CYTHON_FALLTHROUGH; + case 2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + CYTHON_FALLTHROUGH; + case -3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + CYTHON_FALLTHROUGH; + case 3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + CYTHON_FALLTHROUGH; + case -4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + CYTHON_FALLTHROUGH; + case 4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + CYTHON_FALLTHROUGH; + default: return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + } + x = a + b; + return PyLong_FromLong(x); +#ifdef HAVE_LONG_LONG + long_long: + llx = lla + llb; + return PyLong_FromLongLong(llx); +#endif + + + } + #endif + if (PyFloat_CheckExact(op1)) { + const long b = intval; + double a = PyFloat_AS_DOUBLE(op1); + double result; + PyFPE_START_PROTECT("add", return NULL) + result = ((double)a) + (double)b; + PyFPE_END_PROTECT(result) + return PyFloat_FromDouble(result); + } + return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); +} +#endif + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, wrapped_i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return m->sq_item(o, i); + } + } +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +/* ObjectGetItem */ +#if CYTHON_USE_TYPE_SLOTS +static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { + PyObject *runerr = NULL; + Py_ssize_t key_value; + PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; + if (unlikely(!(m && m->sq_item))) { + PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); + return NULL; + } + key_value = __Pyx_PyIndex_AsSsize_t(index); + if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { + return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); + } + if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { + PyErr_Clear(); + PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); + } + return NULL; +} +static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { + PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; + if (likely(m && m->mp_subscript)) { + return m->mp_subscript(obj, key); + } + return __Pyx_PyObject_GetIndex(obj, key); +} +#endif + +/* PyObjectCall2Args */ +static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args, *result = NULL; + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(function)) { + PyObject *args[2] = {arg1, arg2}; + return __Pyx_PyFunction_FastCall(function, args, 2); + } + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(function)) { + PyObject *args[2] = {arg1, arg2}; + return __Pyx_PyCFunction_FastCall(function, args, 2); + } + #endif + args = PyTuple_New(2); + if (unlikely(!args)) goto done; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + Py_INCREF(function); + result = __Pyx_PyObject_Call(function, args, NULL); + Py_DECREF(args); + Py_DECREF(function); +done: + return result; +} + +/* RaiseTooManyValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/* RaiseNeedMoreValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/* IterFinish */ +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; +#else + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } + } + return 0; +#endif +} + +/* UnpackItemEndCheck */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } + return __Pyx_IterFinish(); +} + +/* BufferIndexError */ +static void __Pyx_RaiseBufferIndexError(int axis) { + PyErr_Format(PyExc_IndexError, + "Out of bounds on buffer access (axis %d)", axis); +} + +/* MemviewSliceInit */ +static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (unlikely(memviewslice->memview || memviewslice->data)) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); + } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} +#ifndef Py_NO_RETURN +#define Py_NO_RETURN +#endif +static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { + va_list vargs; + char msg[200]; +#if PY_VERSION_HEX >= 0x030A0000 || defined(HAVE_STDARG_PROTOTYPES) + va_start(vargs, fmt); +#else + va_start(vargs); +#endif + vsnprintf(msg, 200, fmt, vargs); + va_end(vargs); + Py_FatalError(msg); +} +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; +} +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (unlikely(!memview || (PyObject *) memview == Py_None)) + return; + if (unlikely(__pyx_get_slice_count(memview) < 0)) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (unlikely(first_time)) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); + } + } +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (unlikely(!memview || (PyObject *) memview == Py_None)) { + memslice->memview = NULL; + return; + } + if (unlikely(__pyx_get_slice_count(memview) <= 0)) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (unlikely(last_time)) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } + } else { + memslice->memview = NULL; + } +} + +/* SetItemInt */ +static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, int is_list, + CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return -1; + PyErr_Clear(); + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) +#else + if (is_list || PySequence_Check(o)) +#endif + { + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + +/* GetTopmostException */ +#if CYTHON_USE_EXC_INFO_STACK +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + #endif + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +} +#endif + +/* PyErrExceptionMatches */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; icurexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; + if (unlikely(PyTuple_Check(err))) + return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); +} +#endif + +/* GetException */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +/* PyErrFetchRestore */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +} +#endif + +/* RaiseException */ +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, + CYTHON_UNUSED PyObject *cause) { + __Pyx_PyThreadState_declare + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + } + __Pyx_PyThreadState_assign + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +/* BytesEquals */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + #if CYTHON_PEP393_ENABLED + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + #else + hash1 = ((PyUnicodeObject*)s1)->hash; + hash2 = ((PyUnicodeObject*)s2)->hash; + #endif + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +/* DivInt[Py_ssize_t] */ +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { + Py_ssize_t q = a / b; + Py_ssize_t r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +/* GetAttr */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_USE_TYPE_SLOTS +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) +#else + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +/* decode_c_string */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + size_t slen = strlen(cstring); + if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, + "c-string too long to convert to Python"); + return NULL; + } + length = (Py_ssize_t) slen; + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + if (unlikely(stop <= start)) + return __Pyx_NewRef(__pyx_empty_unicode); + length = stop - start; + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/* GetAttr3 */ +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r = __Pyx_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +} + +/* RaiseNoneIterError */ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +/* SwapException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = *type; + exc_info->exc_value = *value; + exc_info->exc_traceback = *tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#endif + +/* Import */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_MAJOR_VERSION < 3 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; + } + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_MAJOR_VERSION < 3 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } + } +bad: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; +} + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = a->tp_base; + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +#if PY_MAJOR_VERSION == 2 +static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { + PyObject *exception, *value, *tb; + int res; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&exception, &value, &tb); + res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + if (!res) { + res = PyObject_IsSubclass(err, exc_type2); + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + } + __Pyx_ErrRestore(exception, value, tb); + return res; +} +#else +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; + if (!res) { + res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } + return res; +} +#endif +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; i= 3 + "'%.50s' object has no attribute '%U'", + tp->tp_name, attr_name); +#else + "'%.50s' object has no attribute '%.400s'", + tp->tp_name, PyString_AS_STRING(attr_name)); +#endif + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { + PyObject *descr; + PyTypeObject *tp = Py_TYPE(obj); + if (unlikely(!PyString_Check(attr_name))) { + return PyObject_GenericGetAttr(obj, attr_name); + } + assert(!tp->tp_dictoffset); + descr = _PyType_Lookup(tp, attr_name); + if (unlikely(!descr)) { + return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); + } + Py_INCREF(descr); + #if PY_MAJOR_VERSION < 3 + if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) + #endif + { + descrgetfunc f = Py_TYPE(descr)->tp_descr_get; + if (unlikely(f)) { + PyObject *res = f(descr, obj, (PyObject *)tp); + Py_DECREF(descr); + return res; + } + } + return descr; +} +#endif + +/* PyObject_GenericGetAttr */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { + if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { + return PyObject_GenericGetAttr(obj, attr_name); + } + return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); +} +#endif + +/* SetVTable */ +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +#if PY_VERSION_HEX >= 0x02070000 + PyObject *ob = PyCapsule_New(vtable, 0, 0); +#else + PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); +#endif + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* PyObjectGetAttrStrNoError */ +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +} + +/* SetupReduce */ +static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name_2); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_getstate = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; + PyObject *getstate = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate); +#else + getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_getstate); + if (!getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (getstate) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_getstate); +#else + object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_n_s_getstate); + if (!object_getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (object_getstate != getstate) { + goto __PYX_GOOD; + } + } +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); + if (likely(reduce_cython)) { + ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (reduce == object_reduce || PyErr_Occurred()) { + goto __PYX_BAD; + } + setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); + if (likely(setstate_cython)) { + ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (!setstate || PyErr_Occurred()) { + goto __PYX_BAD; + } + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto __PYX_GOOD; +__PYX_BAD: + if (!PyErr_Occurred()) + PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); + ret = -1; +__PYX_GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); + Py_XDECREF(object_getstate); + Py_XDECREF(getstate); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* TypeImport */ +#ifndef __PYX_HAVE_RT_ImportType_0_29_35 +#define __PYX_HAVE_RT_ImportType_0_29_35 +static PyTypeObject *__Pyx_ImportType_0_29_35(PyObject *module, const char *module_name, const char *class_name, + size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_0_29_35 check_size) +{ + PyObject *result = 0; + char warning[200]; + Py_ssize_t basicsize; + Py_ssize_t itemsize; +#ifdef Py_LIMITED_API + PyObject *py_basicsize; + PyObject *py_itemsize; +#endif + result = PyObject_GetAttrString(module, class_name); + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#ifndef Py_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; + itemsize = ((PyTypeObject *)result)->tp_itemsize; +#else + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; + py_itemsize = PyObject_GetAttrString(result, "__itemsize__"); + if (!py_itemsize) + goto bad; + itemsize = PyLong_AsSsize_t(py_itemsize); + Py_DECREF(py_itemsize); + py_itemsize = 0; + if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (itemsize) { + if (size % alignment) { + alignment = size % alignment; + } + if (itemsize < (Py_ssize_t)alignment) + itemsize = (Py_ssize_t)alignment; + } + if ((size_t)(basicsize + itemsize) < size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize); + goto bad; + } + if (check_size == __Pyx_ImportType_CheckSize_Error_0_29_35 && (size_t)basicsize != size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize); + goto bad; + } + else if (check_size == __Pyx_ImportType_CheckSize_Warn_0_29_35 && (size_t)basicsize > size) { + PyOS_snprintf(warning, sizeof(warning), + "%s.%s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize); + if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(result); + return NULL; +} +#endif + +/* CLineInTraceback */ +#ifndef CYTHON_CLINE_IN_TRACEBACK +static int __Pyx_CLineForTraceback(CYTHON_UNUSED PyThreadState *tstate, int c_line) { + PyObject *use_cline; + PyObject *ptype, *pvalue, *ptraceback; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject **cython_runtime_dict; +#endif + if (unlikely(!__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); +#if CYTHON_COMPILING_IN_CPYTHON + cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, *cython_runtime_dict, + __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) + } else +#endif + { + PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); + if (use_cline_obj) { + use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; + Py_DECREF(use_cline_obj); + } else { + PyErr_Clear(); + use_cline = NULL; + } + } + if (!use_cline) { + c_line = 0; + (void) PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); + } + else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + #if PY_MAJOR_VERSION < 3 + PyObject *py_srcfile = NULL; + py_srcfile = PyString_FromString(filename); + if (!py_srcfile) goto bad; + #endif + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + if (!py_funcname) goto bad; + #endif + } + #if PY_MAJOR_VERSION < 3 + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + #else + py_code = PyCode_NewEmpty(filename, funcname, py_line); + #endif + Py_XDECREF(py_funcname); // XDECREF since it's only set on Py3 if cline + return py_code; +bad: + Py_XDECREF(py_funcname); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_srcfile); + #endif + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +/* Declarations */ +#if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return ::std::complex< double >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + return x + y*(__pyx_t_double_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { + __pyx_t_double_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +/* Arithmetic */ +#if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + #if 1 + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + if (b.imag == 0) { + return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); + } else if (fabs(b.real) >= fabs(b.imag)) { + if (b.real == 0 && b.imag == 0) { + return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); + } else { + double r = b.imag / b.real; + double s = (double)(1.0) / (b.real + b.imag * r); + return __pyx_t_double_complex_from_parts( + (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); + } + } else { + double r = b.real / b.imag; + double s = (double)(1.0) / (b.imag + b.real * r); + return __pyx_t_double_complex_from_parts( + (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); + } + } + #else + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + if (b.imag == 0) { + return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); + } else { + double denom = b.real * b.real + b.imag * b.imag; + return __pyx_t_double_complex_from_parts( + (a.real * b.real + a.imag * b.imag) / denom, + (a.imag * b.real - a.real * b.imag) / denom); + } + } + #endif + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { + __pyx_t_double_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrt(z.real*z.real + z.imag*z.imag); + #else + return hypot(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { + __pyx_t_double_complex z; + double r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + double denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + return __Pyx_c_prod_double(a, a); + case 3: + z = __Pyx_c_prod_double(a, a); + return __Pyx_c_prod_double(z, a); + case 4: + z = __Pyx_c_prod_double(a, a); + return __Pyx_c_prod_double(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } else if ((b.imag == 0) && (a.real >= 0)) { + z.real = pow(a.real, b.real); + z.imag = 0; + return z; + } else if (a.real > 0) { + r = a.real; + theta = 0; + } else { + r = -a.real; + theta = atan2(0.0, -1.0); + } + } else { + r = __Pyx_c_abs_double(a); + theta = atan2(a.imag, a.real); + } + lnr = log(r); + z_r = exp(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cos(z_theta); + z.imag = z_r * sin(z_theta); + return z; + } + #endif +#endif + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (__Pyx_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (__Pyx_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + if ((0)) {} + view->obj = NULL; + Py_DECREF(obj); +} +#endif + + +/* MemviewSliceIsContig */ +static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim) +{ + int i, index, step, start; + Py_ssize_t itemsize = mvs.memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs.suboffsets[index] >= 0 || mvs.strides[index] != itemsize) + return 0; + itemsize *= mvs.shape[index]; + } + return 1; +} + +/* OverlappingSlices */ +static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + *out_start = start; + *out_end = end + itemsize; +} +static int +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) +{ + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); +} + +/* Capsule */ +static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) +{ + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; +} + +/* IsLittleEndian */ +static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) +{ + union { + uint32_t u32; + uint8_t u8[4]; + } S; + S.u32 = 0x01020304; + return S.u8[0] == 4; +} + +/* BufferFormatCheck */ +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t <= '9') { + count *= 10; + count += *t++ - '0'; + } + } + *ts = t; + return count; +} +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; +} +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case '?': return "'bool'"; + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; + } + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case '?': case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; + } else { + expected = ctx->head->field->type->name; + quote = "'"; + } + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } +} +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; + } + } + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; + } + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; + } + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + } + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); + } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + } + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } + } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; +} +static PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number, ndim; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ndim = ctx->head->field->type->ndim; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); + return NULL; + } + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; +} +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_Is_Little_Endian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_Is_Little_Endian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + CYTHON_FALLTHROUGH; + case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if ((ctx->enc_type == *ts) && (got_Z == ctx->is_complex) && + (ctx->enc_packmode == ctx->new_packmode) && (!ctx->is_valid_array)) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + CYTHON_FALLTHROUGH; + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; + } + } + } +} + +/* TypeInfoCompare */ + static int +__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) +{ + int i; + if (!a || !b) + return 0; + if (a == b) + return 1; + if (a->size != b->size || a->typegroup != b->typegroup || + a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { + if (a->typegroup == 'H' || b->typegroup == 'H') { + return a->size == b->size; + } else { + return 0; + } + } + if (a->ndim) { + for (i = 0; i < a->ndim; i++) + if (a->arraysize[i] != b->arraysize[i]) + return 0; + } + if (a->typegroup == 'S') { + if (a->flags != b->flags) + return 0; + if (a->fields || b->fields) { + if (!(a->fields && b->fields)) + return 0; + for (i = 0; a->fields[i].type && b->fields[i].type; i++) { + __Pyx_StructField *field_a = a->fields + i; + __Pyx_StructField *field_b = b->fields + i; + if (field_a->offset != field_b->offset || + !__pyx_typeinfo_cmp(field_a->type, field_b->type)) + return 0; + } + return !a->fields[i].type && !b->fields[i].type; + } + } + return 1; +} + +/* MemviewSliceValidateAndInit */ + static int +__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) +{ + if (buf->shape[dim] <= 1) + return 1; + if (buf->strides) { + if (spec & __Pyx_MEMVIEW_CONTIG) { + if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { + if (unlikely(buf->strides[dim] != sizeof(void *))) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (unlikely(buf->strides[dim] != buf->itemsize)) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_FOLLOW) { + Py_ssize_t stride = buf->strides[dim]; + if (stride < 0) + stride = -stride; + if (unlikely(stride < buf->itemsize)) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (unlikely(spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not contiguous in " + "dimension %d", dim); + goto fail; + } else if (unlikely(spec & (__Pyx_MEMVIEW_PTR))) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (unlikely(buf->suboffsets)) { + PyErr_SetString(PyExc_ValueError, + "Buffer exposes suboffsets but no strides"); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) +{ + if (spec & __Pyx_MEMVIEW_DIRECT) { + if (unlikely(buf->suboffsets && buf->suboffsets[dim] >= 0)) { + PyErr_Format(PyExc_ValueError, + "Buffer not compatible with direct access " + "in dimension %d.", dim); + goto fail; + } + } + if (spec & __Pyx_MEMVIEW_PTR) { + if (unlikely(!buf->suboffsets || (buf->suboffsets[dim] < 0))) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly accessible " + "in dimension %d.", dim); + goto fail; + } + } + return 1; +fail: + return 0; +} +static int +__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) +{ + int i; + if (c_or_f_flag & __Pyx_IS_F_CONTIG) { + Py_ssize_t stride = 1; + for (i = 0; i < ndim; i++) { + if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { + PyErr_SetString(PyExc_ValueError, + "Buffer not fortran contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { + Py_ssize_t stride = 1; + for (i = ndim - 1; i >- 1; i--) { + if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { + PyErr_SetString(PyExc_ValueError, + "Buffer not C contiguous."); + goto fail; + } + stride = stride * buf->shape[i]; + } + } + return 1; +fail: + return 0; +} +static int __Pyx_ValidateAndInit_memviewslice( + int *axes_specs, + int c_or_f_flag, + int buf_flags, + int ndim, + __Pyx_TypeInfo *dtype, + __Pyx_BufFmt_StackElem stack[], + __Pyx_memviewslice *memviewslice, + PyObject *original_obj) +{ + struct __pyx_memoryview_obj *memview, *new_memview; + __Pyx_RefNannyDeclarations + Py_buffer *buf; + int i, spec = 0, retval = -1; + __Pyx_BufFmt_Context ctx; + int from_memoryview = __pyx_memoryview_check(original_obj); + __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); + if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) + original_obj)->typeinfo)) { + memview = (struct __pyx_memoryview_obj *) original_obj; + new_memview = NULL; + } else { + memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + original_obj, buf_flags, 0, dtype); + new_memview = memview; + if (unlikely(!memview)) + goto fail; + } + buf = &memview->view; + if (unlikely(buf->ndim != ndim)) { + PyErr_Format(PyExc_ValueError, + "Buffer has wrong number of dimensions (expected %d, got %d)", + ndim, buf->ndim); + goto fail; + } + if (new_memview) { + __Pyx_BufFmt_Init(&ctx, stack, dtype); + if (unlikely(!__Pyx_BufFmt_CheckString(&ctx, buf->format))) goto fail; + } + if (unlikely((unsigned) buf->itemsize != dtype->size)) { + PyErr_Format(PyExc_ValueError, + "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " + "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", + buf->itemsize, + (buf->itemsize > 1) ? "s" : "", + dtype->name, + dtype->size, + (dtype->size > 1) ? "s" : ""); + goto fail; + } + if (buf->len > 0) { + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (unlikely(!__pyx_check_strides(buf, i, ndim, spec))) + goto fail; + if (unlikely(!__pyx_check_suboffsets(buf, i, ndim, spec))) + goto fail; + } + if (unlikely(buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag))) + goto fail; + } + if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, + new_memview != NULL) == -1)) { + goto fail; + } + retval = 0; + goto no_fail; +fail: + Py_XDECREF(new_memview); + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; +} + +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(PyObject *obj, int writable_flag) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS_RO | writable_flag, 2, + &__Pyx_TypeInfo___pyx_t_double_complex, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_long(PyObject *obj, int writable_flag) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS_RO | writable_flag, 1, + &__Pyx_TypeInfo_long, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +/* CIntFromPyVerify */ + #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *obj, int writable_flag) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS_RO | writable_flag, 1, + &__Pyx_TypeInfo_double, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsdsds___pyx_t_double_complex(PyObject *obj, int writable_flag) { + __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; + __Pyx_BufFmt_StackElem stack[1]; + int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; + int retcode; + if (obj == Py_None) { + result.memview = (struct __pyx_memoryview_obj *) Py_None; + return result; + } + retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, + PyBUF_RECORDS_RO | writable_flag, 3, + &__Pyx_TypeInfo___pyx_t_double_complex, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +/* MemviewDtypeToObject */ + static CYTHON_INLINE PyObject *__pyx_memview_get_long(const char *itemp) { + return (PyObject *) __Pyx_PyInt_From_long(*(long *) itemp); +} +static CYTHON_INLINE int __pyx_memview_set_long(const char *itemp, PyObject *obj) { + long value = __Pyx_PyInt_As_long(obj); + if ((value == (long)-1) && PyErr_Occurred()) + return 0; + *(long *) itemp = value; + return 1; +} + +/* FromPy */ + static __pyx_t_double_complex __Pyx_PyComplex_As___pyx_t_double_complex(PyObject* o) { + Py_complex cval; +#if !CYTHON_COMPILING_IN_PYPY + if (PyComplex_CheckExact(o)) + cval = ((PyComplexObject *)o)->cval; + else +#endif + cval = PyComplex_AsCComplex(o); + return __pyx_t_double_complex_from_parts( + (double)cval.real, + (double)cval.imag); +} + +/* MemviewDtypeToObject */ + static CYTHON_INLINE PyObject *__pyx_memview_get___pyx_t_double_complex(const char *itemp) { + return (PyObject *) __pyx_PyComplex_FromComplex(*(__pyx_t_double_complex *) itemp); +} +static CYTHON_INLINE int __pyx_memview_set___pyx_t_double_complex(const char *itemp, PyObject *obj) { + __pyx_t_double_complex value = __Pyx_PyComplex_As___pyx_t_double_complex(obj); + if (PyErr_Occurred()) + return 0; + *(__pyx_t_double_complex *) itemp = value; + return 1; +} + +/* Declarations */ + #if CYTHON_CCOMPLEX + #ifdef __cplusplus + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return ::std::complex< float >(x, y); + } + #else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + return x + y*(__pyx_t_float_complex)_Complex_I; + } + #endif +#else + static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { + __pyx_t_float_complex z; + z.real = x; + z.imag = y; + return z; + } +#endif + +/* Arithmetic */ + #if CYTHON_CCOMPLEX +#else + static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { + return (a.real == b.real) && (a.imag == b.imag); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real + b.real; + z.imag = a.imag + b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real - b.real; + z.imag = a.imag - b.imag; + return z; + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + z.real = a.real * b.real - a.imag * b.imag; + z.imag = a.real * b.imag + a.imag * b.real; + return z; + } + #if 1 + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { + if (b.imag == 0) { + return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); + } else if (fabsf(b.real) >= fabsf(b.imag)) { + if (b.real == 0 && b.imag == 0) { + return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); + } else { + float r = b.imag / b.real; + float s = (float)(1.0) / (b.real + b.imag * r); + return __pyx_t_float_complex_from_parts( + (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); + } + } else { + float r = b.real / b.imag; + float s = (float)(1.0) / (b.imag + b.real * r); + return __pyx_t_float_complex_from_parts( + (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); + } + } + #else + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { + if (b.imag == 0) { + return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); + } else { + float denom = b.real * b.real + b.imag * b.imag; + return __pyx_t_float_complex_from_parts( + (a.real * b.real + a.imag * b.imag) / denom, + (a.imag * b.real - a.real * b.imag) / denom); + } + } + #endif + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = -a.real; + z.imag = -a.imag; + return z; + } + static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) { + return (a.real == 0) && (a.imag == 0); + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) { + __pyx_t_float_complex z; + z.real = a.real; + z.imag = -a.imag; + return z; + } + #if 1 + static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) { + #if !defined(HAVE_HYPOT) || defined(_MSC_VER) + return sqrtf(z.real*z.real + z.imag*z.imag); + #else + return hypotf(z.real, z.imag); + #endif + } + static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { + __pyx_t_float_complex z; + float r, lnr, theta, z_r, z_theta; + if (b.imag == 0 && b.real == (int)b.real) { + if (b.real < 0) { + float denom = a.real * a.real + a.imag * a.imag; + a.real = a.real / denom; + a.imag = -a.imag / denom; + b.real = -b.real; + } + switch ((int)b.real) { + case 0: + z.real = 1; + z.imag = 0; + return z; + case 1: + return a; + case 2: + return __Pyx_c_prod_float(a, a); + case 3: + z = __Pyx_c_prod_float(a, a); + return __Pyx_c_prod_float(z, a); + case 4: + z = __Pyx_c_prod_float(a, a); + return __Pyx_c_prod_float(z, z); + } + } + if (a.imag == 0) { + if (a.real == 0) { + return a; + } else if ((b.imag == 0) && (a.real >= 0)) { + z.real = powf(a.real, b.real); + z.imag = 0; + return z; + } else if (a.real > 0) { + r = a.real; + theta = 0; + } else { + r = -a.real; + theta = atan2f(0.0, -1.0); + } + } else { + r = __Pyx_c_abs_float(a); + theta = atan2f(a.imag, a.real); + } + lnr = logf(r); + z_r = expf(lnr * b.real - theta * b.imag); + z_theta = theta * b.real + lnr * b.imag; + z.real = z_r * cosf(z_theta); + z.imag = z_r * sinf(z_theta); + return z; + } + #endif +#endif + +/* MemviewSliceCopyTemplate */ + static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (unlikely(from_mvs->suboffsets[i] >= 0)) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; + } + } + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; + } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; + } else { + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; + } + } + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; +} + +/* CIntFromPy */ + static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(long) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (long) 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) + case 2: + if (8 * sizeof(long) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if (8 * sizeof(long) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if (8 * sizeof(long) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if (sizeof(long) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (long) 0; + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) + case -2: + if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if (8 * sizeof(long) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if (8 * sizeof(long) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if (8 * sizeof(long) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } +#endif + if (sizeof(long) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + long val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* CIntFromPy */ + static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(int) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (int) 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) + case 2: + if (8 * sizeof(int) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if (8 * sizeof(int) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if (8 * sizeof(int) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if (sizeof(int) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (int) 0; + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) + case -2: + if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if (8 * sizeof(int) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if (8 * sizeof(int) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if (8 * sizeof(int) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } +#endif + if (sizeof(int) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + int val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntToPy */ + static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +/* CIntToPy */ + static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +/* CIntFromPy */ + static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const char neg_one = (char) -1, const_zero = (char) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(char) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (char) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (char) 0; + case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) + case 2: + if (8 * sizeof(char) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { + return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + case 3: + if (8 * sizeof(char) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { + return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + case 4: + if (8 * sizeof(char) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { + return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (char) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if (sizeof(char) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (char) 0; + case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) + case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) + case -2: + if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { + return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 2: + if (8 * sizeof(char) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { + return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case -3: + if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { + return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 3: + if (8 * sizeof(char) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { + return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case -4: + if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { + return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 4: + if (8 * sizeof(char) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { + return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + } +#endif + if (sizeof(char) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + char val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (char) -1; + } + } else { + char val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (char) -1; + val = __Pyx_PyInt_As_char(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to char"); + return (char) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; +} + +/* CheckBinaryVersion */ + static int __Pyx_check_binary_version(void) { + char ctversion[5]; + int same=1, i, found_dot; + const char* rt_from_call = Py_GetVersion(); + PyOS_snprintf(ctversion, 5, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + found_dot = 0; + for (i = 0; i < 4; i++) { + if (!ctversion[i]) { + same = (rt_from_call[i] < '0' || rt_from_call[i] > '9'); + break; + } + if (rt_from_call[i] != ctversion[i]) { + same = 0; + break; + } + } + if (!same) { + char rtversion[5] = {'\0'}; + char message[200]; + for (i=0; i<4; ++i) { + if (rt_from_call[i] == '.') { + if (found_dot) break; + found_dot = 1; + } else if (rt_from_call[i] < '0' || rt_from_call[i] > '9') { + break; + } + rtversion[i] = rt_from_call[i]; + } + PyOS_snprintf(message, sizeof(message), + "compiletime version %s of module '%.100s' " + "does not match runtime version %s", + ctversion, __Pyx_MODULE_NAME, rtversion); + return PyErr_WarnEx(NULL, message, 1); + } + return 0; +} + +/* InitStrings */ + static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION < 3 + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + #else + if (t->is_unicode | t->is_str) { + if (t->intern) { + *t->p = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); + } else { + *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + #endif + if (!*t->p) + return -1; + if (PyObject_Hash(*t->p) == -1) + return -1; + ++t; + } + return 0; +} + +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +#if !CYTHON_PEP393_ENABLED +static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +} +#else +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +} +#endif +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif +#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { +#if PY_MAJOR_VERSION >= 3 + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type %.200s). " + "The ability to return an instance of a strict subclass of int " + "is deprecated, and may be removed in a future version of Python.", + Py_TYPE(result)->tp_name)) { + Py_DECREF(result); + return NULL; + } + return result; + } +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type %.200s)", + type_name, type_name, Py_TYPE(result)->tp_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x) || PyLong_Check(x))) +#else + if (likely(PyLong_Check(x))) +#endif + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + #if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = m->nb_int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = m->nb_long(x); + } + #else + if (likely(m && m->nb_int)) { + name = "int"; + res = m->nb_int(x); + } + #endif +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Int(x); + } +#endif + if (likely(res)) { +#if PY_MAJOR_VERSION < 3 + if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { +#else + if (unlikely(!PyLong_CheckExact(res))) { +#endif + return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) { + if (sizeof(Py_ssize_t) >= sizeof(long)) + return PyInt_AS_LONG(b); + else + return PyInt_AsSsize_t(b); + } +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)b)->ob_digit; + const Py_ssize_t size = Py_SIZE(b); + if (likely(__Pyx_sst_abs(size) <= 1)) { + ival = likely(size) ? digits[0] : 0; + if (size == -1) ival = -ival; + return ival; + } else { + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); +#if PY_MAJOR_VERSION < 3 + } else if (likely(PyInt_CheckExact(o))) { + return PyInt_AS_LONG(o); +#endif + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyInt_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { + return PyInt_FromSize_t(ival); +} + + +#endif /* Py_PYTHON_H */ diff --git a/ipie/addons/thermal/utils/ueg_kernels.pyx b/ipie/addons/thermal/utils/ueg_kernels.pyx new file mode 100644 index 00000000..77545707 --- /dev/null +++ b/ipie/addons/thermal/utils/ueg_kernels.pyx @@ -0,0 +1,169 @@ +import numpy + +cimport numpy + +import itertools +import math + +from ipie.legacy.estimators.utils import convolve + +DTYPE_CX = numpy.complex128 +DTYPE = numpy.float64 + + +def vq(numpy.ndarray q): + assert(q.shape[0] == 3) + cdef double q2 = numpy.dot(q, q) + if (q2 < 1e-10): + return 0.0 + else: + return 4*math.pi / q2 + +def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): + """ Add a diagonal term of two-body Hamiltonian to the one-body term + Parameters + ---------- + T : float + one-body Hamiltonian (i.e. kinetic energy) + Returns + ------- + h1e_mod: float + modified one-body Hamiltonian + """ + + cdef size_t nbsf = basis.shape[0] + cdef numpy.ndarray h1e_mod = T.copy() + cdef double fac = 1.0 / (2.0 * vol) + + for (i, ki) in enumerate(basis): + for (j, kj) in enumerate(basis): + if i != j: + q = kfac * (ki - kj) + h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) + return h1e_mod + +def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): + + cdef int nq = kpq_i.shape[0] + + cdef int idxkpq, idxpmq, i, j, iq + + cdef double complex Gkpq = 0.0 + cdef double complex Gpmq = 0.0 + + for (idxkpq,i) in zip(kpq,kpq_i): + Gkpq += G[i,idxkpq] + for (idxpmq,i) in zip(pmq,pmq_i): + Gpmq += G[i,idxpmq] + + return Gkpq, Gpmq + +def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): + + cdef int nkpq = kpq_i.shape[0] + cdef int npmq = pmq_i.shape[0] + + cdef double complex Gprod = 0.0 + + cdef int idxkpq, idxpmq, i, j + + for inkpq in range(nkpq): + idxkpq = kpq[inkpq] + i = kpq_i[inkpq] + for jnpmq in range(npmq): + idxpmq = pmq[jnpmq] + j = pmq_i[jnpmq] + Gprod += G[j,idxkpq]*G[i,idxpmq] + + return Gprod + +def exchange_greens_function_fft (long nocc, long nbsf, + long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, + double complex[:,:] CTdagger, double complex[:,:] Ghalf): + + assert (mesh.shape[0] == 3) + assert (qmesh.shape[0] == 3) + assert (Ghalf.shape[0] == nocc) + assert (Ghalf.shape[1] == nbsf) + assert (CTdagger.shape[0] == nocc) + assert (CTdagger.shape[1] == nbsf) + + cdef long ngrid = numpy.prod(mesh) + cdef long nqgrid = numpy.prod(qmesh) + + cdef long nq = qmap.shape[0] + cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) + + cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) + cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) + cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) + + for i in range(nocc): + for j in range(nocc): + Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) + CTdagger_j = numpy.asarray(CTdagger[j,:]) + + Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + Gh_i_cube[gmap] = Gh_i + CTdagger_j_cube[gmap] = CTdagger_j + + lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] + + Gh_j = numpy.asarray(Ghalf[j,:]) + CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) + + Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) + + Gh_j_cube[gmap] = Gh_j + CTdagger_i_cube[gmap] = CTdagger_i + + lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] + + Gprod += lQ_ji*lQ_ij + + return Gprod + +def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, + list kpq, list pmq_i, list pmq, + double complex[:,:] Gkpq, double complex[:,:] Gpmq): + + cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) + cdef int i, j + for iq in range(nq): + for i, j in zip(pmq_i[iq], pmq[iq]): + J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) + for i, j in zip(kpq_i[iq], kpq[iq]): + J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) + + J[1] = J[0] + + return J + +def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, + list kpq, list pmq_i, list pmq, + double complex[:,:,:] G): + + cdef numpy.ndarray K = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) + cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp + + for s in range(2): + for iq in range(nq): + for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): + for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): + K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] + for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): + for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): + K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] + return K From 12740225d0fb6939c751ed8811a3d16b41986126 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 16 Mar 2024 16:33:21 -0400 Subject: [PATCH 65/84] Skip `pytest` if `cython` modules are not built. --- .../thermal/estimators/tests/test_generic.py | 8 + .../propagation/tests/test_operations.py | 8 + .../propagation/tests/test_prop_generic.py | 12 + .../propagation/tests/ueg/test_prop_ueg.py | 15 +- .../thermal/qmc/tests/test_afqmc_generic.py | 7 + .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 10 + .../utils/legacy/legacy_thermal_afqmc.py | 383 ------------------ .../utils/legacy/legacy_trial_utils.py | 39 -- ipie/addons/thermal/utils/legacy_testing.py | 5 +- .../walkers/tests/test_population_control.py | 11 + .../walkers/tests/test_thermal_walkers.py | 9 + 11 files changed, 79 insertions(+), 428 deletions(-) delete mode 100644 ipie/addons/thermal/utils/legacy/legacy_thermal_afqmc.py delete mode 100644 ipie/addons/thermal/utils/legacy/legacy_trial_utils.py diff --git a/ipie/addons/thermal/estimators/tests/test_generic.py b/ipie/addons/thermal/estimators/tests/test_generic.py index acd8ae1a..032a30b8 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic.py +++ b/ipie/addons/thermal/estimators/tests/test_generic.py @@ -12,8 +12,16 @@ from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers +try: + from ipie.legacy.estimators.ueg import fock_ueg + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + comm = MPI.COMM_WORLD +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_local_energy_cholesky(mf_trial=False): # System params. diff --git a/ipie/addons/thermal/propagation/tests/test_operations.py b/ipie/addons/thermal/propagation/tests/test_operations.py index 8d2ab633..c852ea0e 100644 --- a/ipie/addons/thermal/propagation/tests/test_operations.py +++ b/ipie/addons/thermal/propagation/tests/test_operations.py @@ -7,8 +7,16 @@ from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers +try: + from ipie.legacy.estimators.ueg import fock_ueg + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + comm = MPI.COMM_WORLD +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_apply_exponential(): # System params. diff --git a/ipie/addons/thermal/propagation/tests/test_prop_generic.py b/ipie/addons/thermal/propagation/tests/test_prop_generic.py index eb6d7714..5bdd7ed2 100644 --- a/ipie/addons/thermal/propagation/tests/test_prop_generic.py +++ b/ipie/addons/thermal/propagation/tests/test_prop_generic.py @@ -12,6 +12,13 @@ from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers +try: + from ipie.legacy.estimators.ueg import fock_ueg + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + comm = MPI.COMM_WORLD # System params. @@ -62,6 +69,7 @@ } +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_mf_shift(): # Test. @@ -87,6 +95,8 @@ def test_mf_shift(): numpy.testing.assert_almost_equal(legacy_propagator.propagator.mf_shift, propagator.mf_shift, decimal=10) + +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_BH1(): # Test. @@ -113,6 +123,7 @@ def test_BH1(): propagator.BH1, decimal=10) +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_construct_two_body_propagator(): # Test. @@ -174,6 +185,7 @@ def test_construct_two_body_propagator(): numpy.testing.assert_almost_equal(legacy_VHS, VHS, decimal=10) +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_phaseless_generic_propagator(): # Test. diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index 4920ab6d..46db3bae 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -6,17 +6,26 @@ from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G +from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg from ipie.addons.thermal.utils.testing import build_ueg_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import build_legacy_ueg_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers -from ipie.addons.thermal.utils.ueg import local_energy_ueg as legacy_local_energy_ueg + +try: + from ipie.legacy.estimators.ueg import fock_ueg + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True comm = MPI.COMM_WORLD + +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit -def test_phaseless_generic_propagator(): +def test_phaseless_ueg_propagator(): # UEG params. nup = 7 ndown = 7 @@ -146,4 +155,4 @@ def test_phaseless_generic_propagator(): if __name__ == "__main__": - test_phaseless_generic_propagator() + test_phaseless_ueg_propagator() diff --git a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py index b455121d..84570ce8 100644 --- a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py +++ b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py @@ -15,6 +15,12 @@ from ipie.addons.thermal.utils.testing import build_driver_generic_test_instance from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_generic_test_instance +try: + from ipie.legacy.estimators.ueg import fock_ueg + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True comm = MPI.COMM_WORLD serial_test = comm.size == 1 @@ -29,6 +35,7 @@ test_id = comm.bcast(test_id, root=0) +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_thermal_afqmc(): # System params. diff --git a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index 1bd168dd..a097eecb 100644 --- a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -19,6 +19,12 @@ from ipie.addons.thermal.utils.testing import build_driver_ueg_test_instance from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_ueg_test_instance +try: + from ipie.legacy.estimators.ueg import fock_ueg + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True comm = MPI.COMM_WORLD serial_test = comm.size == 1 @@ -65,6 +71,7 @@ def compare_test_data(ref_data, test_data): return comparison +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_thermal_afqmc_1walker(against_ref=False): # UEG params. @@ -252,6 +259,8 @@ def test_thermal_afqmc_1walker(against_ref=False): if local_err_count == 0: print(f"\n*** PASSED : {test_name} ***\n") + +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_thermal_afqmc(against_ref=False): # UEG params. @@ -438,6 +447,7 @@ def test_thermal_afqmc(against_ref=False): print(f"\n*** PASSED : {test_name} ***\n") +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.mpi def test_thermal_afqmc_mpi(against_ref=False): # UEG params. diff --git a/ipie/addons/thermal/utils/legacy/legacy_thermal_afqmc.py b/ipie/addons/thermal/utils/legacy/legacy_thermal_afqmc.py deleted file mode 100644 index f1ab65b8..00000000 --- a/ipie/addons/thermal/utils/legacy/legacy_thermal_afqmc.py +++ /dev/null @@ -1,383 +0,0 @@ -"""Driver to perform AFQMC calculation""" -import copy -import json -import sys -import time -import uuid -import warnings -from math import exp - -import h5py -import numpy - -from ipie.addons.thermal.utils.legacy.legacy_trial_utils import get_trial_density_matrix - -from ipie.legacy.estimators.handler import Estimators -from ipie.legacy.estimators.local_energy import local_energy -from ipie.legacy.hamiltonians.utils import get_hamiltonian -from ipie.legacy.thermal_propagation.utils import get_propagator -from ipie.legacy.walkers.handler import Walkers -from ipie.legacy.qmc.options import QMCOpts -from ipie.qmc.utils import set_rng_seed -from ipie.legacy.systems.utils import get_system -from ipie.utils.io import get_input_value, to_json -from ipie.utils.misc import get_git_info, print_env_info -from ipie.utils.mpi import get_shared_comm - - -class ThermalAFQMC(object): - """AFQMC driver. - - Non-zero temperature AFQMC using open ended random walk. - - Parameters - ---------- - model : dict - Input parameters for model system. - qmc_opts : dict - Input options relating to qmc parameters. - estimates : dict - Input options relating to what estimator to calculate. - trial : dict - Input options relating to trial wavefunction. - propagator : dict - Input options relating to propagator. - parallel : bool - If true we are running in parallel. - verbose : bool - If true we print out additional setup information. - - Attributes - ---------- - uuid : string - Simulation state uuid. - sha1 : string - Git hash. - seed : int - RNG seed. This is set during initialisation in calc. - root : bool - If true we are on the root / master processor. - nprocs : int - Number of processors. - rank : int - Processor id. - cplx : bool - If true then most numpy arrays are complex valued. - init_time : float - Calculation initialisation (cpu) time. - init_time : float - Human readable initialisation time. - system : system object. - Container for model input options. - qmc : :class:`pie.state.QMCOpts` object. - Container for qmc input options. - trial : :class:`pie.trial_wavefunction.X' object - Trial wavefunction class. - propagators : :class:`pie.propagation.Projectors` object - Container for system specific propagation routines. - estimators : :class:`pie.estimators.Estimators` object - Estimator handler. - walk : :class:`pie.walkers.Walkers` object - Stores walkers which sample the partition function. - """ - - def __init__( - self, - comm, - options=None, - system=None, - hamiltonian=None, - trial=None, - parallel=False, - verbose=None, - ): - if verbose is not None: - self.verbosity = verbose - if comm.rank != 0: - self.verbosity = 0 - verbose = verbose > 0 and comm.rank == 0 - else: - self.verbosity = 0 - verbose = False - qmc_opts = get_input_value( - options, - "qmc", - default={}, - alias=["qmc_options"], - verbose=self.verbosity > 1, - ) - if qmc_opts.get("beta") is None: - print("Shouldn't call ThermalAFQMC without specifying beta") - exit() - # 1. Environment attributes - if comm.rank == 0: - self.uuid = str(uuid.uuid1()) - get_sha1 = options.get("get_sha1", True) - if get_sha1: - self.sha1, self.branch, self.local_mods = get_git_info() - else: - self.sha1 = "None" - #if verbose: - # self.sys_info = print_env_info( - # self.sha1, self.branch, self.local_mods, self.uuid, comm.size - # ) - # Hack - this is modified later if running in parallel on - # initialisation. - self.root = comm.rank == 0 - self.nprocs = comm.size - self.rank = comm.rank - self._init_time = time.time() - self.run_time = (time.asctime(),) - self.shared_comm = get_shared_comm(comm, verbose=verbose) - - # 2. Calculation objects. - sys_opts = options.get("system") - if system is not None: - self.system = system - else: - sys_opts = get_input_value( - options, - "system", - default={}, - alias=["model"], - verbose=self.verbosity > 1, - ) - sys_opts["thermal"] = True - self.system = get_system(sys_opts=sys_opts, verbose=verbose) - - if hamiltonian is not None: - self.hamiltonian = hamiltonian - else: - ham_opts = get_input_value( - options, "hamiltonian", default={}, verbose=self.verbosity > 1 - ) - # backward compatibility with previous code (to be removed) - for item in sys_opts.items(): - if item[0].lower() == "name" and "name" in ham_opts.keys(): - continue - ham_opts[item[0]] = item[1] - self.hamiltonian = get_hamiltonian( - self.system, ham_opts, verbose=verbose, comm=self.shared_comm - ) - - self.qmc = QMCOpts(qmc_opts, self.system, verbose) - self.qmc.rng_seed = set_rng_seed(self.qmc.rng_seed, comm) - self.qmc.ntime_slices = int(round(self.qmc.beta / self.qmc.dt)) - # Overide whatever's in the input file due to structure of FT algorithm. - self.qmc.nsteps = 1 - self.qmc.total_steps = self.qmc.nblocks - if verbose: - print("# Number of time slices = %i" % self.qmc.ntime_slices) - self.cplx = True - if trial is not None: - self.trial = trial - if verbose: - print( - "# Trial density matrix passed from input: {} ".format( - self.trial.__class__.__name__ - ) - ) - else: - trial_opts = get_input_value( - options, - "trial", - default={}, - alias=["trial_density"], - verbose=self.verbosity > 1, - ) - self.trial = get_trial_density_matrix( - self.system, - self.hamiltonian, - self.qmc.beta, - self.qmc.dt, - comm=comm, - options=trial_opts, - verbose=verbose, - ) - - self.qmc.ntot_walkers = self.qmc.nwalkers - # Number of walkers per core/rank. - self.qmc.nwalkers = int(self.qmc.nwalkers / comm.size) - # Total number of walkers. - self.qmc.ntot_walkers = self.qmc.nwalkers * self.nprocs - if self.qmc.nwalkers == 0: - if comm.rank == 0 and verbose: - print("# WARNING: Not enough walkers for selected core count.") - print( - "# There must be at least one walker per core set in the " - "input file." - ) - print("# Setting one walker per core.") - self.qmc.nwalkers = 1 - self.qmc.ntot_walkers = self.qmc.nwalkers * self.nprocs - wlk_opts = get_input_value( - options, - "walkers", - default={}, - alias=["walker", "walker_opts"], - verbose=self.verbosity > 1, - ) - self.walk = Walkers( - self.system, - self.hamiltonian, - self.trial, - self.qmc, - walker_opts=wlk_opts, - verbose=verbose, - ) - lowrank = self.walk.walkers[0].lowrank - prop_opts = get_input_value( - options, - "propagator", - default={}, - alias=["prop", "propagation"], - verbose=self.verbosity > 1, - ) - self.propagators = get_propagator( - prop_opts, - self.qmc, - self.system, - self.hamiltonian, - self.trial, - verbose=verbose, - lowrank=lowrank, - ) - - self.tsetup = time.time() - self._init_time - est_opts = get_input_value( - options, - "estimators", - default={}, - alias=["estimates"], - verbose=self.verbosity > 1, - ) - self.estimators = Estimators( - est_opts, - self.root, - self.qmc, - self.system, - self.hamiltonian, - self.trial, - self.propagators.BT_BP, - verbose, - ) - # stabilization frequency might be updated due to wrong user input - if self.qmc.nstblz != self.propagators.nstblz: - self.propagators.nstblz = self.qmc.nstblz - if comm.rank == 0: - json_string = to_json(self) - self.estimators.json_string = json_string - self.estimators.dump_metadata() - if verbose: - self.estimators.estimators["mixed"].print_key() - self.estimators.estimators["mixed"].print_header() - - def run(self, walk=None, comm=None, verbose=None): - """Perform AFQMC simulation on state object using open-ended random walk. - - Parameters - ---------- - state : :class:`pie.state.State` object - Model and qmc parameters. - walk: :class:`pie.walker.Walkers` object - Initial wavefunction / distribution of walkers. - comm : MPI communicator - """ - if walk is not None: - self.walk = walk - self.setup_timers() - # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) - (E_T, ke, pe) = local_energy( - self.system, self.hamiltonian, self.walk.walkers[0], self.trial - ) - # (E_T, ke, pe) = self.walk.walkers[0].local_energy(self.system) - # Calculate estimates for initial distribution of walkers. - self.estimators.estimators["mixed"].update( - self.qmc, - self.system, - self.hamiltonian, - self.trial, - self.walk, - 0, - self.propagators.free_projection, - ) - # Print out zeroth step for convenience. - self.estimators.estimators["mixed"].print_step(comm, self.nprocs, 0, 1) - - for step in range(1, self.qmc.total_steps + 1): - start_path = time.time() - for ts in range(0, self.qmc.ntime_slices): - if self.verbosity >= 2 and comm.rank == 0: - print(" # Timeslice %d of %d." % (ts, self.qmc.ntime_slices)) - start = time.time() - for w in self.walk.walkers: - self.propagators.propagate_walker(self.hamiltonian, w, ts, 0) - if (abs(w.weight) > w.total_weight * 0.10) and ts > 0: - w.weight = w.total_weight * 0.10 - self.tprop += time.time() - start - start = time.time() - if ts % self.qmc.npop_control == 0 and ts != 0: - self.walk.pop_control(comm) - self.tpopc += time.time() - start - self.tpath += time.time() - start_path - start = time.time() - self.estimators.update( - self.qmc, - self.system, - self.hamiltonian, - self.trial, - self.walk, - step, - self.propagators.free_projection, - ) - self.testim += time.time() - start - self.estimators.print_step( - comm, - self.nprocs, - step, - free_projection=self.propagators.free_projection, - ) - self.walk.reset(self.trial) - - def finalise(self, verbose): - """Tidy up. - - Parameters - ---------- - verbose : bool - If true print out some information to stdout. - """ - if self.root: - if verbose: - print(f"# End Time: {time.asctime()}") - print(f"# Running time : {time.time() - self._init_time:.6f} seconds") - print("# Timing breakdown (per processor, per path/slice):") - print(f"# - Setup: {self.tsetup:f} s") - nsteps = self.qmc.nsteps - nslice = nsteps * self.qmc.ntime_slices - npcon = nslice // self.qmc.npop_control - print(f"# - Path update: {self.tpath / nsteps:f} s") - print(f"# - Propagation: {self.tprop / nslice:f} s") - print(f"# - Estimators: {self.testim / nsteps:f} s") - print(f"# - Population control: {self.tpopc / npcon:f} s") - - def determine_dtype(self, propagator, system): - """Determine dtype for trial wavefunction and walkers. - - Parameters - ---------- - propagator : dict - Propagator input options. - system : object - System object. - """ - hs_type = propagator.get("hubbard_stratonovich", "discrete") - continuous = "continuous" in hs_type - twist = system.ktwist.all() is not None - return continuous or twist - - def setup_timers(self): - self.tpath = 0 - self.tprop = 0 - self.testim = 0 - self.tpopc = 0 diff --git a/ipie/addons/thermal/utils/legacy/legacy_trial_utils.py b/ipie/addons/thermal/utils/legacy/legacy_trial_utils.py deleted file mode 100644 index f96fffa3..00000000 --- a/ipie/addons/thermal/utils/legacy/legacy_trial_utils.py +++ /dev/null @@ -1,39 +0,0 @@ -from ipie.addons.thermal.utils.legacy.legacy_mean_field import MeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody - - -def get_trial_density_matrix(system, hamiltonian, beta, dt, options={}, comm=None, verbose=False): - """Wrapper to select trial wavefunction class. - - Parameters - ---------- - - Returns - ------- - trial : class or None - Trial density matrix class. - """ - trial_type = options.get("name", "one_body") - if comm is None or comm.rank == 0: - if trial_type == "one_body_mod": - trial = OneBody( - system, - hamiltonian, - beta, - dt, - options=options, - H1=hamiltonian.h1e_mod, - verbose=verbose, - ) - elif trial_type == "one_body": - trial = OneBody(system, hamiltonian, beta, dt, options=options, verbose=verbose) - elif trial_type == "thermal_hartree_fock": - trial = MeanField(system, hamiltonian, beta, dt, options=options, verbose=verbose) - else: - trial = None - else: - trial = None - if comm is not None: - trial = comm.bcast(trial) - - return trial diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index 9e9ec737..42939a49 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -10,13 +10,12 @@ from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField from ipie.legacy.walkers.thermal import ThermalWalker from ipie.legacy.walkers.handler import Walkers from ipie.legacy.thermal_propagation.continuous import Continuous from ipie.legacy.thermal_propagation.planewave import PlaneWave - -from ipie.addons.thermal.utils.legacy.legacy_mean_field import MeanField as LegacyMeanField -from ipie.addons.thermal.utils.legacy.legacy_thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC +from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, legacy_propagator, xi=None): diff --git a/ipie/addons/thermal/walkers/tests/test_population_control.py b/ipie/addons/thermal/walkers/tests/test_population_control.py index ab03416a..9f7c29ed 100644 --- a/ipie/addons/thermal/walkers/tests/test_population_control.py +++ b/ipie/addons/thermal/walkers/tests/test_population_control.py @@ -10,8 +10,16 @@ from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers_mpi from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers +try: + from ipie.legacy.estimators.ueg import fock_ueg + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + comm = MPI.COMM_WORLD +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_pair_branch_batch(): mpi_handler = MPIHandler() @@ -122,6 +130,7 @@ def test_pair_branch_batch(): assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) +#@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") #@pytest.mark.unit def test_pair_branch_batch_lowrank(): mpi_handler = MPIHandler() @@ -233,6 +242,7 @@ def test_pair_branch_batch_lowrank(): assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_comb_batch(): mpi_handler = MPIHandler() @@ -341,6 +351,7 @@ def test_comb_batch(): assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) +#@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") #@pytest.mark.unit def test_comb_batch_lowrank(): mpi_handler = MPIHandler() diff --git a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py index 86ba3d6f..7343a46f 100644 --- a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py @@ -13,8 +13,16 @@ from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers +try: + from ipie.legacy.estimators.ueg import fock_ueg + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + comm = MPI.COMM_WORLD +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_thermal_walkers_fullrank(): # System params. @@ -106,6 +114,7 @@ def test_thermal_walkers_fullrank(): numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) +#@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") #@pytest.mark.unit def test_thermal_walkers_lowrank(): # System params. From db599e5b1ddf7928bfd429749004cf350e313ebd Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sat, 16 Mar 2024 16:43:29 -0400 Subject: [PATCH 66/84] Remove `ueg_kernels` import in `utils/ueg.py` --- ipie/addons/thermal/utils/ueg.py | 303 ------------------------------- 1 file changed, 303 deletions(-) diff --git a/ipie/addons/thermal/utils/ueg.py b/ipie/addons/thermal/utils/ueg.py index 3c895e00..c1eff342 100644 --- a/ipie/addons/thermal/utils/ueg.py +++ b/ipie/addons/thermal/utils/ueg.py @@ -2,306 +2,6 @@ import scipy.sparse from ipie.utils.io import write_qmcpack_sparse -# ----------------------------------------------------------------------------- -# Functions -# ----------------------------------------------------------------------------- -from ipie.addons.thermal.utils.ueg_kernels import ( - build_J_opt, - build_K_opt, - coulomb_greens_function_per_qvec, - exchange_greens_function_per_qvec, -) - - -def exchange_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gprod, G): - for iq in range(nq): - for idxkpq, i in zip(kpq[iq], kpq_i[iq]): - for idxpmq, j in zip(pmq[iq], pmq_i[iq]): - Gprod[iq] += G[j, idxkpq] * G[i, idxpmq] - - -def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G): - for iq in range(nq): - for idxkpq, i in zip(kpq[iq], kpq_i[iq]): - Gkpq[iq] += G[i, idxkpq] - for idxpmq, i in zip(pmq[iq], pmq_i[iq]): - Gpmq[iq] += G[i, idxpmq] - - -def local_energy_ueg(system, ham, G, Ghalf=None, two_rdm=None, debug=False): - """Local energy computation for uniform electron gas - Parameters - ---------- - system : - system class - ham : - hamiltonian class - G : - Green's function - Returns - ------- - etot : float - total energy - ke : float - kinetic energy - pe : float - potential energy - """ - if ham.diagH1: - ke = numpy.einsum("sii,sii->", ham.H1, G) - else: - ke = numpy.einsum("sij,sij->", ham.H1, G) - - Gkpq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - Gpmq = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - Gprod = numpy.zeros((2, len(ham.qvecs)), dtype=numpy.complex128) - - ne = [system.nup, system.ndown] - nq = numpy.shape(ham.qvecs)[0] - - for s in [0, 1]: - # exchange_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i,ham.ipmq_pmq, Gprod[s],G[s]) - # coulomb_greens_function(nq, ham.ikpq_i, ham.ikpq_kpq, ham.ipmq_i, ham.ipmq_pmq,Gkpq[s], Gpmq[s],G[s]) - for iq in range(nq): - Gkpq[s, iq], Gpmq[s, iq] = coulomb_greens_function_per_qvec( - ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] - ) - Gprod[s, iq] = exchange_greens_function_per_qvec( - ham.ikpq_i[iq], ham.ikpq_kpq[iq], ham.ipmq_i[iq], ham.ipmq_pmq[iq], G[s] - ) - - if two_rdm is None: - two_rdm = numpy.zeros((2, 2, len(ham.qvecs)), dtype=numpy.complex128) - - two_rdm[0, 0] = numpy.multiply(Gkpq[0], Gpmq[0]) - Gprod[0] - two_rdm[1, 1] = numpy.multiply(Gkpq[1], Gpmq[1]) - Gprod[1] - two_rdm[0, 1] = numpy.multiply(Gkpq[0], Gpmq[1]) - two_rdm[1, 0] = numpy.multiply(Gkpq[1], Gpmq[0]) - - essa = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[0, 0]) - essb = (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(two_rdm[1, 1]) - eos = (1.0 / (2.0 * ham.vol)) * ( - ham.vqvec.dot(two_rdm[0, 1]) + ham.vqvec.dot(two_rdm[1, 0])) - pe = essa + essb + eos - - if debug: - ecoul, exx = 0., 0. - - for s1 in range(2): - exx -= (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(Gprod[s1]) - - for s2 in range(2): - ecoul += (1.0 / (2.0 * ham.vol)) * ham.vqvec.dot(numpy.multiply(Gkpq[s1], Gpmq[s2])) - - print(f'\n# ueg ecoul = {ecoul}') - print(f'# ueg exx = {exx}') - print(f'# ueg e2 = {(ecoul + exx)}') - - return (ke + pe, ke, pe) - - -# JHLFML -def build_J(system, Gpmq, Gkpq): - J = [ - numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), - numpy.zeros((system.nbasis, system.nbasis), dtype=numpy.complex128), - ] - - for iq, q in enumerate(system.qvecs): - for idxi, i in enumerate(system.basis): - for idxj, j in enumerate(system.basis): - jpq = j + q - idxjpq = system.lookup_basis(jpq) - if (idxjpq is not None) and (idxjpq == idxi): - J[0][idxj, idxi] += ( - (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - ) - - for iq, q in enumerate(system.qvecs): - for idxi, i in enumerate(system.basis): - for idxj, j in enumerate(system.basis): - jpq = j - q - idxjmq = system.lookup_basis(jpq) - if (idxjmq is not None) and (idxjmq == idxi): - J[0][idxj, idxi] += ( - (1.0 / (2.0 * system.vol)) * system.vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - ) - - J[1] = J[0] - - return J - - -def build_K(system, G): - K = numpy.zeros((2, system.nbasis, system.nbasis), dtype=numpy.complex128) - for s in [0, 1]: - for iq in range(len(system.vqvec)): - for idxjmq, idxj in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): - for idxkpq, idxk in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): - K[s, idxj, idxkpq] += ( - -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjmq, idxk] - ) - for iq in range(len(system.vqvec)): - for idxjpq, idxj in zip(system.ikpq_kpq[iq], system.ikpq_i[iq]): - for idxpmq, idxp in zip(system.ipmq_pmq[iq], system.ipmq_i[iq]): - K[s, idxj, idxpmq] += ( - -(1.0 / (2.0 * system.vol)) * system.vqvec[iq] * G[s][idxjpq, idxp] - ) - return K - - -def fock_ueg(ham, G): - """Fock matrix computation for uniform electron gas - - Parameters - ---------- - ham : :class`ipie.legacy.hamiltonians.ueg` - UEG hamiltonian class. - G : :class:`numpy.ndarray` - Green's function. - Returns - ------- - F : :class:`numpy.ndarray` - Fock matrix (2, nbasis, nbasis). - """ - nbsf = ham.nbasis - nq = len(ham.qvecs) - assert nq == len(ham.vqvec) - - Fock = numpy.zeros((2, nbsf, nbsf), dtype=numpy.complex128) - Gkpq = numpy.zeros((2, nq), dtype=numpy.complex128) - Gpmq = numpy.zeros((2, nq), dtype=numpy.complex128) - - for s in [0, 1]: - coulomb_greens_function( - nq, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - Gkpq[s], - Gpmq[s], - G[s], - ) - - J = build_J_opt( - nq, - ham.vqvec, - ham.vol, - ham.nbasis, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - Gkpq, - Gpmq, - ) - - K = build_K_opt( - nq, - ham.vqvec, - ham.vol, - ham.nbasis, - ham.ikpq_i, - ham.ikpq_kpq, - ham.ipmq_i, - ham.ipmq_pmq, - G, - ) - - for s in [0, 1]: - Fock[s] = ham.H1[s] + J[s] + K[s] - - return Fock - - -def unit_test(): - import numpy as np - - from ipie.legacy.systems.ueg import UEG - - inputs = {"nup": 7, "ndown": 7, "rs": 1.0, "ecut": 2.0} - system = UEG(inputs, True) - system.build() - nbsf = system.nbasis - Pa = np.zeros([nbsf, nbsf], dtype=np.complex128) - Pb = np.zeros([nbsf, nbsf], dtype=np.complex128) - na = system.nup - nb = system.ndown - for i in range(na): - Pa[i, i] = 1.0 - for i in range(nb): - Pb[i, i] = 1.0 - P = np.array([Pa, Pb]) - etot, ekin, epot = local_energy_ueg(system, G=P) - print(f"ERHF = {etot}, {ekin}, {epot}") - - from ipie.legacy.estimators.greens_function import gab - from ipie.utils.linalg import exponentiate_matrix, reortho - - # numpy.random.seed() - rCa = numpy.random.randn(nbsf, na) - zCa = numpy.random.randn(nbsf, na) - rCb = numpy.random.randn(nbsf, nb) - zCb = numpy.random.randn(nbsf, nb) - - Ca = rCa + 1j * zCa - Cb = rCb + 1j * zCb - - Ca, detR = reortho(Ca) - Cb, detR = reortho(Cb) - # S = print(Ca.dot(Cb.T)) - # print(S) - # exit() - Ca = numpy.array(Ca, dtype=numpy.complex128) - Cb = numpy.array(Cb, dtype=numpy.complex128) - P = [gab(Ca, Ca), gab(Cb, Cb)] - # diff = P[0] - P[1] - # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) - - # solver = lib.diis.DIIS() - - # dt = 0.1 - # for i in range(100): - # # Compute Fock matrix - # Fock = fock_ueg(system, G=P) - # # Compute DIIS Errvec - # PFmFPa = P[0].dot(Fock[0]) - Fock[0].dot(P[0]) - # PFmFPb = P[1].dot(Fock[1]) - Fock[1].dot(P[1]) - # errvec = numpy.append(numpy.reshape(PFmFPa, nbsf*nbsf),numpy.reshape(PFmFPb, nbsf*nbsf)) - # RMS = np.sqrt(np.dot(errvec, errvec)) - # print ("{} {} {}".format(i,numpy.real(local_energy_ueg(system, P)), numpy.real(RMS))) - # # Form Fockvec - # Fock[0] = numpy.array(Fock[0]) - # Fock[1] = numpy.array(Fock[1]) - # Fockvec = numpy.append(numpy.reshape(Fock[0],nbsf*nbsf), numpy.reshape(Fock[1],nbsf*nbsf)) - # # Extrapolate Fockvec - # # Fockvec = solver.update(Fockvec, xerr=errvec) - - # # Apply Propagator - # Fock = numpy.reshape(Fockvec, (2, nbsf, nbsf)) - # ea, Ca = numpy.linalg.eig(Fock[0]) - # eb, Cb = numpy.linalg.eig(Fock[1]) - # sort_perm = ea.argsort() - # ea.sort() - # Ca = Ca[:, sort_perm] - # sort_perm = eb.argsort() - # eb.sort() - # Cb = Cb[:, sort_perm] - - # Ca = Ca[:,:na] - # Cb = Cb[:,:nb] - # Ca, detR = reortho(Ca) - # Cb, detR = reortho(Cb) - - # P = [gab(Ca, Ca), gab(Cb, Cb)] - # # expF = [exponentiate_matrix(-dt*Fock[0]), exponentiate_matrix(-dt*Fock[1])] - # # Ca = expF[0].dot(Ca) - # # Cb = expF[1].dot(Cb) - # # diff = P[0] - P[1] - # # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro'))) - - # ----------------------------------------------------------------------------- # System class. # ----------------------------------------------------------------------------- @@ -863,6 +563,3 @@ def write_integrals(self, filename="ueg_integrals.h5"): enuc=0.0, filename=filename) - -if __name__ == "__main__": - unit_test() From 39abb9bc3ed26c1ce73c203e292171767a55b448 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 17 Mar 2024 17:42:48 -0400 Subject: [PATCH 67/84] Skip `pytest` for tests that invoke `fock_ueg` imports. --- .../thermal/estimators/tests/test_generic.py | 18 +- .../propagation/tests/test_operations.py | 13 +- .../propagation/tests/test_prop_generic.py | 20 +- .../propagation/tests/ueg/test_prop_ueg.py | 21 +- .../thermal/qmc/tests/test_afqmc_generic.py | 15 +- .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 15 +- .../thermal/utils/legacy/legacy_fock.py | 8 - .../thermal/utils/legacy/legacy_mean_field.py | 114 - ipie/addons/thermal/utils/ueg_kernels.c | 28372 ---------------- ipie/addons/thermal/utils/ueg_kernels.pyx | 169 - .../walkers/tests/test_population_control.py | 16 +- .../walkers/tests/test_thermal_walkers.py | 20 +- 12 files changed, 62 insertions(+), 28739 deletions(-) delete mode 100644 ipie/addons/thermal/utils/legacy/legacy_fock.py delete mode 100644 ipie/addons/thermal/utils/legacy/legacy_mean_field.py delete mode 100644 ipie/addons/thermal/utils/ueg_kernels.c delete mode 100644 ipie/addons/thermal/utils/ueg_kernels.pyx diff --git a/ipie/addons/thermal/estimators/tests/test_generic.py b/ipie/addons/thermal/estimators/tests/test_generic.py index 032a30b8..337318fe 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic.py +++ b/ipie/addons/thermal/estimators/tests/test_generic.py @@ -2,23 +2,21 @@ import pytest from typing import Tuple, Union +try: + from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + from ipie.config import MPI from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky -from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers - -try: - from ipie.legacy.estimators.ueg import fock_ueg - _no_cython = False - -except ModuleNotFoundError: - _no_cython = True - comm = MPI.COMM_WORLD @pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") diff --git a/ipie/addons/thermal/propagation/tests/test_operations.py b/ipie/addons/thermal/propagation/tests/test_operations.py index c852ea0e..dca76528 100644 --- a/ipie/addons/thermal/propagation/tests/test_operations.py +++ b/ipie/addons/thermal/propagation/tests/test_operations.py @@ -1,19 +1,18 @@ import numpy import pytest -from ipie.config import MPI -from ipie.addons.thermal.propagation.operations import apply_exponential -from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers - try: - from ipie.legacy.estimators.ueg import fock_ueg + from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers + from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers _no_cython = False except ModuleNotFoundError: _no_cython = True +from ipie.config import MPI +from ipie.addons.thermal.propagation.operations import apply_exponential +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers + comm = MPI.COMM_WORLD @pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") diff --git a/ipie/addons/thermal/propagation/tests/test_prop_generic.py b/ipie/addons/thermal/propagation/tests/test_prop_generic.py index 5bdd7ed2..de68068b 100644 --- a/ipie/addons/thermal/propagation/tests/test_prop_generic.py +++ b/ipie/addons/thermal/propagation/tests/test_prop_generic.py @@ -1,24 +1,22 @@ import numpy import pytest +try: + from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers + from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + from ipie.config import MPI from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers - -try: - from ipie.legacy.estimators.ueg import fock_ueg - _no_cython = False - -except ModuleNotFoundError: - _no_cython = True - comm = MPI.COMM_WORLD # System params. diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index 46db3bae..d759cb5d 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -1,25 +1,22 @@ import pytest import numpy +try: + from ipie.addons.thermal.utils.legacy_testing import build_legacy_ueg_test_case_handlers + from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + from ipie.config import MPI from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.utils.testing import build_ueg_test_case_handlers from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg -from ipie.addons.thermal.utils.testing import build_ueg_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import build_legacy_ueg_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers - - -try: - from ipie.legacy.estimators.ueg import fock_ueg - _no_cython = False - -except ModuleNotFoundError: - _no_cython = True - comm = MPI.COMM_WORLD diff --git a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py index 84570ce8..b617120e 100644 --- a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py +++ b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py @@ -6,6 +6,13 @@ import numpy from typing import Union +try: + from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_generic_test_instance + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + from ipie.config import MPI from ipie.analysis.extraction import ( extract_test_data_hdf5, @@ -13,14 +20,6 @@ extract_observable, extract_mixed_estimates) from ipie.addons.thermal.utils.testing import build_driver_generic_test_instance -from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_generic_test_instance - -try: - from ipie.legacy.estimators.ueg import fock_ueg - _no_cython = False - -except ModuleNotFoundError: - _no_cython = True comm = MPI.COMM_WORLD serial_test = comm.size == 1 diff --git a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index a097eecb..ccb210f0 100644 --- a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -9,6 +9,13 @@ import numpy from typing import Union +try: + from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_ueg_test_instance + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + from ipie.config import MPI from ipie.analysis.extraction import ( get_metadata, @@ -17,14 +24,6 @@ extract_observable, extract_mixed_estimates) from ipie.addons.thermal.utils.testing import build_driver_ueg_test_instance -from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_ueg_test_instance - -try: - from ipie.legacy.estimators.ueg import fock_ueg - _no_cython = False - -except ModuleNotFoundError: - _no_cython = True comm = MPI.COMM_WORLD serial_test = comm.size == 1 diff --git a/ipie/addons/thermal/utils/legacy/legacy_fock.py b/ipie/addons/thermal/utils/legacy/legacy_fock.py deleted file mode 100644 index f78116a1..00000000 --- a/ipie/addons/thermal/utils/legacy/legacy_fock.py +++ /dev/null @@ -1,8 +0,0 @@ -from ipie.estimators.generic import fock_generic - -def fock_matrix(system, G): - if system.name == "Generic": - return fock_generic(system, G) - else: - print(f"# Fock matrix not implemented for {system.name}") - return None diff --git a/ipie/addons/thermal/utils/legacy/legacy_mean_field.py b/ipie/addons/thermal/utils/legacy/legacy_mean_field.py deleted file mode 100644 index 5a0927b4..00000000 --- a/ipie/addons/thermal/utils/legacy/legacy_mean_field.py +++ /dev/null @@ -1,114 +0,0 @@ -import numpy -import scipy.linalg - -from ipie.addons.thermal.utils.legacy.legacy_fock import fock_matrix - -from ipie.legacy.estimators.local_energy import local_energy -from ipie.legacy.estimators.thermal import entropy, greens_function, one_rdm_stable, particle_number -from ipie.legacy.trial_density_matrices.chem_pot import compute_rho, find_chemical_potential -from ipie.legacy.trial_density_matrices.onebody import OneBody - - -class MeanField(OneBody): - def __init__(self, system, hamiltonian, beta, dt, options={}, H1=None, verbose=False): - OneBody.__init__( - self, system, hamiltonian, beta, dt, options=options, H1=H1, verbose=verbose - ) - if verbose: - print(" # Building THF density matrix.") - self.alpha = options.get("alpha", 0.75) - self.max_scf_it = options.get("max_scf_it", self.max_it) - self.max_macro_it = options.get("max_macro_it", self.max_it) - self.find_mu = options.get("find_mu", True) - self.P, HMF, self.mu = self.thermal_hartree_fock(hamiltonian, beta) - muN = self.mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) - self.dmat = numpy.array( - [ - scipy.linalg.expm(-dt * (HMF[0] - muN)), - scipy.linalg.expm(-dt * (HMF[1] - muN)), - ] - ) - self.dmat_inv = numpy.array( - [ - scipy.linalg.inv(self.dmat[0], check_finite=False), - scipy.linalg.inv(self.dmat[1], check_finite=False), - ] - ) - self.G = numpy.array([greens_function(self.dmat[0]), greens_function(self.dmat[1])]) - self.nav = particle_number(self.P).real - - def thermal_hartree_fock(self, system, beta): - dt = self.dtau - mu_old = self.mu - P = self.P.copy() - if self.verbose: - print("# Determining Thermal Hartree-Fock Density Matrix.") - for it in range(self.max_macro_it): - if self.verbose: - print(f"# Macro iteration: {it}") - HMF = self.scf(system, beta, mu_old, P) - rho = numpy.array([scipy.linalg.expm(-dt * HMF[0]), scipy.linalg.expm(-dt * HMF[1])]) - if self.find_mu: - mu = find_chemical_potential( - system._alt_convention, - rho, - dt, - self.num_bins, - self.nav, - deps=self.deps, - max_it=self.max_it, - verbose=self.verbose, - ) - else: - mu = self.mu - rho_mu = compute_rho(rho, mu_old, dt) - P = one_rdm_stable(rho_mu, self.num_bins) - dmu = abs(mu - mu_old) - if self.verbose: - print(f"# New mu: {mu:13.8e} Old mu: {mu_old:13.8e} Dmu: {dmu:13.8e}") - if dmu < self.deps: - break - mu_old = mu - return P, HMF, mu - - def scf(self, system, beta, mu, P): - # 1. Compute HMF - HMF = fock_matrix(system, P) - dt = self.dtau - muN = mu * numpy.eye(system.nbasis, dtype=self.G.dtype) - rho = numpy.array( - [ - scipy.linalg.expm(-dt * (HMF[0] - muN)), - scipy.linalg.expm(-dt * (HMF[1] - muN)), - ] - ) - Pold = one_rdm_stable(rho, self.num_bins) - if self.verbose: - print(" # Running Thermal SCF.") - for it in range(self.max_scf_it): - HMF = fock_matrix(system, Pold) - rho = numpy.array( - [ - scipy.linalg.expm(-dt * (HMF[0] - muN)), - scipy.linalg.expm(-dt * (HMF[1] - muN)), - ] - ) - Pnew = (1 - self.alpha) * one_rdm_stable(rho, self.num_bins) + self.alpha * Pold - change = numpy.linalg.norm(Pnew - Pold) - if change < self.deps: - break - #if self.verbose: - # N = particle_number(P).real - # E = local_energy(system, P)[0].real - # S = entropy(beta, mu, HMF) - # omega = E - mu * N - 1.0 / beta * S - # print( - # " # Iteration: {:4d} dP: {:13.8e} Omega: {:13.8e}".format( - # it, change, omega.real - # ) - # ) - Pold = Pnew.copy() - if self.verbose: - N = particle_number(P).real - print(f" # Average particle number: {N:13.8e}") - return HMF diff --git a/ipie/addons/thermal/utils/ueg_kernels.c b/ipie/addons/thermal/utils/ueg_kernels.c deleted file mode 100644 index 428b8d9a..00000000 --- a/ipie/addons/thermal/utils/ueg_kernels.c +++ /dev/null @@ -1,28372 +0,0 @@ -/* Generated by Cython 0.29.35 */ - -/* BEGIN: Cython Metadata -{ - "distutils": { - "depends": [ - "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/arrayobject.h", - "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/arrayscalars.h", - "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/ndarrayobject.h", - "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/ndarraytypes.h", - "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include/numpy/ufuncobject.h" - ], - "extra_compile_args": [ - "-O3" - ], - "include_dirs": [ - "/Users/shufay/envs/ipie/lib/python3.9/site-packages/numpy/core/include" - ], - "name": "ueg_kernels", - "sources": [ - "ueg_kernels.pyx" - ] - }, - "module_name": "ueg_kernels" -} -END: Cython Metadata */ - -#ifndef PY_SSIZE_T_CLEAN -#define PY_SSIZE_T_CLEAN -#endif /* PY_SSIZE_T_CLEAN */ -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) - #error Cython requires Python 2.6+ or Python 3.3+. -#else -#define CYTHON_ABI "0_29_35" -#define CYTHON_HEX_VERSION 0x001D23F0 -#define CYTHON_FUTURE_DIVISION 1 -#include -#ifndef offsetof - #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#define __PYX_COMMA , -#ifndef HAVE_LONG_LONG - #if PY_VERSION_HEX >= 0x02070000 - #define HAVE_LONG_LONG - #endif -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION - #define CYTHON_COMPILING_IN_PYPY 1 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #define CYTHON_COMPILING_IN_NOGIL 0 - #undef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 0 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #if PY_VERSION_HEX < 0x03050000 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #undef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #undef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 1 - #undef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 0 - #undef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 0 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #if PY_VERSION_HEX < 0x03090000 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) - #define CYTHON_PEP489_MULTI_PHASE_INIT 1 - #endif - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 - #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC - #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 - #endif -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #define CYTHON_COMPILING_IN_NOGIL 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 - #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC - #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 - #endif -#elif defined(PY_NOGIL) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #define CYTHON_COMPILING_IN_NOGIL 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #ifndef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 1 - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 1 - #endif - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #define CYTHON_COMPILING_IN_NOGIL 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) - #define CYTHON_USE_PYTYPE_LOOKUP 1 - #endif - #if PY_MAJOR_VERSION < 3 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #elif !defined(CYTHON_USE_PYLONG_INTERNALS) - #define CYTHON_USE_PYLONG_INTERNALS (PY_VERSION_HEX < 0x030C00A5) - #endif - #ifndef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 1 - #endif - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #if PY_VERSION_HEX < 0x030300F0 || PY_VERSION_HEX >= 0x030B00A2 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #elif !defined(CYTHON_USE_UNICODE_WRITER) - #define CYTHON_USE_UNICODE_WRITER 1 - #endif - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #if PY_VERSION_HEX >= 0x030B00A4 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #elif !defined(CYTHON_FAST_THREAD_STATE) - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL (PY_VERSION_HEX < 0x030A0000) - #endif - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) - #endif - #ifndef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS ((PY_VERSION_HEX >= 0x030600B1) && (PY_VERSION_HEX < 0x030C00A5)) - #endif - #if PY_VERSION_HEX >= 0x030B00A4 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 - #elif !defined(CYTHON_USE_EXC_INFO_STACK) - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif - #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC - #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #if PY_MAJOR_VERSION < 3 - #include "longintrepr.h" - #endif - #undef SHIFT - #undef BASE - #undef MASK - #ifdef SIZEOF_VOID_P - enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; - #endif -#endif -#ifndef __has_attribute - #define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute - #define __has_cpp_attribute(x) 0 -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_MAYBE_UNUSED_VAR -# if defined(__cplusplus) - template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } -# else -# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) -#ifdef _MSC_VER - #ifndef _MSC_STDINT_H_ - #if _MSC_VER < 1300 - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; - #else - typedef unsigned __int8 uint8_t; - typedef unsigned __int32 uint32_t; - #endif - #endif -#else - #include -#endif -#ifndef CYTHON_FALLTHROUGH - #if defined(__cplusplus) && __cplusplus >= 201103L - #if __has_cpp_attribute(fallthrough) - #define CYTHON_FALLTHROUGH [[fallthrough]] - #elif __has_cpp_attribute(clang::fallthrough) - #define CYTHON_FALLTHROUGH [[clang::fallthrough]] - #elif __has_cpp_attribute(gnu::fallthrough) - #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] - #endif - #endif - #ifndef CYTHON_FALLTHROUGH - #if __has_attribute(fallthrough) - #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) - #else - #define CYTHON_FALLTHROUGH - #endif - #endif - #if defined(__clang__ ) && defined(__apple_build_version__) - #if __apple_build_version__ < 7000000 - #undef CYTHON_FALLTHROUGH - #define CYTHON_FALLTHROUGH - #endif - #endif -#endif - -#ifndef CYTHON_INLINE - #if defined(__clang__) - #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) - #elif defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) - #define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" - #define __Pyx_DefaultClassType PyType_Type -#if PY_VERSION_HEX >= 0x030B00A1 - static CYTHON_INLINE PyCodeObject* __Pyx_PyCode_New(int a, int k, int l, int s, int f, - PyObject *code, PyObject *c, PyObject* n, PyObject *v, - PyObject *fv, PyObject *cell, PyObject* fn, - PyObject *name, int fline, PyObject *lnos) { - PyObject *kwds=NULL, *argcount=NULL, *posonlyargcount=NULL, *kwonlyargcount=NULL; - PyObject *nlocals=NULL, *stacksize=NULL, *flags=NULL, *replace=NULL, *call_result=NULL, *empty=NULL; - const char *fn_cstr=NULL; - const char *name_cstr=NULL; - PyCodeObject* co=NULL; - PyObject *type, *value, *traceback; - PyErr_Fetch(&type, &value, &traceback); - if (!(kwds=PyDict_New())) goto end; - if (!(argcount=PyLong_FromLong(a))) goto end; - if (PyDict_SetItemString(kwds, "co_argcount", argcount) != 0) goto end; - if (!(posonlyargcount=PyLong_FromLong(0))) goto end; - if (PyDict_SetItemString(kwds, "co_posonlyargcount", posonlyargcount) != 0) goto end; - if (!(kwonlyargcount=PyLong_FromLong(k))) goto end; - if (PyDict_SetItemString(kwds, "co_kwonlyargcount", kwonlyargcount) != 0) goto end; - if (!(nlocals=PyLong_FromLong(l))) goto end; - if (PyDict_SetItemString(kwds, "co_nlocals", nlocals) != 0) goto end; - if (!(stacksize=PyLong_FromLong(s))) goto end; - if (PyDict_SetItemString(kwds, "co_stacksize", stacksize) != 0) goto end; - if (!(flags=PyLong_FromLong(f))) goto end; - if (PyDict_SetItemString(kwds, "co_flags", flags) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_code", code) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_consts", c) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_names", n) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_varnames", v) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_freevars", fv) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_cellvars", cell) != 0) goto end; - if (PyDict_SetItemString(kwds, "co_linetable", lnos) != 0) goto end; - if (!(fn_cstr=PyUnicode_AsUTF8AndSize(fn, NULL))) goto end; - if (!(name_cstr=PyUnicode_AsUTF8AndSize(name, NULL))) goto end; - if (!(co = PyCode_NewEmpty(fn_cstr, name_cstr, fline))) goto end; - if (!(replace = PyObject_GetAttrString((PyObject*)co, "replace"))) goto cleanup_code_too; - if (!(empty = PyTuple_New(0))) goto cleanup_code_too; // unfortunately __pyx_empty_tuple isn't available here - if (!(call_result = PyObject_Call(replace, empty, kwds))) goto cleanup_code_too; - Py_XDECREF((PyObject*)co); - co = (PyCodeObject*)call_result; - call_result = NULL; - if (0) { - cleanup_code_too: - Py_XDECREF((PyObject*)co); - co = NULL; - } - end: - Py_XDECREF(kwds); - Py_XDECREF(argcount); - Py_XDECREF(posonlyargcount); - Py_XDECREF(kwonlyargcount); - Py_XDECREF(nlocals); - Py_XDECREF(stacksize); - Py_XDECREF(replace); - Py_XDECREF(call_result); - Py_XDECREF(empty); - if (type) { - PyErr_Restore(type, value, traceback); - } - return co; - } -#else - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#ifndef METH_STACKLESS - #define METH_STACKLESS 0 -#endif -#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) - #ifndef METH_FASTCALL - #define METH_FASTCALL 0x80 - #endif - typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); - typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames); -#else - #define __Pyx_PyCFunctionFast _PyCFunctionFast - #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords -#endif -#if CYTHON_FAST_PYCCALL -#define __Pyx_PyFastCFunction_Check(func)\ - ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) -#else -#define __Pyx_PyFastCFunction_Check(func) 0 -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) - #define PyObject_Malloc(s) PyMem_Malloc(s) - #define PyObject_Free(p) PyMem_Free(p) - #define PyObject_Realloc(p) PyMem_Realloc(p) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 - #define PyMem_RawMalloc(n) PyMem_Malloc(n) - #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) - #define PyMem_RawFree(p) PyMem_Free(p) -#endif -#if CYTHON_COMPILING_IN_PYSTON - #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) -#else - #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) -#endif -#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#elif PY_VERSION_HEX >= 0x03060000 - #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() -#elif PY_VERSION_HEX >= 0x03000000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#else - #define __Pyx_PyThreadState_Current _PyThreadState_Current -#endif -#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) -#include "pythread.h" -#define Py_tss_NEEDS_INIT 0 -typedef int Py_tss_t; -static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { - *key = PyThread_create_key(); - return 0; -} -static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { - Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); - *key = Py_tss_NEEDS_INIT; - return key; -} -static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { - PyObject_Free(key); -} -static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { - return *key != Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { - PyThread_delete_key(*key); - *key = Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { - return PyThread_set_key_value(*key, value); -} -static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { - return PyThread_get_key_value(*key); -} -#endif -#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) -#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) -#else -#define __Pyx_PyDict_NewPresized(n) PyDict_New() -#endif -#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS -#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) -#else -#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #if PY_VERSION_HEX >= 0x030C0000 - #define __Pyx_PyUnicode_READY(op) (0) - #else - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #endif - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) - #if PY_VERSION_HEX >= 0x030C0000 - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) - #else - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) - #endif - #endif -#else - #define CYTHON_PEP393_ENABLED 0 - #define PyUnicode_1BYTE_KIND 1 - #define PyUnicode_2BYTE_KIND 2 - #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) - #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) - #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) - #define PyObject_ASCII(o) PyObject_Repr(o) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#ifndef PyObject_Unicode - #define PyObject_Unicode PyObject_Str -#endif -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#if PY_VERSION_HEX >= 0x030900A4 - #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) -#else - #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) -#endif -#if CYTHON_ASSUME_SAFE_MACROS - #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) -#else - #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsHash_t -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if CYTHON_USE_ASYNC_SLOTS - #if PY_VERSION_HEX >= 0x030500B1 - #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods - #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) - #else - #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) - #endif -#else - #define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef __Pyx_PyAsyncMethodsStruct - typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; - } __Pyx_PyAsyncMethodsStruct; -#endif - -#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) - #if !defined(_USE_MATH_DEFINES) - #define _USE_MATH_DEFINES - #endif -#endif -#include -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif -#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) -#define __Pyx_truncl trunc -#else -#define __Pyx_truncl truncl -#endif - -#define __PYX_MARK_ERR_POS(f_index, lineno) \ - { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } -#define __PYX_ERR(f_index, lineno, Ln_error) \ - { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE__ueg_kernels -#define __PYX_HAVE_API__ueg_kernels -/* Early includes */ -#include -#include -#include "numpy/arrayobject.h" -#include "numpy/ndarrayobject.h" -#include "numpy/ndarraytypes.h" -#include "numpy/arrayscalars.h" -#include "numpy/ufuncobject.h" - - /* NumPy API declarations from "numpy/__init__.pxd" */ - -#include "pythread.h" -#include -#include "pystate.h" -#ifdef _OPENMP -#include -#endif /* _OPENMP */ - -#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { - return (size_t) i < (size_t) limit; -} -#if defined (__cplusplus) && __cplusplus >= 201103L - #include - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) - #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); -#define __Pyx_PySequence_Tuple(obj)\ - (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); -#if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) -#else -#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) -#endif -#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ -static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } - -static PyObject *__pyx_m = NULL; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime = NULL; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static PyObject *__pyx_empty_unicode; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - -/* Header.proto */ -#if !defined(CYTHON_CCOMPLEX) - #if defined(__cplusplus) - #define CYTHON_CCOMPLEX 1 - #elif defined(_Complex_I) - #define CYTHON_CCOMPLEX 1 - #else - #define CYTHON_CCOMPLEX 0 - #endif -#endif -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - #include - #else - #include - #endif -#endif -#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) - #undef _Complex_I - #define _Complex_I 1.0fj -#endif - - -static const char *__pyx_f[] = { - "ueg_kernels.pyx", - "__init__.pxd", - "stringsource", - "type.pxd", -}; -/* MemviewSliceStruct.proto */ -struct __pyx_memoryview_obj; -typedef struct { - struct __pyx_memoryview_obj *memview; - char *data; - Py_ssize_t shape[8]; - Py_ssize_t strides[8]; - Py_ssize_t suboffsets[8]; -} __Pyx_memviewslice; -#define __Pyx_MemoryView_Len(m) (m.shape[0]) - -/* Atomics.proto */ -#include -#ifndef CYTHON_ATOMICS - #define CYTHON_ATOMICS 1 -#endif -#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS -#define __pyx_atomic_int_type int -#if CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ - (__GNUC_MINOR__ > 1 ||\ - (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) - #define __pyx_atomic_incr_aligned(value) __sync_fetch_and_add(value, 1) - #define __pyx_atomic_decr_aligned(value) __sync_fetch_and_sub(value, 1) - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using GNU atomics" - #endif -#elif CYTHON_ATOMICS && defined(_MSC_VER) && CYTHON_COMPILING_IN_NOGIL - #include - #undef __pyx_atomic_int_type - #define __pyx_atomic_int_type long - #pragma intrinsic (_InterlockedExchangeAdd) - #define __pyx_atomic_incr_aligned(value) _InterlockedExchangeAdd(value, 1) - #define __pyx_atomic_decr_aligned(value) _InterlockedExchangeAdd(value, -1) - #ifdef __PYX_DEBUG_ATOMICS - #pragma message ("Using MSVC atomics") - #endif -#else - #undef CYTHON_ATOMICS - #define CYTHON_ATOMICS 0 - #ifdef __PYX_DEBUG_ATOMICS - #warning "Not using atomics" - #endif -#endif -typedef volatile __pyx_atomic_int_type __pyx_atomic_int; -#if CYTHON_ATOMICS - #define __pyx_add_acquisition_count(memview)\ - __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview)) - #define __pyx_sub_acquisition_count(memview)\ - __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview)) -#else - #define __pyx_add_acquisition_count(memview)\ - __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview)\ - __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) -#endif - -/* ForceInitThreads.proto */ -#ifndef __PYX_FORCE_INIT_THREADS - #define __PYX_FORCE_INIT_THREADS 0 -#endif - -/* NoFastGil.proto */ -#define __Pyx_PyGILState_Ensure PyGILState_Ensure -#define __Pyx_PyGILState_Release PyGILState_Release -#define __Pyx_FastGIL_Remember() -#define __Pyx_FastGIL_Forget() -#define __Pyx_FastGilFuncInit() - -/* BufferFormatStructs.proto */ -#define IS_UNSIGNED(type) (((type) -1) > 0) -struct __Pyx_StructField_; -#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) -typedef struct { - const char* name; - struct __Pyx_StructField_* fields; - size_t size; - size_t arraysize[8]; - int ndim; - char typegroup; - char is_unsigned; - int flags; -} __Pyx_TypeInfo; -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - size_t struct_alignment; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; - char is_valid_array; -} __Pyx_BufFmt_Context; - - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":689 - * # in Cython to enable them only on the right systems. - * - * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< - * ctypedef npy_int16 int16_t - * ctypedef npy_int32 int32_t - */ -typedef npy_int8 __pyx_t_5numpy_int8_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":690 - * - * ctypedef npy_int8 int8_t - * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< - * ctypedef npy_int32 int32_t - * ctypedef npy_int64 int64_t - */ -typedef npy_int16 __pyx_t_5numpy_int16_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":691 - * ctypedef npy_int8 int8_t - * ctypedef npy_int16 int16_t - * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< - * ctypedef npy_int64 int64_t - * #ctypedef npy_int96 int96_t - */ -typedef npy_int32 __pyx_t_5numpy_int32_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":692 - * ctypedef npy_int16 int16_t - * ctypedef npy_int32 int32_t - * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< - * #ctypedef npy_int96 int96_t - * #ctypedef npy_int128 int128_t - */ -typedef npy_int64 __pyx_t_5numpy_int64_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":696 - * #ctypedef npy_int128 int128_t - * - * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< - * ctypedef npy_uint16 uint16_t - * ctypedef npy_uint32 uint32_t - */ -typedef npy_uint8 __pyx_t_5numpy_uint8_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":697 - * - * ctypedef npy_uint8 uint8_t - * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< - * ctypedef npy_uint32 uint32_t - * ctypedef npy_uint64 uint64_t - */ -typedef npy_uint16 __pyx_t_5numpy_uint16_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":698 - * ctypedef npy_uint8 uint8_t - * ctypedef npy_uint16 uint16_t - * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< - * ctypedef npy_uint64 uint64_t - * #ctypedef npy_uint96 uint96_t - */ -typedef npy_uint32 __pyx_t_5numpy_uint32_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":699 - * ctypedef npy_uint16 uint16_t - * ctypedef npy_uint32 uint32_t - * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< - * #ctypedef npy_uint96 uint96_t - * #ctypedef npy_uint128 uint128_t - */ -typedef npy_uint64 __pyx_t_5numpy_uint64_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":703 - * #ctypedef npy_uint128 uint128_t - * - * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< - * ctypedef npy_float64 float64_t - * #ctypedef npy_float80 float80_t - */ -typedef npy_float32 __pyx_t_5numpy_float32_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":704 - * - * ctypedef npy_float32 float32_t - * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< - * #ctypedef npy_float80 float80_t - * #ctypedef npy_float128 float128_t - */ -typedef npy_float64 __pyx_t_5numpy_float64_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":713 - * # The int types are mapped a bit surprising -- - * # numpy.int corresponds to 'l' and numpy.long to 'q' - * ctypedef npy_long int_t # <<<<<<<<<<<<<< - * ctypedef npy_longlong long_t - * ctypedef npy_longlong longlong_t - */ -typedef npy_long __pyx_t_5numpy_int_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":714 - * # numpy.int corresponds to 'l' and numpy.long to 'q' - * ctypedef npy_long int_t - * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< - * ctypedef npy_longlong longlong_t - * - */ -typedef npy_longlong __pyx_t_5numpy_long_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":715 - * ctypedef npy_long int_t - * ctypedef npy_longlong long_t - * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< - * - * ctypedef npy_ulong uint_t - */ -typedef npy_longlong __pyx_t_5numpy_longlong_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":717 - * ctypedef npy_longlong longlong_t - * - * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< - * ctypedef npy_ulonglong ulong_t - * ctypedef npy_ulonglong ulonglong_t - */ -typedef npy_ulong __pyx_t_5numpy_uint_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":718 - * - * ctypedef npy_ulong uint_t - * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< - * ctypedef npy_ulonglong ulonglong_t - * - */ -typedef npy_ulonglong __pyx_t_5numpy_ulong_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":719 - * ctypedef npy_ulong uint_t - * ctypedef npy_ulonglong ulong_t - * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< - * - * ctypedef npy_intp intp_t - */ -typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":721 - * ctypedef npy_ulonglong ulonglong_t - * - * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< - * ctypedef npy_uintp uintp_t - * - */ -typedef npy_intp __pyx_t_5numpy_intp_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":722 - * - * ctypedef npy_intp intp_t - * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< - * - * ctypedef npy_double float_t - */ -typedef npy_uintp __pyx_t_5numpy_uintp_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":724 - * ctypedef npy_uintp uintp_t - * - * ctypedef npy_double float_t # <<<<<<<<<<<<<< - * ctypedef npy_double double_t - * ctypedef npy_longdouble longdouble_t - */ -typedef npy_double __pyx_t_5numpy_float_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":725 - * - * ctypedef npy_double float_t - * ctypedef npy_double double_t # <<<<<<<<<<<<<< - * ctypedef npy_longdouble longdouble_t - * - */ -typedef npy_double __pyx_t_5numpy_double_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":726 - * ctypedef npy_double float_t - * ctypedef npy_double double_t - * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< - * - * ctypedef npy_cfloat cfloat_t - */ -typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* Declarations.proto */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - typedef ::std::complex< double > __pyx_t_double_complex; - #else - typedef double _Complex __pyx_t_double_complex; - #endif -#else - typedef struct { double real, imag; } __pyx_t_double_complex; -#endif -static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); - -/* Declarations.proto */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - typedef ::std::complex< float > __pyx_t_float_complex; - #else - typedef float _Complex __pyx_t_float_complex; - #endif -#else - typedef struct { float real, imag; } __pyx_t_float_complex; -#endif -static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); - - -/*--- Type declarations ---*/ -struct __pyx_array_obj; -struct __pyx_MemviewEnum_obj; -struct __pyx_memoryview_obj; -struct __pyx_memoryviewslice_obj; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":728 - * ctypedef npy_longdouble longdouble_t - * - * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< - * ctypedef npy_cdouble cdouble_t - * ctypedef npy_clongdouble clongdouble_t - */ -typedef npy_cfloat __pyx_t_5numpy_cfloat_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":729 - * - * ctypedef npy_cfloat cfloat_t - * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< - * ctypedef npy_clongdouble clongdouble_t - * - */ -typedef npy_cdouble __pyx_t_5numpy_cdouble_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":730 - * ctypedef npy_cfloat cfloat_t - * ctypedef npy_cdouble cdouble_t - * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< - * - * ctypedef npy_cdouble complex_t - */ -typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":732 - * ctypedef npy_clongdouble clongdouble_t - * - * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew1(a): - */ -typedef npy_cdouble __pyx_t_5numpy_complex_t; - -/* "View.MemoryView":106 - * - * @cname("__pyx_array") - * cdef class array: # <<<<<<<<<<<<<< - * - * cdef: - */ -struct __pyx_array_obj { - PyObject_HEAD - struct __pyx_vtabstruct_array *__pyx_vtab; - char *data; - Py_ssize_t len; - char *format; - int ndim; - Py_ssize_t *_shape; - Py_ssize_t *_strides; - Py_ssize_t itemsize; - PyObject *mode; - PyObject *_format; - void (*callback_free_data)(void *); - int free_data; - int dtype_is_object; -}; - - -/* "View.MemoryView":280 - * - * @cname('__pyx_MemviewEnum') - * cdef class Enum(object): # <<<<<<<<<<<<<< - * cdef object name - * def __init__(self, name): - */ -struct __pyx_MemviewEnum_obj { - PyObject_HEAD - PyObject *name; -}; - - -/* "View.MemoryView":331 - * - * @cname('__pyx_memoryview') - * cdef class memoryview(object): # <<<<<<<<<<<<<< - * - * cdef object obj - */ -struct __pyx_memoryview_obj { - PyObject_HEAD - struct __pyx_vtabstruct_memoryview *__pyx_vtab; - PyObject *obj; - PyObject *_size; - PyObject *_array_interface; - PyThread_type_lock lock; - __pyx_atomic_int acquisition_count[2]; - __pyx_atomic_int *acquisition_count_aligned_p; - Py_buffer view; - int flags; - int dtype_is_object; - __Pyx_TypeInfo *typeinfo; -}; - - -/* "View.MemoryView":967 - * - * @cname('__pyx_memoryviewslice') - * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< - * "Internal class for passing memoryview slices to Python" - * - */ -struct __pyx_memoryviewslice_obj { - struct __pyx_memoryview_obj __pyx_base; - __Pyx_memviewslice from_slice; - PyObject *from_object; - PyObject *(*to_object_func)(char *); - int (*to_dtype_func)(char *, PyObject *); -}; - - - -/* "View.MemoryView":106 - * - * @cname("__pyx_array") - * cdef class array: # <<<<<<<<<<<<<< - * - * cdef: - */ - -struct __pyx_vtabstruct_array { - PyObject *(*get_memview)(struct __pyx_array_obj *); -}; -static struct __pyx_vtabstruct_array *__pyx_vtabptr_array; - - -/* "View.MemoryView":331 - * - * @cname('__pyx_memoryview') - * cdef class memoryview(object): # <<<<<<<<<<<<<< - * - * cdef object obj - */ - -struct __pyx_vtabstruct_memoryview { - char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); - PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); - PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); - PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); - PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); -}; -static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; - - -/* "View.MemoryView":967 - * - * @cname('__pyx_memoryviewslice') - * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< - * "Internal class for passing memoryview slices to Python" - * - */ - -struct __pyx_vtabstruct__memoryviewslice { - struct __pyx_vtabstruct_memoryview __pyx_base; -}; -static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; - -/* --- Runtime support code (head) --- */ -/* Refnanny.proto */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/* PyObjectGetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -/* GetBuiltinName.proto */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -/* ArgTypeTest.proto */ -#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ - ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ - __Pyx__ArgTypeTest(obj, type, name, exact)) -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); - -/* PyDictVersioning.proto */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) -#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ - (version_var) = __PYX_GET_DICT_VERSION(dict);\ - (cache_var) = (value); -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ - (VAR) = __pyx_dict_cached_value;\ - } else {\ - (VAR) = __pyx_dict_cached_value = (LOOKUP);\ - __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ - }\ -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); -#else -#define __PYX_GET_DICT_VERSION(dict) (0) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); -#endif - -/* GetModuleGlobalName.proto */ -#if CYTHON_USE_DICT_VERSIONS -#define __Pyx_GetModuleGlobalName(var, name) do {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ - (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ - __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} while(0) -#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} while(0) -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); -#else -#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) -#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); -#endif - -/* PyFunctionFastCall.proto */ -#if CYTHON_FAST_PYCALL -#define __Pyx_PyFunction_FastCall(func, args, nargs)\ - __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#define __Pyx_BUILD_ASSERT_EXPR(cond)\ - (sizeof(char [1 - 2*!(cond)]) - 1) -#ifndef Py_MEMBER_SIZE -#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) -#endif -#if CYTHON_FAST_PYCALL - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" -#if PY_VERSION_HEX >= 0x030b00a6 - #ifndef Py_BUILD_CORE - #define Py_BUILD_CORE 1 - #endif - #include "internal/pycore_frame.h" -#endif - #define __Pxy_PyFrame_Initialize_Offsets()\ - ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ - (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) - #define __Pyx_PyFrame_GetLocalsplus(frame)\ - (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) -#endif // CYTHON_FAST_PYCALL -#endif - -/* PyCFunctionFastCall.proto */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); -#else -#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) -#endif - -/* PyObjectCall.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/* RaiseArgTupleInvalid.proto */ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallNoArg.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); -#else -#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* ExtTypeTest.proto */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); - -/* PyIntBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ - (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) -#endif - -/* GetItemInt.proto */ -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) -#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -/* ObjectGetItem.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); -#else -#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) -#endif - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/* IterFinish.proto */ -static CYTHON_INLINE int __Pyx_IterFinish(void); - -/* UnpackItemEndCheck.proto */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); - -/* BufferIndexError.proto */ -static void __Pyx_RaiseBufferIndexError(int axis); - -/* MemviewSliceInit.proto */ -#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d -#define __Pyx_MEMVIEW_DIRECT 1 -#define __Pyx_MEMVIEW_PTR 2 -#define __Pyx_MEMVIEW_FULL 4 -#define __Pyx_MEMVIEW_CONTIG 8 -#define __Pyx_MEMVIEW_STRIDED 16 -#define __Pyx_MEMVIEW_FOLLOW 32 -#define __Pyx_IS_C_CONTIG 1 -#define __Pyx_IS_F_CONTIG 2 -static int __Pyx_init_memviewslice( - struct __pyx_memoryview_obj *memview, - int ndim, - __Pyx_memviewslice *memviewslice, - int memview_is_new_reference); -static CYTHON_INLINE int __pyx_add_acquisition_count_locked( - __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); -static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( - __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); -#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) -#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) -#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) -#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) -static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); - -/* SetItemInt.proto */ -#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) :\ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) -static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, - int is_list, int wraparound, int boundscheck); - -/* GetTopmostException.proto */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); -#endif - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* SaveResetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -#else -#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) -#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) -#endif - -/* PyErrExceptionMatches.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) -static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); -#else -#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) -#endif - -/* GetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* IncludeStringH.proto */ -#include - -/* BytesEquals.proto */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); - -/* UnicodeEquals.proto */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); - -/* StrEquals.proto */ -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals -#else -#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals -#endif - -/* DivInt[Py_ssize_t].proto */ -static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); - -/* UnaryNegOverflows.proto */ -#define UNARY_NEG_WOULD_OVERFLOW(x)\ - (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) - -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/ -/* GetAttr.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); - -/* decode_c_string_utf16.proto */ -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = 0; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = -1; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = 1; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} - -/* decode_c_string.proto */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); - -/* GetAttr3.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); - -/* RaiseNoneIterError.proto */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); - -/* SwapException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* FastTypeChecks.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); -#else -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) -#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) -#endif -#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) - -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -/* ListCompAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len)) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) -#endif - -/* ListExtend.proto */ -static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject* none = _PyList_Extend((PyListObject*)L, v); - if (unlikely(!none)) - return -1; - Py_DECREF(none); - return 0; -#else - return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); -#endif -} - -/* ListAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) -#endif - -/* None.proto */ -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); - -/* DivInt[long].proto */ -static CYTHON_INLINE long __Pyx_div_long(long, long); - -/* PySequenceContains.proto */ -static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { - int result = PySequence_Contains(seq, item); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* HasAttr.proto */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); - -/* PyObject_GenericGetAttrNoDict.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr -#endif - -/* PyObject_GenericGetAttr.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr -#endif - -/* SetVTable.proto */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable); - -/* PyObjectGetAttrStrNoError.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); - -/* SetupReduce.proto */ -static int __Pyx_setup_reduce(PyObject* type_obj); - -/* TypeImport.proto */ -#ifndef __PYX_HAVE_RT_ImportType_proto_0_29_35 -#define __PYX_HAVE_RT_ImportType_proto_0_29_35 -#if __STDC_VERSION__ >= 201112L -#include -#endif -#if __STDC_VERSION__ >= 201112L || __cplusplus >= 201103L -#define __PYX_GET_STRUCT_ALIGNMENT_0_29_35(s) alignof(s) -#else -#define __PYX_GET_STRUCT_ALIGNMENT_0_29_35(s) sizeof(void*) -#endif -enum __Pyx_ImportType_CheckSize_0_29_35 { - __Pyx_ImportType_CheckSize_Error_0_29_35 = 0, - __Pyx_ImportType_CheckSize_Warn_0_29_35 = 1, - __Pyx_ImportType_CheckSize_Ignore_0_29_35 = 2 -}; -static PyTypeObject *__Pyx_ImportType_0_29_35(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_0_29_35 check_size); -#endif - -/* CLineInTraceback.proto */ -#ifdef CYTHON_CLINE_IN_TRACEBACK -#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) -#else -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); -#endif - -/* CodeObjectCache.proto */ -typedef struct { - PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/* AddTraceback.proto */ -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -/* RealImag.proto */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - #define __Pyx_CREAL(z) ((z).real()) - #define __Pyx_CIMAG(z) ((z).imag()) - #else - #define __Pyx_CREAL(z) (__real__(z)) - #define __Pyx_CIMAG(z) (__imag__(z)) - #endif -#else - #define __Pyx_CREAL(z) ((z).real) - #define __Pyx_CIMAG(z) ((z).imag) -#endif -#if defined(__cplusplus) && CYTHON_CCOMPLEX\ - && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) - #define __Pyx_SET_CREAL(z,x) ((z).real(x)) - #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) -#else - #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) - #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) -#endif - -/* Arithmetic.proto */ -#if CYTHON_CCOMPLEX - #define __Pyx_c_eq_double(a, b) ((a)==(b)) - #define __Pyx_c_sum_double(a, b) ((a)+(b)) - #define __Pyx_c_diff_double(a, b) ((a)-(b)) - #define __Pyx_c_prod_double(a, b) ((a)*(b)) - #define __Pyx_c_quot_double(a, b) ((a)/(b)) - #define __Pyx_c_neg_double(a) (-(a)) - #ifdef __cplusplus - #define __Pyx_c_is_zero_double(z) ((z)==(double)0) - #define __Pyx_c_conj_double(z) (::std::conj(z)) - #if 1 - #define __Pyx_c_abs_double(z) (::std::abs(z)) - #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) - #endif - #else - #define __Pyx_c_is_zero_double(z) ((z)==0) - #define __Pyx_c_conj_double(z) (conj(z)) - #if 1 - #define __Pyx_c_abs_double(z) (cabs(z)) - #define __Pyx_c_pow_double(a, b) (cpow(a, b)) - #endif - #endif -#else - static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); - static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); - #if 1 - static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); - #endif -#endif - -#if PY_MAJOR_VERSION < 3 - static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); - static void __Pyx_ReleaseBuffer(Py_buffer *view); -#else - #define __Pyx_GetBuffer PyObject_GetBuffer - #define __Pyx_ReleaseBuffer PyBuffer_Release -#endif - - -/* BufferStructDeclare.proto */ -typedef struct { - Py_ssize_t shape, strides, suboffsets; -} __Pyx_Buf_DimInfo; -typedef struct { - size_t refcount; - Py_buffer pybuffer; -} __Pyx_Buffer; -typedef struct { - __Pyx_Buffer *rcbuffer; - char *data; - __Pyx_Buf_DimInfo diminfo[8]; -} __Pyx_LocalBuf_ND; - -/* MemviewSliceIsContig.proto */ -static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim); - -/* OverlappingSlices.proto */ -static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, - __Pyx_memviewslice *slice2, - int ndim, size_t itemsize); - -/* Capsule.proto */ -static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); - -/* IsLittleEndian.proto */ -static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); - -/* BufferFormatCheck.proto */ -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type); - -/* TypeInfoCompare.proto */ -static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); - -/* MemviewSliceValidateAndInit.proto */ -static int __Pyx_ValidateAndInit_memviewslice( - int *axes_specs, - int c_or_f_flag, - int buf_flags, - int ndim, - __Pyx_TypeInfo *dtype, - __Pyx_BufFmt_StackElem stack[], - __Pyx_memviewslice *memviewslice, - PyObject *original_obj); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(PyObject *, int writable_flag); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_long(PyObject *, int writable_flag); - -/* GCCDiagnostics.proto */ -#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -#define __Pyx_HAS_GCC_DIAGNOSTIC -#endif - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *, int writable_flag); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsdsds___pyx_t_double_complex(PyObject *, int writable_flag); - -/* ToPy.proto */ -#define __pyx_PyComplex_FromComplex(z)\ - PyComplex_FromDoubles((double)__Pyx_CREAL(z),\ - (double)__Pyx_CIMAG(z)) - -/* MemviewDtypeToObject.proto */ -static CYTHON_INLINE PyObject *__pyx_memview_get_long(const char *itemp); -static CYTHON_INLINE int __pyx_memview_set_long(const char *itemp, PyObject *obj); - -/* FromPy.proto */ -static __pyx_t_double_complex __Pyx_PyComplex_As___pyx_t_double_complex(PyObject*); - -/* MemviewDtypeToObject.proto */ -static CYTHON_INLINE PyObject *__pyx_memview_get___pyx_t_double_complex(const char *itemp); -static CYTHON_INLINE int __pyx_memview_set___pyx_t_double_complex(const char *itemp, PyObject *obj); - -/* Arithmetic.proto */ -#if CYTHON_CCOMPLEX - #define __Pyx_c_eq_float(a, b) ((a)==(b)) - #define __Pyx_c_sum_float(a, b) ((a)+(b)) - #define __Pyx_c_diff_float(a, b) ((a)-(b)) - #define __Pyx_c_prod_float(a, b) ((a)*(b)) - #define __Pyx_c_quot_float(a, b) ((a)/(b)) - #define __Pyx_c_neg_float(a) (-(a)) - #ifdef __cplusplus - #define __Pyx_c_is_zero_float(z) ((z)==(float)0) - #define __Pyx_c_conj_float(z) (::std::conj(z)) - #if 1 - #define __Pyx_c_abs_float(z) (::std::abs(z)) - #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) - #endif - #else - #define __Pyx_c_is_zero_float(z) ((z)==0) - #define __Pyx_c_conj_float(z) (conjf(z)) - #if 1 - #define __Pyx_c_abs_float(z) (cabsf(z)) - #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) - #endif - #endif -#else - static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); - static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); - #if 1 - static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); - #endif -#endif - -/* MemviewSliceCopyTemplate.proto */ -static __Pyx_memviewslice -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object); - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* CIntFromPy.proto */ -static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/ -static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ -static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ -static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ -static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ -static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ -static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ -static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ - -/* Module declarations from 'cpython.buffer' */ - -/* Module declarations from 'libc.string' */ - -/* Module declarations from 'libc.stdio' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.type' */ -static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; - -/* Module declarations from 'cpython' */ - -/* Module declarations from 'cpython.object' */ - -/* Module declarations from 'cpython.ref' */ - -/* Module declarations from 'cpython.mem' */ - -/* Module declarations from 'numpy' */ - -/* Module declarations from 'numpy' */ -static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; -static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; -static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; -static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; -static PyTypeObject *__pyx_ptype_5numpy_generic = 0; -static PyTypeObject *__pyx_ptype_5numpy_number = 0; -static PyTypeObject *__pyx_ptype_5numpy_integer = 0; -static PyTypeObject *__pyx_ptype_5numpy_signedinteger = 0; -static PyTypeObject *__pyx_ptype_5numpy_unsignedinteger = 0; -static PyTypeObject *__pyx_ptype_5numpy_inexact = 0; -static PyTypeObject *__pyx_ptype_5numpy_floating = 0; -static PyTypeObject *__pyx_ptype_5numpy_complexfloating = 0; -static PyTypeObject *__pyx_ptype_5numpy_flexible = 0; -static PyTypeObject *__pyx_ptype_5numpy_character = 0; -static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; - -/* Module declarations from 'ueg_kernels' */ -static PyTypeObject *__pyx_array_type = 0; -static PyTypeObject *__pyx_MemviewEnum_type = 0; -static PyTypeObject *__pyx_memoryview_type = 0; -static PyTypeObject *__pyx_memoryviewslice_type = 0; -static PyObject *generic = 0; -static PyObject *strided = 0; -static PyObject *indirect = 0; -static PyObject *contiguous = 0; -static PyObject *indirect_contiguous = 0; -static int __pyx_memoryview_thread_locks_used; -static PyThread_type_lock __pyx_memoryview_thread_locks[8]; -static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ -static void *__pyx_align_pointer(void *, size_t); /*proto*/ -static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ -static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ -static PyObject *_unellipsify(PyObject *, int); /*proto*/ -static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ -static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ -static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ -static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ -static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ -static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ -static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ -static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ -static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ -static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ -static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ -static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ -static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ -static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ -static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ -static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ -static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ -static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ -static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ -static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ -static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ -static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ -static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ -static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ -static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ -static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo___pyx_t_double_complex = { "double complex", NULL, sizeof(__pyx_t_double_complex), { 0 }, 0, 'C', 0, 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_long = { "long", NULL, sizeof(long), { 0 }, 0, IS_UNSIGNED(long) ? 'U' : 'I', IS_UNSIGNED(long), 0 }; -static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; -#define __Pyx_MODULE_NAME "ueg_kernels" -extern int __pyx_module_is_main_ueg_kernels; -int __pyx_module_is_main_ueg_kernels = 0; - -/* Implementation of 'ueg_kernels' */ -static PyObject *__pyx_builtin_enumerate; -static PyObject *__pyx_builtin_zip; -static PyObject *__pyx_builtin_range; -static PyObject *__pyx_builtin_ImportError; -static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_MemoryError; -static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_Ellipsis; -static PyObject *__pyx_builtin_id; -static PyObject *__pyx_builtin_IndexError; -static const char __pyx_k_G[] = "G"; -static const char __pyx_k_J[] = "J"; -static const char __pyx_k_K[] = "K"; -static const char __pyx_k_O[] = "O"; -static const char __pyx_k_T[] = "T"; -static const char __pyx_k_c[] = "c"; -static const char __pyx_k_i[] = "i"; -static const char __pyx_k_j[] = "j"; -static const char __pyx_k_q[] = "q"; -static const char __pyx_k_s[] = "s"; -static const char __pyx_k_id[] = "id"; -static const char __pyx_k_iq[] = "iq"; -static const char __pyx_k_ki[] = "ki"; -static const char __pyx_k_kj[] = "kj"; -static const char __pyx_k_nq[] = "nq"; -static const char __pyx_k_pi[] = "pi"; -static const char __pyx_k_q2[] = "q2"; -static const char __pyx_k_vq[] = "vq"; -static const char __pyx_k_dot[] = "dot"; -static const char __pyx_k_fac[] = "fac"; -static const char __pyx_k_kpq[] = "kpq"; -static const char __pyx_k_new[] = "__new__"; -static const char __pyx_k_obj[] = "obj"; -static const char __pyx_k_pmq[] = "pmq"; -static const char __pyx_k_vol[] = "vol"; -static const char __pyx_k_zip[] = "zip"; -static const char __pyx_k_Gh_i[] = "Gh_i"; -static const char __pyx_k_Gh_j[] = "Gh_j"; -static const char __pyx_k_Gkpq[] = "Gkpq"; -static const char __pyx_k_Gpmq[] = "Gpmq"; -static const char __pyx_k_base[] = "base"; -static const char __pyx_k_copy[] = "copy"; -static const char __pyx_k_dict[] = "__dict__"; -static const char __pyx_k_flip[] = "flip"; -static const char __pyx_k_gmap[] = "gmap"; -static const char __pyx_k_idxj[] = "idxj"; -static const char __pyx_k_idxk[] = "idxk"; -static const char __pyx_k_idxp[] = "idxp"; -static const char __pyx_k_kfac[] = "kfac"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_math[] = "math"; -static const char __pyx_k_mesh[] = "mesh"; -static const char __pyx_k_mode[] = "mode"; -static const char __pyx_k_name[] = "name"; -static const char __pyx_k_nbsf[] = "nbsf"; -static const char __pyx_k_ndim[] = "ndim"; -static const char __pyx_k_nkpq[] = "nkpq"; -static const char __pyx_k_nocc[] = "nocc"; -static const char __pyx_k_npmq[] = "npmq"; -static const char __pyx_k_pack[] = "pack"; -static const char __pyx_k_prod[] = "prod"; -static const char __pyx_k_qmap[] = "qmap"; -static const char __pyx_k_size[] = "size"; -static const char __pyx_k_step[] = "step"; -static const char __pyx_k_stop[] = "stop"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_ASCII[] = "ASCII"; -static const char __pyx_k_DTYPE[] = "DTYPE"; -static const char __pyx_k_Ghalf[] = "Ghalf"; -static const char __pyx_k_Gprod[] = "Gprod"; -static const char __pyx_k_basis[] = "basis"; -static const char __pyx_k_class[] = "__class__"; -static const char __pyx_k_dtype[] = "dtype"; -static const char __pyx_k_error[] = "error"; -static const char __pyx_k_flags[] = "flags"; -static const char __pyx_k_inkpq[] = "inkpq"; -static const char __pyx_k_jnpmq[] = "jnpmq"; -static const char __pyx_k_kpq_i[] = "kpq_i"; -static const char __pyx_k_lQ_ij[] = "lQ_ij"; -static const char __pyx_k_lQ_ji[] = "lQ_ji"; -static const char __pyx_k_ngrid[] = "ngrid"; -static const char __pyx_k_numpy[] = "numpy"; -static const char __pyx_k_pmq_i[] = "pmq_i"; -static const char __pyx_k_qmesh[] = "qmesh"; -static const char __pyx_k_range[] = "range"; -static const char __pyx_k_shape[] = "shape"; -static const char __pyx_k_start[] = "start"; -static const char __pyx_k_vqvec[] = "vqvec"; -static const char __pyx_k_zeros[] = "zeros"; -static const char __pyx_k_encode[] = "encode"; -static const char __pyx_k_format[] = "format"; -static const char __pyx_k_idxjmq[] = "idxjmq"; -static const char __pyx_k_idxjpq[] = "idxjpq"; -static const char __pyx_k_idxkpq[] = "idxkpq"; -static const char __pyx_k_idxpmq[] = "idxpmq"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_name_2[] = "__name__"; -static const char __pyx_k_nqgrid[] = "nqgrid"; -static const char __pyx_k_pickle[] = "pickle"; -static const char __pyx_k_reduce[] = "__reduce__"; -static const char __pyx_k_struct[] = "struct"; -static const char __pyx_k_unpack[] = "unpack"; -static const char __pyx_k_update[] = "update"; -static const char __pyx_k_asarray[] = "asarray"; -static const char __pyx_k_float64[] = "float64"; -static const char __pyx_k_fortran[] = "fortran"; -static const char __pyx_k_h1e_mod[] = "h1e_mod"; -static const char __pyx_k_memview[] = "memview"; -static const char __pyx_k_CTdagger[] = "CTdagger"; -static const char __pyx_k_DTYPE_CX[] = "DTYPE_CX"; -static const char __pyx_k_Ellipsis[] = "Ellipsis"; -static const char __pyx_k_convolve[] = "convolve"; -static const char __pyx_k_getstate[] = "__getstate__"; -static const char __pyx_k_itemsize[] = "itemsize"; -static const char __pyx_k_pyx_type[] = "__pyx_type"; -static const char __pyx_k_setstate[] = "__setstate__"; -static const char __pyx_k_Gh_i_cube[] = "Gh_i_cube"; -static const char __pyx_k_Gh_j_cube[] = "Gh_j_cube"; -static const char __pyx_k_TypeError[] = "TypeError"; -static const char __pyx_k_enumerate[] = "enumerate"; -static const char __pyx_k_itertools[] = "itertools"; -static const char __pyx_k_pyx_state[] = "__pyx_state"; -static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; -static const char __pyx_k_CTdagger_i[] = "CTdagger_i"; -static const char __pyx_k_CTdagger_j[] = "CTdagger_j"; -static const char __pyx_k_IndexError[] = "IndexError"; -static const char __pyx_k_ValueError[] = "ValueError"; -static const char __pyx_k_complex128[] = "complex128"; -static const char __pyx_k_pyx_result[] = "__pyx_result"; -static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; -static const char __pyx_k_ImportError[] = "ImportError"; -static const char __pyx_k_MemoryError[] = "MemoryError"; -static const char __pyx_k_PickleError[] = "PickleError"; -static const char __pyx_k_build_J_opt[] = "build_J_opt"; -static const char __pyx_k_build_K_opt[] = "build_K_opt"; -static const char __pyx_k_ueg_kernels[] = "ueg_kernels"; -static const char __pyx_k_mod_one_body[] = "mod_one_body"; -static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; -static const char __pyx_k_stringsource[] = "stringsource"; -static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; -static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; -static const char __pyx_k_CTdagger_i_cube[] = "CTdagger_i_cube"; -static const char __pyx_k_CTdagger_j_cube[] = "CTdagger_j_cube"; -static const char __pyx_k_View_MemoryView[] = "View.MemoryView"; -static const char __pyx_k_allocate_buffer[] = "allocate_buffer"; -static const char __pyx_k_dtype_is_object[] = "dtype_is_object"; -static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; -static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; -static const char __pyx_k_ueg_kernels_pyx[] = "ueg_kernels.pyx"; -static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_strided_and_direct[] = ""; -static const char __pyx_k_strided_and_indirect[] = ""; -static const char __pyx_k_contiguous_and_direct[] = ""; -static const char __pyx_k_MemoryView_of_r_object[] = ""; -static const char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; -static const char __pyx_k_contiguous_and_indirect[] = ""; -static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; -static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; -static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; -static const char __pyx_k_exchange_greens_function_fft[] = "exchange_greens_function_fft"; -static const char __pyx_k_ipie_legacy_estimators_utils[] = "ipie.legacy.estimators.utils"; -static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; -static const char __pyx_k_strided_and_direct_or_indirect[] = ""; -static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; -static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; -static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; -static const char __pyx_k_Cannot_assign_to_read_only_memor[] = "Cannot assign to read-only memoryview"; -static const char __pyx_k_Cannot_create_writable_memory_vi[] = "Cannot create writable memory view from read-only memoryview"; -static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; -static const char __pyx_k_Incompatible_checksums_0x_x_vs_0[] = "Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))"; -static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; -static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; -static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; -static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; -static const char __pyx_k_coulomb_greens_function_per_qvec[] = "coulomb_greens_function_per_qvec"; -static const char __pyx_k_exchange_greens_function_per_qve[] = "exchange_greens_function_per_qvec"; -static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; -static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; -static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; -static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; -static PyObject *__pyx_n_s_ASCII; -static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; -static PyObject *__pyx_n_s_CTdagger; -static PyObject *__pyx_n_s_CTdagger_i; -static PyObject *__pyx_n_s_CTdagger_i_cube; -static PyObject *__pyx_n_s_CTdagger_j; -static PyObject *__pyx_n_s_CTdagger_j_cube; -static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; -static PyObject *__pyx_kp_s_Cannot_assign_to_read_only_memor; -static PyObject *__pyx_kp_s_Cannot_create_writable_memory_vi; -static PyObject *__pyx_kp_s_Cannot_index_with_type_s; -static PyObject *__pyx_n_s_DTYPE; -static PyObject *__pyx_n_s_DTYPE_CX; -static PyObject *__pyx_n_s_Ellipsis; -static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; -static PyObject *__pyx_n_s_G; -static PyObject *__pyx_n_s_Gh_i; -static PyObject *__pyx_n_s_Gh_i_cube; -static PyObject *__pyx_n_s_Gh_j; -static PyObject *__pyx_n_s_Gh_j_cube; -static PyObject *__pyx_n_s_Ghalf; -static PyObject *__pyx_n_s_Gkpq; -static PyObject *__pyx_n_s_Gpmq; -static PyObject *__pyx_n_s_Gprod; -static PyObject *__pyx_n_s_ImportError; -static PyObject *__pyx_kp_s_Incompatible_checksums_0x_x_vs_0; -static PyObject *__pyx_n_s_IndexError; -static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; -static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; -static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; -static PyObject *__pyx_n_s_J; -static PyObject *__pyx_n_s_K; -static PyObject *__pyx_n_s_MemoryError; -static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; -static PyObject *__pyx_kp_s_MemoryView_of_r_object; -static PyObject *__pyx_n_b_O; -static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; -static PyObject *__pyx_n_s_PickleError; -static PyObject *__pyx_n_s_T; -static PyObject *__pyx_n_s_TypeError; -static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; -static PyObject *__pyx_n_s_ValueError; -static PyObject *__pyx_n_s_View_MemoryView; -static PyObject *__pyx_n_s_allocate_buffer; -static PyObject *__pyx_n_s_asarray; -static PyObject *__pyx_n_s_base; -static PyObject *__pyx_n_s_basis; -static PyObject *__pyx_n_s_build_J_opt; -static PyObject *__pyx_n_s_build_K_opt; -static PyObject *__pyx_n_s_c; -static PyObject *__pyx_n_u_c; -static PyObject *__pyx_n_s_class; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_n_s_complex128; -static PyObject *__pyx_kp_s_contiguous_and_direct; -static PyObject *__pyx_kp_s_contiguous_and_indirect; -static PyObject *__pyx_n_s_convolve; -static PyObject *__pyx_n_s_copy; -static PyObject *__pyx_n_s_coulomb_greens_function_per_qvec; -static PyObject *__pyx_n_s_dict; -static PyObject *__pyx_n_s_dot; -static PyObject *__pyx_n_s_dtype; -static PyObject *__pyx_n_s_dtype_is_object; -static PyObject *__pyx_n_s_encode; -static PyObject *__pyx_n_s_enumerate; -static PyObject *__pyx_n_s_error; -static PyObject *__pyx_n_s_exchange_greens_function_fft; -static PyObject *__pyx_n_s_exchange_greens_function_per_qve; -static PyObject *__pyx_n_s_fac; -static PyObject *__pyx_n_s_flags; -static PyObject *__pyx_n_s_flip; -static PyObject *__pyx_n_s_float64; -static PyObject *__pyx_n_s_format; -static PyObject *__pyx_n_s_fortran; -static PyObject *__pyx_n_u_fortran; -static PyObject *__pyx_n_s_getstate; -static PyObject *__pyx_n_s_gmap; -static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; -static PyObject *__pyx_n_s_h1e_mod; -static PyObject *__pyx_n_s_i; -static PyObject *__pyx_n_s_id; -static PyObject *__pyx_n_s_idxj; -static PyObject *__pyx_n_s_idxjmq; -static PyObject *__pyx_n_s_idxjpq; -static PyObject *__pyx_n_s_idxk; -static PyObject *__pyx_n_s_idxkpq; -static PyObject *__pyx_n_s_idxp; -static PyObject *__pyx_n_s_idxpmq; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_inkpq; -static PyObject *__pyx_n_s_ipie_legacy_estimators_utils; -static PyObject *__pyx_n_s_iq; -static PyObject *__pyx_n_s_itemsize; -static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; -static PyObject *__pyx_n_s_itertools; -static PyObject *__pyx_n_s_j; -static PyObject *__pyx_n_s_jnpmq; -static PyObject *__pyx_n_s_kfac; -static PyObject *__pyx_n_s_ki; -static PyObject *__pyx_n_s_kj; -static PyObject *__pyx_n_s_kpq; -static PyObject *__pyx_n_s_kpq_i; -static PyObject *__pyx_n_s_lQ_ij; -static PyObject *__pyx_n_s_lQ_ji; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_math; -static PyObject *__pyx_n_s_memview; -static PyObject *__pyx_n_s_mesh; -static PyObject *__pyx_n_s_mod_one_body; -static PyObject *__pyx_n_s_mode; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_name_2; -static PyObject *__pyx_n_s_nbsf; -static PyObject *__pyx_n_s_ndim; -static PyObject *__pyx_n_s_new; -static PyObject *__pyx_n_s_ngrid; -static PyObject *__pyx_n_s_nkpq; -static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; -static PyObject *__pyx_n_s_nocc; -static PyObject *__pyx_n_s_npmq; -static PyObject *__pyx_n_s_nq; -static PyObject *__pyx_n_s_nqgrid; -static PyObject *__pyx_n_s_numpy; -static PyObject *__pyx_kp_u_numpy_core_multiarray_failed_to; -static PyObject *__pyx_kp_u_numpy_core_umath_failed_to_impor; -static PyObject *__pyx_n_s_obj; -static PyObject *__pyx_n_s_pack; -static PyObject *__pyx_n_s_pi; -static PyObject *__pyx_n_s_pickle; -static PyObject *__pyx_n_s_pmq; -static PyObject *__pyx_n_s_pmq_i; -static PyObject *__pyx_n_s_prod; -static PyObject *__pyx_n_s_pyx_PickleError; -static PyObject *__pyx_n_s_pyx_checksum; -static PyObject *__pyx_n_s_pyx_getbuffer; -static PyObject *__pyx_n_s_pyx_result; -static PyObject *__pyx_n_s_pyx_state; -static PyObject *__pyx_n_s_pyx_type; -static PyObject *__pyx_n_s_pyx_unpickle_Enum; -static PyObject *__pyx_n_s_pyx_vtable; -static PyObject *__pyx_n_s_q; -static PyObject *__pyx_n_s_q2; -static PyObject *__pyx_n_s_qmap; -static PyObject *__pyx_n_s_qmesh; -static PyObject *__pyx_n_s_range; -static PyObject *__pyx_n_s_reduce; -static PyObject *__pyx_n_s_reduce_cython; -static PyObject *__pyx_n_s_reduce_ex; -static PyObject *__pyx_n_s_s; -static PyObject *__pyx_n_s_setstate; -static PyObject *__pyx_n_s_setstate_cython; -static PyObject *__pyx_n_s_shape; -static PyObject *__pyx_n_s_size; -static PyObject *__pyx_n_s_start; -static PyObject *__pyx_n_s_step; -static PyObject *__pyx_n_s_stop; -static PyObject *__pyx_kp_s_strided_and_direct; -static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; -static PyObject *__pyx_kp_s_strided_and_indirect; -static PyObject *__pyx_kp_s_stringsource; -static PyObject *__pyx_n_s_struct; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_n_s_ueg_kernels; -static PyObject *__pyx_kp_s_ueg_kernels_pyx; -static PyObject *__pyx_kp_s_unable_to_allocate_array_data; -static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; -static PyObject *__pyx_n_s_unpack; -static PyObject *__pyx_n_s_update; -static PyObject *__pyx_n_s_vol; -static PyObject *__pyx_n_s_vq; -static PyObject *__pyx_n_s_vqvec; -static PyObject *__pyx_n_s_zeros; -static PyObject *__pyx_n_s_zip; -static PyObject *__pyx_pf_11ueg_kernels_vq(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_q); /* proto */ -static PyObject *__pyx_pf_11ueg_kernels_2mod_one_body(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T, PyArrayObject *__pyx_v_basis, double __pyx_v_vol, double __pyx_v_kfac); /* proto */ -static PyObject *__pyx_pf_11ueg_kernels_4coulomb_greens_function_per_qvec(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_kpq_i, PyArrayObject *__pyx_v_kpq, PyArrayObject *__pyx_v_pmq_i, PyArrayObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_G); /* proto */ -static PyObject *__pyx_pf_11ueg_kernels_6exchange_greens_function_per_qvec(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_kpq_i, __Pyx_memviewslice __pyx_v_kpq, __Pyx_memviewslice __pyx_v_pmq_i, __Pyx_memviewslice __pyx_v_pmq, __Pyx_memviewslice __pyx_v_G); /* proto */ -static PyObject *__pyx_pf_11ueg_kernels_8exchange_greens_function_fft(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nocc, long __pyx_v_nbsf, __Pyx_memviewslice __pyx_v_mesh, __Pyx_memviewslice __pyx_v_qmesh, __Pyx_memviewslice __pyx_v_gmap, __Pyx_memviewslice __pyx_v_qmap, __Pyx_memviewslice __pyx_v_CTdagger, __Pyx_memviewslice __pyx_v_Ghalf); /* proto */ -static PyObject *__pyx_pf_11ueg_kernels_10build_J_opt(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nq, __Pyx_memviewslice __pyx_v_vqvec, double __pyx_v_vol, long __pyx_v_nbsf, PyObject *__pyx_v_kpq_i, PyObject *__pyx_v_kpq, PyObject *__pyx_v_pmq_i, PyObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_Gkpq, __Pyx_memviewslice __pyx_v_Gpmq); /* proto */ -static PyObject *__pyx_pf_11ueg_kernels_12build_K_opt(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nq, __Pyx_memviewslice __pyx_v_vqvec, double __pyx_v_vol, long __pyx_v_nbsf, PyObject *__pyx_v_kpq_i, PyObject *__pyx_v_kpq, PyObject *__pyx_v_pmq_i, PyObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_G); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ -static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ -static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ -static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ -static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_float_0_0; -static PyObject *__pyx_int_0; -static PyObject *__pyx_int_1; -static PyObject *__pyx_int_2; -static PyObject *__pyx_int_4; -static PyObject *__pyx_int_112105877; -static PyObject *__pyx_int_136983863; -static PyObject *__pyx_int_184977713; -static PyObject *__pyx_int_neg_1; -static PyObject *__pyx_tuple_; -static PyObject *__pyx_tuple__2; -static PyObject *__pyx_tuple__3; -static PyObject *__pyx_tuple__4; -static PyObject *__pyx_tuple__5; -static PyObject *__pyx_tuple__6; -static PyObject *__pyx_tuple__7; -static PyObject *__pyx_tuple__8; -static PyObject *__pyx_tuple__9; -static PyObject *__pyx_slice__17; -static PyObject *__pyx_tuple__10; -static PyObject *__pyx_tuple__11; -static PyObject *__pyx_tuple__12; -static PyObject *__pyx_tuple__13; -static PyObject *__pyx_tuple__14; -static PyObject *__pyx_tuple__15; -static PyObject *__pyx_tuple__16; -static PyObject *__pyx_tuple__18; -static PyObject *__pyx_tuple__19; -static PyObject *__pyx_tuple__20; -static PyObject *__pyx_tuple__21; -static PyObject *__pyx_tuple__22; -static PyObject *__pyx_tuple__24; -static PyObject *__pyx_tuple__26; -static PyObject *__pyx_tuple__28; -static PyObject *__pyx_tuple__30; -static PyObject *__pyx_tuple__32; -static PyObject *__pyx_tuple__34; -static PyObject *__pyx_tuple__36; -static PyObject *__pyx_tuple__37; -static PyObject *__pyx_tuple__38; -static PyObject *__pyx_tuple__39; -static PyObject *__pyx_tuple__40; -static PyObject *__pyx_tuple__41; -static PyObject *__pyx_codeobj__23; -static PyObject *__pyx_codeobj__25; -static PyObject *__pyx_codeobj__27; -static PyObject *__pyx_codeobj__29; -static PyObject *__pyx_codeobj__31; -static PyObject *__pyx_codeobj__33; -static PyObject *__pyx_codeobj__35; -static PyObject *__pyx_codeobj__42; -/* Late includes */ - -/* "ueg_kernels.pyx":14 - * - * - * def vq(numpy.ndarray q): # <<<<<<<<<<<<<< - * assert(q.shape[0] == 3) - * cdef double q2 = numpy.dot(q, q) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_11ueg_kernels_1vq(PyObject *__pyx_self, PyObject *__pyx_v_q); /*proto*/ -static PyMethodDef __pyx_mdef_11ueg_kernels_1vq = {"vq", (PyCFunction)__pyx_pw_11ueg_kernels_1vq, METH_O, 0}; -static PyObject *__pyx_pw_11ueg_kernels_1vq(PyObject *__pyx_self, PyObject *__pyx_v_q) { - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("vq (wrapper)", 0); - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_q), __pyx_ptype_5numpy_ndarray, 1, "q", 0))) __PYX_ERR(0, 14, __pyx_L1_error) - __pyx_r = __pyx_pf_11ueg_kernels_vq(__pyx_self, ((PyArrayObject *)__pyx_v_q)); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_11ueg_kernels_vq(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_q) { - double __pyx_v_q2; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - double __pyx_t_6; - int __pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("vq", 0); - - /* "ueg_kernels.pyx":15 - * - * def vq(numpy.ndarray q): - * assert(q.shape[0] == 3) # <<<<<<<<<<<<<< - * cdef double q2 = numpy.dot(q, q) - * if (q2 < 1e-10): - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!(((__pyx_v_q->dimensions[0]) == 3) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(0, 15, __pyx_L1_error) - } - } - #endif - - /* "ueg_kernels.pyx":16 - * def vq(numpy.ndarray q): - * assert(q.shape[0] == 3) - * cdef double q2 = numpy.dot(q, q) # <<<<<<<<<<<<<< - * if (q2 < 1e-10): - * return 0.0 - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 16, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_dot); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 16, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - __pyx_t_4 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_4 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, ((PyObject *)__pyx_v_q), ((PyObject *)__pyx_v_q)}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_4, 2+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_2, ((PyObject *)__pyx_v_q), ((PyObject *)__pyx_v_q)}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_4, 2+__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(2+__pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 16, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (__pyx_t_2) { - __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __pyx_t_2 = NULL; - } - __Pyx_INCREF(((PyObject *)__pyx_v_q)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_q)); - PyTuple_SET_ITEM(__pyx_t_5, 0+__pyx_t_4, ((PyObject *)__pyx_v_q)); - __Pyx_INCREF(((PyObject *)__pyx_v_q)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_q)); - PyTuple_SET_ITEM(__pyx_t_5, 1+__pyx_t_4, ((PyObject *)__pyx_v_q)); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_q2 = __pyx_t_6; - - /* "ueg_kernels.pyx":17 - * assert(q.shape[0] == 3) - * cdef double q2 = numpy.dot(q, q) - * if (q2 < 1e-10): # <<<<<<<<<<<<<< - * return 0.0 - * else: - */ - __pyx_t_7 = ((__pyx_v_q2 < 1e-10) != 0); - if (__pyx_t_7) { - - /* "ueg_kernels.pyx":18 - * cdef double q2 = numpy.dot(q, q) - * if (q2 < 1e-10): - * return 0.0 # <<<<<<<<<<<<<< - * else: - * return 4*math.pi / q2 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_float_0_0); - __pyx_r = __pyx_float_0_0; - goto __pyx_L0; - - /* "ueg_kernels.pyx":17 - * assert(q.shape[0] == 3) - * cdef double q2 = numpy.dot(q, q) - * if (q2 < 1e-10): # <<<<<<<<<<<<<< - * return 0.0 - * else: - */ - } - - /* "ueg_kernels.pyx":20 - * return 0.0 - * else: - * return 4*math.pi / q2 # <<<<<<<<<<<<<< - * - * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_math); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_pi); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_int_4, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_q2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - } - - /* "ueg_kernels.pyx":14 - * - * - * def vq(numpy.ndarray q): # <<<<<<<<<<<<<< - * assert(q.shape[0] == 3) - * cdef double q2 = numpy.dot(q, q) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("ueg_kernels.vq", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "ueg_kernels.pyx":22 - * return 4*math.pi / q2 - * - * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): # <<<<<<<<<<<<<< - * """ Add a diagonal term of two-body Hamiltonian to the one-body term - * Parameters - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_11ueg_kernels_3mod_one_body(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_11ueg_kernels_2mod_one_body[] = " Add a diagonal term of two-body Hamiltonian to the one-body term\n Parameters\n ----------\n T : float\n one-body Hamiltonian (i.e. kinetic energy)\n Returns\n -------\n h1e_mod: float\n modified one-body Hamiltonian\n "; -static PyMethodDef __pyx_mdef_11ueg_kernels_3mod_one_body = {"mod_one_body", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_3mod_one_body, METH_VARARGS|METH_KEYWORDS, __pyx_doc_11ueg_kernels_2mod_one_body}; -static PyObject *__pyx_pw_11ueg_kernels_3mod_one_body(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_T = 0; - PyArrayObject *__pyx_v_basis = 0; - double __pyx_v_vol; - double __pyx_v_kfac; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("mod_one_body (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_T,&__pyx_n_s_basis,&__pyx_n_s_vol,&__pyx_n_s_kfac,0}; - PyObject* values[4] = {0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_T)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_basis)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("mod_one_body", 1, 4, 4, 1); __PYX_ERR(0, 22, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vol)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("mod_one_body", 1, 4, 4, 2); __PYX_ERR(0, 22, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kfac)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("mod_one_body", 1, 4, 4, 3); __PYX_ERR(0, 22, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "mod_one_body") < 0)) __PYX_ERR(0, 22, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - } - __pyx_v_T = ((PyArrayObject *)values[0]); - __pyx_v_basis = ((PyArrayObject *)values[1]); - __pyx_v_vol = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_vol == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 22, __pyx_L3_error) - __pyx_v_kfac = __pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_kfac == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 22, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("mod_one_body", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 22, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("ueg_kernels.mod_one_body", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_T), __pyx_ptype_5numpy_ndarray, 1, "T", 0))) __PYX_ERR(0, 22, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_basis), __pyx_ptype_5numpy_ndarray, 1, "basis", 0))) __PYX_ERR(0, 22, __pyx_L1_error) - __pyx_r = __pyx_pf_11ueg_kernels_2mod_one_body(__pyx_self, __pyx_v_T, __pyx_v_basis, __pyx_v_vol, __pyx_v_kfac); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_11ueg_kernels_2mod_one_body(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_T, PyArrayObject *__pyx_v_basis, double __pyx_v_vol, double __pyx_v_kfac) { - CYTHON_UNUSED size_t __pyx_v_nbsf; - PyArrayObject *__pyx_v_h1e_mod = 0; - double __pyx_v_fac; - PyObject *__pyx_v_i = NULL; - PyObject *__pyx_v_ki = NULL; - PyObject *__pyx_v_j = NULL; - PyObject *__pyx_v_kj = NULL; - PyObject *__pyx_v_q = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - double __pyx_t_4; - Py_ssize_t __pyx_t_5; - PyObject *(*__pyx_t_6)(PyObject *); - PyObject *__pyx_t_7 = NULL; - Py_ssize_t __pyx_t_8; - PyObject *(*__pyx_t_9)(PyObject *); - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - PyObject *__pyx_t_14 = NULL; - PyObject *__pyx_t_15 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("mod_one_body", 0); - - /* "ueg_kernels.pyx":34 - * """ - * - * cdef size_t nbsf = basis.shape[0] # <<<<<<<<<<<<<< - * cdef numpy.ndarray h1e_mod = T.copy() - * cdef double fac = 1.0 / (2.0 * vol) - */ - __pyx_v_nbsf = (__pyx_v_basis->dimensions[0]); - - /* "ueg_kernels.pyx":35 - * - * cdef size_t nbsf = basis.shape[0] - * cdef numpy.ndarray h1e_mod = T.copy() # <<<<<<<<<<<<<< - * cdef double fac = 1.0 / (2.0 * vol) - * - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_T), __pyx_n_s_copy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 35, __pyx_L1_error) - __pyx_v_h1e_mod = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":36 - * cdef size_t nbsf = basis.shape[0] - * cdef numpy.ndarray h1e_mod = T.copy() - * cdef double fac = 1.0 / (2.0 * vol) # <<<<<<<<<<<<<< - * - * for (i, ki) in enumerate(basis): - */ - __pyx_t_4 = (2.0 * __pyx_v_vol); - if (unlikely(__pyx_t_4 == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 36, __pyx_L1_error) - } - __pyx_v_fac = (1.0 / __pyx_t_4); - - /* "ueg_kernels.pyx":38 - * cdef double fac = 1.0 / (2.0 * vol) - * - * for (i, ki) in enumerate(basis): # <<<<<<<<<<<<<< - * for (j, kj) in enumerate(basis): - * if i != j: - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_t_1 = __pyx_int_0; - if (likely(PyList_CheckExact(((PyObject *)__pyx_v_basis))) || PyTuple_CheckExact(((PyObject *)__pyx_v_basis))) { - __pyx_t_2 = ((PyObject *)__pyx_v_basis); __Pyx_INCREF(__pyx_t_2); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - } else { - __pyx_t_5 = -1; __pyx_t_2 = PyObject_GetIter(((PyObject *)__pyx_v_basis)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 38, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_6)) { - if (likely(PyList_CheckExact(__pyx_t_2))) { - if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 38, __pyx_L1_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_2, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - } else { - if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 38, __pyx_L1_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_2, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - } - } else { - __pyx_t_3 = __pyx_t_6(__pyx_t_2); - if (unlikely(!__pyx_t_3)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 38, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_3); - } - __Pyx_XDECREF_SET(__pyx_v_ki, __pyx_t_3); - __pyx_t_3 = 0; - __Pyx_INCREF(__pyx_t_1); - __Pyx_XDECREF_SET(__pyx_v_i, __pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_t_1, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); - __pyx_t_1 = __pyx_t_3; - __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":39 - * - * for (i, ki) in enumerate(basis): - * for (j, kj) in enumerate(basis): # <<<<<<<<<<<<<< - * if i != j: - * q = kfac * (ki - kj) - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_t_3 = __pyx_int_0; - if (likely(PyList_CheckExact(((PyObject *)__pyx_v_basis))) || PyTuple_CheckExact(((PyObject *)__pyx_v_basis))) { - __pyx_t_7 = ((PyObject *)__pyx_v_basis); __Pyx_INCREF(__pyx_t_7); __pyx_t_8 = 0; - __pyx_t_9 = NULL; - } else { - __pyx_t_8 = -1; __pyx_t_7 = PyObject_GetIter(((PyObject *)__pyx_v_basis)); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 39, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = Py_TYPE(__pyx_t_7)->tp_iternext; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 39, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_9)) { - if (likely(PyList_CheckExact(__pyx_t_7))) { - if (__pyx_t_8 >= PyList_GET_SIZE(__pyx_t_7)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_10 = PyList_GET_ITEM(__pyx_t_7, __pyx_t_8); __Pyx_INCREF(__pyx_t_10); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 39, __pyx_L1_error) - #else - __pyx_t_10 = PySequence_ITEM(__pyx_t_7, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 39, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - #endif - } else { - if (__pyx_t_8 >= PyTuple_GET_SIZE(__pyx_t_7)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_10 = PyTuple_GET_ITEM(__pyx_t_7, __pyx_t_8); __Pyx_INCREF(__pyx_t_10); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 39, __pyx_L1_error) - #else - __pyx_t_10 = PySequence_ITEM(__pyx_t_7, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 39, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - #endif - } - } else { - __pyx_t_10 = __pyx_t_9(__pyx_t_7); - if (unlikely(!__pyx_t_10)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 39, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_10); - } - __Pyx_XDECREF_SET(__pyx_v_kj, __pyx_t_10); - __pyx_t_10 = 0; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_j, __pyx_t_3); - __pyx_t_10 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 39, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); - __pyx_t_3 = __pyx_t_10; - __pyx_t_10 = 0; - - /* "ueg_kernels.pyx":40 - * for (i, ki) in enumerate(basis): - * for (j, kj) in enumerate(basis): - * if i != j: # <<<<<<<<<<<<<< - * q = kfac * (ki - kj) - * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) - */ - __pyx_t_10 = PyObject_RichCompare(__pyx_v_i, __pyx_v_j, Py_NE); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 40, __pyx_L1_error) - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely(__pyx_t_11 < 0)) __PYX_ERR(0, 40, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (__pyx_t_11) { - - /* "ueg_kernels.pyx":41 - * for (j, kj) in enumerate(basis): - * if i != j: - * q = kfac * (ki - kj) # <<<<<<<<<<<<<< - * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) - * return h1e_mod - */ - __pyx_t_10 = PyFloat_FromDouble(__pyx_v_kfac); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 41, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_12 = PyNumber_Subtract(__pyx_v_ki, __pyx_v_kj); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 41, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_12); - __pyx_t_13 = PyNumber_Multiply(__pyx_t_10, __pyx_t_12); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 41, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_13); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_XDECREF_SET(__pyx_v_q, __pyx_t_13); - __pyx_t_13 = 0; - - /* "ueg_kernels.pyx":42 - * if i != j: - * q = kfac * (ki - kj) - * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) # <<<<<<<<<<<<<< - * return h1e_mod - * - */ - __pyx_t_13 = PyTuple_New(2); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_13); - __Pyx_INCREF(__pyx_v_i); - __Pyx_GIVEREF(__pyx_v_i); - PyTuple_SET_ITEM(__pyx_t_13, 0, __pyx_v_i); - __Pyx_INCREF(__pyx_v_i); - __Pyx_GIVEREF(__pyx_v_i); - PyTuple_SET_ITEM(__pyx_t_13, 1, __pyx_v_i); - __pyx_t_12 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_h1e_mod), __pyx_t_13); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __pyx_t_13 = PyFloat_FromDouble(__pyx_v_fac); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_13); - __Pyx_GetModuleGlobalName(__pyx_t_14, __pyx_n_s_vq); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_14); - __pyx_t_15 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_14))) { - __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_14); - if (likely(__pyx_t_15)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_14); - __Pyx_INCREF(__pyx_t_15); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_14, function); - } - } - __pyx_t_10 = (__pyx_t_15) ? __Pyx_PyObject_Call2Args(__pyx_t_14, __pyx_t_15, __pyx_v_q) : __Pyx_PyObject_CallOneArg(__pyx_t_14, __pyx_v_q); - __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; - if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - __pyx_t_14 = PyNumber_Multiply(__pyx_t_13, __pyx_t_10); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_14); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = PyNumber_Subtract(__pyx_t_12, __pyx_t_14); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - __pyx_t_14 = PyTuple_New(2); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_14); - __Pyx_INCREF(__pyx_v_i); - __Pyx_GIVEREF(__pyx_v_i); - PyTuple_SET_ITEM(__pyx_t_14, 0, __pyx_v_i); - __Pyx_INCREF(__pyx_v_i); - __Pyx_GIVEREF(__pyx_v_i); - PyTuple_SET_ITEM(__pyx_t_14, 1, __pyx_v_i); - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_h1e_mod), __pyx_t_14, __pyx_t_10) < 0)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - - /* "ueg_kernels.pyx":40 - * for (i, ki) in enumerate(basis): - * for (j, kj) in enumerate(basis): - * if i != j: # <<<<<<<<<<<<<< - * q = kfac * (ki - kj) - * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) - */ - } - - /* "ueg_kernels.pyx":39 - * - * for (i, ki) in enumerate(basis): - * for (j, kj) in enumerate(basis): # <<<<<<<<<<<<<< - * if i != j: - * q = kfac * (ki - kj) - */ - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":38 - * cdef double fac = 1.0 / (2.0 * vol) - * - * for (i, ki) in enumerate(basis): # <<<<<<<<<<<<<< - * for (j, kj) in enumerate(basis): - * if i != j: - */ - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":43 - * q = kfac * (ki - kj) - * h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) - * return h1e_mod # <<<<<<<<<<<<<< - * - * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_h1e_mod)); - __pyx_r = ((PyObject *)__pyx_v_h1e_mod); - goto __pyx_L0; - - /* "ueg_kernels.pyx":22 - * return 4*math.pi / q2 - * - * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): # <<<<<<<<<<<<<< - * """ Add a diagonal term of two-body Hamiltonian to the one-body term - * Parameters - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_XDECREF(__pyx_t_14); - __Pyx_XDECREF(__pyx_t_15); - __Pyx_AddTraceback("ueg_kernels.mod_one_body", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_h1e_mod); - __Pyx_XDECREF(__pyx_v_i); - __Pyx_XDECREF(__pyx_v_ki); - __Pyx_XDECREF(__pyx_v_j); - __Pyx_XDECREF(__pyx_v_kj); - __Pyx_XDECREF(__pyx_v_q); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "ueg_kernels.pyx":45 - * return h1e_mod - * - * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): # <<<<<<<<<<<<<< - * - * cdef int nq = kpq_i.shape[0] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_11ueg_kernels_5coulomb_greens_function_per_qvec(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_11ueg_kernels_5coulomb_greens_function_per_qvec = {"coulomb_greens_function_per_qvec", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_5coulomb_greens_function_per_qvec, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_11ueg_kernels_5coulomb_greens_function_per_qvec(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_kpq_i = 0; - PyArrayObject *__pyx_v_kpq = 0; - PyArrayObject *__pyx_v_pmq_i = 0; - PyArrayObject *__pyx_v_pmq = 0; - __Pyx_memviewslice __pyx_v_G = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("coulomb_greens_function_per_qvec (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_kpq_i,&__pyx_n_s_kpq,&__pyx_n_s_pmq_i,&__pyx_n_s_pmq,&__pyx_n_s_G,0}; - PyObject* values[5] = {0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq_i)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, 1); __PYX_ERR(0, 45, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq_i)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, 2); __PYX_ERR(0, 45, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, 3); __PYX_ERR(0, 45, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_G)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, 4); __PYX_ERR(0, 45, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "coulomb_greens_function_per_qvec") < 0)) __PYX_ERR(0, 45, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - } - __pyx_v_kpq_i = ((PyArrayObject *)values[0]); - __pyx_v_kpq = ((PyArrayObject *)values[1]); - __pyx_v_pmq_i = ((PyArrayObject *)values[2]); - __pyx_v_pmq = ((PyArrayObject *)values[3]); - __pyx_v_G = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_G.memview)) __PYX_ERR(0, 45, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("coulomb_greens_function_per_qvec", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 45, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("ueg_kernels.coulomb_greens_function_per_qvec", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq_i), __pyx_ptype_5numpy_ndarray, 1, "kpq_i", 0))) __PYX_ERR(0, 45, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq), __pyx_ptype_5numpy_ndarray, 1, "kpq", 0))) __PYX_ERR(0, 45, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq_i), __pyx_ptype_5numpy_ndarray, 1, "pmq_i", 0))) __PYX_ERR(0, 45, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq), __pyx_ptype_5numpy_ndarray, 1, "pmq", 0))) __PYX_ERR(0, 45, __pyx_L1_error) - __pyx_r = __pyx_pf_11ueg_kernels_4coulomb_greens_function_per_qvec(__pyx_self, __pyx_v_kpq_i, __pyx_v_kpq, __pyx_v_pmq_i, __pyx_v_pmq, __pyx_v_G); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_11ueg_kernels_4coulomb_greens_function_per_qvec(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_kpq_i, PyArrayObject *__pyx_v_kpq, PyArrayObject *__pyx_v_pmq_i, PyArrayObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_G) { - CYTHON_UNUSED int __pyx_v_nq; - int __pyx_v_idxkpq; - int __pyx_v_idxpmq; - int __pyx_v_i; - __pyx_t_double_complex __pyx_v_Gkpq; - __pyx_t_double_complex __pyx_v_Gpmq; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - Py_ssize_t __pyx_t_3; - PyObject *(*__pyx_t_4)(PyObject *); - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *(*__pyx_t_8)(PyObject *); - int __pyx_t_9; - int __pyx_t_10; - Py_ssize_t __pyx_t_11; - Py_ssize_t __pyx_t_12; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("coulomb_greens_function_per_qvec", 0); - - /* "ueg_kernels.pyx":47 - * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): - * - * cdef int nq = kpq_i.shape[0] # <<<<<<<<<<<<<< - * - * cdef int idxkpq, idxpmq, i, j, iq - */ - __pyx_v_nq = (__pyx_v_kpq_i->dimensions[0]); - - /* "ueg_kernels.pyx":51 - * cdef int idxkpq, idxpmq, i, j, iq - * - * cdef double complex Gkpq = 0.0 # <<<<<<<<<<<<<< - * cdef double complex Gpmq = 0.0 - * - */ - __pyx_v_Gkpq = __pyx_t_double_complex_from_parts(0.0, 0); - - /* "ueg_kernels.pyx":52 - * - * cdef double complex Gkpq = 0.0 - * cdef double complex Gpmq = 0.0 # <<<<<<<<<<<<<< - * - * for (idxkpq,i) in zip(kpq,kpq_i): - */ - __pyx_v_Gpmq = __pyx_t_double_complex_from_parts(0.0, 0); - - /* "ueg_kernels.pyx":54 - * cdef double complex Gpmq = 0.0 - * - * for (idxkpq,i) in zip(kpq,kpq_i): # <<<<<<<<<<<<<< - * Gkpq += G[i,idxkpq] - * for (idxpmq,i) in zip(pmq,pmq_i): - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_v_kpq)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_kpq)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_kpq)); - __Pyx_INCREF(((PyObject *)__pyx_v_kpq_i)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_kpq_i)); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_kpq_i)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { - __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - } else { - __pyx_t_3 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 54, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - for (;;) { - if (likely(!__pyx_t_4)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 54, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 54, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } - } else { - __pyx_t_2 = __pyx_t_4(__pyx_t_1); - if (unlikely(!__pyx_t_2)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 54, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_2); - } - if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { - PyObject* sequence = __pyx_t_2; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 54, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_5 = PyList_GET_ITEM(sequence, 0); - __pyx_t_6 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(__pyx_t_6); - #else - __pyx_t_5 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; - index = 0; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_5); - index = 1; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L5_unpacking_failed; - __Pyx_GOTREF(__pyx_t_6); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < 0) __PYX_ERR(0, 54, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L6_unpacking_done; - __pyx_L5_unpacking_failed:; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 54, __pyx_L1_error) - __pyx_L6_unpacking_done:; - } - __pyx_t_9 = __Pyx_PyInt_As_int(__pyx_t_5); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_10 = __Pyx_PyInt_As_int(__pyx_t_6); if (unlikely((__pyx_t_10 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 54, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_v_idxkpq = __pyx_t_9; - __pyx_v_i = __pyx_t_10; - - /* "ueg_kernels.pyx":55 - * - * for (idxkpq,i) in zip(kpq,kpq_i): - * Gkpq += G[i,idxkpq] # <<<<<<<<<<<<<< - * for (idxpmq,i) in zip(pmq,pmq_i): - * Gpmq += G[i,idxpmq] - */ - __pyx_t_11 = __pyx_v_i; - __pyx_t_12 = __pyx_v_idxkpq; - __pyx_t_10 = -1; - if (__pyx_t_11 < 0) { - __pyx_t_11 += __pyx_v_G.shape[0]; - if (unlikely(__pyx_t_11 < 0)) __pyx_t_10 = 0; - } else if (unlikely(__pyx_t_11 >= __pyx_v_G.shape[0])) __pyx_t_10 = 0; - if (__pyx_t_12 < 0) { - __pyx_t_12 += __pyx_v_G.shape[1]; - if (unlikely(__pyx_t_12 < 0)) __pyx_t_10 = 1; - } else if (unlikely(__pyx_t_12 >= __pyx_v_G.shape[1])) __pyx_t_10 = 1; - if (unlikely(__pyx_t_10 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_10); - __PYX_ERR(0, 55, __pyx_L1_error) - } - __pyx_v_Gkpq = __Pyx_c_sum_double(__pyx_v_Gkpq, (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_11 * __pyx_v_G.strides[0]) ) + __pyx_t_12 * __pyx_v_G.strides[1]) )))); - - /* "ueg_kernels.pyx":54 - * cdef double complex Gpmq = 0.0 - * - * for (idxkpq,i) in zip(kpq,kpq_i): # <<<<<<<<<<<<<< - * Gkpq += G[i,idxkpq] - * for (idxpmq,i) in zip(pmq,pmq_i): - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":56 - * for (idxkpq,i) in zip(kpq,kpq_i): - * Gkpq += G[i,idxkpq] - * for (idxpmq,i) in zip(pmq,pmq_i): # <<<<<<<<<<<<<< - * Gpmq += G[i,idxpmq] - * - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_v_pmq)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_pmq)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_pmq)); - __Pyx_INCREF(((PyObject *)__pyx_v_pmq_i)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_pmq_i)); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)__pyx_v_pmq_i)); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { - __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - } else { - __pyx_t_3 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 56, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - for (;;) { - if (likely(!__pyx_t_4)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 56, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(0, 56, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } - } else { - __pyx_t_2 = __pyx_t_4(__pyx_t_1); - if (unlikely(!__pyx_t_2)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 56, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_2); - } - if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { - PyObject* sequence = __pyx_t_2; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 56, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_6 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(__pyx_t_5); - #else - __pyx_t_6 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; - index = 0; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_6); - index = 1; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_5); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < 0) __PYX_ERR(0, 56, __pyx_L1_error) - __pyx_t_8 = NULL; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L10_unpacking_done; - __pyx_L9_unpacking_failed:; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 56, __pyx_L1_error) - __pyx_L10_unpacking_done:; - } - __pyx_t_10 = __Pyx_PyInt_As_int(__pyx_t_6); if (unlikely((__pyx_t_10 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_9 = __Pyx_PyInt_As_int(__pyx_t_5); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 56, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_idxpmq = __pyx_t_10; - __pyx_v_i = __pyx_t_9; - - /* "ueg_kernels.pyx":57 - * Gkpq += G[i,idxkpq] - * for (idxpmq,i) in zip(pmq,pmq_i): - * Gpmq += G[i,idxpmq] # <<<<<<<<<<<<<< - * - * return Gkpq, Gpmq - */ - __pyx_t_12 = __pyx_v_i; - __pyx_t_11 = __pyx_v_idxpmq; - __pyx_t_9 = -1; - if (__pyx_t_12 < 0) { - __pyx_t_12 += __pyx_v_G.shape[0]; - if (unlikely(__pyx_t_12 < 0)) __pyx_t_9 = 0; - } else if (unlikely(__pyx_t_12 >= __pyx_v_G.shape[0])) __pyx_t_9 = 0; - if (__pyx_t_11 < 0) { - __pyx_t_11 += __pyx_v_G.shape[1]; - if (unlikely(__pyx_t_11 < 0)) __pyx_t_9 = 1; - } else if (unlikely(__pyx_t_11 >= __pyx_v_G.shape[1])) __pyx_t_9 = 1; - if (unlikely(__pyx_t_9 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_9); - __PYX_ERR(0, 57, __pyx_L1_error) - } - __pyx_v_Gpmq = __Pyx_c_sum_double(__pyx_v_Gpmq, (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_12 * __pyx_v_G.strides[0]) ) + __pyx_t_11 * __pyx_v_G.strides[1]) )))); - - /* "ueg_kernels.pyx":56 - * for (idxkpq,i) in zip(kpq,kpq_i): - * Gkpq += G[i,idxkpq] - * for (idxpmq,i) in zip(pmq,pmq_i): # <<<<<<<<<<<<<< - * Gpmq += G[i,idxpmq] - * - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":59 - * Gpmq += G[i,idxpmq] - * - * return Gkpq, Gpmq # <<<<<<<<<<<<<< - * - * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_v_Gkpq); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 59, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __pyx_PyComplex_FromComplex(__pyx_v_Gpmq); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 59, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 59, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "ueg_kernels.pyx":45 - * return h1e_mod - * - * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): # <<<<<<<<<<<<<< - * - * cdef int nq = kpq_i.shape[0] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("ueg_kernels.coulomb_greens_function_per_qvec", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __PYX_XDEC_MEMVIEW(&__pyx_v_G, 1); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "ueg_kernels.pyx":61 - * return Gkpq, Gpmq - * - * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): # <<<<<<<<<<<<<< - * - * cdef int nkpq = kpq_i.shape[0] - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_11ueg_kernels_7exchange_greens_function_per_qvec(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_11ueg_kernels_7exchange_greens_function_per_qvec = {"exchange_greens_function_per_qvec", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_7exchange_greens_function_per_qvec, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_11ueg_kernels_7exchange_greens_function_per_qvec(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - __Pyx_memviewslice __pyx_v_kpq_i = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_kpq = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_pmq_i = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_pmq = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_G = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("exchange_greens_function_per_qvec (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_kpq_i,&__pyx_n_s_kpq,&__pyx_n_s_pmq_i,&__pyx_n_s_pmq,&__pyx_n_s_G,0}; - PyObject* values[5] = {0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq_i)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, 1); __PYX_ERR(0, 61, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq_i)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, 2); __PYX_ERR(0, 61, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, 3); __PYX_ERR(0, 61, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_G)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, 4); __PYX_ERR(0, 61, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "exchange_greens_function_per_qvec") < 0)) __PYX_ERR(0, 61, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - } - __pyx_v_kpq_i = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_kpq_i.memview)) __PYX_ERR(0, 61, __pyx_L3_error) - __pyx_v_kpq = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_kpq.memview)) __PYX_ERR(0, 61, __pyx_L3_error) - __pyx_v_pmq_i = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_pmq_i.memview)) __PYX_ERR(0, 61, __pyx_L3_error) - __pyx_v_pmq = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_pmq.memview)) __PYX_ERR(0, 61, __pyx_L3_error) - __pyx_v_G = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_G.memview)) __PYX_ERR(0, 61, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_per_qvec", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 61, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("ueg_kernels.exchange_greens_function_per_qvec", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_11ueg_kernels_6exchange_greens_function_per_qvec(__pyx_self, __pyx_v_kpq_i, __pyx_v_kpq, __pyx_v_pmq_i, __pyx_v_pmq, __pyx_v_G); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_11ueg_kernels_6exchange_greens_function_per_qvec(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_kpq_i, __Pyx_memviewslice __pyx_v_kpq, __Pyx_memviewslice __pyx_v_pmq_i, __Pyx_memviewslice __pyx_v_pmq, __Pyx_memviewslice __pyx_v_G) { - int __pyx_v_nkpq; - int __pyx_v_npmq; - __pyx_t_double_complex __pyx_v_Gprod; - int __pyx_v_idxkpq; - int __pyx_v_idxpmq; - int __pyx_v_i; - int __pyx_v_j; - int __pyx_v_inkpq; - int __pyx_v_jnpmq; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - Py_ssize_t __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - Py_ssize_t __pyx_t_9; - Py_ssize_t __pyx_t_10; - Py_ssize_t __pyx_t_11; - PyObject *__pyx_t_12 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("exchange_greens_function_per_qvec", 0); - - /* "ueg_kernels.pyx":63 - * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): - * - * cdef int nkpq = kpq_i.shape[0] # <<<<<<<<<<<<<< - * cdef int npmq = pmq_i.shape[0] - * - */ - __pyx_v_nkpq = (__pyx_v_kpq_i.shape[0]); - - /* "ueg_kernels.pyx":64 - * - * cdef int nkpq = kpq_i.shape[0] - * cdef int npmq = pmq_i.shape[0] # <<<<<<<<<<<<<< - * - * cdef double complex Gprod = 0.0 - */ - __pyx_v_npmq = (__pyx_v_pmq_i.shape[0]); - - /* "ueg_kernels.pyx":66 - * cdef int npmq = pmq_i.shape[0] - * - * cdef double complex Gprod = 0.0 # <<<<<<<<<<<<<< - * - * cdef int idxkpq, idxpmq, i, j - */ - __pyx_v_Gprod = __pyx_t_double_complex_from_parts(0.0, 0); - - /* "ueg_kernels.pyx":70 - * cdef int idxkpq, idxpmq, i, j - * - * for inkpq in range(nkpq): # <<<<<<<<<<<<<< - * idxkpq = kpq[inkpq] - * i = kpq_i[inkpq] - */ - __pyx_t_1 = __pyx_v_nkpq; - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_inkpq = __pyx_t_3; - - /* "ueg_kernels.pyx":71 - * - * for inkpq in range(nkpq): - * idxkpq = kpq[inkpq] # <<<<<<<<<<<<<< - * i = kpq_i[inkpq] - * for jnpmq in range(npmq): - */ - __pyx_t_4 = __pyx_v_inkpq; - __pyx_t_5 = -1; - if (__pyx_t_4 < 0) { - __pyx_t_4 += __pyx_v_kpq.shape[0]; - if (unlikely(__pyx_t_4 < 0)) __pyx_t_5 = 0; - } else if (unlikely(__pyx_t_4 >= __pyx_v_kpq.shape[0])) __pyx_t_5 = 0; - if (unlikely(__pyx_t_5 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_5); - __PYX_ERR(0, 71, __pyx_L1_error) - } - __pyx_v_idxkpq = (*((long *) ( /* dim=0 */ (__pyx_v_kpq.data + __pyx_t_4 * __pyx_v_kpq.strides[0]) ))); - - /* "ueg_kernels.pyx":72 - * for inkpq in range(nkpq): - * idxkpq = kpq[inkpq] - * i = kpq_i[inkpq] # <<<<<<<<<<<<<< - * for jnpmq in range(npmq): - * idxpmq = pmq[jnpmq] - */ - __pyx_t_4 = __pyx_v_inkpq; - __pyx_t_5 = -1; - if (__pyx_t_4 < 0) { - __pyx_t_4 += __pyx_v_kpq_i.shape[0]; - if (unlikely(__pyx_t_4 < 0)) __pyx_t_5 = 0; - } else if (unlikely(__pyx_t_4 >= __pyx_v_kpq_i.shape[0])) __pyx_t_5 = 0; - if (unlikely(__pyx_t_5 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_5); - __PYX_ERR(0, 72, __pyx_L1_error) - } - __pyx_v_i = (*((long *) ( /* dim=0 */ (__pyx_v_kpq_i.data + __pyx_t_4 * __pyx_v_kpq_i.strides[0]) ))); - - /* "ueg_kernels.pyx":73 - * idxkpq = kpq[inkpq] - * i = kpq_i[inkpq] - * for jnpmq in range(npmq): # <<<<<<<<<<<<<< - * idxpmq = pmq[jnpmq] - * j = pmq_i[jnpmq] - */ - __pyx_t_5 = __pyx_v_npmq; - __pyx_t_6 = __pyx_t_5; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { - __pyx_v_jnpmq = __pyx_t_7; - - /* "ueg_kernels.pyx":74 - * i = kpq_i[inkpq] - * for jnpmq in range(npmq): - * idxpmq = pmq[jnpmq] # <<<<<<<<<<<<<< - * j = pmq_i[jnpmq] - * Gprod += G[j,idxkpq]*G[i,idxpmq] - */ - __pyx_t_4 = __pyx_v_jnpmq; - __pyx_t_8 = -1; - if (__pyx_t_4 < 0) { - __pyx_t_4 += __pyx_v_pmq.shape[0]; - if (unlikely(__pyx_t_4 < 0)) __pyx_t_8 = 0; - } else if (unlikely(__pyx_t_4 >= __pyx_v_pmq.shape[0])) __pyx_t_8 = 0; - if (unlikely(__pyx_t_8 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_8); - __PYX_ERR(0, 74, __pyx_L1_error) - } - __pyx_v_idxpmq = (*((long *) ( /* dim=0 */ (__pyx_v_pmq.data + __pyx_t_4 * __pyx_v_pmq.strides[0]) ))); - - /* "ueg_kernels.pyx":75 - * for jnpmq in range(npmq): - * idxpmq = pmq[jnpmq] - * j = pmq_i[jnpmq] # <<<<<<<<<<<<<< - * Gprod += G[j,idxkpq]*G[i,idxpmq] - * - */ - __pyx_t_4 = __pyx_v_jnpmq; - __pyx_t_8 = -1; - if (__pyx_t_4 < 0) { - __pyx_t_4 += __pyx_v_pmq_i.shape[0]; - if (unlikely(__pyx_t_4 < 0)) __pyx_t_8 = 0; - } else if (unlikely(__pyx_t_4 >= __pyx_v_pmq_i.shape[0])) __pyx_t_8 = 0; - if (unlikely(__pyx_t_8 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_8); - __PYX_ERR(0, 75, __pyx_L1_error) - } - __pyx_v_j = (*((long *) ( /* dim=0 */ (__pyx_v_pmq_i.data + __pyx_t_4 * __pyx_v_pmq_i.strides[0]) ))); - - /* "ueg_kernels.pyx":76 - * idxpmq = pmq[jnpmq] - * j = pmq_i[jnpmq] - * Gprod += G[j,idxkpq]*G[i,idxpmq] # <<<<<<<<<<<<<< - * - * return Gprod - */ - __pyx_t_4 = __pyx_v_j; - __pyx_t_9 = __pyx_v_idxkpq; - __pyx_t_8 = -1; - if (__pyx_t_4 < 0) { - __pyx_t_4 += __pyx_v_G.shape[0]; - if (unlikely(__pyx_t_4 < 0)) __pyx_t_8 = 0; - } else if (unlikely(__pyx_t_4 >= __pyx_v_G.shape[0])) __pyx_t_8 = 0; - if (__pyx_t_9 < 0) { - __pyx_t_9 += __pyx_v_G.shape[1]; - if (unlikely(__pyx_t_9 < 0)) __pyx_t_8 = 1; - } else if (unlikely(__pyx_t_9 >= __pyx_v_G.shape[1])) __pyx_t_8 = 1; - if (unlikely(__pyx_t_8 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_8); - __PYX_ERR(0, 76, __pyx_L1_error) - } - __pyx_t_10 = __pyx_v_i; - __pyx_t_11 = __pyx_v_idxpmq; - __pyx_t_8 = -1; - if (__pyx_t_10 < 0) { - __pyx_t_10 += __pyx_v_G.shape[0]; - if (unlikely(__pyx_t_10 < 0)) __pyx_t_8 = 0; - } else if (unlikely(__pyx_t_10 >= __pyx_v_G.shape[0])) __pyx_t_8 = 0; - if (__pyx_t_11 < 0) { - __pyx_t_11 += __pyx_v_G.shape[1]; - if (unlikely(__pyx_t_11 < 0)) __pyx_t_8 = 1; - } else if (unlikely(__pyx_t_11 >= __pyx_v_G.shape[1])) __pyx_t_8 = 1; - if (unlikely(__pyx_t_8 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_8); - __PYX_ERR(0, 76, __pyx_L1_error) - } - __pyx_v_Gprod = __Pyx_c_sum_double(__pyx_v_Gprod, __Pyx_c_prod_double((*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_4 * __pyx_v_G.strides[0]) ) + __pyx_t_9 * __pyx_v_G.strides[1]) ))), (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_10 * __pyx_v_G.strides[0]) ) + __pyx_t_11 * __pyx_v_G.strides[1]) ))))); - } - } - - /* "ueg_kernels.pyx":78 - * Gprod += G[j,idxkpq]*G[i,idxpmq] - * - * return Gprod # <<<<<<<<<<<<<< - * - * def exchange_greens_function_fft (long nocc, long nbsf, - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_12 = __pyx_PyComplex_FromComplex(__pyx_v_Gprod); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 78, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_12); - __pyx_r = __pyx_t_12; - __pyx_t_12 = 0; - goto __pyx_L0; - - /* "ueg_kernels.pyx":61 - * return Gkpq, Gpmq - * - * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): # <<<<<<<<<<<<<< - * - * cdef int nkpq = kpq_i.shape[0] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_12); - __Pyx_AddTraceback("ueg_kernels.exchange_greens_function_per_qvec", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __PYX_XDEC_MEMVIEW(&__pyx_v_kpq_i, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_kpq, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_pmq_i, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_pmq, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_G, 1); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "ueg_kernels.pyx":80 - * return Gprod - * - * def exchange_greens_function_fft (long nocc, long nbsf, # <<<<<<<<<<<<<< - * long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, - * double complex[:,:] CTdagger, double complex[:,:] Ghalf): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_11ueg_kernels_9exchange_greens_function_fft(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_11ueg_kernels_9exchange_greens_function_fft = {"exchange_greens_function_fft", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_9exchange_greens_function_fft, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_11ueg_kernels_9exchange_greens_function_fft(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - long __pyx_v_nocc; - long __pyx_v_nbsf; - __Pyx_memviewslice __pyx_v_mesh = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_qmesh = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_gmap = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_qmap = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_CTdagger = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_Ghalf = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("exchange_greens_function_fft (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_nocc,&__pyx_n_s_nbsf,&__pyx_n_s_mesh,&__pyx_n_s_qmesh,&__pyx_n_s_gmap,&__pyx_n_s_qmap,&__pyx_n_s_CTdagger,&__pyx_n_s_Ghalf,0}; - PyObject* values[8] = {0,0,0,0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nocc)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nbsf)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 1); __PYX_ERR(0, 80, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mesh)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 2); __PYX_ERR(0, 80, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_qmesh)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 3); __PYX_ERR(0, 80, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_gmap)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 4); __PYX_ERR(0, 80, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 5: - if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_qmap)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 5); __PYX_ERR(0, 80, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 6: - if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_CTdagger)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 6); __PYX_ERR(0, 80, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 7: - if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Ghalf)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, 7); __PYX_ERR(0, 80, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "exchange_greens_function_fft") < 0)) __PYX_ERR(0, 80, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 8) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - } - __pyx_v_nocc = __Pyx_PyInt_As_long(values[0]); if (unlikely((__pyx_v_nocc == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 80, __pyx_L3_error) - __pyx_v_nbsf = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v_nbsf == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 80, __pyx_L3_error) - __pyx_v_mesh = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_mesh.memview)) __PYX_ERR(0, 81, __pyx_L3_error) - __pyx_v_qmesh = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_qmesh.memview)) __PYX_ERR(0, 81, __pyx_L3_error) - __pyx_v_gmap = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_gmap.memview)) __PYX_ERR(0, 81, __pyx_L3_error) - __pyx_v_qmap = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[5], PyBUF_WRITABLE); if (unlikely(!__pyx_v_qmap.memview)) __PYX_ERR(0, 81, __pyx_L3_error) - __pyx_v_CTdagger = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[6], PyBUF_WRITABLE); if (unlikely(!__pyx_v_CTdagger.memview)) __PYX_ERR(0, 82, __pyx_L3_error) - __pyx_v_Ghalf = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[7], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Ghalf.memview)) __PYX_ERR(0, 82, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("exchange_greens_function_fft", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 80, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("ueg_kernels.exchange_greens_function_fft", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_11ueg_kernels_8exchange_greens_function_fft(__pyx_self, __pyx_v_nocc, __pyx_v_nbsf, __pyx_v_mesh, __pyx_v_qmesh, __pyx_v_gmap, __pyx_v_qmap, __pyx_v_CTdagger, __pyx_v_Ghalf); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_11ueg_kernels_8exchange_greens_function_fft(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nocc, long __pyx_v_nbsf, __Pyx_memviewslice __pyx_v_mesh, __Pyx_memviewslice __pyx_v_qmesh, __Pyx_memviewslice __pyx_v_gmap, __Pyx_memviewslice __pyx_v_qmap, __Pyx_memviewslice __pyx_v_CTdagger, __Pyx_memviewslice __pyx_v_Ghalf) { - long __pyx_v_ngrid; - long __pyx_v_nqgrid; - long __pyx_v_nq; - PyArrayObject *__pyx_v_Gprod = 0; - PyArrayObject *__pyx_v_Gh_i = 0; - PyArrayObject *__pyx_v_CTdagger_j = 0; - PyArrayObject *__pyx_v_Gh_i_cube = 0; - PyArrayObject *__pyx_v_CTdagger_j_cube = 0; - PyArrayObject *__pyx_v_Gh_j = 0; - PyArrayObject *__pyx_v_CTdagger_i = 0; - PyArrayObject *__pyx_v_Gh_j_cube = 0; - PyArrayObject *__pyx_v_CTdagger_i_cube = 0; - PyArrayObject *__pyx_v_lQ_ji = 0; - PyArrayObject *__pyx_v_lQ_ij = 0; - long __pyx_v_i; - long __pyx_v_j; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - long __pyx_t_5; - long __pyx_t_6; - long __pyx_t_7; - long __pyx_t_8; - long __pyx_t_9; - long __pyx_t_10; - PyObject *__pyx_t_11 = NULL; - __Pyx_memviewslice __pyx_t_12 = { 0, 0, { 0 }, { 0 }, { 0 } }; - PyObject *__pyx_t_13 = NULL; - int __pyx_t_14; - PyObject *__pyx_t_15 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("exchange_greens_function_fft", 0); - - /* "ueg_kernels.pyx":84 - * double complex[:,:] CTdagger, double complex[:,:] Ghalf): - * - * assert (mesh.shape[0] == 3) # <<<<<<<<<<<<<< - * assert (qmesh.shape[0] == 3) - * assert (Ghalf.shape[0] == nocc) - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!(((__pyx_v_mesh.shape[0]) == 3) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(0, 84, __pyx_L1_error) - } - } - #endif - - /* "ueg_kernels.pyx":85 - * - * assert (mesh.shape[0] == 3) - * assert (qmesh.shape[0] == 3) # <<<<<<<<<<<<<< - * assert (Ghalf.shape[0] == nocc) - * assert (Ghalf.shape[1] == nbsf) - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!(((__pyx_v_qmesh.shape[0]) == 3) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(0, 85, __pyx_L1_error) - } - } - #endif - - /* "ueg_kernels.pyx":86 - * assert (mesh.shape[0] == 3) - * assert (qmesh.shape[0] == 3) - * assert (Ghalf.shape[0] == nocc) # <<<<<<<<<<<<<< - * assert (Ghalf.shape[1] == nbsf) - * assert (CTdagger.shape[0] == nocc) - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!(((__pyx_v_Ghalf.shape[0]) == __pyx_v_nocc) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(0, 86, __pyx_L1_error) - } - } - #endif - - /* "ueg_kernels.pyx":87 - * assert (qmesh.shape[0] == 3) - * assert (Ghalf.shape[0] == nocc) - * assert (Ghalf.shape[1] == nbsf) # <<<<<<<<<<<<<< - * assert (CTdagger.shape[0] == nocc) - * assert (CTdagger.shape[1] == nbsf) - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!(((__pyx_v_Ghalf.shape[1]) == __pyx_v_nbsf) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(0, 87, __pyx_L1_error) - } - } - #endif - - /* "ueg_kernels.pyx":88 - * assert (Ghalf.shape[0] == nocc) - * assert (Ghalf.shape[1] == nbsf) - * assert (CTdagger.shape[0] == nocc) # <<<<<<<<<<<<<< - * assert (CTdagger.shape[1] == nbsf) - * - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!(((__pyx_v_CTdagger.shape[0]) == __pyx_v_nocc) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(0, 88, __pyx_L1_error) - } - } - #endif - - /* "ueg_kernels.pyx":89 - * assert (Ghalf.shape[1] == nbsf) - * assert (CTdagger.shape[0] == nocc) - * assert (CTdagger.shape[1] == nbsf) # <<<<<<<<<<<<<< - * - * cdef long ngrid = numpy.prod(mesh) - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!(((__pyx_v_CTdagger.shape[1]) == __pyx_v_nbsf) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(0, 89, __pyx_L1_error) - } - } - #endif - - /* "ueg_kernels.pyx":91 - * assert (CTdagger.shape[1] == nbsf) - * - * cdef long ngrid = numpy.prod(mesh) # <<<<<<<<<<<<<< - * cdef long nqgrid = numpy.prod(qmesh) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_prod); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_mesh, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __Pyx_PyInt_As_long(__pyx_t_1); if (unlikely((__pyx_t_5 == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 91, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_ngrid = __pyx_t_5; - - /* "ueg_kernels.pyx":92 - * - * cdef long ngrid = numpy.prod(mesh) - * cdef long nqgrid = numpy.prod(qmesh) # <<<<<<<<<<<<<< - * - * cdef long nq = qmap.shape[0] - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_numpy); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 92, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_prod); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 92, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_qmesh, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 92, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 92, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_5 = __Pyx_PyInt_As_long(__pyx_t_1); if (unlikely((__pyx_t_5 == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 92, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_nqgrid = __pyx_t_5; - - /* "ueg_kernels.pyx":94 - * cdef long nqgrid = numpy.prod(qmesh) - * - * cdef long nq = qmap.shape[0] # <<<<<<<<<<<<<< - * cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) - * - */ - __pyx_v_nq = (__pyx_v_qmap.shape[0]); - - /* "ueg_kernels.pyx":95 - * - * cdef long nq = qmap.shape[0] - * cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * - * cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nq); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 95, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 95, __pyx_L1_error) - __pyx_v_Gprod = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "ueg_kernels.pyx":97 - * cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) - * - * cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 97, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 97, __pyx_L1_error) - __pyx_v_Gh_i = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":98 - * - * cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 98, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 98, __pyx_L1_error) - __pyx_v_CTdagger_j = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":99 - * cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 99, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 99, __pyx_L1_error) - __pyx_v_Gh_i_cube = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "ueg_kernels.pyx":100 - * cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * - * cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 100, __pyx_L1_error) - __pyx_v_CTdagger_j_cube = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":102 - * cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * - * cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 102, __pyx_L1_error) - __pyx_v_Gh_j = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":103 - * - * cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 103, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 103, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 103, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 103, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 103, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 103, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 103, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 103, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 103, __pyx_L1_error) - __pyx_v_CTdagger_i = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "ueg_kernels.pyx":104 - * cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 104, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 104, __pyx_L1_error) - __pyx_v_Gh_j_cube = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":105 - * cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - * cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * - * cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 105, __pyx_L1_error) - __pyx_v_CTdagger_i_cube = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":107 - * cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * - * cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nqgrid); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 107, __pyx_L1_error) - __pyx_v_lQ_ji = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "ueg_kernels.pyx":108 - * - * cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) - * cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * - * for i in range(nocc): - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 108, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 108, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyInt_From_long(__pyx_v_nqgrid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 108, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 108, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 108, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 108, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 108, __pyx_L1_error) - __pyx_v_lQ_ij = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":110 - * cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) - * - * for i in range(nocc): # <<<<<<<<<<<<<< - * for j in range(nocc): - * Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) - */ - __pyx_t_5 = __pyx_v_nocc; - __pyx_t_6 = __pyx_t_5; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { - __pyx_v_i = __pyx_t_7; - - /* "ueg_kernels.pyx":111 - * - * for i in range(nocc): - * for j in range(nocc): # <<<<<<<<<<<<<< - * Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) - * CTdagger_j = numpy.asarray(CTdagger[j,:]) - */ - __pyx_t_8 = __pyx_v_nocc; - __pyx_t_9 = __pyx_t_8; - for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { - __pyx_v_j = __pyx_t_10; - - /* "ueg_kernels.pyx":112 - * for i in range(nocc): - * for j in range(nocc): - * Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) # <<<<<<<<<<<<<< - * CTdagger_j = numpy.asarray(CTdagger[j,:]) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_flip); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_asarray); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_12.data = __pyx_v_Ghalf.data; - __pyx_t_12.memview = __pyx_v_Ghalf.memview; - __PYX_INC_MEMVIEW(&__pyx_t_12, 0); - { - Py_ssize_t __pyx_tmp_idx = __pyx_v_i; - Py_ssize_t __pyx_tmp_shape = __pyx_v_Ghalf.shape[0]; - Py_ssize_t __pyx_tmp_stride = __pyx_v_Ghalf.strides[0]; - if (__pyx_tmp_idx < 0) - __pyx_tmp_idx += __pyx_tmp_shape; - if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { - PyErr_SetString(PyExc_IndexError, - "Index out of bounds (axis 0)"); - __PYX_ERR(0, 112, __pyx_L1_error) - } - __pyx_t_12.data += __pyx_tmp_idx * __pyx_tmp_stride; -} - -__pyx_t_12.shape[0] = __pyx_v_Ghalf.shape[1]; -__pyx_t_12.strides[0] = __pyx_v_Ghalf.strides[1]; - __pyx_t_12.suboffsets[0] = -1; - -__pyx_t_1 = __pyx_memoryview_fromslice(__pyx_t_12, 1, (PyObject *(*)(char *)) __pyx_memview_get___pyx_t_double_complex, (int (*)(char *, PyObject *)) __pyx_memview_set___pyx_t_double_complex, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); - __pyx_t_12.memview = NULL; - __pyx_t_12.data = NULL; - __pyx_t_13 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_11))) { - __pyx_t_13 = PyMethod_GET_SELF(__pyx_t_11); - if (likely(__pyx_t_13)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_11); - __Pyx_INCREF(__pyx_t_13); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_11, function); - } - } - __pyx_t_4 = (__pyx_t_13) ? __Pyx_PyObject_Call2Args(__pyx_t_11, __pyx_t_13, __pyx_t_1) : __Pyx_PyObject_CallOneArg(__pyx_t_11, __pyx_t_1); - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_2 = (__pyx_t_11) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_11, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 112, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 112, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_Gh_i, ((PyArrayObject *)__pyx_t_2)); - __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":113 - * for j in range(nocc): - * Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) - * CTdagger_j = numpy.asarray(CTdagger[j,:]) # <<<<<<<<<<<<<< - * - * Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_numpy); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 113, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_asarray); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 113, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_12.data = __pyx_v_CTdagger.data; - __pyx_t_12.memview = __pyx_v_CTdagger.memview; - __PYX_INC_MEMVIEW(&__pyx_t_12, 0); - { - Py_ssize_t __pyx_tmp_idx = __pyx_v_j; - Py_ssize_t __pyx_tmp_shape = __pyx_v_CTdagger.shape[0]; - Py_ssize_t __pyx_tmp_stride = __pyx_v_CTdagger.strides[0]; - if (__pyx_tmp_idx < 0) - __pyx_tmp_idx += __pyx_tmp_shape; - if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { - PyErr_SetString(PyExc_IndexError, - "Index out of bounds (axis 0)"); - __PYX_ERR(0, 113, __pyx_L1_error) - } - __pyx_t_12.data += __pyx_tmp_idx * __pyx_tmp_stride; -} - -__pyx_t_12.shape[0] = __pyx_v_CTdagger.shape[1]; -__pyx_t_12.strides[0] = __pyx_v_CTdagger.strides[1]; - __pyx_t_12.suboffsets[0] = -1; - -__pyx_t_3 = __pyx_memoryview_fromslice(__pyx_t_12, 1, (PyObject *(*)(char *)) __pyx_memview_get___pyx_t_double_complex, (int (*)(char *, PyObject *)) __pyx_memview_set___pyx_t_double_complex, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 113, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); - __pyx_t_12.memview = NULL; - __pyx_t_12.data = NULL; - __pyx_t_11 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_2 = (__pyx_t_11) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_11, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 113, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 113, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_CTdagger_j, ((PyArrayObject *)__pyx_t_2)); - __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":115 - * CTdagger_j = numpy.asarray(CTdagger[j,:]) - * - * Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_dtype, __pyx_t_11) < 0) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 115, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_Gh_i_cube, ((PyArrayObject *)__pyx_t_11)); - __pyx_t_11 = 0; - - /* "ueg_kernels.pyx":116 - * - * Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * - * Gh_i_cube[gmap] = Gh_i - */ - __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_numpy); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_11, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_11); - __pyx_t_11 = 0; - __pyx_t_11 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_11, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_11); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_CTdagger_j_cube, ((PyArrayObject *)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "ueg_kernels.pyx":118 - * CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * - * Gh_i_cube[gmap] = Gh_i # <<<<<<<<<<<<<< - * CTdagger_j_cube[gmap] = CTdagger_j - * - */ - __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_gmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 118, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_Gh_i_cube), __pyx_t_4, ((PyObject *)__pyx_v_Gh_i)) < 0)) __PYX_ERR(0, 118, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "ueg_kernels.pyx":119 - * - * Gh_i_cube[gmap] = Gh_i - * CTdagger_j_cube[gmap] = CTdagger_j # <<<<<<<<<<<<<< - * - * lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] - */ - __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_gmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_CTdagger_j_cube), __pyx_t_4, ((PyObject *)__pyx_v_CTdagger_j)) < 0)) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "ueg_kernels.pyx":121 - * CTdagger_j_cube[gmap] = CTdagger_j - * - * lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] # <<<<<<<<<<<<<< - * - * Gh_j = numpy.asarray(Ghalf[j,:]) - */ - __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_numpy); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_11, __pyx_n_s_flip); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_convolve); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __pyx_memoryview_fromslice(__pyx_v_mesh, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_13 = NULL; - __pyx_t_14 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_13 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_13)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_13); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - __pyx_t_14 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_13, ((PyObject *)__pyx_v_CTdagger_j_cube), ((PyObject *)__pyx_v_Gh_i_cube), __pyx_t_1}; - __pyx_t_11 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_14, 3+__pyx_t_14); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[4] = {__pyx_t_13, ((PyObject *)__pyx_v_CTdagger_j_cube), ((PyObject *)__pyx_v_Gh_i_cube), __pyx_t_1}; - __pyx_t_11 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-__pyx_t_14, 3+__pyx_t_14); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - { - __pyx_t_15 = PyTuple_New(3+__pyx_t_14); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - if (__pyx_t_13) { - __Pyx_GIVEREF(__pyx_t_13); PyTuple_SET_ITEM(__pyx_t_15, 0, __pyx_t_13); __pyx_t_13 = NULL; - } - __Pyx_INCREF(((PyObject *)__pyx_v_CTdagger_j_cube)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_CTdagger_j_cube)); - PyTuple_SET_ITEM(__pyx_t_15, 0+__pyx_t_14, ((PyObject *)__pyx_v_CTdagger_j_cube)); - __Pyx_INCREF(((PyObject *)__pyx_v_Gh_i_cube)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_Gh_i_cube)); - PyTuple_SET_ITEM(__pyx_t_15, 1+__pyx_t_14, ((PyObject *)__pyx_v_Gh_i_cube)); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_15, 2+__pyx_t_14, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_15, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_4 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_11) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_11); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_qmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_11 = __Pyx_PyObject_GetItem(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_lQ_ji, ((PyArrayObject *)__pyx_t_11)); - __pyx_t_11 = 0; - - /* "ueg_kernels.pyx":123 - * lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] - * - * Gh_j = numpy.asarray(Ghalf[j,:]) # <<<<<<<<<<<<<< - * CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_numpy); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 123, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_asarray); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 123, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_12.data = __pyx_v_Ghalf.data; - __pyx_t_12.memview = __pyx_v_Ghalf.memview; - __PYX_INC_MEMVIEW(&__pyx_t_12, 0); - { - Py_ssize_t __pyx_tmp_idx = __pyx_v_j; - Py_ssize_t __pyx_tmp_shape = __pyx_v_Ghalf.shape[0]; - Py_ssize_t __pyx_tmp_stride = __pyx_v_Ghalf.strides[0]; - if (__pyx_tmp_idx < 0) - __pyx_tmp_idx += __pyx_tmp_shape; - if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { - PyErr_SetString(PyExc_IndexError, - "Index out of bounds (axis 0)"); - __PYX_ERR(0, 123, __pyx_L1_error) - } - __pyx_t_12.data += __pyx_tmp_idx * __pyx_tmp_stride; -} - -__pyx_t_12.shape[0] = __pyx_v_Ghalf.shape[1]; -__pyx_t_12.strides[0] = __pyx_v_Ghalf.strides[1]; - __pyx_t_12.suboffsets[0] = -1; - -__pyx_t_3 = __pyx_memoryview_fromslice(__pyx_t_12, 1, (PyObject *(*)(char *)) __pyx_memview_get___pyx_t_double_complex, (int (*)(char *, PyObject *)) __pyx_memview_set___pyx_t_double_complex, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 123, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); - __pyx_t_12.memview = NULL; - __pyx_t_12.data = NULL; - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_11 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 123, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 123, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_Gh_j, ((PyArrayObject *)__pyx_t_11)); - __pyx_t_11 = 0; - - /* "ueg_kernels.pyx":124 - * - * Gh_j = numpy.asarray(Ghalf[j,:]) - * CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) # <<<<<<<<<<<<<< - * - * Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_numpy); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_flip); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_15 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_asarray); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_12.data = __pyx_v_CTdagger.data; - __pyx_t_12.memview = __pyx_v_CTdagger.memview; - __PYX_INC_MEMVIEW(&__pyx_t_12, 0); - { - Py_ssize_t __pyx_tmp_idx = __pyx_v_i; - Py_ssize_t __pyx_tmp_shape = __pyx_v_CTdagger.shape[0]; - Py_ssize_t __pyx_tmp_stride = __pyx_v_CTdagger.strides[0]; - if (__pyx_tmp_idx < 0) - __pyx_tmp_idx += __pyx_tmp_shape; - if (unlikely(!__Pyx_is_valid_index(__pyx_tmp_idx, __pyx_tmp_shape))) { - PyErr_SetString(PyExc_IndexError, - "Index out of bounds (axis 0)"); - __PYX_ERR(0, 124, __pyx_L1_error) - } - __pyx_t_12.data += __pyx_tmp_idx * __pyx_tmp_stride; -} - -__pyx_t_12.shape[0] = __pyx_v_CTdagger.shape[1]; -__pyx_t_12.strides[0] = __pyx_v_CTdagger.strides[1]; - __pyx_t_12.suboffsets[0] = -1; - -__pyx_t_2 = __pyx_memoryview_fromslice(__pyx_t_12, 1, (PyObject *(*)(char *)) __pyx_memview_get___pyx_t_double_complex, (int (*)(char *, PyObject *)) __pyx_memview_set___pyx_t_double_complex, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); - __pyx_t_12.memview = NULL; - __pyx_t_12.data = NULL; - __pyx_t_1 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_15))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_15); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_15); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_15, function); - } - } - __pyx_t_4 = (__pyx_t_1) ? __Pyx_PyObject_Call2Args(__pyx_t_15, __pyx_t_1, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_15, __pyx_t_2); - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __pyx_t_15 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_15)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_15); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_11 = (__pyx_t_15) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_15, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 124, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_CTdagger_i, ((PyArrayObject *)__pyx_t_11)); - __pyx_t_11 = 0; - - /* "ueg_kernels.pyx":126 - * CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) - * - * Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_numpy); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_11, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_11); - __pyx_t_11 = 0; - __pyx_t_11 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GetModuleGlobalName(__pyx_t_15, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - if (PyDict_SetItem(__pyx_t_11, __pyx_n_s_dtype, __pyx_t_15) < 0) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __pyx_t_15 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_11); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - if (!(likely(((__pyx_t_15) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_15, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 126, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_Gh_j_cube, ((PyArrayObject *)__pyx_t_15)); - __pyx_t_15 = 0; - - /* "ueg_kernels.pyx":127 - * - * Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * - * Gh_j_cube[gmap] = Gh_j - */ - __Pyx_GetModuleGlobalName(__pyx_t_15, __pyx_n_s_numpy); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_15, __pyx_n_s_zeros); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __pyx_t_15 = __Pyx_PyInt_From_long(__pyx_v_ngrid); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_15); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_15); - __pyx_t_15 = 0; - __pyx_t_15 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_15, __pyx_n_s_dtype, __pyx_t_3) < 0) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_11, __pyx_t_4, __pyx_t_15); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 127, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_CTdagger_i_cube, ((PyArrayObject *)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":129 - * CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - * - * Gh_j_cube[gmap] = Gh_j # <<<<<<<<<<<<<< - * CTdagger_i_cube[gmap] = CTdagger_i - * - */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_gmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 129, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_Gh_j_cube), __pyx_t_3, ((PyObject *)__pyx_v_Gh_j)) < 0)) __PYX_ERR(0, 129, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":130 - * - * Gh_j_cube[gmap] = Gh_j - * CTdagger_i_cube[gmap] = CTdagger_i # <<<<<<<<<<<<<< - * - * lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] - */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_gmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 130, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_CTdagger_i_cube), __pyx_t_3, ((PyObject *)__pyx_v_CTdagger_i)) < 0)) __PYX_ERR(0, 130, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":132 - * CTdagger_i_cube[gmap] = CTdagger_i - * - * lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] # <<<<<<<<<<<<<< - * - * Gprod += lQ_ji*lQ_ij - */ - __Pyx_GetModuleGlobalName(__pyx_t_15, __pyx_n_s_numpy); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_15, __pyx_n_s_flip); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_n_s_convolve); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_2 = __pyx_memoryview_fromslice(__pyx_v_mesh, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = NULL; - __pyx_t_14 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_11))) { - __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_11); - if (likely(__pyx_t_1)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_11); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_11, function); - __pyx_t_14 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_11)) { - PyObject *__pyx_temp[4] = {__pyx_t_1, ((PyObject *)__pyx_v_Gh_j_cube), ((PyObject *)__pyx_v_CTdagger_i_cube), __pyx_t_2}; - __pyx_t_15 = __Pyx_PyFunction_FastCall(__pyx_t_11, __pyx_temp+1-__pyx_t_14, 3+__pyx_t_14); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_11)) { - PyObject *__pyx_temp[4] = {__pyx_t_1, ((PyObject *)__pyx_v_Gh_j_cube), ((PyObject *)__pyx_v_CTdagger_i_cube), __pyx_t_2}; - __pyx_t_15 = __Pyx_PyCFunction_FastCall(__pyx_t_11, __pyx_temp+1-__pyx_t_14, 3+__pyx_t_14); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else - #endif - { - __pyx_t_13 = PyTuple_New(3+__pyx_t_14); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_13); - if (__pyx_t_1) { - __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_13, 0, __pyx_t_1); __pyx_t_1 = NULL; - } - __Pyx_INCREF(((PyObject *)__pyx_v_Gh_j_cube)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_Gh_j_cube)); - PyTuple_SET_ITEM(__pyx_t_13, 0+__pyx_t_14, ((PyObject *)__pyx_v_Gh_j_cube)); - __Pyx_INCREF(((PyObject *)__pyx_v_CTdagger_i_cube)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_CTdagger_i_cube)); - PyTuple_SET_ITEM(__pyx_t_13, 1+__pyx_t_14, ((PyObject *)__pyx_v_CTdagger_i_cube)); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_13, 2+__pyx_t_14, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_15 = __Pyx_PyObject_Call(__pyx_t_11, __pyx_t_13, NULL); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - } - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_11 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_3 = (__pyx_t_11) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_11, __pyx_t_15) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_15); - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __pyx_memoryview_fromslice(__pyx_v_qmap, 1, (PyObject *(*)(char *)) __pyx_memview_get_long, (int (*)(char *, PyObject *)) __pyx_memview_set_long, 0);; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_15 = __Pyx_PyObject_GetItem(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_15) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_15, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_lQ_ij, ((PyArrayObject *)__pyx_t_15)); - __pyx_t_15 = 0; - - /* "ueg_kernels.pyx":134 - * lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] - * - * Gprod += lQ_ji*lQ_ij # <<<<<<<<<<<<<< - * - * return Gprod - */ - __pyx_t_15 = PyNumber_Multiply(((PyObject *)__pyx_v_lQ_ji), ((PyObject *)__pyx_v_lQ_ij)); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 134, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __pyx_t_4 = PyNumber_InPlaceAdd(((PyObject *)__pyx_v_Gprod), __pyx_t_15); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 134, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 134, __pyx_L1_error) - __Pyx_DECREF_SET(__pyx_v_Gprod, ((PyArrayObject *)__pyx_t_4)); - __pyx_t_4 = 0; - } - } - - /* "ueg_kernels.pyx":136 - * Gprod += lQ_ji*lQ_ij - * - * return Gprod # <<<<<<<<<<<<<< - * - * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_Gprod)); - __pyx_r = ((PyObject *)__pyx_v_Gprod); - goto __pyx_L0; - - /* "ueg_kernels.pyx":80 - * return Gprod - * - * def exchange_greens_function_fft (long nocc, long nbsf, # <<<<<<<<<<<<<< - * long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, - * double complex[:,:] CTdagger, double complex[:,:] Ghalf): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_11); - __PYX_XDEC_MEMVIEW(&__pyx_t_12, 1); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_XDECREF(__pyx_t_15); - __Pyx_AddTraceback("ueg_kernels.exchange_greens_function_fft", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_Gprod); - __Pyx_XDECREF((PyObject *)__pyx_v_Gh_i); - __Pyx_XDECREF((PyObject *)__pyx_v_CTdagger_j); - __Pyx_XDECREF((PyObject *)__pyx_v_Gh_i_cube); - __Pyx_XDECREF((PyObject *)__pyx_v_CTdagger_j_cube); - __Pyx_XDECREF((PyObject *)__pyx_v_Gh_j); - __Pyx_XDECREF((PyObject *)__pyx_v_CTdagger_i); - __Pyx_XDECREF((PyObject *)__pyx_v_Gh_j_cube); - __Pyx_XDECREF((PyObject *)__pyx_v_CTdagger_i_cube); - __Pyx_XDECREF((PyObject *)__pyx_v_lQ_ji); - __Pyx_XDECREF((PyObject *)__pyx_v_lQ_ij); - __PYX_XDEC_MEMVIEW(&__pyx_v_mesh, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_qmesh, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_gmap, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_qmap, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_CTdagger, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_Ghalf, 1); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "ueg_kernels.pyx":138 - * return Gprod - * - * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< - * list kpq, list pmq_i, list pmq, - * double complex[:,:] Gkpq, double complex[:,:] Gpmq): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_11ueg_kernels_11build_J_opt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_11ueg_kernels_11build_J_opt = {"build_J_opt", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_11build_J_opt, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_11ueg_kernels_11build_J_opt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - long __pyx_v_nq; - __Pyx_memviewslice __pyx_v_vqvec = { 0, 0, { 0 }, { 0 }, { 0 } }; - double __pyx_v_vol; - long __pyx_v_nbsf; - PyObject *__pyx_v_kpq_i = 0; - PyObject *__pyx_v_kpq = 0; - PyObject *__pyx_v_pmq_i = 0; - PyObject *__pyx_v_pmq = 0; - __Pyx_memviewslice __pyx_v_Gkpq = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_memviewslice __pyx_v_Gpmq = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("build_J_opt (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_nq,&__pyx_n_s_vqvec,&__pyx_n_s_vol,&__pyx_n_s_nbsf,&__pyx_n_s_kpq_i,&__pyx_n_s_kpq,&__pyx_n_s_pmq_i,&__pyx_n_s_pmq,&__pyx_n_s_Gkpq,&__pyx_n_s_Gpmq,0}; - PyObject* values[10] = {0,0,0,0,0,0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - CYTHON_FALLTHROUGH; - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - CYTHON_FALLTHROUGH; - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nq)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vqvec)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 1); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vol)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 2); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nbsf)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 3); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq_i)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 4); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 5: - if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 5); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 6: - if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq_i)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 6); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 7: - if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 7); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 8: - if (likely((values[8] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Gkpq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 8); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 9: - if (likely((values[9] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_Gpmq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, 9); __PYX_ERR(0, 138, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "build_J_opt") < 0)) __PYX_ERR(0, 138, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 10) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - } - __pyx_v_nq = __Pyx_PyInt_As_long(values[0]); if (unlikely((__pyx_v_nq == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 138, __pyx_L3_error) - __pyx_v_vqvec = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_vqvec.memview)) __PYX_ERR(0, 138, __pyx_L3_error) - __pyx_v_vol = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_vol == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 138, __pyx_L3_error) - __pyx_v_nbsf = __Pyx_PyInt_As_long(values[3]); if (unlikely((__pyx_v_nbsf == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 138, __pyx_L3_error) - __pyx_v_kpq_i = ((PyObject*)values[4]); - __pyx_v_kpq = ((PyObject*)values[5]); - __pyx_v_pmq_i = ((PyObject*)values[6]); - __pyx_v_pmq = ((PyObject*)values[7]); - __pyx_v_Gkpq = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[8], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Gkpq.memview)) __PYX_ERR(0, 140, __pyx_L3_error) - __pyx_v_Gpmq = __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(values[9], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Gpmq.memview)) __PYX_ERR(0, 140, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("build_J_opt", 1, 10, 10, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 138, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("ueg_kernels.build_J_opt", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq_i), (&PyList_Type), 1, "kpq_i", 1))) __PYX_ERR(0, 138, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq), (&PyList_Type), 1, "kpq", 1))) __PYX_ERR(0, 139, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq_i), (&PyList_Type), 1, "pmq_i", 1))) __PYX_ERR(0, 139, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq), (&PyList_Type), 1, "pmq", 1))) __PYX_ERR(0, 139, __pyx_L1_error) - __pyx_r = __pyx_pf_11ueg_kernels_10build_J_opt(__pyx_self, __pyx_v_nq, __pyx_v_vqvec, __pyx_v_vol, __pyx_v_nbsf, __pyx_v_kpq_i, __pyx_v_kpq, __pyx_v_pmq_i, __pyx_v_pmq, __pyx_v_Gkpq, __pyx_v_Gpmq); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_11ueg_kernels_10build_J_opt(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nq, __Pyx_memviewslice __pyx_v_vqvec, double __pyx_v_vol, long __pyx_v_nbsf, PyObject *__pyx_v_kpq_i, PyObject *__pyx_v_kpq, PyObject *__pyx_v_pmq_i, PyObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_Gkpq, __Pyx_memviewslice __pyx_v_Gpmq) { - PyArrayObject *__pyx_v_J = 0; - int __pyx_v_i; - int __pyx_v_j; - long __pyx_v_iq; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - long __pyx_t_5; - long __pyx_t_6; - long __pyx_t_7; - Py_ssize_t __pyx_t_8; - PyObject *(*__pyx_t_9)(PyObject *); - PyObject *__pyx_t_10 = NULL; - PyObject *(*__pyx_t_11)(PyObject *); - int __pyx_t_12; - int __pyx_t_13; - double __pyx_t_14; - Py_ssize_t __pyx_t_15; - Py_ssize_t __pyx_t_16; - Py_ssize_t __pyx_t_17; - Py_ssize_t __pyx_t_18; - Py_ssize_t __pyx_t_19; - __pyx_t_double_complex __pyx_t_20; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("build_J_opt", 0); - - /* "ueg_kernels.pyx":142 - * double complex[:,:] Gkpq, double complex[:,:] Gpmq): - * - * cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef int i, j - * for iq in range(nq): - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyList_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_int_2); - __Pyx_GIVEREF(__pyx_int_2); - PyList_SET_ITEM(__pyx_t_4, 0, __pyx_int_2); - __Pyx_GIVEREF(__pyx_t_1); - PyList_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyList_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 142, __pyx_L1_error) - __pyx_v_J = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":144 - * cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) - * cdef int i, j - * for iq in range(nq): # <<<<<<<<<<<<<< - * for i, j in zip(pmq_i[iq], pmq[iq]): - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - */ - __pyx_t_5 = __pyx_v_nq; - __pyx_t_6 = __pyx_t_5; - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { - __pyx_v_iq = __pyx_t_7; - - /* "ueg_kernels.pyx":145 - * cdef int i, j - * for iq in range(nq): - * for i, j in zip(pmq_i[iq], pmq[iq]): # <<<<<<<<<<<<<< - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - * for i, j in zip(kpq_i[iq], kpq[iq]): - */ - if (unlikely(__pyx_v_pmq_i == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 145, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_pmq_i, __pyx_v_iq, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (unlikely(__pyx_v_pmq == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 145, __pyx_L1_error) - } - __pyx_t_4 = __Pyx_GetItemInt_List(__pyx_v_pmq, __pyx_v_iq, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __pyx_t_1 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (likely(PyList_CheckExact(__pyx_t_4)) || PyTuple_CheckExact(__pyx_t_4)) { - __pyx_t_3 = __pyx_t_4; __Pyx_INCREF(__pyx_t_3); __pyx_t_8 = 0; - __pyx_t_9 = NULL; - } else { - __pyx_t_8 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_9 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 145, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - for (;;) { - if (likely(!__pyx_t_9)) { - if (likely(PyList_CheckExact(__pyx_t_3))) { - if (__pyx_t_8 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_8); __Pyx_INCREF(__pyx_t_4); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 145, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - if (__pyx_t_8 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_8); __Pyx_INCREF(__pyx_t_4); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 145, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } - } else { - __pyx_t_4 = __pyx_t_9(__pyx_t_3); - if (unlikely(!__pyx_t_4)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 145, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { - PyObject* sequence = __pyx_t_4; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 145, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_10 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_11 = Py_TYPE(__pyx_t_10)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_1)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_11(__pyx_t_10), 2) < 0) __PYX_ERR(0, 145, __pyx_L1_error) - __pyx_t_11 = NULL; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_11 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 145, __pyx_L1_error) - __pyx_L8_unpacking_done:; - } - __pyx_t_12 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_12 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_i = __pyx_t_12; - __pyx_v_j = __pyx_t_13; - - /* "ueg_kernels.pyx":146 - * for iq in range(nq): - * for i, j in zip(pmq_i[iq], pmq[iq]): - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) # <<<<<<<<<<<<<< - * for i, j in zip(kpq_i[iq], kpq[iq]): - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - */ - __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_j); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_2); - __pyx_t_4 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_J), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_14 = (2.0 * __pyx_v_vol); - if (unlikely(__pyx_t_14 == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 146, __pyx_L1_error) - } - __pyx_t_15 = __pyx_v_iq; - __pyx_t_13 = -1; - if (__pyx_t_15 < 0) { - __pyx_t_15 += __pyx_v_vqvec.shape[0]; - if (unlikely(__pyx_t_15 < 0)) __pyx_t_13 = 0; - } else if (unlikely(__pyx_t_15 >= __pyx_v_vqvec.shape[0])) __pyx_t_13 = 0; - if (unlikely(__pyx_t_13 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_13); - __PYX_ERR(0, 146, __pyx_L1_error) - } - __pyx_t_16 = 0; - __pyx_t_17 = __pyx_v_iq; - __pyx_t_13 = -1; - if (__pyx_t_16 < 0) { - __pyx_t_16 += __pyx_v_Gpmq.shape[0]; - if (unlikely(__pyx_t_16 < 0)) __pyx_t_13 = 0; - } else if (unlikely(__pyx_t_16 >= __pyx_v_Gpmq.shape[0])) __pyx_t_13 = 0; - if (__pyx_t_17 < 0) { - __pyx_t_17 += __pyx_v_Gpmq.shape[1]; - if (unlikely(__pyx_t_17 < 0)) __pyx_t_13 = 1; - } else if (unlikely(__pyx_t_17 >= __pyx_v_Gpmq.shape[1])) __pyx_t_13 = 1; - if (unlikely(__pyx_t_13 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_13); - __PYX_ERR(0, 146, __pyx_L1_error) - } - __pyx_t_18 = 1; - __pyx_t_19 = __pyx_v_iq; - __pyx_t_13 = -1; - if (__pyx_t_18 < 0) { - __pyx_t_18 += __pyx_v_Gpmq.shape[0]; - if (unlikely(__pyx_t_18 < 0)) __pyx_t_13 = 0; - } else if (unlikely(__pyx_t_18 >= __pyx_v_Gpmq.shape[0])) __pyx_t_13 = 0; - if (__pyx_t_19 < 0) { - __pyx_t_19 += __pyx_v_Gpmq.shape[1]; - if (unlikely(__pyx_t_19 < 0)) __pyx_t_13 = 1; - } else if (unlikely(__pyx_t_19 >= __pyx_v_Gpmq.shape[1])) __pyx_t_13 = 1; - if (unlikely(__pyx_t_13 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_13); - __PYX_ERR(0, 146, __pyx_L1_error) - } - __pyx_t_20 = __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(((1.0 / __pyx_t_14) * (*((double *) ( /* dim=0 */ (__pyx_v_vqvec.data + __pyx_t_15 * __pyx_v_vqvec.strides[0]) )))), 0), __Pyx_c_sum_double((*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Gpmq.data + __pyx_t_16 * __pyx_v_Gpmq.strides[0]) ) + __pyx_t_17 * __pyx_v_Gpmq.strides[1]) ))), (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Gpmq.data + __pyx_t_18 * __pyx_v_Gpmq.strides[0]) ) + __pyx_t_19 * __pyx_v_Gpmq.strides[1]) ))))); - __pyx_t_4 = __pyx_PyComplex_FromComplex(__pyx_t_20); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_10 = PyNumber_InPlaceAdd(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_J), __pyx_t_1, __pyx_t_10) < 0)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":145 - * cdef int i, j - * for iq in range(nq): - * for i, j in zip(pmq_i[iq], pmq[iq]): # <<<<<<<<<<<<<< - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - * for i, j in zip(kpq_i[iq], kpq[iq]): - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":147 - * for i, j in zip(pmq_i[iq], pmq[iq]): - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - * for i, j in zip(kpq_i[iq], kpq[iq]): # <<<<<<<<<<<<<< - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - * - */ - if (unlikely(__pyx_v_kpq_i == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 147, __pyx_L1_error) - } - __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_kpq_i, __pyx_v_iq, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (unlikely(__pyx_v_kpq == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 147, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_kpq, __pyx_v_iq, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_1); - __pyx_t_3 = 0; - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_10, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { - __pyx_t_10 = __pyx_t_1; __Pyx_INCREF(__pyx_t_10); __pyx_t_8 = 0; - __pyx_t_9 = NULL; - } else { - __pyx_t_8 = -1; __pyx_t_10 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_9 = Py_TYPE(__pyx_t_10)->tp_iternext; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 147, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - for (;;) { - if (likely(!__pyx_t_9)) { - if (likely(PyList_CheckExact(__pyx_t_10))) { - if (__pyx_t_8 >= PyList_GET_SIZE(__pyx_t_10)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyList_GET_ITEM(__pyx_t_10, __pyx_t_8); __Pyx_INCREF(__pyx_t_1); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 147, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_10, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - if (__pyx_t_8 >= PyTuple_GET_SIZE(__pyx_t_10)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_10, __pyx_t_8); __Pyx_INCREF(__pyx_t_1); __pyx_t_8++; if (unlikely(0 < 0)) __PYX_ERR(0, 147, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_10, __pyx_t_8); __pyx_t_8++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } - } else { - __pyx_t_1 = __pyx_t_9(__pyx_t_10); - if (unlikely(!__pyx_t_1)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 147, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_1); - } - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 147, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_3 = PyList_GET_ITEM(sequence, 0); - __pyx_t_4 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_11 = Py_TYPE(__pyx_t_2)->tp_iternext; - index = 0; __pyx_t_3 = __pyx_t_11(__pyx_t_2); if (unlikely(!__pyx_t_3)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 1; __pyx_t_4 = __pyx_t_11(__pyx_t_2); if (unlikely(!__pyx_t_4)) goto __pyx_L11_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_11(__pyx_t_2), 2) < 0) __PYX_ERR(0, 147, __pyx_L1_error) - __pyx_t_11 = NULL; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - goto __pyx_L12_unpacking_done; - __pyx_L11_unpacking_failed:; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_11 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 147, __pyx_L1_error) - __pyx_L12_unpacking_done:; - } - __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_12 = __Pyx_PyInt_As_int(__pyx_t_4); if (unlikely((__pyx_t_12 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_i = __pyx_t_13; - __pyx_v_j = __pyx_t_12; - - /* "ueg_kernels.pyx":148 - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - * for i, j in zip(kpq_i[iq], kpq[iq]): - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) # <<<<<<<<<<<<<< - * - * J[1] = J[0] - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_j); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_4); - __pyx_t_1 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_J), __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_14 = (2.0 * __pyx_v_vol); - if (unlikely(__pyx_t_14 == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 148, __pyx_L1_error) - } - __pyx_t_19 = __pyx_v_iq; - __pyx_t_12 = -1; - if (__pyx_t_19 < 0) { - __pyx_t_19 += __pyx_v_vqvec.shape[0]; - if (unlikely(__pyx_t_19 < 0)) __pyx_t_12 = 0; - } else if (unlikely(__pyx_t_19 >= __pyx_v_vqvec.shape[0])) __pyx_t_12 = 0; - if (unlikely(__pyx_t_12 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_12); - __PYX_ERR(0, 148, __pyx_L1_error) - } - __pyx_t_18 = 0; - __pyx_t_17 = __pyx_v_iq; - __pyx_t_12 = -1; - if (__pyx_t_18 < 0) { - __pyx_t_18 += __pyx_v_Gkpq.shape[0]; - if (unlikely(__pyx_t_18 < 0)) __pyx_t_12 = 0; - } else if (unlikely(__pyx_t_18 >= __pyx_v_Gkpq.shape[0])) __pyx_t_12 = 0; - if (__pyx_t_17 < 0) { - __pyx_t_17 += __pyx_v_Gkpq.shape[1]; - if (unlikely(__pyx_t_17 < 0)) __pyx_t_12 = 1; - } else if (unlikely(__pyx_t_17 >= __pyx_v_Gkpq.shape[1])) __pyx_t_12 = 1; - if (unlikely(__pyx_t_12 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_12); - __PYX_ERR(0, 148, __pyx_L1_error) - } - __pyx_t_16 = 1; - __pyx_t_15 = __pyx_v_iq; - __pyx_t_12 = -1; - if (__pyx_t_16 < 0) { - __pyx_t_16 += __pyx_v_Gkpq.shape[0]; - if (unlikely(__pyx_t_16 < 0)) __pyx_t_12 = 0; - } else if (unlikely(__pyx_t_16 >= __pyx_v_Gkpq.shape[0])) __pyx_t_12 = 0; - if (__pyx_t_15 < 0) { - __pyx_t_15 += __pyx_v_Gkpq.shape[1]; - if (unlikely(__pyx_t_15 < 0)) __pyx_t_12 = 1; - } else if (unlikely(__pyx_t_15 >= __pyx_v_Gkpq.shape[1])) __pyx_t_12 = 1; - if (unlikely(__pyx_t_12 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_12); - __PYX_ERR(0, 148, __pyx_L1_error) - } - __pyx_t_20 = __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(((1.0 / __pyx_t_14) * (*((double *) ( /* dim=0 */ (__pyx_v_vqvec.data + __pyx_t_19 * __pyx_v_vqvec.strides[0]) )))), 0), __Pyx_c_sum_double((*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Gkpq.data + __pyx_t_18 * __pyx_v_Gkpq.strides[0]) ) + __pyx_t_17 * __pyx_v_Gkpq.strides[1]) ))), (*((__pyx_t_double_complex *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Gkpq.data + __pyx_t_16 * __pyx_v_Gkpq.strides[0]) ) + __pyx_t_15 * __pyx_v_Gkpq.strides[1]) ))))); - __pyx_t_1 = __pyx_PyComplex_FromComplex(__pyx_t_20); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_J), __pyx_t_3, __pyx_t_2) < 0)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":147 - * for i, j in zip(pmq_i[iq], pmq[iq]): - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - * for i, j in zip(kpq_i[iq], kpq[iq]): # <<<<<<<<<<<<<< - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - * - */ - } - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - - /* "ueg_kernels.pyx":150 - * J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - * - * J[1] = J[0] # <<<<<<<<<<<<<< - * - * return J - */ - __pyx_t_10 = __Pyx_GetItemInt(((PyObject *)__pyx_v_J), 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (unlikely(__Pyx_SetItemInt(((PyObject *)__pyx_v_J), 1, __pyx_t_10, long, 1, __Pyx_PyInt_From_long, 0, 0, 1) < 0)) __PYX_ERR(0, 150, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - - /* "ueg_kernels.pyx":152 - * J[1] = J[0] - * - * return J # <<<<<<<<<<<<<< - * - * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_J)); - __pyx_r = ((PyObject *)__pyx_v_J); - goto __pyx_L0; - - /* "ueg_kernels.pyx":138 - * return Gprod - * - * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< - * list kpq, list pmq_i, list pmq, - * double complex[:,:] Gkpq, double complex[:,:] Gpmq): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("ueg_kernels.build_J_opt", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_J); - __PYX_XDEC_MEMVIEW(&__pyx_v_vqvec, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_Gkpq, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_Gpmq, 1); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "ueg_kernels.pyx":154 - * return J - * - * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< - * list kpq, list pmq_i, list pmq, - * double complex[:,:,:] G): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_11ueg_kernels_13build_K_opt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_11ueg_kernels_13build_K_opt = {"build_K_opt", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11ueg_kernels_13build_K_opt, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_11ueg_kernels_13build_K_opt(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - long __pyx_v_nq; - __Pyx_memviewslice __pyx_v_vqvec = { 0, 0, { 0 }, { 0 }, { 0 } }; - double __pyx_v_vol; - long __pyx_v_nbsf; - PyObject *__pyx_v_kpq_i = 0; - PyObject *__pyx_v_kpq = 0; - PyObject *__pyx_v_pmq_i = 0; - PyObject *__pyx_v_pmq = 0; - __Pyx_memviewslice __pyx_v_G = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("build_K_opt (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_nq,&__pyx_n_s_vqvec,&__pyx_n_s_vol,&__pyx_n_s_nbsf,&__pyx_n_s_kpq_i,&__pyx_n_s_kpq,&__pyx_n_s_pmq_i,&__pyx_n_s_pmq,&__pyx_n_s_G,0}; - PyObject* values[9] = {0,0,0,0,0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - CYTHON_FALLTHROUGH; - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nq)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vqvec)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 1); __PYX_ERR(0, 154, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_vol)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 2); __PYX_ERR(0, 154, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_nbsf)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 3); __PYX_ERR(0, 154, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq_i)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 4); __PYX_ERR(0, 154, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 5: - if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_kpq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 5); __PYX_ERR(0, 154, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 6: - if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq_i)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 6); __PYX_ERR(0, 154, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 7: - if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pmq)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 7); __PYX_ERR(0, 154, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 8: - if (likely((values[8] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_G)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, 8); __PYX_ERR(0, 154, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "build_K_opt") < 0)) __PYX_ERR(0, 154, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 9) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - } - __pyx_v_nq = __Pyx_PyInt_As_long(values[0]); if (unlikely((__pyx_v_nq == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 154, __pyx_L3_error) - __pyx_v_vqvec = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_vqvec.memview)) __PYX_ERR(0, 154, __pyx_L3_error) - __pyx_v_vol = __pyx_PyFloat_AsDouble(values[2]); if (unlikely((__pyx_v_vol == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 154, __pyx_L3_error) - __pyx_v_nbsf = __Pyx_PyInt_As_long(values[3]); if (unlikely((__pyx_v_nbsf == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 154, __pyx_L3_error) - __pyx_v_kpq_i = ((PyObject*)values[4]); - __pyx_v_kpq = ((PyObject*)values[5]); - __pyx_v_pmq_i = ((PyObject*)values[6]); - __pyx_v_pmq = ((PyObject*)values[7]); - __pyx_v_G = __Pyx_PyObject_to_MemoryviewSlice_dsdsds___pyx_t_double_complex(values[8], PyBUF_WRITABLE); if (unlikely(!__pyx_v_G.memview)) __PYX_ERR(0, 156, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("build_K_opt", 1, 9, 9, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 154, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("ueg_kernels.build_K_opt", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq_i), (&PyList_Type), 1, "kpq_i", 1))) __PYX_ERR(0, 154, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kpq), (&PyList_Type), 1, "kpq", 1))) __PYX_ERR(0, 155, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq_i), (&PyList_Type), 1, "pmq_i", 1))) __PYX_ERR(0, 155, __pyx_L1_error) - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pmq), (&PyList_Type), 1, "pmq", 1))) __PYX_ERR(0, 155, __pyx_L1_error) - __pyx_r = __pyx_pf_11ueg_kernels_12build_K_opt(__pyx_self, __pyx_v_nq, __pyx_v_vqvec, __pyx_v_vol, __pyx_v_nbsf, __pyx_v_kpq_i, __pyx_v_kpq, __pyx_v_pmq_i, __pyx_v_pmq, __pyx_v_G); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_11ueg_kernels_12build_K_opt(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nq, __Pyx_memviewslice __pyx_v_vqvec, double __pyx_v_vol, long __pyx_v_nbsf, PyObject *__pyx_v_kpq_i, PyObject *__pyx_v_kpq, PyObject *__pyx_v_pmq_i, PyObject *__pyx_v_pmq, __Pyx_memviewslice __pyx_v_G) { - PyArrayObject *__pyx_v_K = 0; - int __pyx_v_iq; - int __pyx_v_s; - int __pyx_v_idxjmq; - int __pyx_v_idxkpq; - int __pyx_v_idxk; - int __pyx_v_idxjpq; - int __pyx_v_idxj; - int __pyx_v_idxpmq; - int __pyx_v_idxp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - long __pyx_t_6; - long __pyx_t_7; - int __pyx_t_8; - Py_ssize_t __pyx_t_9; - PyObject *(*__pyx_t_10)(PyObject *); - PyObject *__pyx_t_11 = NULL; - PyObject *(*__pyx_t_12)(PyObject *); - int __pyx_t_13; - int __pyx_t_14; - Py_ssize_t __pyx_t_15; - PyObject *(*__pyx_t_16)(PyObject *); - PyObject *__pyx_t_17 = NULL; - double __pyx_t_18; - Py_ssize_t __pyx_t_19; - Py_ssize_t __pyx_t_20; - Py_ssize_t __pyx_t_21; - Py_ssize_t __pyx_t_22; - __pyx_t_double_complex __pyx_t_23; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("build_K_opt", 0); - - /* "ueg_kernels.pyx":158 - * double complex[:,:,:] G): - * - * cdef numpy.ndarray K = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) # <<<<<<<<<<<<<< - * cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_From_long(__pyx_v_nbsf); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyList_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_int_2); - __Pyx_GIVEREF(__pyx_int_2); - PyList_SET_ITEM(__pyx_t_4, 0, __pyx_int_2); - __Pyx_GIVEREF(__pyx_t_1); - PyList_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_3); - PyList_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DTYPE_CX); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 158, __pyx_L1_error) - __pyx_v_K = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":161 - * cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp - * - * for s in range(2): # <<<<<<<<<<<<<< - * for iq in range(nq): - * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): - */ - for (__pyx_t_5 = 0; __pyx_t_5 < 2; __pyx_t_5+=1) { - __pyx_v_s = __pyx_t_5; - - /* "ueg_kernels.pyx":162 - * - * for s in range(2): - * for iq in range(nq): # <<<<<<<<<<<<<< - * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): - * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - */ - __pyx_t_6 = __pyx_v_nq; - __pyx_t_7 = __pyx_t_6; - for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { - __pyx_v_iq = __pyx_t_8; - - /* "ueg_kernels.pyx":163 - * for s in range(2): - * for iq in range(nq): - * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): # <<<<<<<<<<<<<< - * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - */ - if (unlikely(__pyx_v_pmq == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 163, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_pmq, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (unlikely(__pyx_v_pmq_i == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 163, __pyx_L1_error) - } - __pyx_t_4 = __Pyx_GetItemInt_List(__pyx_v_pmq_i, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4); - __pyx_t_1 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (likely(PyList_CheckExact(__pyx_t_4)) || PyTuple_CheckExact(__pyx_t_4)) { - __pyx_t_3 = __pyx_t_4; __Pyx_INCREF(__pyx_t_3); __pyx_t_9 = 0; - __pyx_t_10 = NULL; - } else { - __pyx_t_9 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 163, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - for (;;) { - if (likely(!__pyx_t_10)) { - if (likely(PyList_CheckExact(__pyx_t_3))) { - if (__pyx_t_9 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_9); __Pyx_INCREF(__pyx_t_4); __pyx_t_9++; if (unlikely(0 < 0)) __PYX_ERR(0, 163, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - if (__pyx_t_9 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_9); __Pyx_INCREF(__pyx_t_4); __pyx_t_9++; if (unlikely(0 < 0)) __PYX_ERR(0, 163, __pyx_L1_error) - #else - __pyx_t_4 = PySequence_ITEM(__pyx_t_3, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } - } else { - __pyx_t_4 = __pyx_t_10(__pyx_t_3); - if (unlikely(!__pyx_t_4)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 163, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_4); - } - if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { - PyObject* sequence = __pyx_t_4; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 163, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_11 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_12 = Py_TYPE(__pyx_t_11)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_12(__pyx_t_11); if (unlikely(!__pyx_t_1)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_2 = __pyx_t_12(__pyx_t_11); if (unlikely(!__pyx_t_2)) goto __pyx_L9_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_11), 2) < 0) __PYX_ERR(0, 163, __pyx_L1_error) - __pyx_t_12 = NULL; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - goto __pyx_L10_unpacking_done; - __pyx_L9_unpacking_failed:; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_12 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 163, __pyx_L1_error) - __pyx_L10_unpacking_done:; - } - __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_idxjmq = __pyx_t_13; - __pyx_v_idxj = __pyx_t_14; - - /* "ueg_kernels.pyx":164 - * for iq in range(nq): - * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): - * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): # <<<<<<<<<<<<<< - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - */ - if (unlikely(__pyx_v_kpq == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 164, __pyx_L1_error) - } - __pyx_t_4 = __Pyx_GetItemInt_List(__pyx_v_kpq, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (unlikely(__pyx_v_kpq_i == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 164, __pyx_L1_error) - } - __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_v_kpq_i, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); - __pyx_t_4 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { - __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); __pyx_t_15 = 0; - __pyx_t_16 = NULL; - } else { - __pyx_t_15 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_16 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 164, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - for (;;) { - if (likely(!__pyx_t_16)) { - if (likely(PyList_CheckExact(__pyx_t_1))) { - if (__pyx_t_15 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_15); __Pyx_INCREF(__pyx_t_2); __pyx_t_15++; if (unlikely(0 < 0)) __PYX_ERR(0, 164, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_15); __pyx_t_15++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - if (__pyx_t_15 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_15); __Pyx_INCREF(__pyx_t_2); __pyx_t_15++; if (unlikely(0 < 0)) __PYX_ERR(0, 164, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_1, __pyx_t_15); __pyx_t_15++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } - } else { - __pyx_t_2 = __pyx_t_16(__pyx_t_1); - if (unlikely(!__pyx_t_2)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 164, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_2); - } - if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { - PyObject* sequence = __pyx_t_2; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 164, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_4 = PyList_GET_ITEM(sequence, 0); - __pyx_t_11 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_11); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_11 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_17 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_17); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_12 = Py_TYPE(__pyx_t_17)->tp_iternext; - index = 0; __pyx_t_4 = __pyx_t_12(__pyx_t_17); if (unlikely(!__pyx_t_4)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - index = 1; __pyx_t_11 = __pyx_t_12(__pyx_t_17); if (unlikely(!__pyx_t_11)) goto __pyx_L13_unpacking_failed; - __Pyx_GOTREF(__pyx_t_11); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_17), 2) < 0) __PYX_ERR(0, 164, __pyx_L1_error) - __pyx_t_12 = NULL; - __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; - goto __pyx_L14_unpacking_done; - __pyx_L13_unpacking_failed:; - __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; - __pyx_t_12 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 164, __pyx_L1_error) - __pyx_L14_unpacking_done:; - } - __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_t_4); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_11); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 164, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_v_idxkpq = __pyx_t_14; - __pyx_v_idxk = __pyx_t_13; - - /* "ueg_kernels.pyx":165 - * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): - * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] # <<<<<<<<<<<<<< - * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): - */ - __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_s); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_11 = __Pyx_PyInt_From_int(__pyx_v_idxj); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_idxkpq); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_17 = PyTuple_New(3); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_17); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_17, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_17, 1, __pyx_t_11); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_17, 2, __pyx_t_4); - __pyx_t_2 = 0; - __pyx_t_11 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_K), __pyx_t_17); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_18 = (2.0 * __pyx_v_vol); - if (unlikely(__pyx_t_18 == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 165, __pyx_L1_error) - } - __pyx_t_19 = __pyx_v_iq; - __pyx_t_13 = -1; - if (__pyx_t_19 < 0) { - __pyx_t_19 += __pyx_v_vqvec.shape[0]; - if (unlikely(__pyx_t_19 < 0)) __pyx_t_13 = 0; - } else if (unlikely(__pyx_t_19 >= __pyx_v_vqvec.shape[0])) __pyx_t_13 = 0; - if (unlikely(__pyx_t_13 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_13); - __PYX_ERR(0, 165, __pyx_L1_error) - } - __pyx_t_20 = __pyx_v_s; - __pyx_t_21 = __pyx_v_idxjmq; - __pyx_t_22 = __pyx_v_idxk; - __pyx_t_13 = -1; - if (__pyx_t_20 < 0) { - __pyx_t_20 += __pyx_v_G.shape[0]; - if (unlikely(__pyx_t_20 < 0)) __pyx_t_13 = 0; - } else if (unlikely(__pyx_t_20 >= __pyx_v_G.shape[0])) __pyx_t_13 = 0; - if (__pyx_t_21 < 0) { - __pyx_t_21 += __pyx_v_G.shape[1]; - if (unlikely(__pyx_t_21 < 0)) __pyx_t_13 = 1; - } else if (unlikely(__pyx_t_21 >= __pyx_v_G.shape[1])) __pyx_t_13 = 1; - if (__pyx_t_22 < 0) { - __pyx_t_22 += __pyx_v_G.shape[2]; - if (unlikely(__pyx_t_22 < 0)) __pyx_t_13 = 2; - } else if (unlikely(__pyx_t_22 >= __pyx_v_G.shape[2])) __pyx_t_13 = 2; - if (unlikely(__pyx_t_13 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_13); - __PYX_ERR(0, 165, __pyx_L1_error) - } - __pyx_t_23 = __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(((-(1.0 / __pyx_t_18)) * (*((double *) ( /* dim=0 */ (__pyx_v_vqvec.data + __pyx_t_19 * __pyx_v_vqvec.strides[0]) )))), 0), (*((__pyx_t_double_complex *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_20 * __pyx_v_G.strides[0]) ) + __pyx_t_21 * __pyx_v_G.strides[1]) ) + __pyx_t_22 * __pyx_v_G.strides[2]) )))); - __pyx_t_11 = __pyx_PyComplex_FromComplex(__pyx_t_23); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_4, __pyx_t_11); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_K), __pyx_t_17, __pyx_t_2) < 0)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; - - /* "ueg_kernels.pyx":164 - * for iq in range(nq): - * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): - * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): # <<<<<<<<<<<<<< - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":163 - * for s in range(2): - * for iq in range(nq): - * for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): # <<<<<<<<<<<<<< - * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":166 - * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): # <<<<<<<<<<<<<< - * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): - * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] - */ - if (unlikely(__pyx_v_kpq == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 166, __pyx_L1_error) - } - __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_kpq, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (unlikely(__pyx_v_kpq_i == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 166, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_kpq_i, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_17 = PyTuple_New(2); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_17); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_17, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_17, 1, __pyx_t_1); - __pyx_t_3 = 0; - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_17, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; - if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { - __pyx_t_17 = __pyx_t_1; __Pyx_INCREF(__pyx_t_17); __pyx_t_9 = 0; - __pyx_t_10 = NULL; - } else { - __pyx_t_9 = -1; __pyx_t_17 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_17); - __pyx_t_10 = Py_TYPE(__pyx_t_17)->tp_iternext; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 166, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - for (;;) { - if (likely(!__pyx_t_10)) { - if (likely(PyList_CheckExact(__pyx_t_17))) { - if (__pyx_t_9 >= PyList_GET_SIZE(__pyx_t_17)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyList_GET_ITEM(__pyx_t_17, __pyx_t_9); __Pyx_INCREF(__pyx_t_1); __pyx_t_9++; if (unlikely(0 < 0)) __PYX_ERR(0, 166, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_17, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } else { - if (__pyx_t_9 >= PyTuple_GET_SIZE(__pyx_t_17)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_17, __pyx_t_9); __Pyx_INCREF(__pyx_t_1); __pyx_t_9++; if (unlikely(0 < 0)) __PYX_ERR(0, 166, __pyx_L1_error) - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_17, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - #endif - } - } else { - __pyx_t_1 = __pyx_t_10(__pyx_t_17); - if (unlikely(!__pyx_t_1)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 166, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_1); - } - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 166, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_3 = PyList_GET_ITEM(sequence, 0); - __pyx_t_2 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_11 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_12 = Py_TYPE(__pyx_t_11)->tp_iternext; - index = 0; __pyx_t_3 = __pyx_t_12(__pyx_t_11); if (unlikely(!__pyx_t_3)) goto __pyx_L17_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 1; __pyx_t_2 = __pyx_t_12(__pyx_t_11); if (unlikely(!__pyx_t_2)) goto __pyx_L17_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_11), 2) < 0) __PYX_ERR(0, 166, __pyx_L1_error) - __pyx_t_12 = NULL; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - goto __pyx_L18_unpacking_done; - __pyx_L17_unpacking_failed:; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_t_12 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 166, __pyx_L1_error) - __pyx_L18_unpacking_done:; - } - __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_t_2); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_idxjpq = __pyx_t_13; - __pyx_v_idxj = __pyx_t_14; - - /* "ueg_kernels.pyx":167 - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): # <<<<<<<<<<<<<< - * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] - * return K - */ - if (unlikely(__pyx_v_pmq == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 167, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_List(__pyx_v_pmq, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (unlikely(__pyx_v_pmq_i == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 167, __pyx_L1_error) - } - __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_v_pmq_i, __pyx_v_iq, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { - __pyx_t_3 = __pyx_t_2; __Pyx_INCREF(__pyx_t_3); __pyx_t_15 = 0; - __pyx_t_16 = NULL; - } else { - __pyx_t_15 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_16 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 167, __pyx_L1_error) - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - for (;;) { - if (likely(!__pyx_t_16)) { - if (likely(PyList_CheckExact(__pyx_t_3))) { - if (__pyx_t_15 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_15); __Pyx_INCREF(__pyx_t_2); __pyx_t_15++; if (unlikely(0 < 0)) __PYX_ERR(0, 167, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_15); __pyx_t_15++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } else { - if (__pyx_t_15 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_15); __Pyx_INCREF(__pyx_t_2); __pyx_t_15++; if (unlikely(0 < 0)) __PYX_ERR(0, 167, __pyx_L1_error) - #else - __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_15); __pyx_t_15++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - #endif - } - } else { - __pyx_t_2 = __pyx_t_16(__pyx_t_3); - if (unlikely(!__pyx_t_2)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(0, 167, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_2); - } - if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { - PyObject* sequence = __pyx_t_2; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 167, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_1 = PyList_GET_ITEM(sequence, 0); - __pyx_t_11 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_11); - #else - __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_11 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_12 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_1 = __pyx_t_12(__pyx_t_4); if (unlikely(!__pyx_t_1)) goto __pyx_L21_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 1; __pyx_t_11 = __pyx_t_12(__pyx_t_4); if (unlikely(!__pyx_t_11)) goto __pyx_L21_unpacking_failed; - __Pyx_GOTREF(__pyx_t_11); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_4), 2) < 0) __PYX_ERR(0, 167, __pyx_L1_error) - __pyx_t_12 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L22_unpacking_done; - __pyx_L21_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_12 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 167, __pyx_L1_error) - __pyx_L22_unpacking_done:; - } - __pyx_t_14 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_13 = __Pyx_PyInt_As_int(__pyx_t_11); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __pyx_v_idxpmq = __pyx_t_14; - __pyx_v_idxp = __pyx_t_13; - - /* "ueg_kernels.pyx":168 - * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): - * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] # <<<<<<<<<<<<<< - * return K - */ - __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_s); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_11 = __Pyx_PyInt_From_int(__pyx_v_idxj); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_idxpmq); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_11); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_1); - __pyx_t_2 = 0; - __pyx_t_11 = 0; - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_K), __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_18 = (2.0 * __pyx_v_vol); - if (unlikely(__pyx_t_18 == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division"); - __PYX_ERR(0, 168, __pyx_L1_error) - } - __pyx_t_22 = __pyx_v_iq; - __pyx_t_13 = -1; - if (__pyx_t_22 < 0) { - __pyx_t_22 += __pyx_v_vqvec.shape[0]; - if (unlikely(__pyx_t_22 < 0)) __pyx_t_13 = 0; - } else if (unlikely(__pyx_t_22 >= __pyx_v_vqvec.shape[0])) __pyx_t_13 = 0; - if (unlikely(__pyx_t_13 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_13); - __PYX_ERR(0, 168, __pyx_L1_error) - } - __pyx_t_21 = __pyx_v_s; - __pyx_t_20 = __pyx_v_idxjpq; - __pyx_t_19 = __pyx_v_idxp; - __pyx_t_13 = -1; - if (__pyx_t_21 < 0) { - __pyx_t_21 += __pyx_v_G.shape[0]; - if (unlikely(__pyx_t_21 < 0)) __pyx_t_13 = 0; - } else if (unlikely(__pyx_t_21 >= __pyx_v_G.shape[0])) __pyx_t_13 = 0; - if (__pyx_t_20 < 0) { - __pyx_t_20 += __pyx_v_G.shape[1]; - if (unlikely(__pyx_t_20 < 0)) __pyx_t_13 = 1; - } else if (unlikely(__pyx_t_20 >= __pyx_v_G.shape[1])) __pyx_t_13 = 1; - if (__pyx_t_19 < 0) { - __pyx_t_19 += __pyx_v_G.shape[2]; - if (unlikely(__pyx_t_19 < 0)) __pyx_t_13 = 2; - } else if (unlikely(__pyx_t_19 >= __pyx_v_G.shape[2])) __pyx_t_13 = 2; - if (unlikely(__pyx_t_13 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_13); - __PYX_ERR(0, 168, __pyx_L1_error) - } - __pyx_t_23 = __Pyx_c_prod_double(__pyx_t_double_complex_from_parts(((-(1.0 / __pyx_t_18)) * (*((double *) ( /* dim=0 */ (__pyx_v_vqvec.data + __pyx_t_22 * __pyx_v_vqvec.strides[0]) )))), 0), (*((__pyx_t_double_complex *) ( /* dim=2 */ (( /* dim=1 */ (( /* dim=0 */ (__pyx_v_G.data + __pyx_t_21 * __pyx_v_G.strides[0]) ) + __pyx_t_20 * __pyx_v_G.strides[1]) ) + __pyx_t_19 * __pyx_v_G.strides[2]) )))); - __pyx_t_11 = __pyx_PyComplex_FromComplex(__pyx_t_23); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_2 = PyNumber_InPlaceAdd(__pyx_t_1, __pyx_t_11); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_K), __pyx_t_4, __pyx_t_2) < 0)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "ueg_kernels.pyx":167 - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): # <<<<<<<<<<<<<< - * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] - * return K - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "ueg_kernels.pyx":166 - * for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - * K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - * for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): # <<<<<<<<<<<<<< - * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): - * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] - */ - } - __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; - } - } - - /* "ueg_kernels.pyx":169 - * for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): - * K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] - * return K # <<<<<<<<<<<<<< - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_K)); - __pyx_r = ((PyObject *)__pyx_v_K); - goto __pyx_L0; - - /* "ueg_kernels.pyx":154 - * return J - * - * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< - * list kpq, list pmq_i, list pmq, - * double complex[:,:,:] G): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_17); - __Pyx_AddTraceback("ueg_kernels.build_K_opt", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_K); - __PYX_XDEC_MEMVIEW(&__pyx_v_vqvec, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_G, 1); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":734 - * ctypedef npy_cdouble complex_t - * - * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(1, a) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":735 - * - * cdef inline object PyArray_MultiIterNew1(a): - * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew2(a, b): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 735, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":734 - * ctypedef npy_cdouble complex_t - * - * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(1, a) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":737 - * return PyArray_MultiIterNew(1, a) - * - * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(2, a, b) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":738 - * - * cdef inline object PyArray_MultiIterNew2(a, b): - * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 738, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":737 - * return PyArray_MultiIterNew(1, a) - * - * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(2, a, b) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":740 - * return PyArray_MultiIterNew(2, a, b) - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(3, a, b, c) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":741 - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 741, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":740 - * return PyArray_MultiIterNew(2, a, b) - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(3, a, b, c) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":743 - * return PyArray_MultiIterNew(3, a, b, c) - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(4, a, b, c, d) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":744 - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): - * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 744, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":743 - * return PyArray_MultiIterNew(3, a, b, c) - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(4, a, b, c, d) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":746 - * return PyArray_MultiIterNew(4, a, b, c, d) - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":747 - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): - * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< - * - * cdef inline tuple PyDataType_SHAPE(dtype d): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 747, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":746 - * return PyArray_MultiIterNew(4, a, b, c, d) - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":749 - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< - * if PyDataType_HASSUBARRAY(d): - * return d.subarray.shape - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("PyDataType_SHAPE", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":750 - * - * cdef inline tuple PyDataType_SHAPE(dtype d): - * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< - * return d.subarray.shape - * else: - */ - __pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0); - if (__pyx_t_1) { - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":751 - * cdef inline tuple PyDataType_SHAPE(dtype d): - * if PyDataType_HASSUBARRAY(d): - * return d.subarray.shape # <<<<<<<<<<<<<< - * else: - * return () - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape)); - __pyx_r = ((PyObject*)__pyx_v_d->subarray->shape); - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":750 - * - * cdef inline tuple PyDataType_SHAPE(dtype d): - * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< - * return d.subarray.shape - * else: - */ - } - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":753 - * return d.subarray.shape - * else: - * return () # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_empty_tuple); - __pyx_r = __pyx_empty_tuple; - goto __pyx_L0; - } - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":749 - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< - * if PyDataType_HASSUBARRAY(d): - * return d.subarray.shape - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":928 - * int _import_umath() except -1 - * - * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< - * Py_INCREF(base) # important to do this before stealing the reference below! - * PyArray_SetBaseObject(arr, base) - */ - -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("set_array_base", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":929 - * - * cdef inline void set_array_base(ndarray arr, object base): - * Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<< - * PyArray_SetBaseObject(arr, base) - * - */ - Py_INCREF(__pyx_v_base); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":930 - * cdef inline void set_array_base(ndarray arr, object base): - * Py_INCREF(base) # important to do this before stealing the reference below! - * PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<< - * - * cdef inline object get_array_base(ndarray arr): - */ - (void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base)); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":928 - * int _import_umath() except -1 - * - * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< - * Py_INCREF(base) # important to do this before stealing the reference below! - * PyArray_SetBaseObject(arr, base) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":932 - * PyArray_SetBaseObject(arr, base) - * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * base = PyArray_BASE(arr) - * if base is NULL: - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { - PyObject *__pyx_v_base; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":933 - * - * cdef inline object get_array_base(ndarray arr): - * base = PyArray_BASE(arr) # <<<<<<<<<<<<<< - * if base is NULL: - * return None - */ - __pyx_v_base = PyArray_BASE(__pyx_v_arr); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":934 - * cdef inline object get_array_base(ndarray arr): - * base = PyArray_BASE(arr) - * if base is NULL: # <<<<<<<<<<<<<< - * return None - * return base - */ - __pyx_t_1 = ((__pyx_v_base == NULL) != 0); - if (__pyx_t_1) { - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":935 - * base = PyArray_BASE(arr) - * if base is NULL: - * return None # <<<<<<<<<<<<<< - * return base - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":934 - * cdef inline object get_array_base(ndarray arr): - * base = PyArray_BASE(arr) - * if base is NULL: # <<<<<<<<<<<<<< - * return None - * return base - */ - } - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":936 - * if base is NULL: - * return None - * return base # <<<<<<<<<<<<<< - * - * # Versions of the import_* functions which are more suitable for - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_base)); - __pyx_r = ((PyObject *)__pyx_v_base); - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":932 - * PyArray_SetBaseObject(arr, base) - * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * base = PyArray_BASE(arr) - * if base is NULL: - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":940 - * # Versions of the import_* functions which are more suitable for - * # Cython code. - * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< - * try: - * __pyx_import_array() - */ - -static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("import_array", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":941 - * # Cython code. - * cdef inline int import_array() except -1: - * try: # <<<<<<<<<<<<<< - * __pyx_import_array() - * except Exception: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - /*try:*/ { - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":942 - * cdef inline int import_array() except -1: - * try: - * __pyx_import_array() # <<<<<<<<<<<<<< - * except Exception: - * raise ImportError("numpy.core.multiarray failed to import") - */ - __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 942, __pyx_L3_error) - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":941 - * # Cython code. - * cdef inline int import_array() except -1: - * try: # <<<<<<<<<<<<<< - * __pyx_import_array() - * except Exception: - */ - } - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_try_end; - __pyx_L3_error:; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":943 - * try: - * __pyx_import_array() - * except Exception: # <<<<<<<<<<<<<< - * raise ImportError("numpy.core.multiarray failed to import") - * - */ - __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); - if (__pyx_t_4) { - __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 943, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":944 - * __pyx_import_array() - * except Exception: - * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< - * - * cdef inline int import_umath() except -1: - */ - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 944, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __PYX_ERR(1, 944, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":941 - * # Cython code. - * cdef inline int import_array() except -1: - * try: # <<<<<<<<<<<<<< - * __pyx_import_array() - * except Exception: - */ - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L1_error; - __pyx_L8_try_end:; - } - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":940 - * # Versions of the import_* functions which are more suitable for - * # Cython code. - * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< - * try: - * __pyx_import_array() - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":946 - * raise ImportError("numpy.core.multiarray failed to import") - * - * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< - * try: - * _import_umath() - */ - -static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("import_umath", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":947 - * - * cdef inline int import_umath() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - /*try:*/ { - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":948 - * cdef inline int import_umath() except -1: - * try: - * _import_umath() # <<<<<<<<<<<<<< - * except Exception: - * raise ImportError("numpy.core.umath failed to import") - */ - __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 948, __pyx_L3_error) - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":947 - * - * cdef inline int import_umath() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - } - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_try_end; - __pyx_L3_error:; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":949 - * try: - * _import_umath() - * except Exception: # <<<<<<<<<<<<<< - * raise ImportError("numpy.core.umath failed to import") - * - */ - __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); - if (__pyx_t_4) { - __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 949, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":950 - * _import_umath() - * except Exception: - * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< - * - * cdef inline int import_ufunc() except -1: - */ - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 950, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __PYX_ERR(1, 950, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":947 - * - * cdef inline int import_umath() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L1_error; - __pyx_L8_try_end:; - } - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":946 - * raise ImportError("numpy.core.multiarray failed to import") - * - * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< - * try: - * _import_umath() - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":952 - * raise ImportError("numpy.core.umath failed to import") - * - * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< - * try: - * _import_umath() - */ - -static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("import_ufunc", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":953 - * - * cdef inline int import_ufunc() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - /*try:*/ { - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":954 - * cdef inline int import_ufunc() except -1: - * try: - * _import_umath() # <<<<<<<<<<<<<< - * except Exception: - * raise ImportError("numpy.core.umath failed to import") - */ - __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 954, __pyx_L3_error) - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":953 - * - * cdef inline int import_ufunc() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - } - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_try_end; - __pyx_L3_error:; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":955 - * try: - * _import_umath() - * except Exception: # <<<<<<<<<<<<<< - * raise ImportError("numpy.core.umath failed to import") - * - */ - __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); - if (__pyx_t_4) { - __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 955, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":956 - * _import_umath() - * except Exception: - * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< - * - * cdef extern from *: - */ - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 956, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __PYX_ERR(1, 956, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":953 - * - * cdef inline int import_ufunc() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L1_error; - __pyx_L8_try_end:; - } - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":952 - * raise ImportError("numpy.core.umath failed to import") - * - * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< - * try: - * _import_umath() - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":966 - * - * - * cdef inline bint is_timedelta64_object(object obj): # <<<<<<<<<<<<<< - * """ - * Cython equivalent of `isinstance(obj, np.timedelta64)` - */ - -static CYTHON_INLINE int __pyx_f_5numpy_is_timedelta64_object(PyObject *__pyx_v_obj) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("is_timedelta64_object", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":978 - * bool - * """ - * return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = PyObject_TypeCheck(__pyx_v_obj, (&PyTimedeltaArrType_Type)); - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":966 - * - * - * cdef inline bint is_timedelta64_object(object obj): # <<<<<<<<<<<<<< - * """ - * Cython equivalent of `isinstance(obj, np.timedelta64)` - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":981 - * - * - * cdef inline bint is_datetime64_object(object obj): # <<<<<<<<<<<<<< - * """ - * Cython equivalent of `isinstance(obj, np.datetime64)` - */ - -static CYTHON_INLINE int __pyx_f_5numpy_is_datetime64_object(PyObject *__pyx_v_obj) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("is_datetime64_object", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":993 - * bool - * """ - * return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = PyObject_TypeCheck(__pyx_v_obj, (&PyDatetimeArrType_Type)); - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":981 - * - * - * cdef inline bint is_datetime64_object(object obj): # <<<<<<<<<<<<<< - * """ - * Cython equivalent of `isinstance(obj, np.datetime64)` - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":996 - * - * - * cdef inline npy_datetime get_datetime64_value(object obj) nogil: # <<<<<<<<<<<<<< - * """ - * returns the int64 value underlying scalar numpy datetime64 object - */ - -static CYTHON_INLINE npy_datetime __pyx_f_5numpy_get_datetime64_value(PyObject *__pyx_v_obj) { - npy_datetime __pyx_r; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1003 - * also needed. That can be found using `get_datetime64_unit`. - * """ - * return (obj).obval # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = ((PyDatetimeScalarObject *)__pyx_v_obj)->obval; - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":996 - * - * - * cdef inline npy_datetime get_datetime64_value(object obj) nogil: # <<<<<<<<<<<<<< - * """ - * returns the int64 value underlying scalar numpy datetime64 object - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1006 - * - * - * cdef inline npy_timedelta get_timedelta64_value(object obj) nogil: # <<<<<<<<<<<<<< - * """ - * returns the int64 value underlying scalar numpy timedelta64 object - */ - -static CYTHON_INLINE npy_timedelta __pyx_f_5numpy_get_timedelta64_value(PyObject *__pyx_v_obj) { - npy_timedelta __pyx_r; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1010 - * returns the int64 value underlying scalar numpy timedelta64 object - * """ - * return (obj).obval # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = ((PyTimedeltaScalarObject *)__pyx_v_obj)->obval; - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1006 - * - * - * cdef inline npy_timedelta get_timedelta64_value(object obj) nogil: # <<<<<<<<<<<<<< - * """ - * returns the int64 value underlying scalar numpy timedelta64 object - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1013 - * - * - * cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil: # <<<<<<<<<<<<<< - * """ - * returns the unit part of the dtype for a numpy datetime64 object. - */ - -static CYTHON_INLINE NPY_DATETIMEUNIT __pyx_f_5numpy_get_datetime64_unit(PyObject *__pyx_v_obj) { - NPY_DATETIMEUNIT __pyx_r; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1017 - * returns the unit part of the dtype for a numpy datetime64 object. - * """ - * return (obj).obmeta.base # <<<<<<<<<<<<<< - */ - __pyx_r = ((NPY_DATETIMEUNIT)((PyDatetimeScalarObject *)__pyx_v_obj)->obmeta.base); - goto __pyx_L0; - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":1013 - * - * - * cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil: # <<<<<<<<<<<<<< - * """ - * returns the unit part of the dtype for a numpy datetime64 object. - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":123 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - -/* Python wrapper */ -static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_shape = 0; - Py_ssize_t __pyx_v_itemsize; - PyObject *__pyx_v_format = 0; - PyObject *__pyx_v_mode = 0; - int __pyx_v_allocate_buffer; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; - PyObject* values[5] = {0,0,0,0,0}; - values[3] = ((PyObject *)__pyx_n_s_c); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(2, 123, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(2, 123, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mode); - if (value) { values[3] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 4: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_allocate_buffer); - if (value) { values[4] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(2, 123, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_shape = ((PyObject*)values[0]); - __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 123, __pyx_L3_error) - __pyx_v_format = values[2]; - __pyx_v_mode = values[3]; - if (values[4]) { - __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 124, __pyx_L3_error) - } else { - - /* "View.MemoryView":124 - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, - * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< - * - * cdef int idx - */ - __pyx_v_allocate_buffer = ((int)1); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 123, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) __PYX_ERR(2, 123, __pyx_L1_error) - if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { - PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(2, 123, __pyx_L1_error) - } - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); - - /* "View.MemoryView":123 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { - int __pyx_v_idx; - Py_ssize_t __pyx_v_i; - Py_ssize_t __pyx_v_dim; - PyObject **__pyx_v_p; - char __pyx_v_order; - int __pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - char *__pyx_t_7; - int __pyx_t_8; - Py_ssize_t __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - Py_ssize_t __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - __Pyx_INCREF(__pyx_v_format); - - /* "View.MemoryView":130 - * cdef PyObject **p - * - * self.ndim = len(shape) # <<<<<<<<<<<<<< - * self.itemsize = itemsize - * - */ - if (unlikely(__pyx_v_shape == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(2, 130, __pyx_L1_error) - } - __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(2, 130, __pyx_L1_error) - __pyx_v_self->ndim = ((int)__pyx_t_1); - - /* "View.MemoryView":131 - * - * self.ndim = len(shape) - * self.itemsize = itemsize # <<<<<<<<<<<<<< - * - * if not self.ndim: - */ - __pyx_v_self->itemsize = __pyx_v_itemsize; - - /* "View.MemoryView":133 - * self.itemsize = itemsize - * - * if not self.ndim: # <<<<<<<<<<<<<< - * raise ValueError("Empty shape tuple for cython.array") - * - */ - __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":134 - * - * if not self.ndim: - * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< - * - * if itemsize <= 0: - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 134, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(2, 134, __pyx_L1_error) - - /* "View.MemoryView":133 - * self.itemsize = itemsize - * - * if not self.ndim: # <<<<<<<<<<<<<< - * raise ValueError("Empty shape tuple for cython.array") - * - */ - } - - /* "View.MemoryView":136 - * raise ValueError("Empty shape tuple for cython.array") - * - * if itemsize <= 0: # <<<<<<<<<<<<<< - * raise ValueError("itemsize <= 0 for cython.array") - * - */ - __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":137 - * - * if itemsize <= 0: - * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< - * - * if not isinstance(format, bytes): - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 137, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(2, 137, __pyx_L1_error) - - /* "View.MemoryView":136 - * raise ValueError("Empty shape tuple for cython.array") - * - * if itemsize <= 0: # <<<<<<<<<<<<<< - * raise ValueError("itemsize <= 0 for cython.array") - * - */ - } - - /* "View.MemoryView":139 - * raise ValueError("itemsize <= 0 for cython.array") - * - * if not isinstance(format, bytes): # <<<<<<<<<<<<<< - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - */ - __pyx_t_2 = PyBytes_Check(__pyx_v_format); - __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":140 - * - * if not isinstance(format, bytes): - * format = format.encode('ASCII') # <<<<<<<<<<<<<< - * self._format = format # keep a reference to the byte string - * self.format = self._format - */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 140, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - } - } - __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_n_s_ASCII) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_n_s_ASCII); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 140, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":139 - * raise ValueError("itemsize <= 0 for cython.array") - * - * if not isinstance(format, bytes): # <<<<<<<<<<<<<< - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - */ - } - - /* "View.MemoryView":141 - * if not isinstance(format, bytes): - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< - * self.format = self._format - * - */ - if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) __PYX_ERR(2, 141, __pyx_L1_error) - __pyx_t_3 = __pyx_v_format; - __Pyx_INCREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->_format); - __Pyx_DECREF(__pyx_v_self->_format); - __pyx_v_self->_format = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":142 - * format = format.encode('ASCII') - * self._format = format # keep a reference to the byte string - * self.format = self._format # <<<<<<<<<<<<<< - * - * - */ - if (unlikely(__pyx_v_self->_format == Py_None)) { - PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); - __PYX_ERR(2, 142, __pyx_L1_error) - } - __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(2, 142, __pyx_L1_error) - __pyx_v_self->format = __pyx_t_7; - - /* "View.MemoryView":145 - * - * - * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< - * self._strides = self._shape + self.ndim - * - */ - __pyx_v_self->_shape = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); - - /* "View.MemoryView":146 - * - * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) - * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< - * - * if not self._shape: - */ - __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); - - /* "View.MemoryView":148 - * self._strides = self._shape + self.ndim - * - * if not self._shape: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate shape and strides.") - * - */ - __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":149 - * - * if not self._shape: - * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 149, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(2, 149, __pyx_L1_error) - - /* "View.MemoryView":148 - * self._strides = self._shape + self.ndim - * - * if not self._shape: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate shape and strides.") - * - */ - } - - /* "View.MemoryView":152 - * - * - * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - */ - __pyx_t_8 = 0; - __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; - for (;;) { - if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_5); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(2, 152, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 152, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_5); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 152, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_dim = __pyx_t_9; - __pyx_v_idx = __pyx_t_8; - __pyx_t_8 = (__pyx_t_8 + 1); - - /* "View.MemoryView":153 - * - * for idx, dim in enumerate(shape): - * if dim <= 0: # <<<<<<<<<<<<<< - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim - */ - __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":154 - * for idx, dim in enumerate(shape): - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< - * self._shape[idx] = dim - * - */ - __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_6); - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(2, 154, __pyx_L1_error) - - /* "View.MemoryView":153 - * - * for idx, dim in enumerate(shape): - * if dim <= 0: # <<<<<<<<<<<<<< - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim - */ - } - - /* "View.MemoryView":155 - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - * self._shape[idx] = dim # <<<<<<<<<<<<<< - * - * cdef char order - */ - (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; - - /* "View.MemoryView":152 - * - * - * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< - * if dim <= 0: - * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":158 - * - * cdef char order - * if mode == 'fortran': # <<<<<<<<<<<<<< - * order = b'F' - * self.mode = u'fortran' - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(2, 158, __pyx_L1_error) - if (__pyx_t_4) { - - /* "View.MemoryView":159 - * cdef char order - * if mode == 'fortran': - * order = b'F' # <<<<<<<<<<<<<< - * self.mode = u'fortran' - * elif mode == 'c': - */ - __pyx_v_order = 'F'; - - /* "View.MemoryView":160 - * if mode == 'fortran': - * order = b'F' - * self.mode = u'fortran' # <<<<<<<<<<<<<< - * elif mode == 'c': - * order = b'C' - */ - __Pyx_INCREF(__pyx_n_u_fortran); - __Pyx_GIVEREF(__pyx_n_u_fortran); - __Pyx_GOTREF(__pyx_v_self->mode); - __Pyx_DECREF(__pyx_v_self->mode); - __pyx_v_self->mode = __pyx_n_u_fortran; - - /* "View.MemoryView":158 - * - * cdef char order - * if mode == 'fortran': # <<<<<<<<<<<<<< - * order = b'F' - * self.mode = u'fortran' - */ - goto __pyx_L10; - } - - /* "View.MemoryView":161 - * order = b'F' - * self.mode = u'fortran' - * elif mode == 'c': # <<<<<<<<<<<<<< - * order = b'C' - * self.mode = u'c' - */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(2, 161, __pyx_L1_error) - if (likely(__pyx_t_4)) { - - /* "View.MemoryView":162 - * self.mode = u'fortran' - * elif mode == 'c': - * order = b'C' # <<<<<<<<<<<<<< - * self.mode = u'c' - * else: - */ - __pyx_v_order = 'C'; - - /* "View.MemoryView":163 - * elif mode == 'c': - * order = b'C' - * self.mode = u'c' # <<<<<<<<<<<<<< - * else: - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) - */ - __Pyx_INCREF(__pyx_n_u_c); - __Pyx_GIVEREF(__pyx_n_u_c); - __Pyx_GOTREF(__pyx_v_self->mode); - __Pyx_DECREF(__pyx_v_self->mode); - __pyx_v_self->mode = __pyx_n_u_c; - - /* "View.MemoryView":161 - * order = b'F' - * self.mode = u'fortran' - * elif mode == 'c': # <<<<<<<<<<<<<< - * order = b'C' - * self.mode = u'c' - */ - goto __pyx_L10; - } - - /* "View.MemoryView":165 - * self.mode = u'c' - * else: - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< - * - * self.len = fill_contig_strides_array(self._shape, self._strides, - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(2, 165, __pyx_L1_error) - } - __pyx_L10:; - - /* "View.MemoryView":167 - * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) - * - * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< - * itemsize, self.ndim, order) - * - */ - __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); - - /* "View.MemoryView":170 - * itemsize, self.ndim, order) - * - * self.free_data = allocate_buffer # <<<<<<<<<<<<<< - * self.dtype_is_object = format == b'O' - * if allocate_buffer: - */ - __pyx_v_self->free_data = __pyx_v_allocate_buffer; - - /* "View.MemoryView":171 - * - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< - * if allocate_buffer: - * - */ - __pyx_t_10 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 171, __pyx_L1_error) - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 171, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_v_self->dtype_is_object = __pyx_t_4; - - /* "View.MemoryView":172 - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' - * if allocate_buffer: # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_4 = (__pyx_v_allocate_buffer != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":175 - * - * - * self.data = malloc(self.len) # <<<<<<<<<<<<<< - * if not self.data: - * raise MemoryError("unable to allocate array data.") - */ - __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); - - /* "View.MemoryView":176 - * - * self.data = malloc(self.len) - * if not self.data: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate array data.") - * - */ - __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":177 - * self.data = malloc(self.len) - * if not self.data: - * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< - * - * if self.dtype_is_object: - */ - __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(2, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __PYX_ERR(2, 177, __pyx_L1_error) - - /* "View.MemoryView":176 - * - * self.data = malloc(self.len) - * if not self.data: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate array data.") - * - */ - } - - /* "View.MemoryView":179 - * raise MemoryError("unable to allocate array data.") - * - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * p = self.data - * for i in range(self.len / itemsize): - */ - __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":180 - * - * if self.dtype_is_object: - * p = self.data # <<<<<<<<<<<<<< - * for i in range(self.len / itemsize): - * p[i] = Py_None - */ - __pyx_v_p = ((PyObject **)__pyx_v_self->data); - - /* "View.MemoryView":181 - * if self.dtype_is_object: - * p = self.data - * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< - * p[i] = Py_None - * Py_INCREF(Py_None) - */ - if (unlikely(__pyx_v_itemsize == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - __PYX_ERR(2, 181, __pyx_L1_error) - } - else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { - PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); - __PYX_ERR(2, 181, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); - __pyx_t_9 = __pyx_t_1; - for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { - __pyx_v_i = __pyx_t_11; - - /* "View.MemoryView":182 - * p = self.data - * for i in range(self.len / itemsize): - * p[i] = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - (__pyx_v_p[__pyx_v_i]) = Py_None; - - /* "View.MemoryView":183 - * for i in range(self.len / itemsize): - * p[i] = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - Py_INCREF(Py_None); - } - - /* "View.MemoryView":179 - * raise MemoryError("unable to allocate array data.") - * - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * p = self.data - * for i in range(self.len / itemsize): - */ - } - - /* "View.MemoryView":172 - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' - * if allocate_buffer: # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":123 - * cdef bint dtype_is_object - * - * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< - * mode="c", bint allocate_buffer=True): - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_format); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":186 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * cdef int bufmode = -1 - * if self.mode == u"c": - */ - -/* Python wrapper */ -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_bufmode; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - char *__pyx_t_4; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - Py_ssize_t *__pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - if (__pyx_v_info == NULL) { - PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); - return -1; - } - __Pyx_RefNannySetupContext("__getbuffer__", 0); - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - - /* "View.MemoryView":187 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 # <<<<<<<<<<<<<< - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - */ - __pyx_v_bufmode = -1; - - /* "View.MemoryView":188 - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 - * if self.mode == u"c": # <<<<<<<<<<<<<< - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - */ - __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 188, __pyx_L1_error) - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":189 - * cdef int bufmode = -1 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - */ - __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); - - /* "View.MemoryView":188 - * def __getbuffer__(self, Py_buffer *info, int flags): - * cdef int bufmode = -1 - * if self.mode == u"c": # <<<<<<<<<<<<<< - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - */ - goto __pyx_L3; - } - - /* "View.MemoryView":190 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": # <<<<<<<<<<<<<< - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - */ - __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(2, 190, __pyx_L1_error) - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":191 - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") - */ - __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); - - /* "View.MemoryView":190 - * if self.mode == u"c": - * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * elif self.mode == u"fortran": # <<<<<<<<<<<<<< - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - */ - } - __pyx_L3:; - - /* "View.MemoryView":192 - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): # <<<<<<<<<<<<<< - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - */ - __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":193 - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< - * info.buf = self.data - * info.len = self.len - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(2, 193, __pyx_L1_error) - - /* "View.MemoryView":192 - * elif self.mode == u"fortran": - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): # <<<<<<<<<<<<<< - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - */ - } - - /* "View.MemoryView":194 - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data # <<<<<<<<<<<<<< - * info.len = self.len - * info.ndim = self.ndim - */ - __pyx_t_4 = __pyx_v_self->data; - __pyx_v_info->buf = __pyx_t_4; - - /* "View.MemoryView":195 - * raise ValueError("Can only create a buffer that is contiguous in memory.") - * info.buf = self.data - * info.len = self.len # <<<<<<<<<<<<<< - * info.ndim = self.ndim - * info.shape = self._shape - */ - __pyx_t_5 = __pyx_v_self->len; - __pyx_v_info->len = __pyx_t_5; - - /* "View.MemoryView":196 - * info.buf = self.data - * info.len = self.len - * info.ndim = self.ndim # <<<<<<<<<<<<<< - * info.shape = self._shape - * info.strides = self._strides - */ - __pyx_t_6 = __pyx_v_self->ndim; - __pyx_v_info->ndim = __pyx_t_6; - - /* "View.MemoryView":197 - * info.len = self.len - * info.ndim = self.ndim - * info.shape = self._shape # <<<<<<<<<<<<<< - * info.strides = self._strides - * info.suboffsets = NULL - */ - __pyx_t_7 = __pyx_v_self->_shape; - __pyx_v_info->shape = __pyx_t_7; - - /* "View.MemoryView":198 - * info.ndim = self.ndim - * info.shape = self._shape - * info.strides = self._strides # <<<<<<<<<<<<<< - * info.suboffsets = NULL - * info.itemsize = self.itemsize - */ - __pyx_t_7 = __pyx_v_self->_strides; - __pyx_v_info->strides = __pyx_t_7; - - /* "View.MemoryView":199 - * info.shape = self._shape - * info.strides = self._strides - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * info.itemsize = self.itemsize - * info.readonly = 0 - */ - __pyx_v_info->suboffsets = NULL; - - /* "View.MemoryView":200 - * info.strides = self._strides - * info.suboffsets = NULL - * info.itemsize = self.itemsize # <<<<<<<<<<<<<< - * info.readonly = 0 - * - */ - __pyx_t_5 = __pyx_v_self->itemsize; - __pyx_v_info->itemsize = __pyx_t_5; - - /* "View.MemoryView":201 - * info.suboffsets = NULL - * info.itemsize = self.itemsize - * info.readonly = 0 # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - __pyx_v_info->readonly = 0; - - /* "View.MemoryView":203 - * info.readonly = 0 - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.format - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":204 - * - * if flags & PyBUF_FORMAT: - * info.format = self.format # <<<<<<<<<<<<<< - * else: - * info.format = NULL - */ - __pyx_t_4 = __pyx_v_self->format; - __pyx_v_info->format = __pyx_t_4; - - /* "View.MemoryView":203 - * info.readonly = 0 - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.format - * else: - */ - goto __pyx_L5; - } - - /* "View.MemoryView":206 - * info.format = self.format - * else: - * info.format = NULL # <<<<<<<<<<<<<< - * - * info.obj = self - */ - /*else*/ { - __pyx_v_info->format = NULL; - } - __pyx_L5:; - - /* "View.MemoryView":208 - * info.format = NULL - * - * info.obj = self # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - - /* "View.MemoryView":186 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * cdef int bufmode = -1 - * if self.mode == u"c": - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - __pyx_L2:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":212 - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - * - * def __dealloc__(array self): # <<<<<<<<<<<<<< - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - */ - -/* Python wrapper */ -static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":213 - * - * def __dealloc__(array self): - * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< - * self.callback_free_data(self.data) - * elif self.free_data: - */ - __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":214 - * def __dealloc__(array self): - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) # <<<<<<<<<<<<<< - * elif self.free_data: - * if self.dtype_is_object: - */ - __pyx_v_self->callback_free_data(__pyx_v_self->data); - - /* "View.MemoryView":213 - * - * def __dealloc__(array self): - * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< - * self.callback_free_data(self.data) - * elif self.free_data: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":215 - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - * elif self.free_data: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, - */ - __pyx_t_1 = (__pyx_v_self->free_data != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":216 - * self.callback_free_data(self.data) - * elif self.free_data: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - */ - __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":217 - * elif self.free_data: - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< - * self._strides, self.ndim, False) - * free(self.data) - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); - - /* "View.MemoryView":216 - * self.callback_free_data(self.data) - * elif self.free_data: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - */ - } - - /* "View.MemoryView":219 - * refcount_objects_in_slice(self.data, self._shape, - * self._strides, self.ndim, False) - * free(self.data) # <<<<<<<<<<<<<< - * PyObject_Free(self._shape) - * - */ - free(__pyx_v_self->data); - - /* "View.MemoryView":215 - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - * elif self.free_data: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * refcount_objects_in_slice(self.data, self._shape, - */ - } - __pyx_L3:; - - /* "View.MemoryView":220 - * self._strides, self.ndim, False) - * free(self.data) - * PyObject_Free(self._shape) # <<<<<<<<<<<<<< - * - * @property - */ - PyObject_Free(__pyx_v_self->_shape); - - /* "View.MemoryView":212 - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") - * - * def __dealloc__(array self): # <<<<<<<<<<<<<< - * if self.callback_free_data != NULL: - * self.callback_free_data(self.data) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":223 - * - * @property - * def memview(self): # <<<<<<<<<<<<<< - * return self.get_memview() - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":224 - * @property - * def memview(self): - * return self.get_memview() # <<<<<<<<<<<<<< - * - * @cname('get_memview') - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = ((struct __pyx_vtabstruct_array *)__pyx_v_self->__pyx_vtab)->get_memview(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 224, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":223 - * - * @property - * def memview(self): # <<<<<<<<<<<<<< - * return self.get_memview() - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":227 - * - * @cname('get_memview') - * cdef get_memview(self): # <<<<<<<<<<<<<< - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) - */ - -static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self) { - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_memview", 0); - - /* "View.MemoryView":228 - * @cname('get_memview') - * cdef get_memview(self): - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< - * return memoryview(self, flags, self.dtype_is_object) - * - */ - __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); - - /* "View.MemoryView":229 - * cdef get_memview(self): - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 229, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 229, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 229, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 229, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":227 - * - * @cname('get_memview') - * cdef get_memview(self): # <<<<<<<<<<<<<< - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.array.get_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":231 - * return memoryview(self, flags, self.dtype_is_object) - * - * def __len__(self): # <<<<<<<<<<<<<< - * return self._shape[0] - * - */ - -/* Python wrapper */ -static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__", 0); - - /* "View.MemoryView":232 - * - * def __len__(self): - * return self._shape[0] # <<<<<<<<<<<<<< - * - * def __getattr__(self, attr): - */ - __pyx_r = (__pyx_v_self->_shape[0]); - goto __pyx_L0; - - /* "View.MemoryView":231 - * return memoryview(self, flags, self.dtype_is_object) - * - * def __len__(self): # <<<<<<<<<<<<<< - * return self._shape[0] - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":234 - * return self._shape[0] - * - * def __getattr__(self, attr): # <<<<<<<<<<<<<< - * return getattr(self.memview, attr) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ -static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getattr__", 0); - - /* "View.MemoryView":235 - * - * def __getattr__(self, attr): - * return getattr(self.memview, attr) # <<<<<<<<<<<<<< - * - * def __getitem__(self, item): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 235, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 235, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":234 - * return self._shape[0] - * - * def __getattr__(self, attr): # <<<<<<<<<<<<<< - * return getattr(self.memview, attr) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":237 - * return getattr(self.memview, attr) - * - * def __getitem__(self, item): # <<<<<<<<<<<<<< - * return self.memview[item] - * - */ - -/* Python wrapper */ -static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ -static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "View.MemoryView":238 - * - * def __getitem__(self, item): - * return self.memview[item] # <<<<<<<<<<<<<< - * - * def __setitem__(self, item, value): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":237 - * return getattr(self.memview, attr) - * - * def __getitem__(self, item): # <<<<<<<<<<<<<< - * return self.memview[item] - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":240 - * return self.memview[item] - * - * def __setitem__(self, item, value): # <<<<<<<<<<<<<< - * self.memview[item] = value - * - */ - -/* Python wrapper */ -static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setitem__", 0); - - /* "View.MemoryView":241 - * - * def __setitem__(self, item, value): - * self.memview[item] = value # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 241, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(2, 241, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "View.MemoryView":240 - * return self.memview[item] - * - * def __setitem__(self, item, value): # <<<<<<<<<<<<<< - * self.memview[item] = value - * - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_array___reduce_cython__(((struct __pyx_array_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(2, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_array_2__setstate_cython__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(2, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.array.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":245 - * - * @cname("__pyx_array_new") - * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< - * char *mode, char *buf): - * cdef array result - */ - -static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { - struct __pyx_array_obj *__pyx_v_result = 0; - struct __pyx_array_obj *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("array_cwrapper", 0); - - /* "View.MemoryView":249 - * cdef array result - * - * if buf == NULL: # <<<<<<<<<<<<<< - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - */ - __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":250 - * - * if buf == NULL: - * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), - */ - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 250, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 250, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 250, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 250, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 250, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":249 - * cdef array result - * - * if buf == NULL: # <<<<<<<<<<<<<< - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":252 - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< - * allocate_buffer=False) - * result.data = buf - */ - /*else*/ { - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_3 = 0; - - /* "View.MemoryView":253 - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), - * allocate_buffer=False) # <<<<<<<<<<<<<< - * result.data = buf - * - */ - __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 253, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(2, 253, __pyx_L1_error) - - /* "View.MemoryView":252 - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< - * allocate_buffer=False) - * result.data = buf - */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "View.MemoryView":254 - * result = array(shape, itemsize, format, mode.decode('ASCII'), - * allocate_buffer=False) - * result.data = buf # <<<<<<<<<<<<<< - * - * return result - */ - __pyx_v_result->data = __pyx_v_buf; - } - __pyx_L3:; - - /* "View.MemoryView":256 - * result.data = buf - * - * return result # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(((PyObject *)__pyx_r)); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = __pyx_v_result; - goto __pyx_L0; - - /* "View.MemoryView":245 - * - * @cname("__pyx_array_new") - * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< - * char *mode, char *buf): - * cdef array result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF((PyObject *)__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":282 - * cdef class Enum(object): - * cdef object name - * def __init__(self, name): # <<<<<<<<<<<<<< - * self.name = name - * def __repr__(self): - */ - -/* Python wrapper */ -static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_name = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(2, 282, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_name = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 282, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__", 0); - - /* "View.MemoryView":283 - * cdef object name - * def __init__(self, name): - * self.name = name # <<<<<<<<<<<<<< - * def __repr__(self): - * return self.name - */ - __Pyx_INCREF(__pyx_v_name); - __Pyx_GIVEREF(__pyx_v_name); - __Pyx_GOTREF(__pyx_v_self->name); - __Pyx_DECREF(__pyx_v_self->name); - __pyx_v_self->name = __pyx_v_name; - - /* "View.MemoryView":282 - * cdef class Enum(object): - * cdef object name - * def __init__(self, name): # <<<<<<<<<<<<<< - * self.name = name - * def __repr__(self): - */ - - /* function exit code */ - __pyx_r = 0; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":284 - * def __init__(self, name): - * self.name = name - * def __repr__(self): # <<<<<<<<<<<<<< - * return self.name - * - */ - -/* Python wrapper */ -static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "View.MemoryView":285 - * self.name = name - * def __repr__(self): - * return self.name # <<<<<<<<<<<<<< - * - * cdef generic = Enum("") - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->name); - __pyx_r = __pyx_v_self->name; - goto __pyx_L0; - - /* "View.MemoryView":284 - * def __init__(self, name): - * self.name = name - * def __repr__(self): # <<<<<<<<<<<<<< - * return self.name - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_MemviewEnum___reduce_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { - PyObject *__pyx_v_state = 0; - PyObject *__pyx_v__dict = 0; - int __pyx_v_use_setstate; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":5 - * cdef object _dict - * cdef bint use_setstate - * state = (self.name,) # <<<<<<<<<<<<<< - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->name); - __Pyx_GIVEREF(__pyx_v_self->name); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); - __pyx_v_state = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "(tree fragment)":6 - * cdef bint use_setstate - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< - * if _dict is not None: - * state += (_dict,) - */ - __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v__dict = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":7 - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - __pyx_t_2 = (__pyx_v__dict != Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":8 - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - * state += (_dict,) # <<<<<<<<<<<<<< - * use_setstate = True - * else: - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v__dict); - __Pyx_GIVEREF(__pyx_v__dict); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); - __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "(tree fragment)":9 - * if _dict is not None: - * state += (_dict,) - * use_setstate = True # <<<<<<<<<<<<<< - * else: - * use_setstate = self.name is not None - */ - __pyx_v_use_setstate = 1; - - /* "(tree fragment)":7 - * state = (self.name,) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - goto __pyx_L3; - } - - /* "(tree fragment)":11 - * use_setstate = True - * else: - * use_setstate = self.name is not None # <<<<<<<<<<<<<< - * if use_setstate: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - */ - /*else*/ { - __pyx_t_3 = (__pyx_v_self->name != Py_None); - __pyx_v_use_setstate = __pyx_t_3; - } - __pyx_L3:; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.name is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - */ - __pyx_t_3 = (__pyx_v_use_setstate != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":13 - * use_setstate = self.name is not None - * if use_setstate: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state # <<<<<<<<<<<<<< - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_184977713); - __Pyx_GIVEREF(__pyx_int_184977713); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state); - __pyx_t_4 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.name is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - */ - } - - /* "(tree fragment)":15 - * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_184977713); - __Pyx_GIVEREF(__pyx_int_184977713); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); - __pyx_t_5 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - } - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.Enum.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_state); - __Pyx_XDECREF(__pyx_v__dict); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":16 - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_MemviewEnum_2__setstate_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":17 - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_Enum__set_state(self, __pyx_state) # <<<<<<<<<<<<<< - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(2, 17, __pyx_L1_error) - __pyx_t_1 = __pyx_unpickle_Enum__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":16 - * else: - * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state(self, __pyx_state) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.Enum.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":299 - * - * @cname('__pyx_align_pointer') - * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory - */ - -static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { - Py_intptr_t __pyx_v_aligned_p; - size_t __pyx_v_offset; - void *__pyx_r; - int __pyx_t_1; - - /* "View.MemoryView":301 - * cdef void *align_pointer(void *memory, size_t alignment) nogil: - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< - * cdef size_t offset - * - */ - __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); - - /* "View.MemoryView":305 - * - * with cython.cdivision(True): - * offset = aligned_p % alignment # <<<<<<<<<<<<<< - * - * if offset > 0: - */ - __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); - - /* "View.MemoryView":307 - * offset = aligned_p % alignment - * - * if offset > 0: # <<<<<<<<<<<<<< - * aligned_p += alignment - offset - * - */ - __pyx_t_1 = ((__pyx_v_offset > 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":308 - * - * if offset > 0: - * aligned_p += alignment - offset # <<<<<<<<<<<<<< - * - * return aligned_p - */ - __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); - - /* "View.MemoryView":307 - * offset = aligned_p % alignment - * - * if offset > 0: # <<<<<<<<<<<<<< - * aligned_p += alignment - offset - * - */ - } - - /* "View.MemoryView":310 - * aligned_p += alignment - offset - * - * return aligned_p # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = ((void *)__pyx_v_aligned_p); - goto __pyx_L0; - - /* "View.MemoryView":299 - * - * @cname('__pyx_align_pointer') - * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":346 - * cdef __Pyx_TypeInfo *typeinfo - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< - * self.obj = obj - * self.flags = flags - */ - -/* Python wrapper */ -static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_obj = 0; - int __pyx_v_flags; - int __pyx_v_dtype_is_object; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(2, 346, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_dtype_is_object); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(2, 346, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_obj = values[0]; - __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 346, __pyx_L3_error) - if (values[2]) { - __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 346, __pyx_L3_error) - } else { - __pyx_v_dtype_is_object = ((int)0); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 346, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "View.MemoryView":347 - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): - * self.obj = obj # <<<<<<<<<<<<<< - * self.flags = flags - * if type(self) is memoryview or obj is not None: - */ - __Pyx_INCREF(__pyx_v_obj); - __Pyx_GIVEREF(__pyx_v_obj); - __Pyx_GOTREF(__pyx_v_self->obj); - __Pyx_DECREF(__pyx_v_self->obj); - __pyx_v_self->obj = __pyx_v_obj; - - /* "View.MemoryView":348 - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): - * self.obj = obj - * self.flags = flags # <<<<<<<<<<<<<< - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - */ - __pyx_v_self->flags = __pyx_v_flags; - - /* "View.MemoryView":349 - * self.obj = obj - * self.flags = flags - * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - */ - __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)__pyx_memoryview_type)); - __pyx_t_3 = (__pyx_t_2 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_1 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_3 = (__pyx_v_obj != Py_None); - __pyx_t_2 = (__pyx_t_3 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (__pyx_t_1) { - - /* "View.MemoryView":350 - * self.flags = flags - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None - */ - __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 350, __pyx_L1_error) - - /* "View.MemoryView":351 - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) - */ - __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":352 - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; - - /* "View.MemoryView":353 - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * if not __PYX_CYTHON_ATOMICS_ENABLED(): - */ - Py_INCREF(Py_None); - - /* "View.MemoryView":351 - * if type(self) is memoryview or obj is not None: - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) - */ - } - - /* "View.MemoryView":349 - * self.obj = obj - * self.flags = flags - * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< - * __Pyx_GetBuffer(obj, &self.view, flags) - * if self.view.obj == NULL: - */ - } - - /* "View.MemoryView":355 - * Py_INCREF(Py_None) - * - * if not __PYX_CYTHON_ATOMICS_ENABLED(): # <<<<<<<<<<<<<< - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: - */ - __pyx_t_1 = ((!(__PYX_CYTHON_ATOMICS_ENABLED() != 0)) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":357 - * if not __PYX_CYTHON_ATOMICS_ENABLED(): - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - */ - __pyx_t_1 = ((__pyx_memoryview_thread_locks_used < 8) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":358 - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: - */ - __pyx_v_self->lock = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); - - /* "View.MemoryView":359 - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 # <<<<<<<<<<<<<< - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - */ - __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used + 1); - - /* "View.MemoryView":357 - * if not __PYX_CYTHON_ATOMICS_ENABLED(): - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - */ - } - - /* "View.MemoryView":360 - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: # <<<<<<<<<<<<<< - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - */ - __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":361 - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< - * if self.lock is NULL: - * raise MemoryError - */ - __pyx_v_self->lock = PyThread_allocate_lock(); - - /* "View.MemoryView":362 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * - */ - __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":363 - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - * raise MemoryError # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - PyErr_NoMemory(); __PYX_ERR(2, 363, __pyx_L1_error) - - /* "View.MemoryView":362 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * - */ - } - - /* "View.MemoryView":360 - * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] - * __pyx_memoryview_thread_locks_used += 1 - * if self.lock is NULL: # <<<<<<<<<<<<<< - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - */ - } - - /* "View.MemoryView":355 - * Py_INCREF(Py_None) - * - * if not __PYX_CYTHON_ATOMICS_ENABLED(): # <<<<<<<<<<<<<< - * global __pyx_memoryview_thread_locks_used - * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: - */ - } - - /* "View.MemoryView":365 - * raise MemoryError - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":366 - * - * if flags & PyBUF_FORMAT: - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') # <<<<<<<<<<<<<< - * else: - * self.dtype_is_object = dtype_is_object - */ - __pyx_t_2 = (((__pyx_v_self->view.format[0]) == 'O') != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L12_bool_binop_done; - } - __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L12_bool_binop_done:; - __pyx_v_self->dtype_is_object = __pyx_t_1; - - /* "View.MemoryView":365 - * raise MemoryError - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - */ - goto __pyx_L11; - } - - /* "View.MemoryView":368 - * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') - * else: - * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< - * - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( - */ - /*else*/ { - __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; - } - __pyx_L11:; - - /* "View.MemoryView":370 - * self.dtype_is_object = dtype_is_object - * - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< - * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) - * self.typeinfo = NULL - */ - __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); - - /* "View.MemoryView":372 - * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( - * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) - * self.typeinfo = NULL # <<<<<<<<<<<<<< - * - * def __dealloc__(memoryview self): - */ - __pyx_v_self->typeinfo = NULL; - - /* "View.MemoryView":346 - * cdef __Pyx_TypeInfo *typeinfo - * - * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< - * self.obj = obj - * self.flags = flags - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":374 - * self.typeinfo = NULL - * - * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - */ - -/* Python wrapper */ -static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { - int __pyx_v_i; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyThread_type_lock __pyx_t_6; - PyThread_type_lock __pyx_t_7; - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":375 - * - * def __dealloc__(memoryview self): - * if self.obj is not None: # <<<<<<<<<<<<<< - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - */ - __pyx_t_1 = (__pyx_v_self->obj != Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":376 - * def __dealloc__(memoryview self): - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - * - */ - __Pyx_ReleaseBuffer((&__pyx_v_self->view)); - - /* "View.MemoryView":375 - * - * def __dealloc__(memoryview self): - * if self.obj is not None: # <<<<<<<<<<<<<< - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":377 - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< - * - * (<__pyx_buffer *> &self.view).obj = NULL - */ - __pyx_t_2 = ((((Py_buffer *)(&__pyx_v_self->view))->obj == Py_None) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":379 - * elif (<__pyx_buffer *> &self.view).obj == Py_None: - * - * (<__pyx_buffer *> &self.view).obj = NULL # <<<<<<<<<<<<<< - * Py_DECREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_self->view))->obj = NULL; - - /* "View.MemoryView":380 - * - * (<__pyx_buffer *> &self.view).obj = NULL - * Py_DECREF(Py_None) # <<<<<<<<<<<<<< - * - * cdef int i - */ - Py_DECREF(Py_None); - - /* "View.MemoryView":377 - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< - * - * (<__pyx_buffer *> &self.view).obj = NULL - */ - } - __pyx_L3:; - - /* "View.MemoryView":384 - * cdef int i - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: # <<<<<<<<<<<<<< - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - */ - __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":385 - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - */ - __pyx_t_3 = __pyx_memoryview_thread_locks_used; - __pyx_t_4 = __pyx_t_3; - for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { - __pyx_v_i = __pyx_t_5; - - /* "View.MemoryView":386 - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - */ - __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":387 - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - */ - __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); - - /* "View.MemoryView":388 - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - */ - __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":390 - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) # <<<<<<<<<<<<<< - * break - * else: - */ - __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); - __pyx_t_7 = (__pyx_memoryview_thread_locks[__pyx_v_i]); - - /* "View.MemoryView":389 - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - * break - */ - (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_6; - (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_7; - - /* "View.MemoryView":388 - * if __pyx_memoryview_thread_locks[i] is self.lock: - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - */ - } - - /* "View.MemoryView":391 - * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( - * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) - * break # <<<<<<<<<<<<<< - * else: - * PyThread_free_lock(self.lock) - */ - goto __pyx_L6_break; - - /* "View.MemoryView":386 - * if self.lock != NULL: - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< - * __pyx_memoryview_thread_locks_used -= 1 - * if i != __pyx_memoryview_thread_locks_used: - */ - } - } - /*else*/ { - - /* "View.MemoryView":393 - * break - * else: - * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: - */ - PyThread_free_lock(__pyx_v_self->lock); - } - __pyx_L6_break:; - - /* "View.MemoryView":384 - * cdef int i - * global __pyx_memoryview_thread_locks_used - * if self.lock != NULL: # <<<<<<<<<<<<<< - * for i in range(__pyx_memoryview_thread_locks_used): - * if __pyx_memoryview_thread_locks[i] is self.lock: - */ - } - - /* "View.MemoryView":374 - * self.typeinfo = NULL - * - * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":395 - * PyThread_free_lock(self.lock) - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf - */ - -static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { - Py_ssize_t __pyx_v_dim; - char *__pyx_v_itemp; - PyObject *__pyx_v_idx = NULL; - char *__pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - Py_ssize_t __pyx_t_3; - PyObject *(*__pyx_t_4)(PyObject *); - PyObject *__pyx_t_5 = NULL; - Py_ssize_t __pyx_t_6; - char *__pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_item_pointer", 0); - - /* "View.MemoryView":397 - * cdef char *get_item_pointer(memoryview self, object index) except NULL: - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< - * - * for dim, idx in enumerate(index): - */ - __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); - - /* "View.MemoryView":399 - * cdef char *itemp = self.view.buf - * - * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - */ - __pyx_t_1 = 0; - if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { - __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; - __pyx_t_4 = NULL; - } else { - __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 399, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 399, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_4)) { - if (likely(PyList_CheckExact(__pyx_t_2))) { - if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(2, 399, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 399, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - } else { - if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(2, 399, __pyx_L1_error) - #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 399, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - } - } else { - __pyx_t_5 = __pyx_t_4(__pyx_t_2); - if (unlikely(!__pyx_t_5)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(2, 399, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_5); - } - __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); - __pyx_t_5 = 0; - __pyx_v_dim = __pyx_t_1; - __pyx_t_1 = (__pyx_t_1 + 1); - - /* "View.MemoryView":400 - * - * for dim, idx in enumerate(index): - * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< - * - * return itemp - */ - __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 400, __pyx_L1_error) - __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == ((char *)NULL))) __PYX_ERR(2, 400, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_7; - - /* "View.MemoryView":399 - * cdef char *itemp = self.view.buf - * - * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - */ - } - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":402 - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - * return itemp # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_itemp; - goto __pyx_L0; - - /* "View.MemoryView":395 - * PyThread_free_lock(self.lock) - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_idx); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":405 - * - * - * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< - * if index is Ellipsis: - * return self - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ -static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { - PyObject *__pyx_v_have_slices = NULL; - PyObject *__pyx_v_indices = NULL; - char *__pyx_v_itemp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - char *__pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "View.MemoryView":406 - * - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: # <<<<<<<<<<<<<< - * return self - * - */ - __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":407 - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: - * return self # <<<<<<<<<<<<<< - * - * have_slices, indices = _unellipsify(index, self.view.ndim) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __pyx_r = ((PyObject *)__pyx_v_self); - goto __pyx_L0; - - /* "View.MemoryView":406 - * - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: # <<<<<<<<<<<<<< - * return self - * - */ - } - - /* "View.MemoryView":409 - * return self - * - * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< - * - * cdef char *itemp - */ - __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 409, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (likely(__pyx_t_3 != Py_None)) { - PyObject* sequence = __pyx_t_3; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(2, 409, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 409, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 409, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 409, __pyx_L1_error) - } - __pyx_v_have_slices = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_v_indices = __pyx_t_5; - __pyx_t_5 = 0; - - /* "View.MemoryView":412 - * - * cdef char *itemp - * if have_slices: # <<<<<<<<<<<<<< - * return memview_slice(self, indices) - * else: - */ - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(2, 412, __pyx_L1_error) - if (__pyx_t_2) { - - /* "View.MemoryView":413 - * cdef char *itemp - * if have_slices: - * return memview_slice(self, indices) # <<<<<<<<<<<<<< - * else: - * itemp = self.get_item_pointer(indices) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 413, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":412 - * - * cdef char *itemp - * if have_slices: # <<<<<<<<<<<<<< - * return memview_slice(self, indices) - * else: - */ - } - - /* "View.MemoryView":415 - * return memview_slice(self, indices) - * else: - * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< - * return self.convert_item_to_object(itemp) - * - */ - /*else*/ { - __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == ((char *)NULL))) __PYX_ERR(2, 415, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_6; - - /* "View.MemoryView":416 - * else: - * itemp = self.get_item_pointer(indices) - * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< - * - * def __setitem__(memoryview self, object index, object value): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 416, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":405 - * - * - * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< - * if index is Ellipsis: - * return self - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_have_slices); - __Pyx_XDECREF(__pyx_v_indices); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":418 - * return self.convert_item_to_object(itemp) - * - * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") - */ - -/* Python wrapper */ -static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - PyObject *__pyx_v_have_slices = NULL; - PyObject *__pyx_v_obj = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setitem__", 0); - __Pyx_INCREF(__pyx_v_index); - - /* "View.MemoryView":419 - * - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: # <<<<<<<<<<<<<< - * raise TypeError("Cannot assign to read-only memoryview") - * - */ - __pyx_t_1 = (__pyx_v_self->view.readonly != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":420 - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< - * - * have_slices, index = _unellipsify(index, self.view.ndim) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(2, 420, __pyx_L1_error) - - /* "View.MemoryView":419 - * - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: # <<<<<<<<<<<<<< - * raise TypeError("Cannot assign to read-only memoryview") - * - */ - } - - /* "View.MemoryView":422 - * raise TypeError("Cannot assign to read-only memoryview") - * - * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< - * - * if have_slices: - */ - __pyx_t_2 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 422, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (likely(__pyx_t_2 != Py_None)) { - PyObject* sequence = __pyx_t_2; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(2, 422, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 422, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 422, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 422, __pyx_L1_error) - } - __pyx_v_have_slices = __pyx_t_3; - __pyx_t_3 = 0; - __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":424 - * have_slices, index = _unellipsify(index, self.view.ndim) - * - * if have_slices: # <<<<<<<<<<<<<< - * obj = self.is_slice(value) - * if obj: - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 424, __pyx_L1_error) - if (__pyx_t_1) { - - /* "View.MemoryView":425 - * - * if have_slices: - * obj = self.is_slice(value) # <<<<<<<<<<<<<< - * if obj: - * self.setitem_slice_assignment(self[index], obj) - */ - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 425, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_obj = __pyx_t_2; - __pyx_t_2 = 0; - - /* "View.MemoryView":426 - * if have_slices: - * obj = self.is_slice(value) - * if obj: # <<<<<<<<<<<<<< - * self.setitem_slice_assignment(self[index], obj) - * else: - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 426, __pyx_L1_error) - if (__pyx_t_1) { - - /* "View.MemoryView":427 - * obj = self.is_slice(value) - * if obj: - * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< - * else: - * self.setitem_slice_assign_scalar(self[index], value) - */ - __pyx_t_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 427, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_2, __pyx_v_obj); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 427, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "View.MemoryView":426 - * if have_slices: - * obj = self.is_slice(value) - * if obj: # <<<<<<<<<<<<<< - * self.setitem_slice_assignment(self[index], obj) - * else: - */ - goto __pyx_L5; - } - - /* "View.MemoryView":429 - * self.setitem_slice_assignment(self[index], obj) - * else: - * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< - * else: - * self.setitem_indexed(index, value) - */ - /*else*/ { - __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 429, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_memoryview_type))))) __PYX_ERR(2, 429, __pyx_L1_error) - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_4), __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 429, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L5:; - - /* "View.MemoryView":424 - * have_slices, index = _unellipsify(index, self.view.ndim) - * - * if have_slices: # <<<<<<<<<<<<<< - * obj = self.is_slice(value) - * if obj: - */ - goto __pyx_L4; - } - - /* "View.MemoryView":431 - * self.setitem_slice_assign_scalar(self[index], value) - * else: - * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< - * - * cdef is_slice(self, obj): - */ - /*else*/ { - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 431, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L4:; - - /* "View.MemoryView":418 - * return self.convert_item_to_object(itemp) - * - * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_have_slices); - __Pyx_XDECREF(__pyx_v_obj); - __Pyx_XDECREF(__pyx_v_index); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":433 - * self.setitem_indexed(index, value) - * - * cdef is_slice(self, obj): # <<<<<<<<<<<<<< - * if not isinstance(obj, memoryview): - * try: - */ - -static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_slice", 0); - __Pyx_INCREF(__pyx_v_obj); - - /* "View.MemoryView":434 - * - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":435 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_5); - /*try:*/ { - - /* "View.MemoryView":436 - * if not isinstance(obj, memoryview): - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< - * self.dtype_is_object) - * except TypeError: - */ - __pyx_t_6 = __Pyx_PyInt_From_int(((__pyx_v_self->flags & (~PyBUF_WRITABLE)) | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 436, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "View.MemoryView":437 - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) # <<<<<<<<<<<<<< - * except TypeError: - * return None - */ - __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 437, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "View.MemoryView":436 - * if not isinstance(obj, memoryview): - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< - * self.dtype_is_object) - * except TypeError: - */ - __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 436, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_INCREF(__pyx_v_obj); - __Pyx_GIVEREF(__pyx_v_obj); - PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 436, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); - __pyx_t_7 = 0; - - /* "View.MemoryView":435 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - } - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L9_try_end; - __pyx_L4_error:; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "View.MemoryView":438 - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - * except TypeError: # <<<<<<<<<<<<<< - * return None - * - */ - __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_TypeError); - if (__pyx_t_9) { - __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) __PYX_ERR(2, 438, __pyx_L6_except_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_6); - - /* "View.MemoryView":439 - * self.dtype_is_object) - * except TypeError: - * return None # <<<<<<<<<<<<<< - * - * return obj - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - goto __pyx_L7_except_return; - } - goto __pyx_L6_except_error; - __pyx_L6_except_error:; - - /* "View.MemoryView":435 - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): - * try: # <<<<<<<<<<<<<< - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - * self.dtype_is_object) - */ - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); - goto __pyx_L1_error; - __pyx_L7_except_return:; - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); - goto __pyx_L0; - __pyx_L9_try_end:; - } - - /* "View.MemoryView":434 - * - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - */ - } - - /* "View.MemoryView":441 - * return None - * - * return obj # <<<<<<<<<<<<<< - * - * cdef setitem_slice_assignment(self, dst, src): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_obj); - __pyx_r = __pyx_v_obj; - goto __pyx_L0; - - /* "View.MemoryView":433 - * self.setitem_indexed(index, value) - * - * cdef is_slice(self, obj): # <<<<<<<<<<<<<< - * if not isinstance(obj, memoryview): - * try: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_obj); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":443 - * return obj - * - * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice dst_slice - * cdef __Pyx_memviewslice src_slice - */ - -static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { - __Pyx_memviewslice __pyx_v_dst_slice; - __Pyx_memviewslice __pyx_v_src_slice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - __Pyx_memviewslice *__pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); - - /* "View.MemoryView":447 - * cdef __Pyx_memviewslice src_slice - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) - */ - if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) __PYX_ERR(2, 447, __pyx_L1_error) - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 447, __pyx_L1_error) - - /* "View.MemoryView":448 - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], - * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< - * src.ndim, dst.ndim, self.dtype_is_object) - * - */ - if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) __PYX_ERR(2, 448, __pyx_L1_error) - __pyx_t_2 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice)); if (unlikely(__pyx_t_2 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 448, __pyx_L1_error) - - /* "View.MemoryView":449 - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 449, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 449, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 449, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 449, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":447 - * cdef __Pyx_memviewslice src_slice - * - * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< - * get_slice_from_memview(dst, &dst_slice)[0], - * src.ndim, dst.ndim, self.dtype_is_object) - */ - __pyx_t_6 = __pyx_memoryview_copy_contents((__pyx_t_1[0]), (__pyx_t_2[0]), __pyx_t_4, __pyx_t_5, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(2, 447, __pyx_L1_error) - - /* "View.MemoryView":443 - * return obj - * - * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice dst_slice - * cdef __Pyx_memviewslice src_slice - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":451 - * src.ndim, dst.ndim, self.dtype_is_object) - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< - * cdef int array[128] - * cdef void *tmp = NULL - */ - -static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { - int __pyx_v_array[0x80]; - void *__pyx_v_tmp; - void *__pyx_v_item; - __Pyx_memviewslice *__pyx_v_dst_slice; - __Pyx_memviewslice __pyx_v_tmp_slice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - char const *__pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); - - /* "View.MemoryView":453 - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): - * cdef int array[128] - * cdef void *tmp = NULL # <<<<<<<<<<<<<< - * cdef void *item - * - */ - __pyx_v_tmp = NULL; - - /* "View.MemoryView":458 - * cdef __Pyx_memviewslice *dst_slice - * cdef __Pyx_memviewslice tmp_slice - * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< - * - * if self.view.itemsize > sizeof(array): - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 458, __pyx_L1_error) - __pyx_v_dst_slice = __pyx_t_1; - - /* "View.MemoryView":460 - * dst_slice = get_slice_from_memview(dst, &tmp_slice) - * - * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - */ - __pyx_t_2 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":461 - * - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< - * if tmp == NULL: - * raise MemoryError - */ - __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); - - /* "View.MemoryView":462 - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * item = tmp - */ - __pyx_t_2 = ((__pyx_v_tmp == NULL) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":463 - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - * raise MemoryError # <<<<<<<<<<<<<< - * item = tmp - * else: - */ - PyErr_NoMemory(); __PYX_ERR(2, 463, __pyx_L1_error) - - /* "View.MemoryView":462 - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * item = tmp - */ - } - - /* "View.MemoryView":464 - * if tmp == NULL: - * raise MemoryError - * item = tmp # <<<<<<<<<<<<<< - * else: - * item = array - */ - __pyx_v_item = __pyx_v_tmp; - - /* "View.MemoryView":460 - * dst_slice = get_slice_from_memview(dst, &tmp_slice) - * - * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":466 - * item = tmp - * else: - * item = array # <<<<<<<<<<<<<< - * - * try: - */ - /*else*/ { - __pyx_v_item = ((void *)__pyx_v_array); - } - __pyx_L3:; - - /* "View.MemoryView":468 - * item = array - * - * try: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * ( item)[0] = value - */ - /*try:*/ { - - /* "View.MemoryView":469 - * - * try: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * ( item)[0] = value - * else: - */ - __pyx_t_2 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":470 - * try: - * if self.dtype_is_object: - * ( item)[0] = value # <<<<<<<<<<<<<< - * else: - * self.assign_item_from_object( item, value) - */ - (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); - - /* "View.MemoryView":469 - * - * try: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * ( item)[0] = value - * else: - */ - goto __pyx_L8; - } - - /* "View.MemoryView":472 - * ( item)[0] = value - * else: - * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 472, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __pyx_L8:; - - /* "View.MemoryView":476 - * - * - * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - */ - __pyx_t_2 = ((__pyx_v_self->view.suboffsets != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":477 - * - * if self.view.suboffsets != NULL: - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - * item, self.dtype_is_object) - */ - __pyx_t_3 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 477, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":476 - * - * - * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, - */ - } - - /* "View.MemoryView":478 - * if self.view.suboffsets != NULL: - * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) - * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< - * item, self.dtype_is_object) - * finally: - */ - __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); - } - - /* "View.MemoryView":481 - * item, self.dtype_is_object) - * finally: - * PyMem_Free(tmp) # <<<<<<<<<<<<<< - * - * cdef setitem_indexed(self, index, value): - */ - /*finally:*/ { - /*normal exit:*/{ - PyMem_Free(__pyx_v_tmp); - goto __pyx_L7; - } - __pyx_L6_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9) < 0)) __Pyx_ErrFetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); - __Pyx_XGOTREF(__pyx_t_7); - __Pyx_XGOTREF(__pyx_t_8); - __Pyx_XGOTREF(__pyx_t_9); - __Pyx_XGOTREF(__pyx_t_10); - __Pyx_XGOTREF(__pyx_t_11); - __Pyx_XGOTREF(__pyx_t_12); - __pyx_t_4 = __pyx_lineno; __pyx_t_5 = __pyx_clineno; __pyx_t_6 = __pyx_filename; - { - PyMem_Free(__pyx_v_tmp); - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_10); - __Pyx_XGIVEREF(__pyx_t_11); - __Pyx_XGIVEREF(__pyx_t_12); - __Pyx_ExceptionReset(__pyx_t_10, __pyx_t_11, __pyx_t_12); - } - __Pyx_XGIVEREF(__pyx_t_7); - __Pyx_XGIVEREF(__pyx_t_8); - __Pyx_XGIVEREF(__pyx_t_9); - __Pyx_ErrRestore(__pyx_t_7, __pyx_t_8, __pyx_t_9); - __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; - __pyx_lineno = __pyx_t_4; __pyx_clineno = __pyx_t_5; __pyx_filename = __pyx_t_6; - goto __pyx_L1_error; - } - __pyx_L7:; - } - - /* "View.MemoryView":451 - * src.ndim, dst.ndim, self.dtype_is_object) - * - * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< - * cdef int array[128] - * cdef void *tmp = NULL - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":483 - * PyMem_Free(tmp) - * - * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) - */ - -static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { - char *__pyx_v_itemp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - char *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("setitem_indexed", 0); - - /* "View.MemoryView":484 - * - * cdef setitem_indexed(self, index, value): - * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< - * self.assign_item_from_object(itemp, value) - * - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == ((char *)NULL))) __PYX_ERR(2, 484, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_1; - - /* "View.MemoryView":485 - * cdef setitem_indexed(self, index, value): - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< - * - * cdef convert_item_to_object(self, char *itemp): - */ - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 485, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":483 - * PyMem_Free(tmp) - * - * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< - * cdef char *itemp = self.get_item_pointer(index) - * self.assign_item_from_object(itemp, value) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":487 - * self.assign_item_from_object(itemp, value) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - -static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { - PyObject *__pyx_v_struct = NULL; - PyObject *__pyx_v_bytesitem = 0; - PyObject *__pyx_v_result = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - size_t __pyx_t_10; - int __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("convert_item_to_object", 0); - - /* "View.MemoryView":490 - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - * import struct # <<<<<<<<<<<<<< - * cdef bytes bytesitem - * - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 490, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_struct = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":493 - * cdef bytes bytesitem - * - * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< - * try: - * result = struct.unpack(self.view.format, bytesitem) - */ - __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 493, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":494 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "View.MemoryView":495 - * bytesitem = itemp[:self.view.itemsize] - * try: - * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< - * except struct.error: - * raise ValueError("Unable to convert item to object") - */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 495, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 495, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_5)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 495, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 495, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 495, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); - __Pyx_INCREF(__pyx_v_bytesitem); - __Pyx_GIVEREF(__pyx_v_bytesitem); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 495, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_v_result = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":494 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - } - - /* "View.MemoryView":499 - * raise ValueError("Unable to convert item to object") - * else: - * if len(self.view.format) == 1: # <<<<<<<<<<<<<< - * return result[0] - * return result - */ - /*else:*/ { - __pyx_t_10 = strlen(__pyx_v_self->view.format); - __pyx_t_11 = ((__pyx_t_10 == 1) != 0); - if (__pyx_t_11) { - - /* "View.MemoryView":500 - * else: - * if len(self.view.format) == 1: - * return result[0] # <<<<<<<<<<<<<< - * return result - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 500, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L6_except_return; - - /* "View.MemoryView":499 - * raise ValueError("Unable to convert item to object") - * else: - * if len(self.view.format) == 1: # <<<<<<<<<<<<<< - * return result[0] - * return result - */ - } - - /* "View.MemoryView":501 - * if len(self.view.format) == 1: - * return result[0] - * return result # <<<<<<<<<<<<<< - * - * cdef assign_item_from_object(self, char *itemp, object value): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_result); - __pyx_r = __pyx_v_result; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "View.MemoryView":496 - * try: - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: # <<<<<<<<<<<<<< - * raise ValueError("Unable to convert item to object") - * else: - */ - __Pyx_ErrFetch(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9); - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 496, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = __Pyx_PyErr_GivenExceptionMatches(__pyx_t_1, __pyx_t_6); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_ErrRestore(__pyx_t_1, __pyx_t_5, __pyx_t_9); - __pyx_t_1 = 0; __pyx_t_5 = 0; __pyx_t_9 = 0; - if (__pyx_t_8) { - __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_5, &__pyx_t_1) < 0) __PYX_ERR(2, 496, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_1); - - /* "View.MemoryView":497 - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< - * else: - * if len(self.view.format) == 1: - */ - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 497, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_Raise(__pyx_t_6, 0, 0, 0); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __PYX_ERR(2, 497, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "View.MemoryView":494 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "View.MemoryView":487 - * self.assign_item_from_object(itemp, value) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_struct); - __Pyx_XDECREF(__pyx_v_bytesitem); - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":503 - * return result - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - -static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { - PyObject *__pyx_v_struct = NULL; - char __pyx_v_c; - PyObject *__pyx_v_bytesvalue = 0; - Py_ssize_t __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - Py_ssize_t __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - char *__pyx_t_11; - char *__pyx_t_12; - char *__pyx_t_13; - char *__pyx_t_14; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assign_item_from_object", 0); - - /* "View.MemoryView":506 - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - * import struct # <<<<<<<<<<<<<< - * cdef char c - * cdef bytes bytesvalue - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 506, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_struct = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":511 - * cdef Py_ssize_t i - * - * if isinstance(value, tuple): # <<<<<<<<<<<<<< - * bytesvalue = struct.pack(self.view.format, *value) - * else: - */ - __pyx_t_2 = PyTuple_Check(__pyx_v_value); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "View.MemoryView":512 - * - * if isinstance(value, tuple): - * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< - * else: - * bytesvalue = struct.pack(self.view.format, value) - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 512, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(2, 512, __pyx_L1_error) - __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":511 - * cdef Py_ssize_t i - * - * if isinstance(value, tuple): # <<<<<<<<<<<<<< - * bytesvalue = struct.pack(self.view.format, *value) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":514 - * bytesvalue = struct.pack(self.view.format, *value) - * else: - * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< - * - * for i, c in enumerate(bytesvalue): - */ - /*else*/ { - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 514, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 514, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - __pyx_t_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; - __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 514, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; - __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 514, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - #endif - { - __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 514, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_5) { - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; - } - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); - __pyx_t_1 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 514, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(2, 514, __pyx_L1_error) - __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - } - __pyx_L3:; - - /* "View.MemoryView":516 - * bytesvalue = struct.pack(self.view.format, value) - * - * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< - * itemp[i] = c - * - */ - __pyx_t_9 = 0; - if (unlikely(__pyx_v_bytesvalue == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); - __PYX_ERR(2, 516, __pyx_L1_error) - } - __Pyx_INCREF(__pyx_v_bytesvalue); - __pyx_t_10 = __pyx_v_bytesvalue; - __pyx_t_12 = PyBytes_AS_STRING(__pyx_t_10); - __pyx_t_13 = (__pyx_t_12 + PyBytes_GET_SIZE(__pyx_t_10)); - for (__pyx_t_14 = __pyx_t_12; __pyx_t_14 < __pyx_t_13; __pyx_t_14++) { - __pyx_t_11 = __pyx_t_14; - __pyx_v_c = (__pyx_t_11[0]); - - /* "View.MemoryView":517 - * - * for i, c in enumerate(bytesvalue): - * itemp[i] = c # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - __pyx_v_i = __pyx_t_9; - - /* "View.MemoryView":516 - * bytesvalue = struct.pack(self.view.format, value) - * - * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< - * itemp[i] = c - * - */ - __pyx_t_9 = (__pyx_t_9 + 1); - - /* "View.MemoryView":517 - * - * for i, c in enumerate(bytesvalue): - * itemp[i] = c # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; - } - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - - /* "View.MemoryView":503 - * return result - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * """Only used if instantiated manually by the user, or if Cython doesn't - * know how to convert the type""" - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_struct); - __Pyx_XDECREF(__pyx_v_bytesvalue); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":520 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") - */ - -/* Python wrapper */ -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - Py_ssize_t *__pyx_t_4; - char *__pyx_t_5; - void *__pyx_t_6; - int __pyx_t_7; - Py_ssize_t __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - if (__pyx_v_info == NULL) { - PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); - return -1; - } - __Pyx_RefNannySetupContext("__getbuffer__", 0); - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - - /* "View.MemoryView":521 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - */ - __pyx_t_2 = ((__pyx_v_flags & PyBUF_WRITABLE) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_2 = (__pyx_v_self->view.readonly != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":522 - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< - * - * if flags & PyBUF_ND: - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 522, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(2, 522, __pyx_L1_error) - - /* "View.MemoryView":521 - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - */ - } - - /* "View.MemoryView":524 - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - * if flags & PyBUF_ND: # <<<<<<<<<<<<<< - * info.shape = self.view.shape - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_ND) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":525 - * - * if flags & PyBUF_ND: - * info.shape = self.view.shape # <<<<<<<<<<<<<< - * else: - * info.shape = NULL - */ - __pyx_t_4 = __pyx_v_self->view.shape; - __pyx_v_info->shape = __pyx_t_4; - - /* "View.MemoryView":524 - * raise ValueError("Cannot create writable memory view from read-only memoryview") - * - * if flags & PyBUF_ND: # <<<<<<<<<<<<<< - * info.shape = self.view.shape - * else: - */ - goto __pyx_L6; - } - - /* "View.MemoryView":527 - * info.shape = self.view.shape - * else: - * info.shape = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_STRIDES: - */ - /*else*/ { - __pyx_v_info->shape = NULL; - } - __pyx_L6:; - - /* "View.MemoryView":529 - * info.shape = NULL - * - * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< - * info.strides = self.view.strides - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":530 - * - * if flags & PyBUF_STRIDES: - * info.strides = self.view.strides # <<<<<<<<<<<<<< - * else: - * info.strides = NULL - */ - __pyx_t_4 = __pyx_v_self->view.strides; - __pyx_v_info->strides = __pyx_t_4; - - /* "View.MemoryView":529 - * info.shape = NULL - * - * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< - * info.strides = self.view.strides - * else: - */ - goto __pyx_L7; - } - - /* "View.MemoryView":532 - * info.strides = self.view.strides - * else: - * info.strides = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_INDIRECT: - */ - /*else*/ { - __pyx_v_info->strides = NULL; - } - __pyx_L7:; - - /* "View.MemoryView":534 - * info.strides = NULL - * - * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< - * info.suboffsets = self.view.suboffsets - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":535 - * - * if flags & PyBUF_INDIRECT: - * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< - * else: - * info.suboffsets = NULL - */ - __pyx_t_4 = __pyx_v_self->view.suboffsets; - __pyx_v_info->suboffsets = __pyx_t_4; - - /* "View.MemoryView":534 - * info.strides = NULL - * - * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< - * info.suboffsets = self.view.suboffsets - * else: - */ - goto __pyx_L8; - } - - /* "View.MemoryView":537 - * info.suboffsets = self.view.suboffsets - * else: - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - /*else*/ { - __pyx_v_info->suboffsets = NULL; - } - __pyx_L8:; - - /* "View.MemoryView":539 - * info.suboffsets = NULL - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.view.format - * else: - */ - __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":540 - * - * if flags & PyBUF_FORMAT: - * info.format = self.view.format # <<<<<<<<<<<<<< - * else: - * info.format = NULL - */ - __pyx_t_5 = __pyx_v_self->view.format; - __pyx_v_info->format = __pyx_t_5; - - /* "View.MemoryView":539 - * info.suboffsets = NULL - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.view.format - * else: - */ - goto __pyx_L9; - } - - /* "View.MemoryView":542 - * info.format = self.view.format - * else: - * info.format = NULL # <<<<<<<<<<<<<< - * - * info.buf = self.view.buf - */ - /*else*/ { - __pyx_v_info->format = NULL; - } - __pyx_L9:; - - /* "View.MemoryView":544 - * info.format = NULL - * - * info.buf = self.view.buf # <<<<<<<<<<<<<< - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize - */ - __pyx_t_6 = __pyx_v_self->view.buf; - __pyx_v_info->buf = __pyx_t_6; - - /* "View.MemoryView":545 - * - * info.buf = self.view.buf - * info.ndim = self.view.ndim # <<<<<<<<<<<<<< - * info.itemsize = self.view.itemsize - * info.len = self.view.len - */ - __pyx_t_7 = __pyx_v_self->view.ndim; - __pyx_v_info->ndim = __pyx_t_7; - - /* "View.MemoryView":546 - * info.buf = self.view.buf - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< - * info.len = self.view.len - * info.readonly = self.view.readonly - */ - __pyx_t_8 = __pyx_v_self->view.itemsize; - __pyx_v_info->itemsize = __pyx_t_8; - - /* "View.MemoryView":547 - * info.ndim = self.view.ndim - * info.itemsize = self.view.itemsize - * info.len = self.view.len # <<<<<<<<<<<<<< - * info.readonly = self.view.readonly - * info.obj = self - */ - __pyx_t_8 = __pyx_v_self->view.len; - __pyx_v_info->len = __pyx_t_8; - - /* "View.MemoryView":548 - * info.itemsize = self.view.itemsize - * info.len = self.view.len - * info.readonly = self.view.readonly # <<<<<<<<<<<<<< - * info.obj = self - * - */ - __pyx_t_1 = __pyx_v_self->view.readonly; - __pyx_v_info->readonly = __pyx_t_1; - - /* "View.MemoryView":549 - * info.len = self.view.len - * info.readonly = self.view.readonly - * info.obj = self # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - - /* "View.MemoryView":520 - * - * @cname('getbuffer') - * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - __pyx_L2:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":555 - * - * @property - * def T(self): # <<<<<<<<<<<<<< - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":556 - * @property - * def T(self): - * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< - * transpose_memslice(&result.from_slice) - * return result - */ - __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 556, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) __PYX_ERR(2, 556, __pyx_L1_error) - __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":557 - * def T(self): - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< - * return result - * - */ - __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(2, 557, __pyx_L1_error) - - /* "View.MemoryView":558 - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - * return result # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":555 - * - * @property - * def T(self): # <<<<<<<<<<<<<< - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":561 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.obj - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":562 - * @property - * def base(self): - * return self.obj # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->obj); - __pyx_r = __pyx_v_self->obj; - goto __pyx_L0; - - /* "View.MemoryView":561 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.obj - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":565 - * - * @property - * def shape(self): # <<<<<<<<<<<<<< - * return tuple([length for length in self.view.shape[:self.view.ndim]]) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_length; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":566 - * @property - * def shape(self): - * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 566, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); - for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { - __pyx_t_2 = __pyx_t_4; - __pyx_v_length = (__pyx_t_2[0]); - __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 566, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(2, 566, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 566, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "View.MemoryView":565 - * - * @property - * def shape(self): # <<<<<<<<<<<<<< - * return tuple([length for length in self.view.shape[:self.view.ndim]]) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":569 - * - * @property - * def strides(self): # <<<<<<<<<<<<<< - * if self.view.strides == NULL: - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_stride; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":570 - * @property - * def strides(self): - * if self.view.strides == NULL: # <<<<<<<<<<<<<< - * - * raise ValueError("Buffer view does not expose strides") - */ - __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":572 - * if self.view.strides == NULL: - * - * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) - */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(2, 572, __pyx_L1_error) - - /* "View.MemoryView":570 - * @property - * def strides(self): - * if self.view.strides == NULL: # <<<<<<<<<<<<<< - * - * raise ValueError("Buffer view does not expose strides") - */ - } - - /* "View.MemoryView":574 - * raise ValueError("Buffer view does not expose strides") - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 574, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); - for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { - __pyx_t_3 = __pyx_t_5; - __pyx_v_stride = (__pyx_t_3[0]); - __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 574, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(2, 574, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 574, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "View.MemoryView":569 - * - * @property - * def strides(self): # <<<<<<<<<<<<<< - * if self.view.strides == NULL: - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":577 - * - * @property - * def suboffsets(self): # <<<<<<<<<<<<<< - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - Py_ssize_t *__pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":578 - * @property - * def suboffsets(self): - * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< - * return (-1,) * self.view.ndim - * - */ - __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":579 - * def suboffsets(self): - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__14, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":578 - * @property - * def suboffsets(self): - * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< - * return (-1,) * self.view.ndim - * - */ - } - - /* "View.MemoryView":581 - * return (-1,) * self.view.ndim - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 581, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); - for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { - __pyx_t_4 = __pyx_t_6; - __pyx_v_suboffset = (__pyx_t_4[0]); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 581, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(2, 581, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 581, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":577 - * - * @property - * def suboffsets(self): # <<<<<<<<<<<<<< - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":584 - * - * @property - * def ndim(self): # <<<<<<<<<<<<<< - * return self.view.ndim - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":585 - * @property - * def ndim(self): - * return self.view.ndim # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 585, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":584 - * - * @property - * def ndim(self): # <<<<<<<<<<<<<< - * return self.view.ndim - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":588 - * - * @property - * def itemsize(self): # <<<<<<<<<<<<<< - * return self.view.itemsize - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":589 - * @property - * def itemsize(self): - * return self.view.itemsize # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 589, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":588 - * - * @property - * def itemsize(self): # <<<<<<<<<<<<<< - * return self.view.itemsize - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":592 - * - * @property - * def nbytes(self): # <<<<<<<<<<<<<< - * return self.size * self.view.itemsize - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":593 - * @property - * def nbytes(self): - * return self.size * self.view.itemsize # <<<<<<<<<<<<<< - * - * @property - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 593, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 593, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 593, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":592 - * - * @property - * def nbytes(self): # <<<<<<<<<<<<<< - * return self.size * self.view.itemsize - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":596 - * - * @property - * def size(self): # <<<<<<<<<<<<<< - * if self._size is None: - * result = 1 - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_v_result = NULL; - PyObject *__pyx_v_length = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - Py_ssize_t *__pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":597 - * @property - * def size(self): - * if self._size is None: # <<<<<<<<<<<<<< - * result = 1 - * - */ - __pyx_t_1 = (__pyx_v_self->_size == Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":598 - * def size(self): - * if self._size is None: - * result = 1 # <<<<<<<<<<<<<< - * - * for length in self.view.shape[:self.view.ndim]: - */ - __Pyx_INCREF(__pyx_int_1); - __pyx_v_result = __pyx_int_1; - - /* "View.MemoryView":600 - * result = 1 - * - * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< - * result *= length - * - */ - __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); - for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { - __pyx_t_3 = __pyx_t_5; - __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 600, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); - __pyx_t_6 = 0; - - /* "View.MemoryView":601 - * - * for length in self.view.shape[:self.view.ndim]: - * result *= length # <<<<<<<<<<<<<< - * - * self._size = result - */ - __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 601, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); - __pyx_t_6 = 0; - } - - /* "View.MemoryView":603 - * result *= length - * - * self._size = result # <<<<<<<<<<<<<< - * - * return self._size - */ - __Pyx_INCREF(__pyx_v_result); - __Pyx_GIVEREF(__pyx_v_result); - __Pyx_GOTREF(__pyx_v_self->_size); - __Pyx_DECREF(__pyx_v_self->_size); - __pyx_v_self->_size = __pyx_v_result; - - /* "View.MemoryView":597 - * @property - * def size(self): - * if self._size is None: # <<<<<<<<<<<<<< - * result = 1 - * - */ - } - - /* "View.MemoryView":605 - * self._size = result - * - * return self._size # <<<<<<<<<<<<<< - * - * def __len__(self): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->_size); - __pyx_r = __pyx_v_self->_size; - goto __pyx_L0; - - /* "View.MemoryView":596 - * - * @property - * def size(self): # <<<<<<<<<<<<<< - * if self._size is None: - * result = 1 - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XDECREF(__pyx_v_length); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":607 - * return self._size - * - * def __len__(self): # <<<<<<<<<<<<<< - * if self.view.ndim >= 1: - * return self.view.shape[0] - */ - -/* Python wrapper */ -static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ -static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { - Py_ssize_t __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__len__", 0); - - /* "View.MemoryView":608 - * - * def __len__(self): - * if self.view.ndim >= 1: # <<<<<<<<<<<<<< - * return self.view.shape[0] - * - */ - __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":609 - * def __len__(self): - * if self.view.ndim >= 1: - * return self.view.shape[0] # <<<<<<<<<<<<<< - * - * return 0 - */ - __pyx_r = (__pyx_v_self->view.shape[0]); - goto __pyx_L0; - - /* "View.MemoryView":608 - * - * def __len__(self): - * if self.view.ndim >= 1: # <<<<<<<<<<<<<< - * return self.view.shape[0] - * - */ - } - - /* "View.MemoryView":611 - * return self.view.shape[0] - * - * return 0 # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":607 - * return self._size - * - * def __len__(self): # <<<<<<<<<<<<<< - * if self.view.ndim >= 1: - * return self.view.shape[0] - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":613 - * return 0 - * - * def __repr__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__, - * id(self)) - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "View.MemoryView":614 - * - * def __repr__(self): - * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< - * id(self)) - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 614, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 614, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 614, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":615 - * def __repr__(self): - * return "" % (self.base.__class__.__name__, - * id(self)) # <<<<<<<<<<<<<< - * - * def __str__(self): - */ - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 615, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "View.MemoryView":614 - * - * def __repr__(self): - * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< - * id(self)) - * - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 614, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 614, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":613 - * return 0 - * - * def __repr__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__, - * id(self)) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":617 - * id(self)) - * - * def __str__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__,) - * - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__str__", 0); - - /* "View.MemoryView":618 - * - * def __str__(self): - * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 618, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 618, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 618, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 618, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 618, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":617 - * id(self)) - * - * def __str__(self): # <<<<<<<<<<<<<< - * return "" % (self.base.__class__.__name__,) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":621 - * - * - * def is_c_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice *__pyx_v_mslice; - __Pyx_memviewslice __pyx_v_tmp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_c_contig", 0); - - /* "View.MemoryView":624 - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 624, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":625 - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) - * return slice_is_contig(mslice[0], 'C', self.view.ndim) # <<<<<<<<<<<<<< - * - * def is_f_contig(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 625, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":621 - * - * - * def is_c_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":627 - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - * def is_f_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice *__pyx_v_mslice; - __Pyx_memviewslice __pyx_v_tmp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice *__pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("is_f_contig", 0); - - /* "View.MemoryView":630 - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - */ - __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(2, 630, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":631 - * cdef __Pyx_memviewslice tmp - * mslice = get_slice_from_memview(self, &tmp) - * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< - * - * def copy(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 631, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":627 - * return slice_is_contig(mslice[0], 'C', self.view.ndim) - * - * def is_f_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":633 - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - * def copy(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice __pyx_v_mslice; - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy", 0); - - /* "View.MemoryView":635 - * def copy(self): - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< - * - * slice_copy(self, &mslice) - */ - __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); - - /* "View.MemoryView":637 - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - * - * slice_copy(self, &mslice) # <<<<<<<<<<<<<< - * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, - * self.view.itemsize, - */ - __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); - - /* "View.MemoryView":638 - * - * slice_copy(self, &mslice) - * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< - * self.view.itemsize, - * flags|PyBUF_C_CONTIGUOUS, - */ - __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), ((char *)"c"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(2, 638, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":643 - * self.dtype_is_object) - * - * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< - * - * def copy_fortran(self): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 643, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":633 - * return slice_is_contig(mslice[0], 'F', self.view.ndim) - * - * def copy(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice mslice - * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":645 - * return memoryview_copy_from_slice(self, &mslice) - * - * def copy_fortran(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - */ - -/* Python wrapper */ -static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); - __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { - __Pyx_memviewslice __pyx_v_src; - __Pyx_memviewslice __pyx_v_dst; - int __pyx_v_flags; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_memviewslice __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("copy_fortran", 0); - - /* "View.MemoryView":647 - * def copy_fortran(self): - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< - * - * slice_copy(self, &src) - */ - __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); - - /* "View.MemoryView":649 - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - * - * slice_copy(self, &src) # <<<<<<<<<<<<<< - * dst = slice_copy_contig(&src, "fortran", self.view.ndim, - * self.view.itemsize, - */ - __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); - - /* "View.MemoryView":650 - * - * slice_copy(self, &src) - * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< - * self.view.itemsize, - * flags|PyBUF_F_CONTIGUOUS, - */ - __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), ((char *)"fortran"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(2, 650, __pyx_L1_error) - __pyx_v_dst = __pyx_t_1; - - /* "View.MemoryView":655 - * self.dtype_is_object) - * - * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 655, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":645 - * return memoryview_copy_from_slice(self, &mslice) - * - * def copy_fortran(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice src, dst - * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryview___reduce_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(2, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryview_2__setstate_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(2, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":659 - * - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - */ - -static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { - struct __pyx_memoryview_obj *__pyx_v_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); - - /* "View.MemoryView":660 - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): - * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< - * result.typeinfo = typeinfo - * return result - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 660, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 660, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 660, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_o); - __Pyx_GIVEREF(__pyx_v_o); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 660, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":661 - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo # <<<<<<<<<<<<<< - * return result - * - */ - __pyx_v_result->typeinfo = __pyx_v_typeinfo; - - /* "View.MemoryView":662 - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - * return result # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_check') - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":659 - * - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":665 - * - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< - * return isinstance(o, memoryview) - * - */ - -static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("memoryview_check", 0); - - /* "View.MemoryView":666 - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): - * return isinstance(o, memoryview) # <<<<<<<<<<<<<< - * - * cdef tuple _unellipsify(object index, int ndim): - */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, __pyx_memoryview_type); - __pyx_r = __pyx_t_1; - goto __pyx_L0; - - /* "View.MemoryView":665 - * - * @cname('__pyx_memoryview_check') - * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< - * return isinstance(o, memoryview) - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":668 - * return isinstance(o, memoryview) - * - * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< - * """ - * Replace all ellipses with full slices and fill incomplete indices with - */ - -static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { - PyObject *__pyx_v_tup = NULL; - PyObject *__pyx_v_result = NULL; - int __pyx_v_have_slices; - int __pyx_v_seen_ellipsis; - CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; - PyObject *__pyx_v_item = NULL; - Py_ssize_t __pyx_v_nslices; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - Py_ssize_t __pyx_t_5; - PyObject *(*__pyx_t_6)(PyObject *); - PyObject *__pyx_t_7 = NULL; - Py_ssize_t __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; - PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_unellipsify", 0); - - /* "View.MemoryView":673 - * full slices. - * """ - * if not isinstance(index, tuple): # <<<<<<<<<<<<<< - * tup = (index,) - * else: - */ - __pyx_t_1 = PyTuple_Check(__pyx_v_index); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":674 - * """ - * if not isinstance(index, tuple): - * tup = (index,) # <<<<<<<<<<<<<< - * else: - * tup = index - */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 674, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_index); - __Pyx_GIVEREF(__pyx_v_index); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); - __pyx_v_tup = __pyx_t_3; - __pyx_t_3 = 0; - - /* "View.MemoryView":673 - * full slices. - * """ - * if not isinstance(index, tuple): # <<<<<<<<<<<<<< - * tup = (index,) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":676 - * tup = (index,) - * else: - * tup = index # <<<<<<<<<<<<<< - * - * result = [] - */ - /*else*/ { - __Pyx_INCREF(__pyx_v_index); - __pyx_v_tup = __pyx_v_index; - } - __pyx_L3:; - - /* "View.MemoryView":678 - * tup = index - * - * result = [] # <<<<<<<<<<<<<< - * have_slices = False - * seen_ellipsis = False - */ - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 678, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_result = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":679 - * - * result = [] - * have_slices = False # <<<<<<<<<<<<<< - * seen_ellipsis = False - * for idx, item in enumerate(tup): - */ - __pyx_v_have_slices = 0; - - /* "View.MemoryView":680 - * result = [] - * have_slices = False - * seen_ellipsis = False # <<<<<<<<<<<<<< - * for idx, item in enumerate(tup): - * if item is Ellipsis: - */ - __pyx_v_seen_ellipsis = 0; - - /* "View.MemoryView":681 - * have_slices = False - * seen_ellipsis = False - * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< - * if item is Ellipsis: - * if not seen_ellipsis: - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_t_3 = __pyx_int_0; - if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { - __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - } else { - __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 681, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 681, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_6)) { - if (likely(PyList_CheckExact(__pyx_t_4))) { - if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(2, 681, __pyx_L1_error) - #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 681, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - } else { - if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(2, 681, __pyx_L1_error) - #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 681, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - #endif - } - } else { - __pyx_t_7 = __pyx_t_6(__pyx_t_4); - if (unlikely(!__pyx_t_7)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(2, 681, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_7); - } - __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); - __pyx_t_7 = 0; - __Pyx_INCREF(__pyx_t_3); - __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); - __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 681, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); - __pyx_t_3 = __pyx_t_7; - __pyx_t_7 = 0; - - /* "View.MemoryView":682 - * seen_ellipsis = False - * for idx, item in enumerate(tup): - * if item is Ellipsis: # <<<<<<<<<<<<<< - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - */ - __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":683 - * for idx, item in enumerate(tup): - * if item is Ellipsis: - * if not seen_ellipsis: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True - */ - __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":684 - * if item is Ellipsis: - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< - * seen_ellipsis = True - * else: - */ - __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == ((Py_ssize_t)-1))) __PYX_ERR(2, 684, __pyx_L1_error) - __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 684, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - { Py_ssize_t __pyx_temp; - for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { - __Pyx_INCREF(__pyx_slice__17); - __Pyx_GIVEREF(__pyx_slice__17); - PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__17); - } - } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 684, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "View.MemoryView":685 - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True # <<<<<<<<<<<<<< - * else: - * result.append(slice(None)) - */ - __pyx_v_seen_ellipsis = 1; - - /* "View.MemoryView":683 - * for idx, item in enumerate(tup): - * if item is Ellipsis: - * if not seen_ellipsis: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - * seen_ellipsis = True - */ - goto __pyx_L7; - } - - /* "View.MemoryView":687 - * seen_ellipsis = True - * else: - * result.append(slice(None)) # <<<<<<<<<<<<<< - * have_slices = True - * else: - */ - /*else*/ { - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__17); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 687, __pyx_L1_error) - } - __pyx_L7:; - - /* "View.MemoryView":688 - * else: - * result.append(slice(None)) - * have_slices = True # <<<<<<<<<<<<<< - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): - */ - __pyx_v_have_slices = 1; - - /* "View.MemoryView":682 - * seen_ellipsis = False - * for idx, item in enumerate(tup): - * if item is Ellipsis: # <<<<<<<<<<<<<< - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) - */ - goto __pyx_L6; - } - - /* "View.MemoryView":690 - * have_slices = True - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - */ - /*else*/ { - __pyx_t_2 = PySlice_Check(__pyx_v_item); - __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_10) { - } else { - __pyx_t_1 = __pyx_t_10; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); - __pyx_t_1 = __pyx_t_10; - __pyx_L9_bool_binop_done:; - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":691 - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): - * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< - * - * have_slices = have_slices or isinstance(item, slice) - */ - __pyx_t_7 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 691, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_11 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(2, 691, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_Raise(__pyx_t_11, 0, 0, 0); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __PYX_ERR(2, 691, __pyx_L1_error) - - /* "View.MemoryView":690 - * have_slices = True - * else: - * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - */ - } - - /* "View.MemoryView":693 - * raise TypeError("Cannot index with type '%s'" % type(item)) - * - * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< - * result.append(item) - * - */ - __pyx_t_10 = (__pyx_v_have_slices != 0); - if (!__pyx_t_10) { - } else { - __pyx_t_1 = __pyx_t_10; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_10 = PySlice_Check(__pyx_v_item); - __pyx_t_2 = (__pyx_t_10 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L11_bool_binop_done:; - __pyx_v_have_slices = __pyx_t_1; - - /* "View.MemoryView":694 - * - * have_slices = have_slices or isinstance(item, slice) - * result.append(item) # <<<<<<<<<<<<<< - * - * nslices = ndim - len(result) - */ - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 694, __pyx_L1_error) - } - __pyx_L6:; - - /* "View.MemoryView":681 - * have_slices = False - * seen_ellipsis = False - * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< - * if item is Ellipsis: - * if not seen_ellipsis: - */ - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":696 - * result.append(item) - * - * nslices = ndim - len(result) # <<<<<<<<<<<<<< - * if nslices: - * result.extend([slice(None)] * nslices) - */ - __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(2, 696, __pyx_L1_error) - __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); - - /* "View.MemoryView":697 - * - * nslices = ndim - len(result) - * if nslices: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * nslices) - * - */ - __pyx_t_1 = (__pyx_v_nslices != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":698 - * nslices = ndim - len(result) - * if nslices: - * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< - * - * return have_slices or nslices, tuple(result) - */ - __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - { Py_ssize_t __pyx_temp; - for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { - __Pyx_INCREF(__pyx_slice__17); - __Pyx_GIVEREF(__pyx_slice__17); - PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__17); - } - } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 698, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":697 - * - * nslices = ndim - len(result) - * if nslices: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * nslices) - * - */ - } - - /* "View.MemoryView":700 - * result.extend([slice(None)] * nslices) - * - * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - */ - __Pyx_XDECREF(__pyx_r); - if (!__pyx_v_have_slices) { - } else { - __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 700, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L14_bool_binop_done; - } - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 700, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_L14_bool_binop_done:; - __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 700, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(2, 700, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_4); - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_r = ((PyObject*)__pyx_t_11); - __pyx_t_11 = 0; - goto __pyx_L0; - - /* "View.MemoryView":668 - * return isinstance(o, memoryview) - * - * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< - * """ - * Replace all ellipses with full slices and fill incomplete indices with - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_tup); - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XDECREF(__pyx_v_idx); - __Pyx_XDECREF(__pyx_v_item); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":702 - * return have_slices or nslices, tuple(result) - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - */ - -static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t *__pyx_t_1; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); - - /* "View.MemoryView":703 - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") - */ - __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); - for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { - __pyx_t_1 = __pyx_t_3; - __pyx_v_suboffset = (__pyx_t_1[0]); - - /* "View.MemoryView":704 - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * raise ValueError("Indirect dimensions not supported") - * - */ - __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); - if (unlikely(__pyx_t_4)) { - - /* "View.MemoryView":705 - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 705, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __PYX_ERR(2, 705, __pyx_L1_error) - - /* "View.MemoryView":704 - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * raise ValueError("Indirect dimensions not supported") - * - */ - } - } - - /* "View.MemoryView":702 - * return have_slices or nslices, tuple(result) - * - * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":712 - * - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< - * cdef int new_ndim = 0, suboffset_dim = -1, dim - * cdef bint negative_step - */ - -static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { - int __pyx_v_new_ndim; - int __pyx_v_suboffset_dim; - int __pyx_v_dim; - __Pyx_memviewslice __pyx_v_src; - __Pyx_memviewslice __pyx_v_dst; - __Pyx_memviewslice *__pyx_v_p_src; - struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; - __Pyx_memviewslice *__pyx_v_p_dst; - int *__pyx_v_p_suboffset_dim; - Py_ssize_t __pyx_v_start; - Py_ssize_t __pyx_v_stop; - Py_ssize_t __pyx_v_step; - int __pyx_v_have_start; - int __pyx_v_have_stop; - int __pyx_v_have_step; - PyObject *__pyx_v_index = NULL; - struct __pyx_memoryview_obj *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - struct __pyx_memoryview_obj *__pyx_t_4; - char *__pyx_t_5; - int __pyx_t_6; - Py_ssize_t __pyx_t_7; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; - Py_ssize_t __pyx_t_10; - int __pyx_t_11; - Py_ssize_t __pyx_t_12; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memview_slice", 0); - - /* "View.MemoryView":713 - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): - * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< - * cdef bint negative_step - * cdef __Pyx_memviewslice src, dst - */ - __pyx_v_new_ndim = 0; - __pyx_v_suboffset_dim = -1; - - /* "View.MemoryView":720 - * - * - * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< - * - * cdef _memoryviewslice memviewsliceobj - */ - (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); - - /* "View.MemoryView":724 - * cdef _memoryviewslice memviewsliceobj - * - * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< - * - * if isinstance(memview, _memoryviewslice): - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(2, 724, __pyx_L1_error) - } - } - #endif - - /* "View.MemoryView":726 - * assert memview.view.ndim > 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":727 - * - * if isinstance(memview, _memoryviewslice): - * memviewsliceobj = memview # <<<<<<<<<<<<<< - * p_src = &memviewsliceobj.from_slice - * else: - */ - if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(2, 727, __pyx_L1_error) - __pyx_t_3 = ((PyObject *)__pyx_v_memview); - __Pyx_INCREF(__pyx_t_3); - __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":728 - * if isinstance(memview, _memoryviewslice): - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< - * else: - * slice_copy(memview, &src) - */ - __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); - - /* "View.MemoryView":726 - * assert memview.view.ndim > 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice - */ - goto __pyx_L3; - } - - /* "View.MemoryView":730 - * p_src = &memviewsliceobj.from_slice - * else: - * slice_copy(memview, &src) # <<<<<<<<<<<<<< - * p_src = &src - * - */ - /*else*/ { - __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); - - /* "View.MemoryView":731 - * else: - * slice_copy(memview, &src) - * p_src = &src # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_p_src = (&__pyx_v_src); - } - __pyx_L3:; - - /* "View.MemoryView":737 - * - * - * dst.memview = p_src.memview # <<<<<<<<<<<<<< - * dst.data = p_src.data - * - */ - __pyx_t_4 = __pyx_v_p_src->memview; - __pyx_v_dst.memview = __pyx_t_4; - - /* "View.MemoryView":738 - * - * dst.memview = p_src.memview - * dst.data = p_src.data # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __pyx_v_p_src->data; - __pyx_v_dst.data = __pyx_t_5; - - /* "View.MemoryView":743 - * - * - * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< - * cdef int *p_suboffset_dim = &suboffset_dim - * cdef Py_ssize_t start, stop, step - */ - __pyx_v_p_dst = (&__pyx_v_dst); - - /* "View.MemoryView":744 - * - * cdef __Pyx_memviewslice *p_dst = &dst - * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< - * cdef Py_ssize_t start, stop, step - * cdef bint have_start, have_stop, have_step - */ - __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); - - /* "View.MemoryView":748 - * cdef bint have_start, have_stop, have_step - * - * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< - * if PyIndex_Check(index): - * slice_memviewslice( - */ - __pyx_t_6 = 0; - if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { - __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; - __pyx_t_8 = NULL; - } else { - __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 748, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 748, __pyx_L1_error) - } - for (;;) { - if (likely(!__pyx_t_8)) { - if (likely(PyList_CheckExact(__pyx_t_3))) { - if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(2, 748, __pyx_L1_error) - #else - __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 748, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - } else { - if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(2, 748, __pyx_L1_error) - #else - __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 748, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - #endif - } - } else { - __pyx_t_9 = __pyx_t_8(__pyx_t_3); - if (unlikely(!__pyx_t_9)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(2, 748, __pyx_L1_error) - } - break; - } - __Pyx_GOTREF(__pyx_t_9); - } - __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); - __pyx_t_9 = 0; - __pyx_v_dim = __pyx_t_6; - __pyx_t_6 = (__pyx_t_6 + 1); - - /* "View.MemoryView":749 - * - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): # <<<<<<<<<<<<<< - * slice_memviewslice( - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - */ - __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":753 - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< - * 0, 0, 0, # have_{start,stop,step} - * False) - */ - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 753, __pyx_L1_error) - - /* "View.MemoryView":750 - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): - * slice_memviewslice( # <<<<<<<<<<<<<< - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - */ - __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(2, 750, __pyx_L1_error) - - /* "View.MemoryView":749 - * - * for dim, index in enumerate(indices): - * if PyIndex_Check(index): # <<<<<<<<<<<<<< - * slice_memviewslice( - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - */ - goto __pyx_L6; - } - - /* "View.MemoryView":756 - * 0, 0, 0, # have_{start,stop,step} - * False) - * elif index is None: # <<<<<<<<<<<<<< - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - */ - __pyx_t_2 = (__pyx_v_index == Py_None); - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":757 - * False) - * elif index is None: - * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 - */ - (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; - - /* "View.MemoryView":758 - * elif index is None: - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< - * p_dst.suboffsets[new_ndim] = -1 - * new_ndim += 1 - */ - (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; - - /* "View.MemoryView":759 - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< - * new_ndim += 1 - * else: - */ - (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1L; - - /* "View.MemoryView":760 - * p_dst.strides[new_ndim] = 0 - * p_dst.suboffsets[new_ndim] = -1 - * new_ndim += 1 # <<<<<<<<<<<<<< - * else: - * start = index.start or 0 - */ - __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); - - /* "View.MemoryView":756 - * 0, 0, 0, # have_{start,stop,step} - * False) - * elif index is None: # <<<<<<<<<<<<<< - * p_dst.shape[new_ndim] = 1 - * p_dst.strides[new_ndim] = 0 - */ - goto __pyx_L6; - } - - /* "View.MemoryView":762 - * new_ndim += 1 - * else: - * start = index.start or 0 # <<<<<<<<<<<<<< - * stop = index.stop or 0 - * step = index.step or 0 - */ - /*else*/ { - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 762, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 762, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 762, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L7_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L7_bool_binop_done:; - __pyx_v_start = __pyx_t_10; - - /* "View.MemoryView":763 - * else: - * start = index.start or 0 - * stop = index.stop or 0 # <<<<<<<<<<<<<< - * step = index.step or 0 - * - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 763, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 763, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 763, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L9_bool_binop_done:; - __pyx_v_stop = __pyx_t_10; - - /* "View.MemoryView":764 - * start = index.start or 0 - * stop = index.stop or 0 - * step = index.step or 0 # <<<<<<<<<<<<<< - * - * have_start = index.start is not None - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 764, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(2, 764, __pyx_L1_error) - if (!__pyx_t_1) { - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 764, __pyx_L1_error) - __pyx_t_10 = __pyx_t_12; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_10 = 0; - __pyx_L11_bool_binop_done:; - __pyx_v_step = __pyx_t_10; - - /* "View.MemoryView":766 - * step = index.step or 0 - * - * have_start = index.start is not None # <<<<<<<<<<<<<< - * have_stop = index.stop is not None - * have_step = index.step is not None - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 766, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_start = __pyx_t_1; - - /* "View.MemoryView":767 - * - * have_start = index.start is not None - * have_stop = index.stop is not None # <<<<<<<<<<<<<< - * have_step = index.step is not None - * - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 767, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_stop = __pyx_t_1; - - /* "View.MemoryView":768 - * have_start = index.start is not None - * have_stop = index.stop is not None - * have_step = index.step is not None # <<<<<<<<<<<<<< - * - * slice_memviewslice( - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(2, 768, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = (__pyx_t_9 != Py_None); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_v_have_step = __pyx_t_1; - - /* "View.MemoryView":770 - * have_step = index.step is not None - * - * slice_memviewslice( # <<<<<<<<<<<<<< - * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], - * dim, new_ndim, p_suboffset_dim, - */ - __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(2, 770, __pyx_L1_error) - - /* "View.MemoryView":776 - * have_start, have_stop, have_step, - * True) - * new_ndim += 1 # <<<<<<<<<<<<<< - * - * if isinstance(memview, _memoryviewslice): - */ - __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); - } - __pyx_L6:; - - /* "View.MemoryView":748 - * cdef bint have_start, have_stop, have_step - * - * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< - * if PyIndex_Check(index): - * slice_memviewslice( - */ - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":778 - * new_ndim += 1 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":779 - * - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, - */ - __Pyx_XDECREF(((PyObject *)__pyx_r)); - - /* "View.MemoryView":780 - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< - * memviewsliceobj.to_dtype_func, - * memview.dtype_is_object) - */ - if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(2, 780, __pyx_L1_error) } - - /* "View.MemoryView":781 - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * else: - */ - if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(2, 781, __pyx_L1_error) } - - /* "View.MemoryView":779 - * - * if isinstance(memview, _memoryviewslice): - * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< - * memviewsliceobj.to_object_func, - * memviewsliceobj.to_dtype_func, - */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 779, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(2, 779, __pyx_L1_error) - __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":778 - * new_ndim += 1 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - */ - } - - /* "View.MemoryView":784 - * memview.dtype_is_object) - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * - */ - /*else*/ { - __Pyx_XDECREF(((PyObject *)__pyx_r)); - - /* "View.MemoryView":785 - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, - * memview.dtype_is_object) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 784, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "View.MemoryView":784 - * memview.dtype_is_object) - * else: - * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< - * memview.dtype_is_object) - * - */ - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(2, 784, __pyx_L1_error) - __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":712 - * - * @cname('__pyx_memview_slice') - * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< - * cdef int new_ndim = 0, suboffset_dim = -1, dim - * cdef bint negative_step - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); - __Pyx_XDECREF(__pyx_v_index); - __Pyx_XGIVEREF((PyObject *)__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":809 - * - * @cname('__pyx_memoryview_slice_memviewslice') - * cdef int slice_memviewslice( # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, - */ - -static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { - Py_ssize_t __pyx_v_new_shape; - int __pyx_v_negative_step; - int __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":829 - * cdef bint negative_step - * - * if not is_slice: # <<<<<<<<<<<<<< - * - * if start < 0: - */ - __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":831 - * if not is_slice: - * - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if not 0 <= start < shape: - */ - __pyx_t_1 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":832 - * - * if start < 0: - * start += shape # <<<<<<<<<<<<<< - * if not 0 <= start < shape: - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - */ - __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - - /* "View.MemoryView":831 - * if not is_slice: - * - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if not 0 <= start < shape: - */ - } - - /* "View.MemoryView":833 - * if start < 0: - * start += shape - * if not 0 <= start < shape: # <<<<<<<<<<<<<< - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - * else: - */ - __pyx_t_1 = (0 <= __pyx_v_start); - if (__pyx_t_1) { - __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); - } - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":834 - * start += shape - * if not 0 <= start < shape: - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< - * else: - * - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"Index out of bounds (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 834, __pyx_L1_error) - - /* "View.MemoryView":833 - * if start < 0: - * start += shape - * if not 0 <= start < shape: # <<<<<<<<<<<<<< - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - * else: - */ - } - - /* "View.MemoryView":829 - * cdef bint negative_step - * - * if not is_slice: # <<<<<<<<<<<<<< - * - * if start < 0: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":837 - * else: - * - * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< - * - * if have_step and step == 0: - */ - /*else*/ { - __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); - if (__pyx_t_1) { - } else { - __pyx_t_2 = __pyx_t_1; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_1 = ((__pyx_v_step < 0) != 0); - __pyx_t_2 = __pyx_t_1; - __pyx_L6_bool_binop_done:; - __pyx_v_negative_step = __pyx_t_2; - - /* "View.MemoryView":839 - * negative_step = have_step != 0 and step < 0 - * - * if have_step and step == 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) - * - */ - __pyx_t_1 = (__pyx_v_have_step != 0); - if (__pyx_t_1) { - } else { - __pyx_t_2 = __pyx_t_1; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_1 = ((__pyx_v_step == 0) != 0); - __pyx_t_2 = __pyx_t_1; - __pyx_L9_bool_binop_done:; - if (__pyx_t_2) { - - /* "View.MemoryView":840 - * - * if have_step and step == 0: - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Step may not be zero (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 840, __pyx_L1_error) - - /* "View.MemoryView":839 - * negative_step = have_step != 0 and step < 0 - * - * if have_step and step == 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) - * - */ - } - - /* "View.MemoryView":843 - * - * - * if have_start: # <<<<<<<<<<<<<< - * if start < 0: - * start += shape - */ - __pyx_t_2 = (__pyx_v_have_start != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":844 - * - * if have_start: - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if start < 0: - */ - __pyx_t_2 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":845 - * if have_start: - * if start < 0: - * start += shape # <<<<<<<<<<<<<< - * if start < 0: - * start = 0 - */ - __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - - /* "View.MemoryView":846 - * if start < 0: - * start += shape - * if start < 0: # <<<<<<<<<<<<<< - * start = 0 - * elif start >= shape: - */ - __pyx_t_2 = ((__pyx_v_start < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":847 - * start += shape - * if start < 0: - * start = 0 # <<<<<<<<<<<<<< - * elif start >= shape: - * if negative_step: - */ - __pyx_v_start = 0; - - /* "View.MemoryView":846 - * if start < 0: - * start += shape - * if start < 0: # <<<<<<<<<<<<<< - * start = 0 - * elif start >= shape: - */ - } - - /* "View.MemoryView":844 - * - * if have_start: - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if start < 0: - */ - goto __pyx_L12; - } - - /* "View.MemoryView":848 - * if start < 0: - * start = 0 - * elif start >= shape: # <<<<<<<<<<<<<< - * if negative_step: - * start = shape - 1 - */ - __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":849 - * start = 0 - * elif start >= shape: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":850 - * elif start >= shape: - * if negative_step: - * start = shape - 1 # <<<<<<<<<<<<<< - * else: - * start = shape - */ - __pyx_v_start = (__pyx_v_shape - 1); - - /* "View.MemoryView":849 - * start = 0 - * elif start >= shape: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - goto __pyx_L14; - } - - /* "View.MemoryView":852 - * start = shape - 1 - * else: - * start = shape # <<<<<<<<<<<<<< - * else: - * if negative_step: - */ - /*else*/ { - __pyx_v_start = __pyx_v_shape; - } - __pyx_L14:; - - /* "View.MemoryView":848 - * if start < 0: - * start = 0 - * elif start >= shape: # <<<<<<<<<<<<<< - * if negative_step: - * start = shape - 1 - */ - } - __pyx_L12:; - - /* "View.MemoryView":843 - * - * - * if have_start: # <<<<<<<<<<<<<< - * if start < 0: - * start += shape - */ - goto __pyx_L11; - } - - /* "View.MemoryView":854 - * start = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":855 - * else: - * if negative_step: - * start = shape - 1 # <<<<<<<<<<<<<< - * else: - * start = 0 - */ - __pyx_v_start = (__pyx_v_shape - 1); - - /* "View.MemoryView":854 - * start = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - goto __pyx_L15; - } - - /* "View.MemoryView":857 - * start = shape - 1 - * else: - * start = 0 # <<<<<<<<<<<<<< - * - * if have_stop: - */ - /*else*/ { - __pyx_v_start = 0; - } - __pyx_L15:; - } - __pyx_L11:; - - /* "View.MemoryView":859 - * start = 0 - * - * if have_stop: # <<<<<<<<<<<<<< - * if stop < 0: - * stop += shape - */ - __pyx_t_2 = (__pyx_v_have_stop != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":860 - * - * if have_stop: - * if stop < 0: # <<<<<<<<<<<<<< - * stop += shape - * if stop < 0: - */ - __pyx_t_2 = ((__pyx_v_stop < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":861 - * if have_stop: - * if stop < 0: - * stop += shape # <<<<<<<<<<<<<< - * if stop < 0: - * stop = 0 - */ - __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); - - /* "View.MemoryView":862 - * if stop < 0: - * stop += shape - * if stop < 0: # <<<<<<<<<<<<<< - * stop = 0 - * elif stop > shape: - */ - __pyx_t_2 = ((__pyx_v_stop < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":863 - * stop += shape - * if stop < 0: - * stop = 0 # <<<<<<<<<<<<<< - * elif stop > shape: - * stop = shape - */ - __pyx_v_stop = 0; - - /* "View.MemoryView":862 - * if stop < 0: - * stop += shape - * if stop < 0: # <<<<<<<<<<<<<< - * stop = 0 - * elif stop > shape: - */ - } - - /* "View.MemoryView":860 - * - * if have_stop: - * if stop < 0: # <<<<<<<<<<<<<< - * stop += shape - * if stop < 0: - */ - goto __pyx_L17; - } - - /* "View.MemoryView":864 - * if stop < 0: - * stop = 0 - * elif stop > shape: # <<<<<<<<<<<<<< - * stop = shape - * else: - */ - __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":865 - * stop = 0 - * elif stop > shape: - * stop = shape # <<<<<<<<<<<<<< - * else: - * if negative_step: - */ - __pyx_v_stop = __pyx_v_shape; - - /* "View.MemoryView":864 - * if stop < 0: - * stop = 0 - * elif stop > shape: # <<<<<<<<<<<<<< - * stop = shape - * else: - */ - } - __pyx_L17:; - - /* "View.MemoryView":859 - * start = 0 - * - * if have_stop: # <<<<<<<<<<<<<< - * if stop < 0: - * stop += shape - */ - goto __pyx_L16; - } - - /* "View.MemoryView":867 - * stop = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * stop = -1 - * else: - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":868 - * else: - * if negative_step: - * stop = -1 # <<<<<<<<<<<<<< - * else: - * stop = shape - */ - __pyx_v_stop = -1L; - - /* "View.MemoryView":867 - * stop = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * stop = -1 - * else: - */ - goto __pyx_L19; - } - - /* "View.MemoryView":870 - * stop = -1 - * else: - * stop = shape # <<<<<<<<<<<<<< - * - * if not have_step: - */ - /*else*/ { - __pyx_v_stop = __pyx_v_shape; - } - __pyx_L19:; - } - __pyx_L16:; - - /* "View.MemoryView":872 - * stop = shape - * - * if not have_step: # <<<<<<<<<<<<<< - * step = 1 - * - */ - __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":873 - * - * if not have_step: - * step = 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_step = 1; - - /* "View.MemoryView":872 - * stop = shape - * - * if not have_step: # <<<<<<<<<<<<<< - * step = 1 - * - */ - } - - /* "View.MemoryView":877 - * - * with cython.cdivision(True): - * new_shape = (stop - start) // step # <<<<<<<<<<<<<< - * - * if (stop - start) - step * new_shape: - */ - __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); - - /* "View.MemoryView":879 - * new_shape = (stop - start) // step - * - * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< - * new_shape += 1 - * - */ - __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":880 - * - * if (stop - start) - step * new_shape: - * new_shape += 1 # <<<<<<<<<<<<<< - * - * if new_shape < 0: - */ - __pyx_v_new_shape = (__pyx_v_new_shape + 1); - - /* "View.MemoryView":879 - * new_shape = (stop - start) // step - * - * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< - * new_shape += 1 - * - */ - } - - /* "View.MemoryView":882 - * new_shape += 1 - * - * if new_shape < 0: # <<<<<<<<<<<<<< - * new_shape = 0 - * - */ - __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":883 - * - * if new_shape < 0: - * new_shape = 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_new_shape = 0; - - /* "View.MemoryView":882 - * new_shape += 1 - * - * if new_shape < 0: # <<<<<<<<<<<<<< - * new_shape = 0 - * - */ - } - - /* "View.MemoryView":886 - * - * - * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< - * dst.shape[new_ndim] = new_shape - * dst.suboffsets[new_ndim] = suboffset - */ - (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); - - /* "View.MemoryView":887 - * - * dst.strides[new_ndim] = stride * step - * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< - * dst.suboffsets[new_ndim] = suboffset - * - */ - (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; - - /* "View.MemoryView":888 - * dst.strides[new_ndim] = stride * step - * dst.shape[new_ndim] = new_shape - * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< - * - * - */ - (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; - } - __pyx_L3:; - - /* "View.MemoryView":891 - * - * - * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< - * dst.data += start * stride - * else: - */ - __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":892 - * - * if suboffset_dim[0] < 0: - * dst.data += start * stride # <<<<<<<<<<<<<< - * else: - * dst.suboffsets[suboffset_dim[0]] += start * stride - */ - __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); - - /* "View.MemoryView":891 - * - * - * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< - * dst.data += start * stride - * else: - */ - goto __pyx_L23; - } - - /* "View.MemoryView":894 - * dst.data += start * stride - * else: - * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< - * - * if suboffset >= 0: - */ - /*else*/ { - __pyx_t_3 = (__pyx_v_suboffset_dim[0]); - (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); - } - __pyx_L23:; - - /* "View.MemoryView":896 - * dst.suboffsets[suboffset_dim[0]] += start * stride - * - * if suboffset >= 0: # <<<<<<<<<<<<<< - * if not is_slice: - * if new_ndim == 0: - */ - __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":897 - * - * if suboffset >= 0: - * if not is_slice: # <<<<<<<<<<<<<< - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset - */ - __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":898 - * if suboffset >= 0: - * if not is_slice: - * if new_ndim == 0: # <<<<<<<<<<<<<< - * dst.data = ( dst.data)[0] + suboffset - * else: - */ - __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":899 - * if not is_slice: - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " - */ - __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); - - /* "View.MemoryView":898 - * if suboffset >= 0: - * if not is_slice: - * if new_ndim == 0: # <<<<<<<<<<<<<< - * dst.data = ( dst.data)[0] + suboffset - * else: - */ - goto __pyx_L26; - } - - /* "View.MemoryView":901 - * dst.data = ( dst.data)[0] + suboffset - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< - * "must be indexed and not sliced", dim) - * else: - */ - /*else*/ { - - /* "View.MemoryView":902 - * else: - * _err_dim(IndexError, "All dimensions preceding dimension %d " - * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< - * else: - * suboffset_dim[0] = new_ndim - */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"All dimensions preceding dimension %d must be indexed and not sliced"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 901, __pyx_L1_error) - } - __pyx_L26:; - - /* "View.MemoryView":897 - * - * if suboffset >= 0: - * if not is_slice: # <<<<<<<<<<<<<< - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset - */ - goto __pyx_L25; - } - - /* "View.MemoryView":904 - * "must be indexed and not sliced", dim) - * else: - * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< - * - * return 0 - */ - /*else*/ { - (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; - } - __pyx_L25:; - - /* "View.MemoryView":896 - * dst.suboffsets[suboffset_dim[0]] += start * stride - * - * if suboffset >= 0: # <<<<<<<<<<<<<< - * if not is_slice: - * if new_ndim == 0: - */ - } - - /* "View.MemoryView":906 - * suboffset_dim[0] = new_ndim - * - * return 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":809 - * - * @cname('__pyx_memoryview_slice_memviewslice') - * cdef int slice_memviewslice( # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = -1; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":912 - * - * @cname('__pyx_pybuffer_index') - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - */ - -static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { - Py_ssize_t __pyx_v_shape; - Py_ssize_t __pyx_v_stride; - Py_ssize_t __pyx_v_suboffset; - Py_ssize_t __pyx_v_itemsize; - char *__pyx_v_resultp; - char *__pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("pybuffer_index", 0); - - /* "View.MemoryView":914 - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< - * cdef Py_ssize_t itemsize = view.itemsize - * cdef char *resultp - */ - __pyx_v_suboffset = -1L; - - /* "View.MemoryView":915 - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< - * cdef char *resultp - * - */ - __pyx_t_1 = __pyx_v_view->itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":918 - * cdef char *resultp - * - * if view.ndim == 0: # <<<<<<<<<<<<<< - * shape = view.len / itemsize - * stride = itemsize - */ - __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":919 - * - * if view.ndim == 0: - * shape = view.len / itemsize # <<<<<<<<<<<<<< - * stride = itemsize - * else: - */ - if (unlikely(__pyx_v_itemsize == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - __PYX_ERR(2, 919, __pyx_L1_error) - } - else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { - PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); - __PYX_ERR(2, 919, __pyx_L1_error) - } - __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); - - /* "View.MemoryView":920 - * if view.ndim == 0: - * shape = view.len / itemsize - * stride = itemsize # <<<<<<<<<<<<<< - * else: - * shape = view.shape[dim] - */ - __pyx_v_stride = __pyx_v_itemsize; - - /* "View.MemoryView":918 - * cdef char *resultp - * - * if view.ndim == 0: # <<<<<<<<<<<<<< - * shape = view.len / itemsize - * stride = itemsize - */ - goto __pyx_L3; - } - - /* "View.MemoryView":922 - * stride = itemsize - * else: - * shape = view.shape[dim] # <<<<<<<<<<<<<< - * stride = view.strides[dim] - * if view.suboffsets != NULL: - */ - /*else*/ { - __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); - - /* "View.MemoryView":923 - * else: - * shape = view.shape[dim] - * stride = view.strides[dim] # <<<<<<<<<<<<<< - * if view.suboffsets != NULL: - * suboffset = view.suboffsets[dim] - */ - __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); - - /* "View.MemoryView":924 - * shape = view.shape[dim] - * stride = view.strides[dim] - * if view.suboffsets != NULL: # <<<<<<<<<<<<<< - * suboffset = view.suboffsets[dim] - * - */ - __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":925 - * stride = view.strides[dim] - * if view.suboffsets != NULL: - * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< - * - * if index < 0: - */ - __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); - - /* "View.MemoryView":924 - * shape = view.shape[dim] - * stride = view.strides[dim] - * if view.suboffsets != NULL: # <<<<<<<<<<<<<< - * suboffset = view.suboffsets[dim] - * - */ - } - } - __pyx_L3:; - - /* "View.MemoryView":927 - * suboffset = view.suboffsets[dim] - * - * if index < 0: # <<<<<<<<<<<<<< - * index += view.shape[dim] - * if index < 0: - */ - __pyx_t_2 = ((__pyx_v_index < 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":928 - * - * if index < 0: - * index += view.shape[dim] # <<<<<<<<<<<<<< - * if index < 0: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - */ - __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); - - /* "View.MemoryView":929 - * if index < 0: - * index += view.shape[dim] - * if index < 0: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - __pyx_t_2 = ((__pyx_v_index < 0) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":930 - * index += view.shape[dim] - * if index < 0: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< - * - * if index >= shape: - */ - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 930, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 930, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 930, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(2, 930, __pyx_L1_error) - - /* "View.MemoryView":929 - * if index < 0: - * index += view.shape[dim] - * if index < 0: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - } - - /* "View.MemoryView":927 - * suboffset = view.suboffsets[dim] - * - * if index < 0: # <<<<<<<<<<<<<< - * index += view.shape[dim] - * if index < 0: - */ - } - - /* "View.MemoryView":932 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * if index >= shape: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); - if (unlikely(__pyx_t_2)) { - - /* "View.MemoryView":933 - * - * if index >= shape: - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< - * - * resultp = bufp + index * stride - */ - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 933, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 933, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 933, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(2, 933, __pyx_L1_error) - - /* "View.MemoryView":932 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * if index >= shape: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - } - - /* "View.MemoryView":935 - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - * resultp = bufp + index * stride # <<<<<<<<<<<<<< - * if suboffset >= 0: - * resultp = ( resultp)[0] + suboffset - */ - __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); - - /* "View.MemoryView":936 - * - * resultp = bufp + index * stride - * if suboffset >= 0: # <<<<<<<<<<<<<< - * resultp = ( resultp)[0] + suboffset - * - */ - __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":937 - * resultp = bufp + index * stride - * if suboffset >= 0: - * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< - * - * return resultp - */ - __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); - - /* "View.MemoryView":936 - * - * resultp = bufp + index * stride - * if suboffset >= 0: # <<<<<<<<<<<<<< - * resultp = ( resultp)[0] + suboffset - * - */ - } - - /* "View.MemoryView":939 - * resultp = ( resultp)[0] + suboffset - * - * return resultp # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_resultp; - goto __pyx_L0; - - /* "View.MemoryView":912 - * - * @cname('__pyx_pybuffer_index') - * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< - * Py_ssize_t dim) except NULL: - * cdef Py_ssize_t shape, stride, suboffset = -1 - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":945 - * - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< - * cdef int ndim = memslice.memview.view.ndim - * - */ - -static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { - int __pyx_v_ndim; - Py_ssize_t *__pyx_v_shape; - Py_ssize_t *__pyx_v_strides; - int __pyx_v_i; - int __pyx_v_j; - int __pyx_r; - int __pyx_t_1; - Py_ssize_t *__pyx_t_2; - long __pyx_t_3; - long __pyx_t_4; - Py_ssize_t __pyx_t_5; - Py_ssize_t __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":946 - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: - * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< - * - * cdef Py_ssize_t *shape = memslice.shape - */ - __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; - __pyx_v_ndim = __pyx_t_1; - - /* "View.MemoryView":948 - * cdef int ndim = memslice.memview.view.ndim - * - * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< - * cdef Py_ssize_t *strides = memslice.strides - * - */ - __pyx_t_2 = __pyx_v_memslice->shape; - __pyx_v_shape = __pyx_t_2; - - /* "View.MemoryView":949 - * - * cdef Py_ssize_t *shape = memslice.shape - * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __pyx_v_memslice->strides; - __pyx_v_strides = __pyx_t_2; - - /* "View.MemoryView":953 - * - * cdef int i, j - * for i in range(ndim / 2): # <<<<<<<<<<<<<< - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] - */ - __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); - __pyx_t_4 = __pyx_t_3; - for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_4; __pyx_t_1+=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":954 - * cdef int i, j - * for i in range(ndim / 2): - * j = ndim - 1 - i # <<<<<<<<<<<<<< - * strides[i], strides[j] = strides[j], strides[i] - * shape[i], shape[j] = shape[j], shape[i] - */ - __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); - - /* "View.MemoryView":955 - * for i in range(ndim / 2): - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< - * shape[i], shape[j] = shape[j], shape[i] - * - */ - __pyx_t_5 = (__pyx_v_strides[__pyx_v_j]); - __pyx_t_6 = (__pyx_v_strides[__pyx_v_i]); - (__pyx_v_strides[__pyx_v_i]) = __pyx_t_5; - (__pyx_v_strides[__pyx_v_j]) = __pyx_t_6; - - /* "View.MemoryView":956 - * j = ndim - 1 - i - * strides[i], strides[j] = strides[j], strides[i] - * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: - */ - __pyx_t_6 = (__pyx_v_shape[__pyx_v_j]); - __pyx_t_5 = (__pyx_v_shape[__pyx_v_i]); - (__pyx_v_shape[__pyx_v_i]) = __pyx_t_6; - (__pyx_v_shape[__pyx_v_j]) = __pyx_t_5; - - /* "View.MemoryView":958 - * shape[i], shape[j] = shape[j], shape[i] - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - */ - __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); - if (!__pyx_t_8) { - } else { - __pyx_t_7 = __pyx_t_8; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); - __pyx_t_7 = __pyx_t_8; - __pyx_L6_bool_binop_done:; - if (__pyx_t_7) { - - /* "View.MemoryView":959 - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< - * - * return 1 - */ - __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(2, 959, __pyx_L1_error) - - /* "View.MemoryView":958 - * shape[i], shape[j] = shape[j], shape[i] - * - * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - */ - } - } - - /* "View.MemoryView":961 - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - * return 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 1; - goto __pyx_L0; - - /* "View.MemoryView":945 - * - * @cname('__pyx_memslice_transpose') - * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< - * cdef int ndim = memslice.memview.view.ndim - * - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = 0; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":978 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - */ - -/* Python wrapper */ -static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "View.MemoryView":979 - * - * def __dealloc__(self): - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< - * - * cdef convert_item_to_object(self, char *itemp): - */ - __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); - - /* "View.MemoryView":978 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":981 - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) - */ - -static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("convert_item_to_object", 0); - - /* "View.MemoryView":982 - * - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: # <<<<<<<<<<<<<< - * return self.to_object_func(itemp) - * else: - */ - __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":983 - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) # <<<<<<<<<<<<<< - * else: - * return memoryview.convert_item_to_object(self, itemp) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 983, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":982 - * - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: # <<<<<<<<<<<<<< - * return self.to_object_func(itemp) - * else: - */ - } - - /* "View.MemoryView":985 - * return self.to_object_func(itemp) - * else: - * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< - * - * cdef assign_item_from_object(self, char *itemp, object value): - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 985, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":981 - * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) - * - * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< - * if self.to_object_func != NULL: - * return self.to_object_func(itemp) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":987 - * return memoryview.convert_item_to_object(self, itemp) - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) - */ - -static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("assign_item_from_object", 0); - - /* "View.MemoryView":988 - * - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< - * self.to_dtype_func(itemp, value) - * else: - */ - __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":989 - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< - * else: - * memoryview.assign_item_from_object(self, itemp, value) - */ - __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(2, 989, __pyx_L1_error) - - /* "View.MemoryView":988 - * - * cdef assign_item_from_object(self, char *itemp, object value): - * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< - * self.to_dtype_func(itemp, value) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":991 - * self.to_dtype_func(itemp, value) - * else: - * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< - * - * @property - */ - /*else*/ { - __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 991, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __pyx_L3:; - - /* "View.MemoryView":987 - * return memoryview.convert_item_to_object(self, itemp) - * - * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< - * if self.to_dtype_func != NULL: - * self.to_dtype_func(itemp, value) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":994 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.from_object - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":995 - * @property - * def base(self): - * return self.from_object # <<<<<<<<<<<<<< - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->from_object); - __pyx_r = __pyx_v_self->from_object; - goto __pyx_L0; - - /* "View.MemoryView":994 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.from_object - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryviewslice___reduce_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(2, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf___pyx_memoryviewslice_2__setstate_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(2, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1001 - * - * @cname('__pyx_memoryview_fromslice') - * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< - * int ndim, - * object (*to_object_func)(char *), - */ - -static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { - struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; - Py_ssize_t __pyx_v_suboffset; - PyObject *__pyx_v_length = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - __Pyx_TypeInfo *__pyx_t_4; - Py_buffer __pyx_t_5; - Py_ssize_t *__pyx_t_6; - Py_ssize_t *__pyx_t_7; - Py_ssize_t *__pyx_t_8; - Py_ssize_t __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_fromslice", 0); - - /* "View.MemoryView":1009 - * cdef _memoryviewslice result - * - * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< - * return None - * - */ - __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1010 - * - * if memviewslice.memview == Py_None: - * return None # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - - /* "View.MemoryView":1009 - * cdef _memoryviewslice result - * - * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< - * return None - * - */ - } - - /* "View.MemoryView":1015 - * - * - * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< - * - * result.from_slice = memviewslice - */ - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1015, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1015, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); - __Pyx_INCREF(__pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1015, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":1017 - * result = _memoryviewslice(None, 0, dtype_is_object) - * - * result.from_slice = memviewslice # <<<<<<<<<<<<<< - * __PYX_INC_MEMVIEW(&memviewslice, 1) - * - */ - __pyx_v_result->from_slice = __pyx_v_memviewslice; - - /* "View.MemoryView":1018 - * - * result.from_slice = memviewslice - * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< - * - * result.from_object = ( memviewslice.memview).base - */ - __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); - - /* "View.MemoryView":1020 - * __PYX_INC_MEMVIEW(&memviewslice, 1) - * - * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< - * result.typeinfo = memviewslice.memview.typeinfo - * - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1020, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_v_result->from_object); - __Pyx_DECREF(__pyx_v_result->from_object); - __pyx_v_result->from_object = __pyx_t_2; - __pyx_t_2 = 0; - - /* "View.MemoryView":1021 - * - * result.from_object = ( memviewslice.memview).base - * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< - * - * result.view = memviewslice.memview.view - */ - __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; - __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; - - /* "View.MemoryView":1023 - * result.typeinfo = memviewslice.memview.typeinfo - * - * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< - * result.view.buf = memviewslice.data - * result.view.ndim = ndim - */ - __pyx_t_5 = __pyx_v_memviewslice.memview->view; - __pyx_v_result->__pyx_base.view = __pyx_t_5; - - /* "View.MemoryView":1024 - * - * result.view = memviewslice.memview.view - * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None - */ - __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); - - /* "View.MemoryView":1025 - * result.view = memviewslice.memview.view - * result.view.buf = memviewslice.data - * result.view.ndim = ndim # <<<<<<<<<<<<<< - * (<__pyx_buffer *> &result.view).obj = Py_None - * Py_INCREF(Py_None) - */ - __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; - - /* "View.MemoryView":1026 - * result.view.buf = memviewslice.data - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< - * Py_INCREF(Py_None) - * - */ - ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; - - /* "View.MemoryView":1027 - * result.view.ndim = ndim - * (<__pyx_buffer *> &result.view).obj = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: - */ - Py_INCREF(Py_None); - - /* "View.MemoryView":1029 - * Py_INCREF(Py_None) - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< - * result.flags = PyBUF_RECORDS - * else: - */ - __pyx_t_1 = ((((struct __pyx_memoryview_obj *)__pyx_v_memviewslice.memview)->flags & PyBUF_WRITABLE) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1030 - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: - * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< - * else: - * result.flags = PyBUF_RECORDS_RO - */ - __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; - - /* "View.MemoryView":1029 - * Py_INCREF(Py_None) - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< - * result.flags = PyBUF_RECORDS - * else: - */ - goto __pyx_L4; - } - - /* "View.MemoryView":1032 - * result.flags = PyBUF_RECORDS - * else: - * result.flags = PyBUF_RECORDS_RO # <<<<<<<<<<<<<< - * - * result.view.shape = result.from_slice.shape - */ - /*else*/ { - __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS_RO; - } - __pyx_L4:; - - /* "View.MemoryView":1034 - * result.flags = PyBUF_RECORDS_RO - * - * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< - * result.view.strides = result.from_slice.strides - * - */ - __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); - - /* "View.MemoryView":1035 - * - * result.view.shape = result.from_slice.shape - * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); - - /* "View.MemoryView":1038 - * - * - * result.view.suboffsets = NULL # <<<<<<<<<<<<<< - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: - */ - __pyx_v_result->__pyx_base.view.suboffsets = NULL; - - /* "View.MemoryView":1039 - * - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets - */ - __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); - for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { - __pyx_t_6 = __pyx_t_8; - __pyx_v_suboffset = (__pyx_t_6[0]); - - /* "View.MemoryView":1040 - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * result.view.suboffsets = result.from_slice.suboffsets - * break - */ - __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1041 - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); - - /* "View.MemoryView":1042 - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets - * break # <<<<<<<<<<<<<< - * - * result.view.len = result.view.itemsize - */ - goto __pyx_L6_break; - - /* "View.MemoryView":1040 - * result.view.suboffsets = NULL - * for suboffset in result.from_slice.suboffsets[:ndim]: - * if suboffset >= 0: # <<<<<<<<<<<<<< - * result.view.suboffsets = result.from_slice.suboffsets - * break - */ - } - } - __pyx_L6_break:; - - /* "View.MemoryView":1044 - * break - * - * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< - * for length in result.view.shape[:ndim]: - * result.view.len *= length - */ - __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; - __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - - /* "View.MemoryView":1045 - * - * result.view.len = result.view.itemsize - * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< - * result.view.len *= length - * - */ - __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); - for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { - __pyx_t_6 = __pyx_t_8; - __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1045, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":1046 - * result.view.len = result.view.itemsize - * for length in result.view.shape[:ndim]: - * result.view.len *= length # <<<<<<<<<<<<<< - * - * result.to_object_func = to_object_func - */ - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1046, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1046, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 1046, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - } - - /* "View.MemoryView":1048 - * result.view.len *= length - * - * result.to_object_func = to_object_func # <<<<<<<<<<<<<< - * result.to_dtype_func = to_dtype_func - * - */ - __pyx_v_result->to_object_func = __pyx_v_to_object_func; - - /* "View.MemoryView":1049 - * - * result.to_object_func = to_object_func - * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< - * - * return result - */ - __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; - - /* "View.MemoryView":1051 - * result.to_dtype_func = to_dtype_func - * - * return result # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_result)); - __pyx_r = ((PyObject *)__pyx_v_result); - goto __pyx_L0; - - /* "View.MemoryView":1001 - * - * @cname('__pyx_memoryview_fromslice') - * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< - * int ndim, - * object (*to_object_func)(char *), - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_result); - __Pyx_XDECREF(__pyx_v_length); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1054 - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - */ - -static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { - struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; - __Pyx_memviewslice *__pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_slice_from_memview", 0); - - /* "View.MemoryView":1057 - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * obj = memview - * return &obj.from_slice - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1058 - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): - * obj = memview # <<<<<<<<<<<<<< - * return &obj.from_slice - * else: - */ - if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(2, 1058, __pyx_L1_error) - __pyx_t_3 = ((PyObject *)__pyx_v_memview); - __Pyx_INCREF(__pyx_t_3); - __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":1059 - * if isinstance(memview, _memoryviewslice): - * obj = memview - * return &obj.from_slice # <<<<<<<<<<<<<< - * else: - * slice_copy(memview, mslice) - */ - __pyx_r = (&__pyx_v_obj->from_slice); - goto __pyx_L0; - - /* "View.MemoryView":1057 - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * obj = memview - * return &obj.from_slice - */ - } - - /* "View.MemoryView":1061 - * return &obj.from_slice - * else: - * slice_copy(memview, mslice) # <<<<<<<<<<<<<< - * return mslice - * - */ - /*else*/ { - __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); - - /* "View.MemoryView":1062 - * else: - * slice_copy(memview, mslice) - * return mslice # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_slice_copy') - */ - __pyx_r = __pyx_v_mslice; - goto __pyx_L0; - } - - /* "View.MemoryView":1054 - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *mslice) except NULL: - * cdef _memoryviewslice obj - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_obj); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1065 - * - * @cname('__pyx_memoryview_slice_copy') - * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< - * cdef int dim - * cdef (Py_ssize_t*) shape, strides, suboffsets - */ - -static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { - int __pyx_v_dim; - Py_ssize_t *__pyx_v_shape; - Py_ssize_t *__pyx_v_strides; - Py_ssize_t *__pyx_v_suboffsets; - __Pyx_RefNannyDeclarations - Py_ssize_t *__pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - Py_ssize_t __pyx_t_5; - __Pyx_RefNannySetupContext("slice_copy", 0); - - /* "View.MemoryView":1069 - * cdef (Py_ssize_t*) shape, strides, suboffsets - * - * shape = memview.view.shape # <<<<<<<<<<<<<< - * strides = memview.view.strides - * suboffsets = memview.view.suboffsets - */ - __pyx_t_1 = __pyx_v_memview->view.shape; - __pyx_v_shape = __pyx_t_1; - - /* "View.MemoryView":1070 - * - * shape = memview.view.shape - * strides = memview.view.strides # <<<<<<<<<<<<<< - * suboffsets = memview.view.suboffsets - * - */ - __pyx_t_1 = __pyx_v_memview->view.strides; - __pyx_v_strides = __pyx_t_1; - - /* "View.MemoryView":1071 - * shape = memview.view.shape - * strides = memview.view.strides - * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< - * - * dst.memview = <__pyx_memoryview *> memview - */ - __pyx_t_1 = __pyx_v_memview->view.suboffsets; - __pyx_v_suboffsets = __pyx_t_1; - - /* "View.MemoryView":1073 - * suboffsets = memview.view.suboffsets - * - * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< - * dst.data = memview.view.buf - * - */ - __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); - - /* "View.MemoryView":1074 - * - * dst.memview = <__pyx_memoryview *> memview - * dst.data = memview.view.buf # <<<<<<<<<<<<<< - * - * for dim in range(memview.view.ndim): - */ - __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); - - /* "View.MemoryView":1076 - * dst.data = memview.view.buf - * - * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] - */ - __pyx_t_2 = __pyx_v_memview->view.ndim; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_dim = __pyx_t_4; - - /* "View.MemoryView":1077 - * - * for dim in range(memview.view.ndim): - * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< - * dst.strides[dim] = strides[dim] - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 - */ - (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); - - /* "View.MemoryView":1078 - * for dim in range(memview.view.ndim): - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 - * - */ - (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); - - /* "View.MemoryView":1079 - * dst.shape[dim] = shape[dim] - * dst.strides[dim] = strides[dim] - * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_object') - */ - if ((__pyx_v_suboffsets != 0)) { - __pyx_t_5 = (__pyx_v_suboffsets[__pyx_v_dim]); - } else { - __pyx_t_5 = -1L; - } - (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_5; - } - - /* "View.MemoryView":1065 - * - * @cname('__pyx_memoryview_slice_copy') - * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< - * cdef int dim - * cdef (Py_ssize_t*) shape, strides, suboffsets - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":1082 - * - * @cname('__pyx_memoryview_copy_object') - * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - */ - -static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { - __Pyx_memviewslice __pyx_v_memviewslice; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_copy", 0); - - /* "View.MemoryView":1085 - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< - * return memoryview_copy_from_slice(memview, &memviewslice) - * - */ - __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); - - /* "View.MemoryView":1086 - * cdef __Pyx_memviewslice memviewslice - * slice_copy(memview, &memviewslice) - * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_object_from_slice') - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1086, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":1082 - * - * @cname('__pyx_memoryview_copy_object') - * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< - * "Create a new memoryview object" - * cdef __Pyx_memviewslice memviewslice - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1089 - * - * @cname('__pyx_memoryview_copy_object_from_slice') - * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< - * """ - * Create a new memoryview object from a given memoryview object and slice. - */ - -static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { - PyObject *(*__pyx_v_to_object_func)(char *); - int (*__pyx_v_to_dtype_func)(char *, PyObject *); - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *(*__pyx_t_3)(char *); - int (*__pyx_t_4)(char *, PyObject *); - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); - - /* "View.MemoryView":1096 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1097 - * - * if isinstance(memview, _memoryviewslice): - * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - * else: - */ - __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; - __pyx_v_to_object_func = __pyx_t_3; - - /* "View.MemoryView":1098 - * if isinstance(memview, _memoryviewslice): - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< - * else: - * to_object_func = NULL - */ - __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; - __pyx_v_to_dtype_func = __pyx_t_4; - - /* "View.MemoryView":1096 - * cdef int (*to_dtype_func)(char *, object) except 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * to_object_func = (<_memoryviewslice> memview).to_object_func - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1100 - * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func - * else: - * to_object_func = NULL # <<<<<<<<<<<<<< - * to_dtype_func = NULL - * - */ - /*else*/ { - __pyx_v_to_object_func = NULL; - - /* "View.MemoryView":1101 - * else: - * to_object_func = NULL - * to_dtype_func = NULL # <<<<<<<<<<<<<< - * - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, - */ - __pyx_v_to_dtype_func = NULL; - } - __pyx_L3:; - - /* "View.MemoryView":1103 - * to_dtype_func = NULL - * - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< - * to_object_func, to_dtype_func, - * memview.dtype_is_object) - */ - __Pyx_XDECREF(__pyx_r); - - /* "View.MemoryView":1105 - * return memoryview_fromslice(memviewslice[0], memview.view.ndim, - * to_object_func, to_dtype_func, - * memview.dtype_is_object) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 1103, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "View.MemoryView":1089 - * - * @cname('__pyx_memoryview_copy_object_from_slice') - * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< - * """ - * Create a new memoryview object from a given memoryview object and slice. - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1111 - * - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< - * if arg < 0: - * return -arg - */ - -static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { - Py_ssize_t __pyx_r; - int __pyx_t_1; - - /* "View.MemoryView":1112 - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: # <<<<<<<<<<<<<< - * return -arg - * else: - */ - __pyx_t_1 = ((__pyx_v_arg < 0) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1113 - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: - * return -arg # <<<<<<<<<<<<<< - * else: - * return arg - */ - __pyx_r = (-__pyx_v_arg); - goto __pyx_L0; - - /* "View.MemoryView":1112 - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: # <<<<<<<<<<<<<< - * return -arg - * else: - */ - } - - /* "View.MemoryView":1115 - * return -arg - * else: - * return arg # <<<<<<<<<<<<<< - * - * @cname('__pyx_get_best_slice_order') - */ - /*else*/ { - __pyx_r = __pyx_v_arg; - goto __pyx_L0; - } - - /* "View.MemoryView":1111 - * - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< - * if arg < 0: - * return -arg - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1118 - * - * @cname('__pyx_get_best_slice_order') - * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< - * """ - * Figure out the best memory access order for a given slice. - */ - -static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { - int __pyx_v_i; - Py_ssize_t __pyx_v_c_stride; - Py_ssize_t __pyx_v_f_stride; - char __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - - /* "View.MemoryView":1123 - * """ - * cdef int i - * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< - * cdef Py_ssize_t f_stride = 0 - * - */ - __pyx_v_c_stride = 0; - - /* "View.MemoryView":1124 - * cdef int i - * cdef Py_ssize_t c_stride = 0 - * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< - * - * for i in range(ndim - 1, -1, -1): - */ - __pyx_v_f_stride = 0; - - /* "View.MemoryView":1126 - * cdef Py_ssize_t f_stride = 0 - * - * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] - */ - for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":1127 - * - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * c_stride = mslice.strides[i] - * break - */ - __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1128 - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1129 - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] - * break # <<<<<<<<<<<<<< - * - * for i in range(ndim): - */ - goto __pyx_L4_break; - - /* "View.MemoryView":1127 - * - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * c_stride = mslice.strides[i] - * break - */ - } - } - __pyx_L4_break:; - - /* "View.MemoryView":1131 - * break - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] - */ - __pyx_t_1 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_1; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1132 - * - * for i in range(ndim): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * f_stride = mslice.strides[i] - * break - */ - __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1133 - * for i in range(ndim): - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< - * break - * - */ - __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1134 - * if mslice.shape[i] > 1: - * f_stride = mslice.strides[i] - * break # <<<<<<<<<<<<<< - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): - */ - goto __pyx_L7_break; - - /* "View.MemoryView":1132 - * - * for i in range(ndim): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * f_stride = mslice.strides[i] - * break - */ - } - } - __pyx_L7_break:; - - /* "View.MemoryView":1136 - * break - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< - * return 'C' - * else: - */ - __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1137 - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): - * return 'C' # <<<<<<<<<<<<<< - * else: - * return 'F' - */ - __pyx_r = 'C'; - goto __pyx_L0; - - /* "View.MemoryView":1136 - * break - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< - * return 'C' - * else: - */ - } - - /* "View.MemoryView":1139 - * return 'C' - * else: - * return 'F' # <<<<<<<<<<<<<< - * - * @cython.cdivision(True) - */ - /*else*/ { - __pyx_r = 'F'; - goto __pyx_L0; - } - - /* "View.MemoryView":1118 - * - * @cname('__pyx_get_best_slice_order') - * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< - * """ - * Figure out the best memory access order for a given slice. - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1142 - * - * @cython.cdivision(True) - * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< - * char *dst_data, Py_ssize_t *dst_strides, - * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, - */ - -static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; - Py_ssize_t __pyx_v_dst_extent; - Py_ssize_t __pyx_v_src_stride; - Py_ssize_t __pyx_v_dst_stride; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - Py_ssize_t __pyx_t_4; - Py_ssize_t __pyx_t_5; - Py_ssize_t __pyx_t_6; - - /* "View.MemoryView":1149 - * - * cdef Py_ssize_t i - * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] - */ - __pyx_v_src_extent = (__pyx_v_src_shape[0]); - - /* "View.MemoryView":1150 - * cdef Py_ssize_t i - * cdef Py_ssize_t src_extent = src_shape[0] - * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t src_stride = src_strides[0] - * cdef Py_ssize_t dst_stride = dst_strides[0] - */ - __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); - - /* "View.MemoryView":1151 - * cdef Py_ssize_t src_extent = src_shape[0] - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - */ - __pyx_v_src_stride = (__pyx_v_src_strides[0]); - - /* "View.MemoryView":1152 - * cdef Py_ssize_t dst_extent = dst_shape[0] - * cdef Py_ssize_t src_stride = src_strides[0] - * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< - * - * if ndim == 1: - */ - __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); - - /* "View.MemoryView":1154 - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - */ - __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1155 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L5_bool_binop_done; - } - __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L5_bool_binop_done; - } - - /* "View.MemoryView":1156 - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< - * memcpy(dst_data, src_data, itemsize * dst_extent) - * else: - */ - __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); - if (__pyx_t_2) { - __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); - } - __pyx_t_3 = (__pyx_t_2 != 0); - __pyx_t_1 = __pyx_t_3; - __pyx_L5_bool_binop_done:; - - /* "View.MemoryView":1155 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - if (__pyx_t_1) { - - /* "View.MemoryView":1157 - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< - * else: - * for i in range(dst_extent): - */ - (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent))); - - /* "View.MemoryView":1155 - * - * if ndim == 1: - * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< - * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) - */ - goto __pyx_L4; - } - - /* "View.MemoryView":1159 - * memcpy(dst_data, src_data, itemsize * dst_extent) - * else: - * for i in range(dst_extent): # <<<<<<<<<<<<<< - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride - */ - /*else*/ { - __pyx_t_4 = __pyx_v_dst_extent; - __pyx_t_5 = __pyx_t_4; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1160 - * else: - * for i in range(dst_extent): - * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< - * src_data += src_stride - * dst_data += dst_stride - */ - (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize)); - - /* "View.MemoryView":1161 - * for i in range(dst_extent): - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride # <<<<<<<<<<<<<< - * dst_data += dst_stride - * else: - */ - __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - - /* "View.MemoryView":1162 - * memcpy(dst_data, src_data, itemsize) - * src_data += src_stride - * dst_data += dst_stride # <<<<<<<<<<<<<< - * else: - * for i in range(dst_extent): - */ - __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); - } - } - __pyx_L4:; - - /* "View.MemoryView":1154 - * cdef Py_ssize_t dst_stride = dst_strides[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * if (src_stride > 0 and dst_stride > 0 and - * src_stride == itemsize == dst_stride): - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1164 - * dst_data += dst_stride - * else: - * for i in range(dst_extent): # <<<<<<<<<<<<<< - * _copy_strided_to_strided(src_data, src_strides + 1, - * dst_data, dst_strides + 1, - */ - /*else*/ { - __pyx_t_4 = __pyx_v_dst_extent; - __pyx_t_5 = __pyx_t_4; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1165 - * else: - * for i in range(dst_extent): - * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< - * dst_data, dst_strides + 1, - * src_shape + 1, dst_shape + 1, - */ - _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); - - /* "View.MemoryView":1169 - * src_shape + 1, dst_shape + 1, - * ndim - 1, itemsize) - * src_data += src_stride # <<<<<<<<<<<<<< - * dst_data += dst_stride - * - */ - __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - - /* "View.MemoryView":1170 - * ndim - 1, itemsize) - * src_data += src_stride - * dst_data += dst_stride # <<<<<<<<<<<<<< - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, - */ - __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); - } - } - __pyx_L3:; - - /* "View.MemoryView":1142 - * - * @cython.cdivision(True) - * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< - * char *dst_data, Py_ssize_t *dst_strides, - * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, - */ - - /* function exit code */ -} - -/* "View.MemoryView":1172 - * dst_data += dst_stride - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - */ - -static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { - - /* "View.MemoryView":1175 - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< - * src.shape, dst.shape, ndim, itemsize) - * - */ - _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); - - /* "View.MemoryView":1172 - * dst_data += dst_stride - * - * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *dst, - * int ndim, size_t itemsize) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1179 - * - * @cname('__pyx_memoryview_slice_get_size') - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - */ - -static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { - Py_ssize_t __pyx_v_shape; - Py_ssize_t __pyx_v_size; - Py_ssize_t __pyx_r; - Py_ssize_t __pyx_t_1; - Py_ssize_t *__pyx_t_2; - Py_ssize_t *__pyx_t_3; - Py_ssize_t *__pyx_t_4; - - /* "View.MemoryView":1181 - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize # <<<<<<<<<<<<<< - * - * for shape in src.shape[:ndim]: - */ - __pyx_t_1 = __pyx_v_src->memview->view.itemsize; - __pyx_v_size = __pyx_t_1; - - /* "View.MemoryView":1183 - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - * - * for shape in src.shape[:ndim]: # <<<<<<<<<<<<<< - * size *= shape - * - */ - __pyx_t_3 = (__pyx_v_src->shape + __pyx_v_ndim); - for (__pyx_t_4 = __pyx_v_src->shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { - __pyx_t_2 = __pyx_t_4; - __pyx_v_shape = (__pyx_t_2[0]); - - /* "View.MemoryView":1184 - * - * for shape in src.shape[:ndim]: - * size *= shape # <<<<<<<<<<<<<< - * - * return size - */ - __pyx_v_size = (__pyx_v_size * __pyx_v_shape); - } - - /* "View.MemoryView":1186 - * size *= shape - * - * return size # <<<<<<<<<<<<<< - * - * @cname('__pyx_fill_contig_strides_array') - */ - __pyx_r = __pyx_v_size; - goto __pyx_L0; - - /* "View.MemoryView":1179 - * - * @cname('__pyx_memoryview_slice_get_size') - * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef Py_ssize_t shape, size = src.memview.view.itemsize - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1189 - * - * @cname('__pyx_fill_contig_strides_array') - * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< - * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, - * int ndim, char order) nogil: - */ - -static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { - int __pyx_v_idx; - Py_ssize_t __pyx_r; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - - /* "View.MemoryView":1198 - * cdef int idx - * - * if order == 'F': # <<<<<<<<<<<<<< - * for idx in range(ndim): - * strides[idx] = stride - */ - __pyx_t_1 = ((__pyx_v_order == 'F') != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1199 - * - * if order == 'F': - * for idx in range(ndim): # <<<<<<<<<<<<<< - * strides[idx] = stride - * stride *= shape[idx] - */ - __pyx_t_2 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_idx = __pyx_t_4; - - /* "View.MemoryView":1200 - * if order == 'F': - * for idx in range(ndim): - * strides[idx] = stride # <<<<<<<<<<<<<< - * stride *= shape[idx] - * else: - */ - (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - - /* "View.MemoryView":1201 - * for idx in range(ndim): - * strides[idx] = stride - * stride *= shape[idx] # <<<<<<<<<<<<<< - * else: - * for idx in range(ndim - 1, -1, -1): - */ - __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); - } - - /* "View.MemoryView":1198 - * cdef int idx - * - * if order == 'F': # <<<<<<<<<<<<<< - * for idx in range(ndim): - * strides[idx] = stride - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1203 - * stride *= shape[idx] - * else: - * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * strides[idx] = stride - * stride *= shape[idx] - */ - /*else*/ { - for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { - __pyx_v_idx = __pyx_t_2; - - /* "View.MemoryView":1204 - * else: - * for idx in range(ndim - 1, -1, -1): - * strides[idx] = stride # <<<<<<<<<<<<<< - * stride *= shape[idx] - * - */ - (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - - /* "View.MemoryView":1205 - * for idx in range(ndim - 1, -1, -1): - * strides[idx] = stride - * stride *= shape[idx] # <<<<<<<<<<<<<< - * - * return stride - */ - __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); - } - } - __pyx_L3:; - - /* "View.MemoryView":1207 - * stride *= shape[idx] - * - * return stride # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_data_to_temp') - */ - __pyx_r = __pyx_v_stride; - goto __pyx_L0; - - /* "View.MemoryView":1189 - * - * @cname('__pyx_fill_contig_strides_array') - * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< - * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, - * int ndim, char order) nogil: - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1210 - * - * @cname('__pyx_memoryview_copy_data_to_temp') - * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *tmpslice, - * char order, - */ - -static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { - int __pyx_v_i; - void *__pyx_v_result; - size_t __pyx_v_itemsize; - size_t __pyx_v_size; - void *__pyx_r; - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - struct __pyx_memoryview_obj *__pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":1221 - * cdef void *result - * - * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< - * cdef size_t size = slice_get_size(src, ndim) - * - */ - __pyx_t_1 = __pyx_v_src->memview->view.itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":1222 - * - * cdef size_t itemsize = src.memview.view.itemsize - * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< - * - * result = malloc(size) - */ - __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); - - /* "View.MemoryView":1224 - * cdef size_t size = slice_get_size(src, ndim) - * - * result = malloc(size) # <<<<<<<<<<<<<< - * if not result: - * _err(MemoryError, NULL) - */ - __pyx_v_result = malloc(__pyx_v_size); - - /* "View.MemoryView":1225 - * - * result = malloc(size) - * if not result: # <<<<<<<<<<<<<< - * _err(MemoryError, NULL) - * - */ - __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1226 - * result = malloc(size) - * if not result: - * _err(MemoryError, NULL) # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(2, 1226, __pyx_L1_error) - - /* "View.MemoryView":1225 - * - * result = malloc(size) - * if not result: # <<<<<<<<<<<<<< - * _err(MemoryError, NULL) - * - */ - } - - /* "View.MemoryView":1229 - * - * - * tmpslice.data = result # <<<<<<<<<<<<<< - * tmpslice.memview = src.memview - * for i in range(ndim): - */ - __pyx_v_tmpslice->data = ((char *)__pyx_v_result); - - /* "View.MemoryView":1230 - * - * tmpslice.data = result - * tmpslice.memview = src.memview # <<<<<<<<<<<<<< - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] - */ - __pyx_t_4 = __pyx_v_src->memview; - __pyx_v_tmpslice->memview = __pyx_t_4; - - /* "View.MemoryView":1231 - * tmpslice.data = result - * tmpslice.memview = src.memview - * for i in range(ndim): # <<<<<<<<<<<<<< - * tmpslice.shape[i] = src.shape[i] - * tmpslice.suboffsets[i] = -1 - */ - __pyx_t_3 = __pyx_v_ndim; - __pyx_t_5 = __pyx_t_3; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1232 - * tmpslice.memview = src.memview - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< - * tmpslice.suboffsets[i] = -1 - * - */ - (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); - - /* "View.MemoryView":1233 - * for i in range(ndim): - * tmpslice.shape[i] = src.shape[i] - * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< - * - * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, - */ - (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1L; - } - - /* "View.MemoryView":1235 - * tmpslice.suboffsets[i] = -1 - * - * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< - * ndim, order) - * - */ - (void)(__pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order)); - - /* "View.MemoryView":1239 - * - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if tmpslice.shape[i] == 1: - * tmpslice.strides[i] = 0 - */ - __pyx_t_3 = __pyx_v_ndim; - __pyx_t_5 = __pyx_t_3; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "View.MemoryView":1240 - * - * for i in range(ndim): - * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< - * tmpslice.strides[i] = 0 - * - */ - __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1241 - * for i in range(ndim): - * if tmpslice.shape[i] == 1: - * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< - * - * if slice_is_contig(src[0], order, ndim): - */ - (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; - - /* "View.MemoryView":1240 - * - * for i in range(ndim): - * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< - * tmpslice.strides[i] = 0 - * - */ - } - } - - /* "View.MemoryView":1243 - * tmpslice.strides[i] = 0 - * - * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< - * memcpy(result, src.data, size) - * else: - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1244 - * - * if slice_is_contig(src[0], order, ndim): - * memcpy(result, src.data, size) # <<<<<<<<<<<<<< - * else: - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) - */ - (void)(memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size)); - - /* "View.MemoryView":1243 - * tmpslice.strides[i] = 0 - * - * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< - * memcpy(result, src.data, size) - * else: - */ - goto __pyx_L9; - } - - /* "View.MemoryView":1246 - * memcpy(result, src.data, size) - * else: - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< - * - * return result - */ - /*else*/ { - copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); - } - __pyx_L9:; - - /* "View.MemoryView":1248 - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) - * - * return result # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_result; - goto __pyx_L0; - - /* "View.MemoryView":1210 - * - * @cname('__pyx_memoryview_copy_data_to_temp') - * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *tmpslice, - * char order, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = NULL; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1253 - * - * @cname('__pyx_memoryview_err_extents') - * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - */ - -static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err_extents", 0); - - /* "View.MemoryView":1256 - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - * (i, extent1, extent2)) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_err_dim') - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1256, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1256, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1256, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1256, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - - /* "View.MemoryView":1255 - * cdef int _err_extents(int i, Py_ssize_t extent1, - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< - * (i, extent1, extent2)) - * - */ - __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1255, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1255, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __PYX_ERR(2, 1255, __pyx_L1_error) - - /* "View.MemoryView":1253 - * - * @cname('__pyx_memoryview_err_extents') - * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< - * Py_ssize_t extent2) except -1 with gil: - * raise ValueError("got differing extents in dimension %d (got %d and %d)" % - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1259 - * - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii') % dim) - * - */ - -static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err_dim", 0); - __Pyx_INCREF(__pyx_v_error); - - /* "View.MemoryView":1260 - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: - * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_err') - */ - __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1260, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1260, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 1260, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_INCREF(__pyx_v_error); - __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 1260, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(2, 1260, __pyx_L1_error) - - /* "View.MemoryView":1259 - * - * @cname('__pyx_memoryview_err_dim') - * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii') % dim) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_XDECREF(__pyx_v_error); - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1263 - * - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< - * if msg != NULL: - * raise error(msg.decode('ascii')) - */ - -static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err", 0); - __Pyx_INCREF(__pyx_v_error); - - /* "View.MemoryView":1264 - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii')) - * else: - */ - __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":1265 - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: - * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< - * else: - * raise error - */ - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 1265, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_error); - __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1265, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __PYX_ERR(2, 1265, __pyx_L1_error) - - /* "View.MemoryView":1264 - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: - * if msg != NULL: # <<<<<<<<<<<<<< - * raise error(msg.decode('ascii')) - * else: - */ - } - - /* "View.MemoryView":1267 - * raise error(msg.decode('ascii')) - * else: - * raise error # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_contents') - */ - /*else*/ { - __Pyx_Raise(__pyx_v_error, 0, 0, 0); - __PYX_ERR(2, 1267, __pyx_L1_error) - } - - /* "View.MemoryView":1263 - * - * @cname('__pyx_memoryview_err') - * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< - * if msg != NULL: - * raise error(msg.decode('ascii')) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_XDECREF(__pyx_v_error); - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - return __pyx_r; -} - -/* "View.MemoryView":1270 - * - * @cname('__pyx_memoryview_copy_contents') - * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice dst, - * int src_ndim, int dst_ndim, - */ - -static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { - void *__pyx_v_tmpdata; - size_t __pyx_v_itemsize; - int __pyx_v_i; - char __pyx_v_order; - int __pyx_v_broadcasting; - int __pyx_v_direct_copy; - __Pyx_memviewslice __pyx_v_tmp; - int __pyx_v_ndim; - int __pyx_r; - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - void *__pyx_t_7; - int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - - /* "View.MemoryView":1278 - * Check for overlapping memory and verify the shapes. - * """ - * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< - * cdef size_t itemsize = src.memview.view.itemsize - * cdef int i - */ - __pyx_v_tmpdata = NULL; - - /* "View.MemoryView":1279 - * """ - * cdef void *tmpdata = NULL - * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) - */ - __pyx_t_1 = __pyx_v_src.memview->view.itemsize; - __pyx_v_itemsize = __pyx_t_1; - - /* "View.MemoryView":1281 - * cdef size_t itemsize = src.memview.view.itemsize - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< - * cdef bint broadcasting = False - * cdef bint direct_copy = False - */ - __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); - - /* "View.MemoryView":1282 - * cdef int i - * cdef char order = get_best_order(&src, src_ndim) - * cdef bint broadcasting = False # <<<<<<<<<<<<<< - * cdef bint direct_copy = False - * cdef __Pyx_memviewslice tmp - */ - __pyx_v_broadcasting = 0; - - /* "View.MemoryView":1283 - * cdef char order = get_best_order(&src, src_ndim) - * cdef bint broadcasting = False - * cdef bint direct_copy = False # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice tmp - * - */ - __pyx_v_direct_copy = 0; - - /* "View.MemoryView":1286 - * cdef __Pyx_memviewslice tmp - * - * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - */ - __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1287 - * - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< - * elif dst_ndim < src_ndim: - * broadcast_leading(&dst, dst_ndim, src_ndim) - */ - __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); - - /* "View.MemoryView":1286 - * cdef __Pyx_memviewslice tmp - * - * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1288 - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - */ - __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1289 - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: - * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< - * - * cdef int ndim = max(src_ndim, dst_ndim) - */ - __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); - - /* "View.MemoryView":1288 - * if src_ndim < dst_ndim: - * broadcast_leading(&src, src_ndim, dst_ndim) - * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - */ - } - __pyx_L3:; - - /* "View.MemoryView":1291 - * broadcast_leading(&dst, dst_ndim, src_ndim) - * - * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< - * - * for i in range(ndim): - */ - __pyx_t_3 = __pyx_v_dst_ndim; - __pyx_t_4 = __pyx_v_src_ndim; - if (((__pyx_t_3 > __pyx_t_4) != 0)) { - __pyx_t_5 = __pyx_t_3; - } else { - __pyx_t_5 = __pyx_t_4; - } - __pyx_v_ndim = __pyx_t_5; - - /* "View.MemoryView":1293 - * cdef int ndim = max(src_ndim, dst_ndim) - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: - */ - __pyx_t_5 = __pyx_v_ndim; - __pyx_t_3 = __pyx_t_5; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1294 - * - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< - * if src.shape[i] == 1: - * broadcasting = True - */ - __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1295 - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: # <<<<<<<<<<<<<< - * broadcasting = True - * src.strides[i] = 0 - */ - __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1296 - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: - * broadcasting = True # <<<<<<<<<<<<<< - * src.strides[i] = 0 - * else: - */ - __pyx_v_broadcasting = 1; - - /* "View.MemoryView":1297 - * if src.shape[i] == 1: - * broadcasting = True - * src.strides[i] = 0 # <<<<<<<<<<<<<< - * else: - * _err_extents(i, dst.shape[i], src.shape[i]) - */ - (__pyx_v_src.strides[__pyx_v_i]) = 0; - - /* "View.MemoryView":1295 - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: - * if src.shape[i] == 1: # <<<<<<<<<<<<<< - * broadcasting = True - * src.strides[i] = 0 - */ - goto __pyx_L7; - } - - /* "View.MemoryView":1299 - * src.strides[i] = 0 - * else: - * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< - * - * if src.suboffsets[i] >= 0: - */ - /*else*/ { - __pyx_t_6 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(2, 1299, __pyx_L1_error) - } - __pyx_L7:; - - /* "View.MemoryView":1294 - * - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< - * if src.shape[i] == 1: - * broadcasting = True - */ - } - - /* "View.MemoryView":1301 - * _err_extents(i, dst.shape[i], src.shape[i]) - * - * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - */ - __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1302 - * - * if src.suboffsets[i] >= 0: - * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< - * - * if slices_overlap(&src, &dst, ndim, itemsize): - */ - __pyx_t_6 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(2, 1302, __pyx_L1_error) - - /* "View.MemoryView":1301 - * _err_extents(i, dst.shape[i], src.shape[i]) - * - * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - */ - } - } - - /* "View.MemoryView":1304 - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< - * - * if not slice_is_contig(src, order, ndim): - */ - __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1306 - * if slices_overlap(&src, &dst, ndim, itemsize): - * - * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< - * order = get_best_order(&dst, ndim) - * - */ - __pyx_t_2 = ((!(__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1307 - * - * if not slice_is_contig(src, order, ndim): - * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) - */ - __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); - - /* "View.MemoryView":1306 - * if slices_overlap(&src, &dst, ndim, itemsize): - * - * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< - * order = get_best_order(&dst, ndim) - * - */ - } - - /* "View.MemoryView":1309 - * order = get_best_order(&dst, ndim) - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< - * src = tmp - * - */ - __pyx_t_7 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_7 == ((void *)NULL))) __PYX_ERR(2, 1309, __pyx_L1_error) - __pyx_v_tmpdata = __pyx_t_7; - - /* "View.MemoryView":1310 - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) - * src = tmp # <<<<<<<<<<<<<< - * - * if not broadcasting: - */ - __pyx_v_src = __pyx_v_tmp; - - /* "View.MemoryView":1304 - * _err_dim(ValueError, "Dimension %d is not direct", i) - * - * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< - * - * if not slice_is_contig(src, order, ndim): - */ - } - - /* "View.MemoryView":1312 - * src = tmp - * - * if not broadcasting: # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1315 - * - * - * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'C', __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1316 - * - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) # <<<<<<<<<<<<<< - * elif slice_is_contig(src, 'F', ndim): - * direct_copy = slice_is_contig(dst, 'F', ndim) - */ - __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'C', __pyx_v_ndim); - - /* "View.MemoryView":1315 - * - * - * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - */ - goto __pyx_L12; - } - - /* "View.MemoryView":1317 - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - */ - __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'F', __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1318 - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): - * direct_copy = slice_is_contig(dst, 'F', ndim) # <<<<<<<<<<<<<< - * - * if direct_copy: - */ - __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'F', __pyx_v_ndim); - - /* "View.MemoryView":1317 - * if slice_is_contig(src, 'C', ndim): - * direct_copy = slice_is_contig(dst, 'C', ndim) - * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - */ - } - __pyx_L12:; - - /* "View.MemoryView":1320 - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - * if direct_copy: # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - __pyx_t_2 = (__pyx_v_direct_copy != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1322 - * if direct_copy: - * - * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1323 - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) - */ - (void)(memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim))); - - /* "View.MemoryView":1324 - * refcount_copying(&dst, dtype_is_object, ndim, False) - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * free(tmpdata) - * return 0 - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1325 - * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) # <<<<<<<<<<<<<< - * return 0 - * - */ - free(__pyx_v_tmpdata); - - /* "View.MemoryView":1326 - * refcount_copying(&dst, dtype_is_object, ndim, True) - * free(tmpdata) - * return 0 # <<<<<<<<<<<<<< - * - * if order == 'F' == get_best_order(&dst, ndim): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":1320 - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - * if direct_copy: # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - } - - /* "View.MemoryView":1312 - * src = tmp - * - * if not broadcasting: # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":1328 - * return 0 - * - * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = (__pyx_v_order == 'F'); - if (__pyx_t_2) { - __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); - } - __pyx_t_8 = (__pyx_t_2 != 0); - if (__pyx_t_8) { - - /* "View.MemoryView":1331 - * - * - * transpose_memslice(&src) # <<<<<<<<<<<<<< - * transpose_memslice(&dst) - * - */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(2, 1331, __pyx_L1_error) - - /* "View.MemoryView":1332 - * - * transpose_memslice(&src) - * transpose_memslice(&dst) # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(2, 1332, __pyx_L1_error) - - /* "View.MemoryView":1328 - * return 0 - * - * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":1334 - * transpose_memslice(&dst) - * - * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * copy_strided_to_strided(&src, &dst, ndim, itemsize) - * refcount_copying(&dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1335 - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< - * refcount_copying(&dst, dtype_is_object, ndim, True) - * - */ - copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); - - /* "View.MemoryView":1336 - * refcount_copying(&dst, dtype_is_object, ndim, False) - * copy_strided_to_strided(&src, &dst, ndim, itemsize) - * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * - * free(tmpdata) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1338 - * refcount_copying(&dst, dtype_is_object, ndim, True) - * - * free(tmpdata) # <<<<<<<<<<<<<< - * return 0 - * - */ - free(__pyx_v_tmpdata); - - /* "View.MemoryView":1339 - * - * free(tmpdata) - * return 0 # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_broadcast_leading') - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":1270 - * - * @cname('__pyx_memoryview_copy_contents') - * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< - * __Pyx_memviewslice dst, - * int src_ndim, int dst_ndim, - */ - - /* function exit code */ - __pyx_L1_error:; - { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif - } - __pyx_r = -1; - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1342 - * - * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< - * int ndim, - * int ndim_other) nogil: - */ - -static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { - int __pyx_v_i; - int __pyx_v_offset; - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - - /* "View.MemoryView":1346 - * int ndim_other) nogil: - * cdef int i - * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< - * - * for i in range(ndim - 1, -1, -1): - */ - __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); - - /* "View.MemoryView":1348 - * cdef int offset = ndim_other - ndim - * - * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] - */ - for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { - __pyx_v_i = __pyx_t_1; - - /* "View.MemoryView":1349 - * - * for i in range(ndim - 1, -1, -1): - * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< - * mslice.strides[i + offset] = mslice.strides[i] - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - */ - (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); - - /* "View.MemoryView":1350 - * for i in range(ndim - 1, -1, -1): - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - * - */ - (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1351 - * mslice.shape[i + offset] = mslice.shape[i] - * mslice.strides[i + offset] = mslice.strides[i] - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< - * - * for i in range(offset): - */ - (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); - } - - /* "View.MemoryView":1353 - * mslice.suboffsets[i + offset] = mslice.suboffsets[i] - * - * for i in range(offset): # <<<<<<<<<<<<<< - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] - */ - __pyx_t_1 = __pyx_v_offset; - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_i = __pyx_t_3; - - /* "View.MemoryView":1354 - * - * for i in range(offset): - * mslice.shape[i] = 1 # <<<<<<<<<<<<<< - * mslice.strides[i] = mslice.strides[0] - * mslice.suboffsets[i] = -1 - */ - (__pyx_v_mslice->shape[__pyx_v_i]) = 1; - - /* "View.MemoryView":1355 - * for i in range(offset): - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< - * mslice.suboffsets[i] = -1 - * - */ - (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); - - /* "View.MemoryView":1356 - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] - * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< - * - * - */ - (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; - } - - /* "View.MemoryView":1342 - * - * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< - * int ndim, - * int ndim_other) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1364 - * - * @cname('__pyx_memoryview_refcount_copying') - * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< - * int ndim, bint inc) nogil: - * - */ - -static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { - int __pyx_t_1; - - /* "View.MemoryView":1368 - * - * - * if dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, - * dst.strides, ndim, inc) - */ - __pyx_t_1 = (__pyx_v_dtype_is_object != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1369 - * - * if dtype_is_object: - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< - * dst.strides, ndim, inc) - * - */ - __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); - - /* "View.MemoryView":1368 - * - * - * if dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, - * dst.strides, ndim, inc) - */ - } - - /* "View.MemoryView":1364 - * - * @cname('__pyx_memoryview_refcount_copying') - * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< - * int ndim, bint inc) nogil: - * - */ - - /* function exit code */ -} - -/* "View.MemoryView":1373 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') - * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - */ - -static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { - __Pyx_RefNannyDeclarations - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); - - /* "View.MemoryView":1376 - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); - - /* "View.MemoryView":1373 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') - * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * bint inc) with gil: - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - #ifdef WITH_THREAD - __Pyx_PyGILState_Release(__pyx_gilstate_save); - #endif -} - -/* "View.MemoryView":1379 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, bint inc): - * cdef Py_ssize_t i - */ - -static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); - - /* "View.MemoryView":1383 - * cdef Py_ssize_t i - * - * for i in range(shape[0]): # <<<<<<<<<<<<<< - * if ndim == 1: - * if inc: - */ - __pyx_t_1 = (__pyx_v_shape[0]); - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_i = __pyx_t_3; - - /* "View.MemoryView":1384 - * - * for i in range(shape[0]): - * if ndim == 1: # <<<<<<<<<<<<<< - * if inc: - * Py_INCREF(( data)[0]) - */ - __pyx_t_4 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":1385 - * for i in range(shape[0]): - * if ndim == 1: - * if inc: # <<<<<<<<<<<<<< - * Py_INCREF(( data)[0]) - * else: - */ - __pyx_t_4 = (__pyx_v_inc != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":1386 - * if ndim == 1: - * if inc: - * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< - * else: - * Py_DECREF(( data)[0]) - */ - Py_INCREF((((PyObject **)__pyx_v_data)[0])); - - /* "View.MemoryView":1385 - * for i in range(shape[0]): - * if ndim == 1: - * if inc: # <<<<<<<<<<<<<< - * Py_INCREF(( data)[0]) - * else: - */ - goto __pyx_L6; - } - - /* "View.MemoryView":1388 - * Py_INCREF(( data)[0]) - * else: - * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, - */ - /*else*/ { - Py_DECREF((((PyObject **)__pyx_v_data)[0])); - } - __pyx_L6:; - - /* "View.MemoryView":1384 - * - * for i in range(shape[0]): - * if ndim == 1: # <<<<<<<<<<<<<< - * if inc: - * Py_INCREF(( data)[0]) - */ - goto __pyx_L5; - } - - /* "View.MemoryView":1390 - * Py_DECREF(( data)[0]) - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< - * ndim - 1, inc) - * - */ - /*else*/ { - - /* "View.MemoryView":1391 - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, - * ndim - 1, inc) # <<<<<<<<<<<<<< - * - * data += strides[0] - */ - __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); - } - __pyx_L5:; - - /* "View.MemoryView":1393 - * ndim - 1, inc) - * - * data += strides[0] # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); - } - - /* "View.MemoryView":1379 - * - * @cname('__pyx_memoryview_refcount_objects_in_slice') - * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, bint inc): - * cdef Py_ssize_t i - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":1399 - * - * @cname('__pyx_memoryview_slice_assign_scalar') - * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - */ - -static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { - - /* "View.MemoryView":1402 - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, - * itemsize, item) - */ - __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - - /* "View.MemoryView":1403 - * bint dtype_is_object) nogil: - * refcount_copying(dst, dtype_is_object, ndim, False) - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< - * itemsize, item) - * refcount_copying(dst, dtype_is_object, ndim, True) - */ - __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); - - /* "View.MemoryView":1405 - * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, - * itemsize, item) - * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< - * - * - */ - __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1399 - * - * @cname('__pyx_memoryview_slice_assign_scalar') - * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< - * size_t itemsize, void *item, - * bint dtype_is_object) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1409 - * - * @cname('__pyx_memoryview__slice_assign_scalar') - * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * size_t itemsize, void *item) nogil: - */ - -static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { - CYTHON_UNUSED Py_ssize_t __pyx_v_i; - Py_ssize_t __pyx_v_stride; - Py_ssize_t __pyx_v_extent; - int __pyx_t_1; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - Py_ssize_t __pyx_t_4; - - /* "View.MemoryView":1413 - * size_t itemsize, void *item) nogil: - * cdef Py_ssize_t i - * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< - * cdef Py_ssize_t extent = shape[0] - * - */ - __pyx_v_stride = (__pyx_v_strides[0]); - - /* "View.MemoryView":1414 - * cdef Py_ssize_t i - * cdef Py_ssize_t stride = strides[0] - * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< - * - * if ndim == 1: - */ - __pyx_v_extent = (__pyx_v_shape[0]); - - /* "View.MemoryView":1416 - * cdef Py_ssize_t extent = shape[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * for i in range(extent): - * memcpy(data, item, itemsize) - */ - __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":1417 - * - * if ndim == 1: - * for i in range(extent): # <<<<<<<<<<<<<< - * memcpy(data, item, itemsize) - * data += stride - */ - __pyx_t_2 = __pyx_v_extent; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1418 - * if ndim == 1: - * for i in range(extent): - * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< - * data += stride - * else: - */ - (void)(memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize)); - - /* "View.MemoryView":1419 - * for i in range(extent): - * memcpy(data, item, itemsize) - * data += stride # <<<<<<<<<<<<<< - * else: - * for i in range(extent): - */ - __pyx_v_data = (__pyx_v_data + __pyx_v_stride); - } - - /* "View.MemoryView":1416 - * cdef Py_ssize_t extent = shape[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * for i in range(extent): - * memcpy(data, item, itemsize) - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1421 - * data += stride - * else: - * for i in range(extent): # <<<<<<<<<<<<<< - * _slice_assign_scalar(data, shape + 1, strides + 1, - * ndim - 1, itemsize, item) - */ - /*else*/ { - __pyx_t_2 = __pyx_v_extent; - __pyx_t_3 = __pyx_t_2; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - - /* "View.MemoryView":1422 - * else: - * for i in range(extent): - * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< - * ndim - 1, itemsize, item) - * data += stride - */ - __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); - - /* "View.MemoryView":1424 - * _slice_assign_scalar(data, shape + 1, strides + 1, - * ndim - 1, itemsize, item) - * data += stride # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_data = (__pyx_v_data + __pyx_v_stride); - } - } - __pyx_L3:; - - /* "View.MemoryView":1409 - * - * @cname('__pyx_memoryview__slice_assign_scalar') - * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< - * Py_ssize_t *strides, int ndim, - * size_t itemsize, void *item) nogil: - */ - - /* function exit code */ -} - -/* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum = {"__pyx_unpickle_Enum", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v___pyx_type = 0; - long __pyx_v___pyx_checksum; - PyObject *__pyx_v___pyx_state = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 1); __PYX_ERR(2, 1, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 2); __PYX_ERR(2, 1, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_Enum") < 0)) __PYX_ERR(2, 1, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - } - __pyx_v___pyx_type = values[0]; - __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(2, 1, __pyx_L3_error) - __pyx_v___pyx_state = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(2, 1, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_v___pyx_PickleError = 0; - PyObject *__pyx_v___pyx_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum not in (0xb068931, 0x82a3537, 0x6ae9995): # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) - */ - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = (__Pyx_PySequence_ContainsTF(__pyx_t_1, __pyx_tuple__21, Py_NE)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":5 - * cdef object __pyx_result - * if __pyx_checksum not in (0xb068931, 0x82a3537, 0x6ae9995): - * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< - * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_PickleError); - __Pyx_GIVEREF(__pyx_n_s_PickleError); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_PickleError); - __pyx_t_4 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_1, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_4, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_1); - __pyx_v___pyx_PickleError = __pyx_t_1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "(tree fragment)":6 - * if __pyx_checksum not in (0xb068931, 0x82a3537, 0x6ae9995): - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: - */ - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_0x_x_vs_0, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(2, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_INCREF(__pyx_v___pyx_PickleError); - __pyx_t_1 = __pyx_v___pyx_PickleError; __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - __pyx_t_4 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_1, __pyx_t_6, __pyx_t_5) : __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __PYX_ERR(2, 6, __pyx_L1_error) - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum not in (0xb068931, 0x82a3537, 0x6ae9995): # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) - */ - } - - /* "(tree fragment)":7 - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) # <<<<<<<<<<<<<< - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_1))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_1); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_1, function); - } - } - __pyx_t_4 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_1, __pyx_t_5, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_1, __pyx_v___pyx_type); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v___pyx_result = __pyx_t_4; - __pyx_t_4 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - __pyx_t_3 = (__pyx_v___pyx_state != Py_None); - __pyx_t_2 = (__pyx_t_3 != 0); - if (__pyx_t_2) { - - /* "(tree fragment)":9 - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||((void)PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(2, 9, __pyx_L1_error) - __pyx_t_4 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (0x%x vs (0xb068931, 0x82a3537, 0x6ae9995) = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - } - - /* "(tree fragment)":10 - * if __pyx_state is not None: - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result # <<<<<<<<<<<<<< - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v___pyx_result); - __pyx_r = __pyx_v___pyx_result; - goto __pyx_L0; - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v___pyx_PickleError); - __Pyx_XDECREF(__pyx_v___pyx_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - -static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum__set_state", 0); - - /* "(tree fragment)":12 - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] # <<<<<<<<<<<<<< - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(2, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->name); - __Pyx_DECREF(__pyx_v___pyx_result->name); - __pyx_v___pyx_result->name = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(2, 13, __pyx_L1_error) - } - __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(2, 13, __pyx_L1_error) - __pyx_t_4 = ((__pyx_t_3 > 1) != 0); - if (__pyx_t_4) { - } else { - __pyx_t_2 = __pyx_t_4; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 13, __pyx_L1_error) - __pyx_t_5 = (__pyx_t_4 != 0); - __pyx_t_2 = __pyx_t_5; - __pyx_L4_bool_binop_done:; - if (__pyx_t_2) { - - /* "(tree fragment)":14 - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[1]) # <<<<<<<<<<<<<< - */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(2, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(2, 14, __pyx_L1_error) - } - __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(2, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[1]) - */ - } - - /* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static struct __pyx_vtabstruct_array __pyx_vtable_array; - -static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_array_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_array_obj *)o); - p->__pyx_vtab = __pyx_vtabptr_array; - p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); - if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) goto bad; - return o; - bad: - Py_DECREF(o); o = 0; - return NULL; -} - -static void __pyx_tp_dealloc_array(PyObject *o) { - struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_array___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->mode); - Py_CLEAR(p->_format); - (*Py_TYPE(o)->tp_free)(o); -} -static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { - PyObject *r; - PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; - r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); - Py_DECREF(x); - return r; -} - -static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_array___setitem__(o, i, v); - } - else { - PyErr_Format(PyExc_NotImplementedError, - "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); - return -1; - } -} - -static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { - PyObject *v = __Pyx_PyObject_GenericGetAttr(o, n); - if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - v = __pyx_array___getattr__(o, n); - } - return v; -} - -static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(o); -} - -static PyMethodDef __pyx_methods_array[] = { - {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_array_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_array_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_array[] = { - {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence_array = { - __pyx_array___len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - __pyx_sq_item_array, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_array = { - __pyx_array___len__, /*mp_length*/ - __pyx_array___getitem__, /*mp_subscript*/ - __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_array = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - __pyx_array_getbuffer, /*bf_getbuffer*/ - 0, /*bf_releasebuffer*/ -}; - -static PyTypeObject __pyx_type___pyx_array = { - PyVarObject_HEAD_INIT(0, 0) - "ueg_kernels.array", /*tp_name*/ - sizeof(struct __pyx_array_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_array, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - __pyx_tp_getattro_array, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_array, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_array, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_array, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_MemviewEnum_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_MemviewEnum_obj *)o); - p->name = Py_None; Py_INCREF(Py_None); - return o; -} - -static void __pyx_tp_dealloc_Enum(PyObject *o) { - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->name); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - if (p->name) { - e = (*v)(p->name, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_Enum(PyObject *o) { - PyObject* tmp; - struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - tmp = ((PyObject*)p->name); - p->name = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyMethodDef __pyx_methods_Enum[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type___pyx_MemviewEnum = { - PyVarObject_HEAD_INIT(0, 0) - "ueg_kernels.Enum", /*tp_name*/ - sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_Enum, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_MemviewEnum___repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_Enum, /*tp_traverse*/ - __pyx_tp_clear_Enum, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_Enum, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_MemviewEnum___init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_Enum, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; -static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; - -static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_memoryview_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_memoryview_obj *)o); - p->__pyx_vtab = __pyx_vtabptr_memoryview; - p->obj = Py_None; Py_INCREF(Py_None); - p->_size = Py_None; Py_INCREF(Py_None); - p->_array_interface = Py_None; Py_INCREF(Py_None); - p->view.obj = NULL; - if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) goto bad; - return o; - bad: - Py_DECREF(o); o = 0; - return NULL; -} - -static void __pyx_tp_dealloc_memoryview(PyObject *o) { - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_memoryview___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->obj); - Py_CLEAR(p->_size); - Py_CLEAR(p->_array_interface); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - if (p->obj) { - e = (*v)(p->obj, a); if (e) return e; - } - if (p->_size) { - e = (*v)(p->_size, a); if (e) return e; - } - if (p->_array_interface) { - e = (*v)(p->_array_interface, a); if (e) return e; - } - if (p->view.obj) { - e = (*v)(p->view.obj, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_memoryview(PyObject *o) { - PyObject* tmp; - struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - tmp = ((PyObject*)p->obj); - p->obj = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_size); - p->_size = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_array_interface); - p->_array_interface = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - Py_CLEAR(p->view.obj); - return 0; -} -static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { - PyObject *r; - PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; - r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); - Py_DECREF(x); - return r; -} - -static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_memoryview___setitem__(o, i, v); - } - else { - PyErr_Format(PyExc_NotImplementedError, - "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); - return -1; - } -} - -static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(o); -} - -static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(o); -} - -static PyMethodDef __pyx_methods_memoryview[] = { - {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, - {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, - {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, - {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_memoryview[] = { - {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, (char *)0, 0}, - {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, (char *)0, 0}, - {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, (char *)0, 0}, - {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, (char *)0, 0}, - {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, (char *)0, 0}, - {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, (char *)0, 0}, - {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, (char *)0, 0}, - {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, (char *)0, 0}, - {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PySequenceMethods __pyx_tp_as_sequence_memoryview = { - __pyx_memoryview___len__, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - __pyx_sq_item_memoryview, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_memoryview = { - __pyx_memoryview___len__, /*mp_length*/ - __pyx_memoryview___getitem__, /*mp_subscript*/ - __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_memoryview = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - __pyx_memoryview_getbuffer, /*bf_getbuffer*/ - 0, /*bf_releasebuffer*/ -}; - -static PyTypeObject __pyx_type___pyx_memoryview = { - PyVarObject_HEAD_INIT(0, 0) - "ueg_kernels.memoryview", /*tp_name*/ - sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_memoryview___repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - __pyx_memoryview___str__, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_memoryview, /*tp_traverse*/ - __pyx_tp_clear_memoryview, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_memoryview, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_memoryview, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_memoryview, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; -static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; - -static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_memoryviewslice_obj *p; - PyObject *o = __pyx_tp_new_memoryview(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_memoryviewslice_obj *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; - p->from_object = Py_None; Py_INCREF(Py_None); - p->from_slice.memview = NULL; - return o; -} - -static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_memoryviewslice___dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->from_object); - PyObject_GC_Track(o); - __pyx_tp_dealloc_memoryview(o); -} - -static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; - if (p->from_object) { - e = (*v)(p->from_object, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear__memoryviewslice(PyObject *o) { - PyObject* tmp; - struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - __pyx_tp_clear_memoryview(o); - tmp = ((PyObject*)p->from_object); - p->from_object = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - __PYX_XDEC_MEMVIEW(&p->from_slice, 1); - return 0; -} - -static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); -} - -static PyMethodDef __pyx_methods__memoryviewslice[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_1__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_3__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { - {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type___pyx_memoryviewslice = { - PyVarObject_HEAD_INIT(0, 0) - "ueg_kernels._memoryviewslice", /*tp_name*/ - sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - #if CYTHON_COMPILING_IN_PYPY - __pyx_memoryview___repr__, /*tp_repr*/ - #else - 0, /*tp_repr*/ - #endif - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - #if CYTHON_COMPILING_IN_PYPY - __pyx_memoryview___str__, /*tp_str*/ - #else - 0, /*tp_str*/ - #endif - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - "Internal class for passing memoryview slices to Python", /*tp_doc*/ - __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ - __pyx_tp_clear__memoryviewslice, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods__memoryviewslice, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets__memoryviewslice, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new__memoryviewslice, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif - #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 - 0, /*tp_pypy_flags*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -#if CYTHON_PEP489_MULTI_PHASE_INIT -static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ -static int __pyx_pymod_exec_ueg_kernels(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec_ueg_kernels}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "ueg_kernels", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1}, - {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, - {&__pyx_n_s_CTdagger, __pyx_k_CTdagger, sizeof(__pyx_k_CTdagger), 0, 0, 1, 1}, - {&__pyx_n_s_CTdagger_i, __pyx_k_CTdagger_i, sizeof(__pyx_k_CTdagger_i), 0, 0, 1, 1}, - {&__pyx_n_s_CTdagger_i_cube, __pyx_k_CTdagger_i_cube, sizeof(__pyx_k_CTdagger_i_cube), 0, 0, 1, 1}, - {&__pyx_n_s_CTdagger_j, __pyx_k_CTdagger_j, sizeof(__pyx_k_CTdagger_j), 0, 0, 1, 1}, - {&__pyx_n_s_CTdagger_j_cube, __pyx_k_CTdagger_j_cube, sizeof(__pyx_k_CTdagger_j_cube), 0, 0, 1, 1}, - {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_assign_to_read_only_memor, __pyx_k_Cannot_assign_to_read_only_memor, sizeof(__pyx_k_Cannot_assign_to_read_only_memor), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_create_writable_memory_vi, __pyx_k_Cannot_create_writable_memory_vi, sizeof(__pyx_k_Cannot_create_writable_memory_vi), 0, 0, 1, 0}, - {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, - {&__pyx_n_s_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, - {&__pyx_n_s_DTYPE_CX, __pyx_k_DTYPE_CX, sizeof(__pyx_k_DTYPE_CX), 0, 0, 1, 1}, - {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, - {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, - {&__pyx_n_s_G, __pyx_k_G, sizeof(__pyx_k_G), 0, 0, 1, 1}, - {&__pyx_n_s_Gh_i, __pyx_k_Gh_i, sizeof(__pyx_k_Gh_i), 0, 0, 1, 1}, - {&__pyx_n_s_Gh_i_cube, __pyx_k_Gh_i_cube, sizeof(__pyx_k_Gh_i_cube), 0, 0, 1, 1}, - {&__pyx_n_s_Gh_j, __pyx_k_Gh_j, sizeof(__pyx_k_Gh_j), 0, 0, 1, 1}, - {&__pyx_n_s_Gh_j_cube, __pyx_k_Gh_j_cube, sizeof(__pyx_k_Gh_j_cube), 0, 0, 1, 1}, - {&__pyx_n_s_Ghalf, __pyx_k_Ghalf, sizeof(__pyx_k_Ghalf), 0, 0, 1, 1}, - {&__pyx_n_s_Gkpq, __pyx_k_Gkpq, sizeof(__pyx_k_Gkpq), 0, 0, 1, 1}, - {&__pyx_n_s_Gpmq, __pyx_k_Gpmq, sizeof(__pyx_k_Gpmq), 0, 0, 1, 1}, - {&__pyx_n_s_Gprod, __pyx_k_Gprod, sizeof(__pyx_k_Gprod), 0, 0, 1, 1}, - {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, - {&__pyx_kp_s_Incompatible_checksums_0x_x_vs_0, __pyx_k_Incompatible_checksums_0x_x_vs_0, sizeof(__pyx_k_Incompatible_checksums_0x_x_vs_0), 0, 0, 1, 0}, - {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, - {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, - {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, - {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, - {&__pyx_n_s_J, __pyx_k_J, sizeof(__pyx_k_J), 0, 0, 1, 1}, - {&__pyx_n_s_K, __pyx_k_K, sizeof(__pyx_k_K), 0, 0, 1, 1}, - {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, - {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, - {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, - {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, - {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, - {&__pyx_n_s_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_T, __pyx_k_T, sizeof(__pyx_k_T), 0, 0, 1, 1}, - {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, - {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, - {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, - {&__pyx_n_s_View_MemoryView, __pyx_k_View_MemoryView, sizeof(__pyx_k_View_MemoryView), 0, 0, 1, 1}, - {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, - {&__pyx_n_s_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 0, 0, 1, 1}, - {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, - {&__pyx_n_s_basis, __pyx_k_basis, sizeof(__pyx_k_basis), 0, 0, 1, 1}, - {&__pyx_n_s_build_J_opt, __pyx_k_build_J_opt, sizeof(__pyx_k_build_J_opt), 0, 0, 1, 1}, - {&__pyx_n_s_build_K_opt, __pyx_k_build_K_opt, sizeof(__pyx_k_build_K_opt), 0, 0, 1, 1}, - {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, - {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, - {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, - {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, - {&__pyx_n_s_complex128, __pyx_k_complex128, sizeof(__pyx_k_complex128), 0, 0, 1, 1}, - {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, - {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, - {&__pyx_n_s_convolve, __pyx_k_convolve, sizeof(__pyx_k_convolve), 0, 0, 1, 1}, - {&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, - {&__pyx_n_s_coulomb_greens_function_per_qvec, __pyx_k_coulomb_greens_function_per_qvec, sizeof(__pyx_k_coulomb_greens_function_per_qvec), 0, 0, 1, 1}, - {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, - {&__pyx_n_s_dot, __pyx_k_dot, sizeof(__pyx_k_dot), 0, 0, 1, 1}, - {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, - {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, - {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, - {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, - {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, - {&__pyx_n_s_exchange_greens_function_fft, __pyx_k_exchange_greens_function_fft, sizeof(__pyx_k_exchange_greens_function_fft), 0, 0, 1, 1}, - {&__pyx_n_s_exchange_greens_function_per_qve, __pyx_k_exchange_greens_function_per_qve, sizeof(__pyx_k_exchange_greens_function_per_qve), 0, 0, 1, 1}, - {&__pyx_n_s_fac, __pyx_k_fac, sizeof(__pyx_k_fac), 0, 0, 1, 1}, - {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, - {&__pyx_n_s_flip, __pyx_k_flip, sizeof(__pyx_k_flip), 0, 0, 1, 1}, - {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, - {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, - {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, - {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, - {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, - {&__pyx_n_s_gmap, __pyx_k_gmap, sizeof(__pyx_k_gmap), 0, 0, 1, 1}, - {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, - {&__pyx_n_s_h1e_mod, __pyx_k_h1e_mod, sizeof(__pyx_k_h1e_mod), 0, 0, 1, 1}, - {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, - {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, - {&__pyx_n_s_idxj, __pyx_k_idxj, sizeof(__pyx_k_idxj), 0, 0, 1, 1}, - {&__pyx_n_s_idxjmq, __pyx_k_idxjmq, sizeof(__pyx_k_idxjmq), 0, 0, 1, 1}, - {&__pyx_n_s_idxjpq, __pyx_k_idxjpq, sizeof(__pyx_k_idxjpq), 0, 0, 1, 1}, - {&__pyx_n_s_idxk, __pyx_k_idxk, sizeof(__pyx_k_idxk), 0, 0, 1, 1}, - {&__pyx_n_s_idxkpq, __pyx_k_idxkpq, sizeof(__pyx_k_idxkpq), 0, 0, 1, 1}, - {&__pyx_n_s_idxp, __pyx_k_idxp, sizeof(__pyx_k_idxp), 0, 0, 1, 1}, - {&__pyx_n_s_idxpmq, __pyx_k_idxpmq, sizeof(__pyx_k_idxpmq), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_inkpq, __pyx_k_inkpq, sizeof(__pyx_k_inkpq), 0, 0, 1, 1}, - {&__pyx_n_s_ipie_legacy_estimators_utils, __pyx_k_ipie_legacy_estimators_utils, sizeof(__pyx_k_ipie_legacy_estimators_utils), 0, 0, 1, 1}, - {&__pyx_n_s_iq, __pyx_k_iq, sizeof(__pyx_k_iq), 0, 0, 1, 1}, - {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, - {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, - {&__pyx_n_s_itertools, __pyx_k_itertools, sizeof(__pyx_k_itertools), 0, 0, 1, 1}, - {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, - {&__pyx_n_s_jnpmq, __pyx_k_jnpmq, sizeof(__pyx_k_jnpmq), 0, 0, 1, 1}, - {&__pyx_n_s_kfac, __pyx_k_kfac, sizeof(__pyx_k_kfac), 0, 0, 1, 1}, - {&__pyx_n_s_ki, __pyx_k_ki, sizeof(__pyx_k_ki), 0, 0, 1, 1}, - {&__pyx_n_s_kj, __pyx_k_kj, sizeof(__pyx_k_kj), 0, 0, 1, 1}, - {&__pyx_n_s_kpq, __pyx_k_kpq, sizeof(__pyx_k_kpq), 0, 0, 1, 1}, - {&__pyx_n_s_kpq_i, __pyx_k_kpq_i, sizeof(__pyx_k_kpq_i), 0, 0, 1, 1}, - {&__pyx_n_s_lQ_ij, __pyx_k_lQ_ij, sizeof(__pyx_k_lQ_ij), 0, 0, 1, 1}, - {&__pyx_n_s_lQ_ji, __pyx_k_lQ_ji, sizeof(__pyx_k_lQ_ji), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_math, __pyx_k_math, sizeof(__pyx_k_math), 0, 0, 1, 1}, - {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, - {&__pyx_n_s_mesh, __pyx_k_mesh, sizeof(__pyx_k_mesh), 0, 0, 1, 1}, - {&__pyx_n_s_mod_one_body, __pyx_k_mod_one_body, sizeof(__pyx_k_mod_one_body), 0, 0, 1, 1}, - {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, - {&__pyx_n_s_nbsf, __pyx_k_nbsf, sizeof(__pyx_k_nbsf), 0, 0, 1, 1}, - {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, - {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, - {&__pyx_n_s_ngrid, __pyx_k_ngrid, sizeof(__pyx_k_ngrid), 0, 0, 1, 1}, - {&__pyx_n_s_nkpq, __pyx_k_nkpq, sizeof(__pyx_k_nkpq), 0, 0, 1, 1}, - {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, - {&__pyx_n_s_nocc, __pyx_k_nocc, sizeof(__pyx_k_nocc), 0, 0, 1, 1}, - {&__pyx_n_s_npmq, __pyx_k_npmq, sizeof(__pyx_k_npmq), 0, 0, 1, 1}, - {&__pyx_n_s_nq, __pyx_k_nq, sizeof(__pyx_k_nq), 0, 0, 1, 1}, - {&__pyx_n_s_nqgrid, __pyx_k_nqgrid, sizeof(__pyx_k_nqgrid), 0, 0, 1, 1}, - {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, - {&__pyx_kp_u_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 1, 0, 0}, - {&__pyx_kp_u_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 1, 0, 0}, - {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, - {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, - {&__pyx_n_s_pi, __pyx_k_pi, sizeof(__pyx_k_pi), 0, 0, 1, 1}, - {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, - {&__pyx_n_s_pmq, __pyx_k_pmq, sizeof(__pyx_k_pmq), 0, 0, 1, 1}, - {&__pyx_n_s_pmq_i, __pyx_k_pmq_i, sizeof(__pyx_k_pmq_i), 0, 0, 1, 1}, - {&__pyx_n_s_prod, __pyx_k_prod, sizeof(__pyx_k_prod), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_unpickle_Enum, __pyx_k_pyx_unpickle_Enum, sizeof(__pyx_k_pyx_unpickle_Enum), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, - {&__pyx_n_s_q, __pyx_k_q, sizeof(__pyx_k_q), 0, 0, 1, 1}, - {&__pyx_n_s_q2, __pyx_k_q2, sizeof(__pyx_k_q2), 0, 0, 1, 1}, - {&__pyx_n_s_qmap, __pyx_k_qmap, sizeof(__pyx_k_qmap), 0, 0, 1, 1}, - {&__pyx_n_s_qmesh, __pyx_k_qmesh, sizeof(__pyx_k_qmesh), 0, 0, 1, 1}, - {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, - {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, - {&__pyx_n_s_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 0, 1, 1}, - {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, - {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, - {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, - {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, - {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, - {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, - {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, - {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, - {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, - {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, - {&__pyx_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, - {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_ueg_kernels, __pyx_k_ueg_kernels, sizeof(__pyx_k_ueg_kernels), 0, 0, 1, 1}, - {&__pyx_kp_s_ueg_kernels_pyx, __pyx_k_ueg_kernels_pyx, sizeof(__pyx_k_ueg_kernels_pyx), 0, 0, 1, 0}, - {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, - {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, - {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, - {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, - {&__pyx_n_s_vol, __pyx_k_vol, sizeof(__pyx_k_vol), 0, 0, 1, 1}, - {&__pyx_n_s_vq, __pyx_k_vq, sizeof(__pyx_k_vq), 0, 0, 1, 1}, - {&__pyx_n_s_vqvec, __pyx_k_vqvec, sizeof(__pyx_k_vqvec), 0, 0, 1, 1}, - {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, - {&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(0, 38, __pyx_L1_error) - __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 54, __pyx_L1_error) - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 70, __pyx_L1_error) - __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 944, __pyx_L1_error) - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(2, 134, __pyx_L1_error) - __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(2, 149, __pyx_L1_error) - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(2, 2, __pyx_L1_error) - __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(2, 406, __pyx_L1_error) - __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(2, 615, __pyx_L1_error) - __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(2, 834, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":944 - * __pyx_import_array() - * except Exception: - * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< - * - * cdef inline int import_umath() except -1: - */ - __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 944, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple_); - __Pyx_GIVEREF(__pyx_tuple_); - - /* "../../../../../../../../envs/ipie/lib/python3.9/site-packages/numpy/__init__.pxd":950 - * _import_umath() - * except Exception: - * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< - * - * cdef inline int import_ufunc() except -1: - */ - __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 950, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__2); - __Pyx_GIVEREF(__pyx_tuple__2); - - /* "View.MemoryView":134 - * - * if not self.ndim: - * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< - * - * if itemsize <= 0: - */ - __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(2, 134, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__3); - __Pyx_GIVEREF(__pyx_tuple__3); - - /* "View.MemoryView":137 - * - * if itemsize <= 0: - * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< - * - * if not isinstance(format, bytes): - */ - __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(2, 137, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__4); - __Pyx_GIVEREF(__pyx_tuple__4); - - /* "View.MemoryView":149 - * - * if not self._shape: - * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(2, 149, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); - - /* "View.MemoryView":177 - * self.data = malloc(self.len) - * if not self.data: - * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< - * - * if self.dtype_is_object: - */ - __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(2, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__6); - __Pyx_GIVEREF(__pyx_tuple__6); - - /* "View.MemoryView":193 - * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS - * if not (flags & bufmode): - * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< - * info.buf = self.data - * info.len = self.len - */ - __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(2, 193, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__7); - __Pyx_GIVEREF(__pyx_tuple__7); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(2, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__8); - __Pyx_GIVEREF(__pyx_tuple__8); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__9); - __Pyx_GIVEREF(__pyx_tuple__9); - - /* "View.MemoryView":420 - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: - * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< - * - * have_slices, index = _unellipsify(index, self.view.ndim) - */ - __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(2, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__10); - __Pyx_GIVEREF(__pyx_tuple__10); - - /* "View.MemoryView":497 - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< - * else: - * if len(self.view.format) == 1: - */ - __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(2, 497, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__11); - __Pyx_GIVEREF(__pyx_tuple__11); - - /* "View.MemoryView":522 - * def __getbuffer__(self, Py_buffer *info, int flags): - * if flags & PyBUF_WRITABLE and self.view.readonly: - * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< - * - * if flags & PyBUF_ND: - */ - __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(2, 522, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__12); - __Pyx_GIVEREF(__pyx_tuple__12); - - /* "View.MemoryView":572 - * if self.view.strides == NULL: - * - * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< - * - * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) - */ - __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(2, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__13); - __Pyx_GIVEREF(__pyx_tuple__13); - - /* "View.MemoryView":579 - * def suboffsets(self): - * if self.view.suboffsets == NULL: - * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< - * - * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) - */ - __pyx_tuple__14 = PyTuple_New(1); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(2, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__14); - __Pyx_INCREF(__pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_tuple__14, 0, __pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_tuple__14); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(2, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__15); - __Pyx_GIVEREF(__pyx_tuple__15); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__16); - __Pyx_GIVEREF(__pyx_tuple__16); - - /* "View.MemoryView":684 - * if item is Ellipsis: - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< - * seen_ellipsis = True - * else: - */ - __pyx_slice__17 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__17)) __PYX_ERR(2, 684, __pyx_L1_error) - __Pyx_GOTREF(__pyx_slice__17); - __Pyx_GIVEREF(__pyx_slice__17); - - /* "View.MemoryView":705 - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(2, 705, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__18); - __Pyx_GIVEREF(__pyx_tuple__18); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(2, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__19); - __Pyx_GIVEREF(__pyx_tuple__19); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__20); - __Pyx_GIVEREF(__pyx_tuple__20); - __pyx_tuple__21 = PyTuple_Pack(3, __pyx_int_184977713, __pyx_int_136983863, __pyx_int_112105877); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(2, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__21); - __Pyx_GIVEREF(__pyx_tuple__21); - - /* "ueg_kernels.pyx":14 - * - * - * def vq(numpy.ndarray q): # <<<<<<<<<<<<<< - * assert(q.shape[0] == 3) - * cdef double q2 = numpy.dot(q, q) - */ - __pyx_tuple__22 = PyTuple_Pack(2, __pyx_n_s_q, __pyx_n_s_q2); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(0, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__22); - __Pyx_GIVEREF(__pyx_tuple__22); - __pyx_codeobj__23 = (PyObject*)__Pyx_PyCode_New(1, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__22, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_vq, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__23)) __PYX_ERR(0, 14, __pyx_L1_error) - - /* "ueg_kernels.pyx":22 - * return 4*math.pi / q2 - * - * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): # <<<<<<<<<<<<<< - * """ Add a diagonal term of two-body Hamiltonian to the one-body term - * Parameters - */ - __pyx_tuple__24 = PyTuple_Pack(12, __pyx_n_s_T, __pyx_n_s_basis, __pyx_n_s_vol, __pyx_n_s_kfac, __pyx_n_s_nbsf, __pyx_n_s_h1e_mod, __pyx_n_s_fac, __pyx_n_s_i, __pyx_n_s_ki, __pyx_n_s_j, __pyx_n_s_kj, __pyx_n_s_q); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(0, 22, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__24); - __Pyx_GIVEREF(__pyx_tuple__24); - __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(4, 0, 12, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__24, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_mod_one_body, 22, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) __PYX_ERR(0, 22, __pyx_L1_error) - - /* "ueg_kernels.pyx":45 - * return h1e_mod - * - * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): # <<<<<<<<<<<<<< - * - * cdef int nq = kpq_i.shape[0] - */ - __pyx_tuple__26 = PyTuple_Pack(13, __pyx_n_s_kpq_i, __pyx_n_s_kpq, __pyx_n_s_pmq_i, __pyx_n_s_pmq, __pyx_n_s_G, __pyx_n_s_nq, __pyx_n_s_idxkpq, __pyx_n_s_idxpmq, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_iq, __pyx_n_s_Gkpq, __pyx_n_s_Gpmq); if (unlikely(!__pyx_tuple__26)) __PYX_ERR(0, 45, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__26); - __Pyx_GIVEREF(__pyx_tuple__26); - __pyx_codeobj__27 = (PyObject*)__Pyx_PyCode_New(5, 0, 13, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__26, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_coulomb_greens_function_per_qvec, 45, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__27)) __PYX_ERR(0, 45, __pyx_L1_error) - - /* "ueg_kernels.pyx":61 - * return Gkpq, Gpmq - * - * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): # <<<<<<<<<<<<<< - * - * cdef int nkpq = kpq_i.shape[0] - */ - __pyx_tuple__28 = PyTuple_Pack(14, __pyx_n_s_kpq_i, __pyx_n_s_kpq, __pyx_n_s_pmq_i, __pyx_n_s_pmq, __pyx_n_s_G, __pyx_n_s_nkpq, __pyx_n_s_npmq, __pyx_n_s_Gprod, __pyx_n_s_idxkpq, __pyx_n_s_idxpmq, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_inkpq, __pyx_n_s_jnpmq); if (unlikely(!__pyx_tuple__28)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__28); - __Pyx_GIVEREF(__pyx_tuple__28); - __pyx_codeobj__29 = (PyObject*)__Pyx_PyCode_New(5, 0, 14, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__28, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_exchange_greens_function_per_qve, 61, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__29)) __PYX_ERR(0, 61, __pyx_L1_error) - - /* "ueg_kernels.pyx":80 - * return Gprod - * - * def exchange_greens_function_fft (long nocc, long nbsf, # <<<<<<<<<<<<<< - * long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, - * double complex[:,:] CTdagger, double complex[:,:] Ghalf): - */ - __pyx_tuple__30 = PyTuple_Pack(24, __pyx_n_s_nocc, __pyx_n_s_nbsf, __pyx_n_s_mesh, __pyx_n_s_qmesh, __pyx_n_s_gmap, __pyx_n_s_qmap, __pyx_n_s_CTdagger, __pyx_n_s_Ghalf, __pyx_n_s_ngrid, __pyx_n_s_nqgrid, __pyx_n_s_nq, __pyx_n_s_Gprod, __pyx_n_s_Gh_i, __pyx_n_s_CTdagger_j, __pyx_n_s_Gh_i_cube, __pyx_n_s_CTdagger_j_cube, __pyx_n_s_Gh_j, __pyx_n_s_CTdagger_i, __pyx_n_s_Gh_j_cube, __pyx_n_s_CTdagger_i_cube, __pyx_n_s_lQ_ji, __pyx_n_s_lQ_ij, __pyx_n_s_i, __pyx_n_s_j); if (unlikely(!__pyx_tuple__30)) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__30); - __Pyx_GIVEREF(__pyx_tuple__30); - __pyx_codeobj__31 = (PyObject*)__Pyx_PyCode_New(8, 0, 24, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__30, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_exchange_greens_function_fft, 80, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__31)) __PYX_ERR(0, 80, __pyx_L1_error) - - /* "ueg_kernels.pyx":138 - * return Gprod - * - * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< - * list kpq, list pmq_i, list pmq, - * double complex[:,:] Gkpq, double complex[:,:] Gpmq): - */ - __pyx_tuple__32 = PyTuple_Pack(14, __pyx_n_s_nq, __pyx_n_s_vqvec, __pyx_n_s_vol, __pyx_n_s_nbsf, __pyx_n_s_kpq_i, __pyx_n_s_kpq, __pyx_n_s_pmq_i, __pyx_n_s_pmq, __pyx_n_s_Gkpq, __pyx_n_s_Gpmq, __pyx_n_s_J, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_iq); if (unlikely(!__pyx_tuple__32)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__32); - __Pyx_GIVEREF(__pyx_tuple__32); - __pyx_codeobj__33 = (PyObject*)__Pyx_PyCode_New(10, 0, 14, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__32, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_build_J_opt, 138, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__33)) __PYX_ERR(0, 138, __pyx_L1_error) - - /* "ueg_kernels.pyx":154 - * return J - * - * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< - * list kpq, list pmq_i, list pmq, - * double complex[:,:,:] G): - */ - __pyx_tuple__34 = PyTuple_Pack(19, __pyx_n_s_nq, __pyx_n_s_vqvec, __pyx_n_s_vol, __pyx_n_s_nbsf, __pyx_n_s_kpq_i, __pyx_n_s_kpq, __pyx_n_s_pmq_i, __pyx_n_s_pmq, __pyx_n_s_G, __pyx_n_s_K, __pyx_n_s_iq, __pyx_n_s_s, __pyx_n_s_idxjmq, __pyx_n_s_idxkpq, __pyx_n_s_idxk, __pyx_n_s_idxjpq, __pyx_n_s_idxj, __pyx_n_s_idxpmq, __pyx_n_s_idxp); if (unlikely(!__pyx_tuple__34)) __PYX_ERR(0, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__34); - __Pyx_GIVEREF(__pyx_tuple__34); - __pyx_codeobj__35 = (PyObject*)__Pyx_PyCode_New(9, 0, 19, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_ueg_kernels_pyx, __pyx_n_s_build_K_opt, 154, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__35)) __PYX_ERR(0, 154, __pyx_L1_error) - - /* "View.MemoryView":287 - * return self.name - * - * cdef generic = Enum("") # <<<<<<<<<<<<<< - * cdef strided = Enum("") # default - * cdef indirect = Enum("") - */ - __pyx_tuple__36 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__36)) __PYX_ERR(2, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__36); - __Pyx_GIVEREF(__pyx_tuple__36); - - /* "View.MemoryView":288 - * - * cdef generic = Enum("") - * cdef strided = Enum("") # default # <<<<<<<<<<<<<< - * cdef indirect = Enum("") - * - */ - __pyx_tuple__37 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__37)) __PYX_ERR(2, 288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__37); - __Pyx_GIVEREF(__pyx_tuple__37); - - /* "View.MemoryView":289 - * cdef generic = Enum("") - * cdef strided = Enum("") # default - * cdef indirect = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__38 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__38)) __PYX_ERR(2, 289, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__38); - __Pyx_GIVEREF(__pyx_tuple__38); - - /* "View.MemoryView":292 - * - * - * cdef contiguous = Enum("") # <<<<<<<<<<<<<< - * cdef indirect_contiguous = Enum("") - * - */ - __pyx_tuple__39 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__39)) __PYX_ERR(2, 292, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__39); - __Pyx_GIVEREF(__pyx_tuple__39); - - /* "View.MemoryView":293 - * - * cdef contiguous = Enum("") - * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__40 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__40)) __PYX_ERR(2, 293, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__40); - __Pyx_GIVEREF(__pyx_tuple__40); - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_tuple__41 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__41)) __PYX_ERR(2, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__41); - __Pyx_GIVEREF(__pyx_tuple__41); - __pyx_codeobj__42 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__41, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__42)) __PYX_ERR(2, 1, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_float_0_0 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_float_0_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_4 = PyInt_FromLong(4); if (unlikely(!__pyx_int_4)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_112105877 = PyInt_FromLong(112105877L); if (unlikely(!__pyx_int_112105877)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_136983863 = PyInt_FromLong(136983863L); if (unlikely(!__pyx_int_136983863)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_184977713 = PyInt_FromLong(184977713L); if (unlikely(!__pyx_int_184977713)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ - -static int __Pyx_modinit_global_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); - /*--- Global init code ---*/ - generic = Py_None; Py_INCREF(Py_None); - strided = Py_None; Py_INCREF(Py_None); - indirect = Py_None; Py_INCREF(Py_None); - contiguous = Py_None; Py_INCREF(Py_None); - indirect_contiguous = Py_None; Py_INCREF(Py_None); - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); - /*--- Variable export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); - /*--- Function export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - __pyx_vtabptr_array = &__pyx_vtable_array; - __pyx_vtable_array.get_memview = (PyObject *(*)(struct __pyx_array_obj *))__pyx_array_get_memview; - if (PyType_Ready(&__pyx_type___pyx_array) < 0) __PYX_ERR(2, 106, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_array.tp_print = 0; - #endif - if (__Pyx_SetVtable(__pyx_type___pyx_array.tp_dict, __pyx_vtabptr_array) < 0) __PYX_ERR(2, 106, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(2, 106, __pyx_L1_error) - __pyx_array_type = &__pyx_type___pyx_array; - if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(2, 280, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_MemviewEnum.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_MemviewEnum.tp_dictoffset && __pyx_type___pyx_MemviewEnum.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_MemviewEnum.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(2, 280, __pyx_L1_error) - __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; - __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; - __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; - __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; - __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; - __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; - __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; - __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; - __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; - if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(2, 331, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_memoryview.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryview.tp_dictoffset && __pyx_type___pyx_memoryview.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_memoryview.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(2, 331, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(2, 331, __pyx_L1_error) - __pyx_memoryview_type = &__pyx_type___pyx_memoryview; - __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; - __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; - __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; - __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; - __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; - if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(2, 967, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type___pyx_memoryviewslice.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryviewslice.tp_dictoffset && __pyx_type___pyx_memoryviewslice.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type___pyx_memoryviewslice.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(2, 967, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(2, 967, __pyx_L1_error) - __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_4type_type = __Pyx_ImportType_0_29_35(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", - #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 - sizeof(PyTypeObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyTypeObject), - #else - sizeof(PyHeapTypeObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyHeapTypeObject), - #endif - __Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(3, 9, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyImport_ImportModule("numpy"); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 199, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_5numpy_dtype = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "dtype", sizeof(PyArray_Descr), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyArray_Descr),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_dtype) __PYX_ERR(1, 199, __pyx_L1_error) - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "flatiter", sizeof(PyArrayIterObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyArrayIterObject),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_flatiter) __PYX_ERR(1, 222, __pyx_L1_error) - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "broadcast", sizeof(PyArrayMultiIterObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyArrayMultiIterObject),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_broadcast) __PYX_ERR(1, 226, __pyx_L1_error) - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "ndarray", sizeof(PyArrayObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyArrayObject),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_ndarray) __PYX_ERR(1, 238, __pyx_L1_error) - __pyx_ptype_5numpy_generic = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "generic", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_generic) __PYX_ERR(1, 770, __pyx_L1_error) - __pyx_ptype_5numpy_number = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "number", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_number) __PYX_ERR(1, 772, __pyx_L1_error) - __pyx_ptype_5numpy_integer = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "integer", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_integer) __PYX_ERR(1, 774, __pyx_L1_error) - __pyx_ptype_5numpy_signedinteger = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "signedinteger", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_signedinteger) __PYX_ERR(1, 776, __pyx_L1_error) - __pyx_ptype_5numpy_unsignedinteger = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "unsignedinteger", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_unsignedinteger) __PYX_ERR(1, 778, __pyx_L1_error) - __pyx_ptype_5numpy_inexact = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "inexact", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_inexact) __PYX_ERR(1, 780, __pyx_L1_error) - __pyx_ptype_5numpy_floating = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "floating", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_floating) __PYX_ERR(1, 782, __pyx_L1_error) - __pyx_ptype_5numpy_complexfloating = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "complexfloating", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_complexfloating) __PYX_ERR(1, 784, __pyx_L1_error) - __pyx_ptype_5numpy_flexible = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "flexible", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_flexible) __PYX_ERR(1, 786, __pyx_L1_error) - __pyx_ptype_5numpy_character = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "character", sizeof(PyObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyObject),__Pyx_ImportType_CheckSize_Warn_0_29_35); if (!__pyx_ptype_5numpy_character) __PYX_ERR(1, 788, __pyx_L1_error) - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType_0_29_35(__pyx_t_1, "numpy", "ufunc", sizeof(PyUFuncObject), __PYX_GET_STRUCT_ALIGNMENT_0_29_35(PyUFuncObject),__Pyx_ImportType_CheckSize_Ignore_0_29_35); if (!__pyx_ptype_5numpy_ufunc) __PYX_ERR(1, 826, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_variable_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); - /*--- Variable import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); - /*--- Function import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - - -#ifndef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#elif PY_MAJOR_VERSION < 3 -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" void -#else -#define __Pyx_PyMODINIT_FUNC void -#endif -#else -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyObject * -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC initueg_kernels(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC initueg_kernels(void) -#else -__Pyx_PyMODINIT_FUNC PyInit_ueg_kernels(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit_ueg_kernels(void) -#if CYTHON_PEP489_MULTI_PHASE_INIT -{ - return PyModuleDef_Init(&__pyx_moduledef); -} -static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { - #if PY_VERSION_HEX >= 0x030700A1 - static PY_INT64_T main_interpreter_id = -1; - PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); - if (main_interpreter_id == -1) { - main_interpreter_id = current_id; - return (unlikely(current_id == -1)) ? -1 : 0; - } else if (unlikely(main_interpreter_id != current_id)) - #else - static PyInterpreterState *main_interpreter = NULL; - PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; - if (!main_interpreter) { - main_interpreter = current_interpreter; - } else if (unlikely(main_interpreter != current_interpreter)) - #endif - { - PyErr_SetString( - PyExc_ImportError, - "Interpreter change detected - this module can only be loaded into one interpreter per process."); - return -1; - } - return 0; -} -static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - if (allow_none || value != Py_None) { - result = PyDict_SetItemString(moddict, to_name, value); - } - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - if (__Pyx_check_single_interpreter()) - return NULL; - if (__pyx_m) - return __Pyx_NewRef(__pyx_m); - modname = PyObject_GetAttrString(spec, "name"); - if (unlikely(!modname)) goto bad; - module = PyModule_NewObject(modname); - Py_DECREF(modname); - if (unlikely(!module)) goto bad; - moddict = PyModule_GetDict(module); - if (unlikely(!moddict)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} - - -static CYTHON_SMALL_CODE int __pyx_pymod_exec_ueg_kernels(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - static PyThread_type_lock __pyx_t_3[8]; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module 'ueg_kernels' has already been imported. Re-initialisation is not supported."); - return -1; - } - #elif PY_MAJOR_VERSION >= 3 - if (__pyx_m) return __Pyx_NewRef(__pyx_m); - #endif - #if CYTHON_REFNANNY -__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); -if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); -} -#endif - __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_ueg_kernels(void)", 0); - if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pxy_PyFrame_Initialize_Offsets - __Pxy_PyFrame_Initialize_Offsets(); - #endif - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - PyEval_InitThreads(); - #endif - /*--- Module creation code ---*/ - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_m = __pyx_pyinit_module; - Py_INCREF(__pyx_m); - #else - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("ueg_kernels", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main_ueg_kernels) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name_2, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "ueg_kernels")) { - if (unlikely(PyDict_SetItemString(modules, "ueg_kernels", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Global type/function init code ---*/ - (void)__Pyx_modinit_global_init_code(); - (void)__Pyx_modinit_variable_export_code(); - (void)__Pyx_modinit_function_export_code(); - if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - if (unlikely(__Pyx_modinit_type_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - (void)__Pyx_modinit_variable_import_code(); - (void)__Pyx_modinit_function_import_code(); - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - - /* "ueg_kernels.pyx":1 - * import numpy # <<<<<<<<<<<<<< - * - * cimport numpy - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_numpy, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":5 - * cimport numpy - * - * import itertools # <<<<<<<<<<<<<< - * import math - * - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_itertools, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_itertools, __pyx_t_1) < 0) __PYX_ERR(0, 5, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":6 - * - * import itertools - * import math # <<<<<<<<<<<<<< - * - * from ipie.legacy.estimators.utils import convolve - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_math, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_math, __pyx_t_1) < 0) __PYX_ERR(0, 6, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":8 - * import math - * - * from ipie.legacy.estimators.utils import convolve # <<<<<<<<<<<<<< - * - * DTYPE_CX = numpy.complex128 - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_convolve); - __Pyx_GIVEREF(__pyx_n_s_convolve); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_convolve); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_ipie_legacy_estimators_utils, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_convolve); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_convolve, __pyx_t_1) < 0) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":10 - * from ipie.legacy.estimators.utils import convolve - * - * DTYPE_CX = numpy.complex128 # <<<<<<<<<<<<<< - * DTYPE = numpy.float64 - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_numpy); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 10, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_complex128); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE_CX, __pyx_t_1) < 0) __PYX_ERR(0, 10, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "ueg_kernels.pyx":11 - * - * DTYPE_CX = numpy.complex128 - * DTYPE = numpy.float64 # <<<<<<<<<<<<<< - * - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_numpy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 11, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_float64); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 11, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_2) < 0) __PYX_ERR(0, 11, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":14 - * - * - * def vq(numpy.ndarray q): # <<<<<<<<<<<<<< - * assert(q.shape[0] == 3) - * cdef double q2 = numpy.dot(q, q) - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_1vq, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_vq, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":22 - * return 4*math.pi / q2 - * - * def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): # <<<<<<<<<<<<<< - * """ Add a diagonal term of two-body Hamiltonian to the one-body term - * Parameters - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_3mod_one_body, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 22, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_mod_one_body, __pyx_t_2) < 0) __PYX_ERR(0, 22, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":45 - * return h1e_mod - * - * def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): # <<<<<<<<<<<<<< - * - * cdef int nq = kpq_i.shape[0] - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_5coulomb_greens_function_per_qvec, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 45, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_coulomb_greens_function_per_qvec, __pyx_t_2) < 0) __PYX_ERR(0, 45, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":61 - * return Gkpq, Gpmq - * - * def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): # <<<<<<<<<<<<<< - * - * cdef int nkpq = kpq_i.shape[0] - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_7exchange_greens_function_per_qvec, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_exchange_greens_function_per_qve, __pyx_t_2) < 0) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":80 - * return Gprod - * - * def exchange_greens_function_fft (long nocc, long nbsf, # <<<<<<<<<<<<<< - * long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, - * double complex[:,:] CTdagger, double complex[:,:] Ghalf): - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_9exchange_greens_function_fft, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_exchange_greens_function_fft, __pyx_t_2) < 0) __PYX_ERR(0, 80, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":138 - * return Gprod - * - * def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< - * list kpq, list pmq_i, list pmq, - * double complex[:,:] Gkpq, double complex[:,:] Gpmq): - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_11build_J_opt, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_build_J_opt, __pyx_t_2) < 0) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":154 - * return J - * - * def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, # <<<<<<<<<<<<<< - * list kpq, list pmq_i, list pmq, - * double complex[:,:,:] G): - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_11ueg_kernels_13build_K_opt, NULL, __pyx_n_s_ueg_kernels); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 154, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_build_K_opt, __pyx_t_2) < 0) __PYX_ERR(0, 154, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "ueg_kernels.pyx":1 - * import numpy # <<<<<<<<<<<<<< - * - * cimport numpy - */ - __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":210 - * info.obj = self - * - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * def __dealloc__(array self): - */ - __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 210, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) __PYX_ERR(2, 210, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - PyType_Modified(__pyx_array_type); - - /* "View.MemoryView":287 - * return self.name - * - * cdef generic = Enum("") # <<<<<<<<<<<<<< - * cdef strided = Enum("") # default - * cdef indirect = Enum("") - */ - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XGOTREF(generic); - __Pyx_DECREF_SET(generic, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":288 - * - * cdef generic = Enum("") - * cdef strided = Enum("") # default # <<<<<<<<<<<<<< - * cdef indirect = Enum("") - * - */ - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__37, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XGOTREF(strided); - __Pyx_DECREF_SET(strided, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":289 - * cdef generic = Enum("") - * cdef strided = Enum("") # default - * cdef indirect = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__38, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 289, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XGOTREF(indirect); - __Pyx_DECREF_SET(indirect, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":292 - * - * - * cdef contiguous = Enum("") # <<<<<<<<<<<<<< - * cdef indirect_contiguous = Enum("") - * - */ - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 292, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XGOTREF(contiguous); - __Pyx_DECREF_SET(contiguous, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":293 - * - * cdef contiguous = Enum("") - * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 293, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XGOTREF(indirect_contiguous); - __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":317 - * - * DEF THREAD_LOCKS_PREALLOCATED = 8 - * cdef int __pyx_memoryview_thread_locks_used = 0 # <<<<<<<<<<<<<< - * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ - * PyThread_allocate_lock(), - */ - __pyx_memoryview_thread_locks_used = 0; - - /* "View.MemoryView":318 - * DEF THREAD_LOCKS_PREALLOCATED = 8 - * cdef int __pyx_memoryview_thread_locks_used = 0 - * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ # <<<<<<<<<<<<<< - * PyThread_allocate_lock(), - * PyThread_allocate_lock(), - */ - __pyx_t_3[0] = PyThread_allocate_lock(); - __pyx_t_3[1] = PyThread_allocate_lock(); - __pyx_t_3[2] = PyThread_allocate_lock(); - __pyx_t_3[3] = PyThread_allocate_lock(); - __pyx_t_3[4] = PyThread_allocate_lock(); - __pyx_t_3[5] = PyThread_allocate_lock(); - __pyx_t_3[6] = PyThread_allocate_lock(); - __pyx_t_3[7] = PyThread_allocate_lock(); - memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_3, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); - - /* "View.MemoryView":551 - * info.obj = self - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 551, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) __PYX_ERR(2, 551, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - PyType_Modified(__pyx_memoryview_type); - - /* "View.MemoryView":997 - * return self.from_object - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 997, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_2) < 0) __PYX_ERR(2, 997, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - PyType_Modified(__pyx_memoryviewslice_type); - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_2)) __PYX_ERR(2, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_2) < 0) __PYX_ERR(2, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "(tree fragment)":11 - * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0] - * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): - */ - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init ueg_kernels", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init ueg_kernels"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if CYTHON_PEP489_MULTI_PHASE_INIT - return (__pyx_m != NULL) ? 0 : -1; - #elif PY_MAJOR_VERSION >= 3 - return __pyx_m; - #else - return; - #endif -} - -/* --- Runtime support code --- */ -/* Refnanny */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule(modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -/* PyObjectGetAttrStr */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - -/* GetBuiltinName */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/* ArgTypeTest */ -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) -{ - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - else if (exact) { - #if PY_MAJOR_VERSION == 2 - if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; - #endif - } - else { - if (likely(__Pyx_TypeCheck(obj, type))) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} - -/* PyDictVersioning */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { - PyObject **dictptr = NULL; - Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; - if (offset) { -#if CYTHON_COMPILING_IN_CPYTHON - dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); -#else - dictptr = _PyObject_GetDictPtr(obj); -#endif - } - return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; -} -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) - return 0; - return obj_dict_version == __Pyx_get_object_dict_version(obj); -} -#endif - -/* GetModuleGlobalName */ -#if CYTHON_USE_DICT_VERSIONS -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) -#else -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) -#endif -{ - PyObject *result; -#if !CYTHON_AVOID_BORROWED_REFS -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 - result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } else if (unlikely(PyErr_Occurred())) { - return NULL; - } -#else - result = PyDict_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } -#endif -#else - result = PyObject_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } - PyErr_Clear(); -#endif - return __Pyx_GetBuiltinName(name); -} - -/* PyFunctionFastCall */ -#if CYTHON_FAST_PYCALL -static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, - PyObject *globals) { - PyFrameObject *f; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject **fastlocals; - Py_ssize_t i; - PyObject *result; - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) { - return NULL; - } - fastlocals = __Pyx_PyFrame_GetLocalsplus(f); - for (i = 0; i < na; i++) { - Py_INCREF(*args); - fastlocals[i] = *args++; - } - result = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return result; -} -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure; -#if PY_MAJOR_VERSION >= 3 - PyObject *kwdefs; -#endif - PyObject *kwtuple, **k; - PyObject **d; - Py_ssize_t nd; - Py_ssize_t nk; - PyObject *result; - assert(kwargs == NULL || PyDict_Check(kwargs)); - nk = kwargs ? PyDict_Size(kwargs) : 0; - if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { - return NULL; - } - if ( -#if PY_MAJOR_VERSION >= 3 - co->co_kwonlyargcount == 0 && -#endif - likely(kwargs == NULL || nk == 0) && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - if (argdefs == NULL && co->co_argcount == nargs) { - result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); - goto done; - } - else if (nargs == 0 && argdefs != NULL - && co->co_argcount == Py_SIZE(argdefs)) { - /* function called with no arguments, but all parameters have - a default value: use default values as arguments .*/ - args = &PyTuple_GET_ITEM(argdefs, 0); - result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); - goto done; - } - } - if (kwargs != NULL) { - Py_ssize_t pos, i; - kwtuple = PyTuple_New(2 * nk); - if (kwtuple == NULL) { - result = NULL; - goto done; - } - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i / 2; - } - else { - kwtuple = NULL; - k = NULL; - } - closure = PyFunction_GET_CLOSURE(func); -#if PY_MAJOR_VERSION >= 3 - kwdefs = PyFunction_GET_KW_DEFAULTS(func); -#endif - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } -#if PY_MAJOR_VERSION >= 3 - result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, kwdefs, closure); -#else - result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, closure); -#endif - Py_XDECREF(kwtuple); -done: - Py_LeaveRecursiveCall(); - return result; -} -#endif -#endif - -/* PyCFunctionFastCall */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { - PyCFunctionObject *func = (PyCFunctionObject*)func_obj; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - int flags = PyCFunction_GET_FLAGS(func); - assert(PyCFunction_Check(func)); - assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); - assert(nargs >= 0); - assert(nargs == 0 || args != NULL); - /* _PyCFunction_FastCallDict() must not be called with an exception set, - because it may clear it (directly or indirectly) and so the - caller loses its exception */ - assert(!PyErr_Occurred()); - if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); - } -} -#endif - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = Py_TYPE(func)->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* RaiseArgTupleInvalid */ -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -/* RaiseDoubleKeywords */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -/* ParseKeywords */ -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -/* PyObjectCallMethO */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallNoArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, NULL, 0); - } -#endif -#if defined(__Pyx_CyFunction_USED) && defined(NDEBUG) - if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) -#else - if (likely(PyCFunction_Check(func))) -#endif - { - if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { - return __Pyx_PyObject_CallMethO(func, NULL); - } - } - return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); -} -#endif - -/* PyObjectCallOneArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, &arg, 1); - } -#endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); -#if CYTHON_FAST_PYCCALL - } else if (__Pyx_PyFastCFunction_Check(func)) { - return __Pyx_PyCFunction_FastCall(func, &arg, 1); -#endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -/* ExtTypeTest */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(__Pyx_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -/* PyIntBinop */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) { - (void)inplace; - (void)zerodivision_check; - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - const long b = intval; - long x; - long a = PyInt_AS_LONG(op1); - x = (long)((unsigned long)a + b); - if (likely((x^a) >= 0 || (x^b) >= 0)) - return PyInt_FromLong(x); - return PyLong_Type.tp_as_number->nb_add(op1, op2); - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(op1))) { - const long b = intval; - long a, x; -#ifdef HAVE_LONG_LONG - const PY_LONG_LONG llb = intval; - PY_LONG_LONG lla, llx; -#endif - const digit* digits = ((PyLongObject*)op1)->ob_digit; - const Py_ssize_t size = Py_SIZE(op1); - if (likely(__Pyx_sst_abs(size) <= 1)) { - a = likely(size) ? digits[0] : 0; - if (size == -1) a = -a; - } else { - switch (size) { - case -2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case -3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case -4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { - lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - case 4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; -#ifdef HAVE_LONG_LONG - } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { - lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); - goto long_long; -#endif - } - CYTHON_FALLTHROUGH; - default: return PyLong_Type.tp_as_number->nb_add(op1, op2); - } - } - x = a + b; - return PyLong_FromLong(x); -#ifdef HAVE_LONG_LONG - long_long: - llx = lla + llb; - return PyLong_FromLongLong(llx); -#endif - - - } - #endif - if (PyFloat_CheckExact(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - double result; - PyFPE_START_PROTECT("add", return NULL) - result = ((double)a) + (double)b; - PyFPE_END_PROTECT(result) - return PyFloat_FromDouble(result); - } - return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); -} -#endif - -/* GetItemInt */ -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyList_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyTuple_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -/* ObjectGetItem */ -#if CYTHON_USE_TYPE_SLOTS -static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { - PyObject *runerr = NULL; - Py_ssize_t key_value; - PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; - if (unlikely(!(m && m->sq_item))) { - PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); - return NULL; - } - key_value = __Pyx_PyIndex_AsSsize_t(index); - if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { - return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); - } - if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); - } - return NULL; -} -static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { - PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; - if (likely(m && m->mp_subscript)) { - return m->mp_subscript(obj, key); - } - return __Pyx_PyObject_GetIndex(obj, key); -} -#endif - -/* PyObjectCall2Args */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { - PyObject *args, *result = NULL; - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyFunction_FastCall(function, args, 2); - } - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyCFunction_FastCall(function, args, 2); - } - #endif - args = PyTuple_New(2); - if (unlikely(!args)) goto done; - Py_INCREF(arg1); - PyTuple_SET_ITEM(args, 0, arg1); - Py_INCREF(arg2); - PyTuple_SET_ITEM(args, 1, arg2); - Py_INCREF(function); - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); -done: - return result; -} - -/* RaiseTooManyValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -/* RaiseNeedMoreValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -/* IterFinish */ -static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_FAST_THREAD_STATE - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; - } - } - return 0; -#endif -} - -/* UnpackItemEndCheck */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } - return __Pyx_IterFinish(); -} - -/* BufferIndexError */ -static void __Pyx_RaiseBufferIndexError(int axis) { - PyErr_Format(PyExc_IndexError, - "Out of bounds on buffer access (axis %d)", axis); -} - -/* MemviewSliceInit */ -static int -__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, - int ndim, - __Pyx_memviewslice *memviewslice, - int memview_is_new_reference) -{ - __Pyx_RefNannyDeclarations - int i, retval=-1; - Py_buffer *buf = &memview->view; - __Pyx_RefNannySetupContext("init_memviewslice", 0); - if (unlikely(memviewslice->memview || memviewslice->data)) { - PyErr_SetString(PyExc_ValueError, - "memviewslice is already initialized!"); - goto fail; - } - if (buf->strides) { - for (i = 0; i < ndim; i++) { - memviewslice->strides[i] = buf->strides[i]; - } - } else { - Py_ssize_t stride = buf->itemsize; - for (i = ndim - 1; i >= 0; i--) { - memviewslice->strides[i] = stride; - stride *= buf->shape[i]; - } - } - for (i = 0; i < ndim; i++) { - memviewslice->shape[i] = buf->shape[i]; - if (buf->suboffsets) { - memviewslice->suboffsets[i] = buf->suboffsets[i]; - } else { - memviewslice->suboffsets[i] = -1; - } - } - memviewslice->memview = memview; - memviewslice->data = (char *)buf->buf; - if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { - Py_INCREF(memview); - } - retval = 0; - goto no_fail; -fail: - memviewslice->memview = 0; - memviewslice->data = 0; - retval = -1; -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} -#ifndef Py_NO_RETURN -#define Py_NO_RETURN -#endif -static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { - va_list vargs; - char msg[200]; -#if PY_VERSION_HEX >= 0x030A0000 || defined(HAVE_STDARG_PROTOTYPES) - va_start(vargs, fmt); -#else - va_start(vargs); -#endif - vsnprintf(msg, 200, fmt, vargs); - va_end(vargs); - Py_FatalError(msg); -} -static CYTHON_INLINE int -__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)++; - PyThread_release_lock(lock); - return result; -} -static CYTHON_INLINE int -__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)--; - PyThread_release_lock(lock); - return result; -} -static CYTHON_INLINE void -__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) -{ - int first_time; - struct __pyx_memoryview_obj *memview = memslice->memview; - if (unlikely(!memview || (PyObject *) memview == Py_None)) - return; - if (unlikely(__pyx_get_slice_count(memview) < 0)) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - first_time = __pyx_add_acquisition_count(memview) == 0; - if (unlikely(first_time)) { - if (have_gil) { - Py_INCREF((PyObject *) memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_INCREF((PyObject *) memview); - PyGILState_Release(_gilstate); - } - } -} -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, - int have_gil, int lineno) { - int last_time; - struct __pyx_memoryview_obj *memview = memslice->memview; - if (unlikely(!memview || (PyObject *) memview == Py_None)) { - memslice->memview = NULL; - return; - } - if (unlikely(__pyx_get_slice_count(memview) <= 0)) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - last_time = __pyx_sub_acquisition_count(memview) == 1; - memslice->data = NULL; - if (unlikely(last_time)) { - if (have_gil) { - Py_CLEAR(memslice->memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_CLEAR(memslice->memview); - PyGILState_Release(_gilstate); - } - } else { - memslice->memview = NULL; - } -} - -/* SetItemInt */ -static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, int is_list, - CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); - if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o)))) { - PyObject* old = PyList_GET_ITEM(o, n); - Py_INCREF(v); - PyList_SET_ITEM(o, n, v); - Py_DECREF(old); - return 1; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_ass_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return -1; - PyErr_Clear(); - } - } - return m->sq_ass_item(o, i, v); - } - } -#else -#if CYTHON_COMPILING_IN_PYPY - if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) -#else - if (is_list || PySequence_Check(o)) -#endif - { - return PySequence_SetItem(o, i, v); - } -#endif - return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); -} - -/* GetTopmostException */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * -__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) -{ - _PyErr_StackItem *exc_info = tstate->exc_info; - while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && - exc_info->previous_item != NULL) - { - exc_info = exc_info->previous_item; - } - return exc_info; -} -#endif - -/* SaveResetException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); - *type = exc_info->exc_type; - *value = exc_info->exc_value; - *tb = exc_info->exc_traceback; - #else - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - #endif - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -} -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = type; - exc_info->exc_value = value; - exc_info->exc_traceback = tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -#endif - -/* PyErrExceptionMatches */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; icurexc_type; - if (exc_type == err) return 1; - if (unlikely(!exc_type)) return 0; - if (unlikely(PyTuple_Check(err))) - return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); - return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); -} -#endif - -/* GetException */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) -#endif -{ - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_FAST_THREAD_STATE - PyObject *tmp_type, *tmp_value, *tmp_tb; - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_FAST_THREAD_STATE - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - Py_XINCREF(local_tb); - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_FAST_THREAD_STATE - #if CYTHON_USE_EXC_INFO_STACK - { - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = local_type; - exc_info->exc_value = local_value; - exc_info->exc_traceback = local_tb; - } - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -/* PyErrFetchRestore */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* RaiseException */ -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - __Pyx_PyThreadState_declare - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_FAST_THREAD_STATE - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#else - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); - Py_INCREF(tb); - PyErr_Restore(tmp_type, tmp_value, tb); - Py_XDECREF(tmp_tb); -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -/* BytesEquals */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else - if (s1 == s2) { - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - const char *ps1, *ps2; - Py_ssize_t length = PyBytes_GET_SIZE(s1); - if (length != PyBytes_GET_SIZE(s2)) - return (equals == Py_NE); - ps1 = PyBytes_AS_STRING(s1); - ps2 = PyBytes_AS_STRING(s2); - if (ps1[0] != ps2[0]) { - return (equals == Py_NE); - } else if (length == 1) { - return (equals == Py_EQ); - } else { - int result; -#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) - Py_hash_t hash1, hash2; - hash1 = ((PyBytesObject*)s1)->ob_shash; - hash2 = ((PyBytesObject*)s2)->ob_shash; - if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { - return (equals == Py_NE); - } -#endif - result = memcmp(ps1, ps2, (size_t)length); - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -#endif -} - -/* UnicodeEquals */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else -#if PY_MAJOR_VERSION < 3 - PyObject* owned_ref = NULL; -#endif - int s1_is_unicode, s2_is_unicode; - if (s1 == s2) { - goto return_eq; - } - s1_is_unicode = PyUnicode_CheckExact(s1); - s2_is_unicode = PyUnicode_CheckExact(s2); -#if PY_MAJOR_VERSION < 3 - if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { - owned_ref = PyUnicode_FromObject(s2); - if (unlikely(!owned_ref)) - return -1; - s2 = owned_ref; - s2_is_unicode = 1; - } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { - owned_ref = PyUnicode_FromObject(s1); - if (unlikely(!owned_ref)) - return -1; - s1 = owned_ref; - s1_is_unicode = 1; - } else if (((!s2_is_unicode) & (!s1_is_unicode))) { - return __Pyx_PyBytes_Equals(s1, s2, equals); - } -#endif - if (s1_is_unicode & s2_is_unicode) { - Py_ssize_t length; - int kind; - void *data1, *data2; - if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) - return -1; - length = __Pyx_PyUnicode_GET_LENGTH(s1); - if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { - goto return_ne; - } -#if CYTHON_USE_UNICODE_INTERNALS - { - Py_hash_t hash1, hash2; - #if CYTHON_PEP393_ENABLED - hash1 = ((PyASCIIObject*)s1)->hash; - hash2 = ((PyASCIIObject*)s2)->hash; - #else - hash1 = ((PyUnicodeObject*)s1)->hash; - hash2 = ((PyUnicodeObject*)s2)->hash; - #endif - if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { - goto return_ne; - } - } -#endif - kind = __Pyx_PyUnicode_KIND(s1); - if (kind != __Pyx_PyUnicode_KIND(s2)) { - goto return_ne; - } - data1 = __Pyx_PyUnicode_DATA(s1); - data2 = __Pyx_PyUnicode_DATA(s2); - if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { - goto return_ne; - } else if (length == 1) { - goto return_eq; - } else { - int result = memcmp(data1, data2, (size_t)(length * kind)); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & s2_is_unicode) { - goto return_ne; - } else if ((s2 == Py_None) & s1_is_unicode) { - goto return_ne; - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -return_eq: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ); -return_ne: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_NE); -#endif -} - -/* DivInt[Py_ssize_t] */ -static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { - Py_ssize_t q = a / b; - Py_ssize_t r = a - q*b; - q -= ((r != 0) & ((r ^ b) < 0)); - return q; -} - -/* GetAttr */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { -#if CYTHON_USE_TYPE_SLOTS -#if PY_MAJOR_VERSION >= 3 - if (likely(PyUnicode_Check(n))) -#else - if (likely(PyString_Check(n))) -#endif - return __Pyx_PyObject_GetAttrStr(o, n); -#endif - return PyObject_GetAttr(o, n); -} - -/* decode_c_string */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - Py_ssize_t length; - if (unlikely((start < 0) | (stop < 0))) { - size_t slen = strlen(cstring); - if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { - PyErr_SetString(PyExc_OverflowError, - "c-string too long to convert to Python"); - return NULL; - } - length = (Py_ssize_t) slen; - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - } - if (unlikely(stop <= start)) - return __Pyx_NewRef(__pyx_empty_unicode); - length = stop - start; - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -/* GetAttr3 */ -static PyObject *__Pyx_GetAttr3Default(PyObject *d) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - __Pyx_PyErr_Clear(); - Py_INCREF(d); - return d; -} -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { - PyObject *r = __Pyx_GetAttr(o, n); - return (likely(r)) ? r : __Pyx_GetAttr3Default(d); -} - -/* RaiseNoneIterError */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); -} - -/* SwapException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = *type; - exc_info->exc_value = *value; - exc_info->exc_traceback = *tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = *type; - tstate->exc_value = *value; - tstate->exc_traceback = *tb; - #endif - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); - PyErr_SetExcInfo(*type, *value, *tb); - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#endif - -/* Import */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_MAJOR_VERSION < 3 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_MAJOR_VERSION < 3 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -/* FastTypeChecks */ -#if CYTHON_COMPILING_IN_CPYTHON -static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { - while (a) { - a = a->tp_base; - if (a == b) - return 1; - } - return b == &PyBaseObject_Type; -} -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; - if (a == b) return 1; - mro = a->tp_mro; - if (likely(mro)) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - return __Pyx_InBases(a, b); -} -#if PY_MAJOR_VERSION == 2 -static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { - PyObject *exception, *value, *tb; - int res; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&exception, &value, &tb); - res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - } - __Pyx_ErrRestore(exception, value, tb); - return res; -} -#else -static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { - int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; - if (!res) { - res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); - } - return res; -} -#endif -static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - assert(PyExceptionClass_Check(exc_type)); - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; i= 3 - "'%.50s' object has no attribute '%U'", - tp->tp_name, attr_name); -#else - "'%.50s' object has no attribute '%.400s'", - tp->tp_name, PyString_AS_STRING(attr_name)); -#endif - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { - PyObject *descr; - PyTypeObject *tp = Py_TYPE(obj); - if (unlikely(!PyString_Check(attr_name))) { - return PyObject_GenericGetAttr(obj, attr_name); - } - assert(!tp->tp_dictoffset); - descr = _PyType_Lookup(tp, attr_name); - if (unlikely(!descr)) { - return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); - } - Py_INCREF(descr); - #if PY_MAJOR_VERSION < 3 - if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) - #endif - { - descrgetfunc f = Py_TYPE(descr)->tp_descr_get; - if (unlikely(f)) { - PyObject *res = f(descr, obj, (PyObject *)tp); - Py_DECREF(descr); - return res; - } - } - return descr; -} -#endif - -/* PyObject_GenericGetAttr */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { - if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { - return PyObject_GenericGetAttr(obj, attr_name); - } - return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); -} -#endif - -/* SetVTable */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) - goto bad; - Py_DECREF(ob); - return 0; -bad: - Py_XDECREF(ob); - return -1; -} - -/* PyObjectGetAttrStrNoError */ -static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - __Pyx_PyErr_Clear(); -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { - PyObject *result; -#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { - return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); - } -#endif - result = __Pyx_PyObject_GetAttrStr(obj, attr_name); - if (unlikely(!result)) { - __Pyx_PyObject_GetAttrStr_ClearAttributeError(); - } - return result; -} - -/* SetupReduce */ -static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { - int ret; - PyObject *name_attr; - name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name_2); - if (likely(name_attr)) { - ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); - } else { - ret = -1; - } - if (unlikely(ret < 0)) { - PyErr_Clear(); - ret = 0; - } - Py_XDECREF(name_attr); - return ret; -} -static int __Pyx_setup_reduce(PyObject* type_obj) { - int ret = 0; - PyObject *object_reduce = NULL; - PyObject *object_getstate = NULL; - PyObject *object_reduce_ex = NULL; - PyObject *reduce = NULL; - PyObject *reduce_ex = NULL; - PyObject *reduce_cython = NULL; - PyObject *setstate = NULL; - PyObject *setstate_cython = NULL; - PyObject *getstate = NULL; -#if CYTHON_USE_PYTYPE_LOOKUP - getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate); -#else - getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_getstate); - if (!getstate && PyErr_Occurred()) { - goto __PYX_BAD; - } -#endif - if (getstate) { -#if CYTHON_USE_PYTYPE_LOOKUP - object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_getstate); -#else - object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_n_s_getstate); - if (!object_getstate && PyErr_Occurred()) { - goto __PYX_BAD; - } -#endif - if (object_getstate != getstate) { - goto __PYX_GOOD; - } - } -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#else - object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#endif - reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; - if (reduce_ex == object_reduce_ex) { -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#else - object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#endif - reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; - if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { - reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); - if (likely(reduce_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (reduce == object_reduce || PyErr_Occurred()) { - goto __PYX_BAD; - } - setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); - if (!setstate) PyErr_Clear(); - if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { - setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); - if (likely(setstate_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (!setstate || PyErr_Occurred()) { - goto __PYX_BAD; - } - } - PyType_Modified((PyTypeObject*)type_obj); - } - } - goto __PYX_GOOD; -__PYX_BAD: - if (!PyErr_Occurred()) - PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); - ret = -1; -__PYX_GOOD: -#if !CYTHON_USE_PYTYPE_LOOKUP - Py_XDECREF(object_reduce); - Py_XDECREF(object_reduce_ex); - Py_XDECREF(object_getstate); - Py_XDECREF(getstate); -#endif - Py_XDECREF(reduce); - Py_XDECREF(reduce_ex); - Py_XDECREF(reduce_cython); - Py_XDECREF(setstate); - Py_XDECREF(setstate_cython); - return ret; -} - -/* TypeImport */ -#ifndef __PYX_HAVE_RT_ImportType_0_29_35 -#define __PYX_HAVE_RT_ImportType_0_29_35 -static PyTypeObject *__Pyx_ImportType_0_29_35(PyObject *module, const char *module_name, const char *class_name, - size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_0_29_35 check_size) -{ - PyObject *result = 0; - char warning[200]; - Py_ssize_t basicsize; - Py_ssize_t itemsize; -#ifdef Py_LIMITED_API - PyObject *py_basicsize; - PyObject *py_itemsize; -#endif - result = PyObject_GetAttrString(module, class_name); - if (!result) - goto bad; - if (!PyType_Check(result)) { - PyErr_Format(PyExc_TypeError, - "%.200s.%.200s is not a type object", - module_name, class_name); - goto bad; - } -#ifndef Py_LIMITED_API - basicsize = ((PyTypeObject *)result)->tp_basicsize; - itemsize = ((PyTypeObject *)result)->tp_itemsize; -#else - py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); - if (!py_basicsize) - goto bad; - basicsize = PyLong_AsSsize_t(py_basicsize); - Py_DECREF(py_basicsize); - py_basicsize = 0; - if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) - goto bad; - py_itemsize = PyObject_GetAttrString(result, "__itemsize__"); - if (!py_itemsize) - goto bad; - itemsize = PyLong_AsSsize_t(py_itemsize); - Py_DECREF(py_itemsize); - py_itemsize = 0; - if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred()) - goto bad; -#endif - if (itemsize) { - if (size % alignment) { - alignment = size % alignment; - } - if (itemsize < (Py_ssize_t)alignment) - itemsize = (Py_ssize_t)alignment; - } - if ((size_t)(basicsize + itemsize) < size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - if (check_size == __Pyx_ImportType_CheckSize_Error_0_29_35 && (size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - else if (check_size == __Pyx_ImportType_CheckSize_Warn_0_29_35 && (size_t)basicsize > size) { - PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - } - return (PyTypeObject *)result; -bad: - Py_XDECREF(result); - return NULL; -} -#endif - -/* CLineInTraceback */ -#ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_UNUSED PyThreadState *tstate, int c_line) { - PyObject *use_cline; - PyObject *ptype, *pvalue, *ptraceback; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject **cython_runtime_dict; -#endif - if (unlikely(!__pyx_cython_runtime)) { - return c_line; - } - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); -#if CYTHON_COMPILING_IN_CPYTHON - cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); - if (likely(cython_runtime_dict)) { - __PYX_PY_DICT_LOOKUP_IF_MODIFIED( - use_cline, *cython_runtime_dict, - __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) - } else -#endif - { - PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); - if (use_cline_obj) { - use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; - Py_DECREF(use_cline_obj); - } else { - PyErr_Clear(); - use_cline = NULL; - } - } - if (!use_cline) { - c_line = 0; - (void) PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); - } - else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { - c_line = 0; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - return c_line; -} -#endif - -/* CodeObjectCache */ -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/* AddTraceback */ -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -#if PY_VERSION_HEX >= 0x030b00a6 - #ifndef Py_BUILD_CORE - #define Py_BUILD_CORE 1 - #endif - #include "internal/pycore_frame.h" -#endif -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = NULL; - PyObject *py_funcname = NULL; - #if PY_MAJOR_VERSION < 3 - PyObject *py_srcfile = NULL; - py_srcfile = PyString_FromString(filename); - if (!py_srcfile) goto bad; - #endif - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - if (!py_funcname) goto bad; - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - if (!py_funcname) goto bad; - funcname = PyUnicode_AsUTF8(py_funcname); - if (!funcname) goto bad; - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - if (!py_funcname) goto bad; - #endif - } - #if PY_MAJOR_VERSION < 3 - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - #else - py_code = PyCode_NewEmpty(filename, funcname, py_line); - #endif - Py_XDECREF(py_funcname); // XDECREF since it's only set on Py3 if cline - return py_code; -bad: - Py_XDECREF(py_funcname); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_srcfile); - #endif - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject *ptype, *pvalue, *ptraceback; - if (c_line) { - c_line = __Pyx_CLineForTraceback(tstate, c_line); - } - py_code = __pyx_find_code_object(c_line ? -c_line : py_line); - if (!py_code) { - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) { - /* If the code object creation fails, then we should clear the - fetched exception references and propagate the new exception */ - Py_XDECREF(ptype); - Py_XDECREF(pvalue); - Py_XDECREF(ptraceback); - goto bad; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( - tstate, /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -/* Declarations */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - return ::std::complex< double >(x, y); - } - #else - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - return x + y*(__pyx_t_double_complex)_Complex_I; - } - #endif -#else - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - __pyx_t_double_complex z; - z.real = x; - z.imag = y; - return z; - } -#endif - -/* Arithmetic */ -#if CYTHON_CCOMPLEX -#else - static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - return (a.real == b.real) && (a.imag == b.imag); - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real + b.real; - z.imag = a.imag + b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real - b.real; - z.imag = a.imag - b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real * b.real - a.imag * b.imag; - z.imag = a.real * b.imag + a.imag * b.real; - return z; - } - #if 1 - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - if (b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); - } else if (fabs(b.real) >= fabs(b.imag)) { - if (b.real == 0 && b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); - } else { - double r = b.imag / b.real; - double s = (double)(1.0) / (b.real + b.imag * r); - return __pyx_t_double_complex_from_parts( - (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); - } - } else { - double r = b.real / b.imag; - double s = (double)(1.0) / (b.imag + b.real * r); - return __pyx_t_double_complex_from_parts( - (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); - } - } - #else - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - if (b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); - } else { - double denom = b.real * b.real + b.imag * b.imag; - return __pyx_t_double_complex_from_parts( - (a.real * b.real + a.imag * b.imag) / denom, - (a.imag * b.real - a.real * b.imag) / denom); - } - } - #endif - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { - __pyx_t_double_complex z; - z.real = -a.real; - z.imag = -a.imag; - return z; - } - static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { - return (a.real == 0) && (a.imag == 0); - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { - __pyx_t_double_complex z; - z.real = a.real; - z.imag = -a.imag; - return z; - } - #if 1 - static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { - #if !defined(HAVE_HYPOT) || defined(_MSC_VER) - return sqrt(z.real*z.real + z.imag*z.imag); - #else - return hypot(z.real, z.imag); - #endif - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - double r, lnr, theta, z_r, z_theta; - if (b.imag == 0 && b.real == (int)b.real) { - if (b.real < 0) { - double denom = a.real * a.real + a.imag * a.imag; - a.real = a.real / denom; - a.imag = -a.imag / denom; - b.real = -b.real; - } - switch ((int)b.real) { - case 0: - z.real = 1; - z.imag = 0; - return z; - case 1: - return a; - case 2: - return __Pyx_c_prod_double(a, a); - case 3: - z = __Pyx_c_prod_double(a, a); - return __Pyx_c_prod_double(z, a); - case 4: - z = __Pyx_c_prod_double(a, a); - return __Pyx_c_prod_double(z, z); - } - } - if (a.imag == 0) { - if (a.real == 0) { - return a; - } else if ((b.imag == 0) && (a.real >= 0)) { - z.real = pow(a.real, b.real); - z.imag = 0; - return z; - } else if (a.real > 0) { - r = a.real; - theta = 0; - } else { - r = -a.real; - theta = atan2(0.0, -1.0); - } - } else { - r = __Pyx_c_abs_double(a); - theta = atan2(a.imag, a.real); - } - lnr = log(r); - z_r = exp(lnr * b.real - theta * b.imag); - z_theta = theta * b.real + lnr * b.imag; - z.real = z_r * cos(z_theta); - z.imag = z_r * sin(z_theta); - return z; - } - #endif -#endif - -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - if (__Pyx_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); - if (__Pyx_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); - PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; -} -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject *obj = view->obj; - if (!obj) return; - if (PyObject_CheckBuffer(obj)) { - PyBuffer_Release(view); - return; - } - if ((0)) {} - view->obj = NULL; - Py_DECREF(obj); -} -#endif - - -/* MemviewSliceIsContig */ -static int -__pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim) -{ - int i, index, step, start; - Py_ssize_t itemsize = mvs.memview->view.itemsize; - if (order == 'F') { - step = 1; - start = 0; - } else { - step = -1; - start = ndim - 1; - } - for (i = 0; i < ndim; i++) { - index = start + step * i; - if (mvs.suboffsets[index] >= 0 || mvs.strides[index] != itemsize) - return 0; - itemsize *= mvs.shape[index]; - } - return 1; -} - -/* OverlappingSlices */ -static void -__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, - void **out_start, void **out_end, - int ndim, size_t itemsize) -{ - char *start, *end; - int i; - start = end = slice->data; - for (i = 0; i < ndim; i++) { - Py_ssize_t stride = slice->strides[i]; - Py_ssize_t extent = slice->shape[i]; - if (extent == 0) { - *out_start = *out_end = start; - return; - } else { - if (stride > 0) - end += stride * (extent - 1); - else - start += stride * (extent - 1); - } - } - *out_start = start; - *out_end = end + itemsize; -} -static int -__pyx_slices_overlap(__Pyx_memviewslice *slice1, - __Pyx_memviewslice *slice2, - int ndim, size_t itemsize) -{ - void *start1, *end1, *start2, *end2; - __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); - __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); - return (start1 < end2) && (start2 < end1); -} - -/* Capsule */ -static CYTHON_INLINE PyObject * -__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) -{ - PyObject *cobj; -#if PY_VERSION_HEX >= 0x02070000 - cobj = PyCapsule_New(p, sig, NULL); -#else - cobj = PyCObject_FromVoidPtr(p, NULL); -#endif - return cobj; -} - -/* IsLittleEndian */ -static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) -{ - union { - uint32_t u32; - uint8_t u8[4]; - } S; - S.u32 = 0x01020304; - return S.u8[0] == 4; -} - -/* BufferFormatCheck */ -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - ctx->is_valid_array = 0; - ctx->struct_alignment = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } -} -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; - } else { - count = *t++ - '0'; - while (*t >= '0' && *t <= '9') { - count *= 10; - count += *t++ - '0'; - } - } - *ts = t; - return count; -} -static int __Pyx_BufFmt_ExpectNumber(const char **ts) { - int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) - PyErr_Format(PyExc_ValueError,\ - "Does not understand character buffer dtype format string ('%c')", **ts); - return number; -} -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); -} -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case '?': return "'bool'"; - case 'c': return "'char'"; - case 'b': return "'signed char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 's': case 'p': return "a string"; - case 0: return "end"; - default: return "unparseable format string"; - } -} -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; - } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -/* These are for computing the padding at the end of the struct to align - on the first member of the struct. This will probably the same as above, - but we don't have any guarantees. - */ -typedef struct { short x; char c; } __Pyx_pad_short; -typedef struct { int x; char c; } __Pyx_pad_int; -typedef struct { long x; char c; } __Pyx_pad_long; -typedef struct { float x; char c; } __Pyx_pad_float; -typedef struct { double x; char c; } __Pyx_pad_double; -typedef struct { long double x; char c; } __Pyx_pad_longdouble; -typedef struct { void *x; char c; } __Pyx_pad_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); - case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); - case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': - return 'H'; - case 'b': case 'h': case 'i': - case 'l': case 'q': case 's': case 'p': - return 'I'; - case '?': case 'B': case 'H': case 'I': case 'L': case 'Q': - return 'U'; - case 'f': case 'd': case 'g': - return (is_complex ? 'C' : 'R'); - case 'O': - return 'O'; - case 'P': - return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; - } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } -} -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset, arraysize = 1; - if (ctx->enc_type == 0) return 0; - if (ctx->head->field->type->arraysize[0]) { - int i, ndim = 0; - if (ctx->enc_type == 's' || ctx->enc_type == 'p') { - ctx->is_valid_array = ctx->head->field->type->ndim == 1; - ndim = 1; - if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { - PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %zu", - ctx->head->field->type->arraysize[0], ctx->enc_count); - return -1; - } - } - if (!ctx->is_valid_array) { - PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", - ctx->head->field->type->ndim, ndim); - return -1; - } - for (i = 0; i < ctx->head->field->type->ndim; i++) { - arraysize *= ctx->head->field->type->arraysize[i]; - } - ctx->is_valid_array = 0; - ctx->enc_count = 1; - } - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); - } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); - } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - if (ctx->struct_alignment == 0) - ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, - ctx->is_complex); - } - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - if ((type->typegroup == 'H' || group == 'H') && type->size == size) { - } else { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - } - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; - } - ctx->fmt_offset += size; - if (arraysize) - ctx->fmt_offset += (arraysize - 1) * size; - --ctx->enc_count; - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - break; - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } - } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; -} -static PyObject * -__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) -{ - const char *ts = *tsp; - int i = 0, number, ndim; - ++ts; - if (ctx->new_count != 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot handle repeated arrays in format string"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ndim = ctx->head->field->type->ndim; - while (*ts && *ts != ')') { - switch (*ts) { - case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; - default: break; - } - number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) - return PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %d", - ctx->head->field->type->arraysize[i], number); - if (*ts != ',' && *ts != ')') - return PyErr_Format(PyExc_ValueError, - "Expected a comma in format string, got '%c'", *ts); - if (*ts == ',') ts++; - i++; - } - if (i != ndim) - return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", - ctx->head->field->type->ndim, i); - if (!*ts) { - PyErr_SetString(PyExc_ValueError, - "Unexpected end of format string, expected ')'"); - return NULL; - } - ctx->is_valid_array = 1; - ctx->new_count = 1; - *tsp = ++ts; - return Py_None; -} -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case '\r': - case '\n': - ++ts; - break; - case '<': - if (!__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - size_t struct_alignment = ctx->struct_alignment; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - ctx->enc_count = 0; - ctx->struct_alignment = 0; - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; - if (struct_alignment) ctx->struct_alignment = struct_alignment; - } - break; - case '}': - { - size_t alignment = ctx->struct_alignment; - ++ts; - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - if (alignment && ctx->fmt_offset % alignment) { - ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); - } - } - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } - CYTHON_FALLTHROUGH; - case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': case 'p': - if ((ctx->enc_type == *ts) && (got_Z == ctx->is_complex) && - (ctx->enc_packmode == ctx->new_packmode) && (!ctx->is_valid_array)) { - ctx->enc_count += ctx->new_count; - ctx->new_count = 1; - got_Z = 0; - ++ts; - break; - } - CYTHON_FALLTHROUGH; - case 's': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - case '(': - if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; - break; - default: - { - int number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - ctx->new_count = (size_t)number; - } - } - } -} - -/* TypeInfoCompare */ - static int -__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) -{ - int i; - if (!a || !b) - return 0; - if (a == b) - return 1; - if (a->size != b->size || a->typegroup != b->typegroup || - a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { - if (a->typegroup == 'H' || b->typegroup == 'H') { - return a->size == b->size; - } else { - return 0; - } - } - if (a->ndim) { - for (i = 0; i < a->ndim; i++) - if (a->arraysize[i] != b->arraysize[i]) - return 0; - } - if (a->typegroup == 'S') { - if (a->flags != b->flags) - return 0; - if (a->fields || b->fields) { - if (!(a->fields && b->fields)) - return 0; - for (i = 0; a->fields[i].type && b->fields[i].type; i++) { - __Pyx_StructField *field_a = a->fields + i; - __Pyx_StructField *field_b = b->fields + i; - if (field_a->offset != field_b->offset || - !__pyx_typeinfo_cmp(field_a->type, field_b->type)) - return 0; - } - return !a->fields[i].type && !b->fields[i].type; - } - } - return 1; -} - -/* MemviewSliceValidateAndInit */ - static int -__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) -{ - if (buf->shape[dim] <= 1) - return 1; - if (buf->strides) { - if (spec & __Pyx_MEMVIEW_CONTIG) { - if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { - if (unlikely(buf->strides[dim] != sizeof(void *))) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly contiguous " - "in dimension %d.", dim); - goto fail; - } - } else if (unlikely(buf->strides[dim] != buf->itemsize)) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - if (spec & __Pyx_MEMVIEW_FOLLOW) { - Py_ssize_t stride = buf->strides[dim]; - if (stride < 0) - stride = -stride; - if (unlikely(stride < buf->itemsize)) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - } else { - if (unlikely(spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1)) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not contiguous in " - "dimension %d", dim); - goto fail; - } else if (unlikely(spec & (__Pyx_MEMVIEW_PTR))) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not indirect in " - "dimension %d", dim); - goto fail; - } else if (unlikely(buf->suboffsets)) { - PyErr_SetString(PyExc_ValueError, - "Buffer exposes suboffsets but no strides"); - goto fail; - } - } - return 1; -fail: - return 0; -} -static int -__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) -{ - if (spec & __Pyx_MEMVIEW_DIRECT) { - if (unlikely(buf->suboffsets && buf->suboffsets[dim] >= 0)) { - PyErr_Format(PyExc_ValueError, - "Buffer not compatible with direct access " - "in dimension %d.", dim); - goto fail; - } - } - if (spec & __Pyx_MEMVIEW_PTR) { - if (unlikely(!buf->suboffsets || (buf->suboffsets[dim] < 0))) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly accessible " - "in dimension %d.", dim); - goto fail; - } - } - return 1; -fail: - return 0; -} -static int -__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) -{ - int i; - if (c_or_f_flag & __Pyx_IS_F_CONTIG) { - Py_ssize_t stride = 1; - for (i = 0; i < ndim; i++) { - if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { - PyErr_SetString(PyExc_ValueError, - "Buffer not fortran contiguous."); - goto fail; - } - stride = stride * buf->shape[i]; - } - } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { - Py_ssize_t stride = 1; - for (i = ndim - 1; i >- 1; i--) { - if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { - PyErr_SetString(PyExc_ValueError, - "Buffer not C contiguous."); - goto fail; - } - stride = stride * buf->shape[i]; - } - } - return 1; -fail: - return 0; -} -static int __Pyx_ValidateAndInit_memviewslice( - int *axes_specs, - int c_or_f_flag, - int buf_flags, - int ndim, - __Pyx_TypeInfo *dtype, - __Pyx_BufFmt_StackElem stack[], - __Pyx_memviewslice *memviewslice, - PyObject *original_obj) -{ - struct __pyx_memoryview_obj *memview, *new_memview; - __Pyx_RefNannyDeclarations - Py_buffer *buf; - int i, spec = 0, retval = -1; - __Pyx_BufFmt_Context ctx; - int from_memoryview = __pyx_memoryview_check(original_obj); - __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); - if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) - original_obj)->typeinfo)) { - memview = (struct __pyx_memoryview_obj *) original_obj; - new_memview = NULL; - } else { - memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - original_obj, buf_flags, 0, dtype); - new_memview = memview; - if (unlikely(!memview)) - goto fail; - } - buf = &memview->view; - if (unlikely(buf->ndim != ndim)) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - ndim, buf->ndim); - goto fail; - } - if (new_memview) { - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (unlikely(!__Pyx_BufFmt_CheckString(&ctx, buf->format))) goto fail; - } - if (unlikely((unsigned) buf->itemsize != dtype->size)) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " - "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", - buf->itemsize, - (buf->itemsize > 1) ? "s" : "", - dtype->name, - dtype->size, - (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->len > 0) { - for (i = 0; i < ndim; i++) { - spec = axes_specs[i]; - if (unlikely(!__pyx_check_strides(buf, i, ndim, spec))) - goto fail; - if (unlikely(!__pyx_check_suboffsets(buf, i, ndim, spec))) - goto fail; - } - if (unlikely(buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag))) - goto fail; - } - if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, - new_memview != NULL) == -1)) { - goto fail; - } - retval = 0; - goto no_fail; -fail: - Py_XDECREF(new_memview); - retval = -1; -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds___pyx_t_double_complex(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, - PyBUF_RECORDS_RO | writable_flag, 2, - &__Pyx_TypeInfo___pyx_t_double_complex, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_long(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, - PyBUF_RECORDS_RO | writable_flag, 1, - &__Pyx_TypeInfo_long, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* CIntFromPyVerify */ - #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, - PyBUF_RECORDS_RO | writable_flag, 1, - &__Pyx_TypeInfo_double, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsdsds___pyx_t_double_complex(PyObject *obj, int writable_flag) { - __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; - __Pyx_BufFmt_StackElem stack[1]; - int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; - int retcode; - if (obj == Py_None) { - result.memview = (struct __pyx_memoryview_obj *) Py_None; - return result; - } - retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, - PyBUF_RECORDS_RO | writable_flag, 3, - &__Pyx_TypeInfo___pyx_t_double_complex, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* MemviewDtypeToObject */ - static CYTHON_INLINE PyObject *__pyx_memview_get_long(const char *itemp) { - return (PyObject *) __Pyx_PyInt_From_long(*(long *) itemp); -} -static CYTHON_INLINE int __pyx_memview_set_long(const char *itemp, PyObject *obj) { - long value = __Pyx_PyInt_As_long(obj); - if ((value == (long)-1) && PyErr_Occurred()) - return 0; - *(long *) itemp = value; - return 1; -} - -/* FromPy */ - static __pyx_t_double_complex __Pyx_PyComplex_As___pyx_t_double_complex(PyObject* o) { - Py_complex cval; -#if !CYTHON_COMPILING_IN_PYPY - if (PyComplex_CheckExact(o)) - cval = ((PyComplexObject *)o)->cval; - else -#endif - cval = PyComplex_AsCComplex(o); - return __pyx_t_double_complex_from_parts( - (double)cval.real, - (double)cval.imag); -} - -/* MemviewDtypeToObject */ - static CYTHON_INLINE PyObject *__pyx_memview_get___pyx_t_double_complex(const char *itemp) { - return (PyObject *) __pyx_PyComplex_FromComplex(*(__pyx_t_double_complex *) itemp); -} -static CYTHON_INLINE int __pyx_memview_set___pyx_t_double_complex(const char *itemp, PyObject *obj) { - __pyx_t_double_complex value = __Pyx_PyComplex_As___pyx_t_double_complex(obj); - if (PyErr_Occurred()) - return 0; - *(__pyx_t_double_complex *) itemp = value; - return 1; -} - -/* Declarations */ - #if CYTHON_CCOMPLEX - #ifdef __cplusplus - static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { - return ::std::complex< float >(x, y); - } - #else - static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { - return x + y*(__pyx_t_float_complex)_Complex_I; - } - #endif -#else - static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { - __pyx_t_float_complex z; - z.real = x; - z.imag = y; - return z; - } -#endif - -/* Arithmetic */ - #if CYTHON_CCOMPLEX -#else - static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - return (a.real == b.real) && (a.imag == b.imag); - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - __pyx_t_float_complex z; - z.real = a.real + b.real; - z.imag = a.imag + b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - __pyx_t_float_complex z; - z.real = a.real - b.real; - z.imag = a.imag - b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - __pyx_t_float_complex z; - z.real = a.real * b.real - a.imag * b.imag; - z.imag = a.real * b.imag + a.imag * b.real; - return z; - } - #if 1 - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - if (b.imag == 0) { - return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); - } else if (fabsf(b.real) >= fabsf(b.imag)) { - if (b.real == 0 && b.imag == 0) { - return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); - } else { - float r = b.imag / b.real; - float s = (float)(1.0) / (b.real + b.imag * r); - return __pyx_t_float_complex_from_parts( - (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); - } - } else { - float r = b.real / b.imag; - float s = (float)(1.0) / (b.imag + b.real * r); - return __pyx_t_float_complex_from_parts( - (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); - } - } - #else - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - if (b.imag == 0) { - return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); - } else { - float denom = b.real * b.real + b.imag * b.imag; - return __pyx_t_float_complex_from_parts( - (a.real * b.real + a.imag * b.imag) / denom, - (a.imag * b.real - a.real * b.imag) / denom); - } - } - #endif - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) { - __pyx_t_float_complex z; - z.real = -a.real; - z.imag = -a.imag; - return z; - } - static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) { - return (a.real == 0) && (a.imag == 0); - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) { - __pyx_t_float_complex z; - z.real = a.real; - z.imag = -a.imag; - return z; - } - #if 1 - static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) { - #if !defined(HAVE_HYPOT) || defined(_MSC_VER) - return sqrtf(z.real*z.real + z.imag*z.imag); - #else - return hypotf(z.real, z.imag); - #endif - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - __pyx_t_float_complex z; - float r, lnr, theta, z_r, z_theta; - if (b.imag == 0 && b.real == (int)b.real) { - if (b.real < 0) { - float denom = a.real * a.real + a.imag * a.imag; - a.real = a.real / denom; - a.imag = -a.imag / denom; - b.real = -b.real; - } - switch ((int)b.real) { - case 0: - z.real = 1; - z.imag = 0; - return z; - case 1: - return a; - case 2: - return __Pyx_c_prod_float(a, a); - case 3: - z = __Pyx_c_prod_float(a, a); - return __Pyx_c_prod_float(z, a); - case 4: - z = __Pyx_c_prod_float(a, a); - return __Pyx_c_prod_float(z, z); - } - } - if (a.imag == 0) { - if (a.real == 0) { - return a; - } else if ((b.imag == 0) && (a.real >= 0)) { - z.real = powf(a.real, b.real); - z.imag = 0; - return z; - } else if (a.real > 0) { - r = a.real; - theta = 0; - } else { - r = -a.real; - theta = atan2f(0.0, -1.0); - } - } else { - r = __Pyx_c_abs_float(a); - theta = atan2f(a.imag, a.real); - } - lnr = logf(r); - z_r = expf(lnr * b.real - theta * b.imag); - z_theta = theta * b.real + lnr * b.imag; - z.real = z_r * cosf(z_theta); - z.imag = z_r * sinf(z_theta); - return z; - } - #endif -#endif - -/* MemviewSliceCopyTemplate */ - static __Pyx_memviewslice -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object) -{ - __Pyx_RefNannyDeclarations - int i; - __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; - struct __pyx_memoryview_obj *from_memview = from_mvs->memview; - Py_buffer *buf = &from_memview->view; - PyObject *shape_tuple = NULL; - PyObject *temp_int = NULL; - struct __pyx_array_obj *array_obj = NULL; - struct __pyx_memoryview_obj *memview_obj = NULL; - __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); - for (i = 0; i < ndim; i++) { - if (unlikely(from_mvs->suboffsets[i] >= 0)) { - PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " - "indirect dimensions (axis %d)", i); - goto fail; - } - } - shape_tuple = PyTuple_New(ndim); - if (unlikely(!shape_tuple)) { - goto fail; - } - __Pyx_GOTREF(shape_tuple); - for(i = 0; i < ndim; i++) { - temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); - if(unlikely(!temp_int)) { - goto fail; - } else { - PyTuple_SET_ITEM(shape_tuple, i, temp_int); - temp_int = NULL; - } - } - array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); - if (unlikely(!array_obj)) { - goto fail; - } - __Pyx_GOTREF(array_obj); - memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - (PyObject *) array_obj, contig_flag, - dtype_is_object, - from_mvs->memview->typeinfo); - if (unlikely(!memview_obj)) - goto fail; - if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) - goto fail; - if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, - dtype_is_object) < 0)) - goto fail; - goto no_fail; -fail: - __Pyx_XDECREF(new_mvs.memview); - new_mvs.memview = NULL; - new_mvs.data = NULL; -no_fail: - __Pyx_XDECREF(shape_tuple); - __Pyx_XDECREF(temp_int); - __Pyx_XDECREF(array_obj); - __Pyx_RefNannyFinishContext(); - return new_mvs; -} - -/* CIntFromPy */ - static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -/* CIntFromPy */ - static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const int neg_one = (int) -1, const_zero = (int) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const int neg_one = (int) -1, const_zero = (int) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(int) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(int) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(int), - little, !is_unsigned); - } -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -/* CIntFromPy */ - static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const char neg_one = (char) -1, const_zero = (char) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(char) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (char) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (char) 0; - case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) - case 2: - if (8 * sizeof(char) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { - return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(char) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { - return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(char) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { - return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (char) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(char) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (char) 0; - case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) - case -2: - if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(char) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(char) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { - return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(char) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { - return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); - } - } - break; - } -#endif - if (sizeof(char) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - char val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (char) -1; - } - } else { - char val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (char) -1; - val = __Pyx_PyInt_As_char(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to char"); - return (char) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to char"); - return (char) -1; -} - -/* CheckBinaryVersion */ - static int __Pyx_check_binary_version(void) { - char ctversion[5]; - int same=1, i, found_dot; - const char* rt_from_call = Py_GetVersion(); - PyOS_snprintf(ctversion, 5, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - found_dot = 0; - for (i = 0; i < 4; i++) { - if (!ctversion[i]) { - same = (rt_from_call[i] < '0' || rt_from_call[i] > '9'); - break; - } - if (rt_from_call[i] != ctversion[i]) { - same = 0; - break; - } - } - if (!same) { - char rtversion[5] = {'\0'}; - char message[200]; - for (i=0; i<4; ++i) { - if (rt_from_call[i] == '.') { - if (found_dot) break; - found_dot = 1; - } else if (rt_from_call[i] < '0' || rt_from_call[i] > '9') { - break; - } - rtversion[i] = rt_from_call[i]; - } - PyOS_snprintf(message, sizeof(message), - "compiletime version %s of module '%.100s' " - "does not match runtime version %s", - ctversion, __Pyx_MODULE_NAME, rtversion); - return PyErr_WarnEx(NULL, message, 1); - } - return 0; -} - -/* InitStrings */ - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { - while (t->p) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - if (PyObject_Hash(*t->p) == -1) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -#if !CYTHON_PEP393_ENABLED -static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -} -#else -static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (likely(PyUnicode_IS_ASCII(o))) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -} -#endif -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { - return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { - int retval; - if (unlikely(!x)) return -1; - retval = __Pyx_PyObject_IsTrue(x); - Py_DECREF(x); - return retval; -} -static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { -#if PY_MAJOR_VERSION >= 3 - if (PyLong_Check(result)) { - if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, - "__int__ returned non-int (type %.200s). " - "The ability to return an instance of a strict subclass of int " - "is deprecated, and may be removed in a future version of Python.", - Py_TYPE(result)->tp_name)) { - Py_DECREF(result); - return NULL; - } - return result; - } -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - type_name, type_name, Py_TYPE(result)->tp_name); - Py_DECREF(result); - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { -#if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; -#endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else - if (likely(PyLong_Check(x))) -#endif - return __Pyx_NewRef(x); -#if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; - #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = m->nb_long(x); - } - #else - if (likely(m && m->nb_int)) { - name = "int"; - res = m->nb_int(x); - } - #endif -#else - if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { - res = PyNumber_Int(x); - } -#endif - if (likely(res)) { -#if PY_MAJOR_VERSION < 3 - if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else - if (unlikely(!PyLong_CheckExact(res))) { -#endif - return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(b); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { - if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { - return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); -#if PY_MAJOR_VERSION < 3 - } else if (likely(PyInt_CheckExact(o))) { - return PyInt_AS_LONG(o); -#endif - } else { - Py_ssize_t ival; - PyObject *x; - x = PyNumber_Index(o); - if (!x) return -1; - ival = PyInt_AsLong(x); - Py_DECREF(x); - return ival; - } -} -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { - return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/ipie/addons/thermal/utils/ueg_kernels.pyx b/ipie/addons/thermal/utils/ueg_kernels.pyx deleted file mode 100644 index 77545707..00000000 --- a/ipie/addons/thermal/utils/ueg_kernels.pyx +++ /dev/null @@ -1,169 +0,0 @@ -import numpy - -cimport numpy - -import itertools -import math - -from ipie.legacy.estimators.utils import convolve - -DTYPE_CX = numpy.complex128 -DTYPE = numpy.float64 - - -def vq(numpy.ndarray q): - assert(q.shape[0] == 3) - cdef double q2 = numpy.dot(q, q) - if (q2 < 1e-10): - return 0.0 - else: - return 4*math.pi / q2 - -def mod_one_body(numpy.ndarray T, numpy.ndarray basis, double vol, double kfac): - """ Add a diagonal term of two-body Hamiltonian to the one-body term - Parameters - ---------- - T : float - one-body Hamiltonian (i.e. kinetic energy) - Returns - ------- - h1e_mod: float - modified one-body Hamiltonian - """ - - cdef size_t nbsf = basis.shape[0] - cdef numpy.ndarray h1e_mod = T.copy() - cdef double fac = 1.0 / (2.0 * vol) - - for (i, ki) in enumerate(basis): - for (j, kj) in enumerate(basis): - if i != j: - q = kfac * (ki - kj) - h1e_mod[i,i] = h1e_mod[i,i] - fac * vq(q) - return h1e_mod - -def coulomb_greens_function_per_qvec(numpy.ndarray kpq_i, numpy.ndarray kpq, numpy.ndarray pmq_i, numpy.ndarray pmq, double complex[:,:] G): - - cdef int nq = kpq_i.shape[0] - - cdef int idxkpq, idxpmq, i, j, iq - - cdef double complex Gkpq = 0.0 - cdef double complex Gpmq = 0.0 - - for (idxkpq,i) in zip(kpq,kpq_i): - Gkpq += G[i,idxkpq] - for (idxpmq,i) in zip(pmq,pmq_i): - Gpmq += G[i,idxpmq] - - return Gkpq, Gpmq - -def exchange_greens_function_per_qvec(long[:] kpq_i, long[:] kpq, long[:] pmq_i, long[:] pmq, double complex[:,:] G): - - cdef int nkpq = kpq_i.shape[0] - cdef int npmq = pmq_i.shape[0] - - cdef double complex Gprod = 0.0 - - cdef int idxkpq, idxpmq, i, j - - for inkpq in range(nkpq): - idxkpq = kpq[inkpq] - i = kpq_i[inkpq] - for jnpmq in range(npmq): - idxpmq = pmq[jnpmq] - j = pmq_i[jnpmq] - Gprod += G[j,idxkpq]*G[i,idxpmq] - - return Gprod - -def exchange_greens_function_fft (long nocc, long nbsf, - long[:] mesh, long[:] qmesh, long[:] gmap, long[:] qmap, - double complex[:,:] CTdagger, double complex[:,:] Ghalf): - - assert (mesh.shape[0] == 3) - assert (qmesh.shape[0] == 3) - assert (Ghalf.shape[0] == nocc) - assert (Ghalf.shape[1] == nbsf) - assert (CTdagger.shape[0] == nocc) - assert (CTdagger.shape[1] == nbsf) - - cdef long ngrid = numpy.prod(mesh) - cdef long nqgrid = numpy.prod(qmesh) - - cdef long nq = qmap.shape[0] - cdef numpy.ndarray Gprod = numpy.zeros(nq, dtype=DTYPE_CX) - - cdef numpy.ndarray Gh_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - cdef numpy.ndarray Gh_j = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_i = numpy.zeros(nbsf, dtype=DTYPE_CX) - cdef numpy.ndarray Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - cdef numpy.ndarray CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - cdef numpy.ndarray lQ_ji = numpy.zeros(nqgrid, dtype=DTYPE_CX) - cdef numpy.ndarray lQ_ij = numpy.zeros(nqgrid, dtype=DTYPE_CX) - - for i in range(nocc): - for j in range(nocc): - Gh_i = numpy.flip(numpy.asarray(Ghalf[i,:])) - CTdagger_j = numpy.asarray(CTdagger[j,:]) - - Gh_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - CTdagger_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - Gh_i_cube[gmap] = Gh_i - CTdagger_j_cube[gmap] = CTdagger_j - - lQ_ji = numpy.flip(convolve(CTdagger_j_cube, Gh_i_cube, mesh))[qmap] - - Gh_j = numpy.asarray(Ghalf[j,:]) - CTdagger_i = numpy.flip(numpy.asarray(CTdagger[i,:])) - - Gh_j_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - CTdagger_i_cube = numpy.zeros(ngrid, dtype=DTYPE_CX) - - Gh_j_cube[gmap] = Gh_j - CTdagger_i_cube[gmap] = CTdagger_i - - lQ_ij = numpy.flip(convolve(Gh_j_cube, CTdagger_i_cube, mesh))[qmap] - - Gprod += lQ_ji*lQ_ij - - return Gprod - -def build_J_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, - list kpq, list pmq_i, list pmq, - double complex[:,:] Gkpq, double complex[:,:] Gpmq): - - cdef numpy.ndarray J = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) - cdef int i, j - for iq in range(nq): - for i, j in zip(pmq_i[iq], pmq[iq]): - J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq]) - for i, j in zip(kpq_i[iq], kpq[iq]): - J[0,j,i] += (1.0/(2.0*vol)) * vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq]) - - J[1] = J[0] - - return J - -def build_K_opt(long nq, double[:] vqvec, double vol, long nbsf, list kpq_i, - list kpq, list pmq_i, list pmq, - double complex[:,:,:] G): - - cdef numpy.ndarray K = numpy.zeros([2, nbsf, nbsf], dtype=DTYPE_CX) - cdef int iq, s, idxjmq, idxkpq, idxk, idxjpq, idxj, idxpmq, idxp - - for s in range(2): - for iq in range(nq): - for (idxjmq,idxj) in zip(pmq[iq],pmq_i[iq]): - for (idxkpq,idxk) in zip(kpq[iq],kpq_i[iq]): - K[s, idxj, idxkpq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s, idxjmq, idxk] - for (idxjpq,idxj) in zip(kpq[iq],kpq_i[iq]): - for (idxpmq,idxp) in zip(pmq[iq],pmq_i[iq]): - K[s, idxj, idxpmq] += - (1.0/(2.0*vol)) * vqvec[iq] * G[s][idxjpq, idxp] - return K diff --git a/ipie/addons/thermal/walkers/tests/test_population_control.py b/ipie/addons/thermal/walkers/tests/test_population_control.py index 9f7c29ed..9b3adc38 100644 --- a/ipie/addons/thermal/walkers/tests/test_population_control.py +++ b/ipie/addons/thermal/walkers/tests/test_population_control.py @@ -2,21 +2,19 @@ import pytest from typing import Union -from ipie.config import MPI -from ipie.utils.mpi import MPIHandler -from ipie.walkers.pop_controller import PopController - -from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers_mpi -from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers_mpi -from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers - try: - from ipie.legacy.estimators.ueg import fock_ueg + from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers_mpi + from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers _no_cython = False except ModuleNotFoundError: _no_cython = True +from ipie.config import MPI +from ipie.utils.mpi import MPIHandler +from ipie.walkers.pop_controller import PopController +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers_mpi + comm = MPI.COMM_WORLD @pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") diff --git a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py index 7343a46f..fb82bb11 100644 --- a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py @@ -2,24 +2,22 @@ import pytest from typing import Union +try: + from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers + from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + from ipie.config import MPI from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G +from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers -from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers - -try: - from ipie.legacy.estimators.ueg import fock_ueg - _no_cython = False - -except ModuleNotFoundError: - _no_cython = True - comm = MPI.COMM_WORLD @pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") From 1ee949dd35dea47d04299349e37c1678ec34c442 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 17 Mar 2024 17:50:58 -0400 Subject: [PATCH 68/84] Skip `pytest` for tests that invoke `fock_ueg` imports --- .../thermal/propagation/tests/ueg/test_prop_ueg.py | 2 +- ipie/addons/thermal/walkers/tests/__init__.py | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 ipie/addons/thermal/walkers/tests/__init__.py diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index d759cb5d..73428f5f 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -4,6 +4,7 @@ try: from ipie.addons.thermal.utils.legacy_testing import build_legacy_ueg_test_case_handlers from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers + from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg _no_cython = False except ModuleNotFoundError: @@ -15,7 +16,6 @@ from ipie.addons.thermal.utils.testing import build_ueg_test_case_handlers from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.legacy.estimators.ueg import local_energy_ueg as legacy_local_energy_ueg comm = MPI.COMM_WORLD diff --git a/ipie/addons/thermal/walkers/tests/__init__.py b/ipie/addons/thermal/walkers/tests/__init__.py new file mode 100644 index 00000000..381108b3 --- /dev/null +++ b/ipie/addons/thermal/walkers/tests/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + From 335b04ea9fd92d5879d0c5c2a519ef7887baea2f Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 17 Mar 2024 19:17:11 -0400 Subject: [PATCH 69/84] Add tests. Fix `pylint` warnings. --- ipie/addons/thermal/estimators/energy.py | 9 +-- ipie/addons/thermal/estimators/generic.py | 1 - .../thermal/estimators/particle_number.py | 24 +++++-- .../estimators/tests/test_estimators.py | 70 +++++++++++++++++-- .../estimators/tests/test_generic_complex.py | 6 ++ ipie/addons/thermal/estimators/thermal.py | 18 +---- ipie/addons/thermal/propagation/force_bias.py | 1 - ipie/addons/thermal/propagation/operations.py | 3 - .../thermal/propagation/phaseless_base.py | 2 +- .../thermal/propagation/phaseless_generic.py | 8 --- ipie/addons/thermal/qmc/thermal_afqmc.py | 2 - ipie/addons/thermal/trial/chem_pot.py | 3 +- ipie/addons/thermal/trial/mean_field.py | 3 +- ipie/addons/thermal/trial/one_body.py | 5 +- ipie/addons/thermal/walkers/uhf_walkers.py | 6 +- 15 files changed, 105 insertions(+), 56 deletions(-) diff --git a/ipie/addons/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py index 9321ef28..e9164f9f 100644 --- a/ipie/addons/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -15,7 +15,7 @@ # Author: Fionn Malone # -import numpy +from typing import Union from ipie.utils.backend import arraylib as xp from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol @@ -27,13 +27,13 @@ def local_energy( - hamiltonian: GenericRealChol, + hamiltonian: Union[GenericRealChol, GenericComplexChol], walkers: UHFThermalWalkers): - energies = numpy.zeros((walkers.nwalkers, 3), dtype=numpy.complex128) + energies = xp.zeros((walkers.nwalkers, 3), dtype=xp.complex128) for iw in range(walkers.nwalkers): walkers.calc_greens_function(iw) # In-place update of GF. - P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) + P = one_rdm_from_G(xp.array([walkers.Ga[iw], walkers.Gb[iw]])) energy = local_energy_generic_cholesky(hamiltonian, P) for i in range(3): @@ -41,6 +41,7 @@ def local_energy( return energies + class ThermalEnergyEstimator(EstimatorBase): def __init__(self, hamiltonian=None, trial=None, filename=None): super().__init__() diff --git a/ipie/addons/thermal/estimators/generic.py b/ipie/addons/thermal/estimators/generic.py index 45c99c92..bd69abc2 100644 --- a/ipie/addons/thermal/estimators/generic.py +++ b/ipie/addons/thermal/estimators/generic.py @@ -1,6 +1,5 @@ import plum import numpy -from ipie.utils.misc import is_cupy from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol diff --git a/ipie/addons/thermal/estimators/particle_number.py b/ipie/addons/thermal/estimators/particle_number.py index 83343397..d98727ff 100644 --- a/ipie/addons/thermal/estimators/particle_number.py +++ b/ipie/addons/thermal/estimators/particle_number.py @@ -1,9 +1,23 @@ -from ipie.estimators.estimator_base import EstimatorBase -import numpy - from ipie.utils.backend import arraylib as xp from ipie.estimators.estimator_base import EstimatorBase -from ipie.addons.thermal.estimators.thermal import particle_number, one_rdm_from_G +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G + + +def particle_number(dmat): + """Compute average particle number from the thermal 1RDM. + + Parameters + ---------- + dmat : :class:`numpy.ndarray` + Thermal 1RDM. + + Returns + ------- + nav : float + Average particle number. + """ + nav = dmat[0].trace() + dmat[1].trace() + return nav class ThermalNumberEstimator(EstimatorBase): @@ -35,7 +49,7 @@ def compute_estimator(self, walkers, hamiltonian, trial): for iw in range(walkers.nwalkers): walkers.calc_greens_function(iw) nav_iw = particle_number(one_rdm_from_G( - numpy.array([walkers.Ga[iw], walkers.Gb[iw]]))) + xp.array([walkers.Ga[iw], walkers.Gb[iw]]))) self._data["NavNumer"] += walkers.weight[iw] * nav_iw self._data["NavDenom"] = sum(walkers.weight) diff --git a/ipie/addons/thermal/estimators/tests/test_estimators.py b/ipie/addons/thermal/estimators/tests/test_estimators.py index 2c43c59e..849acf25 100644 --- a/ipie/addons/thermal/estimators/tests/test_estimators.py +++ b/ipie/addons/thermal/estimators/tests/test_estimators.py @@ -4,7 +4,11 @@ from typing import Tuple, Union from ipie.config import MPI +from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol + from ipie.addons.thermal.estimators.energy import ThermalEnergyEstimator +from ipie.addons.thermal.estimators.particle_number import ThermalNumberEstimator from ipie.addons.thermal.estimators.handler import ThermalEstimatorHandler from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers @@ -29,7 +33,7 @@ lowrank = False verbose = True -complex_integrals = True +complex_integrals = False debug = True mf_trial = True propagate = False @@ -66,21 +70,74 @@ def test_energy_estimator(): hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] - estim = ThermalEnergyEstimator(hamiltonian=hamiltonian, trial=trial) + assert isinstance(hamiltonian, GenericRealChol) + chol = hamiltonian.chol + + # GenericRealChol. + re_estim = ThermalEnergyEstimator(hamiltonian=hamiltonian, trial=trial) + re_estim.compute_estimator(walkers, hamiltonian, trial) + assert len(re_estim.names) == 5 + tmp = re_estim.data.copy() + re_estim.post_reduce_hook(tmp) + assert re_estim.print_to_stdout + assert re_estim.ascii_filename == None + assert re_estim.shape == (5,) + header = re_estim.header_to_text + data_to_text = re_estim.data_to_text(tmp) + assert len(data_to_text.split()) == 5 + + # GenericComplexChol. + cx_chol = numpy.array(chol, dtype=numpy.complex128) + cx_hamiltonian = HamGeneric( + numpy.array(hamiltonian.H1, dtype=numpy.complex128), cx_chol, + hamiltonian.ecore, verbose=False) + + assert isinstance(cx_hamiltonian, GenericComplexChol) + + cx_estim = ThermalEnergyEstimator(hamiltonian=cx_hamiltonian, trial=trial) + cx_estim.compute_estimator(walkers, cx_hamiltonian, trial) + assert len(cx_estim.names) == 5 + tmp = cx_estim.data.copy() + cx_estim.post_reduce_hook(tmp) + assert cx_estim.print_to_stdout + assert cx_estim.ascii_filename == None + assert cx_estim.shape == (5,) + header = cx_estim.header_to_text + data_to_text = cx_estim.data_to_text(tmp) + assert len(data_to_text.split()) == 5 + + numpy.testing.assert_allclose(re_estim.data, cx_estim.data) + + +@pytest.mark.unit +def test_number_estimator(): + # Test. + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + options['complex_integrals'] = True + objs = build_generic_test_case_handlers(options, seed, debug, verbose) + trial = objs['trial'] + hamiltonian = objs['hamiltonian'] + walkers = objs['walkers'] + + estim = ThermalNumberEstimator(hamiltonian=hamiltonian, trial=trial) estim.compute_estimator(walkers, hamiltonian, trial) - assert len(estim.names) == 5 + assert len(estim.names) == 3 tmp = estim.data.copy() estim.post_reduce_hook(tmp) assert estim.print_to_stdout assert estim.ascii_filename == None - assert estim.shape == (5,) + assert estim.shape == (3,) header = estim.header_to_text data_to_text = estim.data_to_text(tmp) - assert len(data_to_text.split()) == 5 - + assert len(data_to_text.split()) == 3 + @pytest.mark.unit def test_estimator_handler(): + options['complex_integrals'] = True + with tempfile.NamedTemporaryFile() as tmp1, tempfile.NamedTemporaryFile() as tmp2: # Test. print('\n----------------------------') @@ -111,6 +168,7 @@ def test_estimator_handler(): if __name__ == "__main__": test_energy_estimator() + test_number_estimator() test_estimator_handler() diff --git a/ipie/addons/thermal/estimators/tests/test_generic_complex.py b/ipie/addons/thermal/estimators/tests/test_generic_complex.py index 50d23a53..a33b3744 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/addons/thermal/estimators/tests/test_generic_complex.py @@ -3,6 +3,7 @@ from typing import Tuple, Union from ipie.hamiltonians.generic import Generic as HamGeneric +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G @@ -65,12 +66,16 @@ def test_local_energy_vs_real(): trial = objs['trial'] walkers = objs['walkers'] hamiltonian = objs['hamiltonian'] + + assert isinstance(hamiltonian, GenericRealChol) chol = hamiltonian.chol cx_chol = numpy.array(chol, dtype=numpy.complex128) cx_hamiltonian = HamGeneric( numpy.array(hamiltonian.H1, dtype=numpy.complex128), cx_chol, hamiltonian.ecore, verbose=False) + + assert isinstance(cx_hamiltonian, GenericComplexChol) for iw in range(walkers.nwalkers): P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) @@ -91,6 +96,7 @@ def test_local_energy_vs_eri(): trial = objs['trial'] walkers = objs['walkers'] hamiltonian = objs['hamiltonian'] + assert isinstance(hamiltonian, GenericComplexChol) eri = objs['eri'].reshape(nbasis, nbasis, nbasis, nbasis) chol = hamiltonian.chol.copy() diff --git a/ipie/addons/thermal/estimators/thermal.py b/ipie/addons/thermal/estimators/thermal.py index 89bda7d2..90312880 100644 --- a/ipie/addons/thermal/estimators/thermal.py +++ b/ipie/addons/thermal/estimators/thermal.py @@ -71,27 +71,11 @@ def one_rdm_stable(BT, num_slices): G.append(numpy.dot(numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T))) return one_rdm_from_G(numpy.array(G)) -def particle_number(dmat): - """Compute average particle number from the thermal 1RDM. - - Parameters - ---------- - dmat : :class:`numpy.ndarray` - Thermal 1RDM. - - Returns - ------- - nav : float - Average particle number. - """ - nav = dmat[0].trace() + dmat[1].trace() - return nav - def entropy(beta, mu, H): """Compute the entropy. """ assert numpy.linalg.norm(H[0] - H[1]) < 1e-12 - eigs, eigv = numpy.linalg.eigh(H[0]) + eigs, _ = numpy.linalg.eigh(H[0]) p_i = fermi_factor(eigs, beta, mu) S = -2.0 * sum(p * numpy.log(p) + (1 - p) * numpy.log(1 - p) for p in p_i) # muN = mu * numpy.eye(H[0].shape[-1], dtype=H[0].dtype) diff --git a/ipie/addons/thermal/propagation/force_bias.py b/ipie/addons/thermal/propagation/force_bias.py index af8a0c00..6f7a4917 100644 --- a/ipie/addons/thermal/propagation/force_bias.py +++ b/ipie/addons/thermal/propagation/force_bias.py @@ -4,7 +4,6 @@ from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.utils.backend import arraylib as xp -from ipie.utils.backend import synchronize @plum.dispatch def construct_force_bias(hamiltonian: GenericRealChol, walkers): diff --git a/ipie/addons/thermal/propagation/operations.py b/ipie/addons/thermal/propagation/operations.py index 3b13c8c0..cca29dbe 100644 --- a/ipie/addons/thermal/propagation/operations.py +++ b/ipie/addons/thermal/propagation/operations.py @@ -1,7 +1,4 @@ -from ipie.config import config from ipie.utils.backend import arraylib as xp -from ipie.utils.backend import synchronize -from ipie.utils.misc import is_cupy def apply_exponential(VHS, exp_nmax): """Apply exponential propagator of the HS transformation diff --git a/ipie/addons/thermal/propagation/phaseless_base.py b/ipie/addons/thermal/propagation/phaseless_base.py index 2508d2e5..3bf2f451 100644 --- a/ipie/addons/thermal/propagation/phaseless_base.py +++ b/ipie/addons/thermal/propagation/phaseless_base.py @@ -278,7 +278,7 @@ def update_weight_legacy(self, walkers, iw, G, cfb, cmf, eshift): hybrid_energy = cmath.log(oratio) + _cfb + _cmf Q = cmath.exp(hybrid_energy) expQ = self.mf_const_fac * Q - (magn, phase) = cmath.polar(expQ) + (magn, _) = cmath.polar(expQ) if not math.isinf(magn): # Determine cosine phase from Arg(det(1+A'(x))/det(1+A(x))). diff --git a/ipie/addons/thermal/propagation/phaseless_generic.py b/ipie/addons/thermal/propagation/phaseless_generic.py index 994c0bc6..45895bc3 100644 --- a/ipie/addons/thermal/propagation/phaseless_generic.py +++ b/ipie/addons/thermal/propagation/phaseless_generic.py @@ -1,16 +1,8 @@ -import time -import math import plum -import numpy -from ipie.config import config from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol -from ipie.hamiltonians.generic_base import GenericBase -from ipie.addons.thermal.propagation.operations import apply_exponential from ipie.addons.thermal.propagation.phaseless_base import PhaselessBase from ipie.utils.backend import arraylib as xp -from ipie.utils.backend import synchronize -from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers class PhaselessGeneric(PhaselessBase): diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 9808a2e8..5e69f55c 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -20,7 +20,6 @@ from ipie.walkers.pop_controller import PopController from ipie.walkers.base_walkers import WalkerAccumulator from ipie.qmc.afqmc import AFQMC -from ipie.qmc.utils import set_rng_seed class ThermalAFQMC(AFQMC): @@ -199,7 +198,6 @@ def run(self, self.tsetup += time.time() - ft_setup # Propagate. - nwalkers = self.walkers.nwalkers total_steps = self.params.num_steps_per_block * self.params.num_blocks # TODO: This magic value of 2 is pretty much never controlled on input. # Moreover I'm not convinced having a two stage shift update actually diff --git a/ipie/addons/thermal/trial/chem_pot.py b/ipie/addons/thermal/trial/chem_pot.py index 37705edf..8f496297 100644 --- a/ipie/addons/thermal/trial/chem_pot.py +++ b/ipie/addons/thermal/trial/chem_pot.py @@ -1,6 +1,7 @@ import numpy -from ipie.addons.thermal.estimators.thermal import one_rdm_stable, particle_number +from ipie.addons.thermal.estimators.particle_number import particle_number +from ipie.addons.thermal.estimators.thermal import one_rdm_stable from ipie.utils.io import format_fixed_width_floats, format_fixed_width_strings diff --git a/ipie/addons/thermal/trial/mean_field.py b/ipie/addons/thermal/trial/mean_field.py index 86fc508f..d6e02f0b 100644 --- a/ipie/addons/thermal/trial/mean_field.py +++ b/ipie/addons/thermal/trial/mean_field.py @@ -2,8 +2,9 @@ import scipy.linalg from ipie.addons.thermal.estimators.generic import fock_generic +from ipie.addons.thermal.estimators.particle_number import particle_number +from ipie.addons.thermal.estimators.thermal import one_rdm_stable from ipie.addons.thermal.estimators.greens_function import greens_function -from ipie.addons.thermal.estimators.thermal import one_rdm_stable, particle_number from ipie.addons.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.addons.thermal.trial.one_body import OneBody diff --git a/ipie/addons/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py index ba30f2ec..8760db6d 100644 --- a/ipie/addons/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -1,9 +1,9 @@ - import numpy import scipy.linalg +from ipie.addons.thermal.estimators.particle_number import particle_number +from ipie.addons.thermal.estimators.thermal import one_rdm_stable from ipie.addons.thermal.estimators.greens_function import greens_function -from ipie.addons.thermal.estimators.thermal import one_rdm_stable, particle_number from ipie.addons.thermal.trial.chem_pot import compute_rho, find_chemical_potential from ipie.utils.misc import update_stack @@ -59,7 +59,6 @@ def __init__(self, hamiltonian, nelec, beta, dt, options={}, if verbose: print("# Estimating stack size from BT.") - eigs, _ = scipy.linalg.eigh(self.dmat[0]) self.cond = numpy.linalg.cond(self.dmat[0]) # We will end up multiplying many BTs together. Can roughly determine # safe stack size from condition number of BT as the condition number of diff --git a/ipie/addons/thermal/walkers/uhf_walkers.py b/ipie/addons/thermal/walkers/uhf_walkers.py index 51932fcb..a05c1424 100644 --- a/ipie/addons/thermal/walkers/uhf_walkers.py +++ b/ipie/addons/thermal/walkers/uhf_walkers.py @@ -1,10 +1,11 @@ import numpy import scipy.linalg -from ipie.addons.thermal.estimators.thermal import one_rdm_from_G, particle_number +from ipie.addons.thermal.estimators.particle_number import particle_number +from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.addons.thermal.estimators.greens_function import greens_function_qr_strat from ipie.addons.thermal.walkers.stack import PropagatorStack -from ipie.utils.misc import get_numeric_names, update_stack +from ipie.utils.misc import update_stack from ipie.walkers.base_walkers import BaseWalkers from ipie.addons.thermal.trial.one_body import OneBody @@ -119,7 +120,6 @@ def __init__( nav = particle_number(P) print(f"# Trial electron number for {iw}-th walker: {nav}") - #self.buff_names, self.buff_size = get_numeric_names(self.__dict__) self.buff_names += ["Ga", "Gb"] self.buff_size = round(self.set_buff_size_single_walker() / float(self.nwalkers)) self.walker_buffer = numpy.zeros(self.buff_size, dtype=numpy.complex128) From 2dadcbe767369464691e959e12aa6c41c36da568 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 17 Mar 2024 19:26:34 -0400 Subject: [PATCH 70/84] Fix `pylint` `dangerous-default-value` in setting default argument `options={}` --- ipie/addons/thermal/trial/mean_field.py | 5 ++++- ipie/addons/thermal/trial/one_body.py | 5 ++++- ipie/addons/thermal/trial/utils.py | 5 ++++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/ipie/addons/thermal/trial/mean_field.py b/ipie/addons/thermal/trial/mean_field.py index d6e02f0b..6983db2c 100644 --- a/ipie/addons/thermal/trial/mean_field.py +++ b/ipie/addons/thermal/trial/mean_field.py @@ -9,7 +9,10 @@ from ipie.addons.thermal.trial.one_body import OneBody class MeanField(OneBody): - def __init__(self, hamiltonian, nelec, beta, dt, options={}, alt_convention=False, H1=None, verbose=False): + def __init__(self, hamiltonian, nelec, beta, dt, options=None, alt_convention=False, H1=None, verbose=False): + if options is None: + options = {} + OneBody.__init__(self, hamiltonian, nelec, beta, dt, options=options, alt_convention=alt_convention, H1=H1, verbose=verbose) if verbose: diff --git a/ipie/addons/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py index 8760db6d..1896e334 100644 --- a/ipie/addons/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -9,8 +9,11 @@ class OneBody(object): - def __init__(self, hamiltonian, nelec, beta, dt, options={}, + def __init__(self, hamiltonian, nelec, beta, dt, options=None, alt_convention=False, H1=None, verbose=False): + if options is None: + options = {} + self.name = "thermal" self.compute_trial_energy = False self.verbose = verbose diff --git a/ipie/addons/thermal/trial/utils.py b/ipie/addons/thermal/trial/utils.py index 4ee3b6b6..9b8f0406 100644 --- a/ipie/addons/thermal/trial/utils.py +++ b/ipie/addons/thermal/trial/utils.py @@ -2,7 +2,7 @@ from ipie.addons.thermal.trial.one_body import OneBody -def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, +def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options=None, comm=None, verbose=False): """Wrapper to select trial wavefunction class. @@ -14,6 +14,9 @@ def get_trial_density_matrix(hamiltonian, nelec, beta, dt, options={}, trial : class or None Trial density matrix class. """ + if options is None: + options = {} + trial_type = options.get("name", "one_body") alt_convention = options.get("alt_convention", False) if comm is None or comm.rank == 0: From 3a78d3b93f307d199336b9029e5b1761f4a0bb90 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Mon, 18 Mar 2024 18:01:57 -0400 Subject: [PATCH 71/84] Add reference data. --- .../generic/generic_integrals.h5 | Bin 0 -> 30056 bytes .../reference_data/generic/generic_ref.json | 1 + .../thermal/reference_data/ueg/input.json | 32 ++++++++++++++++++ .../reference_data/ueg/input_1walker.json | 32 ++++++++++++++++++ .../reference_data/ueg/input_nompi.json | 32 ++++++++++++++++++ .../thermal/reference_data/ueg/reference.json | 1 + .../reference_data/ueg/reference_1walker.json | 1 + .../reference_data/ueg/reference_nompi.json | 1 + 8 files changed, 100 insertions(+) create mode 100644 ipie/addons/thermal/reference_data/generic/generic_integrals.h5 create mode 100644 ipie/addons/thermal/reference_data/generic/generic_ref.json create mode 100644 ipie/addons/thermal/reference_data/ueg/input.json create mode 100644 ipie/addons/thermal/reference_data/ueg/input_1walker.json create mode 100644 ipie/addons/thermal/reference_data/ueg/input_nompi.json create mode 100644 ipie/addons/thermal/reference_data/ueg/reference.json create mode 100644 ipie/addons/thermal/reference_data/ueg/reference_1walker.json create mode 100644 ipie/addons/thermal/reference_data/ueg/reference_nompi.json diff --git a/ipie/addons/thermal/reference_data/generic/generic_integrals.h5 b/ipie/addons/thermal/reference_data/generic/generic_integrals.h5 new file mode 100644 index 0000000000000000000000000000000000000000..cd0fa383c3589e3ac847d0d975ef0f1c73bbf214 GIT binary patch literal 30056 zcmeF32{4!K|L<+dQVPiu*_TRolI6baOCf7fWXTrF79|Olr9z<;?Z_TNWV}v_FmN=gKx}P(1{%6jA&YYPuXU?4S{ANPw)%*Q=f4+A;&-is+PfKSj0~Z6uKmX9t zQP5CqC*J+{n|1OZS3mSU|9<@MkK2*&P?B#W$+sC)=p9OmfBr{7!9jjMGs*vtpJ#5W ztxd7Wuel8^yBBB=#1;zj9E%nCb|MQv5 ze1HPot{R0LBZb^LHHxrl<9q-4aVjbVq$6J`)Rg3>Q}B_Wi9Vl#;=;f0{2zI1W^_c0 zl7jlbJ|!+}`p;wh`?`;${m(z|-`DkjZ2O=8tp9s|^uNC=beWVJ!~gS-09oxn-qru; z`~TPPjE@ohQfhAGFG;>}{ck_~-~7>k?*m-~vO%$NasR8YBRleUu75A=-y-+_edqt_ zw*{J~_HyHYVaZ#@Xe+yqF#g*5-Ii}f00tyavC7_q)BUA-4b6c-tl=4mNVJ1eQFl{{ z0yV)S&C?C_n?&K@sY=!W3Pz9|MZ4%fK8yd$dEU^vOSgxz>hjgCR};EAVV>EWTu!kP zVBP6CN zZztKSoXo>da{5Aw0xC3Vs=}@EUyn3&LiNjcyFwL9K-{gfmptneVKm7d>mc(ULmt{l zKT2e;Kr&Ad$>}`nzWaJAO_hbPN2)nuMQ{j&`^*3ijba5Nk403FC#L~ zzno!`n@avV0j$VF^atcOW*Y6LMD8_7dVWauh$4GkAoJWOId!B54$_O3Iod7hBD#lk za`!LfUO}X1ACh~U>}5yh`FE#PayK1vM+0)#QSyGilDqF9_ZlEQ8<2i{$X*zk$B^V? zlXq4@-fu2>hkoS!u#vmZkbC{>`5NixG1<$A%=2G484d+ucv= zZ!n6NbKAr1pW)02h?C!SpW5T<2%rEBI|6>k!n2IEm{)&mahVp> ztB}k?L2@3~nfE&0e+TMM&>YjaZwF)d{0^7a0pMIv;>*AH#bEDh&N0^CTYza{HEnms zJU*20z|MSc8^#)f{5&9g^*NzDK_tidz0qvzhdR`>`oC!v~<}Fbko@B&H`fQ(Ao>>m4 zco|!KspO!?1p8O%6&9f8i$yBOF5>#+?keP7sibGiHRNZPKkB73jq(`pMjXDvMkVW# z5}>vi>yv#-6jInZFho?BV@c%w6qCCTlY7mQp6ybQpM0_x-4x1m{|Dmy)VNVjQ&|Kk zFu5F!FPniRd53A_{j8F^pS*|m@?k}udrFa?DnHbVA_L{2&_bN60WS;ps}+D#;%iOJ z&K__o-9O2sRvW1LfB51P(2hG_jTljSu@!tAZ!s$Oo53|hoQ6#YpJ8kgn^&uBDlqG) z-8Ub_LcHv=N2mNiIo1|0(pN|I6qn0DoCmfqqt9wR1MT#|eJ2adf!OWns-z`x$b8NH zwJ=}+*cpdsS!XkGQRab@HLr$nc4dP@sb_~Vb9Py!-+u=1p~Nc+`=nQ$m5xRab?yln^MH-5hmSZ@rrexd-Q3Cc=iCxyOQ8Rh6vPY zRB|6P-~$XtSih9-PGk9~Mhz`85R)xoMFrP=6yV!!H`Hq~2j$UF zwE|bq)PPar*03SLFoo&rNya}(`8poI34B0c|Z zKz=yMUQ9<(oKVSjZ$oml@cc=JwFC*mHj`VYb z>@`B>IY4si>bk}Htw%sem`nj+h^{P6L@;q%o zoM%dNa}K+{g6q*sFV7iYgPY%ux@!x`gFeYT_&f9vurGda?&+7qus0jG^hlKfdJMKY zw6;4z;>yv?6Ey4iP~HGV*r!j}$tTZBByw^5MdI^Qvsn+Z;d;b*AQko|#iAT&;JV7X zcWR_){-;pKvS`@K;M>FE<9RJ0G5`IBO3QweR*wYimNP za}k3Jt9+ojYJz%~0wpy4Yq96vxj{^v>}5&jaUwZG(NaCi`oqA?^l-Xu%?)^Oj3#2U z-xYXKddHf%s6EImVc|`UKL|Ur*E32OIY24bFw<4TAGitWCxq;^^&HCMY=Sr{<-e;6 z=;pvlIyWWGEjM8&|F*%~bY_6fB}Y5W(j1=JRafJgbO89rtHD1jY|w=CoJIQaAbSOo zdF1F3$0>J-+2zJCILi0E=zdQu%&#cB+AQn={<<-53x8z-c~uXYrUyuY7;-N+(sKss z$A;|XAc*p4lbr8Tr-~}q+5tRkZ#|vi3v;bw_V#G&f~_fEC#6cn;g)=~yA!#W5a~Ib z^ixXq>L&ACBRTs|o^_GER||xy{tPGks)ERV?a7*ADG*NHk6<6#{VTaw7wNf;^uyqe zdM%tldGf0f$IjDVcRjoS%rU-sWFVvqa>+ZS`iAbujNCn&+-rpNY)tymBYW9>LV4^M z5Qmr6`{C1)OHi?7c;KtkNjRgnBVeje9cZ_z?EgE(2XiDYDsM^`10&Re!3@VXL6yq7 zQlDZPxRY=5$H!HxSS?fd;M~jz-m{J2o(^9LesuAY=Uwk)j8z?R>Q_{9Rh46b(mk`} zNEu6T*7mHwE`<)1z!e$XH3UF@hD6h+U1H$Lk`0gd#BP|Q@F<3#o(43rW8ooJda-lt zjK8g_Yw+*yQJ!Lw6VzVaQ=swyuzxpfDOhs>4ibHJj-J9m8x#h}RUL+GZ#Lh#{S5=D zyE3oOE%QS!KjU|J${+mvb_PmHj}gpI67@2+LwQn3&QCn^%F^EuKzX?@;mAFGFnV{q zWJjMXI3x7aDVoU|a@5xhy6*x&>kODV26ll_{#li_A}aWi^utT`YL!BH<^m8Ww!S%5 zBQzFTYQ1g9YIT8K<6~p%Iv#+a-WWQIG`M$Z~uBjoM{Bt ztRMi^*C`u()xHk9osEh;OHKp7sqdl!Qp&I_HOz)xd?(2NT_v0~_Y3d3>|;L4--$hb z@ipbw#RB|91j=K%hB)|#)9ZdIv!KK9mj;7i5VXz%mOJCsfv)lO(NR`AXwD;bOY*cP z(7xZJWg;a6Uk4mw`xLnuJeW&$m$jV0E684TWS&?f#Oc|YdB}KA4@fR*6bes^hIS3l zwfSBI0+!JaS9sO!;PFi(35?MIgqASq4%hR+>Fw59vmWah$64g(3)$<@OO)qd&SqJE zk%Qw8VN`DJHREbCIQXGue`bY#b~t?l}Wc^O~4p2iV^S<&3SUi%;oZy-HCCjFcw zd+j6hbY>yWa*^tnV{fj*BCjQ7`XfGI;N$SYKe_raKC7gAwn7Zlt(-bCuSW}ccc8s~ zke*#gKSLv^*Y5Wy&pvO&X}d8eMiR^@q;fnaX=N-KR0A2F;J7mE~}qfVOq-GTizCK&fy0i8Gi5ys$kc*(yU9hPW;q&mLq2LA|W@i=EwgCJ*wn zdoSw6`V-|*vqzlPgFE`CNAJV>xdXkKr*6T`gZ*x)T~^Saz98rFiWgw1eO2uISOZpS zXm1K+Vgp&EXED-G6WMDYndb({xm)NF%niH1QPx6BnHSUo@m zc|U@ZX!nogUa6$#{iGiQvX?!X=Ml;AR7<`S>Q@NYXbd)|`T2wS4s?ffN74O=$)Mf0 z_oKbUHIe5WdgMnu67_N>^ZeL^I5Vtzvz`GSpa%E8tUH_wFHHK}TT%@Ksb5k(&c2O? zSLi~ImTNkK6yLvRc8aUQlwF4HR?m3>Yr==$cTZ75S)=7$b>bt~W$LIj=a3p)PqQUr z^++=2FpW4#C#ds-cZ>u3@p9>-whln6o*}pM(FMSe(7&?+cY-`$%eJO%(gr_2F;&I} z3&Rsl`my2hbRe=U;qA5OGx$r(h}~_S4OkkPhjAEjIJ@8b%SmLy)vkfmtxVBSy?@4r zGR6~}4A6TQpRWn!lncwZ-sJ3Q-%>&)(czpUWy4si{(W7CV2Edsz21^}(nyXS zXU!NrTM^t|?5p`X{XF>fc<_3zpe5WE4fgUL1>l=S@hy3JUU=oT!sk1V>ljbRx30z4 z19&#+$C2zc(1-FEksMWn)R>np8-ETQNjzHq>=>Zy%{)G)ssNi)F?$!v?ZDne@?+qo zFL;L0srS;EO;|4J*@*Pxb^-O8d4lr%9z~o@JayV1{{(`<6ZX3YZ0GJaQate!FBECfEk zyI4jW+=01bMf+;4K4JRg?vKd5-nAmnb)=sWve$|b%9E&vI4=6z&-8qhh3|OMEZcX> z0=WR>I$jXoruWm#-NFv5eyLyP z;SdE6{v36D7gL3aSzkzS>Y2c<@AqAi2&=@0`zl+lP5N+8^DBILBaQg^OT$})3v=+r zh+ysn%?2#cGybrtYcjTP32`1;+>Yl9l7`IBzEoL+%7Xy@(`jC%bTB0ScJWfn1ZJ=l zR3-Lj1rxI>?kU5+Vx4qs*Tw+-bajl6!ProeFS9-?dIobw6nT>utE?bP%-VR%I>mNP;!5b*u7+ zOdzqfFu;C?^y-17(d;TJ`{@D-Ft_X6UakI;~L z@hK6g_{eFmQU(ClF0(feB?aRk=asZwq_xeS8UigXpl;@#d|K>SO za`M`;w;eaS2sEer<40zq;hYH5Z19;&;K#+D_IJbf;8-x)U78W?1&Wbpj&sP5OEKzo ziOkbMas@pg0%WgNGLP3u z#2H}@TG;-547h%}Dv`Au1Wd>~tR?Sfg4}%{xtA;H*_HJ3g6vgK=Ar0E9B(zQ`)@~c zp+FSx<93^!fOhEG(5CVgoUY|&7sV-V__l>YpYyaL*rUWat|-I-emULcWF1|E_`3$%4+`ui|Do)) z*$Qqy=awhRrvVQrn`K42YJs1vpSyfBc|ntrB<0ovJ$P&!`wczod~5)oYojO%#}(eA zJeN-+4(__;@z{Ge;21k$Lfv`+WO^@zYJEEk?q)pvsaWm>=Scmd_y^T10We@3pRun?j&2yG}2vxLe2BIfb3ha^!_5P;8O>1Y^UxJo~s6bH7QuA?B)idq-ROePbAsvG?~W- zAkNU2w%TV5<6!b)kg0n3LC_=k!D(l}B{2ItUb>3?6s+{xF_kQ<4&EO^dsUI1-AF%k zWUmM^kBtlBWH=uWxbrOshR81Yc6voYzdc!Fv|ZL9;XTC>zbKsxX8Wmp+qhN3SzWXPbZNS}uzDRZtX{aJ;>sk%AgI9q?>v`PY@Sq;# zxv?JknIU@(ka_e;j#d4Qdm2nv0JCqOK$U6$C^lDh_`$9XZ=D>V3p5u1<Lqdv<^jT_gPvxZ1UKbCHLFiKXgO714hVXEwhWai4nt>5jdcYs5UkFYdBq3cGdTlX>2Ug3Tg;*{WXR5H%fi zri%m_{gYUJ=<_o`p%Kr@Soaiw7g{Qyu4AQ^ERL-MbxCP3yjpR)3 zIZDx(cL^pnbNW~~7(?D7!&1Iqg5d6I#PJ!+5!`M0`io1O%PR$tv(;Ng7?hb7R`U$hiTqHyPu>*dl_9to`qW@2|vE_sMl&`9Fb?66yo@I z8A{|`l!upoeNP#TMPSYZ;7Z^B=?#DC)?Y_+p?e%&)^87^)`MLW7^`cxuc{XVv zj*`F+rEl?jp}51-3+IFQK$Zx)!;|Uge!N}L?(`Ks#9qtPoP=j*&H=)Y+__ky7llIu zktg#k;#e}M+b(Nwhh|c-5jSURF@3f|OTVa3n4G`F-a)ll%xJN`RQc>XOwdN!nuRL| z7fUX^03N-HT52Z2M68ZRH6z?Y8bOwTY-fF{qUY z{}CDBl3FyE*T@Ykdak;Kn~mUaELC(nH(qzuq1zo4H(t-eVP{6WHl7o;!pM(h6Y90* z@{q`5Xn{B}$YV7tDYeV-f3#WkEnwK%ZL1AkVhi$j>i!)JsAhGEzx0}*lSKKh48GKGeY?3TDwN{N{~T$ijxuNmszf&=f-oQ_ty`>k!=y+ zU{tq%|HgC8WXEgq<&EbhBRAUJUI6WdeL|k8jv_x#@=-53Zj?uW7#!|9k`OHAs54CjGd@qh2>+P@WNzb6<4774OD#IPi99 z4BU9W=QN=^Ol3j$(;J6&54?u<5+gmooj`tuSx~Q89h66p-gkN9_YKCK!FSZy zMPX2Clh3|+Gq9iO-L{RdMS{BD-ruq?SA$oNeUue=s0G7S=g-?M{KeoK@6|sKCh>gc zLkrQ?jTp0xpTyj&EWA!^OTk)4IF^%)I8N3-RCAI;;Ml>}Z;DF7LB!}a=1bOR0Nkw3 zr}M!H2wnQl=V`?aukJ76E2h~Dvaax7vOGJDCzxl+E(*TGehAUhwymb&bId4@kuu_Z zgJ8gNA_CY78yi2JPlOZJbf+X8!{EfV1x>yNd0^9J&UWVq4-9yr(=#Ja0Z!_lQ?M`` z#%Y4*#-oeMu%QLiD{lhjp%6u!(~mDarcFtQrcZCDt5Q~gtDyz8nJ2>F-qR&}cB(l8 z$FTQfi$8SX^cOyzU0Pz`v4Z4ng|JP~=qU0NK#O{9CG%vHoTlrwOnK4iaBFaVPT0OA z=wg0~-fPVRyo|JKy}seKTJw9<(tAN5NpYSkoyo3quUK@h;n#e((ox_oz z*l^VAiZ;rldKhtDvBvDzy1NTRu&c03@mhjzE{9Z8+O2SlB)XpjQ?$E{9@^{GSL8WN z1Nkv|j(P!hlt*kA;ymfOqxC542z;E?l601P7oZkJcgR5APv2#ym$1h}QJFa`^VqTK)tO)K zhp-E=SGAJ-M{$e#aSpD`ZQ zz4>}=?b^_@)UW=V-%*g2bRZ}Bpe4*0+?O4`LlagGx99_FJs2gJEo1P725{R{|Juj@ z5qFC~er`9TUXm&(PcTHB)Vbl0+JzzTHiegeK*q*%!o)ggsPGIZoD~^3xz!n%%krgY zD)YnCS8(Cao*68y4tZ{nMt*w9UZxLGp7SIpa)fX4@y4G?CC*XbGGYg&nWvWIC{e%n?ARR# z>b2H~RQ|d{K1FngPesuEnB!=7EiJUypK#=vA|;XVqq2f}?I!bZYak9!%bncom$X4^ zjH|Hrk~y3yz#gm&TmkJ8qOVWoT!-F{*OSNIngP>rip0%B63}#y6$b@78z`&3m+UzH z6CbyKyYunYE^JMK&SuBA*SP0vpWAAp_pqJ$h;!w4VtK7lKHR;4M`zNNgGRjf}qhWFRN62XxHmhvEao=QJXktXJnRM^OBB+051g zY&#%lXQ}v+`|DU+Uhmq>&rkTK?t501^OacQUF4@K1NC~xi1Hj!N1V1HMRr3vb0~Im z=?wRf8;}-qv9XX-fjd;VV&cEDfjdvEwAC7yafcY|@w}-H?3fJl%$SP&2r!^tGqosB zb`;|5T2#z8jj)BOdrFw?)x-eB-p(jC`Q6|G|C>v)M>;WGu1?P&)k-X)3GF3)A9)V< zLVjlQQ7>;{lqZZ8al8Y=)py&{03O4-g0$01xI^AC?t5Ybm~X@Ly1dX&_|wy9_lVbM zuS{FyndTkx6QhrMvF}28-e0XHI2HQ>ZF)47pyyE6wKYCnz_&?FbFW4;Zi%7$2~I(~ zM|GgR!m^QPwG8AZ_D2=b%Ujfv$b)}E9LDdA47LxI;oF@T4vDr?g2Onv!{%4$eyljr z?(2hSuManoXM+*s$K5}T=ta@SLFDnNI8SiA#VzYrXD!#(#a{ig7>4zZdXK56jUsymfyj|zNW%(u)ASYb`eud0zw zK``qg+{blT6nHL)m8!h?gNF$9@MV;}$HvNQMSuLv#uLAyJi;#!CoW%E-Qbfge3EIS zoe<>)oS#rXD!eNUuKM)EYMs`CF|yQlvHH5O@3~z3{2mSvsdWC`diXc|`M2$7FYju` zk}slO97jyA{x-r+3Kxw$& zOjIe^loF(DnTS-a`HaWkLVmO|Q7;gR^4uml2TMP+yC&WS%XR$xo2Bl+hWy=h)@ETa zXSqlE+tH)o!75BonHGf|YG&=%ztVs{U*y^BJ@RwI5A}M_hw{w7MI7prMYQ${=}^u~ zwS7ju94K@53R`4F!`HXyvRk-a!8G+XTr5u;UN%O1RX8EfEmFwOsyOPE`vT>e@ z2Dg1G!?s-vUYKm{#7YOU%Eg+~FsZguccI~Ytd?u(t!&;qT=PhVa`ZwX_DvRXLf%&x z%Op|&4<gu0jE|OZtHUPG zl9c&@>VZE#F_UE&jqnxwwu4gd9`ztYD;$-_Ud;s-Q+=cRBCWyn`zB(L0 za~Pgvq6~3yPyz0?4;O3rlws4w#%AAYU{o2UqrxjmqN4C z8Tv50!1zOY8ap`Pf;12amII>7IgTm30uw? z13!$bM9bS5M1C8&f4NTczd%^GjQsmAXQ?ydCYedo7gk+`1r3_+d^)y>=|3JiF}>$DUbl z5_OCh@qFbo;gdT~cWNp^HUXa*o^WplbrWE zy!293^Put8RqMYsp`b?(-C=kwx*ww-X!k#JXs?)Tzz4t_V@z^<=`O!L z*y#;_y}TCvJ?$J&JHtU0f0zOcB%P1Jw`~IQEt~p8=;!f*A8zGO?W!@3CgjFt`(*H5zsieppr}iCzp2D9-~{#NlwYZ^=rY$24u9p54B@j2++ml74I0 zP8e`&XH@#QB$zdPU2DFN2L^?`kDB(Sg8RzerJcIB@#h$0xrXZQU%1j_$Wb5mW^Cpf zHLF*39$sUeFZlCjG`1xhae6FtohNeyLC;kHgPPz2GqutTU|5B} z+1Wx5Cfx^5v6~!VsURa=ar+!z5L{fBD%g%Oo<`gqS5Y3$O2l#D-?q}=qz;~qew^{m zHHNP(jSOBf8G+@DoGvWh8HCbX=KgrB03Gl5_^KPwgLINR*NpOJYNKAGy(o|V0OC;h zv#Q1j9D>URCR>ssu7CzRjmZMRDEN0<#?@O*c3=l1;vP&wc~9yf4-$8gAGtEr>%bwD zN5B|y@)rMQ9(K!vd=oF4dg{x-BPYadd4ck_YakE8#mKJ)>G>h)$CB*DPUZ<8N1XB> zhCh}}Wi@0k!s8`x{l!rSOaURn%5xez%i6ZXdWDOf}XQd%% z=bM+%?!#G#JAM!4eMI`nA4I+26O?CS9dSM{Xb^XXeaR*6*W(1bLmg+t9cw^&pJ^ix zr%BHyIml1k7IY5@9VidaBH~PZMz0G~o@cT0_e=o&i85Z>i*6A2H9KFecNP3$Uhoj! zd~)OK-07{-HonfJ`tc#3kY60|+@>w5^H-KI`hK|{rldZ+V9O($(%Ti-n@_nx64^=k zcU{EEjHB?l9_a{zb(oGh?)8Oq$K8LW@A3sBZu>8=S!+W(V;}cE=k5bG_O>-?^^0!V!J`wE0o48|3n@q|vj9O2H=1UUJOpkieS)n`vY(tw%n`=6^rM)1h7i=x?#Lzr5`kkhrNwfHeMajjz~ zpJOu7$dCI))T@W*F_9;HHl5%+-}8cfP?Qz0#DBGWe1QdO?my$ay78R3l3%FwY2)iW ztxEd&)qhN2>3m7|46ZifN7Iq#QG4X)H#_RJd$$IWC&&hIF6R`?9dBa-C0gdOhDN&~ zO~G}qA1tCk$=kc|z7`dHIjr@K=i384{0pi|;WtMeU3=tJIN^+$9+*orQ(J5R(uVy{dd1W%0(K*!W9x}kd#syrAO8440baMc)oW`&5%%m{qPbL{Y9=RN?Ea6v9zf}@}i z|3>D~I2Jj2)xPZW8lGv%cVSwC4a6&T)_-`uga_)(>Ll=uU_DK#16)Owc(>-y9yXWP z*x1o=!4{dfczsgAtIduTSSf7}ktd$!8o_DrD%61`OG`-wd6T`2^I3cO1- zq1{cg&|YcU$a5DH@?)cj zdhs!!Je)j;bK^d%OL&AM`0AnS7!cqFDcaE;Ui3rv6JCXOPgX{IIUGQqrS>8}j|)++ z%U&o?F+buQd1Uh}Il%-BiE2JOwLF8}`I+WTm`_o>)OOejnbxa)!-8~?$ zuAu;)Eo2SP_p-rZ*_{5M0}I%(GqwRo7TfSERWWz=#l6J*@@@BL?YV{fW#tka+r7p& zGmxZ41Gc_Q1TMdC$x_Uzot_vrS<4H6WVwz3J>B zJIG3V4HQNwftywxC0Ip@O zo(Aka2_N1i`9cZ#%`EJczF<4;AOD?V8(-J-s<1-&o&X3b+!v{qxe0nu2EI2qIf8|G zBR|p@>UEX{<++uKI66Q2@{_Xd0Yj_T&!Y7c(D03TJspiAc(`dK^H<3nev?J}$npGP z>~>}K_;go2ZqR}}e@sDs{321WdI6N@nHS=mk$#liv!V&!#GjeA-@y-`q+qv3bm-t{ zPzdGZk$J4NprgA&wi++nj`osRzDRhkAG=EU+4K1~(Tkf4) zQbeze=vPD@iUtk6e>gu6qzhJRT*XrZbLXS@yzypkDXrf647|`Y#aY4&QWjzb)n65safV!(6we8>hQ0+<4HZ1oM`9seg!ntLI^Q9c;+uxR+P;N zOB{q=2RkJhn~W2##yl*u_VM z_Q1iVS+??lFQj7F`Dw?-bE0``zly-d^GBsf&jC|`OdTEHEJiqe#2~G(A+*gJa4bYw1@?Aoc9R_yaAns5*1>Mh)cU8phSNEX3 z%oUL5shh};KM(4aqH9UyQL#ZBj_^?%#*N=Mwm6u=$=!wc>lMM@&!u}YX-1*9!L;A- zZ`LzcTy!@9Dz>L%&1I$dd8H3+A6u#5lbcK`H1R*M)uq@P_RURr;vvV&wW3cj$9*5W z(m#aYN~;*bk(Xbi@`E?=;#C+maXh`zz))7d?r-c80PV)qbvayKDPLGVP)_jw9vK~wUA`q*Dw zqVir<+5rhrIQP-rmQn{gS8Frx_EQ8}YTK@IWi!E@l6gXoNu$`*nq2>pceS`KE$X#$ z-I2(X^|XTE+#9WNii^|)R&o#7nr~Y}tx`&2XJ7 zzG@r1%C!81VQmhZ%e+JQk?&C^dj0XZPvptGi8y;V1z*>+}qA4u1|_*3^y zD2QXH>=M#3hr0)&-mNX|1D@FPM>hnw!YDiBxs_`d;b(-Ylj!xc3FS%ri#U!?6yv(3(DdU3v*EZSH02OXxq)2U*!^cc7$3JoO6R6T2Gv;K+FvdCjM|o zIQxu^6U0h`U*DWAybO{C`-I{u7h`Ckr}uPRMngNci{tgH)g7;K=RYB9xxxvU!5!3V zNfG6te}p(DI(&Lbw{<~IJOBE19W|h36ZqTgku5ab<(t8KQwBsc`{v94+y?6=E#_`* zS;S(3r^6^TTJa*~0>Y1d2kPb2xRb~;u+B$t*sf{6<6csPnMS{dZ~WB;42dGLEKCX$%yHuE5kYhHmm+o}|N zs5rqF|BD`!=qT1E@J-{4wEN6fif1s#1J~|zuUF$YvRH_{T%IG(j>fTspL5GTM6dKB zl;_fiaf0J~YXPrPUc}QY7#YuUFJo4U$G-;uW`>h*DLqg7jbJf;O2qDk`gX)#p3f!; z&pyzH@N=Pen&?F(Cq?90N!vY(PAK9v;lv?-)Yk25s^m(-r|3vYgxSx10 zw7b>yVq!1Xx5%@~AP?cE*nKb2>yE?;BF~hO8o?QE1sxBoNAN@E>l&#XUt`a6(H$0F zMfcNP5lrkZWQO)~JdHflRwF+?U#W>+>-5)%JP9h_2#!taYYtV-7~ID1o!JvbKV0D^ z2Q9l)47TL$`N7pC7vJ(_?y2|VT5K%5aDnw*6#ns&I>%6dFFy8aJG1*j4(8SJ-gDc} zMEt&}>~B7)d~A8$a?m*_6sO8Er6)Md2lX}Y+{Sz9Xe%j?-^MC_4^NiFBx9xKnkv~c zMHu`2;`UC46)e7dMU15_7`^L_r!1@(+KWzwCSh% z!39i!ah5TJvj(5tJW2Gb5OtmUC(oAtbb_<_%k+(E3m#B#z^df5uq>=D>y^x{KMdaH zow4=|;DZl+J-2+jLjguE@r_>ZV}^0NsBEjkMzM6kbixlWn>x|U#~S5nkw6@}_3b^) z)}o-;hax2YxGZG1EQn&`-45#K&7|d=zT>AxzRyxdNq~g0_Eqtab-a8Dc`n&gLimwO zDJOdE6YL}MBvVikoUGT&;zE}N0GIyiJR|)cI7GcUAYSX^955x^xb+rO^q2-$?{WVMe5 zfs;9VUpa*uL1*qZV)u*c*2G?3a+8GTTS>^z+drt+yF(~XzBA&avwYI|P-zJy9=Kg_ z)Nq8$%CnPrwmf*iitZ8$vFPM!;02 z$}2`#2rdkuJFK%n_v0}&L+q~olakoWJPdjMXn_3GUq`*Jw9F8BcJbB_oSz4Uu$#(D zSZR)z;xk%Ld@Gh0YWN`%qd0#&_I#ot)<444>*imFvjuwCtrgc|ie>^gpH$Gp$H~96 za~uY+`v%nsWihWe{vJ0shcWj=?4fZ&l2^Vzp4pfe_75lEqW^U2mIt_O_fzr5x2o~q zAk#DBhkgW?rkwu-aA3O~-5pwXHDB?{s5j`YsP1dWEK(IBpCdJUz>i zKQ9Pgh;8GUyGH>9g<}%cxQ4O6>reL;mg2aPxGB+VOMWqtr|FUj!Ff6ck|lBs!PgNz z4kOD`kVfpd=}o#z;9hCxA#rPC*j-TMp2of(1ggd?!}+c7NIZvo%KS8@P!~Y>5n{+D zddVMkC-PjA)+ac&3J-0Jl8ynh$mECO8{9O8q?W`5`HjD)(eBod&9nHTnEhPqVk7pd zv~D7);XSUYjXXO)Mt(X>P_Oe0C=buqX9VX>?~O|HY(rqn>mhyXs4#2|n;Psswup&I z@?=s4Bw&kUOxfc<3o#lww3ooJ0^vDI82M4Vf_i0m+$Zv!ZgnF#){`-7?0Tyh=upG9 z9WTIbuKo4B*Yg2qJpZS{!gm}K8Gb|Tes@3G>qj0F;knKb`7y6HA$n2W=pyno+j}bi z!;w=cGkkaOCH`FC?X-_+IcB)8Lg)9_X1wb#x*w6qoy6|NmC?jroL`~|&pk)Y2|sZ1 zeAYj`G#jyV|Kzcx0|e*r!_qeb2cP3<67GGkO)@bJ0d$8Idgy*EY|-vFEYMzmf@=uR zhm|M^KZ+@TiC$E(1w@|DMMwJo;V>vT{|;A+!^c8XE}u4plA$ zc+v+`{<2o|565g;E>YZi1#gc7iQ5#If$p;-HHy#nL(4&<=DtN)Fzm+OgPOBF}G&yuxVZAfaKilpe?)!v? zj8Uv}^;Kf!`$Zmp=YNcE`fEh^N!nvV^t$M>g~&tugpc3|Ul>_<&oGZ)d~_^C-~J0W zJQX&UU%PpFb-fi$sKnZqpM z8G2qM{K)J)K=fKa7)0c`xX+Z})ZWR-D4eOoh1VFBly!iT2U{_%Wa4>RE>cxMdJ>sM%Z-9LGb(EOK@ z&O03IJq+VUhm=`LNLKbSB7}V3WMzbsGC~yItc+3_B_Uf%h@z~NgAkSReeKl{8QGDM zmFvHjV@B4EdMB zUfBJ$5-aT0+nxoU>C_iZ2|vTFDqFq8W*mt;Z|)AU5S%J?l@r?wV(^QsL`N%qDQufO z;xcS&iL8vmt{tj&#t)|^)hmbZA@0oXR^{YWyibW-D1Y?{s`lkwtdEYv#xABZkKf)$ zK}=y}|wZxZi zNX*G(Sbn@3Yut@L{5AAF8WL&qQy415(>+P4BBn3V!^D%usgEAw$z%Wd5qW;}?TREg zhVF_EL1iznA@!NGg=ma?CnpvaKlfsLQ_Y#tvRO1uZ|hJy-i^Kf$l6}_Y(bvC68hX~ z8*$c)=C_&7g=l5KSBvNsrknwJO8qM{2u`(Nz7WeZ3ZAhs%}ZJMip;z6L%b7aF+I0H zYTX4IQcJcmtAE)7uKl*XyKiG;^Er_G!|zXj#Y`*wUkN{?G(YH-HDSI){)4&3yqk9@493bLYU13>4aTN*Qz9^C;#=ICw@X z4&cWw;Ux5$(V{?}_>0mz368t_qAu0P8T=W={my8mA?>Z7iB4GKqeQS?R~-E%M{;vz zDrP>rhoZkE340kr$kc)RN%{T(cBh%jfxXhN%Y)~HwC&*M zNW2jA!uRVSk8gnra7H}hbhGqFaksqJRK=%f*GtaiL?LPjQFLbb7#u5F!vD1U# z{C?KaNSOE;-XEO=37L(CRCno zyq(yPf#067yb#%D&jI(p=N;Tco~52VX@bLPsKtA-+MYkc(mCP34WG?TuG4fl- zv$M0MOZ>Y?wM`~x)_bKWLINzG4ZT%Kj1MtzH+24jycO)X!2@;nPw=B2Y6HE}=-)t| zJ#(YL8PMwPPNAox#J^Mia#)>%B=Pb*aP7n|Ltd*SPw-&3|1tR0R(=E@7g$~3^Sq+= z@O8B8r{VihwIpzg_YDKr+G-tM$IYW2UYEwp1#;|}T!viHN4EAF(WHUg#aw03W6**b zdRax90{4;E+!p8Hp9_SC1C&+p!sVnY3J~|;e|2m3X3B;Ku~(?A19%qywdFn5 zhYWd{`>G*Noc9QDxOCjbiQNKK737E=zc+;O5WDKSZtbkl$_u+!H*ax2O>NypmY*AV zm@apKUK}_J@{CgP$`Tx}AXN?G&am~EKXG@@G!DWY2A-XT`$>1Jhuwwawmh6K+VY!d zKLLKyZL8oOwh2z|C-QvgxOtc0L>Mh;R&M@W=uyAWH~6BDxK5hPyRmy=_VX9=Uy6sK zJFdg2D7Hp#YS)3{8sHBB2QI=K5#^tBgajIE72~pOI(*< z8=i?0aE(b^M1sOD)Fz?ZDQ3Ye+G@EU(6OAPk87b{(J%4FiTyN^1m{cepWnkr+Hnt0RzNWA=KIcq zk_^rbuv4NKD#gY~G9)TJzOupwHj0sye#IyrL)=1=;MvEj68t3neGz&IQ$!$7zuZ&c z9BZ7`Fq2!rR2PEI@X9lg>L&uupRyI9kfY5$lKT&nIu}}8862o70ld1fSA~uQc(!=M z2Ywz1YCtb3(E!LZ!l?%wxz6pPp*<^j&)<)AWd?ST%=h2c<=MwgQJz1Zo_~H6_2rhs z?mnR-u$Mz@6nHkMRRKQ=F=fze(Z(6_Tv4O~POjOQch0*dY#RM<*Hq>TD)X|qDqB#8 zH?~Q^{g^T>!0rzfDX`ZX69qhfY32k!@|Vs)FR@U4$P=r)1333*o7D#n4C4gBsAzZ2 z5~SuA4tE%OD**0?bfg+~uU~D2y}0U*gJ;v+Ch#-=ay^ac<<%ACN#v<|JqjGh%E6eo z){%Hu$8NDZrz0_AOM1K(YY8&2lnd|AsKd$sW?XuFdK7tV8B%K#P9Zqgb{mbp-#3gWR?5N`D9DOz$E$56SOwX6a>(a1e^Z$N$czWrIP_D*=b~y0KkjBT#4e7_% zadJ)L3rEj3wE5>;R^e#Z{4+76Ty%CNN#2i{XM{-AYmRxW@L)zP5_uPi#u$T65KX}#+tOq|~ z)-16^FRewDBMWnDUfL-u;X9mZOZ!~O8to`u~}{oEw6 zmxd#oGT}K`rU3jf%g3D~dSz=={U-8g?by-qVw00DurRjou_RL0xzM>zeFWj-@?xqo zrnr@QuHTq+7ir(r3=i;nfG;tOv5+aJVREsa#38N+Tx+S&v@^I zUbXw-F+{l~^1UFq0kjep%IdP&XGM-h4c{ICH|fw)h|KzJ+4v#g3UJTi*s8frd?$WxOzFFv@Z zG}MGL>W$?hw*SWZ!Zr-Phg*>39UtnN(o|e&!3};?-7hW>y?z^3UMBJw1T8-zIA?|t z)tvBK?0AdbMzXORIoZn%1Lsm`8P~|82+KlH|)?>q|(1b=gPqH7kXQX~?ob`a3%5R;!*G zQ-r^EYQSC&dMx01|5_*bDLAMbO7v>#GKM@kL*IdO&~G>{?fxLPj+HEm(VIpVPo5V2 z>y7ctc+dFcQ?W>hP7ik1`@@Z*sX1HA@6{0DjVyI8*=IJVQvhTQwQ zaL6Ubk)m$}XqIc&HD$>t?BYm*`#D+G1iQxy+@L-l0(*rpYJz8n zh(ry-&zJQR&xu~Cbm){ zLWFtxPc-A2BXfkCk)nT6q3E9*o9~B}V3M0RU&8&1?bJ)S4V_Im^=Blv7^~?nCNtJO zM7bY#Bcj*q{Wu!bEUv}Xt{)RRb z#|b}HB{a~>Z1Ec8dDr7zL2w+Jn59>K_TkvC z<7D=fpGe90$C0L{cQ_;}^XA_C1f)~4FOWP~g)h~M_eQGcpwF@a;JHft7Wj#$mWEz; zd}|@k;ptl76klU_X|TT?n@&5d?%wtqy)QbcFqRd~o1$ z;V5n19jv3j2X_BVZwz}KN2TD|#ZWVV@Iy99@g#cPxEahu Date: Mon, 18 Mar 2024 18:21:39 -0400 Subject: [PATCH 72/84] Add tests and edit verbosity. --- ipie/addons/thermal/estimators/particle_number.py | 2 +- .../thermal/estimators/tests/test_estimators.py | 12 +++++++++++- ipie/addons/thermal/qmc/calc.py | 3 ++- ipie/addons/thermal/qmc/tests/test_afqmc_generic.py | 4 ++-- ipie/addons/thermal/qmc/thermal_afqmc.py | 10 ++++++---- ipie/addons/thermal/utils/testing.py | 10 +++++----- 6 files changed, 27 insertions(+), 14 deletions(-) diff --git a/ipie/addons/thermal/estimators/particle_number.py b/ipie/addons/thermal/estimators/particle_number.py index d98727ff..174e6934 100644 --- a/ipie/addons/thermal/estimators/particle_number.py +++ b/ipie/addons/thermal/estimators/particle_number.py @@ -50,7 +50,7 @@ def compute_estimator(self, walkers, hamiltonian, trial): walkers.calc_greens_function(iw) nav_iw = particle_number(one_rdm_from_G( xp.array([walkers.Ga[iw], walkers.Gb[iw]]))) - self._data["NavNumer"] += walkers.weight[iw] * nav_iw + self._data["NavNumer"] += walkers.weight[iw] * nav_iw.real self._data["NavDenom"] = sum(walkers.weight) diff --git a/ipie/addons/thermal/estimators/tests/test_estimators.py b/ipie/addons/thermal/estimators/tests/test_estimators.py index 849acf25..cb12338e 100644 --- a/ipie/addons/thermal/estimators/tests/test_estimators.py +++ b/ipie/addons/thermal/estimators/tests/test_estimators.py @@ -16,13 +16,14 @@ nup = 5 ndown = 5 nelec = (nup, ndown) +ne = nup + ndown nbasis = 10 # Thermal AFQMC params. mu = -10. beta = 0.1 timestep = 0.01 -nwalkers = 12 +nwalkers = 10 # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! nsteps_per_block = 1 nblocks = 12 @@ -77,8 +78,11 @@ def test_energy_estimator(): re_estim = ThermalEnergyEstimator(hamiltonian=hamiltonian, trial=trial) re_estim.compute_estimator(walkers, hamiltonian, trial) assert len(re_estim.names) == 5 + assert re_estim["ENumer"].real == pytest.approx(24.66552451455761) + assert re_estim["ETotal"] == pytest.approx(0.0) tmp = re_estim.data.copy() re_estim.post_reduce_hook(tmp) + assert tmp[re_estim.get_index("ETotal")] == pytest.approx(2.4665524514557613) assert re_estim.print_to_stdout assert re_estim.ascii_filename == None assert re_estim.shape == (5,) @@ -97,8 +101,11 @@ def test_energy_estimator(): cx_estim = ThermalEnergyEstimator(hamiltonian=cx_hamiltonian, trial=trial) cx_estim.compute_estimator(walkers, cx_hamiltonian, trial) assert len(cx_estim.names) == 5 + assert cx_estim["ENumer"].real == pytest.approx(24.66552451455761) + assert cx_estim["ETotal"] == pytest.approx(0.0) tmp = cx_estim.data.copy() cx_estim.post_reduce_hook(tmp) + assert tmp[cx_estim.get_index("ETotal")] == pytest.approx(2.4665524514557613) assert cx_estim.print_to_stdout assert cx_estim.ascii_filename == None assert cx_estim.shape == (5,) @@ -124,8 +131,11 @@ def test_number_estimator(): estim = ThermalNumberEstimator(hamiltonian=hamiltonian, trial=trial) estim.compute_estimator(walkers, hamiltonian, trial) assert len(estim.names) == 3 + assert estim["NavNumer"].real == pytest.approx(ne * nwalkers) + assert estim["Nav"] == pytest.approx(0.0) tmp = estim.data.copy() estim.post_reduce_hook(tmp) + assert tmp[estim.get_index("Nav")] == pytest.approx(ne) assert estim.print_to_stdout assert estim.ascii_filename == None assert estim.shape == (3,) diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index 656e2573..28374efc 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -118,7 +118,7 @@ def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: propagator, params, debug=debug, - verbose=(verbosity and comm.rank == 0), + verbose=verbosity, ) return afqmc @@ -142,6 +142,7 @@ def build_thermal_afqmc_driver( options["system"] = sys_opts options["hamiltonian"] = ham_opts options["qmc"].update(qmc_opts) + options["verbosity"] = verbosity return get_driver(options, comm) diff --git a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py index b617120e..3c6cd468 100644 --- a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py +++ b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py @@ -57,7 +57,7 @@ def test_thermal_afqmc(): #pop_control_method = 'comb' lowrank = False - verbose = False if (comm.rank != 0) else True + verbose = 0 if (comm.rank != 0) else 1 complex_integrals = False debug = True seed = 7 @@ -92,7 +92,7 @@ def test_thermal_afqmc(): print('\n-----------------------') print('Running ThermalAFQMC...') print('-----------------------') - + afqmc = build_driver_generic_test_instance(options, seed, debug, verbose) afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) afqmc.finalise() diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 5e69f55c..22b1c2fc 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -54,11 +54,13 @@ def __init__(self, propagator, params: ThermalQMCParams, debug: bool = False, - verbose: bool = False): + verbose: int = 0): super().__init__(system, hamiltonian, trial, walkers, propagator, params, verbose) self.debug = debug - if self.debug: + + if self.debug and verbose: print('# Using legacy `update_weights`.') + @staticmethod def build( @@ -78,7 +80,7 @@ def build( lowrank: bool = False, lowrank_thresh: float = 1e-6, debug: bool = False, - verbose: bool = True, + verbose: int = 0, mpi_handler=None,) -> "Thermal AFQMC": """Factory method to build thermal AFQMC driver from hamiltonian and trial density matrix. @@ -151,7 +153,7 @@ def build( propagator, params, debug=debug, - verbose=(verbose and comm.rank == 0)) + verbose=verbose) def run(self, diff --git a/ipie/addons/thermal/utils/testing.py b/ipie/addons/thermal/utils/testing.py index 8cfabe76..dbdd2e91 100644 --- a/ipie/addons/thermal/utils/testing.py +++ b/ipie/addons/thermal/utils/testing.py @@ -19,7 +19,7 @@ def build_generic_test_case_handlers(options: dict, seed: Union[int, None], debug: bool = False, with_eri: bool = False, - verbose: bool = False): + verbose: int = 0): # Unpack options nelec = options['nelec'] nbasis = options['nbasis'] @@ -90,7 +90,7 @@ def build_generic_test_case_handlers_mpi(options: dict, mpi_handler: MPIHandler, seed: Union[int, None], debug: bool = False, - verbose: bool = False): + verbose: int = 0): # Unpack options nelec = options['nelec'] nbasis = options['nbasis'] @@ -157,7 +157,7 @@ def build_generic_test_case_handlers_mpi(options: dict, def build_driver_generic_test_instance(options: Union[dict, None], seed: Union[int, None], debug: bool = False, - verbose: bool = False): + verbose: int = 0): # Unpack options nelec = options['nelec'] nbasis = options['nbasis'] @@ -208,7 +208,7 @@ def build_driver_generic_test_instance(options: Union[dict, None], def build_ueg_test_case_handlers(options: dict, seed: Union[int, None], debug: bool = False, - verbose: bool = False): + verbose: int = 0): # Unpack options ueg_opts = options['ueg_opts'] nelec = options['nelec'] @@ -278,7 +278,7 @@ def build_ueg_test_case_handlers(options: dict, def build_driver_ueg_test_instance(options: Union[dict, None], seed: Union[int, None], debug: bool = False, - verbose: bool = False): + verbose: int = 0): # Unpack options ueg_opts = options['ueg_opts'] nelec = options['nelec'] From 80ff261b2f2e0256d5b8c29a1e42d680abbde9d5 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Fri, 22 Mar 2024 11:08:04 -0400 Subject: [PATCH 73/84] Rename `nstack` to `stack_size` and `stack_length` to `nstack`. --- examples/14-ft_afqmc/run_afqmc.py | 2 +- .../thermal/estimators/greens_function.py | 10 ++--- ipie/addons/thermal/estimators/handler.py | 26 ++++++++++++ .../thermal/propagation/phaseless_base.py | 2 + ipie/addons/thermal/qmc/calc.py | 4 +- ipie/addons/thermal/qmc/thermal_afqmc.py | 21 +++++++--- ipie/addons/thermal/trial/one_body.py | 14 +++---- .../thermal/trial/tests/test_chem_pot.py | 4 +- ipie/addons/thermal/utils/legacy_testing.py | 20 ++++----- ipie/addons/thermal/utils/testing.py | 20 ++++----- ipie/addons/thermal/walkers/stack.py | 42 +++++++++---------- ipie/addons/thermal/walkers/uhf_walkers.py | 22 +++++----- 12 files changed, 113 insertions(+), 74 deletions(-) diff --git a/examples/14-ft_afqmc/run_afqmc.py b/examples/14-ft_afqmc/run_afqmc.py index 73063a12..ac29e9ce 100644 --- a/examples/14-ft_afqmc/run_afqmc.py +++ b/examples/14-ft_afqmc/run_afqmc.py @@ -43,7 +43,7 @@ 'beta': 10., 'timestep': 1., 'nwalkers': 12 // comm.size, - 'nstack': 10, + 'stack_size': 10, 'seed': 7, 'nblocks': 50, }, diff --git a/ipie/addons/thermal/estimators/greens_function.py b/ipie/addons/thermal/estimators/greens_function.py index c2c9b4ed..7abea460 100644 --- a/ipie/addons/thermal/estimators/greens_function.py +++ b/ipie/addons/thermal/estimators/greens_function.py @@ -40,10 +40,10 @@ def greens_function_qr_strat(walkers, iw, slice_ix=None, inplace=True): if slice_ix == None: slice_ix = stack_iw.time_slice - bin_ix = slice_ix // stack_iw.nstack + bin_ix = slice_ix // stack_iw.stack_size # For final time slice want first block to be the rightmost (for energy # evaluation). - if bin_ix == stack_iw.stack_length: + if bin_ix == stack_iw.nstack: bin_ix = -1 Ga_iw, Gb_iw = None, None @@ -55,7 +55,7 @@ def greens_function_qr_strat(walkers, iw, slice_ix=None, inplace=True): # Need to construct the product A(l) = B_l B_{l-1}..B_L...B_{l+1} in # stable way. Iteratively construct column pivoted QR decompositions # (A = QDT) starting from the rightmost (product of) propagator(s). - B = stack_iw.get((bin_ix + 1) % stack_iw.stack_length) + B = stack_iw.get((bin_ix + 1) % stack_iw.nstack) (Q1, R1, P1) = scipy.linalg.qr(B[spin], pivoting=True, check_finite=False) # Form D matrices @@ -65,8 +65,8 @@ def greens_function_qr_strat(walkers, iw, slice_ix=None, inplace=True): # permute them T1[:, P1] = T1[:, range(walkers.nbasis)] - for i in range(2, stack_iw.stack_length + 1): - ix = (bin_ix + i) % stack_iw.stack_length + for i in range(2, stack_iw.nstack + 1): + ix = (bin_ix + i) % stack_iw.nstack B = stack_iw.get(ix) C2 = numpy.dot(numpy.dot(B[spin], Q1), D1) (Q1, R1, P1) = scipy.linalg.qr(C2, pivoting=True, check_finite=False) diff --git a/ipie/addons/thermal/estimators/handler.py b/ipie/addons/thermal/estimators/handler.py index 3b1bb4c8..40fc7802 100644 --- a/ipie/addons/thermal/estimators/handler.py +++ b/ipie/addons/thermal/estimators/handler.py @@ -217,6 +217,32 @@ def print_block(self, comm, block, walker_factors, div_factor=None): if comm.rank == 0: print(f"{block:>17d} " + output_string) self.zero() + + def print_cut(self, comm, block, t, walker_factors): + comm.Reduce(self.local_estimates, self.global_estimates, op=MPI.SUM) + # Get walker data. + offset = walker_factors.size + + if comm.rank == 0: + k = 'energy' + e = self[k] + start = offset + self.get_offset(k) + end = start + int(self[k].size) + estim_data = self.global_estimates[start:end] + e.post_reduce_hook(estim_data) + etotal = estim_data[e.get_index("ETotal")] + + k = 'nav' + e = self[k] + start = offset + self.get_offset(k) + end = start + int(self[k].size) + estim_data = self.global_estimates[start:end] + e.post_reduce_hook(estim_data) + nav = estim_data[e.get_index("Nav")] + + print(f"cut : {t} {nav.real} {etotal.real}") + + self.zero() def zero(self): self.local_estimates[:] = 0.0 diff --git a/ipie/addons/thermal/propagation/phaseless_base.py b/ipie/addons/thermal/propagation/phaseless_base.py index 3bf2f451..6896d50e 100644 --- a/ipie/addons/thermal/propagation/phaseless_base.py +++ b/ipie/addons/thermal/propagation/phaseless_base.py @@ -264,6 +264,8 @@ def update_weight(self, walkers, iw, G, cfb, cmf, eshift): def update_weight_legacy(self, walkers, iw, G, cfb, cmf, eshift): """Update weight for walker `iw` using legacy code. """ + #M0a = walkers.M0a[iw] + #M0b = walkers.M0b[iw] M0a = scipy.linalg.det(G[0], check_finite=False) M0b = scipy.linalg.det(G[1], check_finite=False) Mnewa = scipy.linalg.det(walkers.Ga[iw], check_finite=False) diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index 28374efc..96b677c0 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -86,10 +86,10 @@ def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: comm=comm, verbose=verbosity, ) - nstack = get_input_value(wlk_opts, 'nstack', default=10, alias=["stack_size"], verbose=verbosity) + stack_size = get_input_value(wlk_opts, 'stack_size', default=10, verbose=verbosity) lowrank_thresh = get_input_value(wlk_opts, 'lowrank_thresh', default=1e-6, alias=["low_rank_thresh"], verbose=verbosity) walkers = UHFThermalWalkers( - trial, hamiltonian.nbasis, qmc.nwalkers, nstack=nstack, + trial, hamiltonian.nbasis, qmc.nwalkers, stack_size=stack_size, lowrank=lowrank, lowrank_thresh=lowrank_thresh, verbose=verbosity) if (comm.rank == 0) and (qmc.nsteps > 1): diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 22b1c2fc..7b9ba660 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -10,6 +10,7 @@ from ipie.addons.thermal.estimators.handler import ThermalEstimatorHandler from ipie.addons.thermal.qmc.options import ThermalQMCParams +from ipie.config import MPI from ipie.utils.io import to_json from ipie.utils.backend import arraylib as xp from ipie.utils.backend import get_host_memory, synchronize @@ -70,7 +71,7 @@ def build( hamiltonian, trial, nwalkers: int = 100, - nstack: int = 10, + stack_size: int = 10, seed: int = None, nblocks: int = 100, timestep: float = 0.005, @@ -138,7 +139,7 @@ def build( system = Generic(nelec) walkers = UHFThermalWalkers( - trial, hamiltonian.nbasis, nwalkers, nstack=nstack, + trial, hamiltonian.nbasis, nwalkers, stack_size=stack_size, lowrank=lowrank, lowrank_thresh=lowrank_thresh, mpi_handler=mpi_handler, verbose=verbose) propagator = Propagator[type(hamiltonian)]( @@ -240,7 +241,6 @@ def run(self, self.tprop_barrier += time.time() - start_barrier self.tprop += time.time() - start - #print(f'self.walkers.weight = {self.walkers.weight}') if (t > 0) and (t % self.params.pop_control_freq == 0): start = time.time() self.pcontrol.pop_control(self.walkers, comm) @@ -250,6 +250,17 @@ def run(self, self.tpopc_recv = self.pcontrol.timer.recv_time self.tpopc_comm = self.pcontrol.timer.communication_time self.tpopc_non_comm = self.pcontrol.timer.non_communication_time + + # Print cut. + self.estimators.compute_estimators( + self.hamiltonian, self.trial, self.walkers) + + #if comm.rank == 0: + #print(self.walkers.stack[0].time_slice) + + self.estimators.print_cut( + comm, step // self.params.num_steps_per_block, t, self.accumulators) + # Accumulate weight, hybrid energy etc. across block. start = time.time() @@ -259,8 +270,8 @@ def run(self, # Calculate estimators. start = time.time() if step % self.params.num_steps_per_block == 0: - self.estimators.compute_estimators(self.hamiltonian, - self.trial, self.walkers) + self.estimators.compute_estimators( + self.hamiltonian, self.trial, self.walkers) self.estimators.print_block( comm, step // self.params.num_steps_per_block, self.accumulators) diff --git a/ipie/addons/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py index 1896e334..e650ac68 100644 --- a/ipie/addons/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -56,9 +56,9 @@ def __init__(self, hamiltonian, nelec, beta, dt, options=None, self.mu = options.get("mu", None) self.nslice = int(beta / dt) - self.nstack = options.get("nstack", None) + self.stack_size = options.get("stack_size", None) - if self.nstack == None: + if self.stack_size == None: if verbose: print("# Estimating stack size from BT.") @@ -68,15 +68,15 @@ def __init__(self, hamiltonian, nelec, beta, dt, options=None, # the product will scale roughly as cond(BT)^(number of products). # We can determine a conservative stack size by requiring that the # condition number of the product does not exceed 1e3. - self.nstack = min(self.nslice, int(3.0 / numpy.log10(self.cond))) + self.stack_size = min(self.nslice, int(3.0 / numpy.log10(self.cond))) if verbose: print("# Initial stack size, # of slices: {}, {}".format( - self.nstack, self.nslice)) + self.stack_size, self.nslice)) # Adjust stack size - self.nstack = update_stack(self.nstack, self.nslice, verbose=verbose) - self.stack_length = int(beta / (self.nstack * dt)) + self.stack_size = update_stack(self.stack_size, self.nslice, verbose=verbose) + self.stack_length = int(beta / (self.stack_size * dt)) if verbose: print(f"# Number of stacks: {self.stack_length}") @@ -88,7 +88,7 @@ def __init__(self, hamiltonian, nelec, beta, dt, options=None, sign = -1 - self.dtau = self.nstack * dt + self.dtau = self.stack_size * dt if self.mu is None: self.rho = numpy.array([scipy.linalg.expm(-self.dtau * (self.H1[0])), diff --git a/ipie/addons/thermal/trial/tests/test_chem_pot.py b/ipie/addons/thermal/trial/tests/test_chem_pot.py index 749e9544..b0a4b809 100644 --- a/ipie/addons/thermal/trial/tests/test_chem_pot.py +++ b/ipie/addons/thermal/trial/tests/test_chem_pot.py @@ -10,13 +10,13 @@ def test_find_chemical_potential(): dt = 0.01 beta = 1 - nstack = 3 + stack_size = 3 stack_length = 20 nav = 7 nbsf = 14 alt_convention = False - dtau = dt * nstack + dtau = dt * stack_size h1e = numpy.random.random((nbsf, nbsf)) rho = numpy.array([scipy.linalg.expm(-dtau * h1e), scipy.linalg.expm(-dtau * h1e)]) diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index 42939a49..9d98dff2 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -41,7 +41,7 @@ def build_legacy_generic_test_case_handlers(hamiltonian, beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) nsteps_per_block = 1 stabilize_freq = options.get('stabilize_freq', 5) @@ -58,7 +58,7 @@ def build_legacy_generic_test_case_handlers(hamiltonian, legacy_options = { "walkers": { - "stack_size": nstack, + "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, @@ -137,7 +137,7 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) nsteps_per_block = 1 stabilize_freq = options.get('stabilize_freq', 5) @@ -155,7 +155,7 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, legacy_options = { "walkers": { - "stack_size": nstack, + "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, @@ -234,7 +234,7 @@ def build_legacy_driver_generic_test_instance(hamiltonian, beta = options['beta'] timestep = options['timestep'] nwalkers = options['nwalkers'] - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) nsteps_per_block = 1 stabilize_freq = options.get('stabilize_freq', 5) @@ -266,7 +266,7 @@ def build_legacy_driver_generic_test_instance(hamiltonian, }, "walkers": { - "stack_size": nstack, + "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, @@ -312,7 +312,7 @@ def build_legacy_ueg_test_case_handlers(hamiltonian, beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) nsteps_per_block = 1 stabilize_freq = options.get('stabilize_freq', 5) @@ -331,7 +331,7 @@ def build_legacy_ueg_test_case_handlers(hamiltonian, }, "walkers": { - "stack_size": nstack, + "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, @@ -392,7 +392,7 @@ def build_legacy_driver_ueg_test_instance(hamiltonian, beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) nsteps_per_block = 1 stabilize_freq = options.get('stabilize_freq', 5) @@ -423,7 +423,7 @@ def build_legacy_driver_ueg_test_instance(hamiltonian, }, "walkers": { - "stack_size": nstack, + "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, "pop_control_freq": pop_control_freq, diff --git a/ipie/addons/thermal/utils/testing.py b/ipie/addons/thermal/utils/testing.py index dbdd2e91..59920b6e 100644 --- a/ipie/addons/thermal/utils/testing.py +++ b/ipie/addons/thermal/utils/testing.py @@ -27,7 +27,7 @@ def build_generic_test_case_handlers(options: dict, beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) stabilize_freq = options.get('stabilize_freq', 5) pop_control_freq = options.get('pop_control_freq', 1) @@ -64,7 +64,7 @@ def build_generic_test_case_handlers(options: dict, # 4. Build walkers. walkers = UHFThermalWalkers( - trial, nbasis, nwalkers, nstack=nstack, lowrank=lowrank, + trial, nbasis, nwalkers, stack_size=stack_size, lowrank=lowrank, lowrank_thresh=lowrank_thresh, verbose=verbose) # 5. Build propagator. @@ -98,7 +98,7 @@ def build_generic_test_case_handlers_mpi(options: dict, beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) stabilize_freq = options.get('stabilize_freq', 5) pop_control_freq = options.get('pop_control_freq', 1) @@ -135,7 +135,7 @@ def build_generic_test_case_handlers_mpi(options: dict, # 4. Build walkers. walkers = UHFThermalWalkers( - trial, nbasis, nwalkers, nstack=nstack, lowrank=lowrank, + trial, nbasis, nwalkers, stack_size=stack_size, lowrank=lowrank, lowrank_thresh=lowrank_thresh, mpi_handler=mpi_handler, verbose=verbose) # 5. Build propagator. @@ -165,7 +165,7 @@ def build_driver_generic_test_instance(options: Union[dict, None], beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) stabilize_freq = options.get('stabilize_freq', 5) pop_control_freq = options.get('pop_control_freq', 1) @@ -198,7 +198,7 @@ def build_driver_generic_test_instance(options: Union[dict, None], # 4. Build Thermal AFQMC driver. afqmc = ThermalAFQMC.build( nelec, mu, beta, hamiltonian, trial, nwalkers=nwalkers, - nstack=nstack, seed=seed, nblocks=nblocks, timestep=timestep, + stack_size=stack_size, seed=seed, nblocks=nblocks, timestep=timestep, stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, pop_control_method=pop_control_method, lowrank=lowrank, lowrank_thresh=lowrank_thresh, debug=debug, verbose=verbose) @@ -216,7 +216,7 @@ def build_ueg_test_case_handlers(options: dict, beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 101) stabilize_freq = options.get('stabilize_freq', 5) pop_control_freq = options.get('pop_control_freq', 1) @@ -257,7 +257,7 @@ def build_ueg_test_case_handlers(options: dict, # 4. Build walkers. walkers = UHFThermalWalkers( - trial, nbasis, nwalkers, nstack=nstack, lowrank=lowrank, + trial, nbasis, nwalkers, stack_size=stack_size, lowrank=lowrank, lowrank_thresh=lowrank_thresh, verbose=verbose) # 5. Build propagator. @@ -286,7 +286,7 @@ def build_driver_ueg_test_instance(options: Union[dict, None], beta = options['beta'] timestep = options['timestep'] nwalkers = options.get('nwalkers', 100) - nstack = options.get('nstack', 10) + stack_size = options.get('stack_size', 10) nblocks = options.get('nblocks', 100) stabilize_freq = options.get('stabilize_freq', 5) pop_control_freq = options.get('pop_control_freq', 1) @@ -326,7 +326,7 @@ def build_driver_ueg_test_instance(options: Union[dict, None], # 4. Build Thermal AFQMC driver. afqmc = ThermalAFQMC.build( nelec, mu, beta, hamiltonian, trial, nwalkers=nwalkers, - nstack=nstack, seed=seed, nblocks=nblocks, timestep=timestep, + stack_size=stack_size, seed=seed, nblocks=nblocks, timestep=timestep, stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, pop_control_method=pop_control_method, lowrank=lowrank, lowrank_thresh=lowrank_thresh, debug=debug, verbose=verbose) diff --git a/ipie/addons/thermal/walkers/stack.py b/ipie/addons/thermal/walkers/stack.py index 529c284a..dc23637c 100644 --- a/ipie/addons/thermal/walkers/stack.py +++ b/ipie/addons/thermal/walkers/stack.py @@ -6,7 +6,7 @@ class PropagatorStack: def __init__( self, - nstack, + stack_size, nslice, nbasis, dtype, @@ -18,9 +18,9 @@ def __init__( thresh=1e-6, ): self.time_slice = 0 - self.nstack = nstack + self.stack_size = stack_size self.nslice = nslice - self.stack_length = self.nslice // self.nstack + self.nstack = self.nslice // self.stack_size self.nbasis = nbasis self.diagonal_trial = diagonal self.averaging = averaging @@ -32,9 +32,9 @@ def __init__( if self.lowrank: assert diagonal - if self.stack_length * self.nstack < self.nslice: - print("nstack must divide the total path length") - assert self.stack_length * self.nstack == self.nslice + if self.nstack * self.stack_size < self.nslice: + print("stack_size must divide the total path length") + assert self.nstack * self.stack_size == self.nslice self.dtype = dtype self.BT = BT @@ -42,9 +42,9 @@ def __init__( self.counter = 0 self.block = 0 - self.stack = numpy.zeros((self.stack_length, 2, nbasis, nbasis), dtype=dtype) - self.left = numpy.zeros((self.stack_length, 2, nbasis, nbasis), dtype=dtype) - self.right = numpy.zeros((self.stack_length, 2, nbasis, nbasis), dtype=dtype) + self.stack = numpy.zeros((self.nstack, 2, nbasis, nbasis), dtype=dtype) + self.left = numpy.zeros((self.nstack, 2, nbasis, nbasis), dtype=dtype) + self.right = numpy.zeros((self.nstack, 2, nbasis, nbasis), dtype=dtype) self.G = numpy.asarray([numpy.eye(self.nbasis, dtype=dtype), # Ga numpy.eye(self.nbasis, dtype=dtype)]) # Gb @@ -111,7 +111,7 @@ def set_all(self, BT): # Diagonal = True assumes BT is diagonal and left is also diagonal if self.diagonal_trial: for i in range(0, self.nslice): - ix = i // self.nstack # bin index + ix = i // self.stack_size # bin index # Commenting out these two. It is only useful for Hubbard self.left[ix, 0] = numpy.diag( numpy.multiply(BT[0].diagonal(), self.left[ix, 0].diagonal()) @@ -123,7 +123,7 @@ def set_all(self, BT): self.stack[ix, 1] = self.left[ix, 1].copy() else: for i in range(0, self.nslice): - ix = i // self.nstack # bin index + ix = i // self.stack_size # bin index self.left[ix, 0] = numpy.dot(BT[0], self.left[ix, 0]) self.left[ix, 1] = numpy.dot(BT[1], self.left[ix, 1]) self.stack[ix, 0] = self.left[ix, 0].copy() @@ -139,7 +139,7 @@ def set_all(self, BT): def reset(self): self.time_slice = 0 self.block = 0 - for i in range(0, self.stack_length): + for i in range(0, self.nstack): self.stack[i, 0] = numpy.identity(self.nbasis, dtype=self.dtype) self.stack[i, 1] = numpy.identity(self.nbasis, dtype=self.dtype) self.right[i, 0] = numpy.identity(self.nbasis, dtype=self.dtype) @@ -165,8 +165,8 @@ def initialize_left(self): self.Ql[spin] = numpy.identity(B[spin].shape[0]) self.Tl[spin] = numpy.identity(B[spin].shape[0]) - # for ix in range(2, self.stack_length): - for ix in range(1, self.stack_length): + # for ix in range(2, self.nstack): + for ix in range(1, self.nstack): B = self.stack[ix] C2 = numpy.einsum("ii,i->i", B[spin], self.Dl[spin]) self.Dl[spin] = C2 @@ -178,8 +178,8 @@ def update(self, B): self.stack[self.block, 0] = B[0].dot(self.stack[self.block, 0]) self.stack[self.block, 1] = B[1].dot(self.stack[self.block, 1]) self.time_slice += 1 - self.block = self.time_slice // self.nstack - self.counter = (self.counter + 1) % self.nstack + self.block = self.time_slice // self.stack_size + self.counter = (self.counter + 1) % self.stack_size def update_full_rank(self, B): # Diagonal = True assumes BT is diagonal and left is also diagonal @@ -213,8 +213,8 @@ def update_full_rank(self, B): self.stack[self.block, 1] = self.left[self.block, 1].dot(self.right[self.block, 1]) self.time_slice += 1 # Count the time slice - self.block = self.time_slice // self.nstack # Move to the next block if necessary - self.counter = (self.counter + 1) % self.nstack # Counting within a stack + self.block = self.time_slice // self.stack_size # Move to the next block if necessary + self.counter = (self.counter + 1) % self.stack_size # Counting within a stack def update_low_rank(self, B): assert not self.averaging @@ -228,7 +228,7 @@ def update_low_rank(self, B): mR = B.shape[-1] # initial mR mL = B.shape[-1] # initial mR mT = B.shape[-1] # initial mR - next_block = (self.time_slice + 1) // self.nstack # move to the next block if necessary + next_block = (self.time_slice + 1) // self.stack_size # move to the next block if necessary # print("next_block", next_block) # print("self.block", self.block) if next_block > self.block: # Do QR and update here? @@ -386,5 +386,5 @@ def update_low_rank(self, B): # print("ovlp = {}".format(self.ovlp)) self.mT = mT self.time_slice += 1 # Count the time slice - self.block = self.time_slice // self.nstack # move to the next block if necessary - self.counter = (self.counter + 1) % self.nstack # Counting within a stack + self.block = self.time_slice // self.stack_size # move to the next block if necessary + self.counter = (self.counter + 1) % self.stack_size # Counting within a stack diff --git a/ipie/addons/thermal/walkers/uhf_walkers.py b/ipie/addons/thermal/walkers/uhf_walkers.py index a05c1424..1c14462d 100644 --- a/ipie/addons/thermal/walkers/uhf_walkers.py +++ b/ipie/addons/thermal/walkers/uhf_walkers.py @@ -15,7 +15,7 @@ def __init__( trial: OneBody, nbasis: int, nwalkers: int, - nstack = None, + stack_size = None, lowrank: bool = False, lowrank_thresh: float = 1e-6, mpi_handler = None, @@ -29,22 +29,22 @@ def __init__( self.nbasis = nbasis self.mpi_handler = mpi_handler self.nslice = trial.nslice - self.nstack = nstack + self.stack_size = stack_size - if self.nstack == None: - self.nstack = trial.nstack + if self.stack_size == None: + self.stack_size = trial.stack_size - if (self.nslice // self.nstack) * self.nstack != self.nslice: + if (self.nslice // self.stack_size) * self.stack_size != self.nslice: if verbose: print("# Input stack size does not divide number of slices.") - self.nstack = update_stack(self.nstack, self.nslice, verbose) + self.stack_size = update_stack(self.stack_size, self.nslice, verbose) - if self.nstack > trial.nstack: + if self.stack_size > trial.stack_size: if verbose: print("# Walker stack size differs from that estimated from trial density matrix.") - print(f"# Be careful. cond(BT)**nstack: {trial.cond ** self.nstack:10.3e}.") + print(f"# Be careful. cond(BT)**stack_size: {trial.cond ** self.stack_size:10.3e}.") - self.stack_length = self.nslice // self.nstack + self.stack_length = self.nslice // self.stack_size self.lowrank = lowrank self.lowrank_thresh = lowrank_thresh @@ -70,11 +70,11 @@ def __init__( print("# Trial density matrix is not diagonal.") if verbose: - print(f"# Walker stack size: {self.nstack}") + print(f"# Walker stack size: {self.stack_size}") print(f"# Using low rank trick: {self.lowrank}") self.stack = [PropagatorStack( - self.nstack, + self.stack_size, self.nslice, self.nbasis, numpy.complex128, From c4e93baa7773db195b2a95ce7ef3e0f8083005c9 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 4 Apr 2024 11:34:13 -0400 Subject: [PATCH 74/84] Fixed imaginary time trace by using the entire GF in `print_cut` --- examples/14-ft_afqmc/run_afqmc.py | 4 +- ipie/addons/thermal/estimators/energy.py | 3 +- .../thermal/estimators/particle_number.py | 3 +- ipie/addons/thermal/qmc/tests/run_legacy.py | 229 ++++-------------- ipie/addons/thermal/qmc/thermal_afqmc.py | 13 +- ipie/addons/thermal/utils/legacy_testing.py | 3 +- 6 files changed, 57 insertions(+), 198 deletions(-) diff --git a/examples/14-ft_afqmc/run_afqmc.py b/examples/14-ft_afqmc/run_afqmc.py index ac29e9ce..272da7e4 100644 --- a/examples/14-ft_afqmc/run_afqmc.py +++ b/examples/14-ft_afqmc/run_afqmc.py @@ -41,11 +41,11 @@ 'qmc': { 'mu': 0.133579, 'beta': 10., - 'timestep': 1., + 'timestep': 0.5, 'nwalkers': 12 // comm.size, 'stack_size': 10, 'seed': 7, - 'nblocks': 50, + 'nblocks': 20, }, } diff --git a/ipie/addons/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py index e9164f9f..6f87fc1d 100644 --- a/ipie/addons/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -32,7 +32,8 @@ def local_energy( energies = xp.zeros((walkers.nwalkers, 3), dtype=xp.complex128) for iw in range(walkers.nwalkers): - walkers.calc_greens_function(iw) # In-place update of GF. + # Want the full Green's function when calculating observables. + walkers.calc_greens_function(iw, slice_ix=walkers.stack[iw].nslice) P = one_rdm_from_G(xp.array([walkers.Ga[iw], walkers.Gb[iw]])) energy = local_energy_generic_cholesky(hamiltonian, P) diff --git a/ipie/addons/thermal/estimators/particle_number.py b/ipie/addons/thermal/estimators/particle_number.py index 174e6934..5df96be6 100644 --- a/ipie/addons/thermal/estimators/particle_number.py +++ b/ipie/addons/thermal/estimators/particle_number.py @@ -47,7 +47,8 @@ def __init__(self, hamiltonian=None, trial=None, filename=None): def compute_estimator(self, walkers, hamiltonian, trial): for iw in range(walkers.nwalkers): - walkers.calc_greens_function(iw) + # Want the full Green's function when calculating observables. + walkers.calc_greens_function(iw, slice_ix=walkers.stack[iw].nslice) nav_iw = particle_number(one_rdm_from_G( xp.array([walkers.Ga[iw], walkers.Gb[iw]]))) self._data["NavNumer"] += walkers.weight[iw] * nav_iw.real diff --git a/ipie/addons/thermal/qmc/tests/run_legacy.py b/ipie/addons/thermal/qmc/tests/run_legacy.py index b2345635..96acadfc 100644 --- a/ipie/addons/thermal/qmc/tests/run_legacy.py +++ b/ipie/addons/thermal/qmc/tests/run_legacy.py @@ -2,40 +2,19 @@ import os import sys import tempfile -import h5py import uuid -import pytest import numpy from typing import Tuple, Union -from pyscf import gto, scf, lo from ipie.config import MPI -from ipie.systems.generic import Generic -from ipie.hamiltonians.utils import get_hamiltonian -from ipie.qmc.options import QMCOpts - -from ipie.thermal.trial.mean_field import MeanField -from ipie.thermal.trial.one_body import OneBody -from ipie.thermal.walkers.uhf_walkers import UHFThermalWalkers -from ipie.thermal.propagation.phaseless_generic import PhaselessGeneric -from ipie.thermal.qmc.options import ThermalQMCParams -from ipie.thermal.qmc.thermal_afqmc import ThermalAFQMC -from ipie.thermal.estimators.energy import local_energy +from ipie.addons.thermal.utils.testing import build_driver_ueg_test_instance +from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_ueg_test_instance from ipie.analysis.extraction import ( extract_test_data_hdf5, extract_data, extract_observable, extract_mixed_estimates) -from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField -from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody -from ipie.legacy.walkers.thermal import ThermalWalker -from ipie.legacy.thermal_propagation.continuous import Continuous -from ipie.legacy.estimators.generic import local_energy_generic_cholesky as legacy_local_energy_generic_cholesky -from ipie.legacy.estimators.thermal import one_rdm_from_G as legacy_one_rdm_from_G -from ipie.legacy.qmc.thermal_afqmc import ThermalAFQMC as LegacyThermalAFQMC - comm = MPI.COMM_WORLD serial_test = comm.size == 1 @@ -49,189 +28,71 @@ test_id = comm.bcast(test_id, root=0) -def build_legacy_driver_instance(nelec: Tuple[int, int], - hamiltonian, - options: Union[dict, None] = None, - seed: Union[int, None] = None, - verbose: bool = False): - if seed is not None: - numpy.random.seed(seed) - - # Unpack options - nup, ndown = nelec - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] - - legacy_options = { - "qmc": { - "dt": timestep, - "nwalkers": nwalkers, - "blocks": nblocks, - "nsteps": nsteps_per_block, - "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, - "stabilise_freq": stabilize_freq, - "batched": False - }, - - "propagator": { - "optimised": False - }, - - "walkers": { - "low_rank": lowrank, - "pop_control": pop_control_method - }, - - "system": { - "name": "Generic", - "nup": nup, - "ndown": ndown, - "mu": mu - }, - - "hamiltonian": options["hamiltonian"], - "estimators": options["estimators"] - } - - legacy_system = Generic(nelec) - legacy_system.mu = mu - legacy_hamiltonian = LegacyHamGeneric( - h1e=hamiltonian.H1, - chol=hamiltonian.chol, - ecore=hamiltonian.ecore, - options=legacy_options["hamiltonian"]) - legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) - legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( - (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - legacy_hamiltonian._alt_convention = legacy_options["hamiltonian"]["_alt_convention"] - legacy_hamiltonian.mu = legacy_options["hamiltonian"]["mu"] - legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep) - - legacy_walkers = [ - ThermalWalker( - legacy_system, legacy_hamiltonian, legacy_trial, - walker_opts=options, verbose=i == 0) for i in range(nwalkers)] - - #legacy_hamiltonian.chol_vecs = legacy_hamiltonian.chol_vecs.T.reshape( - # (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) - afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, - legacy_hamiltonian, legacy_trial, verbose=verbose) - return afqmc - - -def build_driver_test_instance(nelec: Tuple[int, int], - options: Union[dict, None] = None, - seed: Union[int, None] = None, - debug: bool = False, - verbose: bool = False): - if seed is not None: - numpy.random.seed(seed) - - # Unpack options - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - nsteps_per_block = options['nsteps_per_block'] - nblocks = options['nblocks'] - stabilize_freq = options['stabilize_freq'] - pop_control_freq = options['pop_control_freq'] - pop_control_method = options['pop_control_method'] - lowrank = options['lowrank'] - - params = ThermalQMCParams( - num_walkers=nwalkers, - total_num_walkers=nwalkers * comm.size, - num_blocks=nblocks, - num_steps_per_block=nsteps_per_block, - timestep=timestep, - beta=beta, - num_stblz=stabilize_freq, - pop_control_freq=pop_control_freq, - pop_control_method=pop_control_method, - rng_seed=seed) - - system = Generic(nelec) - hamiltonian = get_hamiltonian(system, options["hamiltonian"]) - trial = MeanField(hamiltonian, nelec, beta, timestep) - - nbasis = trial.dmat.shape[-1] - walkers = UHFThermalWalkers(trial, nbasis, nwalkers, lowrank=lowrank) - propagator = PhaselessGeneric(timestep, mu, lowrank=lowrank) - propagator.build(hamiltonian, trial=trial, walkers=walkers) - - eloc = local_energy(hamiltonian, walkers) - print(f'# Initial energy = {eloc[0]}') - - afqmc = ThermalAFQMC(system, hamiltonian, trial, walkers, propagator, - params, debug=debug, verbose=verbose) - return afqmc, hamiltonian, walkers - - def run_legacy(): - ref_path = "reference_data/generic/" + # UEG params. + nup = 1 + ndown = 1 + nelec = (nup, ndown) + rs = 3 + ecut = 0.5 # Thermal AFQMC params. - nocca = 5 - noccb = 5 - nelec = (nocca, noccb) - - mu = -10.0 - beta = 0.1 - timestep = 0.01 - nwalkers = 9 - seed = 7 - nsteps_per_block = 10 + mu = 2.158847 + beta = 1 + timestep = 0.05 + nwalkers = 12 // comm.size + # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! + nsteps_per_block = 1 nblocks = 10 - stabilize_freq = 10 pop_control_freq = 1 - pop_control_method = 'comb' + pop_control_method = "pair_branch" + #pop_control_method = "comb" lowrank = False - verbose = True + lowrank_thresh = 1e-14 + stack_size = 10 + optimised = False + + verbose = False if (comm.rank != 0) else True debug = True - - with tempfile.NamedTemporaryFile() as tmpf: + seed = 7 + numpy.random.seed(seed) + + with tempfile.NamedTemporaryFile() as tmpf1: options = { + 'nelec': nelec, 'mu': mu, 'beta': beta, 'timestep': timestep, 'nwalkers': nwalkers, - 'seed': 7, + 'seed': seed, 'nsteps_per_block': nsteps_per_block, 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, 'pop_control_freq': pop_control_freq, 'pop_control_method': pop_control_method, 'lowrank': lowrank, - - "hamiltonian": { - "name": "Generic", - "integrals": ref_path + "generic_integrals.h5", - "_alt_convention": False, - "symmetry": False, - "sparse": False, - "mu": mu + 'lowrank_thresh': lowrank_thresh, + 'stack_size': stack_size, + 'optimised': optimised, + + "ueg_opts": { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank }, "estimators": { - "filename": tmpf.name, - } + "filename": tmpf1.name, # For legacy. + }, } - + # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- - afqmc, hamiltonian, walkers = build_driver_test_instance(nelec, options, seed, debug, verbose) + afqmc = build_driver_ueg_test_instance(options, seed, debug, verbose) # --------------------------------------------------------------------- # Legacy. @@ -239,7 +100,8 @@ def run_legacy(): print('\n------------------------------') print('Running Legacy ThermalAFQMC...') print('------------------------------') - legacy_afqmc = build_legacy_driver_instance(nelec, hamiltonian, options, seed, verbose) + legacy_afqmc = build_legacy_driver_ueg_test_instance( + afqmc.hamiltonian, comm, options, seed, verbose) legacy_afqmc.run(comm=comm) legacy_afqmc.finalise(verbose=False) legacy_afqmc.estimators.estimators["mixed"].update( @@ -258,7 +120,6 @@ def run_legacy(): if verbose: print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 7b9ba660..8cdd48b5 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -252,16 +252,11 @@ def run(self, self.tpopc_non_comm = self.pcontrol.timer.non_communication_time # Print cut. - self.estimators.compute_estimators( - self.hamiltonian, self.trial, self.walkers) - - #if comm.rank == 0: - #print(self.walkers.stack[0].time_slice) - - self.estimators.print_cut( - comm, step // self.params.num_steps_per_block, t, self.accumulators) + #self.estimators.compute_estimators( + # self.hamiltonian, self.trial, self.walkers) + #self.estimators.print_cut( + # comm, step // self.params.num_steps_per_block, t, self.accumulators) - # Accumulate weight, hybrid energy etc. across block. start = time.time() self.accumulators.update(self.walkers) diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index 9d98dff2..0723ae3b 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -400,6 +400,7 @@ def build_legacy_driver_ueg_test_instance(hamiltonian, pop_control_method = options.get('pop_control_method', 'pair_branch') lowrank = options.get('lowrank', False) lowrank_thresh = options.get('lowrank_thresh', 1e-6) + optimised = options.get('optimised', False) alt_convention = options.get('alt_convention', False) numpy.random.seed(seed) @@ -419,7 +420,7 @@ def build_legacy_driver_ueg_test_instance(hamiltonian, }, "propagator": { - "optimised": False + "optimised": optimised }, "walkers": { From 3b8b70fddfb4147bce992b7feb3f07f324d0c43c Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 4 Apr 2024 12:36:56 -0400 Subject: [PATCH 75/84] Fix example. --- examples/{14-ft_afqmc => 16-ft_afqmc}/run_afqmc.py | 0 examples/{14-ft_afqmc => 16-ft_afqmc}/ueg.py | 0 ipie/addons/thermal/qmc/calc.py | 1 + 3 files changed, 1 insertion(+) rename examples/{14-ft_afqmc => 16-ft_afqmc}/run_afqmc.py (100%) rename examples/{14-ft_afqmc => 16-ft_afqmc}/ueg.py (100%) diff --git a/examples/14-ft_afqmc/run_afqmc.py b/examples/16-ft_afqmc/run_afqmc.py similarity index 100% rename from examples/14-ft_afqmc/run_afqmc.py rename to examples/16-ft_afqmc/run_afqmc.py diff --git a/examples/14-ft_afqmc/ueg.py b/examples/16-ft_afqmc/ueg.py similarity index 100% rename from examples/14-ft_afqmc/ueg.py rename to examples/16-ft_afqmc/ueg.py diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index 96b677c0..02858b21 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -116,6 +116,7 @@ def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: trial, walkers, propagator, + mpi_handler, params, debug=debug, verbose=verbosity, From de780e6033bdbbdd0cd0f43c99dfbd4fb7f37989 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 7 Apr 2024 20:31:20 -0400 Subject: [PATCH 76/84] Define `ThermalQMCOpts` and `ThermalPopController`. Replaced input dictionary `options` in `utils/*testing.py` with args/kwargs. Addressed other review comments. --- ipie/addons/thermal/estimators/energy.py | 4 +- ipie/addons/thermal/estimators/handler.py | 2 - .../estimators/tests/test_estimators.py | 49 +- .../thermal/estimators/tests/test_generic.py | 45 +- .../estimators/tests/test_generic_complex.py | 51 +-- ipie/addons/thermal/estimators/thermal.py | 19 - .../thermal/propagation/phaseless_base.py | 10 +- .../propagation/tests/test_operations.py | 116 ----- .../propagation/tests/test_prop_generic.py | 66 ++- .../propagation/tests/ueg/test_prop_ueg.py | 45 +- ipie/addons/thermal/qmc/calc.py | 6 +- ipie/addons/thermal/qmc/options.py | 96 +++- .../thermal/qmc/tests/test_afqmc_generic.py | 41 +- .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 139 ++---- ipie/addons/thermal/qmc/thermal_afqmc.py | 4 +- ipie/addons/thermal/trial/mean_field.py | 10 +- ipie/addons/thermal/trial/one_body.py | 8 +- .../thermal/trial/tests/test_chem_pot.py | 6 +- .../thermal/trial/tests/test_mean_field.py | 36 +- ipie/addons/thermal/utils/legacy_testing.py | 328 +++++++------- ipie/addons/thermal/utils/testing.py | 230 +++++----- ipie/addons/thermal/walkers/pop_controller.py | 425 ++++++++++++++++++ .../walkers/tests/test_population_control.py | 148 ++---- .../walkers/tests/test_thermal_walkers.py | 115 ++--- ipie/qmc/options.py | 99 ++-- .../tests/test_single_det_trial.py | 4 +- ipie/walkers/pop_controller.py | 28 +- 27 files changed, 1098 insertions(+), 1032 deletions(-) delete mode 100644 ipie/addons/thermal/propagation/tests/test_operations.py create mode 100644 ipie/addons/thermal/walkers/pop_controller.py diff --git a/ipie/addons/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py index 6f87fc1d..e727477a 100644 --- a/ipie/addons/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -36,9 +36,7 @@ def local_energy( walkers.calc_greens_function(iw, slice_ix=walkers.stack[iw].nslice) P = one_rdm_from_G(xp.array([walkers.Ga[iw], walkers.Gb[iw]])) energy = local_energy_generic_cholesky(hamiltonian, P) - - for i in range(3): - energies[iw, i] = energy[i] + energies[iw] = energy return energies diff --git a/ipie/addons/thermal/estimators/handler.py b/ipie/addons/thermal/estimators/handler.py index 40fc7802..a8cd091d 100644 --- a/ipie/addons/thermal/estimators/handler.py +++ b/ipie/addons/thermal/estimators/handler.py @@ -1,7 +1,5 @@ """Routines and classes for estimation of observables.""" -from __future__ import print_function - import os from typing import Tuple, Union diff --git a/ipie/addons/thermal/estimators/tests/test_estimators.py b/ipie/addons/thermal/estimators/tests/test_estimators.py index cb12338e..64501699 100644 --- a/ipie/addons/thermal/estimators/tests/test_estimators.py +++ b/ipie/addons/thermal/estimators/tests/test_estimators.py @@ -24,49 +24,25 @@ beta = 0.1 timestep = 0.01 nwalkers = 10 -# Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! -nsteps_per_block = 1 -nblocks = 12 -stabilize_freq = 10 -pop_control_freq = 1 -pop_control_method = 'pair_branch' -#pop_control_method = 'comb' lowrank = False -verbose = True +mf_trial = True complex_integrals = False debug = True -mf_trial = True -propagate = False +verbose = True seed = 7 numpy.random.seed(seed) -options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - } - @pytest.mark.unit def test_energy_estimator(): # Test. print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] @@ -122,8 +98,10 @@ def test_number_estimator(): print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - options['complex_integrals'] = True - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=True, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] @@ -146,14 +124,15 @@ def test_number_estimator(): @pytest.mark.unit def test_estimator_handler(): - options['complex_integrals'] = True - with tempfile.NamedTemporaryFile() as tmp1, tempfile.NamedTemporaryFile() as tmp2: # Test. print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=True, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] diff --git a/ipie/addons/thermal/estimators/tests/test_generic.py b/ipie/addons/thermal/estimators/tests/test_generic.py index 337318fe..2bba34ea 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic.py +++ b/ipie/addons/thermal/estimators/tests/test_generic.py @@ -33,58 +33,29 @@ def test_local_energy_cholesky(mf_trial=False): beta = 0.1 timestep = 0.01 nwalkers = 12 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 12 - stabilize_freq = 10 - pop_control_freq = 1 - pop_control_method = 'pair_branch' - #pop_control_method = 'comb' lowrank = False - verbose = True + mf_trial = True complex_integrals = False debug = True - mf_trial = True - propagate = False + verbose = True seed = 7 numpy.random.seed(seed) - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - } - # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] P = one_rdm_from_G(trial.G) eloc = local_energy_generic_cholesky(hamiltonian, P) # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) + hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, + lowrank=lowrank, mf_trial=mf_trial, seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] diff --git a/ipie/addons/thermal/estimators/tests/test_generic_complex.py b/ipie/addons/thermal/estimators/tests/test_generic_complex.py index a33b3744..74e37ac6 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/addons/thermal/estimators/tests/test_generic_complex.py @@ -19,50 +19,22 @@ beta = 0.1 timestep = 0.01 nwalkers = 12 -# Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! -nsteps_per_block = 1 -nblocks = 12 -stabilize_freq = 10 -pop_control_freq = 1 -pop_control_method = 'pair_branch' -#pop_control_method = 'comb' lowrank = False -verbose = True +mf_trial = True complex_integrals = False debug = True -mf_trial = True -propagate = False +verbose = True seed = 7 numpy.random.seed(seed) -options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - } - - @pytest.mark.unit def test_local_energy_vs_real(): # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] walkers = objs['walkers'] hamiltonian = objs['hamiltonian'] @@ -87,12 +59,10 @@ def test_local_energy_vs_real(): @pytest.mark.unit def test_local_energy_vs_eri(): # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - options['complex_integrals'] = True - objs = build_generic_test_case_handlers(options, seed, debug, with_eri=True, - verbose=verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, debug=debug, complex_integrals=True, with_eri=True, + seed=seed, verbose=verbose) trial = objs['trial'] walkers = objs['walkers'] hamiltonian = objs['hamiltonian'] @@ -108,7 +78,6 @@ def test_local_energy_vs_eri(): numpy.testing.assert_allclose(eri, eri_chol, atol=1e-10) for iw in range(walkers.nwalkers): - print(iw) P = one_rdm_from_G(numpy.array([walkers.Ga[iw], walkers.Gb[iw]])) Pa, Pb = P Ptot = Pa + Pb diff --git a/ipie/addons/thermal/estimators/thermal.py b/ipie/addons/thermal/estimators/thermal.py index 90312880..65ee4cad 100644 --- a/ipie/addons/thermal/estimators/thermal.py +++ b/ipie/addons/thermal/estimators/thermal.py @@ -1,9 +1,6 @@ import numpy import scipy.linalg -def fermi_factor(ek, beta, mu): - return 1.0 / (numpy.exp(beta * (ek - mu)) + 1.0) - def one_rdm_from_G(G): r"""Compute one-particle reduced density matrix from Green's function. @@ -70,19 +67,3 @@ def one_rdm_stable(BT, num_slices): # Q is unitary. G.append(numpy.dot(numpy.dot(T1inv, Cinv), numpy.einsum("ii,ij->ij", Db, Q1.conj().T))) return one_rdm_from_G(numpy.array(G)) - -def entropy(beta, mu, H): - """Compute the entropy. - """ - assert numpy.linalg.norm(H[0] - H[1]) < 1e-12 - eigs, _ = numpy.linalg.eigh(H[0]) - p_i = fermi_factor(eigs, beta, mu) - S = -2.0 * sum(p * numpy.log(p) + (1 - p) * numpy.log(1 - p) for p in p_i) - # muN = mu * numpy.eye(H[0].shape[-1], dtype=H[0].dtype) - # rho = numpy.array([scipy.linalg.expm(-beta*(H[0]-muN)), - # scipy.linalg.expm(-beta*(H[1]-muN))]) - # W = rho[0] + rho[1] - # W = W / W.trace() - # logW = -numpy.trace(scipy.linalg.logm(W)) - # S = -numpy.trace(numpy.dot(W,logW)) - return S diff --git a/ipie/addons/thermal/propagation/phaseless_base.py b/ipie/addons/thermal/propagation/phaseless_base.py index 6896d50e..0696d39f 100644 --- a/ipie/addons/thermal/propagation/phaseless_base.py +++ b/ipie/addons/thermal/propagation/phaseless_base.py @@ -6,12 +6,13 @@ import scipy.linalg from abc import abstractmethod +from ipie.utils.backend import arraylib as xp from ipie.propagation.continuous_base import ContinuousBase +from ipie.propagation.operations import apply_exponential +from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol + from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.addons.thermal.propagation.force_bias import construct_force_bias -from ipie.addons.thermal.propagation.operations import apply_exponential -from ipie.utils.backend import arraylib as xp -from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol # TODO: Add lowrank implementation. # Ref: 10.1103/PhysRevB.80.214116 for bounds. @@ -210,7 +211,8 @@ def propagate_walkers(self, walkers, hamiltonian, trial, eshift=0., debug=False) start_time = time.time() for iw in range(walkers.nwalkers): stack = walkers.stack[iw] - BV = apply_exponential(VHS[iw], self.exp_nmax) # Shape (nbasis, nbasis). + phi = xp.identity(VHS[iw].shape[-1], dtype=xp.complex128) + BV = apply_exponential(phi, VHS[iw], self.exp_nmax) # Shape (nbasis, nbasis). B = numpy.array([BV.dot(self.BH1[0]), BV.dot(self.BH1[1])]) B = numpy.array([self.BH1[0].dot(B[0]), self.BH1[1].dot(B[1])]) diff --git a/ipie/addons/thermal/propagation/tests/test_operations.py b/ipie/addons/thermal/propagation/tests/test_operations.py deleted file mode 100644 index dca76528..00000000 --- a/ipie/addons/thermal/propagation/tests/test_operations.py +++ /dev/null @@ -1,116 +0,0 @@ -import numpy -import pytest - -try: - from ipie.addons.thermal.utils.legacy_testing import build_legacy_generic_test_case_handlers - from ipie.addons.thermal.utils.legacy_testing import legacy_propagate_walkers - _no_cython = False - -except ModuleNotFoundError: - _no_cython = True - -from ipie.config import MPI -from ipie.addons.thermal.propagation.operations import apply_exponential -from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers - -comm = MPI.COMM_WORLD - -@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") -@pytest.mark.unit -def test_apply_exponential(): - # System params. - nup = 5 - ndown = 5 - nelec = (nup, ndown) - nbasis = 10 - - # Thermal AFQMC params. - mu = -10. - beta = 0.1 - timestep = 0.01 - nwalkers = 12 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 12 - stabilize_freq = 10 - pop_control_freq = 1 - pop_control_method = 'pair_branch' - #pop_control_method = 'comb' - lowrank = False - - verbose = True - complex_integrals = False - debug = True - mf_trial = True - propagate = False - seed = 7 - numpy.random.seed(seed) - - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - } - - # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) - trial = objs['trial'] - hamiltonian = objs['hamiltonian'] - walkers = objs['walkers'] - propagator = objs['propagator'] - - # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_objs = build_legacy_generic_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) - legacy_system = legacy_objs['system'] - legacy_trial = legacy_objs['trial'] - legacy_hamiltonian = legacy_objs['hamiltonian'] - legacy_walkers = legacy_objs['walkers'] - legacy_propagator = legacy_objs['propagator'] - - _, _, _, VHS = propagator.construct_two_body_propagator(walkers, hamiltonian, trial, debug=True) - - exp = [] - legacy_exp = [] - for iw in range(walkers.nwalkers): - _, _, _, _VHS = legacy_propagator.two_body_propagator( - legacy_walkers.walkers[iw], legacy_hamiltonian, - legacy_trial, xi=propagator.xi[iw]) - _exp = apply_exponential(VHS[iw], propagator.exp_nmax) - _legacy_exp = legacy_propagator.exponentiate(_VHS, debug=True) - exp.append(_exp) - legacy_exp.append(_legacy_exp) - numpy.testing.assert_allclose(_VHS, VHS[iw]) - - exp = numpy.array(exp) - legacy_exp = numpy.array(legacy_exp) - - if verbose: - print(f'\nexp_nmax = {propagator.exp_nmax}') - print(f'legacy_exp = \n{legacy_exp}\n') - print(f'exp = \n{exp}\n') - - numpy.testing.assert_almost_equal(legacy_exp, exp, decimal=10) - - -if __name__ == "__main__": - test_apply_exponential() diff --git a/ipie/addons/thermal/propagation/tests/test_prop_generic.py b/ipie/addons/thermal/propagation/tests/test_prop_generic.py index de68068b..dcb4c597 100644 --- a/ipie/addons/thermal/propagation/tests/test_prop_generic.py +++ b/ipie/addons/thermal/propagation/tests/test_prop_generic.py @@ -30,42 +30,16 @@ beta = 0.1 timestep = 0.01 nwalkers = 12 -# Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! -nsteps_per_block = 1 nblocks = 12 -stabilize_freq = 10 -pop_control_freq = 1 -pop_control_method = 'pair_branch' -#pop_control_method = 'comb' lowrank = False -verbose = True +mf_trial = True complex_integrals = False debug = True -mf_trial = True -propagate = False +verbose = True seed = 7 numpy.random.seed(seed) -options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - } - @pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit @@ -74,7 +48,10 @@ def test_mf_shift(): print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) hamiltonian = objs['hamiltonian'] propagator = objs['propagator'] @@ -83,7 +60,9 @@ def test_mf_shift(): print('Constructing legacy objects...') print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) + hamiltonian, comm, nelec, mu, beta, timestep, + nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, + seed=seed, verbose=verbose) legacy_propagator = legacy_objs['propagator'] if verbose: @@ -101,7 +80,10 @@ def test_BH1(): print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) hamiltonian = objs['hamiltonian'] propagator = objs['propagator'] @@ -110,7 +92,9 @@ def test_BH1(): print('Constructing legacy objects...') print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) + hamiltonian, comm, nelec, mu, beta, timestep, + nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, + seed=seed, verbose=verbose) legacy_propagator = legacy_objs['propagator'] if verbose: @@ -128,7 +112,10 @@ def test_construct_two_body_propagator(): print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] @@ -139,7 +126,9 @@ def test_construct_two_body_propagator(): print('Constructing legacy objects...') print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) + hamiltonian, comm, nelec, mu, beta, timestep, + nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, + seed=seed, verbose=verbose) legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] legacy_walkers = legacy_objs['walkers'] @@ -190,7 +179,10 @@ def test_phaseless_generic_propagator(): print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] @@ -201,7 +193,9 @@ def test_phaseless_generic_propagator(): print('Constructing legacy objects...') print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) + hamiltonian, comm, nelec, mu, beta, timestep, + nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, + seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index 73428f5f..af8bb823 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -35,54 +35,20 @@ def test_phaseless_ueg_propagator(): beta = 0.1 timestep = 0.01 nwalkers = 1 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 11 - stabilize_freq = 10 - pop_control_freq = 1 - - # `pop_control_method` doesn't matter for 1 walker. - pop_control_method = "pair_branch" - #pop_control_method = "comb" lowrank = False - propagate = False - verbose = False if (comm.rank != 0) else True debug = True + verbose = False if (comm.rank != 0) else True seed = 7 numpy.random.seed(seed) - options = { - 'nelec': nelec, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'propagate': propagate, - - "ueg_opts": { - "nup": nup, - "ndown": ndown, - "rs": rs, - "ecut": ecut, - "thermal": True, - "write_integrals": False, - "low_rank": lowrank - }, - } - # Test. print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - objs = build_ueg_test_case_handlers(options, seed, debug, verbose) + objs = build_ueg_test_case_handlers( + nelec, rs, ecut, mu, beta, timestep, nwalkers=nwalkers, + lowrank=lowrank, debug=debug, seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] @@ -93,7 +59,8 @@ def test_phaseless_ueg_propagator(): print('Constructing legacy objects...') print('------------------------------') legacy_objs = build_legacy_ueg_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) + comm, nelec, rs, ecut, mu, beta, timestep, nwalkers=nwalkers, + lowrank=lowrank, seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index 02858b21..86c1cec2 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -11,7 +11,7 @@ from ipie.addons.thermal.trial.utils import get_trial_density_matrix from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers from ipie.addons.thermal.propagation.propagator import Propagator -from ipie.addons.thermal.qmc.options import ThermalQMCParams +from ipie.addons.thermal.qmc.options import ThermalQMCOpts, ThermalQMCParams from ipie.addons.thermal.qmc.thermal_afqmc import ThermalAFQMC @@ -60,9 +60,7 @@ def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: if (lowrank == True) or (batched == True): raise ValueError("Option not supported in thermal code.") else: - from ipie.qmc.options import QMCOpts - - qmc = QMCOpts(qmc_opts, verbose=0) + qmc = ThermalQMCOpts(qmc_opts, verbose=0) mpi_handler = MPIHandler(nmembers=qmc_opts.get("nmembers", 1), verbose=verbosity) system = get_system( sys_opts, verbose=verbosity, comm=comm diff --git a/ipie/addons/thermal/qmc/options.py b/ipie/addons/thermal/qmc/options.py index d9bb548f..e87ce3d5 100644 --- a/ipie/addons/thermal/qmc/options.py +++ b/ipie/addons/thermal/qmc/options.py @@ -1,28 +1,94 @@ from dataclasses import dataclass from typing import ClassVar -from ipie.qmc.options import QMCParams +from ipie.utils.io import get_input_value +from ipie.qmc.options import QMCOpts, QMCParams _no_default = object() +class ThermalQMCOpts(QMCOpts): + r"""Input options and certain constants / parameters derived from them. + + Initialised from a dict containing the following options, not all of which + are required. + + Attributes + ---------- + batched : bool + Whether to do batched calculations. + nwalkers : int + Number of walkers to propagate in a simulation. + dt : float + Timestep. + nsteps : int + Number of steps per block. + nblocks : int + Number of blocks. Total number of iterations = nblocks * nsteps. + nstblz : int + Frequency of Gram-Schmidt orthogonalisation steps. + npop_control : int + Frequency of population control. + pop_control_method : str + Population control method. + eqlb_time : float + Time scale of equilibration phase. Only used to fix local + energy bound when using phaseless approximation. + neqlb : int + Number of time steps for the equilibration phase. Only used to fix the + local energy bound when using phaseless approximation. + rng_seed : int + The random number seed. + mu : float + Chemical potential. + beta : float + Inverse temperature. + """ + # pylint: disable=dangerous-default-value + # TODO: Remove this class / replace with dataclass + def __init__(self, inputs={}, verbose=False): + super().__init__(inputs, verbose) + + self.mu = get_input_value( + inputs, + "mu", + default=None, + verbose=verbose, + ) + self.beta = get_input_value( + inputs, + "beta", + default=None, + verbose=verbose, + ) + + @dataclass class ThermalQMCParams(QMCParams): r"""Input options and certain constants / parameters derived from them. - Args: - mu: chemical potential. - beta: inverse temperature. - num_walkers: number of walkers **per** core / task / computational unit. - total_num_walkers: The total number of walkers in the simulation. - timestep: The timestep delta_t - num_steps_per_block: Number of steps of propagation before estimators - are evaluated. - num_blocks: The number of blocks. Total number of iterations = - num_blocks * num_steps_per_block. - num_stblz: number of steps before QR stabilization of walkers is performed. - pop_control_freq: Frequency at which population control occurs. - rng_seed: The random number seed. If run in parallel the seeds on other - cores / threads are determined from this. + Attributes + ---------- + mu : float + Chemical potential. + beta : float + Inverse temperature. + num_walkers : int + Number of walkers **per** core / task / computational unit. + total_num_walkers : int + The total number of walkers in the simulation. + timestep : float + The timestep delta_t + num_steps_per_block : int + Number of steps of propagation before estimators are evaluated. + num_blocks : int + Number of blocks. Total number of iterations = num_blocks * num_steps_per_block. + num_stblz : int + Number of steps before QR stabilization of walkers is performed. + pop_control_freq : int + Frequency at which population control occurs. + rng_seed : int + The random number seed. If run in parallel the seeds on other cores / + threads are determined from this. """ # Due to structure of FT algorithm, `num_steps_per_block` is fixed at 1. # Overide whatever input for backward compatibility. diff --git a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py index 3c6cd468..c3313b0d 100644 --- a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py +++ b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py @@ -48,8 +48,6 @@ def test_thermal_afqmc(): beta = 0.1 timestep = 0.01 nwalkers = 32 // comm.size - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 nblocks = 12 stabilize_freq = 10 pop_control_freq = 1 @@ -58,33 +56,13 @@ def test_thermal_afqmc(): lowrank = False verbose = 0 if (comm.rank != 0) else 1 + # Local energy evaluation in legacy code seems wrong. complex_integrals = False debug = True seed = 7 numpy.random.seed(seed) with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - - "estimators": { - "filename": tmpf2.name, # For legacy. - }, - } - # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- @@ -93,7 +71,12 @@ def test_thermal_afqmc(): print('Running ThermalAFQMC...') print('-----------------------') - afqmc = build_driver_generic_test_instance(options, seed, debug, verbose) + afqmc = build_driver_generic_test_instance( + nelec, nbasis, mu, beta, timestep, nblocks, nwalkers=nwalkers, + lowrank=lowrank, pop_control_method=pop_control_method, + stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, + complex_integrals=complex_integrals, debug=debug, seed=seed, + verbose=verbose) afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) afqmc.finalise() afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) @@ -118,7 +101,12 @@ def test_thermal_afqmc(): print('------------------------------') legacy_afqmc = build_legacy_driver_generic_test_instance( - afqmc.hamiltonian, comm, options, seed, verbose) + afqmc.hamiltonian, comm, nelec, mu, beta, timestep, + nblocks, nwalkers=nwalkers, lowrank=lowrank, + stabilize_freq=stabilize_freq, + pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, seed=seed, + estimator_filename=tmpf2.name, verbose=verbose) legacy_afqmc.run(comm=comm) legacy_afqmc.finalise(verbose=False) legacy_afqmc.estimators.estimators["mixed"].update( @@ -141,8 +129,7 @@ def test_thermal_afqmc(): legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - print(f'test filename: {afqmc.estimators.filename}') + print(f'\ntest filename: {afqmc.estimators.filename}') print(f'legacy filename: {legacy_afqmc.estimators.filename}') print(f'\ntest_energy_data: \n{test_energy_data}\n') print(f'test_number_data: \n{test_number_data}\n') diff --git a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index ccb210f0..8497ad08 100644 --- a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -85,12 +85,10 @@ def test_thermal_afqmc_1walker(against_ref=False): beta = 0.1 timestep = 0.01 nwalkers = 1 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 nblocks = 11 + stabilize_freq = 10 pop_control_freq = 1 - # `pop_control_method` doesn't matter for 1 walker. pop_control_method = "pair_branch" #pop_control_method = "comb" @@ -102,35 +100,6 @@ def test_thermal_afqmc_1walker(against_ref=False): numpy.random.seed(seed) with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: - options = { - 'nelec': nelec, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - - "ueg_opts": { - "nup": nup, - "ndown": ndown, - "rs": rs, - "ecut": ecut, - "thermal": True, - "write_integrals": False, - "low_rank": lowrank - }, - - "estimators": { - "filename": tmpf2.name, # For legacy. - }, - } - # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- @@ -139,7 +108,11 @@ def test_thermal_afqmc_1walker(against_ref=False): print('Running ThermalAFQMC...') print('-----------------------') - afqmc = build_driver_ueg_test_instance(options, seed, debug, verbose) + afqmc = build_driver_ueg_test_instance( + nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, + lowrank=lowrank, pop_control_method=pop_control_method, + stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, + debug=debug, seed=seed, verbose=verbose) afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) afqmc.finalise() afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) @@ -164,7 +137,12 @@ def test_thermal_afqmc_1walker(against_ref=False): print('------------------------------') legacy_afqmc = build_legacy_driver_ueg_test_instance( - afqmc.hamiltonian, comm, options, seed, verbose) + comm, nelec, rs, ecut, mu, beta, timestep, nblocks, + nwalkers=nwalkers, lowrank=lowrank, + stabilize_freq=stabilize_freq, + pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, seed=seed, + estimator_filename=tmpf2.name, verbose=verbose) legacy_afqmc.run(comm=comm) legacy_afqmc.finalise(verbose=False) legacy_afqmc.estimators.estimators["mixed"].update( @@ -187,8 +165,7 @@ def test_thermal_afqmc_1walker(against_ref=False): legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - print(f'test filename: {afqmc.estimators.filename}') + print(f'\ntest filename: {afqmc.estimators.filename}') print(f'legacy filename: {legacy_afqmc.estimators.filename}') print(f'\ntest_energy_data: \n{test_energy_data}\n') print(f'test_number_data: \n{test_number_data}\n') @@ -289,35 +266,6 @@ def test_thermal_afqmc(against_ref=False): numpy.random.seed(seed) with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: - options = { - 'nelec': nelec, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - - "ueg_opts": { - "nup": nup, - "ndown": ndown, - "rs": rs, - "ecut": ecut, - "thermal": True, - "write_integrals": False, - "low_rank": lowrank - }, - - "estimators": { - "filename": tmpf2.name, # For legacy. - }, - } - # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- @@ -326,7 +274,11 @@ def test_thermal_afqmc(against_ref=False): print('Running ThermalAFQMC...') print('-----------------------') - afqmc = build_driver_ueg_test_instance(options, seed, debug, verbose) + afqmc = build_driver_ueg_test_instance( + nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, + lowrank=lowrank, pop_control_method=pop_control_method, + stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, + debug=debug, seed=seed, verbose=verbose) afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) afqmc.finalise() afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) @@ -351,7 +303,12 @@ def test_thermal_afqmc(against_ref=False): print('------------------------------') legacy_afqmc = build_legacy_driver_ueg_test_instance( - afqmc.hamiltonian, comm, options, seed, verbose) + comm, nelec, rs, ecut, mu, beta, timestep, nblocks, + nwalkers=nwalkers, lowrank=lowrank, + stabilize_freq=stabilize_freq, + pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, seed=seed, + estimator_filename=tmpf2.name, verbose=verbose) legacy_afqmc.run(comm=comm) legacy_afqmc.finalise(verbose=False) legacy_afqmc.estimators.estimators["mixed"].update( @@ -374,8 +331,7 @@ def test_thermal_afqmc(against_ref=False): legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - print(f'test filename: {afqmc.estimators.filename}') + print(f'\ntest filename: {afqmc.estimators.filename}') print(f'legacy filename: {legacy_afqmc.estimators.filename}') print(f'\ntest_energy_data: \n{test_energy_data}\n') print(f'test_number_data: \n{test_number_data}\n') @@ -476,35 +432,6 @@ def test_thermal_afqmc_mpi(against_ref=False): numpy.random.seed(seed) with tempfile.NamedTemporaryFile() as tmpf1, tempfile.NamedTemporaryFile() as tmpf2: - options = { - 'nelec': nelec, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - - "ueg_opts": { - "nup": nup, - "ndown": ndown, - "rs": rs, - "ecut": ecut, - "thermal": True, - "write_integrals": False, - "low_rank": lowrank - }, - - "estimators": { - "filename": tmpf2.name, # For legacy. - }, - } - # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- @@ -513,7 +440,11 @@ def test_thermal_afqmc_mpi(against_ref=False): print('Running ThermalAFQMC...') print('-----------------------') - afqmc = build_driver_ueg_test_instance(options, seed, debug, verbose) + afqmc = build_driver_ueg_test_instance( + nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, + lowrank=lowrank, pop_control_method=pop_control_method, + stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, + debug=debug, seed=seed, verbose=verbose) afqmc.run(verbose=verbose, estimator_filename=tmpf1.name) afqmc.finalise() afqmc.estimators.compute_estimators(afqmc.hamiltonian, afqmc.trial, afqmc.walkers) @@ -538,7 +469,12 @@ def test_thermal_afqmc_mpi(against_ref=False): print('------------------------------') legacy_afqmc = build_legacy_driver_ueg_test_instance( - afqmc.hamiltonian, comm, options, seed, verbose) + comm, nelec, rs, ecut, mu, beta, timestep, nblocks, + nwalkers=nwalkers, lowrank=lowrank, + stabilize_freq=stabilize_freq, + pop_control_freq=pop_control_freq, + pop_control_method=pop_control_method, seed=seed, + estimator_filename=tmpf2.name, verbose=verbose) legacy_afqmc.run(comm=comm) legacy_afqmc.finalise(verbose=False) legacy_afqmc.estimators.estimators["mixed"].update( @@ -561,8 +497,7 @@ def test_thermal_afqmc_mpi(against_ref=False): legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - print(f'test filename: {afqmc.estimators.filename}') + print(f'\ntest filename: {afqmc.estimators.filename}') print(f'legacy filename: {legacy_afqmc.estimators.filename}') print(f'\ntest_energy_data: \n{test_energy_data}\n') print(f'test_number_data: \n{test_number_data}\n') diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 801612fa..d4cfbd1e 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -5,6 +5,7 @@ import uuid from typing import Dict, Optional, Tuple +from ipie.addons.thermal.walkers.pop_controller import ThermalPopController from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers from ipie.addons.thermal.propagation.propagator import Propagator from ipie.addons.thermal.estimators.handler import ThermalEstimatorHandler @@ -18,7 +19,6 @@ from ipie.utils.mpi import MPIHandler from ipie.systems.generic import Generic from ipie.estimators.estimator_base import EstimatorBase -from ipie.walkers.pop_controller import PopController from ipie.walkers.base_walkers import WalkerAccumulator from ipie.qmc.afqmc import AFQMC @@ -188,7 +188,7 @@ def run(self, if walkers is not None: self.walkers = walkers - self.pcontrol = PopController( + self.pcontrol = ThermalPopController( self.params.num_walkers, self.params.num_steps_per_block, self.mpi_handler, diff --git a/ipie/addons/thermal/trial/mean_field.py b/ipie/addons/thermal/trial/mean_field.py index 6983db2c..e6207c3a 100644 --- a/ipie/addons/thermal/trial/mean_field.py +++ b/ipie/addons/thermal/trial/mean_field.py @@ -16,7 +16,7 @@ def __init__(self, hamiltonian, nelec, beta, dt, options=None, alt_convention=Fa OneBody.__init__(self, hamiltonian, nelec, beta, dt, options=options, alt_convention=alt_convention, H1=H1, verbose=verbose) if verbose: - print(" # Building THF density matrix.") + print("# Building THF density matrix.") self.alpha = options.get("alpha", 0.75) self.max_scf_it = options.get("max_scf_it", self.max_it) @@ -49,14 +49,14 @@ def thermal_hartree_fock(self, hamiltonian, beta): scipy.linalg.expm(-dt * HMF[1])]) if self.find_mu: mu = find_chemical_potential( - self.alt_convention, rho, dt, self.stack_length, self.nav, + self.alt_convention, rho, dt, self.nstack, self.nav, deps=self.deps, max_it=self.max_it, verbose=self.verbose) else: mu = self.mu rho_mu = compute_rho(rho, mu_old, dt) - P = one_rdm_stable(rho_mu, self.stack_length) + P = one_rdm_stable(rho_mu, self.nstack) dmu = abs(mu - mu_old) if self.verbose: @@ -76,7 +76,7 @@ def scf(self, hamiltonian, beta, mu, P): muN = mu * numpy.eye(hamiltonian.nbasis, dtype=self.G.dtype) rho = numpy.array([scipy.linalg.expm(-dt * (HMF[0] - muN)), scipy.linalg.expm(-dt * (HMF[1] - muN))]) - Pold = one_rdm_stable(rho, self.stack_length) + Pold = one_rdm_stable(rho, self.nstack) if self.verbose: print("# Running Thermal SCF.") @@ -85,7 +85,7 @@ def scf(self, hamiltonian, beta, mu, P): HMF = fock_generic(hamiltonian, Pold) rho = numpy.array([scipy.linalg.expm(-dt * (HMF[0] - muN)), scipy.linalg.expm(-dt * (HMF[1] - muN))]) - Pnew = (1 - self.alpha) * one_rdm_stable(rho, self.stack_length) + self.alpha * Pold + Pnew = (1 - self.alpha) * one_rdm_stable(rho, self.nstack) + self.alpha * Pold change = numpy.linalg.norm(Pnew - Pold) if change < self.deps: diff --git a/ipie/addons/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py index e650ac68..c06603ce 100644 --- a/ipie/addons/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -76,10 +76,10 @@ def __init__(self, hamiltonian, nelec, beta, dt, options=None, # Adjust stack size self.stack_size = update_stack(self.stack_size, self.nslice, verbose=verbose) - self.stack_length = int(beta / (self.stack_size * dt)) + self.nstack = int(beta / (self.stack_size * dt)) if verbose: - print(f"# Number of stacks: {self.stack_length}") + print(f"# Number of stacks: {self.nstack}") sign = 1 if self.alt_convention: @@ -94,7 +94,7 @@ def __init__(self, hamiltonian, nelec, beta, dt, options=None, self.rho = numpy.array([scipy.linalg.expm(-self.dtau * (self.H1[0])), scipy.linalg.expm(-self.dtau * (self.H1[1]))]) self.mu = find_chemical_potential( - self.alt_convention, self.rho, self.dtau, self.stack_length, + self.alt_convention, self.rho, self.dtau, self.nstack, self.nav, deps=self.deps, max_it=self.max_it, verbose=verbose) else: @@ -104,7 +104,7 @@ def __init__(self, hamiltonian, nelec, beta, dt, options=None, if self.verbose: print(f"# Chemical potential in trial density matrix: {self.mu: .10e}") - self.P = one_rdm_stable(compute_rho(self.rho, self.mu, self.dtau, sign=sign), self.stack_length) + self.P = one_rdm_stable(compute_rho(self.rho, self.mu, self.dtau, sign=sign), self.nstack) self.nav = particle_number(self.P).real if self.verbose: diff --git a/ipie/addons/thermal/trial/tests/test_chem_pot.py b/ipie/addons/thermal/trial/tests/test_chem_pot.py index b0a4b809..bbb4f7bb 100644 --- a/ipie/addons/thermal/trial/tests/test_chem_pot.py +++ b/ipie/addons/thermal/trial/tests/test_chem_pot.py @@ -11,7 +11,7 @@ def test_find_chemical_potential(): dt = 0.01 beta = 1 stack_size = 3 - stack_length = 20 + nstack = 20 nav = 7 nbsf = 14 alt_convention = False @@ -21,8 +21,8 @@ def test_find_chemical_potential(): rho = numpy.array([scipy.linalg.expm(-dtau * h1e), scipy.linalg.expm(-dtau * h1e)]) - mu = find_chemical_potential(alt_convention, rho, dt, stack_length, nav) - legacy_mu = legacy_find_chemical_potential(alt_convention, rho, dt, stack_length, nav) + mu = find_chemical_potential(alt_convention, rho, dt, nstack, nav) + legacy_mu = legacy_find_chemical_potential(alt_convention, rho, dt, nstack, nav) numpy.testing.assert_allclose(mu, legacy_mu) diff --git a/ipie/addons/thermal/trial/tests/test_mean_field.py b/ipie/addons/thermal/trial/tests/test_mean_field.py index 61bbd158..e668d1e4 100644 --- a/ipie/addons/thermal/trial/tests/test_mean_field.py +++ b/ipie/addons/thermal/trial/tests/test_mean_field.py @@ -4,8 +4,14 @@ from ipie.systems.generic import Generic from ipie.utils.testing import generate_hamiltonian from ipie.hamiltonians.generic import Generic as HamGeneric + from ipie.addons.thermal.trial.mean_field import MeanField +from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric +from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField + + + @pytest.mark.unit def test_mean_field(): @@ -17,7 +23,9 @@ def test_mean_field(): mu = -10. beta = 0.1 timestep = 0.01 - + + alt_convention = False + sparse = False complex_integrals = True verbose = True @@ -36,6 +44,25 @@ def test_mean_field(): ecore=0) trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) + # Lgeacy. + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_system = Generic(nelec, verbose=verbose) + legacy_system.mu = mu + legacy_hamiltonian = LegacyHamGeneric( + h1e=hamiltonian.H1, + chol=hamiltonian.chol, + ecore=hamiltonian.ecore, verbose=verbose) + legacy_hamiltonian.hs_pot = numpy.copy(hamiltonian.chol) + legacy_hamiltonian.hs_pot = legacy_hamiltonian.hs_pot.T.reshape( + (hamiltonian.nchol, hamiltonian.nbasis, hamiltonian.nbasis)) + legacy_hamiltonian.mu = mu + legacy_hamiltonian._alt_convention = alt_convention + legacy_hamiltonian.sparse = sparse + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, + timestep, verbose=verbose) + assert trial.nelec == nelec numpy.testing.assert_almost_equal(trial.nav, numpy.sum(nelec), decimal=5) assert trial.rho.shape == (2, nbasis, nbasis) @@ -43,6 +70,13 @@ def test_mean_field(): assert trial.P.shape == (2, nbasis, nbasis) assert trial.G.shape == (2, nbasis, nbasis) + numpy.testing.assert_allclose(trial.mu, legacy_trial.mu) + numpy.testing.assert_allclose(trial.nav, legacy_trial.nav) + numpy.testing.assert_allclose(trial.P, legacy_trial.P) + numpy.testing.assert_allclose(trial.G, legacy_trial.G) + numpy.testing.assert_allclose(trial.dmat, legacy_trial.dmat) + numpy.testing.assert_allclose(trial.dmat_inv, legacy_trial.dmat_inv) + if __name__ == '__main__': test_mean_field() diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index 0723ae3b..bc854f63 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -1,11 +1,12 @@ import numpy import pytest -from typing import Union +from typing import Tuple, Union from ipie.systems.generic import Generic -from ipie.qmc.options import QMCOpts from ipie.utils.mpi import MPIHandler +from ipie.addons.thermal.qmc.options import ThermalQMCOpts + from ipie.legacy.systems.ueg import UEG as LegacyUEG from ipie.legacy.hamiltonians.ueg import UEG as LegacyHamUEG from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric @@ -29,31 +30,26 @@ def legacy_propagate_walkers(legacy_hamiltonian, legacy_trial, legacy_walkers, l return legacy_walkers -def build_legacy_generic_test_case_handlers(hamiltonian, - comm, - options: dict, - seed: Union[int, None], - verbose: bool = False): - # Unpack options - nelec = options['nelec'] - nbasis = options['nbasis'] - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - nsteps_per_block = 1 - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - alt_convention = options.get('alt_convention', False) - sparse = options.get('sparse', False) - - mf_trial = options.get('mf_trial', True) - propagate = options.get('propagate', False) +def build_legacy_generic_test_case_handlers( + hamiltonian, + comm, + nelec: Tuple[int, int], + mu: float, + beta: float, + timestep: float, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + stabilize_freq: int = 5, + pop_control_freq: int = 5, + pop_control_method: str = 'pair_branch', + alt_convention: bool = False, + sparse: bool = False, + mf_trial: bool = True, + propagate: bool = False, + seed: Union[int, None] = None, + verbose: int = 0): numpy.random.seed(seed) legacy_options = { @@ -61,7 +57,6 @@ def build_legacy_generic_test_case_handlers(hamiltonian, "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, - "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, @@ -87,18 +82,21 @@ def build_legacy_generic_test_case_handlers(hamiltonian, legacy_hamiltonian.sparse = sparse # 3. Build trial. - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, - verbose=verbose) + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, + timestep, verbose=verbose) if mf_trial: - legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep, - verbose=verbose) + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, + timestep, verbose=verbose) # 4. Build walkers. - qmc_opts = QMCOpts() + qmc_opts = ThermalQMCOpts() qmc_opts.nwalkers = nwalkers qmc_opts.ntot_walkers = nwalkers qmc_opts.beta = beta - qmc_opts.nsteps = nsteps_per_block + qmc_opts.nsteps = 1 qmc_opts.dt = timestep + qmc_opts.nstblz = stabilize_freq + qmc_opts.npop_control = pop_control_freq + qmc_opts.pop_control_method = pop_control_method qmc_opts.seed = seed legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, @@ -125,31 +123,26 @@ def build_legacy_generic_test_case_handlers(hamiltonian, return legacy_objs -def build_legacy_generic_test_case_handlers_mpi(hamiltonian, - mpi_handler: MPIHandler, - options: dict, - seed: Union[int, None], - verbose: bool = False): - # Unpack options - nelec = options['nelec'] - nbasis = options['nbasis'] - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - nsteps_per_block = 1 - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - alt_convention = options.get('alt_convention', False) - sparse = options.get('sparse', False) - - mf_trial = options.get('mf_trial', True) - propagate = options.get('propagate', False) +def build_legacy_generic_test_case_handlers_mpi( + hamiltonian, + mpi_handler: MPIHandler, + nelec: Tuple[int, int], + mu: float, + beta: float, + timestep: float, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + stabilize_freq: int = 5, + pop_control_freq: int = 5, + pop_control_method: str = 'pair_branch', + alt_convention: bool = False, + sparse: bool = False, + mf_trial: bool = True, + propagate: bool = False, + seed: Union[int, None] = None, + verbose: int = 0): numpy.random.seed(seed) comm = mpi_handler.comm @@ -158,7 +151,6 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, - "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, @@ -184,18 +176,21 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, legacy_hamiltonian.sparse = sparse # 3. Build trial. - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, - verbose=verbose) + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, + timestep, verbose=verbose) if mf_trial: - legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, timestep, - verbose=verbose) + legacy_trial = LegacyMeanField(legacy_system, legacy_hamiltonian, beta, + timestep, verbose=verbose) # 4. Build walkers. - qmc_opts = QMCOpts() + qmc_opts = ThermalQMCOpts() qmc_opts.nwalkers = nwalkers qmc_opts.ntot_walkers = nwalkers * comm.size qmc_opts.beta = beta - qmc_opts.nsteps = nsteps_per_block + qmc_opts.nsteps = 1 qmc_opts.dt = timestep + qmc_opts.nstblz = stabilize_freq + qmc_opts.npop_control = pop_control_freq + qmc_opts.pop_control_method = pop_control_method qmc_opts.seed = seed legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, @@ -222,28 +217,27 @@ def build_legacy_generic_test_case_handlers_mpi(hamiltonian, return legacy_objs -def build_legacy_driver_generic_test_instance(hamiltonian, - comm, - options: Union[dict, None], - seed: Union[int, None], - verbose: bool = False): - # Unpack options - nelec = options['nelec'] +def build_legacy_driver_generic_test_instance( + hamiltonian, + comm, + nelec: Tuple[int, int], + mu: float, + beta: float, + timestep: float, + nblocks: int, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + stabilize_freq: int = 5, + pop_control_freq: int = 5, + pop_control_method: str = 'pair_branch', + alt_convention: bool = False, + sparse: bool = False, + seed: Union[int, None] = None, + estimator_filename: Union[str, None] = None, + verbose: int = 0): nup, ndown = nelec - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options['nwalkers'] - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - nsteps_per_block = 1 - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - alt_convention = options.get('alt_convention', False) - sparse = options.get('sparse', False) numpy.random.seed(seed) legacy_options = { @@ -253,11 +247,12 @@ def build_legacy_driver_generic_test_instance(hamiltonian, # legacy `ThermalAFQMC`. "nwalkers": nwalkers * comm.size, "blocks": nblocks, - "nsteps": nsteps_per_block, + "nsteps": 1, "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, "stabilise_freq": stabilize_freq, + "pop_control_freq": pop_control_freq, + "pop_control_method": pop_control_method, + "rng_seed": seed, "batched": False }, @@ -269,7 +264,6 @@ def build_legacy_driver_generic_test_instance(hamiltonian, "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, - "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, @@ -280,7 +274,9 @@ def build_legacy_driver_generic_test_instance(hamiltonian, "mu": mu }, - "estimators": options["estimators"] + "estimators": { + "filename": estimator_filename, + }, } legacy_system = Generic(nelec) @@ -302,30 +298,39 @@ def build_legacy_driver_generic_test_instance(hamiltonian, return afqmc -def build_legacy_ueg_test_case_handlers(hamiltonian, - comm, - options: dict, - seed: Union[int, None], - verbose: bool = False): - # Unpack options - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - nsteps_per_block = 1 - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - alt_convention = options.get('alt_convention', False) - - propagate = options.get('propagate', False) +def build_legacy_ueg_test_case_handlers( + comm, + nelec: Tuple[int, int], + rs: float, + ecut: float, + mu: float, + beta: float, + timestep: float, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + propagate: bool = False, + stabilize_freq: int = 5, + pop_control_freq: int = 5, + pop_control_method: str = 'pair_branch', + alt_convention: bool = False, + sparse: bool = False, + seed: Union[int, None] = None, + verbose: int = 0): numpy.random.seed(seed) - + nup, ndown = nelec legacy_options = { + "ueg": { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + }, + "propagator": { "optimised": False }, @@ -334,30 +339,33 @@ def build_legacy_ueg_test_case_handlers(hamiltonian, "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, - "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, } # 1. Build out system. - legacy_system = LegacyUEG(options=options["ueg_opts"]) + legacy_system = LegacyUEG(options=legacy_options['ueg']) legacy_system.mu = mu # 2. Build Hamiltonian. - legacy_hamiltonian = LegacyHamUEG(legacy_system, options=options["ueg_opts"]) + legacy_hamiltonian = LegacyHamUEG(legacy_system, options=legacy_options['ueg']) legacy_hamiltonian.mu = mu legacy_hamiltonian._alt_convention = alt_convention # 3. Build trial. - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, + timestep, verbose=verbose) # 4. Build walkers. - qmc_opts = QMCOpts() + qmc_opts = ThermalQMCOpts() qmc_opts.nwalkers = nwalkers qmc_opts.ntot_walkers = nwalkers * comm.size qmc_opts.beta = beta - qmc_opts.nsteps = nsteps_per_block + qmc_opts.nsteps = 1 qmc_opts.dt = timestep + qmc_opts.nstblz = stabilize_freq + qmc_opts.npop_control = pop_control_freq + qmc_opts.pop_control_method = pop_control_method qmc_opts.seed = seed legacy_walkers = Walkers(legacy_system, legacy_hamiltonian, legacy_trial, @@ -365,8 +373,9 @@ def build_legacy_ueg_test_case_handlers(hamiltonian, verbose=verbose, comm=comm) # 5. Build propagator. - legacy_propagator = PlaneWave(legacy_system, legacy_hamiltonian, legacy_trial, qmc_opts, - options=legacy_options["propagator"], lowrank=lowrank, verbose=verbose) + legacy_propagator = PlaneWave(legacy_system, legacy_hamiltonian, legacy_trial, + qmc_opts, options=legacy_options["propagator"], + lowrank=lowrank, verbose=verbose) if propagate: for t in range(legacy_walkers[0].stack.ntime_slices): @@ -382,70 +391,83 @@ def build_legacy_ueg_test_case_handlers(hamiltonian, return legacy_objs -def build_legacy_driver_ueg_test_instance(hamiltonian, - comm, - options: Union[dict, None], - seed: Union[int, None], - verbose: bool = False): - # Unpack options - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - nsteps_per_block = 1 - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - optimised = options.get('optimised', False) - alt_convention = options.get('alt_convention', False) +def build_legacy_driver_ueg_test_instance( + comm, + nelec: Tuple[int, int], + rs: float, + ecut: float, + mu: float, + beta: float, + timestep: float, + nblocks: int, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + stabilize_freq: int = 5, + pop_control_freq: int = 5, + pop_control_method: str = 'pair_branch', + alt_convention: bool = False, + sparse: bool = False, + seed: Union[int, None] = None, + estimator_filename: Union[str, None] = None, + verbose: int = 0): numpy.random.seed(seed) - + nup, ndown = nelec legacy_options = { + "ueg": { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + }, + "qmc": { "dt": timestep, # Input of `nwalkers` refers to the total number of walkers in # legacy `ThermalAFQMC`. "nwalkers": nwalkers * comm.size, "blocks": nblocks, - "nsteps": nsteps_per_block, + "nsteps": 1, "beta": beta, - "rng_seed": seed, - "pop_control_freq": pop_control_freq, "stabilise_freq": stabilize_freq, + "pop_control_freq": pop_control_freq, + "pop_control_method": pop_control_method, + "rng_seed": seed, "batched": False }, "propagator": { - "optimised": optimised + "optimised": False }, "walkers": { "stack_size": stack_size, "low_rank": lowrank, "low_rank_thresh": lowrank_thresh, - "pop_control_freq": pop_control_freq, "pop_control": pop_control_method }, - "ueg_opts": options["ueg_opts"], - "estimators": options["estimators"] + "estimators": { + "filename": estimator_filename, + }, } # 1. Build out system. - legacy_system = LegacyUEG(options=legacy_options["ueg_opts"]) + legacy_system = LegacyUEG(options=legacy_options['ueg']) legacy_system.mu = mu # 2. Build Hamiltonian. - legacy_hamiltonian = LegacyHamUEG(legacy_system, options=legacy_options["ueg_opts"]) + legacy_hamiltonian = LegacyHamUEG(legacy_system, options=legacy_options['ueg']) legacy_hamiltonian.mu = mu legacy_hamiltonian._alt_convention = alt_convention # 3. Build trial. - legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, timestep, verbose=verbose) + legacy_trial = LegacyOneBody(legacy_system, legacy_hamiltonian, beta, + timestep, verbose=verbose) # 4. Build Thermal AFQMC. afqmc = LegacyThermalAFQMC(comm, legacy_options, legacy_system, diff --git a/ipie/addons/thermal/utils/testing.py b/ipie/addons/thermal/utils/testing.py index 59920b6e..faaa1fbd 100644 --- a/ipie/addons/thermal/utils/testing.py +++ b/ipie/addons/thermal/utils/testing.py @@ -1,6 +1,6 @@ import numpy import pytest -from typing import Union +from typing import Tuple, Union from ipie.utils.mpi import MPIHandler from ipie.utils.testing import generate_hamiltonian @@ -15,31 +15,24 @@ from ipie.addons.thermal.qmc.thermal_afqmc import ThermalAFQMC -def build_generic_test_case_handlers(options: dict, - seed: Union[int, None], - debug: bool = False, - with_eri: bool = False, - verbose: int = 0): - # Unpack options - nelec = options['nelec'] - nbasis = options['nbasis'] - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - - complex_integrals = options.get('complex_integrals', True) - mf_trial = options.get('mf_trial', True) - propagate = options.get('propagate', False) - diagonal = options.get('diagonal', False) - +def build_generic_test_case_handlers( + nelec: Tuple[int, int], + nbasis: int, + mu: float, + beta: float, + timestep: float, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + diagonal: bool = False, + mf_trial: bool = True, + propagate: bool = False, + complex_integrals: bool = False, + debug: bool = False, + with_eri: bool = False, + seed: Union[int, None] = None, + verbose: int = 0): sym = 8 if complex_integrals: sym = 4 numpy.random.seed(seed) @@ -86,31 +79,24 @@ def build_generic_test_case_handlers(options: dict, return objs -def build_generic_test_case_handlers_mpi(options: dict, - mpi_handler: MPIHandler, - seed: Union[int, None], - debug: bool = False, - verbose: int = 0): - # Unpack options - nelec = options['nelec'] - nbasis = options['nbasis'] - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - - complex_integrals = options.get('complex_integrals', True) - mf_trial = options.get('mf_trial', True) - propagate = options.get('propagate', False) - diagonal = options.get('diagonal', False) - +def build_generic_test_case_handlers_mpi( + nelec: Tuple[int, int], + nbasis: int, + mu: float, + beta: float, + timestep: float, + mpi_handler: MPIHandler, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + diagonal: bool = False, + mf_trial: bool = True, + propagate: bool = False, + complex_integrals: bool = False, + debug: bool = False, + seed: Union[int, None] = None, + verbose: int = 0): sym = 8 if complex_integrals: sym = 4 numpy.random.seed(seed) @@ -154,28 +140,25 @@ def build_generic_test_case_handlers_mpi(options: dict, return objs -def build_driver_generic_test_instance(options: Union[dict, None], - seed: Union[int, None], - debug: bool = False, - verbose: int = 0): - # Unpack options - nelec = options['nelec'] - nbasis = options['nbasis'] - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - - complex_integrals = options.get('complex_integrals', True) - diagonal = options.get('diagonal', False) - +def build_driver_generic_test_instance( + nelec: Tuple[int, int], + nbasis: int, + mu: float, + beta: float, + timestep: float, + nblocks: int, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + stabilize_freq: int = 5, + pop_control_freq: int = 5, + pop_control_method: str = 'pair_branch', + diagonal: bool = False, + complex_integrals: bool = False, + debug: bool = False, + seed: Union[int, None] = None, + verbose: int = 0): sym = 8 if complex_integrals: sym = 4 numpy.random.seed(seed) @@ -199,32 +182,38 @@ def build_driver_generic_test_instance(options: Union[dict, None], afqmc = ThermalAFQMC.build( nelec, mu, beta, hamiltonian, trial, nwalkers=nwalkers, stack_size=stack_size, seed=seed, nblocks=nblocks, timestep=timestep, - stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, + stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, pop_control_method=pop_control_method, lowrank=lowrank, lowrank_thresh=lowrank_thresh, debug=debug, verbose=verbose) return afqmc -def build_ueg_test_case_handlers(options: dict, - seed: Union[int, None], - debug: bool = False, - verbose: int = 0): - # Unpack options - ueg_opts = options['ueg_opts'] - nelec = options['nelec'] - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 101) - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) - - propagate = options.get('propagate', False) +def build_ueg_test_case_handlers( + nelec: Tuple[int, int], + rs: float, + ecut: float, + mu: float, + beta: float, + timestep: float, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + propagate: bool = False, + debug: bool = False, + seed: Union[int, None] = None, + verbose: int = 0): + nup, ndown = nelec + ueg_opts = { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + } + numpy.random.seed(seed) # 1. Generate UEG integrals. @@ -232,7 +221,6 @@ def build_ueg_test_case_handlers(options: dict, ueg.build(verbose=verbose) nbasis = ueg.nbasis nchol = ueg.nchol - nup, ndown = nelec if verbose: print(f"# nbasis = {nbasis}") @@ -242,7 +230,6 @@ def build_ueg_test_case_handlers(options: dict, h1 = ueg.H1[0] chol = 2. * ueg.chol_vecs.toarray().copy() - #ecore = ueg.ecore ecore = 0. # 2. Build Hamiltonian. @@ -275,24 +262,35 @@ def build_ueg_test_case_handlers(options: dict, return objs -def build_driver_ueg_test_instance(options: Union[dict, None], - seed: Union[int, None], - debug: bool = False, - verbose: int = 0): - # Unpack options - ueg_opts = options['ueg_opts'] - nelec = options['nelec'] - mu = options['mu'] - beta = options['beta'] - timestep = options['timestep'] - nwalkers = options.get('nwalkers', 100) - stack_size = options.get('stack_size', 10) - nblocks = options.get('nblocks', 100) - stabilize_freq = options.get('stabilize_freq', 5) - pop_control_freq = options.get('pop_control_freq', 1) - pop_control_method = options.get('pop_control_method', 'pair_branch') - lowrank = options.get('lowrank', False) - lowrank_thresh = options.get('lowrank_thresh', 1e-6) +def build_driver_ueg_test_instance( + nelec: Tuple[int, int], + rs: float, + ecut: float, + mu: float, + beta: float, + timestep: float, + nblocks: int, + nwalkers: int = 100, + stack_size: int = 10, + lowrank: bool = False, + lowrank_thresh: float = 1e-6, + stabilize_freq: int = 5, + pop_control_freq: int = 5, + pop_control_method: str = 'pair_branch', + debug: bool = False, + seed: Union[int, None] = None, + verbose: int = 0): + nup, ndown = nelec + ueg_opts = { + "nup": nup, + "ndown": ndown, + "rs": rs, + "ecut": ecut, + "thermal": True, + "write_integrals": False, + "low_rank": lowrank + } + numpy.random.seed(seed) # 1. Generate UEG integrals. @@ -300,7 +298,6 @@ def build_driver_ueg_test_instance(options: Union[dict, None], ueg.build(verbose=verbose) nbasis = ueg.nbasis nchol = ueg.nchol - nup, ndown = nelec if verbose: print(f"# nbasis = {nbasis}") @@ -310,7 +307,6 @@ def build_driver_ueg_test_instance(options: Union[dict, None], h1 = ueg.H1[0] chol = 2. * ueg.chol_vecs.toarray().copy() - #ecore = ueg.ecore ecore = 0. # 2. Build Hamiltonian. @@ -327,7 +323,7 @@ def build_driver_ueg_test_instance(options: Union[dict, None], afqmc = ThermalAFQMC.build( nelec, mu, beta, hamiltonian, trial, nwalkers=nwalkers, stack_size=stack_size, seed=seed, nblocks=nblocks, timestep=timestep, - stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, + stabilize_freq=stabilize_freq, pop_control_freq=pop_control_freq, pop_control_method=pop_control_method, lowrank=lowrank, lowrank_thresh=lowrank_thresh, debug=debug, verbose=verbose) return afqmc diff --git a/ipie/addons/thermal/walkers/pop_controller.py b/ipie/addons/thermal/walkers/pop_controller.py new file mode 100644 index 00000000..23743150 --- /dev/null +++ b/ipie/addons/thermal/walkers/pop_controller.py @@ -0,0 +1,425 @@ +import time + +import numpy + +from ipie.config import MPI +from ipie.utils.backend import arraylib as xp +from ipie.walkers.pop_controller import PopController, PopControllerTimer +from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers + + +class ThermalPopController(PopController): + def __init__( + self, + num_walkers_local, + num_steps, + mpi_handler=None, + pop_control_method="pair_branch", + min_weight=0.1, + max_weight=4, + reconfiguration_freq=50, + verbose=False, + ): + super().__init__( + num_walkers_local, num_steps, mpi_handler, pop_control_method, + min_weight, max_weight, reconfiguration_freq, verbose) + + def pop_control(self, walkers, comm): + self.timer.start_time() + if self.ntot_walkers == 1: + return + weights = numpy.abs(xp.array(walkers.weight)) + global_weights = numpy.empty(len(weights) * comm.size) + self.timer.add_non_communication() + self.timer.start_time() + if self.method == "comb": + comm.Allgather(weights, global_weights) + total_weight = sum(global_weights) + else: + sum_weights = numpy.sum(weights) + total_weight = numpy.empty(1, dtype=numpy.float64) + if hasattr(sum_weights, "get"): + sum_weights = sum_weights.get() + comm.Reduce(sum_weights, total_weight, op=MPI.SUM, root=0) + comm.Bcast(total_weight, root=0) + total_weight = total_weight[0] + + self.timer.add_communication() + self.timer.start_time() + + # Rescale weights to combat exponential decay/growth. + scale = total_weight / self.target_weight + if total_weight < 1e-8: + if comm.rank == 0: + print(f"# Warning: Total weight is {total_weight:13.8e}") + print("# Something is seriously wrong.") + raise ValueError + self.total_weight = total_weight + # Todo: Just standardise information we want to send between routines. + walkers.unscaled_weight = walkers.weight + walkers.weight = walkers.weight / scale + if self.method == "comb": + global_weights = global_weights / scale + self.timer.add_non_communication() + comb(walkers, comm, global_weights, self.target_weight, self.timer) + elif self.method == "pair_branch": + pair_branch(walkers, comm, self.max_weight, self.min_weight, self.timer) + elif self.method == "stochastic_reconfiguration": + self.reconfiguration_counter += 1 + if self.reconfiguration_counter % self.reconfiguration_freq == 0: + stochastic_reconfiguration(walkers, comm, self.timer) + self.reconfiguration_counter = 0 + else: + if comm.rank == 0: + print("Unknown population control method.") + + +def get_buffer(walkers, iw): + """Get iw-th walker buffer for MPI communication + iw : int + the walker index of interest + Returns + ------- + buff : dict + Relevant walker information for population control. + """ + s = 0 + buff = xp.zeros(walkers.buff_size, dtype=numpy.complex128) + for d in walkers.buff_names: + data = walkers.__dict__[d] + if (data is None) or isinstance(data, (int, float, complex, numpy.float64, numpy.complex128)): + continue + assert data.size % walkers.nwalkers == 0 # Only walker-specific data is being communicated + if isinstance(data[iw], (xp.ndarray)): + buff[s : s + data[iw].size] = xp.array(data[iw].ravel()) + s += data[iw].size + elif isinstance(data[iw], list): # when data is list + for l in data[iw]: + if isinstance(l, (xp.ndarray)): + buff[s : s + l.size] = xp.array(l.ravel()) + s += l.size + elif isinstance(l, (int, float, complex, numpy.float64, numpy.complex128)): + buff[s : s + 1] = l + s += 1 + else: + buff[s : s + 1] = xp.array(data[iw]) + s += 1 + + stack_buff = walkers.stack[iw].get_buffer() + buff = numpy.concatenate((buff, stack_buff)) + return buff + + +def set_buffer(walkers, iw, buff): + """Set walker buffer following MPI communication + Parameters + ------- + buff : dict + Relevant walker information for population control. + """ + s = 0 + for d in walkers.buff_names: + data = walkers.__dict__[d] + if (data is None) or isinstance(data, (int, float, complex, numpy.float64, numpy.complex128)): + continue + assert data.size % walkers.nwalkers == 0 # Only walker-specific data is being communicated + if isinstance(data[iw], xp.ndarray): + walkers.__dict__[d][iw] = xp.array( + buff[s : s + data[iw].size].reshape(data[iw].shape).copy()) + s += data[iw].size + elif isinstance(data[iw], list): + for ix, l in enumerate(data[iw]): + if isinstance(l, (xp.ndarray)): + walkers.__dict__[d][iw][ix] = xp.array( + buff[s : s + l.size].reshape(l.shape).copy()) + s += l.size + elif isinstance(l, (int, float, complex)): + walkers.__dict__[d][iw][ix] = buff[s] + s += 1 + else: + if isinstance(walkers.__dict__[d][iw], (int, numpy.int64)): + walkers.__dict__[d][iw] = int(buff[s].real) + elif isinstance(walkers.__dict__[d][iw], (float, numpy.float64)): + walkers.__dict__[d][iw] = buff[s].real + else: + walkers.__dict__[d][iw] = buff[s] + s += 1 + + walkers.stack[iw].set_buffer(buff[walkers.buff_size:]) + + +def comb(walkers, comm, weights, target_weight, timer=PopControllerTimer()): + """Apply the comb method of population control / branching. + + See Booth & Gubernatis PRE 80, 046704 (2009). + + Parameters + ---------- + comm : MPI communicator + """ + # Need make a copy to since the elements in psi are only references to + # walker objects in memory. We don't want future changes in a given + # element of psi having unintended consequences. + # todo : add phase to walker for free projection + timer.start_time() + if comm.rank == 0: + parent_ix = numpy.zeros(len(weights), dtype="i") + else: + parent_ix = numpy.empty(len(weights), dtype="i") + if comm.rank == 0: + total_weight = sum(weights) + cprobs = numpy.cumsum(weights) + r = numpy.random.random() + comb = [(i + r) * (total_weight / target_weight) for i in range(target_weight)] + iw = 0 + ic = 0 + while ic < len(comb): + if comb[ic] < cprobs[iw]: + parent_ix[iw] += 1 + ic += 1 + else: + iw += 1 + data = {"ix": parent_ix} + else: + data = None + + timer.add_non_communication() + + timer.start_time() + data = comm.bcast(data, root=0) + timer.add_communication() + timer.start_time() + parent_ix = data["ix"] + # Keep total weight saved for capping purposes. + # where returns a tuple (array,), selecting first element. + kill = numpy.where(parent_ix == 0)[0] + clone = numpy.where(parent_ix > 1)[0] + reqs = [] + # First initiate non-blocking sends of walkers. + timer.add_non_communication() + timer.start_time() + comm.barrier() + timer.add_communication() + for i, (c, k) in enumerate(zip(clone, kill)): + # Sending from current processor? + if c // walkers.nwalkers == comm.rank: + timer.start_time() + # Location of walker to clone in local list. + clone_pos = c % walkers.nwalkers + # copying walker data to intermediate buffer to avoid issues + # with accessing walker data during send. Might not be + # necessary. + dest_proc = k // walkers.nwalkers + buff = get_buffer(walkers, clone_pos) + timer.add_non_communication() + timer.start_time() + reqs.append(comm.Isend(buff, dest=dest_proc, tag=i)) + timer.add_send_time() + # Now receive walkers on processors where walkers are to be killed. + for i, (c, k) in enumerate(zip(clone, kill)): + # Receiving to current processor? + if k // walkers.nwalkers == comm.rank: + timer.start_time() + # Processor we are receiving from. + source_proc = c // walkers.nwalkers + # Location of walker to kill in local list of walkers. + kill_pos = k % walkers.nwalkers + buffer = walkers.walker_buffer + buffer = numpy.concatenate((walkers.walker_buffer, walkers.stack[0].stack_buffer)) + timer.add_non_communication() + timer.start_time() + comm.Recv(buffer, source=source_proc, tag=i) + # with h5py.File('walkers_recv.h5', 'w') as fh5: + # fh5['walk_{}'.format(k)] = walkers.walker_buffer.copy() + timer.add_recv_time() + timer.start_time() + set_buffer(walkers, kill_pos, buffer) + timer.add_non_communication() + # with h5py.File('after_{}.h5'.format(comm.rank), 'a') as fh5: + # fh5['walker_{}_{}_{}'.format(c,k,comm.rank)] = walkers.walkers[kill_pos].get_buffer() + timer.start_time() + # Complete non-blocking send. + for rs in reqs: + rs.wait() + # Necessary? + # if len(kill) > 0 or len(clone) > 0: + # sys.exit() + comm.Barrier() + timer.add_communication() + # Reset walker weight. + # TODO: check this. + # for w in walkers.walkers: + # w.weight = 1.0 + timer.start_time() + walkers.weight.fill(1.0) + timer.add_non_communication() + + +def pair_branch(walkers, comm, max_weight, min_weight, timer=PopControllerTimer()): + timer.start_time() + walker_info_0 = xp.array(xp.abs(walkers.weight)) + timer.add_non_communication() + + timer.start_time() + glob_inf = None + glob_inf_0 = None + glob_inf_1 = None + glob_inf_2 = None + glob_inf_3 = None + if comm.rank == 0: + glob_inf_0 = numpy.empty([comm.size, walkers.nwalkers], dtype=numpy.float64) + glob_inf_1 = numpy.empty([comm.size, walkers.nwalkers], dtype=numpy.int64) + glob_inf_1.fill(1) + glob_inf_2 = numpy.array( + [[r for i in range(walkers.nwalkers)] for r in range(comm.size)], + dtype=numpy.int64) + glob_inf_3 = numpy.array( + [[r for i in range(walkers.nwalkers)] for r in range(comm.size)], + dtype=numpy.int64) + + timer.add_non_communication() + + timer.start_time() + if hasattr(walker_info_0, "get"): + walker_info_0 = walker_info_0.get() + comm.Gather( + walker_info_0, glob_inf_0, root=0 + ) # gather |w_i| from all processors (comm.size x nwalkers) + timer.add_communication() + + # Want same random number seed used on all processors + timer.start_time() + if comm.rank == 0: + # Rescale weights. + glob_inf = numpy.zeros((walkers.nwalkers * comm.size, 4), dtype=numpy.float64) + glob_inf[:, 0] = glob_inf_0.ravel() # contains walker |w_i| + glob_inf[:, 1] = glob_inf_1.ravel() # all initialized to 1 when it becomes 2 then it will be "branched" + glob_inf[:, 2] = glob_inf_2.ravel() # contain processor+walker indices (initial) (i.e., where walkers live) + glob_inf[:, 3] = glob_inf_3.ravel() # contain processor+walker indices (final) (i.e., where walkers live) + sort = numpy.argsort(glob_inf[:, 0], kind="mergesort") + isort = numpy.argsort(sort, kind="mergesort") + glob_inf = glob_inf[sort] + s = 0 + e = len(glob_inf) - 1 + tags = [] + # go through walkers pair-wise + while s < e: + if glob_inf[s][0] < min_weight or glob_inf[e][0] > max_weight: + # sum of paired walker weights + wab = glob_inf[s][0] + glob_inf[e][0] + r = numpy.random.rand() + if r < glob_inf[e][0] / wab: + # clone large weight walker + glob_inf[e][0] = 0.5 * wab + glob_inf[e][1] = 2 + # Processor we will send duplicated walker to + glob_inf[e][3] = glob_inf[s][2] + send = glob_inf[s][2] + # Kill small weight walker + glob_inf[s][0] = 0.0 + glob_inf[s][1] = 0 + glob_inf[s][3] = glob_inf[e][2] + else: + # clone small weight walker + glob_inf[s][0] = 0.5 * wab + glob_inf[s][1] = 2 + # Processor we will send duplicated walker to + glob_inf[s][3] = glob_inf[e][2] + send = glob_inf[e][2] + # Kill small weight walker + glob_inf[e][0] = 0.0 + glob_inf[e][1] = 0 + glob_inf[e][3] = glob_inf[s][2] + tags.append([send]) + s += 1 + e -= 1 + else: + break + nw = walkers.nwalkers + glob_inf = glob_inf[isort].reshape((comm.size, nw, 4)) + else: + data = None + glob_inf = None + timer.add_non_communication() + timer.start_time() + + data = numpy.empty([walkers.nwalkers, 4], dtype=numpy.float64) + # 0 = weight, 1 = status (live, branched, die), 2 = initial index, 3 = final index + comm.Scatter(glob_inf, data, root=0) + + timer.add_communication() + # Keep total weight saved for capping purposes. + reqs = [] + for iw, walker in enumerate(data): + if walker[1] > 1: + timer.start_time() + tag = comm.rank * walkers.nwalkers + walker[3] + walkers.weight[iw] = walker[0] + buff = get_buffer(walkers, iw) + timer.add_non_communication() + timer.start_time() + reqs.append(comm.Isend(buff, dest=int(round(walker[3])), tag=tag)) + timer.add_send_time() + for iw, walker in enumerate(data): + if walker[1] == 0: + timer.start_time() + tag = walker[3] * walkers.nwalkers + comm.rank + buffer = walkers.walker_buffer + buffer = numpy.concatenate((walkers.walker_buffer, walkers.stack[0].stack_buffer)) + timer.add_non_communication() + timer.start_time() + comm.Recv(buffer, source=int(round(walker[3])), tag=tag) + timer.add_recv_time() + timer.start_time() + set_buffer(walkers, iw, buffer) + timer.add_non_communication() + timer.start_time() + for r in reqs: + r.wait() + timer.add_communication() + + +def stochastic_reconfiguration(walkers, comm, timer=PopControllerTimer()): + # gather all walker information on the root + timer.start_time() + nwalkers = walkers.nwalkers + local_buffer = xp.array([get_buffer(walkers, i) for i in range(nwalkers)]) + walker_len = local_buffer[0].shape[0] + global_buffer = None + if comm.rank == 0: + global_buffer = numpy.zeros((comm.size, nwalkers, walker_len), dtype=numpy.complex128) + timer.add_non_communication() + + timer.start_time() + comm.Gather(local_buffer, global_buffer, root=0) + timer.add_communication() + + # perform sr on the root + new_global_buffer = None + timer.start_time() + if comm.rank == 0: + new_global_buffer = numpy.zeros((comm.size, nwalkers, walker_len), dtype=numpy.complex128) + cumulative_weights = numpy.cumsum(abs(global_buffer[:, :, 0])) + total_weight = cumulative_weights[-1] + new_average_weight = total_weight / nwalkers / comm.size + zeta = numpy.random.rand() + for i in range(comm.size * nwalkers): + z = (i + zeta) / nwalkers / comm.size + new_i = numpy.searchsorted(cumulative_weights, z * total_weight) + new_global_buffer[i // nwalkers, i % nwalkers] = global_buffer[ + new_i // nwalkers, new_i % nwalkers + ] + new_global_buffer[i // nwalkers, i % nwalkers, 0] = new_average_weight + + timer.add_non_communication() + + # distribute information of newly selected walkers + timer.start_time() + comm.Scatter(new_global_buffer, local_buffer, root=0) + timer.add_communication() + + # set walkers using distributed information + timer.start_time() + for i in range(nwalkers): + set_buffer(walkers, i, local_buffer[i]) + timer.add_non_communication() diff --git a/ipie/addons/thermal/walkers/tests/test_population_control.py b/ipie/addons/thermal/walkers/tests/test_population_control.py index 9b3adc38..e6d030e6 100644 --- a/ipie/addons/thermal/walkers/tests/test_population_control.py +++ b/ipie/addons/thermal/walkers/tests/test_population_control.py @@ -12,7 +12,7 @@ from ipie.config import MPI from ipie.utils.mpi import MPIHandler -from ipie.walkers.pop_controller import PopController +from ipie.addons.thermal.walkers.pop_controller import ThermalPopController from ipie.addons.thermal.utils.testing import build_generic_test_case_handlers_mpi comm = MPI.COMM_WORLD @@ -33,41 +33,19 @@ def test_pair_branch_batch(): beta = 0.1 timestep = 0.01 nwalkers = 12 + nblocks = 3 # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! nsteps_per_block = 1 - nblocks = 3 - stabilize_freq = 10 - pop_control_freq = 1 pop_control_method = 'pair_branch' lowrank = False - verbose = False if (comm.rank != 0) else True + mf_trial = True complex_integrals = False debug = True - mf_trial = True - propagate = False + verbose = False if (comm.rank != 0) else True seed = 7 numpy.random.seed(seed) - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - } - # Test. if verbose: print('\n----------------------------') @@ -75,13 +53,15 @@ def test_pair_branch_batch(): print('----------------------------') objs = build_generic_test_case_handlers_mpi( - options, mpi_handler, seed, debug, verbose) + nelec, nbasis, mu, beta, timestep, mpi_handler, nwalkers=nwalkers, + lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, + debug=debug, seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] propagator = objs['propagator'] - pcontrol = PopController(nwalkers, nsteps_per_block, mpi_handler, - pop_control_method, verbose=verbose) + pcontrol = ThermalPopController(nwalkers, nsteps_per_block, mpi_handler, + pop_control_method, verbose=verbose) # Legacy. if verbose: @@ -90,7 +70,9 @@ def test_pair_branch_batch(): print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers_mpi( - hamiltonian, mpi_handler, options, seed=seed, verbose=verbose) + hamiltonian, mpi_handler, nelec, mu, beta, timestep, + nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, + seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] @@ -127,7 +109,7 @@ def test_pair_branch_batch(): assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) - +# TODO: Lowrank code is WIP. #@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") #@pytest.mark.unit def test_pair_branch_batch_lowrank(): @@ -144,20 +126,17 @@ def test_pair_branch_batch_lowrank(): beta = 0.1 timestep = 0.01 nwalkers = 12 + nblocks = 3 # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! nsteps_per_block = 1 - nblocks = 3 - stabilize_freq = 10 - pop_control_freq = 1 pop_control_method = 'pair_branch' lowrank = True - verbose = False if (comm.rank != 0) else True - complex_integrals = False - debug = True mf_trial = False - propagate = False diagonal = True + complex_integrals = False + debug = True + verbose = False if (comm.rank != 0) else True seed = 7 numpy.random.seed(seed) @@ -187,12 +166,15 @@ def test_pair_branch_batch_lowrank(): print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers_mpi(options, mpi_handler, seed, debug, verbose) + objs = build_generic_test_case_handlers_mpi( + nelec, nbasis, mu, beta, timestep, mpi_handler, nwalkers=nwalkers, + lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, + diagonal=diagonal, debug=debug, seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] propagator = objs['propagator'] - pcontrol = PopController(nwalkers, nsteps_per_block, mpi_handler, + pcontrol = ThermalPopController(nwalkers, nsteps_per_block, mpi_handler, pop_control_method=pop_control_method, verbose=verbose) # Legacy. @@ -202,7 +184,9 @@ def test_pair_branch_batch_lowrank(): print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers_mpi( - hamiltonian, mpi_handler, options, seed=seed, verbose=verbose) + hamiltonian, mpi_handler, nelec, mu, beta, timestep, + nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, + seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] @@ -255,53 +239,34 @@ def test_comb_batch(): beta = 0.1 timestep = 0.01 nwalkers = 12 + nblocks = 3 # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! nsteps_per_block = 1 - nblocks = 3 - stabilize_freq = 10 - pop_control_freq = 1 pop_control_method = 'comb' lowrank = False - verbose = False if (comm.rank != 0) else True + mf_trial = True complex_integrals = False debug = True - mf_trial = True - propagate = False + verbose = False if (comm.rank != 0) else True seed = 7 numpy.random.seed(seed) - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - } - # Test. if verbose: print('\n----------------------------') print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers_mpi(options, mpi_handler, seed, debug, verbose) + objs = build_generic_test_case_handlers_mpi( + nelec, nbasis, mu, beta, timestep, mpi_handler, nwalkers=nwalkers, + lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, + debug=debug, seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] propagator = objs['propagator'] - pcontrol = PopController(nwalkers, nsteps_per_block, mpi_handler, + pcontrol = ThermalPopController(nwalkers, nsteps_per_block, mpi_handler, pop_control_method=pop_control_method, verbose=verbose) # Legacy. @@ -311,7 +276,10 @@ def test_comb_batch(): print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers_mpi( - hamiltonian, mpi_handler, options, seed=seed, verbose=verbose) + hamiltonian, mpi_handler, nelec, mu, beta, timestep, + nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, + pop_control_method=pop_control_method, seed=seed, + verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] @@ -365,42 +333,19 @@ def test_comb_batch_lowrank(): beta = 0.1 timestep = 0.01 nwalkers = 12 + nblocks = 3 # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! nsteps_per_block = 1 - nblocks = 3 - stabilize_freq = 10 - pop_control_freq = 1 pop_control_method = 'comb' lowrank = True - verbose = False if (comm.rank != 0) else True - complex_integrals = False - debug = True mf_trial = False - propagate = False diagonal = True + complex_integrals = False + debug = True + verbose = False if (comm.rank != 0) else True seed = 7 numpy.random.seed(seed) - - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - 'diagonal': diagonal, - } # Test. if verbose: @@ -408,12 +353,15 @@ def test_comb_batch_lowrank(): print('Constructing test objects...') print('----------------------------') - objs = build_generic_test_case_handlers_mpi(options, mpi_handler, seed, debug, verbose) + objs = build_generic_test_case_handlers_mpi( + nelec, nbasis, mu, beta, timestep, mpi_handler, nwalkers=nwalkers, + lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, + diagonal=diagonal, debug=debug, seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] propagator = objs['propagator'] - pcontrol = PopController(nwalkers, nsteps_per_block, mpi_handler, + pcontrol = ThermalPopController(nwalkers, nsteps_per_block, mpi_handler, pop_control_method=pop_control_method, verbose=verbose) # Legacy. @@ -423,7 +371,9 @@ def test_comb_batch_lowrank(): print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers_mpi( - hamiltonian, mpi_handler, options, seed=seed, verbose=verbose) + hamiltonian, mpi_handler, nelec, mu, beta, timestep, + nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, + seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] diff --git a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py index fb82bb11..5f76301e 100644 --- a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py @@ -34,57 +34,38 @@ def test_thermal_walkers_fullrank(): beta = 0.1 timestep = 0.01 nwalkers = 10 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 12 - stabilize_freq = 10 - pop_control_freq = 1 - pop_control_method = 'pair_branch' - #pop_control_method = 'comb' lowrank = False - verbose = True + mf_trial = True complex_integrals = False debug = True - mf_trial = True - propagate = False + verbose = True seed = 7 numpy.random.seed(seed) - - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - } # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + if verbose: + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') + if verbose: + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_generic_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) + hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, + lowrank=lowrank, mf_trial=mf_trial, seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] @@ -105,13 +86,14 @@ def test_thermal_walkers_fullrank(): print(f'walkers.weight = \n{walkers.weight[iw]}\n') print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') - numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + #numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[1], walkers.stack[iw].ovlp[1], decimal=10) +# TODO: Lowrank code is WIP. #@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") #@pytest.mark.unit def test_thermal_walkers_lowrank(): @@ -126,59 +108,38 @@ def test_thermal_walkers_lowrank(): beta = 0.1 timestep = 0.01 nwalkers = 10 - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 12 - stabilize_freq = 10 - pop_control_freq = 1 - pop_control_method = 'pair_branch' - #pop_control_method = 'comb' lowrank = True - verbose = True - complex_integrals = False - debug = True mf_trial = False - propagate = False diagonal = True + complex_integrals = False + debug = True + verbose = True seed = 7 numpy.random.seed(seed) - - options = { - 'nelec': nelec, - 'nbasis': nbasis, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'stabilize_freq': stabilize_freq, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'complex_integrals': complex_integrals, - 'mf_trial': mf_trial, - 'propagate': propagate, - 'diagonal': diagonal, - } # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers(options, seed, debug, verbose) + if verbose: + print('\n----------------------------') + print('Constructing test objects...') + print('----------------------------') + objs = build_generic_test_case_handlers( + nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, + mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, + seed=seed, verbose=verbose) trial = objs['trial'] hamiltonian = objs['hamiltonian'] walkers = objs['walkers'] # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') + if verbose: + print('\n------------------------------') + print('Constructing legacy objects...') + print('------------------------------') + legacy_objs = build_legacy_generic_test_case_handlers( - hamiltonian, comm, options, seed=seed, verbose=verbose) + hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, + lowrank=lowrank, mf_trial=mf_trial, seed=seed, verbose=verbose) legacy_system = legacy_objs['system'] legacy_trial = legacy_objs['trial'] legacy_hamiltonian = legacy_objs['hamiltonian'] diff --git a/ipie/qmc/options.py b/ipie/qmc/options.py index d77dee31..437a5422 100644 --- a/ipie/qmc/options.py +++ b/ipie/qmc/options.py @@ -45,62 +45,32 @@ class QMCOpts(object): Initialised from a dict containing the following options, not all of which are required. - Parameters + Attributes ---------- - method : string - Which auxiliary field method are we using? Currently only CPMC is - implemented. + batched : bool + Whether to do batched calculations. nwalkers : int Number of walkers to propagate in a simulation. dt : float Timestep. nsteps : int Number of steps per block. - nmeasure : int - Frequency of energy measurements. + nblocks : int + Number of blocks. Total number of iterations = nblocks * nsteps. nstblz : int Frequency of Gram-Schmidt orthogonalisation steps. npop_control : int Frequency of population control. - pop_control_method : int + pop_control_method : str Population control method. - temp : float - Temperature. Currently not used. - nequilibrate : int - Number of steps used for equilibration phase. Only used to fix local + eqlb_time : float + Time scale of equilibration phase. Only used to fix local energy bound when using phaseless approximation. - importance_sampling : boolean - Are we using importance sampling. Default True. - hubbard_statonovich : string - Which hubbard stratonovich transformation are we using. Currently the - options are: - - - discrete : Use the discrete Hirsch spin transformation. - - opt_continuous : Use the continuous transformation for the Hubbard - model. - - generic : Use the generic transformation. To be used with Generic - system class. - - ffts : boolean - Use FFTS to diagonalise the kinetic energy propagator? Default False. - This may speed things up for larger lattices. - - Attributes - ---------- - cplx : boolean - Do we require complex wavefunctions? - mf_shift : float - Mean field shift for continuous Hubbard-Stratonovich transformation. - iut_fac : complex float - Stores i*(U*dt)**0.5 for continuous Hubbard-Stratonovich transformation. - ut_fac : float - Stores (U*dt) for continuous Hubbard-Stratonovich transformation. - mf_nsq : float - Stores M * mf_shift for continuous Hubbard-Stratonovich transformation. - local_energy_bound : float - Energy pound for continuous Hubbard-Stratonovich transformation. - mean_local_energy : float - Estimate for mean energy for continuous Hubbard-Stratonovich transformation. + neqlb : int + Number of time steps for the equilibration phase. Only used to fix the + local energy bound when using phaseless approximation. + rng_seed : int + The random number seed. """ # pylint: disable=dangerous-default-value @@ -157,18 +127,6 @@ def __init__(self, inputs={}, verbose=False): alias=["random_seed", "seed"], verbose=verbose, ) - self.mu = get_input_value( - inputs, - "mu", - default=None, - verbose=verbose, - ) - self.beta = get_input_value( - inputs, - "beta", - default=None, - verbose=verbose, - ) def __str__(self, verbose=0): _str = "" @@ -181,18 +139,25 @@ def __str__(self, verbose=0): class QMCParams: r"""Input options and certain constants / parameters derived from them. - Args: - num_walkers: number of walkers **per** core / task / computational unit. - total_num_walkers: The total number of walkers in the simulation. - timestep: The timestep delta_t - num_steps_per_block: Number of steps of propagation before estimators - are evaluated. - num_blocks: The number of blocks. Total number of iterations = - num_blocks * num_steps_per_block. - num_stblz: number of steps before QR stabilization of walkers is performed. - pop_control_freq: Frequency at which population control occurs. - rng_seed: The random number seed. If run in parallel the seeds on other - cores / threads are determined from this. + Attributes + ---------- + num_walkers : int + Number of walkers **per** core / task / computational unit. + total_num_walkers : int + The total number of walkers in the simulation. + timestep : float + The timestep delta_t + num_steps_per_block : int + Number of steps of propagation before estimators are evaluated. + num_blocks : int + Number of blocks. Total number of iterations = num_blocks * num_steps_per_block. + num_stblz : int + Number of steps before QR stabilization of walkers is performed. + pop_control_freq : int + Frequency at which population control occurs. + rng_seed : int + The random number seed. If run in parallel the seeds on other cores / + threads are determined from this. """ num_walkers: int diff --git a/ipie/trial_wavefunction/tests/test_single_det_trial.py b/ipie/trial_wavefunction/tests/test_single_det_trial.py index 97125309..96a4e524 100644 --- a/ipie/trial_wavefunction/tests/test_single_det_trial.py +++ b/ipie/trial_wavefunction/tests/test_single_det_trial.py @@ -40,7 +40,7 @@ def test_single_det(): assert trial._rH1b.shape == (nbeta, nbasis) -#@pytest.mark.unit +@pytest.mark.unit def test_single_det_ghf(): nbasis = 10 naux = 5 * nbasis @@ -135,5 +135,5 @@ def test_single_det_all_up(): if __name__ == "__main__": test_single_det() - #test_single_det_ghf() + test_single_det_ghf() test_single_det_all_up() diff --git a/ipie/walkers/pop_controller.py b/ipie/walkers/pop_controller.py index f69bc021..17baab27 100644 --- a/ipie/walkers/pop_controller.py +++ b/ipie/walkers/pop_controller.py @@ -4,7 +4,6 @@ from ipie.config import MPI from ipie.utils.backend import arraylib as xp -from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers class PopControllerTimer: def __init__(self): @@ -138,7 +137,7 @@ def get_buffer(walkers, iw): buff = xp.zeros(walkers.buff_size, dtype=numpy.complex128) for d in walkers.buff_names: data = walkers.__dict__[d] - if (data is None) or isinstance(data, (int, float, complex, numpy.float64, numpy.complex128)): + if data is None: continue assert data.size % walkers.nwalkers == 0 # Only walker-specific data is being communicated if isinstance(data[iw], (xp.ndarray)): @@ -156,10 +155,6 @@ def get_buffer(walkers, iw): buff[s : s + 1] = xp.array(data[iw]) s += 1 - if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): - stack_buff = walkers.stack[iw].get_buffer() - buff = numpy.concatenate((buff, stack_buff)) - return buff @@ -173,7 +168,7 @@ def set_buffer(walkers, iw, buff): s = 0 for d in walkers.buff_names: data = walkers.__dict__[d] - if (data is None) or isinstance(data, (int, float, complex, numpy.float64, numpy.complex128)): + if data is None: continue assert data.size % walkers.nwalkers == 0 # Only walker-specific data is being communicated if isinstance(data[iw], xp.ndarray): @@ -197,9 +192,6 @@ def set_buffer(walkers, iw, buff): else: walkers.__dict__[d][iw] = buff[s] s += 1 - - if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): - walkers.stack[iw].set_buffer(buff[walkers.buff_size:]) def comb(walkers, comm, weights, target_weight, timer=PopControllerTimer()): @@ -281,16 +273,12 @@ def comb(walkers, comm, weights, target_weight, timer=PopControllerTimer()): buffer = walkers.walker_buffer timer.add_non_communication() timer.start_time() - if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): - buffer = numpy.concatenate((walkers.walker_buffer, walkers.stack[0].stack_buffer)) - comm.Recv(buffer, source=source_proc, tag=i) - else: - comm.Recv(buffer, source=source_proc, tag=i) + comm.Recv(walkers.walker_buffer, source=source_proc, tag=i) # with h5py.File('walkers_recv.h5', 'w') as fh5: # fh5['walk_{}'.format(k)] = walkers.walker_buffer.copy() timer.add_recv_time() timer.start_time() - set_buffer(walkers, kill_pos, buffer) + set_buffer(walkers, kill_pos, walkers.walker_buffer) timer.add_non_communication() # with h5py.File('after_{}.h5'.format(comm.rank), 'a') as fh5: # fh5['walker_{}_{}_{}'.format(c,k,comm.rank)] = walkers.walkers[kill_pos].get_buffer() @@ -424,14 +412,10 @@ def pair_branch(walkers, comm, max_weight, min_weight, timer=PopControllerTimer( buffer = walkers.walker_buffer timer.add_non_communication() timer.start_time() - if isinstance(walkers, UHFThermalWalkers) and (walkers.stack is not None): - buffer = numpy.concatenate((walkers.walker_buffer, walkers.stack[0].stack_buffer)) - comm.Recv(buffer, source=int(round(walker[3])), tag=tag) - else: - comm.Recv(buffer, source=int(round(walker[3])), tag=tag) + comm.Recv(walkers.walker_buffer, source=int(round(walker[3])), tag=tag) timer.add_recv_time() timer.start_time() - set_buffer(walkers, iw, buffer) + set_buffer(walkers, iw, walkers.walker_buffer) timer.add_non_communication() timer.start_time() for r in reqs: From e576ce18758b8920230821933b9e2f60791260f6 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 7 Apr 2024 20:33:24 -0400 Subject: [PATCH 77/84] Bugfix in legacy. --- ipie/legacy/hamiltonians/_generic.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ipie/legacy/hamiltonians/_generic.py b/ipie/legacy/hamiltonians/_generic.py index e361deb5..6b1a2ef8 100644 --- a/ipie/legacy/hamiltonians/_generic.py +++ b/ipie/legacy/hamiltonians/_generic.py @@ -140,7 +140,7 @@ def __init__( if self.verbose: print("# mixed_precision is used for the propagation") - if isrealobj(self.chol_vecs.dtype): + if isrealobj(self.chol_vecs): if verbose: print("# Found real Choleksy integrals.") self.cplx_chol = False @@ -314,7 +314,7 @@ def construct_h1e_mod(chol, h1e, h1e_mod): chol_view = chol.reshape((nbasis, nbasis * nchol)) # assert chol_view.__array_interface__['data'][0] == chol.__array_interface__['data'][0] v0 = 0.5 * numpy.dot( - chol_view, chol_view.T + chol_view, chol_view.T.conj() # Conjugate added to account for complex integrals ) # einsum('ikn,jkn->ij', chol_3, chol_3, optimize=True) h1e_mod[0, :, :] = h1e[0] - v0 h1e_mod[1, :, :] = h1e[1] - v0 From c478bcdc9eb44e5507e91aa6c9a1ebb660718502 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 7 Apr 2024 20:58:09 -0400 Subject: [PATCH 78/84] Skip test without cython build. --- .../thermal/trial/tests/test_mean_field.py | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/ipie/addons/thermal/trial/tests/test_mean_field.py b/ipie/addons/thermal/trial/tests/test_mean_field.py index e668d1e4..6d5ca3b3 100644 --- a/ipie/addons/thermal/trial/tests/test_mean_field.py +++ b/ipie/addons/thermal/trial/tests/test_mean_field.py @@ -1,6 +1,31 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest +try: + import ipie.legacy.estimators.ueg_kernels + _no_cython = False + +except ModuleNotFoundError: + _no_cython = True + from ipie.systems.generic import Generic from ipie.utils.testing import generate_hamiltonian from ipie.hamiltonians.generic import Generic as HamGeneric @@ -11,8 +36,7 @@ from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField - - +@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @pytest.mark.unit def test_mean_field(): nup = 5 From 366c4990acca450ecc251bc188da6831e84b01e3 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Sun, 7 Apr 2024 20:59:25 -0400 Subject: [PATCH 79/84] Add license --- ipie/addons/thermal/analysis/extraction.py | 18 ++++++++++++++++++ .../thermal/analysis/thermal_analysis.py | 18 ++++++++++++++++++ ipie/addons/thermal/estimators/__init__.py | 17 +++++++++++++++++ ipie/addons/thermal/estimators/energy.py | 3 ++- ipie/addons/thermal/estimators/generic.py | 18 ++++++++++++++++++ .../thermal/estimators/greens_function.py | 18 ++++++++++++++++++ ipie/addons/thermal/estimators/handler.py | 18 ++++++++++++++++++ .../addons/thermal/estimators/local_energy.py | 18 ++++++++++++++++++ .../thermal/estimators/particle_number.py | 18 ++++++++++++++++++ .../estimators/tests/test_estimators.py | 18 ++++++++++++++++++ .../thermal/estimators/tests/test_generic.py | 18 ++++++++++++++++++ .../estimators/tests/test_generic_complex.py | 18 ++++++++++++++++++ ipie/addons/thermal/estimators/thermal.py | 18 ++++++++++++++++++ ipie/addons/thermal/propagation/__init__.py | 17 +++++++++++++++++ ipie/addons/thermal/propagation/force_bias.py | 18 ++++++++++++++++++ ipie/addons/thermal/propagation/operations.py | 18 ++++++++++++++++++ .../thermal/propagation/phaseless_base.py | 18 ++++++++++++++++++ .../thermal/propagation/phaseless_generic.py | 18 ++++++++++++++++++ ipie/addons/thermal/propagation/propagator.py | 18 ++++++++++++++++++ .../propagation/tests/test_prop_generic.py | 18 ++++++++++++++++++ .../propagation/tests/ueg/test_prop_ueg.py | 18 ++++++++++++++++++ ipie/addons/thermal/qmc/__init__.py | 17 +++++++++++++++++ ipie/addons/thermal/qmc/calc.py | 18 ++++++++++++++++++ ipie/addons/thermal/qmc/options.py | 18 ++++++++++++++++++ ipie/addons/thermal/qmc/tests/run_legacy.py | 18 ++++++++++++++++++ .../thermal/qmc/tests/test_afqmc_generic.py | 18 ++++++++++++++++++ .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 18 ++++++++++++++++++ ipie/addons/thermal/qmc/thermal_afqmc.py | 18 ++++++++++++++++++ ipie/addons/thermal/trial/__init__.py | 17 +++++++++++++++++ ipie/addons/thermal/trial/chem_pot.py | 18 ++++++++++++++++++ ipie/addons/thermal/trial/mean_field.py | 18 ++++++++++++++++++ ipie/addons/thermal/trial/one_body.py | 18 ++++++++++++++++++ .../thermal/trial/tests/test_chem_pot.py | 18 ++++++++++++++++++ .../thermal/trial/tests/test_one_body.py | 18 ++++++++++++++++++ ipie/addons/thermal/trial/utils.py | 18 ++++++++++++++++++ ipie/addons/thermal/utils/legacy_testing.py | 18 ++++++++++++++++++ ipie/addons/thermal/utils/testing.py | 18 ++++++++++++++++++ ipie/addons/thermal/utils/ueg.py | 18 ++++++++++++++++++ ipie/addons/thermal/walkers/__init__.py | 17 +++++++++++++++++ ipie/addons/thermal/walkers/pop_controller.py | 19 ++++++++++++++++++- ipie/addons/thermal/walkers/stack.py | 18 ++++++++++++++++++ .../walkers/tests/test_population_control.py | 18 ++++++++++++++++++ .../walkers/tests/test_thermal_walkers.py | 18 ++++++++++++++++++ ipie/addons/thermal/walkers/uhf_walkers.py | 18 ++++++++++++++++++ 44 files changed, 771 insertions(+), 2 deletions(-) diff --git a/ipie/addons/thermal/analysis/extraction.py b/ipie/addons/thermal/analysis/extraction.py index ef327ff3..e87128b5 100644 --- a/ipie/addons/thermal/analysis/extraction.py +++ b/ipie/addons/thermal/analysis/extraction.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import json import h5py diff --git a/ipie/addons/thermal/analysis/thermal_analysis.py b/ipie/addons/thermal/analysis/thermal_analysis.py index 01f2e12e..96a49554 100644 --- a/ipie/addons/thermal/analysis/thermal_analysis.py +++ b/ipie/addons/thermal/analysis/thermal_analysis.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + #!/usr/bin/env python import sys diff --git a/ipie/addons/thermal/estimators/__init__.py b/ipie/addons/thermal/estimators/__init__.py index e69de29b..f91ef518 100644 --- a/ipie/addons/thermal/estimators/__init__.py +++ b/ipie/addons/thermal/estimators/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py index e727477a..5a205c8d 100644 --- a/ipie/addons/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -12,7 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # -# Author: Fionn Malone +# Authors: Fionn Malone +# Joonho Lee # from typing import Union diff --git a/ipie/addons/thermal/estimators/generic.py b/ipie/addons/thermal/estimators/generic.py index bd69abc2..b136aedf 100644 --- a/ipie/addons/thermal/estimators/generic.py +++ b/ipie/addons/thermal/estimators/generic.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import plum import numpy from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol diff --git a/ipie/addons/thermal/estimators/greens_function.py b/ipie/addons/thermal/estimators/greens_function.py index 7abea460..c39abd19 100644 --- a/ipie/addons/thermal/estimators/greens_function.py +++ b/ipie/addons/thermal/estimators/greens_function.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import scipy.linalg diff --git a/ipie/addons/thermal/estimators/handler.py b/ipie/addons/thermal/estimators/handler.py index a8cd091d..169b5feb 100644 --- a/ipie/addons/thermal/estimators/handler.py +++ b/ipie/addons/thermal/estimators/handler.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + """Routines and classes for estimation of observables.""" import os diff --git a/ipie/addons/thermal/estimators/local_energy.py b/ipie/addons/thermal/estimators/local_energy.py index b79fd1c1..0a50035c 100644 --- a/ipie/addons/thermal/estimators/local_energy.py +++ b/ipie/addons/thermal/estimators/local_energy.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G diff --git a/ipie/addons/thermal/estimators/particle_number.py b/ipie/addons/thermal/estimators/particle_number.py index 5df96be6..a2bd5b77 100644 --- a/ipie/addons/thermal/estimators/particle_number.py +++ b/ipie/addons/thermal/estimators/particle_number.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + from ipie.utils.backend import arraylib as xp from ipie.estimators.estimator_base import EstimatorBase from ipie.addons.thermal.estimators.thermal import one_rdm_from_G diff --git a/ipie/addons/thermal/estimators/tests/test_estimators.py b/ipie/addons/thermal/estimators/tests/test_estimators.py index 64501699..87e3c211 100644 --- a/ipie/addons/thermal/estimators/tests/test_estimators.py +++ b/ipie/addons/thermal/estimators/tests/test_estimators.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import pytest import tempfile import numpy diff --git a/ipie/addons/thermal/estimators/tests/test_generic.py b/ipie/addons/thermal/estimators/tests/test_generic.py index 2bba34ea..606fbda0 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic.py +++ b/ipie/addons/thermal/estimators/tests/test_generic.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest from typing import Tuple, Union diff --git a/ipie/addons/thermal/estimators/tests/test_generic_complex.py b/ipie/addons/thermal/estimators/tests/test_generic_complex.py index 74e37ac6..2902f61b 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic_complex.py +++ b/ipie/addons/thermal/estimators/tests/test_generic_complex.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest from typing import Tuple, Union diff --git a/ipie/addons/thermal/estimators/thermal.py b/ipie/addons/thermal/estimators/thermal.py index 65ee4cad..198f965c 100644 --- a/ipie/addons/thermal/estimators/thermal.py +++ b/ipie/addons/thermal/estimators/thermal.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import scipy.linalg diff --git a/ipie/addons/thermal/propagation/__init__.py b/ipie/addons/thermal/propagation/__init__.py index e69de29b..f91ef518 100644 --- a/ipie/addons/thermal/propagation/__init__.py +++ b/ipie/addons/thermal/propagation/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/propagation/force_bias.py b/ipie/addons/thermal/propagation/force_bias.py index 6f7a4917..47fd2138 100644 --- a/ipie/addons/thermal/propagation/force_bias.py +++ b/ipie/addons/thermal/propagation/force_bias.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import plum import numpy diff --git a/ipie/addons/thermal/propagation/operations.py b/ipie/addons/thermal/propagation/operations.py index cca29dbe..661f96b1 100644 --- a/ipie/addons/thermal/propagation/operations.py +++ b/ipie/addons/thermal/propagation/operations.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + from ipie.utils.backend import arraylib as xp def apply_exponential(VHS, exp_nmax): diff --git a/ipie/addons/thermal/propagation/phaseless_base.py b/ipie/addons/thermal/propagation/phaseless_base.py index 0696d39f..cd6250d9 100644 --- a/ipie/addons/thermal/propagation/phaseless_base.py +++ b/ipie/addons/thermal/propagation/phaseless_base.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import time import plum import math diff --git a/ipie/addons/thermal/propagation/phaseless_generic.py b/ipie/addons/thermal/propagation/phaseless_generic.py index 45895bc3..6f196ed8 100644 --- a/ipie/addons/thermal/propagation/phaseless_generic.py +++ b/ipie/addons/thermal/propagation/phaseless_generic.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import plum from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol diff --git a/ipie/addons/thermal/propagation/propagator.py b/ipie/addons/thermal/propagation/propagator.py index 80836ee5..ab9b4600 100644 --- a/ipie/addons/thermal/propagation/propagator.py +++ b/ipie/addons/thermal/propagation/propagator.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + from ipie.hamiltonians.generic import GenericRealChol, GenericComplexChol from ipie.addons.thermal.propagation.phaseless_generic import PhaselessGeneric diff --git a/ipie/addons/thermal/propagation/tests/test_prop_generic.py b/ipie/addons/thermal/propagation/tests/test_prop_generic.py index dcb4c597..0dfc8a8a 100644 --- a/ipie/addons/thermal/propagation/tests/test_prop_generic.py +++ b/ipie/addons/thermal/propagation/tests/test_prop_generic.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index af8bb823..eabec6bc 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import pytest import numpy diff --git a/ipie/addons/thermal/qmc/__init__.py b/ipie/addons/thermal/qmc/__init__.py index e69de29b..f91ef518 100644 --- a/ipie/addons/thermal/qmc/__init__.py +++ b/ipie/addons/thermal/qmc/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index 86c1cec2..9f445df9 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + """Helper Routines for setting up a calculation""" import json diff --git a/ipie/addons/thermal/qmc/options.py b/ipie/addons/thermal/qmc/options.py index e87ce3d5..9e2949da 100644 --- a/ipie/addons/thermal/qmc/options.py +++ b/ipie/addons/thermal/qmc/options.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + from dataclasses import dataclass from typing import ClassVar diff --git a/ipie/addons/thermal/qmc/tests/run_legacy.py b/ipie/addons/thermal/qmc/tests/run_legacy.py index 96acadfc..a316e6ec 100644 --- a/ipie/addons/thermal/qmc/tests/run_legacy.py +++ b/ipie/addons/thermal/qmc/tests/run_legacy.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import json import os import sys diff --git a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py index c3313b0d..9dbc2f89 100644 --- a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py +++ b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import json import tempfile import h5py diff --git a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index 8497ad08..39f44cf3 100644 --- a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import os import sys import json diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index d4cfbd1e..f96f2f46 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + """Driver to perform Thermal AFQMC calculation""" import numpy import time diff --git a/ipie/addons/thermal/trial/__init__.py b/ipie/addons/thermal/trial/__init__.py index e69de29b..f91ef518 100644 --- a/ipie/addons/thermal/trial/__init__.py +++ b/ipie/addons/thermal/trial/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/trial/chem_pot.py b/ipie/addons/thermal/trial/chem_pot.py index 8f496297..85244d40 100644 --- a/ipie/addons/thermal/trial/chem_pot.py +++ b/ipie/addons/thermal/trial/chem_pot.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy from ipie.addons.thermal.estimators.particle_number import particle_number diff --git a/ipie/addons/thermal/trial/mean_field.py b/ipie/addons/thermal/trial/mean_field.py index e6207c3a..06712da4 100644 --- a/ipie/addons/thermal/trial/mean_field.py +++ b/ipie/addons/thermal/trial/mean_field.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import scipy.linalg diff --git a/ipie/addons/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py index c06603ce..f18b6ff9 100644 --- a/ipie/addons/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import scipy.linalg diff --git a/ipie/addons/thermal/trial/tests/test_chem_pot.py b/ipie/addons/thermal/trial/tests/test_chem_pot.py index bbb4f7bb..7fcbcff9 100644 --- a/ipie/addons/thermal/trial/tests/test_chem_pot.py +++ b/ipie/addons/thermal/trial/tests/test_chem_pot.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import scipy.linalg import pytest diff --git a/ipie/addons/thermal/trial/tests/test_one_body.py b/ipie/addons/thermal/trial/tests/test_one_body.py index 4dd5b994..7a290a70 100644 --- a/ipie/addons/thermal/trial/tests/test_one_body.py +++ b/ipie/addons/thermal/trial/tests/test_one_body.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest diff --git a/ipie/addons/thermal/trial/utils.py b/ipie/addons/thermal/trial/utils.py index 9b8f0406..60808a15 100644 --- a/ipie/addons/thermal/trial/utils.py +++ b/ipie/addons/thermal/trial/utils.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + from ipie.addons.thermal.trial.mean_field import MeanField from ipie.addons.thermal.trial.one_body import OneBody diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index bc854f63..d23f4083 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest from typing import Tuple, Union diff --git a/ipie/addons/thermal/utils/testing.py b/ipie/addons/thermal/utils/testing.py index faaa1fbd..16b84870 100644 --- a/ipie/addons/thermal/utils/testing.py +++ b/ipie/addons/thermal/utils/testing.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest from typing import Tuple, Union diff --git a/ipie/addons/thermal/utils/ueg.py b/ipie/addons/thermal/utils/ueg.py index c1eff342..3df52dcd 100644 --- a/ipie/addons/thermal/utils/ueg.py +++ b/ipie/addons/thermal/utils/ueg.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import scipy.sparse from ipie.utils.io import write_qmcpack_sparse diff --git a/ipie/addons/thermal/walkers/__init__.py b/ipie/addons/thermal/walkers/__init__.py index e69de29b..f91ef518 100644 --- a/ipie/addons/thermal/walkers/__init__.py +++ b/ipie/addons/thermal/walkers/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/walkers/pop_controller.py b/ipie/addons/thermal/walkers/pop_controller.py index 23743150..759755e7 100644 --- a/ipie/addons/thermal/walkers/pop_controller.py +++ b/ipie/addons/thermal/walkers/pop_controller.py @@ -1,5 +1,22 @@ -import time +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# +import time import numpy from ipie.config import MPI diff --git a/ipie/addons/thermal/walkers/stack.py b/ipie/addons/thermal/walkers/stack.py index dc23637c..09ac8c81 100644 --- a/ipie/addons/thermal/walkers/stack.py +++ b/ipie/addons/thermal/walkers/stack.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import scipy.linalg diff --git a/ipie/addons/thermal/walkers/tests/test_population_control.py b/ipie/addons/thermal/walkers/tests/test_population_control.py index e6d030e6..b5a2cc5c 100644 --- a/ipie/addons/thermal/walkers/tests/test_population_control.py +++ b/ipie/addons/thermal/walkers/tests/test_population_control.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest from typing import Union diff --git a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py index 5f76301e..d7b7a86d 100644 --- a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import pytest from typing import Union diff --git a/ipie/addons/thermal/walkers/uhf_walkers.py b/ipie/addons/thermal/walkers/uhf_walkers.py index 1c14462d..8b438f7e 100644 --- a/ipie/addons/thermal/walkers/uhf_walkers.py +++ b/ipie/addons/thermal/walkers/uhf_walkers.py @@ -1,3 +1,21 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# + import numpy import scipy.linalg From 061d8f1612e276c71efc46116d0f31babf98a075 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 10 Apr 2024 00:25:21 -0400 Subject: [PATCH 80/84] Addressing PR #296 comments --- ipie/addons/thermal/__init__.py | 18 +- ipie/addons/thermal/analysis/__init__.py | 17 ++ ipie/addons/thermal/estimators/energy.py | 25 +-- ipie/addons/thermal/estimators/generic.py | 2 +- ipie/addons/thermal/estimators/handler.py | 163 ++++-------------- .../addons/thermal/estimators/local_energy.py | 12 +- .../thermal/estimators/particle_number.py | 3 +- .../estimators/tests/test_estimators.py | 10 -- .../thermal/estimators/tests/test_generic.py | 4 - .../thermal/propagation/phaseless_base.py | 2 +- .../thermal/propagation/tests/__init__.py | 17 ++ .../propagation/tests/test_prop_generic.py | 53 ------ .../propagation/tests/ueg/test_prop_ueg.py | 15 -- ipie/addons/thermal/qmc/calc.py | 50 +----- ipie/addons/thermal/qmc/options.py | 19 +- ipie/addons/thermal/qmc/tests/__init__.py | 17 ++ .../thermal/qmc/tests/test_afqmc_generic.py | 16 -- .../thermal/qmc/tests/ueg/test_afqmc_ueg.py | 48 ------ ipie/addons/thermal/qmc/thermal_afqmc.py | 149 +--------------- ipie/addons/thermal/trial/mean_field.py | 2 +- ipie/addons/thermal/trial/one_body.py | 2 +- ipie/addons/thermal/trial/tests/__init__.py | 17 ++ .../thermal/trial/tests/test_mean_field.py | 11 +- .../thermal/trial/tests/test_one_body.py | 3 - ipie/addons/thermal/utils/__init__.py | 17 ++ ipie/addons/thermal/utils/ueg.py | 5 +- ipie/addons/thermal/walkers/stack.py | 3 + .../walkers/tests/test_population_control.py | 83 +-------- .../walkers/tests/test_thermal_walkers.py | 35 +--- ipie/addons/thermal/walkers/uhf_walkers.py | 11 -- ipie/trial_wavefunction/single_det.py | 1 - 31 files changed, 184 insertions(+), 646 deletions(-) create mode 100644 ipie/addons/thermal/analysis/__init__.py create mode 100644 ipie/addons/thermal/propagation/tests/__init__.py create mode 100644 ipie/addons/thermal/qmc/tests/__init__.py create mode 100644 ipie/addons/thermal/trial/tests/__init__.py create mode 100644 ipie/addons/thermal/utils/__init__.py diff --git a/ipie/addons/thermal/__init__.py b/ipie/addons/thermal/__init__.py index 8b137891..f91ef518 100644 --- a/ipie/addons/thermal/__init__.py +++ b/ipie/addons/thermal/__init__.py @@ -1 +1,17 @@ - +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/analysis/__init__.py b/ipie/addons/thermal/analysis/__init__.py new file mode 100644 index 00000000..f91ef518 --- /dev/null +++ b/ipie/addons/thermal/analysis/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py index 5a205c8d..72500b18 100644 --- a/ipie/addons/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -20,6 +20,7 @@ from ipie.utils.backend import arraylib as xp from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol +from ipie.estimators.energy import EnergyEstimator from ipie.estimators.estimator_base import EstimatorBase from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers @@ -42,9 +43,11 @@ def local_energy( return energies -class ThermalEnergyEstimator(EstimatorBase): +class ThermalEnergyEstimator(EnergyEstimator): def __init__(self, hamiltonian=None, trial=None, filename=None): - super().__init__() + assert hamiltonian is not None + assert trial is not None + EstimatorBase.__init__(self) self._eshift = 0.0 self.scalar_estimator = True self._data = { @@ -69,21 +72,3 @@ def compute_estimator(self, walkers, hamiltonian, trial, istep=1): self._data["E1Body"] = xp.sum(walkers.weight * energy[:, 1].real) self._data["E2Body"] = xp.sum(walkers.weight * energy[:, 2].real) return self.data - - def get_index(self, name): - index = self._data_index.get(name, None) - - if index is None: - raise RuntimeError(f"Unknown estimator {name}") - - return index - - def post_reduce_hook(self, data): - ix_proj = self._data_index["ETotal"] - ix_nume = self._data_index["ENumer"] - ix_deno = self._data_index["EDenom"] - data[ix_proj] = data[ix_nume] / data[ix_deno] - ix_nume = self._data_index["E1Body"] - data[ix_nume] = data[ix_nume] / data[ix_deno] - ix_nume = self._data_index["E2Body"] - data[ix_nume] = data[ix_nume] / data[ix_deno] diff --git a/ipie/addons/thermal/estimators/generic.py b/ipie/addons/thermal/estimators/generic.py index b136aedf..0ad971fa 100644 --- a/ipie/addons/thermal/estimators/generic.py +++ b/ipie/addons/thermal/estimators/generic.py @@ -57,7 +57,7 @@ def local_energy_generic_cholesky(hamiltonian: GenericRealChol, P): T = numpy.zeros((nbasis, nbasis), dtype=numpy.complex128) exx = 0.0j # we will iterate over cholesky index to update Ex energy for alpha and beta - for x in range(nchol): # write a cython function that calls blas for this. + for x in range(nchol): # Write a numba function that calls BLAS for this. Lmn = hamiltonian.chol[:, x].reshape((nbasis, nbasis)) T[:, :].real = PaT.real.dot(Lmn) T[:, :].imag = PaT.imag.dot(Lmn) diff --git a/ipie/addons/thermal/estimators/handler.py b/ipie/addons/thermal/estimators/handler.py index 169b5feb..9b9fdef6 100644 --- a/ipie/addons/thermal/estimators/handler.py +++ b/ipie/addons/thermal/estimators/handler.py @@ -19,17 +19,15 @@ """Routines and classes for estimation of observables.""" import os -from typing import Tuple, Union - import h5py import numpy +from typing import Tuple, Union from ipie.config import config, MPI +from ipie.estimators.handler import EstimatorHandler + from ipie.addons.thermal.estimators.energy import ThermalEnergyEstimator from ipie.addons.thermal.estimators.particle_number import ThermalNumberEstimator -from ipie.estimators.estimator_base import EstimatorBase -from ipie.estimators.utils import H5EstimatorHelper -from ipie.utils.io import format_fixed_width_strings # Some supported (non-custom) estimators _predefined_estimators = { @@ -38,20 +36,29 @@ } -class ThermalEstimatorHandler(object): +class ThermalEstimatorHandler(EstimatorHandler): """Container for qmc options of observables. Parameters ---------- comm : MPI.COMM_WORLD - MPI Communicator + MPI Communicator. + hamiltonian : :class:`ipie.hamiltonian.X' object + Hamiltonian describing the system. trial : :class:`ipie.trial_wavefunction.X' object Trial wavefunction class. + walker_state : :class:`WalkerAccumulator` object + WalkerAccumulator class. verbose : bool If true we print out additional setup information. - options: dict - input options detailing which estimators to calculate. By default only - mixed options will be calculated. + filename : str + .h5 file name for saving data. + basename : str + .h5 base name for saving data. + overwrite : bool + Whether to overwrite .h5 files. + observables : tuple + Tuple listing observables to be calculated. Attributes ---------- @@ -67,11 +74,9 @@ def __init__( walker_state=None, verbose: bool = False, filename: Union[str, None] = None, - block_size: int = 1, basename: str = "estimates", overwrite=True, observables: Tuple[str] = ("energy", "nav"), # TODO: Use factory method! - index: int = 0 ): if verbose: print("# Setting up estimator object.") @@ -112,84 +117,17 @@ def __init__( if verbose: print("# Finished settting up estimator object.") - def __setitem__(self, name: str, estimator: EstimatorBase) -> None: - over_writing = self._estimators.get(name) is not None - self._estimators[name] = estimator - if not over_writing: - self._shapes.append(estimator.shape) - if len(self._offsets.keys()) == 0: - self._offsets[name] = 0 - prev_obs = name - else: - prev_obs = list(self._offsets.keys())[-1] - offset = self._estimators[prev_obs].size + self._offsets[prev_obs] - self._offsets[name] = offset - - def get_offset(self, name: str) -> int: - offset = self._offsets.get(name) - assert offset is not None, f"Unknown estimator name {name}" - return offset - - def __getitem__(self, key): - return self._estimators[key] - - @property - def items(self): - return self._estimators.items - - @property - def size(self): - return sum(o.size for k, o in self._estimators.items()) - - def initialize(self, comm): - self.local_estimates = numpy.zeros( - (self.size + self.num_walker_props), dtype=numpy.complex128 - ) - self.global_estimates = numpy.zeros( - (self.size + self.num_walker_props), dtype=numpy.complex128 - ) - header = f"{'Block':>17s} " - header += format_fixed_width_strings(self.walker_header) - header += " " - for k, e in self.items(): - if e.print_to_stdout: - header += e.header_to_text - if comm.rank == 0: - with h5py.File(self.filename, "w") as fh5: - pass - self.dump_metadata() - self.output = H5EstimatorHelper( - self.filename, - base="block_size_1", - chunk_size=self.buffer_size, - shape=(self.size + self.num_walker_props,), - ) - if comm.rank == 0: - with h5py.File(self.filename, "r+") as fh5: - fh5["block_size_1/num_walker_props"] = self.num_walker_props - fh5["block_size_1/walker_prop_header"] = self.walker_header - for k, o in self.items(): - fh5[f"block_size_1/shape/{k}"] = o.shape - fh5[f"block_size_1/size/{k}"] = o.size - fh5[f"block_size_1/scalar/{k}"] = int(o.scalar_estimator) - fh5[f"block_size_1/names/{k}"] = " ".join(name for name in o.names) - fh5[f"block_size_1/offset/{k}"] = self.num_walker_props + self.get_offset(k) - if comm.rank == 0: - print(header) - - def dump_metadata(self): - with h5py.File(self.filename, "a") as fh5: - fh5["metadata"] = self.json_string - - def increment_file_number(self): - self.index = self.index + 1 - self.filename = self.basename + f".{self.index}.h5" - def compute_estimators(self, hamiltonian, trial, walker_batch): - """Update estimators with bached psi + """Update estimators with bached walkers. Parameters ---------- + hamiltonian : :class:`ipie.hamiltonian.X' object + Hamiltonian describing the system. + trial : :class:`ipie.trial_wavefunction.X' object + Trial wavefunction class. + walker_batch : :class:`UHFThermalWalkers' object + Walkers class. """ # Compute all estimators # For the moment only consider estimators compute per block. @@ -201,43 +139,21 @@ def compute_estimators(self, hamiltonian, trial, walker_batch): end = start + int(self[k].size) self.local_estimates[start:end] += e.data - def print_block(self, comm, block, walker_factors, div_factor=None): - self.local_estimates[: walker_factors.size] = walker_factors.buffer - comm.Reduce(self.local_estimates, self.global_estimates, op=MPI.SUM) - output_string = " " - # Get walker data. - offset = walker_factors.size - if comm.rank == 0: - walker_factors.post_reduce_hook(self.global_estimates[:offset], block) - output_string += walker_factors.to_text(self.global_estimates[:offset]) - output_string += " " - for k, e in self.items(): - if comm.rank == 0: - start = offset + self.get_offset(k) - end = start + int(self[k].size) - est_data = self.global_estimates[start:end] - e.post_reduce_hook(est_data) - est_string = e.data_to_text(est_data) - e.to_ascii_file(est_string) - if e.print_to_stdout: - output_string += est_string - if comm.rank == 0: - shift = self.global_estimates[walker_factors.get_index("HybridEnergy")] + def print_time_slice(self, comm, time_slice, walker_state): + """Print estimators at a time slice of the imgainary time propagation. - else: - shift = None - walker_factors.eshift = comm.bcast(shift) - if comm.rank == 0: - self.output.push_to_chunk(self.global_estimates, f"data") - self.output.increment() - if comm.rank == 0: - print(f"{block:>17d} " + output_string) - self.zero() - - def print_cut(self, comm, block, t, walker_factors): + Parameters + ---------- + comm : MPI.COMM_WORLD + MPI Communicator. + time_slice : int + Time slice. + walker_state : :class:`WalkerAccumulator` object + WalkerAccumulator class. + """ comm.Reduce(self.local_estimates, self.global_estimates, op=MPI.SUM) # Get walker data. - offset = walker_factors.size + offset = walker_state.size if comm.rank == 0: k = 'energy' @@ -256,12 +172,7 @@ def print_cut(self, comm, block, t, walker_factors): e.post_reduce_hook(estim_data) nav = estim_data[e.get_index("Nav")] - print(f"cut : {t} {nav.real} {etotal.real}") + print(f"cut : {time_slice} {nav.real} {etotal.real}") self.zero() - def zero(self): - self.local_estimates[:] = 0.0 - self.global_estimates[:] = 0.0 - for _, e in self.items(): - e.zero() diff --git a/ipie/addons/thermal/estimators/local_energy.py b/ipie/addons/thermal/estimators/local_energy.py index 0a50035c..cd52d740 100644 --- a/ipie/addons/thermal/estimators/local_energy.py +++ b/ipie/addons/thermal/estimators/local_energy.py @@ -16,10 +16,18 @@ # Joonho Lee # +import numpy + +from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol +from ipie.addons.thermal.trial.one_body import OneBody +from ipie.addons.thermal.trial.mean_field import MeanField from ipie.addons.thermal.estimators.generic import local_energy_generic_cholesky from ipie.addons.thermal.estimators.thermal import one_rdm_from_G -def local_energy_P(hamiltonian, trial, P): +def local_energy_from_density_matrix( + hamiltonian: Union[GenericRealChol, GenericRealCholChunked], + trial: Union[OneBody, MeanField], + P: numpy.ndarray): """Compute local energy from a given density matrix P. Parameters @@ -40,4 +48,4 @@ def local_energy_P(hamiltonian, trial, P): return local_energy_generic_cholesky(hamiltonian, P) def local_energy(hamiltonian, walker, trial): - return local_energy_P(hamiltonian, trial, one_rdm_from_G(walker.G)) + return local_energy_from_density_matrix(hamiltonian, trial, one_rdm_from_G(walker.G)) diff --git a/ipie/addons/thermal/estimators/particle_number.py b/ipie/addons/thermal/estimators/particle_number.py index a2bd5b77..63fa1f60 100644 --- a/ipie/addons/thermal/estimators/particle_number.py +++ b/ipie/addons/thermal/estimators/particle_number.py @@ -16,12 +16,13 @@ # Joonho Lee # +import numpy from ipie.utils.backend import arraylib as xp from ipie.estimators.estimator_base import EstimatorBase from ipie.addons.thermal.estimators.thermal import one_rdm_from_G -def particle_number(dmat): +def particle_number(dmat: numpy.ndarray): """Compute average particle number from the thermal 1RDM. Parameters diff --git a/ipie/addons/thermal/estimators/tests/test_estimators.py b/ipie/addons/thermal/estimators/tests/test_estimators.py index 87e3c211..15c9ebb7 100644 --- a/ipie/addons/thermal/estimators/tests/test_estimators.py +++ b/ipie/addons/thermal/estimators/tests/test_estimators.py @@ -54,9 +54,6 @@ @pytest.mark.unit def test_energy_estimator(): # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, @@ -113,9 +110,6 @@ def test_energy_estimator(): @pytest.mark.unit def test_number_estimator(): # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=True, debug=debug, @@ -144,9 +138,6 @@ def test_number_estimator(): def test_estimator_handler(): with tempfile.NamedTemporaryFile() as tmp1, tempfile.NamedTemporaryFile() as tmp2: # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=True, debug=debug, @@ -164,7 +155,6 @@ def test_estimator_handler(): comm, hamiltonian, trial, - block_size=10, observables=("energy",), filename=tmp2.name) handler["energy1"] = estim diff --git a/ipie/addons/thermal/estimators/tests/test_generic.py b/ipie/addons/thermal/estimators/tests/test_generic.py index 606fbda0..4205ab58 100644 --- a/ipie/addons/thermal/estimators/tests/test_generic.py +++ b/ipie/addons/thermal/estimators/tests/test_generic.py @@ -82,10 +82,6 @@ def test_local_energy_cholesky(mf_trial=False): legacy_eloc = legacy_local_energy_generic_cholesky( legacy_system, legacy_hamiltonian, legacy_P) - if verbose: - print(f'\neloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') - numpy.testing.assert_allclose(trial.G, legacy_trial.G, atol=1e-10) numpy.testing.assert_allclose(P, legacy_P, atol=1e-10) numpy.testing.assert_allclose(eloc, legacy_eloc, atol=1e-10) diff --git a/ipie/addons/thermal/propagation/phaseless_base.py b/ipie/addons/thermal/propagation/phaseless_base.py index cd6250d9..c5fac4dc 100644 --- a/ipie/addons/thermal/propagation/phaseless_base.py +++ b/ipie/addons/thermal/propagation/phaseless_base.py @@ -32,7 +32,7 @@ from ipie.addons.thermal.estimators.thermal import one_rdm_from_G from ipie.addons.thermal.propagation.force_bias import construct_force_bias -# TODO: Add lowrank implementation. +# TODO: Add lowrank implementation. See: https://github.com/JoonhoLee-Group/ipie/issues/302 # Ref: 10.1103/PhysRevB.80.214116 for bounds. @plum.dispatch diff --git a/ipie/addons/thermal/propagation/tests/__init__.py b/ipie/addons/thermal/propagation/tests/__init__.py new file mode 100644 index 00000000..f91ef518 --- /dev/null +++ b/ipie/addons/thermal/propagation/tests/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/propagation/tests/test_prop_generic.py b/ipie/addons/thermal/propagation/tests/test_prop_generic.py index 0dfc8a8a..c2e7377d 100644 --- a/ipie/addons/thermal/propagation/tests/test_prop_generic.py +++ b/ipie/addons/thermal/propagation/tests/test_prop_generic.py @@ -63,9 +63,6 @@ @pytest.mark.unit def test_mf_shift(): # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, @@ -74,19 +71,12 @@ def test_mf_shift(): propagator = objs['propagator'] # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, seed=seed, verbose=verbose) legacy_propagator = legacy_objs['propagator'] - if verbose: - print(f'\nlegacy_mf_shift = \n{legacy_propagator.propagator.mf_shift}\n') - print(f'mf_shift = \n{propagator.mf_shift}\n') - numpy.testing.assert_almost_equal(legacy_propagator.propagator.mf_shift, propagator.mf_shift, decimal=10) @@ -95,9 +85,6 @@ def test_mf_shift(): @pytest.mark.unit def test_BH1(): # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, @@ -106,19 +93,12 @@ def test_BH1(): propagator = objs['propagator'] # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, seed=seed, verbose=verbose) legacy_propagator = legacy_objs['propagator'] - if verbose: - print(f'\nlegacy_BH1 = \n{legacy_propagator.propagator.BH1}\n') - print(f'BH1 = \n{propagator.BH1}\n') - numpy.testing.assert_almost_equal(legacy_propagator.propagator.BH1, propagator.BH1, decimal=10) @@ -127,9 +107,6 @@ def test_BH1(): @pytest.mark.unit def test_construct_two_body_propagator(): # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, @@ -140,9 +117,6 @@ def test_construct_two_body_propagator(): propagator = objs['propagator'] # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, @@ -171,19 +145,6 @@ def test_construct_two_body_propagator(): legacy_xshifted = numpy.array(legacy_xshifted).T - if verbose: - print(f'\nlegacy_cmf = {legacy_cmf}') - print(f'cmf = {cmf}') - - print(f'\nlegacy_cfb = {legacy_cfb}') - print(f'cfb = {cfb}') - - print(f'\nlegacy_xshifted = \n{legacy_xshifted}\n') - print(f'xshifted = \n{xshifted}\n') - - print(f'legacy_VHS = \n{legacy_VHS}\n') - print(f'VHS = \n{VHS}\n') - numpy.testing.assert_almost_equal(legacy_cmf, cmf, decimal=10) numpy.testing.assert_almost_equal(legacy_cfb, cfb, decimal=10) numpy.testing.assert_almost_equal(legacy_xshifted, xshifted, decimal=10) @@ -194,9 +155,6 @@ def test_construct_two_body_propagator(): @pytest.mark.unit def test_phaseless_generic_propagator(): # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, @@ -207,9 +165,6 @@ def test_phaseless_generic_propagator(): propagator = objs['propagator'] # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') legacy_objs = build_legacy_generic_test_case_handlers( hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, @@ -229,14 +184,6 @@ def test_phaseless_generic_propagator(): legacy_eloc = legacy_local_energy_generic_cholesky( legacy_system, legacy_hamiltonian, legacy_P) - if verbose: - print(f'\nt = {t}') - print(f'iw = {iw}') - print(f'eloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') - print(f'walkers.weight = \n{walkers.weight[iw]}\n') - print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') - numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) numpy.testing.assert_allclose(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw]) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) diff --git a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py index eabec6bc..c7a788c5 100644 --- a/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py +++ b/ipie/addons/thermal/propagation/tests/ueg/test_prop_ueg.py @@ -61,9 +61,6 @@ def test_phaseless_ueg_propagator(): numpy.random.seed(seed) # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_ueg_test_case_handlers( nelec, rs, ecut, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, debug=debug, seed=seed, verbose=verbose) @@ -73,9 +70,6 @@ def test_phaseless_ueg_propagator(): propagator = objs['propagator'] # Legacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') legacy_objs = build_legacy_ueg_test_case_handlers( comm, nelec, rs, ecut, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, seed=seed, verbose=verbose) @@ -109,15 +103,6 @@ def test_phaseless_ueg_propagator(): exx -= 0.5 * numpy.einsum('ijkl,il,kj->', eri, Pb, Pb) ref_e2 = ecoul + exx ref_eloc = (ref_e1 + ref_e2, ref_e1, ref_e2) - - if verbose: - print(f'\nt = {t}') - print(f'iw = {iw}') - print(f'eloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') - print(f'ref_eloc = \n{ref_eloc}\n') - print(f'walkers.weight = \n{walkers.weight[iw]}\n') - print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') numpy.testing.assert_almost_equal(legacy_P, P, decimal=10) numpy.testing.assert_almost_equal(legacy_trial.dmat, trial.dmat, decimal=10) diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index 9f445df9..5c9e7683 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -25,6 +25,7 @@ from ipie.systems.utils import get_system from ipie.hamiltonians.utils import get_hamiltonian +from ipie.qmc.calc import init_communicator, setup_calculation, read_input from ipie.addons.thermal.trial.utils import get_trial_density_matrix from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers @@ -33,20 +34,6 @@ from ipie.addons.thermal.qmc.thermal_afqmc import ThermalAFQMC -def init_communicator(): - return MPI.COMM_WORLD - - -def setup_calculation(input_options): - comm = init_communicator() - if isinstance(input_options, str): - options = read_input(input_options, comm, verbose=True) - else: - options = input_options - afqmc = get_driver(options, comm) - return (afqmc, comm) - - def get_driver(options: dict, comm: MPI.COMM_WORLD) -> ThermalAFQMC: verbosity = options.get("verbosity", 1) qmc_opts = get_input_value(options, "qmc", default={}, alias=["qmc_options"]) @@ -162,38 +149,3 @@ def build_thermal_afqmc_driver( options["verbosity"] = verbosity return get_driver(options, comm) - - -def read_input(input_file, comm, verbose=False): - """Helper function to parse input file and setup parallel calculation. - - Parameters - ---------- - input_file : string - Input filename. - verbose : bool - If true print out set up information. - - Returns - ------- - options : dict - Python dict of input options. - comm : MPI communicator - Communicator object. If mpi4py is not installed then we return a fake - communicator. - """ - if comm.rank == 0: - if verbose: - print(f"# Initialising pie simulation from {input_file}") - try: - with open(input_file) as inp: - options = json.load(inp) - except FileNotFoundError: - options = None - else: - options = None - options = comm.bcast(options, root=0) - if options == None: - raise FileNotFoundError - - return options diff --git a/ipie/addons/thermal/qmc/options.py b/ipie/addons/thermal/qmc/options.py index 9e2949da..671bedab 100644 --- a/ipie/addons/thermal/qmc/options.py +++ b/ipie/addons/thermal/qmc/options.py @@ -17,12 +17,11 @@ # from dataclasses import dataclass -from typing import ClassVar +from typing import ClassVar, Optional from ipie.utils.io import get_input_value from ipie.qmc.options import QMCOpts, QMCParams -_no_default = object() class ThermalQMCOpts(QMCOpts): r"""Input options and certain constants / parameters derived from them. @@ -110,20 +109,14 @@ class ThermalQMCParams(QMCParams): """ # Due to structure of FT algorithm, `num_steps_per_block` is fixed at 1. # Overide whatever input for backward compatibility. - num_steps_per_block: ClassVar[float] = 1 - mu: float = _no_default - beta: float = _no_default + num_steps_per_block: ClassVar[int] = 1 + mu: Optional[float] = None + beta: Optional[float] = None pop_control_method: str = 'pair_branch' - # This is a hack to get around the error: - # - # TypeError: non-default argument follows default argument - # - # due to inheritance from the QMCParams dataclass which has default attributes. - # Ref: https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses def __post_init__(self): - if self.mu is _no_default: + if self.mu is None: raise TypeError("__init__ missing 1 required argument: 'mu'") - if self.beta is _no_default: + if self.beta is None: raise TypeError("__init__ missing 1 required argument: 'beta'") diff --git a/ipie/addons/thermal/qmc/tests/__init__.py b/ipie/addons/thermal/qmc/tests/__init__.py new file mode 100644 index 00000000..f91ef518 --- /dev/null +++ b/ipie/addons/thermal/qmc/tests/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py index 9dbc2f89..88e138b1 100644 --- a/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py +++ b/ipie/addons/thermal/qmc/tests/test_afqmc_generic.py @@ -84,11 +84,6 @@ def test_thermal_afqmc(): # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- - if verbose: - print('\n-----------------------') - print('Running ThermalAFQMC...') - print('-----------------------') - afqmc = build_driver_generic_test_instance( nelec, nbasis, mu, beta, timestep, nblocks, nwalkers=nwalkers, lowrank=lowrank, pop_control_method=pop_control_method, @@ -113,11 +108,6 @@ def test_thermal_afqmc(): # --------------------------------------------------------------------- # Legacy. # --------------------------------------------------------------------- - if verbose: - print('\n------------------------------') - print('Running Legacy ThermalAFQMC...') - print('------------------------------') - legacy_afqmc = build_legacy_driver_generic_test_instance( afqmc.hamiltonian, comm, nelec, mu, beta, timestep, nblocks, nwalkers=nwalkers, lowrank=lowrank, @@ -147,12 +137,6 @@ def test_thermal_afqmc(): legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - print(f'\ntest filename: {afqmc.estimators.filename}') - print(f'legacy filename: {legacy_afqmc.estimators.filename}') - print(f'\ntest_energy_data: \n{test_energy_data}\n') - print(f'test_number_data: \n{test_number_data}\n') - print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') - # Check. assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) diff --git a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py index 39f44cf3..a8906a84 100644 --- a/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py +++ b/ipie/addons/thermal/qmc/tests/ueg/test_afqmc_ueg.py @@ -121,11 +121,6 @@ def test_thermal_afqmc_1walker(against_ref=False): # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- - if verbose: - print('\n-----------------------') - print('Running ThermalAFQMC...') - print('-----------------------') - afqmc = build_driver_ueg_test_instance( nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, lowrank=lowrank, pop_control_method=pop_control_method, @@ -149,11 +144,6 @@ def test_thermal_afqmc_1walker(against_ref=False): # --------------------------------------------------------------------- # Legacy. # --------------------------------------------------------------------- - if verbose: - print('\n------------------------------') - print('Running Legacy ThermalAFQMC...') - print('------------------------------') - legacy_afqmc = build_legacy_driver_ueg_test_instance( comm, nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, lowrank=lowrank, @@ -183,12 +173,6 @@ def test_thermal_afqmc_1walker(against_ref=False): legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - print(f'\ntest filename: {afqmc.estimators.filename}') - print(f'legacy filename: {legacy_afqmc.estimators.filename}') - print(f'\ntest_energy_data: \n{test_energy_data}\n') - print(f'test_number_data: \n{test_number_data}\n') - print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') - # Check. assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) @@ -287,11 +271,6 @@ def test_thermal_afqmc(against_ref=False): # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- - if verbose: - print('\n-----------------------') - print('Running ThermalAFQMC...') - print('-----------------------') - afqmc = build_driver_ueg_test_instance( nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, lowrank=lowrank, pop_control_method=pop_control_method, @@ -315,11 +294,6 @@ def test_thermal_afqmc(against_ref=False): # --------------------------------------------------------------------- # Legacy. # --------------------------------------------------------------------- - if verbose: - print('\n------------------------------') - print('Running Legacy ThermalAFQMC...') - print('------------------------------') - legacy_afqmc = build_legacy_driver_ueg_test_instance( comm, nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, lowrank=lowrank, @@ -349,12 +323,6 @@ def test_thermal_afqmc(against_ref=False): legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - print(f'\ntest filename: {afqmc.estimators.filename}') - print(f'legacy filename: {legacy_afqmc.estimators.filename}') - print(f'\ntest_energy_data: \n{test_energy_data}\n') - print(f'test_number_data: \n{test_number_data}\n') - print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') - # Check. assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) @@ -453,11 +421,6 @@ def test_thermal_afqmc_mpi(against_ref=False): # --------------------------------------------------------------------- # Test. # --------------------------------------------------------------------- - if verbose: - print('\n-----------------------') - print('Running ThermalAFQMC...') - print('-----------------------') - afqmc = build_driver_ueg_test_instance( nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, lowrank=lowrank, pop_control_method=pop_control_method, @@ -481,11 +444,6 @@ def test_thermal_afqmc_mpi(against_ref=False): # --------------------------------------------------------------------- # Legacy. # --------------------------------------------------------------------- - if verbose: - print('\n------------------------------') - print('Running Legacy ThermalAFQMC...') - print('------------------------------') - legacy_afqmc = build_legacy_driver_ueg_test_instance( comm, nelec, rs, ecut, mu, beta, timestep, nblocks, nwalkers=nwalkers, lowrank=lowrank, @@ -515,12 +473,6 @@ def test_thermal_afqmc_mpi(against_ref=False): legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - print(f'\ntest filename: {afqmc.estimators.filename}') - print(f'legacy filename: {legacy_afqmc.estimators.filename}') - print(f'\ntest_energy_data: \n{test_energy_data}\n') - print(f'test_number_data: \n{test_number_data}\n') - print(f'legacy_mixed_data: \n{legacy_mixed_data}\n') - # Check. assert test_energy_numer.real == pytest.approx(legacy_energy_numer.real) assert test_energy_denom.real == pytest.approx(legacy_energy_denom.real) diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index f96f2f46..37c5232d 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -181,7 +181,8 @@ def run(self, walkers = None, verbose: bool = True, estimator_filename = None, - additional_estimators: Optional[Dict[str, EstimatorBase]] = None): + additional_estimators: Optional[Dict[str, EstimatorBase]] = None, + print_time_slice: bool = False): """Perform Thermal AFQMC simulation on state object using open-ended random walk. Parameters @@ -230,7 +231,7 @@ def run(self, for step in range(1, total_steps + 1): synchronize() - start_path = time.time() + start_step = time.time() for t in range(nslices): if self.verbosity >= 2 and comm.rank == 0: @@ -271,11 +272,11 @@ def run(self, self.tpopc_comm = self.pcontrol.timer.communication_time self.tpopc_non_comm = self.pcontrol.timer.non_communication_time - # Print cut. - #self.estimators.compute_estimators( - # self.hamiltonian, self.trial, self.walkers) - #self.estimators.print_cut( - # comm, step // self.params.num_steps_per_block, t, self.accumulators) + # Print estimators at each time slice. + if print_time_slice: + self.estimators.compute_estimators( + self.hamiltonian, self.trial, self.walkers) + self.estimators.print_time_slice(comm, t, self.accumulators) # Accumulate weight, hybrid energy etc. across block. start = time.time() @@ -304,125 +305,7 @@ def run(self, self.walkers.reset(self.trial) # Reset stack, weights, phase. synchronize() - self.tpath += time.time() - start_path - - - def finalise(self, verbose=False): - """Tidy up. - - Parameters - ---------- - verbose : bool - If true print out some information to stdout. - """ - nsteps_per_block = max(self.params.num_steps_per_block, 1) - nblocks = max(self.params.num_blocks, 1) - nstblz = max(nsteps_per_block // self.params.num_stblz, 1) - npcon = max(nsteps_per_block // self.params.pop_control_freq, 1) - - if self.mpi_handler.rank == 0: - if verbose: - print(f"# End Time: {time.asctime():s}") - print(f"# Running time : {time.time() - self._init_time:.6f} seconds") - print("# Timing breakdown (per call, total calls per block, total blocks):") - print(f"# - Setup: {self.tsetup:.6f} s") - print( - "# - Path update: {:.6f} s / block for {} total blocks".format( - self.tpath / (nblocks), nblocks - ) - ) - print( - "# - Propagation: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tprop / (nblocks * nsteps_per_block), nsteps_per_block, nblocks - ) - ) - print( - "# - Force bias: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tprop_fbias / (nblocks * nsteps_per_block), nsteps_per_block, nblocks - ) - ) - print( - "# - VHS: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tprop_vhs / (nblocks * nsteps_per_block), nsteps_per_block, nblocks - ) - ) - print( - "# - Green's Function: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tprop_gf / (nblocks * nsteps_per_block), nsteps_per_block, nblocks - ) - ) - print( - "# - Overlap: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tprop_ovlp / (nblocks * nsteps_per_block), nsteps_per_block, nblocks - ) - ) - print( - "# - Weights Update: {:.6f} s / call for {} call(s) in each of {} blocks".format( - (self.tprop_update + self.tprop_clip) / (nblocks * nsteps_per_block), - nsteps_per_block, - nblocks, - ) - ) - print( - "# - GEMM operations: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tprop_gemm / (nblocks * nsteps_per_block), nsteps_per_block, nblocks - ) - ) - print( - "# - Barrier: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tprop_barrier / (nblocks * nsteps_per_block), nsteps_per_block, nblocks - ) - ) - print( - "# - Estimators: {:.6f} s / call for {} call(s)".format( - self.testim / nblocks, nblocks - ) - ) - print( - "# - Orthogonalisation: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tortho / (nstblz * nblocks), nstblz, nblocks - ) - ) - print( - "# - Population control: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tpopc / (npcon * nblocks), npcon, nblocks - ) - ) - print( - "# - Commnication: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tpopc_comm / (npcon * nblocks), npcon, nblocks - ) - ) - print( - "# - Non-Commnication: {:.6f} s / call for {} call(s) in each of {} blocks".format( - self.tpopc_non_comm / (npcon * nblocks), npcon, nblocks - ) - ) - - - def get_env_info(self): - this_uuid = str(uuid.uuid1()) - - try: - sha1, branch, local_mods = get_git_info() - - except: - sha1 = "None" - branch = "None" - local_mods = [] - - if self.verbose: - self.sys_info = print_env_info( - sha1, - branch, - local_mods, - this_uuid, - self.mpi_handler.size, - ) - - mem_avail = get_host_memory() - print(f"# Available memory on the node is {mem_avail:4.3f} GB") - + self.tstep += time.time() - start_step def setup_estimators( self, @@ -456,17 +339,3 @@ def setup_estimators( self.estimators.print_block(comm, 0, self.accumulators) self.accumulators.zero() - - def setup_timers(self): - self.tsetup = 0 - self.tpath = 0 - - self.tprop = 0 - self.tprop_barrier = 0 - self.tprop_fbias = 0 - self.tprop_update = 0 - self.tprop_vhs = 0 - self.tprop_clip = 0 - - self.testim = 0 - self.tpopc = 0 diff --git a/ipie/addons/thermal/trial/mean_field.py b/ipie/addons/thermal/trial/mean_field.py index 06712da4..4ba6fa78 100644 --- a/ipie/addons/thermal/trial/mean_field.py +++ b/ipie/addons/thermal/trial/mean_field.py @@ -31,7 +31,7 @@ def __init__(self, hamiltonian, nelec, beta, dt, options=None, alt_convention=Fa if options is None: options = {} - OneBody.__init__(self, hamiltonian, nelec, beta, dt, options=options, + super().__init__(hamiltonian, nelec, beta, dt, options=options, alt_convention=alt_convention, H1=H1, verbose=verbose) if verbose: print("# Building THF density matrix.") diff --git a/ipie/addons/thermal/trial/one_body.py b/ipie/addons/thermal/trial/one_body.py index f18b6ff9..c982d452 100644 --- a/ipie/addons/thermal/trial/one_body.py +++ b/ipie/addons/thermal/trial/one_body.py @@ -26,7 +26,7 @@ from ipie.utils.misc import update_stack -class OneBody(object): +class OneBody: def __init__(self, hamiltonian, nelec, beta, dt, options=None, alt_convention=False, H1=None, verbose=False): if options is None: diff --git a/ipie/addons/thermal/trial/tests/__init__.py b/ipie/addons/thermal/trial/tests/__init__.py new file mode 100644 index 00000000..f91ef518 --- /dev/null +++ b/ipie/addons/thermal/trial/tests/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/trial/tests/test_mean_field.py b/ipie/addons/thermal/trial/tests/test_mean_field.py index 6d5ca3b3..8c3aaf6d 100644 --- a/ipie/addons/thermal/trial/tests/test_mean_field.py +++ b/ipie/addons/thermal/trial/tests/test_mean_field.py @@ -20,7 +20,7 @@ import pytest try: - import ipie.legacy.estimators.ueg_kernels + from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField _no_cython = False except ModuleNotFoundError: @@ -29,11 +29,8 @@ from ipie.systems.generic import Generic from ipie.utils.testing import generate_hamiltonian from ipie.hamiltonians.generic import Generic as HamGeneric - from ipie.addons.thermal.trial.mean_field import MeanField - from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric -from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField @pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") @@ -57,9 +54,6 @@ def test_mean_field(): if complex_integrals: sym = 4 # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') system = Generic(nelec) h1e, chol, _, eri = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, sym=sym, tol=1e-10) @@ -69,9 +63,6 @@ def test_mean_field(): trial = MeanField(hamiltonian, nelec, beta, timestep, verbose=verbose) # Lgeacy. - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') legacy_system = Generic(nelec, verbose=verbose) legacy_system.mu = mu legacy_hamiltonian = LegacyHamGeneric( diff --git a/ipie/addons/thermal/trial/tests/test_one_body.py b/ipie/addons/thermal/trial/tests/test_one_body.py index 7a290a70..bdc7dce8 100644 --- a/ipie/addons/thermal/trial/tests/test_one_body.py +++ b/ipie/addons/thermal/trial/tests/test_one_body.py @@ -43,9 +43,6 @@ def test_one_body(): if complex_integrals: sym = 4 # Test. - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') system = Generic(nelec) h1e, chol, _, eri = generate_hamiltonian(nbasis, nelec, cplx=complex_integrals, sym=sym, tol=1e-10) diff --git a/ipie/addons/thermal/utils/__init__.py b/ipie/addons/thermal/utils/__init__.py new file mode 100644 index 00000000..f91ef518 --- /dev/null +++ b/ipie/addons/thermal/utils/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2022 The ipie Developers. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Authors: Fionn Malone +# Joonho Lee +# diff --git a/ipie/addons/thermal/utils/ueg.py b/ipie/addons/thermal/utils/ueg.py index 3df52dcd..9b0b670a 100644 --- a/ipie/addons/thermal/utils/ueg.py +++ b/ipie/addons/thermal/utils/ueg.py @@ -20,10 +20,7 @@ import scipy.sparse from ipie.utils.io import write_qmcpack_sparse -# ----------------------------------------------------------------------------- -# System class. -# ----------------------------------------------------------------------------- -class UEG(object): +class UEG: """UEG system class (integrals read from fcidump) Parameters diff --git a/ipie/addons/thermal/walkers/stack.py b/ipie/addons/thermal/walkers/stack.py index 09ac8c81..af048b77 100644 --- a/ipie/addons/thermal/walkers/stack.py +++ b/ipie/addons/thermal/walkers/stack.py @@ -16,6 +16,9 @@ # Joonho Lee # +# TODO: Incorporate the `stack` buffer in the `walkers` buffer for MPI. See: +# https://github.com/JoonhoLee-Group/ipie/issues/301 + import numpy import scipy.linalg diff --git a/ipie/addons/thermal/walkers/tests/test_population_control.py b/ipie/addons/thermal/walkers/tests/test_population_control.py index b5a2cc5c..9250e5d5 100644 --- a/ipie/addons/thermal/walkers/tests/test_population_control.py +++ b/ipie/addons/thermal/walkers/tests/test_population_control.py @@ -65,11 +65,6 @@ def test_pair_branch_batch(): numpy.random.seed(seed) # Test. - if verbose: - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers_mpi( nelec, nbasis, mu, beta, timestep, mpi_handler, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, @@ -82,11 +77,6 @@ def test_pair_branch_batch(): pop_control_method, verbose=verbose) # Legacy. - if verbose: - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_objs = build_legacy_generic_test_case_handlers_mpi( hamiltonian, mpi_handler, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, @@ -99,16 +89,6 @@ def test_pair_branch_batch(): for block in range(nblocks): for t in range(walkers.stack[0].nslice): - if verbose: - print('\n------------------------------------------') - print(f'block = {block}, t = {t}') - print(f'walkers.weight[0] = {walkers.weight[0]}') - print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') - print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') - print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') - print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') - print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') - propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) legacy_walkers = legacy_propagate_walkers( legacy_hamiltonian, legacy_trial, legacy_walkers, @@ -127,7 +107,7 @@ def test_pair_branch_batch(): assert numpy.allclose(walkers.weight[iw], legacy_walkers.walkers[iw].weight) assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) -# TODO: Lowrank code is WIP. +# TODO: Lowrank code is WIP. See: https://github.com/JoonhoLee-Group/ipie/issues/302 #@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") #@pytest.mark.unit def test_pair_branch_batch_lowrank(): @@ -179,11 +159,6 @@ def test_pair_branch_batch_lowrank(): } # Test. - if verbose: - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers_mpi( nelec, nbasis, mu, beta, timestep, mpi_handler, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, @@ -196,11 +171,6 @@ def test_pair_branch_batch_lowrank(): pop_control_method=pop_control_method, verbose=verbose) # Legacy. - if verbose: - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_objs = build_legacy_generic_test_case_handlers_mpi( hamiltonian, mpi_handler, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, @@ -213,16 +183,6 @@ def test_pair_branch_batch_lowrank(): for block in range(nblocks): for t in range(walkers.stack[0].nslice): - if verbose: - print('\n------------------------------------------') - print(f'block = {block}, t = {t}') - print(f'walkers.weight[0] = {walkers.weight[0]}') - print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') - print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') - print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') - print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') - print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') - propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) legacy_walkers = legacy_propagate_walkers( legacy_hamiltonian, legacy_trial, legacy_walkers, @@ -271,11 +231,6 @@ def test_comb_batch(): numpy.random.seed(seed) # Test. - if verbose: - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers_mpi( nelec, nbasis, mu, beta, timestep, mpi_handler, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, @@ -288,11 +243,6 @@ def test_comb_batch(): pop_control_method=pop_control_method, verbose=verbose) # Legacy. - if verbose: - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_objs = build_legacy_generic_test_case_handlers_mpi( hamiltonian, mpi_handler, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, @@ -306,16 +256,6 @@ def test_comb_batch(): for block in range(nblocks): for t in range(walkers.stack[0].nslice): - if verbose: - print('\n------------------------------------------') - print(f'block = {block}, t = {t}') - print(f'walkers.weight[0] = {walkers.weight[0]}') - print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') - print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') - print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') - print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') - print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') - propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) legacy_walkers = legacy_propagate_walkers( legacy_hamiltonian, legacy_trial, legacy_walkers, @@ -335,6 +275,7 @@ def test_comb_batch(): assert numpy.allclose(walkers.unscaled_weight[iw], legacy_walkers.walkers[iw].unscaled_weight) +# TODO: Lowrank code is WIP. See: https://github.com/JoonhoLee-Group/ipie/issues/302 #@pytest.mark.skipif(_no_cython, reason="Need to build cython modules.") #@pytest.mark.unit def test_comb_batch_lowrank(): @@ -366,11 +307,6 @@ def test_comb_batch_lowrank(): numpy.random.seed(seed) # Test. - if verbose: - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers_mpi( nelec, nbasis, mu, beta, timestep, mpi_handler, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, @@ -383,11 +319,6 @@ def test_comb_batch_lowrank(): pop_control_method=pop_control_method, verbose=verbose) # Legacy. - if verbose: - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_objs = build_legacy_generic_test_case_handlers_mpi( hamiltonian, mpi_handler, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, @@ -400,16 +331,6 @@ def test_comb_batch_lowrank(): for block in range(nblocks): for t in range(walkers.stack[0].nslice): - if verbose: - print('\n------------------------------------------') - print(f'block = {block}, t = {t}') - print(f'walkers.weight[0] = {walkers.weight[0]}') - print(f'legacy_walkers.walkers[0].weight = {legacy_walkers.walkers[0].weight}') - print(f'diff = {walkers.weight[0] - legacy_walkers.walkers[0].weight}') - print(f'\nwalkers.unscaled_weight[0] = {walkers.unscaled_weight[0]}') - print(f'legacy_walkers.walkers[0].unscaled_weight = {legacy_walkers.walkers[0].unscaled_weight}') - print(f'diff = {walkers.unscaled_weight[0] - legacy_walkers.walkers[0].unscaled_weight}') - propagator.propagate_walkers(walkers, hamiltonian, trial, debug=True) legacy_walkers = legacy_propagate_walkers( legacy_hamiltonian, legacy_trial, legacy_walkers, diff --git a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py index d7b7a86d..a02da99c 100644 --- a/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py +++ b/ipie/addons/thermal/walkers/tests/test_thermal_walkers.py @@ -62,11 +62,6 @@ def test_thermal_walkers_fullrank(): numpy.random.seed(seed) # Test. - if verbose: - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') - objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, @@ -76,11 +71,6 @@ def test_thermal_walkers_fullrank(): walkers = objs['walkers'] # Legacy. - if verbose: - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_objs = build_legacy_generic_test_case_handlers( hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, seed=seed, verbose=verbose) @@ -97,14 +87,7 @@ def test_thermal_walkers_fullrank(): legacy_eloc = legacy_local_energy_generic_cholesky( legacy_system, legacy_hamiltonian, legacy_P) - if verbose: - print(f'\niw = {iw}') - print(f'eloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') - print(f'walkers.weight = \n{walkers.weight[iw]}\n') - print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') - - #numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) + numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].stack.ovlp[0], walkers.stack[iw].ovlp[0], decimal=10) @@ -137,10 +120,6 @@ def test_thermal_walkers_lowrank(): numpy.random.seed(seed) # Test. - if verbose: - print('\n----------------------------') - print('Constructing test objects...') - print('----------------------------') objs = build_generic_test_case_handlers( nelec, nbasis, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, complex_integrals=complex_integrals, debug=debug, @@ -150,11 +129,6 @@ def test_thermal_walkers_lowrank(): walkers = objs['walkers'] # Legacy. - if verbose: - print('\n------------------------------') - print('Constructing legacy objects...') - print('------------------------------') - legacy_objs = build_legacy_generic_test_case_handlers( hamiltonian, comm, nelec, mu, beta, timestep, nwalkers=nwalkers, lowrank=lowrank, mf_trial=mf_trial, seed=seed, verbose=verbose) @@ -171,13 +145,6 @@ def test_thermal_walkers_lowrank(): legacy_eloc = legacy_local_energy_generic_cholesky( legacy_system, legacy_hamiltonian, legacy_P) - if verbose: - print(f'\niw = {iw}') - print(f'eloc = \n{eloc}\n') - print(f'legacy_eloc = \n{legacy_eloc}\n') - print(f'walkers.weight = \n{walkers.weight[iw]}\n') - print(f'legacy_walkers.weight = \n{legacy_walkers.walkers[iw].weight}\n') - numpy.testing.assert_almost_equal(legacy_eloc, eloc, decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[0], walkers.Ga[iw], decimal=10) numpy.testing.assert_almost_equal(legacy_walkers.walkers[iw].G[1], walkers.Gb[iw], decimal=10) diff --git a/ipie/addons/thermal/walkers/uhf_walkers.py b/ipie/addons/thermal/walkers/uhf_walkers.py index 8b438f7e..e3cac522 100644 --- a/ipie/addons/thermal/walkers/uhf_walkers.py +++ b/ipie/addons/thermal/walkers/uhf_walkers.py @@ -119,17 +119,6 @@ def __init__( for iw in range(self.nwalkers): self.stack[iw].ovlp = numpy.array([1.0 / self.M0a[iw], 1.0 / self.M0b[iw]]) - # # Temporary storage for stacks... - # We should kill these here and store them in stack (10/02/2023) - # I = numpy.identity(self.nbasis, dtype=numpy.complex128) - # One = numpy.ones(self.nbasis, dtype=numpy.complex128) - # self.Tl = numpy.array([I, I]) - # self.Ql = numpy.array([I, I]) - # self.Dl = numpy.array([One, One]) - # self.Tr = numpy.array([I, I]) - # self.Qr = numpy.array([I, I]) - # self.Dr = numpy.array([One, One]) - self.hybrid_energy = 0.0 if verbose: for iw in range(self.nwalkers): diff --git a/ipie/trial_wavefunction/single_det.py b/ipie/trial_wavefunction/single_det.py index 5194a6e9..3af4e335 100644 --- a/ipie/trial_wavefunction/single_det.py +++ b/ipie/trial_wavefunction/single_det.py @@ -78,7 +78,6 @@ def calculate_energy(self, system, hamiltonian) -> numpy.ndarray: self.energy = self.e1b + self.e2b if self.verbose: - print("# (Ej, Ek) = {}, {}".format(self.ej, self.ek)) print( "# (E, E1B, E2B): (%13.8e, %13.8e, %13.8e)" % (self.energy.real, self.e1b.real, self.e2b.real) From a88f3ac23dcfc7395a148beeebc69dfb3f02177c Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 10 Apr 2024 14:52:43 -0400 Subject: [PATCH 81/84] Bugfixes and addressing https://github.com/JoonhoLee-Group/ipie/pull/296#discussion_r1559782088 --- ipie/addons/thermal/estimators/energy.py | 20 +-- .../addons/thermal/estimators/local_energy.py | 3 +- ipie/addons/thermal/qmc/tests/run_legacy.py | 146 ------------------ ipie/addons/thermal/utils/ueg.py | 22 --- ipie/estimators/energy.py | 3 - 5 files changed, 4 insertions(+), 190 deletions(-) delete mode 100644 ipie/addons/thermal/qmc/tests/run_legacy.py diff --git a/ipie/addons/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py index 72500b18..74983e53 100644 --- a/ipie/addons/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -44,24 +44,8 @@ def local_energy( class ThermalEnergyEstimator(EnergyEstimator): - def __init__(self, hamiltonian=None, trial=None, filename=None): - assert hamiltonian is not None - assert trial is not None - EstimatorBase.__init__(self) - self._eshift = 0.0 - self.scalar_estimator = True - self._data = { - "ENumer": 0.0j, - "EDenom": 0.0j, - "ETotal": 0.0j, - "E1Body": 0.0j, - "E2Body": 0.0j, - } - - self._shape = (len(self.names),) - self._data_index = {k: i for i, k in enumerate(list(self._data.keys()))} - self.print_to_stdout = True - self.ascii_filename = filename + def __init__(self, system=None, hamiltonian=None, trial=None, filename=None): + super().__init__(system=system, ham=hamiltonian, trial=trial, filename=filename) def compute_estimator(self, walkers, hamiltonian, trial, istep=1): # Need to be able to dispatch here. diff --git a/ipie/addons/thermal/estimators/local_energy.py b/ipie/addons/thermal/estimators/local_energy.py index cd52d740..34a06775 100644 --- a/ipie/addons/thermal/estimators/local_energy.py +++ b/ipie/addons/thermal/estimators/local_energy.py @@ -17,6 +17,7 @@ # import numpy +from typing import Union from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol from ipie.addons.thermal.trial.one_body import OneBody @@ -25,7 +26,7 @@ from ipie.addons.thermal.estimators.thermal import one_rdm_from_G def local_energy_from_density_matrix( - hamiltonian: Union[GenericRealChol, GenericRealCholChunked], + hamiltonian: Union[GenericRealChol, GenericComplexChol], trial: Union[OneBody, MeanField], P: numpy.ndarray): """Compute local energy from a given density matrix P. diff --git a/ipie/addons/thermal/qmc/tests/run_legacy.py b/ipie/addons/thermal/qmc/tests/run_legacy.py deleted file mode 100644 index a316e6ec..00000000 --- a/ipie/addons/thermal/qmc/tests/run_legacy.py +++ /dev/null @@ -1,146 +0,0 @@ -# Copyright 2022 The ipie Developers. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Authors: Fionn Malone -# Joonho Lee -# - -import json -import os -import sys -import tempfile -import uuid -import numpy -from typing import Tuple, Union - -from ipie.config import MPI -from ipie.addons.thermal.utils.testing import build_driver_ueg_test_instance -from ipie.addons.thermal.utils.legacy_testing import build_legacy_driver_ueg_test_instance -from ipie.analysis.extraction import ( - extract_test_data_hdf5, - extract_data, - extract_observable, - extract_mixed_estimates) - -comm = MPI.COMM_WORLD -serial_test = comm.size == 1 - -# Unique filename to avoid name collision when running through CI. -if comm.rank == 0: - test_id = str(uuid.uuid1()) - -else: - test_id = None - -test_id = comm.bcast(test_id, root=0) - - -def run_legacy(): - # UEG params. - nup = 1 - ndown = 1 - nelec = (nup, ndown) - rs = 3 - ecut = 0.5 - - # Thermal AFQMC params. - mu = 2.158847 - beta = 1 - timestep = 0.05 - nwalkers = 12 // comm.size - # Must be fixed at 1 for Thermal AFQMC--legacy code overides whatever input! - nsteps_per_block = 1 - nblocks = 10 - pop_control_freq = 1 - pop_control_method = "pair_branch" - #pop_control_method = "comb" - lowrank = False - lowrank_thresh = 1e-14 - stack_size = 10 - optimised = False - - verbose = False if (comm.rank != 0) else True - debug = True - seed = 7 - numpy.random.seed(seed) - - with tempfile.NamedTemporaryFile() as tmpf1: - options = { - 'nelec': nelec, - 'mu': mu, - 'beta': beta, - 'timestep': timestep, - 'nwalkers': nwalkers, - 'seed': seed, - 'nsteps_per_block': nsteps_per_block, - 'nblocks': nblocks, - 'pop_control_freq': pop_control_freq, - 'pop_control_method': pop_control_method, - 'lowrank': lowrank, - 'lowrank_thresh': lowrank_thresh, - 'stack_size': stack_size, - 'optimised': optimised, - - "ueg_opts": { - "nup": nup, - "ndown": ndown, - "rs": rs, - "ecut": ecut, - "thermal": True, - "write_integrals": False, - "low_rank": lowrank - }, - - "estimators": { - "filename": tmpf1.name, # For legacy. - }, - } - - # --------------------------------------------------------------------- - # Test. - # --------------------------------------------------------------------- - afqmc = build_driver_ueg_test_instance(options, seed, debug, verbose) - - # --------------------------------------------------------------------- - # Legacy. - # --------------------------------------------------------------------- - print('\n------------------------------') - print('Running Legacy ThermalAFQMC...') - print('------------------------------') - legacy_afqmc = build_legacy_driver_ueg_test_instance( - afqmc.hamiltonian, comm, options, seed, verbose) - legacy_afqmc.run(comm=comm) - legacy_afqmc.finalise(verbose=False) - legacy_afqmc.estimators.estimators["mixed"].update( - legacy_afqmc.qmc, - legacy_afqmc.system, - legacy_afqmc.hamiltonian, - legacy_afqmc.trial, - legacy_afqmc.walk, - 0, - legacy_afqmc.propagators.free_projection) - legacy_mixed_data = extract_mixed_estimates(legacy_afqmc.estimators.filename) - - enum = legacy_afqmc.estimators.estimators["mixed"].names - legacy_energy_numer = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.enumer] - legacy_energy_denom = legacy_afqmc.estimators.estimators["mixed"].estimates[enum.edenom] - - if verbose: - print(f'\nThermal AFQMC options: \n{json.dumps(options, indent=4)}\n') - - - -if __name__ == '__main__': - run_legacy() - diff --git a/ipie/addons/thermal/utils/ueg.py b/ipie/addons/thermal/utils/ueg.py index 9b0b670a..3308a1f0 100644 --- a/ipie/addons/thermal/utils/ueg.py +++ b/ipie/addons/thermal/utils/ueg.py @@ -375,28 +375,6 @@ def vq(self, q): return 4 * numpy.pi / numpy.dot(q, q) - def density_operator(self, iq): - """Density operator as defined in Eq.(6) of Phys. Rev. B 75, 245123. - - Parameters - ---------- - q : float - a plane-wave vector - - Returns - ------- - rho_q: float - density operator - """ - nnz = self.rho_ikpq_kpq[iq].shape[0] # Number of non-zeros - ones = numpy.ones((nnz), dtype=numpy.complex128) - rho_q = scipy.sparse.csc_matrix( - (ones, (self.rho_ikpq_kpq[iq], self.rho_ikpq_i[iq])), - shape=(self.nbasis, self.nbasis), - dtype=numpy.complex128) - return rho_q - - def scaled_density_operator_incore(self, transpose): """Density operator as defined in Eq.(6) of PRB(75)245123 diff --git a/ipie/estimators/energy.py b/ipie/estimators/energy.py index 9d163bd1..23b5652b 100644 --- a/ipie/estimators/energy.py +++ b/ipie/estimators/energy.py @@ -118,9 +118,6 @@ def __init__( trial=None, filename=None, ): - assert system is not None - assert ham is not None - assert trial is not None super().__init__() self._eshift = 0.0 self.scalar_estimator = True From afb86f7848889ba8ff6b5af6716924329253a780 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Wed, 10 Apr 2024 23:28:12 -0400 Subject: [PATCH 82/84] Add `cplx` kwarg to `ipie.trial_wavefunction.SingleDet` --- ipie/trial_wavefunction/single_det.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ipie/trial_wavefunction/single_det.py b/ipie/trial_wavefunction/single_det.py index 3af4e335..ffbefac4 100644 --- a/ipie/trial_wavefunction/single_det.py +++ b/ipie/trial_wavefunction/single_det.py @@ -28,7 +28,7 @@ # class for UHF trial class SingleDet(TrialWavefunctionBase): - def __init__(self, wavefunction, num_elec, num_basis, handler=MPIHandler(), verbose=False): + def __init__(self, wavefunction, num_elec, num_basis, cplx=False, handler=MPIHandler(), verbose=False): assert isinstance(wavefunction, numpy.ndarray) assert len(wavefunction.shape) == 2 super().__init__(wavefunction, num_elec, num_basis, verbose=verbose) @@ -39,7 +39,7 @@ def __init__(self, wavefunction, num_elec, num_basis, handler=MPIHandler(), verb self._num_dets = 1 self._max_num_dets = 1 imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) - if imag_norm <= 1e-8: + if (not cplx) and (imag_norm <= 1e-8): #print("# making trial wavefunction MO coefficient real") self.psi = numpy.array(self.psi.real, dtype=numpy.float64) From 63ea0e68a639dd05d9e3295c877a6fb134f13310 Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Thu, 11 Apr 2024 12:14:29 -0400 Subject: [PATCH 83/84] Fix `pylint` errors. --- ipie/addons/thermal/analysis/extraction.py | 7 +------ ipie/addons/thermal/analysis/thermal_analysis.py | 5 ----- ipie/addons/thermal/estimators/energy.py | 1 - ipie/addons/thermal/estimators/handler.py | 2 -- ipie/addons/thermal/qmc/calc.py | 2 -- ipie/addons/thermal/qmc/thermal_afqmc.py | 6 ++---- ipie/addons/thermal/utils/legacy_testing.py | 2 -- ipie/addons/thermal/utils/testing.py | 2 -- ipie/addons/thermal/utils/ueg.py | 3 +-- ipie/addons/thermal/walkers/pop_controller.py | 2 -- ipie/utils/testing.py | 2 -- ipie/walkers/pop_controller.py | 2 -- 12 files changed, 4 insertions(+), 32 deletions(-) diff --git a/ipie/addons/thermal/analysis/extraction.py b/ipie/addons/thermal/analysis/extraction.py index e87128b5..913cafb5 100644 --- a/ipie/addons/thermal/analysis/extraction.py +++ b/ipie/addons/thermal/analysis/extraction.py @@ -16,13 +16,9 @@ # Joonho Lee # -import json - -import h5py -import numpy -import pandas as pd from ipie.utils.misc import get_from_dict + def set_info(frame, md): ncols = len(frame.columns) system = md.get("system") @@ -32,7 +28,6 @@ def set_info(frame, md): fp = get_from_dict(md, ["propagators", "free_projection"]) bp = get_from_dict(md, ["estimates", "estimates", "back_prop"]) - beta = qmc.get("beta") br = qmc.get("beta_scaled") ints = system.get("integral_file") diff --git a/ipie/addons/thermal/analysis/thermal_analysis.py b/ipie/addons/thermal/analysis/thermal_analysis.py index 96a49554..b9cba603 100644 --- a/ipie/addons/thermal/analysis/thermal_analysis.py +++ b/ipie/addons/thermal/analysis/thermal_analysis.py @@ -20,17 +20,12 @@ import sys import argparse -import pprint -import json import glob import numpy import scipy.optimize import pandas as pd -from ipie.analysis.blocking import ( - average_ratio - ) from ipie.analysis.extraction import ( extract_observable, get_metadata, diff --git a/ipie/addons/thermal/estimators/energy.py b/ipie/addons/thermal/estimators/energy.py index 74983e53..7ebe8637 100644 --- a/ipie/addons/thermal/estimators/energy.py +++ b/ipie/addons/thermal/estimators/energy.py @@ -21,7 +21,6 @@ from ipie.utils.backend import arraylib as xp from ipie.hamiltonians.generic import GenericComplexChol, GenericRealChol from ipie.estimators.energy import EnergyEstimator -from ipie.estimators.estimator_base import EstimatorBase from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers from ipie.addons.thermal.estimators.thermal import one_rdm_from_G diff --git a/ipie/addons/thermal/estimators/handler.py b/ipie/addons/thermal/estimators/handler.py index 9b9fdef6..8ae4b8b7 100644 --- a/ipie/addons/thermal/estimators/handler.py +++ b/ipie/addons/thermal/estimators/handler.py @@ -19,8 +19,6 @@ """Routines and classes for estimation of observables.""" import os -import h5py -import numpy from typing import Tuple, Union from ipie.config import config, MPI diff --git a/ipie/addons/thermal/qmc/calc.py b/ipie/addons/thermal/qmc/calc.py index 5c9e7683..659ce515 100644 --- a/ipie/addons/thermal/qmc/calc.py +++ b/ipie/addons/thermal/qmc/calc.py @@ -17,7 +17,6 @@ # """Helper Routines for setting up a calculation""" -import json from ipie.config import MPI from ipie.utils.mpi import MPIHandler @@ -25,7 +24,6 @@ from ipie.systems.utils import get_system from ipie.hamiltonians.utils import get_hamiltonian -from ipie.qmc.calc import init_communicator, setup_calculation, read_input from ipie.addons.thermal.trial.utils import get_trial_density_matrix from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers diff --git a/ipie/addons/thermal/qmc/thermal_afqmc.py b/ipie/addons/thermal/qmc/thermal_afqmc.py index 37c5232d..3cea31ee 100644 --- a/ipie/addons/thermal/qmc/thermal_afqmc.py +++ b/ipie/addons/thermal/qmc/thermal_afqmc.py @@ -17,10 +17,10 @@ # """Driver to perform Thermal AFQMC calculation""" + import numpy import time import json -import uuid from typing import Dict, Optional, Tuple from ipie.addons.thermal.walkers.pop_controller import ThermalPopController @@ -29,11 +29,9 @@ from ipie.addons.thermal.estimators.handler import ThermalEstimatorHandler from ipie.addons.thermal.qmc.options import ThermalQMCParams -from ipie.config import MPI from ipie.utils.io import to_json from ipie.utils.backend import arraylib as xp -from ipie.utils.backend import get_host_memory, synchronize -from ipie.utils.misc import get_git_info, print_env_info +from ipie.utils.backend import synchronize from ipie.utils.mpi import MPIHandler from ipie.systems.generic import Generic from ipie.estimators.estimator_base import EstimatorBase diff --git a/ipie/addons/thermal/utils/legacy_testing.py b/ipie/addons/thermal/utils/legacy_testing.py index d23f4083..2e2c829d 100644 --- a/ipie/addons/thermal/utils/legacy_testing.py +++ b/ipie/addons/thermal/utils/legacy_testing.py @@ -17,7 +17,6 @@ # import numpy -import pytest from typing import Tuple, Union from ipie.systems.generic import Generic @@ -30,7 +29,6 @@ from ipie.legacy.hamiltonians._generic import Generic as LegacyHamGeneric from ipie.legacy.trial_density_matrices.onebody import OneBody as LegacyOneBody from ipie.legacy.trial_density_matrices.mean_field import MeanField as LegacyMeanField -from ipie.legacy.walkers.thermal import ThermalWalker from ipie.legacy.walkers.handler import Walkers from ipie.legacy.thermal_propagation.continuous import Continuous from ipie.legacy.thermal_propagation.planewave import PlaneWave diff --git a/ipie/addons/thermal/utils/testing.py b/ipie/addons/thermal/utils/testing.py index 16b84870..0e25b695 100644 --- a/ipie/addons/thermal/utils/testing.py +++ b/ipie/addons/thermal/utils/testing.py @@ -17,7 +17,6 @@ # import numpy -import pytest from typing import Tuple, Union from ipie.utils.mpi import MPIHandler @@ -29,7 +28,6 @@ from ipie.addons.thermal.trial.mean_field import MeanField from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers from ipie.addons.thermal.propagation.phaseless_generic import PhaselessGeneric -from ipie.addons.thermal.qmc.options import ThermalQMCParams from ipie.addons.thermal.qmc.thermal_afqmc import ThermalAFQMC diff --git a/ipie/addons/thermal/utils/ueg.py b/ipie/addons/thermal/utils/ueg.py index 3308a1f0..43286bfa 100644 --- a/ipie/addons/thermal/utils/ueg.py +++ b/ipie/addons/thermal/utils/ueg.py @@ -143,7 +143,7 @@ def build(self, verbose=False): # --------------------------------------------------------------------- # Allowed momentum transfers (4*ecut). - eigs, qvecs, self.qnmax = self.sp_energies(self.ktwist, self.kfac, 4 * self.ecut) + _, qvecs, self.qnmax = self.sp_energies(self.ktwist, self.kfac, 4 * self.ecut) # Omit Q = 0 term. self.qvecs = numpy.copy(qvecs[1:]) @@ -201,7 +201,6 @@ def sp_energies(self, ks, kfac, ecut): nmax = int(numpy.ceil(numpy.sqrt((2 * ecut)))) spval = [] - vec = [] kval = [] for ni in range(-nmax, nmax + 1): diff --git a/ipie/addons/thermal/walkers/pop_controller.py b/ipie/addons/thermal/walkers/pop_controller.py index 759755e7..a0aed19a 100644 --- a/ipie/addons/thermal/walkers/pop_controller.py +++ b/ipie/addons/thermal/walkers/pop_controller.py @@ -16,13 +16,11 @@ # Joonho Lee # -import time import numpy from ipie.config import MPI from ipie.utils.backend import arraylib as xp from ipie.walkers.pop_controller import PopController, PopControllerTimer -from ipie.addons.thermal.walkers.uhf_walkers import UHFThermalWalkers class ThermalPopController(PopController): diff --git a/ipie/utils/testing.py b/ipie/utils/testing.py index 941e2d9e..c141766e 100644 --- a/ipie/utils/testing.py +++ b/ipie/utils/testing.py @@ -21,8 +21,6 @@ from typing import Tuple, Union import numpy -import scipy.sparse -import scipy.stats from ipie.hamiltonians import Generic as HamGeneric from ipie.propagation.phaseless_generic import PhaselessBase, PhaselessGeneric diff --git a/ipie/walkers/pop_controller.py b/ipie/walkers/pop_controller.py index 17baab27..15f7efbf 100644 --- a/ipie/walkers/pop_controller.py +++ b/ipie/walkers/pop_controller.py @@ -270,7 +270,6 @@ def comb(walkers, comm, weights, target_weight, timer=PopControllerTimer()): source_proc = c // walkers.nwalkers # Location of walker to kill in local list of walkers. kill_pos = k % walkers.nwalkers - buffer = walkers.walker_buffer timer.add_non_communication() timer.start_time() comm.Recv(walkers.walker_buffer, source=source_proc, tag=i) @@ -409,7 +408,6 @@ def pair_branch(walkers, comm, max_weight, min_weight, timer=PopControllerTimer( if walker[1] == 0: timer.start_time() tag = walker[3] * walkers.nwalkers + comm.rank - buffer = walkers.walker_buffer timer.add_non_communication() timer.start_time() comm.Recv(walkers.walker_buffer, source=int(round(walker[3])), tag=tag) From 20d10a9b338c5b2b00d8451fbd90efd36b110e4f Mon Sep 17 00:00:00 2001 From: Shu Fay Ung Date: Fri, 17 May 2024 10:51:17 -0400 Subject: [PATCH 84/84] Remove `cplx` kwarg in `ipie.trial_wavefunction.SingleDet` --- ipie/trial_wavefunction/single_det.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ipie/trial_wavefunction/single_det.py b/ipie/trial_wavefunction/single_det.py index ffbefac4..3af4e335 100644 --- a/ipie/trial_wavefunction/single_det.py +++ b/ipie/trial_wavefunction/single_det.py @@ -28,7 +28,7 @@ # class for UHF trial class SingleDet(TrialWavefunctionBase): - def __init__(self, wavefunction, num_elec, num_basis, cplx=False, handler=MPIHandler(), verbose=False): + def __init__(self, wavefunction, num_elec, num_basis, handler=MPIHandler(), verbose=False): assert isinstance(wavefunction, numpy.ndarray) assert len(wavefunction.shape) == 2 super().__init__(wavefunction, num_elec, num_basis, verbose=verbose) @@ -39,7 +39,7 @@ def __init__(self, wavefunction, num_elec, num_basis, cplx=False, handler=MPIHan self._num_dets = 1 self._max_num_dets = 1 imag_norm = numpy.sum(self.psi.imag.ravel() * self.psi.imag.ravel()) - if (not cplx) and (imag_norm <= 1e-8): + if imag_norm <= 1e-8: #print("# making trial wavefunction MO coefficient real") self.psi = numpy.array(self.psi.real, dtype=numpy.float64)