From 27517bcd018eac0ea7a6c89a6cd9bc8c92ee7df6 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 15 Mar 2019 14:11:58 +0100 Subject: [PATCH 001/152] Properly send CV coordinates to root MPI process --- openmmtools/multistate/multistatesampler.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/openmmtools/multistate/multistatesampler.py b/openmmtools/multistate/multistatesampler.py index 5300e39fb..66debda68 100644 --- a/openmmtools/multistate/multistatesampler.py +++ b/openmmtools/multistate/multistatesampler.py @@ -1195,9 +1195,7 @@ def _propagate_replicas(self): # Update all sampler states. For non-0 nodes, this will update only the # sampler states associated to the replicas propagated by this node. for replica_id, propagated_state in zip(replica_ids, propagated_states): - propagated_positions, propagated_box_vectors = propagated_state # Unpack. - self._sampler_states[replica_id].positions = propagated_positions - self._sampler_states[replica_id].box_vectors = propagated_box_vectors + self._sampler_states[replica_id].__setstate__(propagated_state, ignore_velocities=True) # Gather all MCMCMoves statistics. All nodes must have these up-to-date # since they are tied to the ThermodynamicState, not the replica. @@ -1232,7 +1230,7 @@ def _propagate_replica(self, replica_id): raise SimulationNaNError(message) # Return new positions and box vectors. - return sampler_state.positions, sampler_state.box_vectors + return sampler_state.__getstate__(ignore_velocities=True) def _get_replica_move_statistics(self, replica_id): """Return the statistics of the MCMCMove currently associated to this replica.""" From e6f9caeb9be0e35a8caa88be1af58d8d980ee8f2 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Tue, 19 Mar 2019 18:23:25 +0100 Subject: [PATCH 002/152] Add test for uniform mixing with MPI --- openmmtools/tests/test_sampling.py | 116 ++++++++++++++++++++++++++++- 1 file changed, 112 insertions(+), 4 deletions(-) diff --git a/openmmtools/tests/test_sampling.py b/openmmtools/tests/test_sampling.py index d13d0cfb2..fcfa15281 100644 --- a/openmmtools/tests/test_sampling.py +++ b/openmmtools/tests/test_sampling.py @@ -23,15 +23,15 @@ from io import StringIO import numpy as np -import openmmtools as mmtools import scipy.integrate import yaml from nose.plugins.attrib import attr from nose.tools import assert_raises -from openmmtools import testsystems from simtk import openmm, unit - import mpiplus + +import openmmtools as mmtools +from openmmtools import testsystems from openmmtools.multistate import MultiStateReporter, MultiStateSampler, ReplicaExchangeSampler, ParallelTemperingSampler, SAMSSampler from openmmtools.multistate import ReplicaExchangeAnalyzer, SAMSAnalyzer from openmmtools.multistate.multistatereporter import _DictYamlLoader @@ -687,7 +687,8 @@ def call_sampler_create(cls, sampler, reporter, unsampled_states): """Helper function to call the create method for the sampler""" # Allows initial thermodynamic states to be handled by the built in methods - sampler.create(thermodynamic_states, sampler_states, reporter, unsampled_thermodynamic_states=unsampled_states) + sampler.create(thermodynamic_states, sampler_states, reporter, + unsampled_thermodynamic_states=unsampled_states) # -------------------------------- # Tests overwritten by sub-classes @@ -1598,6 +1599,113 @@ def test_stored_properties(self): additional_values.update(self.property_creator('replica_mixing_scheme', 'replica_mixing_scheme', None, None)) self.actual_stored_properties_check(additional_properties=additional_values) + @attr('slow') # Skip on Travis-CI + def test_uniform_mixing(self): + """Test that mixing is uniform for a sequence of harmonic oscillators. + + This test was implemented following choderalab/yank#1130. Briefly, when + a repex calculation was distributed over multiple MPI processes, the + odd replicas turned out to be much less diffusive than the even replicas. + + """ + temperature = 300.0 * unit.kelvin + sigma = 1.0 * unit.angstrom # Distance between two oscillators. + n_states = 50 # Number of harmonic oscillators. + + timestep = 2.0 * unit.femtosecond + n_steps = 5 # Number of steps per iteration. + number_of_iterations = 2000 + + # Build an equidistant sequence of harmonic oscillators. + sampler_states = [] + thermodynamic_states = [] + + # The minima of the harmonic oscillators are 1 kT from each other. + k = mmtools.constants.kB * temperature / sigma**2 # Spring constant. + oscillator = testsystems.HarmonicOscillator(K=k) + + for oscillator_idx in range(n_states): + system = copy.deepcopy(oscillator.system) + positions = copy.deepcopy(oscillator.positions) + + # Determine the position of the harmonic oscillator minimum. + minimum_position = oscillator_idx * sigma + minimum_position_unitless = minimum_position.value_in_unit_system(unit.md_unit_system) + positions[0][0] = minimum_position + + # Create an oscillator starting from its minimum. + force = system.getForce(0) + assert force.getGlobalParameterName(1) == 'testsystems_HarmonicOscillator_x0' + force.setGlobalParameterDefaultValue(1, minimum_position_unitless) + + thermodynamic_states.append(mmtools.states.ThermodynamicState( + system=system, temperature=temperature)) + sampler_states.append(mmtools.states.SamplerState(positions)) + + # Run a short repex simulation and gather data. + with self.temporary_storage_path() as storage_path: + # Create and run object. + sampler = self.SAMPLER( + mcmc_moves=mmtools.mcmc.LangevinDynamicsMove(timestep=timestep, n_steps=n_steps), + number_of_iterations=number_of_iterations, + ) + reporter = self.REPORTER(storage_path, checkpoint_interval=number_of_iterations) + sampler.create(thermodynamic_states, sampler_states, reporter) + sampler.run() + + # Retrieve from the reporter the mixing information before deleting. + # Only the reporter from MPI node 0 should be open. + n_accepted_matrix, n_proposed_matrix = mpiplus.run_single_node( + task=reporter.read_mixing_statistics, + rank=0, broadcast_result=True + ) + replica_thermo_states = mpiplus.run_single_node( + task=reporter.read_replica_thermodynamic_states, + rank=0, broadcast_result=True + ) + del sampler, reporter + + # No need to analyze the same data in multiple MPI processes. + mpicomm = mpiplus.get_mpicomm() + if mpicomm is not None and mpicomm.rank == 0: + print('Acceptance matrix') + print(n_accepted_matrix) + print() + + # Count the number of visited states by each replica. + replica_thermo_state_counts = np.empty(n_states) + for replica_idx in range(n_states): + n_visited_states = len(set(replica_thermo_states[:, replica_idx])) + replica_thermo_state_counts[replica_idx] = n_visited_states + print(replica_idx, ':', n_visited_states) + print() + + # Count the number of visited states by each MPI process. + n_mpi_processes = mpicomm.size + mpi_avg_thermo_state_counts = np.empty(n_mpi_processes) + mpi_sem_thermo_state_counts = np.empty(n_mpi_processes) + for mpi_idx in range(n_mpi_processes): + # Find replicas assigned to this MPI process. + replica_indices = list(i for i in range(n_states) if i % n_mpi_processes == mpi_idx) + # Find the average number of states visited by + # the replicas assigned to this MPI process. + mpi_avg_thermo_state_counts[mpi_idx] = np.mean(replica_thermo_state_counts[replica_indices]) + mpi_sem_thermo_state_counts[mpi_idx] = np.std(replica_thermo_state_counts[replica_indices], ddof=1) / len(replica_indices) + + # These should be roughly equal. + print('MPI process mean number of thermo states visited:') + for mpi_idx, (mean, sem) in enumerate(zip(mpi_avg_thermo_state_counts, + mpi_sem_thermo_state_counts)): + print('{}: {} +- {}'.format(mpi_idx, mean, 2*sem)) + + # Check if the confidence intervals overlap. + def are_overlapping(interval1, interval2): + return min(interval1[1], interval2[1]) - max(interval1[0], interval2[0]) > 0 + + cis = [(mean-2*sem, mean+2*sem) for mean, sem in zip(mpi_avg_thermo_state_counts, mpi_sem_thermo_state_counts)] + for i in range(1, len(cis)): + assert are_overlapping(cis[0], cis[i]) + class TestSingleReplicaSAMS(TestMultiStateSampler): """Test suite for SAMSSampler class.""" From 35a719c84d0240f8f719f0d31ecf1fe53f783b01 Mon Sep 17 00:00:00 2001 From: Silveira Date: Thu, 9 May 2019 19:21:58 -0400 Subject: [PATCH 003/152] option for performing expanded ensemble simulations --- openmmtools/multistate/sams.py | 59 ++++++++++++++++++++++------------ 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 8884bbcb8..e55af11e1 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -102,8 +102,8 @@ class SAMSSampler(multistate.MultiStateSampler): >>> move = mcmc.GHMCMove(timestep=2.0*unit.femtoseconds, n_steps=50) >>> simulation = SAMSSampler(mcmc_moves=move, number_of_iterations=2, ... state_update_scheme='global-jump', locality=5, - ... update_stages='two-stage', flatness_criteria='logZ-flatness', - ... flatness_threshold=0.2, weight_update_method='rao-blackwellized', + ... update_stages='two-stage', flatness_criteria='histogram-flatness', + ... flatness_threshold=0.5, weight_update_method='rao-blackwellized', ... adapt_target_probabilities=False) @@ -171,10 +171,13 @@ def __init__(self, log_target_probabilities=None, state_update_scheme='global-jump', locality=5, + weights_update=True, update_stages='two-stage', - flatness_criteria='logZ-flatness', - flatness_threshold=0.2, + flatness_criteria='histogram-flatness', + flatness_threshold=0.5, + mininum_visits=100, weight_update_method='rao-blackwellized', + beta_factor=0.8, adapt_target_probabilities=False, gamma0=1.0, logZ_guess=None, @@ -195,23 +198,29 @@ def __init__(self, ``restricted-range`` will compute the probabilities for each of the states in the local neighborhood, increasing jump probability locality : int, optional, default=1 Number of neighboring states on either side to consider for local update schemes. + weights_update : bool, optional, default=True + If False, the weight updating is disabled. This allows to perform expanded ensemble simulations. update_stages : str, optional, default='two-stage' One of ['one-stage', 'two-stage'] ``one-stage`` will use the asymptotically optimal scheme throughout the entire simulation (not recommended due to slow convergence) ``two-stage`` will use a heuristic first stage to achieve flat histograms before switching to the asymptotically optimal scheme - flatness_criteria : string, optiona, default='logZ-flatness' + flatness_criteria : string, optional, default='histogram-flatness' Method of assessing when to switch to asymptotically optimal scheme One of ['logZ-flatness','minimum-visits','histogram-flatness'] - flatness_threshold : float, optional, default=0.2 + flatness_threshold : float, optional, default=0.5 Histogram relative flatness threshold to use for first stage of two-stage scheme. + minimum_visits : int, optional, default=100 + Mininum number of visits in each state to use for first stage of two-stage scheme. weight_update_method : str, optional, default='rao-blackwellized' Method to use for updating log weights in SAMS. One of ['optimal', 'rao-blackwellized'] ``rao-blackwellized`` will update log free energy estimate for all states for which energies were computed ``optimal`` will use integral counts to update log free energy estimate of current state only + beta_factor : float, optional, default=0.8 + Exponent for tunning the decaying rate of the gain factor. adapt_target_probabilities : bool, optional, default=False If True, target probabilities will be adapted to achieve minimal thermodynamic length between terminal thermodynamic states. (EXPERIMENTAL) - gamma0 : float, optional, default=0.0 + gamma0 : float, optional, default=1.0 Initial weight adaptation rate. logZ_guess : array-like of shape [n_states] of floats, optiona, default=None Initial guess for logZ for all states, if available. @@ -222,10 +231,13 @@ def __init__(self, self.log_target_probabilities = log_target_probabilities self.state_update_scheme = state_update_scheme self.locality = locality + self.weights_update = weights_update self.update_stages = update_stages self.flatness_criteria = flatness_criteria self.flatness_threshold = flatness_threshold + self.minimum_visits = minimum_visits self.weight_update_method = weight_update_method + self.beta_factor = beta_factor self.adapt_target_probabilities = adapt_target_probabilities self.gamma0 = gamma0 self.logZ_guess = logZ_guess @@ -234,6 +246,7 @@ def __init__(self, self._replica_neighbors = None self._cached_state_histogram = None + class _StoredProperty(multistate.MultiStateSampler._StoredProperty): @staticmethod @@ -280,10 +293,13 @@ def _adapt_target_probabilities_validator(instance, scheme): log_target_probabilities = _StoredProperty('log_target_probabilities', validate_function=None) state_update_scheme = _StoredProperty('state_update_scheme', validate_function=_StoredProperty._state_update_scheme_validator) locality = _StoredProperty('locality', validate_function=None) + weights_update = _StoredProperty('weights_update', validate_function=None) update_stages = _StoredProperty('update_stages', validate_function=_StoredProperty._update_stages_validator) flatness_criteria = _StoredProperty('flatness_criteria', validate_function=_StoredProperty._flatness_criteria_validator) flatness_threshold = _StoredProperty('flatness_threshold', validate_function=None) + minimum_visits = _StoredProperty('minimum_visits, validate_function=None) weight_update_method = _StoredProperty('weight_update_method', validate_function=_StoredProperty._weight_update_method_validator) + beta_factor = _StoredProperty('beta_factor', validate_function=None) adapt_target_probabilities = _StoredProperty('adapt_target_probabilities', validate_function=_StoredProperty._adapt_target_probabilities_validator) gamma0 = _StoredProperty('gamma0', validate_function=None) logZ_guess = _StoredProperty('logZ_guess', validate_function=None) @@ -367,23 +383,26 @@ def _restore_sampler_from_reporter(self, reporter): super()._restore_sampler_from_reporter(reporter) self._cached_state_histogram = self._compute_state_histogram(reporter=reporter) logger.debug('Restored state histogram: {}'.format(self._cached_state_histogram)) - data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'stage', 't0') + data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'weights_update', 'stage', 't0', 'beta_factor') self._logZ = data['logZ'] + self.weights_update = str(data['weights_update'][0]) self._stage = int(data['stage'][0]) self._t0 = int(data['t0'][0]) + self.beta_factor= int(data['beta_factor'][0]) # Compute log weights from log target probability and logZ estimate self._update_log_weights() - - # Determine t0 - self._update_stage() + if (self.weights_update): + # Determine t0 + self._update_stage() @mpiplus.on_single_node(rank=0, broadcast_result=False, sync_nodes=False) @mpiplus.delayed_termination def _report_iteration_items(self): super(SAMSSampler, self)._report_iteration_items() - self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, stage=self._stage, t0=self._t0) + self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, weights_update=self.weights_update, + stage=self._stage, t0=self._t0, beta_factor=self.beta_factor) # Split into which states and how many samplers are in each state # Trying to do histogram[replica_thermo_states] += 1 does not correctly handle multiple # replicas in the same state. @@ -425,12 +444,12 @@ def _mix_replicas(self): swap_fraction_accepted = float(n_swaps_accepted) / n_swaps_proposed logger.debug("Accepted {}/{} attempted swaps ({:.1f}%)".format(n_swaps_accepted, n_swaps_proposed, swap_fraction_accepted * 100.0)) + if (self.weights_update): + # Update logZ estimates + self._update_logZ_estimates(replicas_log_P_k) - # Update logZ estimates - self._update_logZ_estimates(replicas_log_P_k) - - # Update log weights based on target probabilities - self._update_log_weights() + # Update log weights based on target probabilities + self._update_log_weights() def _local_jump(self, replicas_log_P_k): n_replica, n_states, locality = self.n_replicas, self.n_states, self.locality @@ -562,8 +581,7 @@ def _update_stage(self): Determine which adaptation stage we're in by checking histogram flatness. """ - # TODO: Make minimum_visits a user option - minimum_visits = 1 + N_k = self._state_histogram logger.debug(' state histogram counts ({} total): {}'.format(self._cached_state_histogram.sum(), self._cached_state_histogram)) if (self.update_stages == 'two-stage') and (self._stage == 0): @@ -574,7 +592,7 @@ def _update_stage(self): if self.flatness_criteria == 'minimum-visits': # Advance if every state has been visited at least once - if np.all(N_k >= minimum_visits): + if np.all(N_k >= self.minimum_visits): advance = True elif self.flatness_criteria == 'histogram-flatness': # Check histogram flatness @@ -628,7 +646,6 @@ def _update_logZ_estimates(self, replicas_log_P_k): for (replica_index, state_index) in enumerate(self._replica_thermodynamic_states): logger.debug(' Replica %d state %d' % (replica_index, state_index)) # Compute attenuation factor gamma - beta_factor = 0.8 pi_star = pi_k.min() t = float(self._iteration) if self._stage == 0: # initial stage From f2782d240edae9f9c176205d750c8e0d84db0933 Mon Sep 17 00:00:00 2001 From: Silveira Date: Thu, 9 May 2019 19:26:41 -0400 Subject: [PATCH 004/152] fix typo --- openmmtools/multistate/sams.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index e55af11e1..36a75c7e9 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -297,7 +297,7 @@ def _adapt_target_probabilities_validator(instance, scheme): update_stages = _StoredProperty('update_stages', validate_function=_StoredProperty._update_stages_validator) flatness_criteria = _StoredProperty('flatness_criteria', validate_function=_StoredProperty._flatness_criteria_validator) flatness_threshold = _StoredProperty('flatness_threshold', validate_function=None) - minimum_visits = _StoredProperty('minimum_visits, validate_function=None) + minimum_visits = _StoredProperty('minimum_visits', validate_function=None) weight_update_method = _StoredProperty('weight_update_method', validate_function=_StoredProperty._weight_update_method_validator) beta_factor = _StoredProperty('beta_factor', validate_function=None) adapt_target_probabilities = _StoredProperty('adapt_target_probabilities', validate_function=_StoredProperty._adapt_target_probabilities_validator) From 6e9689c74afcc041bb1eea040069d8bfcef00573 Mon Sep 17 00:00:00 2001 From: Silveira Date: Thu, 9 May 2019 19:31:19 -0400 Subject: [PATCH 005/152] fix typo --- openmmtools/multistate/sams.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 36a75c7e9..7f0ee39ea 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -171,7 +171,7 @@ def __init__(self, log_target_probabilities=None, state_update_scheme='global-jump', locality=5, - weights_update=True, + weight_update=True, update_stages='two-stage', flatness_criteria='histogram-flatness', flatness_threshold=0.5, @@ -198,7 +198,7 @@ def __init__(self, ``restricted-range`` will compute the probabilities for each of the states in the local neighborhood, increasing jump probability locality : int, optional, default=1 Number of neighboring states on either side to consider for local update schemes. - weights_update : bool, optional, default=True + weight_update : bool, optional, default=True If False, the weight updating is disabled. This allows to perform expanded ensemble simulations. update_stages : str, optional, default='two-stage' One of ['one-stage', 'two-stage'] @@ -231,7 +231,7 @@ def __init__(self, self.log_target_probabilities = log_target_probabilities self.state_update_scheme = state_update_scheme self.locality = locality - self.weights_update = weights_update + self.weight_update = weight_update self.update_stages = update_stages self.flatness_criteria = flatness_criteria self.flatness_threshold = flatness_threshold @@ -293,7 +293,7 @@ def _adapt_target_probabilities_validator(instance, scheme): log_target_probabilities = _StoredProperty('log_target_probabilities', validate_function=None) state_update_scheme = _StoredProperty('state_update_scheme', validate_function=_StoredProperty._state_update_scheme_validator) locality = _StoredProperty('locality', validate_function=None) - weights_update = _StoredProperty('weights_update', validate_function=None) + weight_update = _StoredProperty('weight_update', validate_function=None) update_stages = _StoredProperty('update_stages', validate_function=_StoredProperty._update_stages_validator) flatness_criteria = _StoredProperty('flatness_criteria', validate_function=_StoredProperty._flatness_criteria_validator) flatness_threshold = _StoredProperty('flatness_threshold', validate_function=None) @@ -383,16 +383,16 @@ def _restore_sampler_from_reporter(self, reporter): super()._restore_sampler_from_reporter(reporter) self._cached_state_histogram = self._compute_state_histogram(reporter=reporter) logger.debug('Restored state histogram: {}'.format(self._cached_state_histogram)) - data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'weights_update', 'stage', 't0', 'beta_factor') + data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'weight_update', 'stage', 't0', 'beta_factor') self._logZ = data['logZ'] - self.weights_update = str(data['weights_update'][0]) + self.weight_update = str(data['weight_update'][0]) self._stage = int(data['stage'][0]) self._t0 = int(data['t0'][0]) self.beta_factor= int(data['beta_factor'][0]) # Compute log weights from log target probability and logZ estimate self._update_log_weights() - if (self.weights_update): + if (self.weight_update): # Determine t0 self._update_stage() @@ -401,7 +401,7 @@ def _restore_sampler_from_reporter(self, reporter): def _report_iteration_items(self): super(SAMSSampler, self)._report_iteration_items() - self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, weights_update=self.weights_update, + self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, weight_update=self.weight_update, stage=self._stage, t0=self._t0, beta_factor=self.beta_factor) # Split into which states and how many samplers are in each state # Trying to do histogram[replica_thermo_states] += 1 does not correctly handle multiple @@ -444,7 +444,7 @@ def _mix_replicas(self): swap_fraction_accepted = float(n_swaps_accepted) / n_swaps_proposed logger.debug("Accepted {}/{} attempted swaps ({:.1f}%)".format(n_swaps_accepted, n_swaps_proposed, swap_fraction_accepted * 100.0)) - if (self.weights_update): + if (self.weight_update): # Update logZ estimates self._update_logZ_estimates(replicas_log_P_k) From e3253e139546604f523cf9b8aa19f4c5eb95f6aa Mon Sep 17 00:00:00 2001 From: Silveira Date: Thu, 9 May 2019 19:34:25 -0400 Subject: [PATCH 006/152] fix typo --- openmmtools/multistate/sams.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 7f0ee39ea..fbef7d54e 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -175,7 +175,7 @@ def __init__(self, update_stages='two-stage', flatness_criteria='histogram-flatness', flatness_threshold=0.5, - mininum_visits=100, + minimum_visits=100, weight_update_method='rao-blackwellized', beta_factor=0.8, adapt_target_probabilities=False, From af9405063f93d9e20a9104db35f98b1fb89c1f62 Mon Sep 17 00:00:00 2001 From: Silveira Date: Fri, 10 May 2019 10:14:39 -0400 Subject: [PATCH 007/152] store weight_update in reporter --- openmmtools/multistate/sams.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index fbef7d54e..08ba979a7 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -380,12 +380,14 @@ def _pre_write_create(self, thermodynamic_states: list, sampler_states: list, st self._update_log_weights() def _restore_sampler_from_reporter(self, reporter): + self.weight_update = True super()._restore_sampler_from_reporter(reporter) self._cached_state_histogram = self._compute_state_histogram(reporter=reporter) logger.debug('Restored state histogram: {}'.format(self._cached_state_histogram)) data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'weight_update', 'stage', 't0', 'beta_factor') self._logZ = data['logZ'] - self.weight_update = str(data['weight_update'][0]) + if data['weight_update'][0] == 0: + self.weight_update = False self._stage = int(data['stage'][0]) self._t0 = int(data['t0'][0]) self.beta_factor= int(data['beta_factor'][0]) @@ -401,7 +403,7 @@ def _restore_sampler_from_reporter(self, reporter): def _report_iteration_items(self): super(SAMSSampler, self)._report_iteration_items() - self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, weight_update=self.weight_update, + self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, weight_update=int(self.weight_update), stage=self._stage, t0=self._t0, beta_factor=self.beta_factor) # Split into which states and how many samplers are in each state # Trying to do histogram[replica_thermo_states] += 1 does not correctly handle multiple From 4bf9551118df287c60ceb35e02a4c2c585c8cb9b Mon Sep 17 00:00:00 2001 From: Silveira Date: Fri, 10 May 2019 10:28:25 -0400 Subject: [PATCH 008/152] print histogram for the expanded ensemble --- openmmtools/multistate/sams.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 08ba979a7..2292c3e4c 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -387,7 +387,7 @@ def _restore_sampler_from_reporter(self, reporter): data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'weight_update', 'stage', 't0', 'beta_factor') self._logZ = data['logZ'] if data['weight_update'][0] == 0: - self.weight_update = False + self.weight_update = False self._stage = int(data['stage'][0]) self._t0 = int(data['t0'][0]) self.beta_factor= int(data['beta_factor'][0]) @@ -453,6 +453,9 @@ def _mix_replicas(self): # Update log weights based on target probabilities self._update_log_weights() + else: + logger.debug(' state histogram counts ({} total): {}'.format(self._cached_state_histogram.sum(), self._cached_state_histogram)) + def _local_jump(self, replicas_log_P_k): n_replica, n_states, locality = self.n_replicas, self.n_states, self.locality for (replica_index, current_state_index) in enumerate(self._replica_thermodynamic_states): From f38263d80089dd90440efd9fef0d1b10edfadace Mon Sep 17 00:00:00 2001 From: Silveira Date: Fri, 10 May 2019 11:00:11 -0400 Subject: [PATCH 009/152] remove sampler options from write online data --- openmmtools/multistate/sams.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 2292c3e4c..c92db62ef 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -380,17 +380,13 @@ def _pre_write_create(self, thermodynamic_states: list, sampler_states: list, st self._update_log_weights() def _restore_sampler_from_reporter(self, reporter): - self.weight_update = True super()._restore_sampler_from_reporter(reporter) self._cached_state_histogram = self._compute_state_histogram(reporter=reporter) logger.debug('Restored state histogram: {}'.format(self._cached_state_histogram)) - data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'weight_update', 'stage', 't0', 'beta_factor') + data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'stage', 't0') self._logZ = data['logZ'] - if data['weight_update'][0] == 0: - self.weight_update = False self._stage = int(data['stage'][0]) self._t0 = int(data['t0'][0]) - self.beta_factor= int(data['beta_factor'][0]) # Compute log weights from log target probability and logZ estimate self._update_log_weights() @@ -403,8 +399,7 @@ def _restore_sampler_from_reporter(self, reporter): def _report_iteration_items(self): super(SAMSSampler, self)._report_iteration_items() - self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, weight_update=int(self.weight_update), - stage=self._stage, t0=self._t0, beta_factor=self.beta_factor) + self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, stage=self._stage, t0=self._t0) # Split into which states and how many samplers are in each state # Trying to do histogram[replica_thermo_states] += 1 does not correctly handle multiple # replicas in the same state. From 89b338d7a726118a9268341fe6cf112fec257323 Mon Sep 17 00:00:00 2001 From: Silveira Date: Fri, 10 May 2019 11:26:20 -0400 Subject: [PATCH 010/152] add weight update option in example --- openmmtools/multistate/sams.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index c92db62ef..a31d7fb1b 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -55,6 +55,8 @@ class SAMSSampler(multistate.MultiStateSampler): Thermodynamic state sampling scheme. One of ['global-jump', 'local-jump', 'restricted-range'] locality : int Number of neighboring states on either side to consider for local update schemes + weight_update : bool, default=True + If False, weights updating is disabled. This allows to perform expanded ensemble simulations. update_stages : str Number of stages to use for update. One of ['one-stage', 'two-stage'] weight_update_method : str @@ -199,7 +201,7 @@ def __init__(self, locality : int, optional, default=1 Number of neighboring states on either side to consider for local update schemes. weight_update : bool, optional, default=True - If False, the weight updating is disabled. This allows to perform expanded ensemble simulations. + If False, weights updating is disabled. This allows to perform expanded ensemble simulations. update_stages : str, optional, default='two-stage' One of ['one-stage', 'two-stage'] ``one-stage`` will use the asymptotically optimal scheme throughout the entire simulation (not recommended due to slow convergence) From 97546ac356dd768efe60294e45dccacdd9d08161 Mon Sep 17 00:00:00 2001 From: Silveira Date: Tue, 14 May 2019 11:38:25 -0400 Subject: [PATCH 011/152] fix bug related to the beta factor variable --- openmmtools/multistate/sams.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index a31d7fb1b..61c309a37 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -651,9 +651,9 @@ def _update_logZ_estimates(self, replicas_log_P_k): pi_star = pi_k.min() t = float(self._iteration) if self._stage == 0: # initial stage - gamma = self.gamma0 * min(pi_star, t**(-beta_factor)) # Eq. 15 of [1] + gamma = self.gamma0 * min(pi_star, t**(-self.beta_factor)) # Eq. 15 of [1] elif self._stage == 1: - gamma = self.gamma0 * min(pi_star, (t - self._t0 + self._t0**beta_factor)**(-1)) # Eq. 15 of [1] + gamma = self.gamma0 * min(pi_star, (t - self._t0 + self._t0**self.beta_factor)**(-1)) # Eq. 15 of [1] else: raise Exception('stage {} unknown'.format(self._stage)) From fdeb7286c4f05f47ebbdd729be0f1424231f0576 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Wed, 22 May 2019 22:50:05 -0400 Subject: [PATCH 012/152] Update everything to match MolSSI cookiecutter --- .codecov.yml | 14 + .github/CONTRIBUTING.md | 42 + .github/PULL_REQUEST_TEMPLATE.md | 15 +- .gitignore | 106 +- .lgtm.yml | 12 + .travis.yml | 87 +- CODE_OF_CONDUCT.md | 77 ++ LICENSE | 2 +- MANIFEST.in | 6 + appveyor.yml | 51 +- devtools/README.md | 70 +- devtools/appveyor/install.ps1 | 91 -- devtools/appveyor/run_with_env.cmd | 47 - devtools/conda-envs/test_env.yaml | 35 + devtools/scripts/create_conda_env.py | 95 ++ devtools/travis-ci/before_install.sh | 41 + devtools/travis-ci/install.sh | 23 - setup.cfg | 30 + versioneer.py | 1822 ++++++++++++++++++++++++++ 19 files changed, 2420 insertions(+), 246 deletions(-) create mode 100644 .codecov.yml create mode 100644 .github/CONTRIBUTING.md create mode 100644 .lgtm.yml create mode 100644 CODE_OF_CONDUCT.md create mode 100644 MANIFEST.in delete mode 100644 devtools/appveyor/install.ps1 delete mode 100644 devtools/appveyor/run_with_env.cmd create mode 100644 devtools/conda-envs/test_env.yaml create mode 100644 devtools/scripts/create_conda_env.py create mode 100755 devtools/travis-ci/before_install.sh delete mode 100755 devtools/travis-ci/install.sh create mode 100644 setup.cfg create mode 100644 versioneer.py diff --git a/.codecov.yml b/.codecov.yml new file mode 100644 index 000000000..a3ed7f477 --- /dev/null +++ b/.codecov.yml @@ -0,0 +1,14 @@ +# Codecov configuration to make it a bit less noisy +coverage: + status: + patch: false + project: + default: + threshold: 50% +comment: + layout: "header" + require_changes: false + branches: null + behavior: default + flags: null + paths: null \ No newline at end of file diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 000000000..9582c7873 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# How to contribute + +We welcome contributions from external contributors, and this document +describes how to merge code changes into this openmmtools. + +## Getting Started + +* Make sure you have a [GitHub account](https://github.com/signup/free). +* [Fork](https://help.github.com/articles/fork-a-repo/) this repository on GitHub. +* On your local machine, + [clone](https://help.github.com/articles/cloning-a-repository/) your fork of + the repository. + +## Making Changes + +* Add some really awesome code to your local fork. It's usually a [good + idea](http://blog.jasonmeridth.com/posts/do-not-issue-pull-requests-from-your-master-branch/) + to make changes on a + [branch](https://help.github.com/articles/creating-and-deleting-branches-within-your-repository/) + with the branch name relating to the feature you are going to add. +* When you are ready for others to examine and comment on your new feature, + navigate to your fork of openmmtools on GitHub and open a [pull + request](https://help.github.com/articles/using-pull-requests/) (PR). Note that + after you launch a PR from one of your fork's branches, all + subsequent commits to that branch will be added to the open pull request + automatically. Each commit added to the PR will be validated for + mergability, compilation and test suite compliance; the results of these tests + will be visible on the PR page. +* If you're providing a new feature, you must add test cases and documentation. +* When the code is ready to go, make sure you run the test suite using pytest. +* When you're ready to be considered for merging, check the "Ready to go" + box on the PR page to let the openmmtools devs know that the changes are complete. + The code will not be merged until this box is checked, the continuous + integration returns checkmarks, + and multiple core developers give "Approved" reviews. + +# Additional Resources + +* [General GitHub documentation](https://help.github.com/) +* [PR best practices](http://codeinthehole.com/writing/pull-requests-and-other-good-practices-for-teams-using-github/) +* [A guide to contributing to software packages](http://www.contribution-guide.org) +* [Thinkful PR example](http://www.thinkful.com/learn/github-pull-request-tutorial/#Time-to-Submit-Your-First-PR) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index a7ef2650d..60c2e74c0 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,4 +1,11 @@ - - [ ] Implement feature / fix bug - - [ ] Add [tests](https://github.com/choderalab/openmmtools/tree/master/openmmtools/tests) - - [ ] Update [documentation](https://github.com/choderalab/openmmtools/tree/master/docs) as needed - - [ ] Update [changelog](https://github.com/choderalab/openmmtools/blob/master/docs/releasehistory.rst) \ No newline at end of file +## Description +Provide a brief description of the PR's purpose here. + +## Todos +- [ ] Implement feature / fix bug +- [ ] Add [tests](https://github.com/choderalab/openmmtools/tree/master/openmmtools/tests) +- [ ] Update [documentation](https://github.com/choderalab/openmmtools/tree/master/docs) as needed +- [ ] Update [changelog](https://github.com/choderalab/openmmtools/blob/master/docs/releasehistory.rst)Notable points that this PR has either accomplished or will accomplish. + +## Status +- [ ] Ready to go diff --git a/.gitignore b/.gitignore index 6f8cee03a..e08538a58 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,102 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ *.py[cod] +*$py.class -openmmtools/version.py +# C extensions +*.so -# Packages -*.egg-info -dist -build -__pycache__ +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg -# PyCharm -.idea +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ diff --git a/.lgtm.yml b/.lgtm.yml new file mode 100644 index 000000000..933988bfd --- /dev/null +++ b/.lgtm.yml @@ -0,0 +1,12 @@ +# Configure LGTM for this package + +extraction: + python: # Configure Python + python_setup: # Configure the setup + version: 3 # Specify Version 3 +path_classifiers: + library: + - versioneer.py # Set Versioneer.py to an external "library" (3rd party code) + - devtools/* + generated: + - openmmtools/_version.py diff --git a/.travis.yml b/.travis.yml index 33a92f67d..110cf623e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,46 +1,55 @@ -language: c -sudo: false -addons: - apt: - sources: - - ubuntu-toolchain-r-test +language: python -install: - - bash -x devtools/travis-ci/install.sh - - export PYTHONUNBUFFERED=true - - export PATH=$HOME/miniconda/bin:$PATH +# Run jobs on container-based infrastructure, can be overridden per job + +matrix: + include: + # Extra includes for OSX since python language is not available by default on OSX + - os: osx + language: generic + env: PYTHON_VER=3.6 + - os: osx + language: generic + env: PYTHON_VER=3.7 -script: - # Create a test environment - - conda create --quiet --yes -n test python=$python - # Activate the test environment - - source activate test - # Add org channel - - conda config --add channels ${ORGNAME} - # Add omnia dev channels - - if [ $DEVOMNIA ]; then conda config --add channels omnia-dev; fi - # Add conda-forge channel back to top priority - - conda config --add channels conda-forge - # Build the recipe - - conda build devtools/conda-recipe - # Install the package - - conda install --yes --quiet --use-local ${PACKAGENAME}-dev - # Install testing dependencies. Without specifying the numpy version, numpy - # is downgraded to 1.9 and we get a "libgfortran not found" issue. - - conda install --yes --quiet nose nose-timer pymbar "numpy>=1.14" - # Test the package - - cd devtools && nosetests $PACKAGENAME --nocapture --verbosity=2 --with-timer --with-doctest -a '!slow' && cd .. + + - os: linux + language: generic # No need to set Python version since its conda + env: PYTHON_VER=3.6 + - os: linux + language: generic + env: PYTHON_VER=3.7 env: - matrix: - - python=3.6 CONDA_PY=36 - - python=3.7 CONDA_PY=37 - - python=3.7 CONDA_PY=37 DEVOMNIA=true # allowed to fail global: - - ORGNAME="omnia" # the name of the organization - - PACKAGENAME="openmmtools" # the name of your package - OPENMM_CPU_THREADS="1" # only use one CPU thread for determinism -matrix: - allow_failures: - - env: python=3.7 CONDA_PY=37 DEVOMNIA=true +before_install: + # Additional info about the build + - uname -a + - df -h + - ulimit -a + + # Install the Python environment + - source devtools/travis-ci/before_install.sh + - python -V + +install: + + # Create test environment for package + - python devtools/scripts/create_conda_env.py -n=test -p=$PYTHON_VER devtools/conda-envs/test_env.yaml + # Activate the test environment + - conda activate test + # Build and install package + - python setup.py develop --no-deps + + +script: + #- pytest -v --cov=openmmtools openmmtools/tests/ + - nosetests openmmtools/tests --nocapture --verbosity=2 --with-timer --with-doctest -a '!slow' + +notifications: + email: false + +after_success: + - codecov diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..1f73685a1 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,77 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, +body size, disability, ethnicity, gender identity and expression, level of +experience, nationality, personal appearance, race, religion, or sexual +identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +Moreover, project maintainers will strive to offer feedback and advice to +ensure quality and consistency of contributions to the code. Contributions +from outside the group of project maintainers are strongly welcomed but the +final decision as to whether commits are merged into the codebase rests with +the team of project maintainers. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an +appointed representative at an online or offline event. Representation of a +project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at 'john.chodera@choderalab.org'. The project team will +review and investigate all complaints, and will respond in a way that it deems +appropriate to the circumstances. The project team is obligated to maintain +confidentiality with regard to the reporter of an incident. Further details of +specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.4, available at +[http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/LICENSE b/LICENSE index eba7475aa..05498a993 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2015-2017 Chodera lab // Memorial Sloan Kettering Cancer Center +Copyright (c) 2015-2019 Chodera lab // Memorial Sloan Kettering Cancer Center Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 000000000..9b7f8e8a3 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,6 @@ +include LICENSE +include MANIFEST.in +include versioneer.py + +graft openmmtools +global-exclude *.py[cod] __pycache__ *.so \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index 05898e072..3be7a1e38 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,33 +1,46 @@ environment: - global: - # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the - # /E:ON and /V:ON options are not enabled in the batch script intepreter - # See: http://stackoverflow.com/a/13751649/163740 - CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\devtools\\appveyor\\run_with_env.cmd" matrix: - - PYTHON: "C:\\Python35_64" - PYTHON_VERSION: "3.5" + - PYTHON: "C:\\Miniconda36-x64" + PYTHON_VERSION: "3.6" PYTHON_ARCH: "64" - CONDA_PY: "35" - CONDA_NPY: "112" - - PYTHON: "C:\\Python36_64" - PYTHON_VERSION: "3.6" + - PYTHON: "C:\\Miniconda37-x64" + PYTHON_VERSION: "3.7" PYTHON_ARCH: "64" - CONDA_PY: "36" - CONDA_NPY: "112" + install: - # this installs the appropriate Miniconda (Py2/Py3, 32/64 bit), - # as well as pip, conda-build, and the binstar CLI - - ps: . ".\\devtools\\appveyor\\install.ps1" + # Make sure pip is around + - python -m ensurepip - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" - - conda config --add channels omnia + + # Add conda-forge channel - conda config --add channels conda-forge - - conda config --add channels omnia/label/rc + + # Add omnia channel + - conda config --add channels omnia + + # Always run commands without asking + - conda config --set always_yes yes + + # Try to update conda first to avoid odd dependency clashes + - conda update --all + + # Create test environment for package + - python devtools\\scripts\\create_conda_env.py -n=test -p=%PYTHON_VERSION% devtools\\conda-envs\\test_env.yaml + + # Activate the test environment + - activate test + + # Build and install package + - python setup.py develop --no-deps + build: false test_script: - - "%CMD_IN_ENV% conda build --quiet devtools\\conda-recipe" + - pytest -v --cov=openmmtools openmmtools\\tests + +on_success: + - codecov diff --git a/devtools/README.md b/devtools/README.md index 998d59756..009e161ae 100644 --- a/devtools/README.md +++ b/devtools/README.md @@ -1,18 +1,60 @@ -Developer Notes / Tools -======================= +# Development, testing, and deployment tools -Assorted notes for developers. +This directory contains a collection of tools for running Continuous Integration (CI) tests, +conda installation, and other development tools not directly related to the coding process. -How to do a release -------------------- -- Update the whatsnew.rst document. Use the github view that shows all the commits to master since the last release to write it. -- Update the version number in `setup.py`, change `ISRELEASED` to `True` -- Commit to master, and [tag](https://github.com/choderalab/openmmtools/releases) the release on github -- To push the source to PyPI, use `python setup.py sdist --formats=gztar,zip upload` -- Conda binaries need to built separately on each platform (`conda build openmmtools; binstar upload `) -- Make an annoucement on github / email -- After tagging the release, make a NEW commit that changes `ISRELEASED` back to `False` in `setup.py` +## Manifest -It's important that the version which is tagged on github for the release be -the one with the ISRELEASED flag in setup.py set to true. +### Continuous Integration + +You should test your code, but do not feel compelled to use these specific programs. You also may not need Unix and +Windows testing if you only plan to deploy on specific platforms. These are just to help you get started + +* `travis-ci`: Linux and OSX based testing through [Travis-CI](https://about.travis-ci.com/) + * `before_install.sh`: Pip/Miniconda pre-package installation script for Travis +* `appveyor`: Windows based testing through [AppVeyor](https://www.appveyor.com/) (there are no files directly related to this) + +### Conda Environment: + +This directory contains the files to setup the Conda environment for testing purposes + +* `conda-envs`: directory containing the YAML file(s) which fully describe Conda Environments, their dependencies, and those dependency provenance's + * `test_env.yaml`: Simple test environment file with base dependencies. Channels are not specified here and therefore respect global Conda configuration + +### Additional Scripts: + +This directory contains OS agnostic helper scripts which don't fall in any of the previous categories +* `scripts` + * `create_conda_env.py`: Helper program for spinning up new conda environments based on a starter file with Python Version and Env. Name command-line options + + +## How to contribute changes +- Clone the repository if you have write access to the main repo, fork the repository if you are a collaborator. +- Make a new branch with `git checkout -b {your branch name}` +- Make changes and test your code +- Ensure that the test environment dependencies (`conda-envs`) line up with the build and deploy dependencies (`conda-recipe/meta.yaml`) +- Push the branch to the repo (either the main or your fork) with `git push -u origin {your branch name}` + * Note that `origin` is the default name assigned to the remote, yours may be different +- Make a PR on GitHub with your changes +- We'll review the changes and get your code into the repo after lively discussion! + + +## Checklist for updates +- [ ] Make sure there is an/are issue(s) opened for your specific update +- [ ] Create the PR, referencing the issue +- [ ] Debug the PR as needed until tests pass +- [ ] Tag the final, debugged version + * `git tag -a X.Y.Z [latest pushed commit] && git push --follow-tags` +- [ ] Get the PR merged in + +## Versioneer Auto-version +[Versioneer](https://github.com/warner/python-versioneer) will automatically infer what version +is installed by looking at the `git` tags and how many commits ahead this version is. The format follows +[PEP 440](https://www.python.org/dev/peps/pep-0440/) and has the regular expression of: +```regexp +\d+.\d+.\d+(?\+\d+-[a-z0-9]+) +``` +If the version of this commit is the same as a `git` tag, the installed version is the same as the tag, +e.g. `openmmtools-0.1.2`, otherwise it will be appended with `+X` where `X` is the number of commits +ahead from the last tag, and then `-YYYYYY` where the `Y`'s are replaced with the `git` commit hash. diff --git a/devtools/appveyor/install.ps1 b/devtools/appveyor/install.ps1 deleted file mode 100644 index 5e2f719bc..000000000 --- a/devtools/appveyor/install.ps1 +++ /dev/null @@ -1,91 +0,0 @@ -# Sample script to install Miniconda under Windows -# Authors: Olivier Grisel, Jonathan Helmus and Kyle Kastner, Robert McGibbon -# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ - -$MINICONDA_URL = "http://repo.continuum.io/miniconda/" - - -function DownloadMiniconda ($python_version, $platform_suffix) { - $webclient = New-Object System.Net.WebClient - $filename = "Miniconda3-4.5.4-Windows-" + $platform_suffix + ".exe" - $url = $MINICONDA_URL + $filename - - $basedir = $pwd.Path + "\" - $filepath = $basedir + $filename - if (Test-Path $filename) { - Write-Host "Reusing" $filepath - return $filepath - } - - # Download and retry up to 3 times in case of network transient errors. - Write-Host "Downloading" $filename "from" $url - $retry_attempts = 2 - for($i=0; $i -lt $retry_attempts; $i++){ - try { - $webclient.DownloadFile($url, $filepath) - break - } - Catch [Exception]{ - Start-Sleep 1 - } - } - if (Test-Path $filepath) { - Write-Host "File saved at" $filepath - } else { - # Retry once to get the error message if any at the last try - $webclient.DownloadFile($url, $filepath) - } - return $filepath -} - - -function InstallMiniconda ($python_version, $architecture, $python_home) { - Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home - if (Test-Path $python_home) { - Write-Host $python_home "already exists, skipping." - return $false - } - if ($architecture -match "32") { - $platform_suffix = "x86" - } else { - $platform_suffix = "x86_64" - } - - $filepath = DownloadMiniconda $python_version $platform_suffix - Write-Host "Installing" $filepath "to" $python_home - $install_log = $python_home + ".log" - $args = "/S /D=$python_home" - Write-Host $filepath $args - Start-Process -FilePath $filepath -ArgumentList $args -Wait -Passthru - if (Test-Path $python_home) { - Write-Host "Python $python_version ($architecture) installation complete" - } else { - Write-Host "Failed to install Python in $python_home" - Get-Content -Path $install_log - Exit 1 - } -} - - -function InstallCondaPackages ($python_home, $spec) { - $conda_path = $python_home + "\Scripts\conda.exe" - $args = "install --yes " + $spec - Write-Host ("conda " + $args) - Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru -} - -function UpdateConda ($python_home) { - $conda_path = $python_home + "\Scripts\conda.exe" - Write-Host "Updating conda..." - $args = "update --yes conda" - Write-Host $conda_path $args - Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru -} - -function main () { - InstallMiniconda $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON - UpdateConda $env:PYTHON - InstallCondaPackages $env:PYTHON "conda-build pip jinja2 binstar" -} - -main diff --git a/devtools/appveyor/run_with_env.cmd b/devtools/appveyor/run_with_env.cmd deleted file mode 100644 index 3a472bc83..000000000 --- a/devtools/appveyor/run_with_env.cmd +++ /dev/null @@ -1,47 +0,0 @@ -:: To build extensions for 64 bit Python 3, we need to configure environment -:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of: -:: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1) -:: -:: To build extensions for 64 bit Python 2, we need to configure environment -:: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of: -:: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0) -:: -:: 32 bit builds do not require specific environment configurations. -:: -:: Note: this script needs to be run with the /E:ON and /V:ON flags for the -:: cmd interpreter, at least for (SDK v7.0) -:: -:: More details at: -:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows -:: http://stackoverflow.com/a/13751649/163740 -:: -:: Author: Olivier Grisel -:: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ -@ECHO OFF - -SET COMMAND_TO_RUN=%* -SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows - -SET MAJOR_PYTHON_VERSION="%PYTHON_VERSION:~0,1%" -IF %MAJOR_PYTHON_VERSION% == "2" ( - SET WINDOWS_SDK_VERSION="v7.0" -) ELSE IF %MAJOR_PYTHON_VERSION% == "3" ( - SET WINDOWS_SDK_VERSION="v7.1" -) ELSE ( - ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%" - EXIT 1 -) - -IF "%PYTHON_ARCH%"=="64" ( - ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture - SET DISTUTILS_USE_SDK=1 - SET MSSdk=1 - "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION% - "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release - ECHO Executing: %COMMAND_TO_RUN% - call %COMMAND_TO_RUN% || EXIT 1 -) ELSE ( - ECHO Using default MSVC build environment for 32 bit architecture - ECHO Executing: %COMMAND_TO_RUN% - call %COMMAND_TO_RUN% || EXIT 1 -) diff --git a/devtools/conda-envs/test_env.yaml b/devtools/conda-envs/test_env.yaml new file mode 100644 index 000000000..6e56c296e --- /dev/null +++ b/devtools/conda-envs/test_env.yaml @@ -0,0 +1,35 @@ +name: test +channels: +dependencies: + # Base depends + - python + - pip + + - setuptools + - openmm >=7.3.1 + - cython + - python + - numpy + - scipy + - six + - openmm >=7.3.1 + - parmed + - mdtraj + - netcdf4 >=1.4.2 # after bugfix: "always return masked array by default, even if there are no masked values" + - libnetcdf >=4.6.2 # workaround for libssl issues + - pyyaml + - cython + - sphinxcontrib-bibtex + - mpiplus + - pymbar + - pyyaml + + # Testing + - nose + #- pytest + #- pytest-cov + - codecov + + # Pip-only installs + - pip: + #- codecov diff --git a/devtools/scripts/create_conda_env.py b/devtools/scripts/create_conda_env.py new file mode 100644 index 000000000..b51adc86d --- /dev/null +++ b/devtools/scripts/create_conda_env.py @@ -0,0 +1,95 @@ +import argparse +import os +import re +import glob +import shutil +import subprocess as sp +from tempfile import TemporaryDirectory +from contextlib import contextmanager +# YAML imports +try: + import yaml # PyYAML + loader = yaml.load +except ImportError: + try: + import ruamel_yaml as yaml # Ruamel YAML + except ImportError: + try: + # Load Ruamel YAML from the base conda environment + from importlib import util as import_util + CONDA_BIN = os.path.dirname(os.environ['CONDA_EXE']) + ruamel_yaml_path = glob.glob(os.path.join(CONDA_BIN, '..', + 'lib', 'python*.*', 'site-packages', + 'ruamel_yaml', '__init__.py'))[0] + # Based on importlib example, but only needs to load_module since its the whole package, not just + # a module + spec = import_util.spec_from_file_location('ruamel_yaml', ruamel_yaml_path) + yaml = spec.loader.load_module() + except (KeyError, ImportError, IndexError): + raise ImportError("No YAML parser could be found in this or the conda environment. " + "Could not find PyYAML or Ruamel YAML in the current environment, " + "AND could not find Ruamel YAML in the base conda environment through CONDA_EXE path. " + "Environment not created!") + loader = yaml.YAML(typ="safe").load # typ="safe" avoids odd typing on output + + +@contextmanager +def temp_cd(): + """Temporary CD Helper""" + cwd = os.getcwd() + with TemporaryDirectory() as td: + try: + os.chdir(td) + yield + finally: + os.chdir(cwd) + + +# Args +parser = argparse.ArgumentParser(description='Creates a conda environment from file for a given Python version.') +parser.add_argument('-n', '--name', type=str, + help='The name of the created Python environment') +parser.add_argument('-p', '--python', type=str, + help='The version of the created Python environment') +parser.add_argument('conda_file', + help='The file for the created Python environment') + +args = parser.parse_args() + +# Open the base file +with open(args.conda_file, "r") as handle: + yaml_script = loader(handle.read()) + +python_replacement_string = "python {}*".format(args.python) + +try: + for dep_index, dep_value in enumerate(yaml_script['dependencies']): + if re.match('python([ ><=*]+[0-9.*]*)?$', dep_value): # Match explicitly 'python' and its formats + yaml_script['dependencies'].pop(dep_index) + break # Making the assumption there is only one Python entry, also avoids need to enumerate in reverse +except (KeyError, TypeError): + # Case of no dependencies key, or dependencies: None + yaml_script['dependencies'] = [] +finally: + # Ensure the python version is added in. Even if the code does not need it, we assume the env does + yaml_script['dependencies'].insert(0, python_replacement_string) + +# Figure out conda path +if "CONDA_EXE" in os.environ: + conda_path = os.environ["CONDA_EXE"] +else: + conda_path = shutil.which("conda") +if conda_path is None: + raise RuntimeError("Could not find a conda binary in CONDA_EXE variable or in executable search path") + +print("CONDA ENV NAME {}".format(args.name)) +print("PYTHON VERSION {}".format(args.python)) +print("CONDA FILE NAME {}".format(args.conda_file)) +print("CONDA PATH {}".format(conda_path)) + +# Write to a temp directory which will always be cleaned up +with temp_cd(): + temp_file_name = "temp_script.yaml" + with open(temp_file_name, 'w') as f: + f.write(yaml.dump(yaml_script)) + sp.call("{} env create -n {} -f {}".format(conda_path, args.name, temp_file_name), shell=True) diff --git a/devtools/travis-ci/before_install.sh b/devtools/travis-ci/before_install.sh new file mode 100755 index 000000000..cfaa07398 --- /dev/null +++ b/devtools/travis-ci/before_install.sh @@ -0,0 +1,41 @@ +# Temporarily change directory to $HOME to install software +pushd . +cd $HOME +# Make sure some level of pip is installed +python -m ensurepip + +# Install Miniconda +if [ "$TRAVIS_OS_NAME" == "osx" ]; then + # Make OSX md5 mimic md5sum from linux, alias does not work + md5sum () { + command md5 -r "$@" + } + MINICONDA=Miniconda3-latest-MacOSX-x86_64.sh +else + MINICONDA=Miniconda3-latest-Linux-x86_64.sh +fi +MINICONDA_HOME=$HOME/miniconda +MINICONDA_MD5=$(curl -s https://repo.continuum.io/miniconda/ | grep -A3 $MINICONDA | sed -n '4p' | sed -n 's/ *\(.*\)<\/td> */\1/p') +wget -q https://repo.continuum.io/miniconda/$MINICONDA +if [[ $MINICONDA_MD5 != $(md5sum $MINICONDA | cut -d ' ' -f 1) ]]; then + echo "Miniconda MD5 mismatch" + exit 1 +fi +bash $MINICONDA -b -p $MINICONDA_HOME + +# Configure miniconda +export PIP_ARGS="-U" +# New to conda >=4.4 +echo ". $MINICONDA_HOME/etc/profile.d/conda.sh" >> ~/.bashrc # Source the profile.d file +echo "conda activate" >> ~/.bashrc # Activate conda +source ~/.bashrc # source file to get new commands +#export PATH=$MINICONDA_HOME/bin:$PATH # Old way, should not be needed anymore + +conda config --add channels conda-forge + +conda config --set always_yes yes +conda install conda conda-build jinja2 anaconda-client +conda update --quiet --all + +# Restore original directory +popd diff --git a/devtools/travis-ci/install.sh b/devtools/travis-ci/install.sh deleted file mode 100755 index 1bab8e1b1..000000000 --- a/devtools/travis-ci/install.sh +++ /dev/null @@ -1,23 +0,0 @@ -# Temporarily change directory to $HOME to install software -pushd . -cd $HOME - -# Install Miniconda -MINICONDA=Miniconda2-latest-Linux-x86_64.sh -MINICONDA_HOME=$HOME/miniconda -MINICONDA_MD5=$(curl -s https://repo.continuum.io/miniconda/ | grep -A3 $MINICONDA | sed -n '4p' | sed -n 's/ *\(.*\)<\/td> */\1/p') -wget -q https://repo.continuum.io/miniconda/$MINICONDA -if [[ $MINICONDA_MD5 != $(md5sum $MINICONDA | cut -d ' ' -f 1) ]]; then - echo "Miniconda MD5 mismatch" - exit 1 -fi -bash $MINICONDA -b -p $MINICONDA_HOME - -# Configure miniconda -export PIP_ARGS="-U" -export PATH=$MINICONDA_HOME/bin:$PATH -conda config --add channels conda-forge -conda install --yes conda\>=4.3 conda-build jinja2 anaconda-client pip - -# Restore original directory -popd diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 000000000..71d5c913e --- /dev/null +++ b/setup.cfg @@ -0,0 +1,30 @@ +# Helper file to handle all configs + +[coverage:run] +# .coveragerc to control coverage.py and pytest-cov +omit = + # Omit the tests + */tests/* + # Omit generated versioneer + openmmtools/_version.py + +[yapf] +# YAPF, in .style.yapf files this shows up as "[style]" header +COLUMN_LIMIT = 119 +INDENT_WIDTH = 4 +USE_TABS = False + +[flake8] +# Flake8, PyFlakes, etc +max-line-length = 119 + +[versioneer] +# Automatic version numbering scheme +VCS = git +style = pep440 +versionfile_source = openmmtools/_version.py +versionfile_build = openmmtools/_version.py +tag_prefix = '' + +[aliases] +test = pytest diff --git a/versioneer.py b/versioneer.py new file mode 100644 index 000000000..64fea1c89 --- /dev/null +++ b/versioneer.py @@ -0,0 +1,1822 @@ + +# Version: 0.18 + +"""The Versioneer - like a rocketeer, but for versions. + +The Versioneer +============== + +* like a rocketeer, but for versions! +* https://github.com/warner/python-versioneer +* Brian Warner +* License: Public Domain +* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy +* [![Latest Version] +(https://pypip.in/version/versioneer/badge.svg?style=flat) +](https://pypi.python.org/pypi/versioneer/) +* [![Build Status] +(https://travis-ci.org/warner/python-versioneer.png?branch=master) +](https://travis-ci.org/warner/python-versioneer) + +This is a tool for managing a recorded version number in distutils-based +python projects. The goal is to remove the tedious and error-prone "update +the embedded version string" step from your release process. Making a new +release should be as easy as recording a new tag in your version-control +system, and maybe making new tarballs. + + +## Quick Install + +* `pip install versioneer` to somewhere to your $PATH +* add a `[versioneer]` section to your setup.cfg (see below) +* run `versioneer install` in your source tree, commit the results + +## Version Identifiers + +Source trees come from a variety of places: + +* a version-control system checkout (mostly used by developers) +* a nightly tarball, produced by build automation +* a snapshot tarball, produced by a web-based VCS browser, like github's + "tarball from tag" feature +* a release tarball, produced by "setup.py sdist", distributed through PyPI + +Within each source tree, the version identifier (either a string or a number, +this tool is format-agnostic) can come from a variety of places: + +* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows + about recent "tags" and an absolute revision-id +* the name of the directory into which the tarball was unpacked +* an expanded VCS keyword ($Id$, etc) +* a `_version.py` created by some earlier build step + +For released software, the version identifier is closely related to a VCS +tag. Some projects use tag names that include more than just the version +string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool +needs to strip the tag prefix to extract the version identifier. For +unreleased software (between tags), the version identifier should provide +enough information to help developers recreate the same tree, while also +giving them an idea of roughly how old the tree is (after version 1.2, before +version 1.3). Many VCS systems can report a description that captures this, +for example `git describe --tags --dirty --always` reports things like +"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the +0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has +uncommitted changes. + +The version identifier is used for multiple purposes: + +* to allow the module to self-identify its version: `myproject.__version__` +* to choose a name and prefix for a 'setup.py sdist' tarball + +## Theory of Operation + +Versioneer works by adding a special `_version.py` file into your source +tree, where your `__init__.py` can import it. This `_version.py` knows how to +dynamically ask the VCS tool for version information at import time. + +`_version.py` also contains `$Revision$` markers, and the installation +process marks `_version.py` to have this marker rewritten with a tag name +during the `git archive` command. As a result, generated tarballs will +contain enough information to get the proper version. + +To allow `setup.py` to compute a version too, a `versioneer.py` is added to +the top level of your source tree, next to `setup.py` and the `setup.cfg` +that configures it. This overrides several distutils/setuptools commands to +compute the version when invoked, and changes `setup.py build` and `setup.py +sdist` to replace `_version.py` with a small static file that contains just +the generated version data. + +## Installation + +See [INSTALL.md](./INSTALL.md) for detailed installation instructions. + +## Version-String Flavors + +Code which uses Versioneer can learn about its version string at runtime by +importing `_version` from your main `__init__.py` file and running the +`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can +import the top-level `versioneer.py` and run `get_versions()`. + +Both functions return a dictionary with different flavors of version +information: + +* `['version']`: A condensed version string, rendered using the selected + style. This is the most commonly used value for the project's version + string. The default "pep440" style yields strings like `0.11`, + `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section + below for alternative styles. + +* `['full-revisionid']`: detailed revision identifier. For Git, this is the + full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". + +* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the + commit date in ISO 8601 format. This will be None if the date is not + available. + +* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that + this is only accurate if run in a VCS checkout, otherwise it is likely to + be False or None + +* `['error']`: if the version string could not be computed, this will be set + to a string describing the problem, otherwise it will be None. It may be + useful to throw an exception in setup.py if this is set, to avoid e.g. + creating tarballs with a version string of "unknown". + +Some variants are more useful than others. Including `full-revisionid` in a +bug report should allow developers to reconstruct the exact code being tested +(or indicate the presence of local changes that should be shared with the +developers). `version` is suitable for display in an "about" box or a CLI +`--version` output: it can be easily compared against release notes and lists +of bugs fixed in various releases. + +The installer adds the following text to your `__init__.py` to place a basic +version in `YOURPROJECT.__version__`: + + from ._version import get_versions + __version__ = get_versions()['version'] + del get_versions + +## Styles + +The setup.cfg `style=` configuration controls how the VCS information is +rendered into a version string. + +The default style, "pep440", produces a PEP440-compliant string, equal to the +un-prefixed tag name for actual releases, and containing an additional "local +version" section with more detail for in-between builds. For Git, this is +TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags +--dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the +tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and +that this commit is two revisions ("+2") beyond the "0.11" tag. For released +software (exactly equal to a known tag), the identifier will only contain the +stripped tag, e.g. "0.11". + +Other styles are available. See [details.md](details.md) in the Versioneer +source tree for descriptions. + +## Debugging + +Versioneer tries to avoid fatal errors: if something goes wrong, it will tend +to return a version of "0+unknown". To investigate the problem, run `setup.py +version`, which will run the version-lookup code in a verbose mode, and will +display the full contents of `get_versions()` (including the `error` string, +which may help identify what went wrong). + +## Known Limitations + +Some situations are known to cause problems for Versioneer. This details the +most significant ones. More can be found on Github +[issues page](https://github.com/warner/python-versioneer/issues). + +### Subprojects + +Versioneer has limited support for source trees in which `setup.py` is not in +the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are +two common reasons why `setup.py` might not be in the root: + +* Source trees which contain multiple subprojects, such as + [Buildbot](https://github.com/buildbot/buildbot), which contains both + "master" and "slave" subprojects, each with their own `setup.py`, + `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI + distributions (and upload multiple independently-installable tarballs). +* Source trees whose main purpose is to contain a C library, but which also + provide bindings to Python (and perhaps other langauges) in subdirectories. + +Versioneer will look for `.git` in parent directories, and most operations +should get the right version string. However `pip` and `setuptools` have bugs +and implementation details which frequently cause `pip install .` from a +subproject directory to fail to find a correct version string (so it usually +defaults to `0+unknown`). + +`pip install --editable .` should work correctly. `setup.py install` might +work too. + +Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in +some later version. + +[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking +this issue. The discussion in +[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the +issue from the Versioneer side in more detail. +[pip PR#3176](https://github.com/pypa/pip/pull/3176) and +[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve +pip to let Versioneer work correctly. + +Versioneer-0.16 and earlier only looked for a `.git` directory next to the +`setup.cfg`, so subprojects were completely unsupported with those releases. + +### Editable installs with setuptools <= 18.5 + +`setup.py develop` and `pip install --editable .` allow you to install a +project into a virtualenv once, then continue editing the source code (and +test) without re-installing after every change. + +"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a +convenient way to specify executable scripts that should be installed along +with the python package. + +These both work as expected when using modern setuptools. When using +setuptools-18.5 or earlier, however, certain operations will cause +`pkg_resources.DistributionNotFound` errors when running the entrypoint +script, which must be resolved by re-installing the package. This happens +when the install happens with one version, then the egg_info data is +regenerated while a different version is checked out. Many setup.py commands +cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into +a different virtualenv), so this can be surprising. + +[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes +this one, but upgrading to a newer version of setuptools should probably +resolve it. + +### Unicode version strings + +While Versioneer works (and is continually tested) with both Python 2 and +Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. +Newer releases probably generate unicode version strings on py2. It's not +clear that this is wrong, but it may be surprising for applications when then +write these strings to a network connection or include them in bytes-oriented +APIs like cryptographic checksums. + +[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates +this question. + + +## Updating Versioneer + +To upgrade your project to a new release of Versioneer, do the following: + +* install the new Versioneer (`pip install -U versioneer` or equivalent) +* edit `setup.cfg`, if necessary, to include any new configuration settings + indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install` in your source tree, to replace + `SRC/_version.py` +* commit any changed files + +## Future Directions + +This tool is designed to make it easily extended to other version-control +systems: all VCS-specific components are in separate directories like +src/git/ . The top-level `versioneer.py` script is assembled from these +components by running make-versioneer.py . In the future, make-versioneer.py +will take a VCS name as an argument, and will construct a version of +`versioneer.py` that is specific to the given VCS. It might also take the +configuration arguments that are currently provided manually during +installation by editing setup.py . Alternatively, it might go the other +direction and include code from all supported VCS systems, reducing the +number of intermediate scripts. + + +## License + +To make Versioneer easier to embed, all its code is dedicated to the public +domain. The `_version.py` that it creates is also in the public domain. +Specifically, both are released under the Creative Commons "Public Domain +Dedication" license (CC0-1.0), as described in +https://creativecommons.org/publicdomain/zero/1.0/ . + +""" + +from __future__ import print_function +try: + import configparser +except ImportError: + import ConfigParser as configparser +import errno +import json +import os +import re +import subprocess +import sys + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_root(): + """Get the project root directory. + + We require that all commands are run from the project root, i.e. the + directory that contains setup.py, setup.cfg, and versioneer.py . + """ + root = os.path.realpath(os.path.abspath(os.getcwd())) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + # allow 'python path/to/setup.py COMMAND' + root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + err = ("Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND').") + raise VersioneerBadRootError(err) + try: + # Certain runtime workflows (setup.py install/develop in a setuptools + # tree) execute all dependencies in a single python process, so + # "versioneer" may be imported multiple times, and python's shared + # module-import table will cache the first one. So we can't use + # os.path.dirname(__file__), as that will find whichever + # versioneer.py was first imported, even in later projects. + me = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(me)[0]) + vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) + if me_dir != vsr_dir: + print("Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(me), versioneer_py)) + except NameError: + pass + return root + + +def get_config_from_root(root): + """Read the project setup.cfg file to determine Versioneer config.""" + # This might raise EnvironmentError (if setup.cfg is missing), or + # configparser.NoSectionError (if it lacks a [versioneer] section), or + # configparser.NoOptionError (if it lacks "VCS="). See the docstring at + # the top of versioneer.py for instructions on writing your setup.cfg . + setup_cfg = os.path.join(root, "setup.cfg") + parser = configparser.SafeConfigParser() + with open(setup_cfg, "r") as f: + parser.readfp(f) + VCS = parser.get("versioneer", "VCS") # mandatory + + def get(parser, name): + if parser.has_option("versioneer", name): + return parser.get("versioneer", name) + return None + cfg = VersioneerConfig() + cfg.VCS = VCS + cfg.style = get(parser, "style") or "" + cfg.versionfile_source = get(parser, "versionfile_source") + cfg.versionfile_build = get(parser, "versionfile_build") + cfg.tag_prefix = get(parser, "tag_prefix") + if cfg.tag_prefix in ("''", '""'): + cfg.tag_prefix = "" + cfg.parentdir_prefix = get(parser, "parentdir_prefix") + cfg.verbose = get(parser, "verbose") + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +# these dictionaries contain VCS-specific tools +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode + + +LONG_VERSION_PY['git'] = ''' +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.18 (https://github.com/warner/python-versioneer) + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" + git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" + git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" + keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "%(STYLE)s" + cfg.tag_prefix = "%(TAG_PREFIX)s" + cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" + cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %%s" %% dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %%s" %% (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %%s (error)" %% dispcmd) + print("stdout was %%s" %% stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %%s but none started with prefix %%s" %% + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %%d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%%s', no digits" %% ",".join(refs - tags)) + if verbose: + print("likely tags: %%s" %% ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %%s" %% r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %%s not under git control" %% root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%%s*" %% tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%%s'" + %% describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%%s' doesn't start with prefix '%%s'" + print(fmt %% (full_tag, tag_prefix)) + pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" + %% (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], + cwd=root)[0].strip() + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%%d" %% pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%%d" %% pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%%s'" %% style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} +''' + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs - tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], + cwd=root)[0].strip() + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def do_vcs_install(manifest_in, versionfile_source, ipy): + """Git-specific installation logic for Versioneer. + + For Git, this means creating/changing .gitattributes to mark _version.py + for export-subst keyword substitution. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + files = [manifest_in, versionfile_source] + if ipy: + files.append(ipy) + try: + me = __file__ + if me.endswith(".pyc") or me.endswith(".pyo"): + me = os.path.splitext(me)[0] + ".py" + versioneer_file = os.path.relpath(me) + except NameError: + versioneer_file = "versioneer.py" + files.append(versioneer_file) + present = False + try: + f = open(".gitattributes", "r") + for line in f.readlines(): + if line.strip().startswith(versionfile_source): + if "export-subst" in line.strip().split()[1:]: + present = True + f.close() + except EnvironmentError: + pass + if not present: + f = open(".gitattributes", "a+") + f.write("%s export-subst\n" % versionfile_source) + f.close() + files.append(".gitattributes") + run_command(GITS, ["add", "--"] + files) + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +SHORT_VERSION_PY = """ +# This file was generated by 'versioneer.py' (0.18) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +import json + +version_json = ''' +%s +''' # END VERSION_JSON + + +def get_versions(): + return json.loads(version_json) +""" + + +def versions_from_file(filename): + """Try to determine the version from _version.py if present.""" + try: + with open(filename) as f: + contents = f.read() + except EnvironmentError: + raise NotThisMethod("unable to read _version.py") + mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + raise NotThisMethod("no version_json in _version.py") + return json.loads(mo.group(1)) + + +def write_to_version_file(filename, versions): + """Write the given version number to the given _version.py file.""" + os.unlink(filename) + contents = json.dumps(versions, sort_keys=True, + indent=1, separators=(",", ": ")) + with open(filename, "w") as f: + f.write(SHORT_VERSION_PY % contents) + + print("set %s to '%s'" % (filename, versions["version"])) + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +class VersioneerBadRootError(Exception): + """The project root directory is unknown or missing key files.""" + + +def get_versions(verbose=False): + """Get the project version from whatever source is available. + + Returns dict with two keys: 'version' and 'full'. + """ + if "versioneer" in sys.modules: + # see the discussion in cmdclass.py:get_cmdclass() + del sys.modules["versioneer"] + + root = get_root() + cfg = get_config_from_root(root) + + assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" + handlers = HANDLERS.get(cfg.VCS) + assert handlers, "unrecognized VCS '%s'" % cfg.VCS + verbose = verbose or cfg.verbose + assert cfg.versionfile_source is not None, \ + "please set versioneer.versionfile_source" + assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" + + versionfile_abs = os.path.join(root, cfg.versionfile_source) + + # extract version from first of: _version.py, VCS command (e.g. 'git + # describe'), parentdir. This is meant to work for developers using a + # source checkout, for users of a tarball created by 'setup.py sdist', + # and for users of a tarball/zipball created by 'git archive' or github's + # download-from-tag feature or the equivalent in other VCSes. + + get_keywords_f = handlers.get("get_keywords") + from_keywords_f = handlers.get("keywords") + if get_keywords_f and from_keywords_f: + try: + keywords = get_keywords_f(versionfile_abs) + ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) + if verbose: + print("got version from expanded keyword %s" % ver) + return ver + except NotThisMethod: + pass + + try: + ver = versions_from_file(versionfile_abs) + if verbose: + print("got version from file %s %s" % (versionfile_abs, ver)) + return ver + except NotThisMethod: + pass + + from_vcs_f = handlers.get("pieces_from_vcs") + if from_vcs_f: + try: + pieces = from_vcs_f(cfg.tag_prefix, root, verbose) + ver = render(pieces, cfg.style) + if verbose: + print("got version from VCS %s" % ver) + return ver + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + if verbose: + print("got version from parentdir %s" % ver) + return ver + except NotThisMethod: + pass + + if verbose: + print("unable to compute version") + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, "error": "unable to compute version", + "date": None} + + +def get_version(): + """Get the short version string for this project.""" + return get_versions()["version"] + + +def get_cmdclass(): + """Get the custom setuptools/distutils subclasses used by Versioneer.""" + if "versioneer" in sys.modules: + del sys.modules["versioneer"] + # this fixes the "python setup.py develop" case (also 'install' and + # 'easy_install .'), in which subdependencies of the main project are + # built (using setup.py bdist_egg) in the same python process. Assume + # a main project A and a dependency B, which use different versions + # of Versioneer. A's setup.py imports A's Versioneer, leaving it in + # sys.modules by the time B's setup.py is executed, causing B to run + # with the wrong versioneer. Setuptools wraps the sub-dep builds in a + # sandbox that restores sys.modules to it's pre-build state, so the + # parent is protected against the child's "import versioneer". By + # removing ourselves from sys.modules here, before the child build + # happens, we protect the child from the parent's versioneer too. + # Also see https://github.com/warner/python-versioneer/issues/52 + + cmds = {} + + # we add "version" to both distutils and setuptools + from distutils.core import Command + + class cmd_version(Command): + description = "report generated version string" + user_options = [] + boolean_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + vers = get_versions(verbose=True) + print("Version: %s" % vers["version"]) + print(" full-revisionid: %s" % vers.get("full-revisionid")) + print(" dirty: %s" % vers.get("dirty")) + print(" date: %s" % vers.get("date")) + if vers["error"]: + print(" error: %s" % vers["error"]) + cmds["version"] = cmd_version + + # we override "build_py" in both distutils and setuptools + # + # most invocation pathways end up running build_py: + # distutils/build -> build_py + # distutils/install -> distutils/build ->.. + # setuptools/bdist_wheel -> distutils/install ->.. + # setuptools/bdist_egg -> distutils/install_lib -> build_py + # setuptools/install -> bdist_egg ->.. + # setuptools/develop -> ? + # pip install: + # copies source tree to a tempdir before running egg_info/etc + # if .git isn't copied too, 'git describe' will fail + # then does setup.py bdist_wheel, or sometimes setup.py install + # setup.py egg_info -> ? + + # we override different "build_py" commands for both environments + if "setuptools" in sys.modules: + from setuptools.command.build_py import build_py as _build_py + else: + from distutils.command.build_py import build_py as _build_py + + class cmd_build_py(_build_py): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_py.run(self) + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if cfg.versionfile_build: + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_py"] = cmd_build_py + + if "cx_Freeze" in sys.modules: # cx_freeze enabled? + from cx_Freeze.dist import build_exe as _build_exe + # nczeczulin reports that py2exe won't like the pep440-style string + # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. + # setup(console=[{ + # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION + # "product_version": versioneer.get_version(), + # ... + + class cmd_build_exe(_build_exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _build_exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["build_exe"] = cmd_build_exe + del cmds["build_py"] + + if 'py2exe' in sys.modules: # py2exe enabled? + try: + from py2exe.distutils_buildexe import py2exe as _py2exe # py3 + except ImportError: + from py2exe.build_exe import py2exe as _py2exe # py2 + + class cmd_py2exe(_py2exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _py2exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["py2exe"] = cmd_py2exe + + # we override different "sdist" commands for both environments + if "setuptools" in sys.modules: + from setuptools.command.sdist import sdist as _sdist + else: + from distutils.command.sdist import sdist as _sdist + + class cmd_sdist(_sdist): + def run(self): + versions = get_versions() + self._versioneer_generated_versions = versions + # unless we update this, the command will keep using the old + # version + self.distribution.metadata.version = versions["version"] + return _sdist.run(self) + + def make_release_tree(self, base_dir, files): + root = get_root() + cfg = get_config_from_root(root) + _sdist.make_release_tree(self, base_dir, files) + # now locate _version.py in the new base_dir directory + # (remembering that it may be a hardlink) and replace it with an + # updated value + target_versionfile = os.path.join(base_dir, cfg.versionfile_source) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, + self._versioneer_generated_versions) + cmds["sdist"] = cmd_sdist + + return cmds + + +CONFIG_ERROR = """ +setup.cfg is missing the necessary Versioneer configuration. You need +a section like: + + [versioneer] + VCS = git + style = pep440 + versionfile_source = src/myproject/_version.py + versionfile_build = myproject/_version.py + tag_prefix = + parentdir_prefix = myproject- + +You will also need to edit your setup.py to use the results: + + import versioneer + setup(version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), ...) + +Please read the docstring in ./versioneer.py for configuration instructions, +edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. +""" + +SAMPLE_CONFIG = """ +# See the docstring in versioneer.py for instructions. Note that you must +# re-run 'versioneer.py setup' after changing this section, and commit the +# resulting files. + +[versioneer] +#VCS = git +#style = pep440 +#versionfile_source = +#versionfile_build = +#tag_prefix = +#parentdir_prefix = + +""" + +INIT_PY_SNIPPET = """ +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions +""" + + +def do_setup(): + """Main VCS-independent setup function for installing Versioneer.""" + root = get_root() + try: + cfg = get_config_from_root(root) + except (EnvironmentError, configparser.NoSectionError, + configparser.NoOptionError) as e: + if isinstance(e, (EnvironmentError, configparser.NoSectionError)): + print("Adding sample versioneer config to setup.cfg", + file=sys.stderr) + with open(os.path.join(root, "setup.cfg"), "a") as f: + f.write(SAMPLE_CONFIG) + print(CONFIG_ERROR, file=sys.stderr) + return 1 + + print(" creating %s" % cfg.versionfile_source) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), + "__init__.py") + if os.path.exists(ipy): + try: + with open(ipy, "r") as f: + old = f.read() + except EnvironmentError: + old = "" + if INIT_PY_SNIPPET not in old: + print(" appending to %s" % ipy) + with open(ipy, "a") as f: + f.write(INIT_PY_SNIPPET) + else: + print(" %s unmodified" % ipy) + else: + print(" %s doesn't exist, ok" % ipy) + ipy = None + + # Make sure both the top-level "versioneer.py" and versionfile_source + # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so + # they'll be copied into source distributions. Pip won't be able to + # install the package without this. + manifest_in = os.path.join(root, "MANIFEST.in") + simple_includes = set() + try: + with open(manifest_in, "r") as f: + for line in f: + if line.startswith("include "): + for include in line.split()[1:]: + simple_includes.add(include) + except EnvironmentError: + pass + # That doesn't cover everything MANIFEST.in can do + # (http://docs.python.org/2/distutils/sourcedist.html#commands), so + # it might give some false negatives. Appending redundant 'include' + # lines is safe, though. + if "versioneer.py" not in simple_includes: + print(" appending 'versioneer.py' to MANIFEST.in") + with open(manifest_in, "a") as f: + f.write("include versioneer.py\n") + else: + print(" 'versioneer.py' already in MANIFEST.in") + if cfg.versionfile_source not in simple_includes: + print(" appending versionfile_source ('%s') to MANIFEST.in" % + cfg.versionfile_source) + with open(manifest_in, "a") as f: + f.write("include %s\n" % cfg.versionfile_source) + else: + print(" versionfile_source already in MANIFEST.in") + + # Make VCS-specific changes. For git, this means creating/changing + # .gitattributes to mark _version.py for export-subst keyword + # substitution. + do_vcs_install(manifest_in, cfg.versionfile_source, ipy) + return 0 + + +def scan_setup_py(): + """Validate the contents of setup.py against Versioneer's expectations.""" + found = set() + setters = False + errors = 0 + with open("setup.py", "r") as f: + for line in f.readlines(): + if "import versioneer" in line: + found.add("import") + if "versioneer.get_cmdclass()" in line: + found.add("cmdclass") + if "versioneer.get_version()" in line: + found.add("get_version") + if "versioneer.VCS" in line: + setters = True + if "versioneer.versionfile_source" in line: + setters = True + if len(found) != 3: + print("") + print("Your setup.py appears to be missing some important items") + print("(but I might be wrong). Please make sure it has something") + print("roughly like the following:") + print("") + print(" import versioneer") + print(" setup( version=versioneer.get_version(),") + print(" cmdclass=versioneer.get_cmdclass(), ...)") + print("") + errors += 1 + if setters: + print("You should remove lines like 'versioneer.VCS = ' and") + print("'versioneer.versionfile_source = ' . This configuration") + print("now lives in setup.cfg, and should be removed from setup.py") + print("") + errors += 1 + return errors + + +if __name__ == "__main__": + cmd = sys.argv[1] + if cmd == "setup": + errors = do_setup() + errors += scan_setup_py() + if errors: + sys.exit(1) From 973e60a2a4a713f8541f690739135ca4be66a9fd Mon Sep 17 00:00:00 2001 From: John Chodera Date: Wed, 22 May 2019 22:51:57 -0400 Subject: [PATCH 013/152] Update changelog --- docs/releasehistory.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index e6fc2958b..96a573c89 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -9,7 +9,7 @@ New features Bugfixes -------- - +- Update build infrasctructure to match `MolSSI cookiecutter `_. 0.18.1 - Bugfix release ======================= @@ -36,7 +36,7 @@ New features - ``MultiStateSampler``: sample independently from multiple thermodynamic states - ``ReplicaExchangeSampler``: replica exchange among thermodynamic states - ``SAMSSampler``: self-adjusted mixture sampling (SAMS) sampling -- All samplers can use MPI via the ``mpiplus `_ package +- All samplers can use MPI via the `mpiplus `_ package 0.17.0 - Removed Py2 support, faster exact PME treatment ======================================================== From d5a27f96f2f17269d2eb81c7c14b09da9f49d883 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Wed, 22 May 2019 23:12:06 -0400 Subject: [PATCH 014/152] Add channels to conda envs --- devtools/conda-envs/test_env.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/devtools/conda-envs/test_env.yaml b/devtools/conda-envs/test_env.yaml index 6e56c296e..c9619296b 100644 --- a/devtools/conda-envs/test_env.yaml +++ b/devtools/conda-envs/test_env.yaml @@ -1,5 +1,8 @@ name: test channels: + - conda-forge + - omnia + - defaults dependencies: # Base depends - python From 55908fd4c20985b8b00de38ca50d1f4eb82f749f Mon Sep 17 00:00:00 2001 From: John Chodera Date: Fri, 24 May 2019 00:09:19 -0400 Subject: [PATCH 015/152] Add missing dependencies --- devtools/conda-envs/test_env.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/devtools/conda-envs/test_env.yaml b/devtools/conda-envs/test_env.yaml index c9619296b..6566224c7 100644 --- a/devtools/conda-envs/test_env.yaml +++ b/devtools/conda-envs/test_env.yaml @@ -29,8 +29,9 @@ dependencies: # Testing - nose - #- pytest - #- pytest-cov + - nose-timer + - pytest + - pytest-cov - codecov # Pip-only installs From b1b361e26afb7eb4f87f046108aff490bb3f7c28 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Fri, 24 May 2019 00:21:42 -0400 Subject: [PATCH 016/152] Fix logsumexp import --- openmmtools/multistate/multistateanalyzer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/multistate/multistateanalyzer.py b/openmmtools/multistate/multistateanalyzer.py index 7a3a1e040..4b0e0b1a1 100644 --- a/openmmtools/multistate/multistateanalyzer.py +++ b/openmmtools/multistate/multistateanalyzer.py @@ -31,7 +31,7 @@ import numpy as np from simtk import openmm import simtk.unit as units -from scipy.misc import logsumexp +from scipy.special import logsumexp from pymbar import MBAR, timeseries from openmmtools import multistate, utils, forces From e206d1b6f264b1565e7efdb88d71d52e60f42e70 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Fri, 24 May 2019 00:24:25 -0400 Subject: [PATCH 017/152] Update changelog --- docs/releasehistory.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 96a573c89..83d10ffe0 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -9,7 +9,8 @@ New features Bugfixes -------- -- Update build infrasctructure to match `MolSSI cookiecutter `_. +- Update build infrastructure to match `MolSSI cookiecutter `_. +- A bug in the multistate samplers where``logsumexp`` was imported from ``scipy.misc`` (now in ``scipy.special``) was fixed 0.18.1 - Bugfix release ======================= From 8181bb53e9c558db3c76a30031eefea6de0f4d5c Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 29 May 2019 10:38:40 +0200 Subject: [PATCH 018/152] Update setup.py to use cookiecutter and versioneer --- setup.py | 199 +++++++++++++++---------------------------------------- 1 file changed, 52 insertions(+), 147 deletions(-) diff --git a/setup.py b/setup.py index aa6d60ef2..f5648c8f7 100644 --- a/setup.py +++ b/setup.py @@ -1,22 +1,32 @@ """ Various Python tools for OpenMM. """ -from __future__ import print_function -import sys import distutils.extension -from setuptools import setup -import os -from os.path import relpath, join -import subprocess from Cython.Build import cythonize -DOCLINES = __doc__.split("\n") +import sys +from setuptools import setup, find_packages +import versioneer + +short_description = __doc__.split("\n") + +# from https://github.com/pytest-dev/pytest-runner#conditional-requirement +needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv) +pytest_runner = ['pytest-runner'] if needs_pytest else [] + +try: + with open("README.md", "r") as handle: + long_description = handle.read() +except: + long_description = "\n".join(short_description[2:]), + +################################################################################ +# SETUP +################################################################################ + +extensions = distutils.extension.Extension("openmmtools.multistate.mixing._mix_replicas", + ['./openmmtools/multistate/mixing/_mix_replicas.pyx']) -######################## -VERSION = "0.19.0" -ISRELEASED = False -__version__ = VERSION -######################## CLASSIFIERS = """\ Development Status :: 3 - Alpha Intended Audience :: Science/Research @@ -32,151 +42,46 @@ Operating System :: MacOS """ -################################################################################ -# Writing version control information to the module -################################################################################ - -def git_version(): - # Return the git revision as a string - # copied from numpy setup.py - def _minimal_ext_cmd(cmd): - # construct minimal environment - env = {} - for k in ['SYSTEMROOT', 'PATH']: - v = os.environ.get(k) - if v is not None: - env[k] = v - # LANGUAGE is used on win32 - env['LANGUAGE'] = 'C' - env['LANG'] = 'C' - env['LC_ALL'] = 'C' - out = subprocess.Popen( - cmd, stdout=subprocess.PIPE, env=env).communicate()[0] - return out - - try: - out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) - GIT_REVISION = out.strip().decode('ascii') - except OSError: - GIT_REVISION = 'Unknown' - - return GIT_REVISION - - -def write_version_py(filename): - cnt = """ -# This file is automatically generated by setup.py -short_version = '%(version)s' -version = '%(version)s' -full_version = '%(full_version)s' -git_revision = '%(git_revision)s' -release = %(isrelease)s - -if not release: - version = full_version -""" - # Adding the git rev number needs to be done inside write_version_py(), - # otherwise the import of numpy.version messes up the build under Python 3. - FULLVERSION = VERSION - if os.path.exists('.git'): - GIT_REVISION = git_version() - else: - GIT_REVISION = 'Unknown' - - if not ISRELEASED: - FULLVERSION += '.dev-' + GIT_REVISION[:7] - - a = open(filename, 'w') - try: - contents = cnt % {'version': VERSION, - 'full_version': FULLVERSION, - 'git_revision': GIT_REVISION, - 'isrelease': str(ISRELEASED)} - a.write(contents) - print("Writing version.py to %s :" % os.path.abspath(filename)) - print('------------version.py-----------------') - print(contents) - print('---------------------------------------') - finally: - a.close() - -################################################################################ -# USEFUL SUBROUTINES -################################################################################ - -def find_package_data(data_root, package_root): - files = [] - for root, dirnames, filenames in os.walk(data_root): - for fn in filenames: - files.append(relpath(join(root, fn), package_root)) - return files - - -def check_dependencies(): - from distutils.version import StrictVersion - found_openmm = True - found_openmm_61_or_later = True - found_numpy = True - - try: - from simtk import openmm - openmm_version = StrictVersion(openmm.Platform.getOpenMMVersion()) - if openmm_version < StrictVersion('6.1.0'): - found_openmm_61_or_later = False - except ImportError as err: - found_openmm = False - - try: - import numpy - except: - found_numpy = False - - msg = None - bar = ('-' * 70) + "\n" + ('-' * 70) - if found_openmm: - if not found_openmm_61_or_later: - msg = [bar, '[Unmet Dependency] openmmtools requires OpenMM version 6.1 or later. You have version %s.' % openmm_version, bar] - else: - msg = [bar, '[Unmet Dependency] openmmtools requires the OpenMM python package. Refer to for details and installation instructions.', bar] - - if not found_numpy: - msg = [bar, '[Unmet Dependency] openmmtools requires the numpy python package. Refer to for numpy installation instructions.', bar] - - if msg is not None: - import textwrap - print() - print(os.linesep.join([line for e in msg for line in textwrap.wrap(e)]), file=sys.stderr) - #print('\n'.join(list(textwrap.wrap(e) for e in msg))) - -################################################################################ -# SETUP -################################################################################ - -extensions = distutils.extension.Extension("openmmtools.multistate.mixing._mix_replicas", - ['./openmmtools/multistate/mixing/_mix_replicas.pyx']) - -write_version_py('openmmtools/version.py') - setup( name='openmmtools', author='John Chodera', author_email='john.chodera@choderalab.org', - description=DOCLINES[0], - long_description="\n".join(DOCLINES[2:]), - version=__version__, + description=short_description, + long_description=long_description, + long_description_content_type="text/markdown", + version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), license='MIT', - url='https://github.com/choderalab/openmmtools', - platforms=['Linux', 'Mac OS-X', 'Unix', 'Windows'], + + # Which Python importable modules should be included when your package is installed + # Handled automatically by setuptools. Use 'exclude' to prevent some specific + # subpackage(s) from being added, if needed + packages=find_packages(), + + # Optional include package data to ship with your package + # Customize MANIFEST.in if the general case does not suit your needs + # Comment out this line to prevent the files from being packaged with your software + include_package_data=True, + + # Allows `setup.py test` to work correctly with pytest + setup_requires=[] + pytest_runner, + + # Additional entries you may want simply uncomment the lines you want and fill in the data + url='https://github.com/choderalab/openmmtools', # Website + # install_requires=[], # Required packages, pulls from pip if needed; do not use for Conda deployment + platforms=['Linux', + 'Mac OS-X', + 'Unix', + 'Windows'], # Valid platforms your code works on, adjust to your flavor classifiers=CLASSIFIERS.splitlines(), - packages=['openmmtools', 'openmmtools.tests', 'openmmtools.scripts', 'openmmtools.storage','openmmtools.multistate', 'openmmtools.multistate.mixing'], - package_dir={'openmmtools': 'openmmtools'}, - package_data={'openmmtools': find_package_data('openmmtools/data', 'openmmtools')}, + python_requires=">=3.6", # Python version restrictions + + # Manual control if final package is compressible or not, set False to prevent the .egg from being made zip_safe=False, - scripts=[], + ext_modules=cythonize(extensions), entry_points={'console_scripts': [ 'test-openmm-platforms = openmmtools.scripts.test_openmm_platforms:main', 'benchmark-alchemy = openmmtools.tests.test_alchemy:benchmark_alchemy_from_pdb', ]}, ) -check_dependencies() From 54dded24ff10563ed0fe7926972005ad533987ea Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 29 May 2019 10:39:48 +0200 Subject: [PATCH 019/152] Create _version.py --- openmmtools/_version.py | 520 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 520 insertions(+) create mode 100644 openmmtools/_version.py diff --git a/openmmtools/_version.py b/openmmtools/_version.py new file mode 100644 index 000000000..d9171440d --- /dev/null +++ b/openmmtools/_version.py @@ -0,0 +1,520 @@ + +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.18 (https://github.com/warner/python-versioneer) + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "$Format:%d$" + git_full = "$Format:%H$" + git_date = "$Format:%ci$" + keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "pep440" + cfg.tag_prefix = "" + cfg.parentdir_prefix = "None" + cfg.versionfile_source = "{{cookiecutter.repo_name}}/_version.py" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = p.communicate()[0].strip() + if sys.version_info[0] >= 3: + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs - tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], + cwd=root)[0].strip() + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Eexceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} From a4b62e4b6afacf2fb9e666498e90ef3e4210ce90 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 29 May 2019 10:43:43 +0200 Subject: [PATCH 020/152] Update releasehistory.rst --- docs/releasehistory.rst | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 83d10ffe0..a21e0d534 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -1,16 +1,16 @@ Release History *************** -0.19.0 -====== - -New features ------------- +0.18.2 - Bugfix release +======================= Bugfixes -------- -- Update build infrastructure to match `MolSSI cookiecutter `_. -- A bug in the multistate samplers where``logsumexp`` was imported from ``scipy.misc`` (now in ``scipy.special``) was fixed +- A bug in the multistate samplers where``logsumexp`` was imported from ``scipy.misc`` (now in ``scipy.special``) was fixed (`#423 `_). + +Other +----- +- Update build infrastructure to match `MolSSI cookiecutter `_ (`#424 `_, `#426 `_). 0.18.1 - Bugfix release ======================= From 030cc13bce3b8a6759fbb8f0a6d2b5fb9063e4c6 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 29 May 2019 11:26:40 +0200 Subject: [PATCH 021/152] Let versioneer set the version --- openmmtools/__init__.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/openmmtools/__init__.py b/openmmtools/__init__.py index 8511b4d2f..85e6e9dc6 100644 --- a/openmmtools/__init__.py +++ b/openmmtools/__init__.py @@ -5,8 +5,4 @@ """ -# Define global version. -from openmmtools import version -__version__ = version.version - from openmmtools import testsystems, integrators, alchemy, mcmc, states, cache, utils, constants, forces, forcefactories, storage, multistate From 1e14040341c38bda3d5c253644ba9534895a0a75 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 29 May 2019 11:30:43 +0200 Subject: [PATCH 022/152] Determine version in __init__ with versioneer --- openmmtools/__init__.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/openmmtools/__init__.py b/openmmtools/__init__.py index 85e6e9dc6..fb273c6da 100644 --- a/openmmtools/__init__.py +++ b/openmmtools/__init__.py @@ -6,3 +6,10 @@ """ from openmmtools import testsystems, integrators, alchemy, mcmc, states, cache, utils, constants, forces, forcefactories, storage, multistate + +# Handle versioneer +from ._version import get_versions +versions = get_versions() +__version__ = versions['version'] +__git_revision__ = versions['full-revisionid'] +del get_versions, versions From d827d20f5820f50ec835646c1ab61d7569f4cc12 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 29 May 2019 11:34:07 +0200 Subject: [PATCH 023/152] Use versioneer version when initializing netcdf --- openmmtools/multistate/multistatereporter.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/openmmtools/multistate/multistatereporter.py b/openmmtools/multistate/multistatereporter.py index 72cfb8000..f562610a1 100644 --- a/openmmtools/multistate/multistatereporter.py +++ b/openmmtools/multistate/multistatereporter.py @@ -46,7 +46,7 @@ from simtk import unit from openmmtools.utils import deserialize, with_timer, serialize, quantity_from_string -from openmmtools import version,states +from openmmtools import states logger = logging.getLogger(__name__) @@ -385,6 +385,8 @@ def _initialize_storage_file(self, ncfile, nc_name, convention): If the dataset has been initialized before, nothing happens. Return True if the file has been initialized before and False otherwise. """ + from openmmtools import versions + if 'scalar' not in ncfile.dimensions: # Create common dimensions. ncfile.createDimension('scalar', 1) # Scalar dimension. @@ -394,7 +396,7 @@ def _initialize_storage_file(self, ncfile, nc_name, convention): # Set global attributes. ncfile.application = 'YANK' ncfile.program = 'yank.py' - ncfile.programVersion = version.short_version + ncfile.programVersion = versions['version'] ncfile.Conventions = convention ncfile.ConventionVersion = '0.2' ncfile.DataUsedFor = nc_name From 727e6a5b19b444ee55135a972f71911567692657 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 29 May 2019 12:01:06 +0200 Subject: [PATCH 024/152] Fix version reference --- openmmtools/multistate/multistatereporter.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmmtools/multistate/multistatereporter.py b/openmmtools/multistate/multistatereporter.py index f562610a1..4f231c9c5 100644 --- a/openmmtools/multistate/multistatereporter.py +++ b/openmmtools/multistate/multistatereporter.py @@ -385,7 +385,7 @@ def _initialize_storage_file(self, ncfile, nc_name, convention): If the dataset has been initialized before, nothing happens. Return True if the file has been initialized before and False otherwise. """ - from openmmtools import versions + from openmmtools import __version__ if 'scalar' not in ncfile.dimensions: # Create common dimensions. @@ -396,7 +396,7 @@ def _initialize_storage_file(self, ncfile, nc_name, convention): # Set global attributes. ncfile.application = 'YANK' ncfile.program = 'yank.py' - ncfile.programVersion = versions['version'] + ncfile.programVersion = __version__ ncfile.Conventions = convention ncfile.ConventionVersion = '0.2' ncfile.DataUsedFor = nc_name From 53170a1c325868d2be872760c3aa2b07982c9ae2 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Thu, 30 May 2019 12:40:46 +0200 Subject: [PATCH 025/152] Fix error handling --- openmmtools/multistate/multistatereporter.py | 2 +- openmmtools/multistate/replicaexchange.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/openmmtools/multistate/multistatereporter.py b/openmmtools/multistate/multistatereporter.py index 4f231c9c5..d6109dcce 100644 --- a/openmmtools/multistate/multistatereporter.py +++ b/openmmtools/multistate/multistatereporter.py @@ -372,7 +372,7 @@ def _open_dataset_robustly(self, *args, n_attempts=5, sleep_time=2, raise e except: logger.debug('Attempt {}/{} to open {} failed. Retrying ' - 'in {} seconds'.format(i+1, n_attempts, sleep_time)) + 'in {} seconds'.format(attempt+1, n_attempts, sleep_time)) time.sleep(sleep_time) diff --git a/openmmtools/multistate/replicaexchange.py b/openmmtools/multistate/replicaexchange.py index e017ef3d9..7c846f00a 100644 --- a/openmmtools/multistate/replicaexchange.py +++ b/openmmtools/multistate/replicaexchange.py @@ -269,8 +269,8 @@ def _mix_replicas(self): # otherwise fall back to Python-accelerated code. try: self._mix_all_replicas_cython() - except ValueError as e: - logger.warning(e.message) + except (ValueError, ImportError) as e: + logger.warning(str(e)) self._mix_all_replicas() else: assert self.replica_mixing_scheme is None From 27c43ce5908e6cd1ccefd81e11ae60eda226f560 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Thu, 30 May 2019 12:41:54 +0200 Subject: [PATCH 026/152] Attempt setting env var HDF5_USE_FILE_LOCKING to false when opening netcdf file on failure --- openmmtools/multistate/multistatereporter.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/openmmtools/multistate/multistatereporter.py b/openmmtools/multistate/multistatereporter.py index d6109dcce..b1ee7d4af 100644 --- a/openmmtools/multistate/multistatereporter.py +++ b/openmmtools/multistate/multistatereporter.py @@ -375,6 +375,10 @@ def _open_dataset_robustly(self, *args, n_attempts=5, sleep_time=2, 'in {} seconds'.format(attempt+1, n_attempts, sleep_time)) time.sleep(sleep_time) + # At the very last attempt, we try setting the environment variable + # controlling the locking mechanism of HDF5 (see choderalab/yank#1165). + if n_attempts > 1: + os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE' # Last attempt finally raises any error. return netcdf.Dataset(*args, **kwargs) From 764290869a3fc2030da5e6d0b635d6c874704fba Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Thu, 30 May 2019 13:49:14 +0200 Subject: [PATCH 027/152] Update releasehistory.rst --- docs/releasehistory.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index a21e0d534..89abc4eb4 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -7,6 +7,8 @@ Release History Bugfixes -------- - A bug in the multistate samplers where``logsumexp`` was imported from ``scipy.misc`` (now in ``scipy.special``) was fixed (`#423 `_). +- Improve the robustness of opening the netcdf file on resuming of the multi-state samplers by setting the environment variable HDF5_USE_FILE_LOCKING to FALSE after 4 failed attempts (`#426 `_). +- Fixed a crash during exception handling (`#426 `_). Other ----- From 92e72b7c9c5228256063acd38a70c2c7f79a1cf5 Mon Sep 17 00:00:00 2001 From: Silveira Date: Thu, 30 May 2019 11:59:15 -0400 Subject: [PATCH 028/152] add round trips as criteria for changing sams stage --- openmmtools/multistate/sams.py | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 61c309a37..c9103354b 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -208,7 +208,7 @@ def __init__(self, ``two-stage`` will use a heuristic first stage to achieve flat histograms before switching to the asymptotically optimal scheme flatness_criteria : string, optional, default='histogram-flatness' Method of assessing when to switch to asymptotically optimal scheme - One of ['logZ-flatness','minimum-visits','histogram-flatness'] + One of ['minimum-logZ,'minimum-visits','histogram-flatness', 'histogram-flatness-round-trips'] flatness_threshold : float, optional, default=0.5 Histogram relative flatness threshold to use for first stage of two-stage scheme. minimum_visits : int, optional, default=100 @@ -238,6 +238,7 @@ def __init__(self, self.flatness_criteria = flatness_criteria self.flatness_threshold = flatness_threshold self.minimum_visits = minimum_visits + self.minimum_round_trips = minimum_round_trips self.weight_update_method = weight_update_method self.beta_factor = beta_factor self.adapt_target_probabilities = adapt_target_probabilities @@ -270,7 +271,7 @@ def _update_stages_validator(instance, scheme): @staticmethod def _flatness_criteria_validator(instance, scheme): - supported_schemes = ['minimum-visits', 'logZ-flatness', 'histogram-flatness'] + supported_schemes = ['minimum-visits', 'minimum-logZ', 'histogram-flatness', 'histogram-flatness-round-trips'] if scheme not in supported_schemes: raise ValueError("Unknown update scheme '{}'. Supported values " "are {}.".format(scheme, supported_schemes)) @@ -300,6 +301,7 @@ def _adapt_target_probabilities_validator(instance, scheme): flatness_criteria = _StoredProperty('flatness_criteria', validate_function=_StoredProperty._flatness_criteria_validator) flatness_threshold = _StoredProperty('flatness_threshold', validate_function=None) minimum_visits = _StoredProperty('minimum_visits', validate_function=None) + minimum_round_trips = _StoredProperty('minimum_round_trips', validate_function=None) weight_update_method = _StoredProperty('weight_update_method', validate_function=_StoredProperty._weight_update_method_validator) beta_factor = _StoredProperty('beta_factor', validate_function=None) adapt_target_probabilities = _StoredProperty('adapt_target_probabilities', validate_function=_StoredProperty._adapt_target_probabilities_validator) @@ -307,6 +309,8 @@ def _adapt_target_probabilities_validator(instance, scheme): logZ_guess = _StoredProperty('logZ_guess', validate_function=None) def _initialize_stage(self): + self.round_trips = 0 + self._downhill = False self._t0 = 0 # reference iteration to subtract if self.update_stages == 'one-stage': self._stage = 1 # start with asymptotically-optimal stage @@ -385,11 +389,12 @@ def _restore_sampler_from_reporter(self, reporter): super()._restore_sampler_from_reporter(reporter) self._cached_state_histogram = self._compute_state_histogram(reporter=reporter) logger.debug('Restored state histogram: {}'.format(self._cached_state_histogram)) - data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'stage', 't0') + data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'stage', 't0', 'round_trips', 'downhill') self._logZ = data['logZ'] self._stage = int(data['stage'][0]) self._t0 = int(data['t0'][0]) - + self.round_trips = int(data['round_trips'][0]) + self._downhill = bool(int(data['downhill'][0])) # Compute log weights from log target probability and logZ estimate self._update_log_weights() if (self.weight_update): @@ -401,7 +406,8 @@ def _restore_sampler_from_reporter(self, reporter): def _report_iteration_items(self): super(SAMSSampler, self)._report_iteration_items() - self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, stage=self._stage, t0=self._t0) + self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, stage=self._stage, + t0=self._t0, round_trips=self.round_trips, downhill=int(self._downhill)) # Split into which states and how many samplers are in each state # Trying to do histogram[replica_thermo_states] += 1 does not correctly handle multiple # replicas in the same state. @@ -434,6 +440,14 @@ def _mix_replicas(self): else: raise Exception('Programming error: Unreachable code') + n_replica, n_states = self.n_replicas, self.n_states + for replica_index, current_state_index in enumerate(self._replica_thermodynamic_states): + if (current_state_index == self.n_states-1): + self._downhill = True + if (current_state_index == 0) and (self._downhill == True): + self.round_trips += 1 + self._downhill = False + # Determine fraction of swaps accepted this iteration. n_swaps_proposed = self._n_proposed_matrix.sum() n_swaps_accepted = self._n_accepted_matrix.sum() @@ -596,14 +610,17 @@ def _update_stage(self): # Advance if every state has been visited at least once if np.all(N_k >= self.minimum_visits): advance = True - elif self.flatness_criteria == 'histogram-flatness': + elif (self.flatness_criteria == 'histogram-flatness-round-trips') or (self.flatness_criteria == 'histogram-flatness'): # Check histogram flatness empirical_pi_k = N_k[:] / N_k.sum() pi_k = np.exp(self.log_target_probabilities) relative_error_k = np.abs(pi_k - empirical_pi_k) / pi_k if np.all(relative_error_k < self.flatness_threshold): - advance = True - elif self.flatness_criteria == 'logZ-flatness': + if (self.flatness_criteria == 'histogram-flatness-round-trips') and (self.round_trips >= self.minimum_round_trips): + advance = True + else: + advance = True + elif self.flatness_criteria == 'minimum-logZ': # TODO: Advance to asymptotically optimal scheme when logZ update fractional counts per state exceed threshold # for all states. criteria = abs(self._logZ / self.gamma0) > self.flatness_threshold From c77bbf346e949d7433143c81eb829929a97bff55 Mon Sep 17 00:00:00 2001 From: Silveira Date: Thu, 30 May 2019 15:47:02 -0400 Subject: [PATCH 029/152] sams accepts multiple criteria for switching stages --- docs/releasehistory.rst | 5 ++ openmmtools/multistate/sams.py | 128 ++++++++++++++++----------------- 2 files changed, 67 insertions(+), 66 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index e6fc2958b..8b21400b9 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -7,6 +7,11 @@ Release History New features ------------ +Enhancements +------------ +- ``SAMSSampler`` supports expanded ensemble simulations +- ``SAMSSampler`` accepts multiple criteria for switching the stage + Bugfixes -------- diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index c9103354b..de84db6df 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -104,11 +104,10 @@ class SAMSSampler(multistate.MultiStateSampler): >>> move = mcmc.GHMCMove(timestep=2.0*unit.femtoseconds, n_steps=50) >>> simulation = SAMSSampler(mcmc_moves=move, number_of_iterations=2, ... state_update_scheme='global-jump', locality=5, - ... update_stages='two-stage', flatness_criteria='histogram-flatness', - ... flatness_threshold=0.5, weight_update_method='rao-blackwellized', + ... update_stages='two-stage', flatness=0.5, + ... weight_update_method='rao-blackwellized', ... adapt_target_probabilities=False) - Create a single-replica SAMS simulation bound to a storage file and run: >>> storage_path = tempfile.NamedTemporaryFile(delete=False).name + '.nc' @@ -174,11 +173,12 @@ def __init__(self, state_update_scheme='global-jump', locality=5, weight_update=True, - update_stages='two-stage', - flatness_criteria='histogram-flatness', - flatness_threshold=0.5, - minimum_visits=100, weight_update_method='rao-blackwellized', + update_stages='two-stage', + flatness = None, + minimum_visits = None, + round_trips = None, + minimum_logZ = None, beta_factor=0.8, adapt_target_probabilities=False, gamma0=1.0, @@ -202,21 +202,22 @@ def __init__(self, Number of neighboring states on either side to consider for local update schemes. weight_update : bool, optional, default=True If False, weights updating is disabled. This allows to perform expanded ensemble simulations. - update_stages : str, optional, default='two-stage' - One of ['one-stage', 'two-stage'] - ``one-stage`` will use the asymptotically optimal scheme throughout the entire simulation (not recommended due to slow convergence) - ``two-stage`` will use a heuristic first stage to achieve flat histograms before switching to the asymptotically optimal scheme - flatness_criteria : string, optional, default='histogram-flatness' - Method of assessing when to switch to asymptotically optimal scheme - One of ['minimum-logZ,'minimum-visits','histogram-flatness', 'histogram-flatness-round-trips'] - flatness_threshold : float, optional, default=0.5 - Histogram relative flatness threshold to use for first stage of two-stage scheme. - minimum_visits : int, optional, default=100 - Mininum number of visits in each state to use for first stage of two-stage scheme. weight_update_method : str, optional, default='rao-blackwellized' Method to use for updating log weights in SAMS. One of ['optimal', 'rao-blackwellized'] ``rao-blackwellized`` will update log free energy estimate for all states for which energies were computed ``optimal`` will use integral counts to update log free energy estimate of current state only + update_stages : str, optional, default='two-stage' + One of ['one-stage', 'two-stage'] + ``one-stage`` will use the asymptotically optimal scheme throughout the entire simulation (not recommended due to slow convergence) + ``two-stage`` will use a heuristic first stage to achieve flat histograms before switching to the asymptotically optimal scheme + flatness: float, default=None + Histogram relative flatness threshold to use in first stage of two-stage scheme. + round_trips : int, default=None + Mininum number of round trips to use in first stage of two-stage scheme. + minimum_visits : int, default=None + Mininum number of visits in each state to use in first stage of two-stage scheme. + minimum_logZ : float, default=None + Mininum logZ value to use in first stage of two-stage scheme. beta_factor : float, optional, default=0.8 Exponent for tunning the decaying rate of the gain factor. adapt_target_probabilities : bool, optional, default=False @@ -235,10 +236,6 @@ def __init__(self, self.locality = locality self.weight_update = weight_update self.update_stages = update_stages - self.flatness_criteria = flatness_criteria - self.flatness_threshold = flatness_threshold - self.minimum_visits = minimum_visits - self.minimum_round_trips = minimum_round_trips self.weight_update_method = weight_update_method self.beta_factor = beta_factor self.adapt_target_probabilities = adapt_target_probabilities @@ -248,7 +245,12 @@ def __init__(self, # self._replica_neighbors[replica_index] is a list of states that form the neighborhood of ``replica_index`` self._replica_neighbors = None self._cached_state_histogram = None - + self.criteria = { criteria: value for criteria, value in (('flatness', flatness), ('round_trips', round_trips), + ('minimum_logZ', minimum_logZ), ('minimum_visits', minimum_visits)) + if value is not None} + self.advance = {criteria: False for criteria, value in self.criteria.items() if value is not None} + if self.self.update_stages = 'two-stage' and not bool(self.criteria)): + raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: flatness, round_trips, minimum_logZ and minimum_visits') class _StoredProperty(multistate.MultiStateSampler._StoredProperty): @@ -270,12 +272,13 @@ def _update_stages_validator(instance, scheme): return scheme @staticmethod - def _flatness_criteria_validator(instance, scheme): - supported_schemes = ['minimum-visits', 'minimum-logZ', 'histogram-flatness', 'histogram-flatness-round-trips'] - if scheme not in supported_schemes: - raise ValueError("Unknown update scheme '{}'. Supported values " - "are {}.".format(scheme, supported_schemes)) - return scheme + def _criteria_validator(instance, **kwargs): + supported_scheme = ['flatness', 'round_trips', 'minimum_visits', 'minimum_logZ'] + for s,v in kwargs.items(): + if s not in supported_scheme: + raise ValueError("Unknown criteria '{}'. Supported values " + "are {}.".format(s, supported_schemes)) + return kwargs @staticmethod def _weight_update_method_validator(instance, scheme): @@ -298,10 +301,8 @@ def _adapt_target_probabilities_validator(instance, scheme): locality = _StoredProperty('locality', validate_function=None) weight_update = _StoredProperty('weight_update', validate_function=None) update_stages = _StoredProperty('update_stages', validate_function=_StoredProperty._update_stages_validator) - flatness_criteria = _StoredProperty('flatness_criteria', validate_function=_StoredProperty._flatness_criteria_validator) - flatness_threshold = _StoredProperty('flatness_threshold', validate_function=None) - minimum_visits = _StoredProperty('minimum_visits', validate_function=None) - minimum_round_trips = _StoredProperty('minimum_round_trips', validate_function=None) + if self.update_stages == 'two-stage': + criteria = _StoredProperty('criteria', validate_function=_StoredProperty._criteria_validator) weight_update_method = _StoredProperty('weight_update_method', validate_function=_StoredProperty._weight_update_method_validator) beta_factor = _StoredProperty('beta_factor', validate_function=None) adapt_target_probabilities = _StoredProperty('adapt_target_probabilities', validate_function=_StoredProperty._adapt_target_probabilities_validator) @@ -442,11 +443,12 @@ def _mix_replicas(self): n_replica, n_states = self.n_replicas, self.n_states for replica_index, current_state_index in enumerate(self._replica_thermodynamic_states): - if (current_state_index == self.n_states-1): + if self._downhill: + if current_state_index == 0: + self.round_trips += 1 + self._downhill = False + elif current_state_index == self.n_states-1: self._downhill = True - if (current_state_index == 0) and (self._downhill == True): - self.round_trips += 1 - self._downhill = False # Determine fraction of swaps accepted this iteration. n_swaps_proposed = self._n_proposed_matrix.sum() @@ -601,39 +603,33 @@ def _update_stage(self): N_k = self._state_histogram logger.debug(' state histogram counts ({} total): {}'.format(self._cached_state_histogram.sum(), self._cached_state_histogram)) if (self.update_stages == 'two-stage') and (self._stage == 0): - advance = False if N_k.sum() == 0: # No samples yet; don't do anything. return - - if self.flatness_criteria == 'minimum-visits': - # Advance if every state has been visited at least once - if np.all(N_k >= self.minimum_visits): - advance = True - elif (self.flatness_criteria == 'histogram-flatness-round-trips') or (self.flatness_criteria == 'histogram-flatness'): - # Check histogram flatness - empirical_pi_k = N_k[:] / N_k.sum() - pi_k = np.exp(self.log_target_probabilities) - relative_error_k = np.abs(pi_k - empirical_pi_k) / pi_k - if np.all(relative_error_k < self.flatness_threshold): - if (self.flatness_criteria == 'histogram-flatness-round-trips') and (self.round_trips >= self.minimum_round_trips): - advance = True - else: - advance = True - elif self.flatness_criteria == 'minimum-logZ': - # TODO: Advance to asymptotically optimal scheme when logZ update fractional counts per state exceed threshold - # for all states. - criteria = abs(self._logZ / self.gamma0) > self.flatness_threshold - logger.debug('logZ-flatness criteria met (%d total): %s' % (np.sum(criteria), str(np.array(criteria, 'i1')))) - if np.all(criteria): - advance = True - else: - raise ValueError("Unknown flatness_criteria %s" % flatness_criteria) - - if advance or ((self._t0 > 0) and (self._iteration > self._t0)): - # Histograms are sufficiently flat; switch to asymptotically optimal scheme + for criteria,value in self.criteria.items(): + if criteria == 'flatness': + # Check histogram flatness + empirical_pi_k = N_k[:] / N_k.sum() + pi_k = np.exp(self.log_target_probabilities) + relative_error_k = np.abs(pi_k - empirical_pi_k) / pi_k + if np.all(relative_error_k < value): + self.advance['flatness'] = True + elif criteria == 'round_trips' and self.round_trips >= value: + # Check number of round_trips + self.advance['round_trips'] = True + elif criteria == 'minimum_visits' and np.all(N_k >= value): + # Check number of visits + self.advance['mimimum_visits'] = True + elif criteria == 'minimum_logZ': + # Check logZ values + criteria = np.abs(self._logZ / self.gamma0) > value + logger.debug('minimum_logZ criteria met (%d total): %s' % (np.sum(criteria), str(np.array(criteria, 'i1')))) + if np.all(criteria): + self.advance['minimum_logZ'] = True + + if np.all(self.advance.values()) or ((self._t0 > 0) and (self._iteration > self._t0)): + # switch to asymptotically optimal scheme self._stage = 1 # asymptotically optimal - # TODO: On resuming, we need to recompute or restore t0, or use some other way to compute it self._t0 = self._iteration - 1 def _update_logZ_estimates(self, replicas_log_P_k): From 093a3614f1701d51236381d36ed05e23c230d51d Mon Sep 17 00:00:00 2001 From: Silveira Date: Thu, 30 May 2019 16:04:48 -0400 Subject: [PATCH 030/152] fix bug --- openmmtools/multistate/sams.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index de84db6df..d49e8445b 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -249,7 +249,7 @@ def __init__(self, ('minimum_logZ', minimum_logZ), ('minimum_visits', minimum_visits)) if value is not None} self.advance = {criteria: False for criteria, value in self.criteria.items() if value is not None} - if self.self.update_stages = 'two-stage' and not bool(self.criteria)): + if (self.update_stages == 'two-stage') and not bool(self.criteria)): raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: flatness, round_trips, minimum_logZ and minimum_visits') class _StoredProperty(multistate.MultiStateSampler._StoredProperty): From 4ab5fdd1ca0687a2422e492298d6950dccc71b84 Mon Sep 17 00:00:00 2001 From: Silveira Date: Thu, 30 May 2019 16:06:30 -0400 Subject: [PATCH 031/152] fix error --- openmmtools/multistate/sams.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index d49e8445b..5084c4ac7 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -249,7 +249,7 @@ def __init__(self, ('minimum_logZ', minimum_logZ), ('minimum_visits', minimum_visits)) if value is not None} self.advance = {criteria: False for criteria, value in self.criteria.items() if value is not None} - if (self.update_stages == 'two-stage') and not bool(self.criteria)): + if (self.update_stages == 'two-stage') and not bool(self.criteria): raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: flatness, round_trips, minimum_logZ and minimum_visits') class _StoredProperty(multistate.MultiStateSampler._StoredProperty): From c729b7314983c85062add19c38950f6aee6e867e Mon Sep 17 00:00:00 2001 From: Ana Silveira Date: Fri, 31 May 2019 15:59:30 -0400 Subject: [PATCH 032/152] first revised version --- openmmtools/multistate/sams.py | 81 ++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 38 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 5084c4ac7..1a1a8e4ea 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -175,9 +175,9 @@ def __init__(self, weight_update=True, weight_update_method='rao-blackwellized', update_stages='two-stage', - flatness = None, + histogram_flatness = None, minimum_visits = None, - round_trips = None, + minimum_round_trips = None, minimum_logZ = None, beta_factor=0.8, adapt_target_probabilities=False, @@ -210,14 +210,14 @@ def __init__(self, One of ['one-stage', 'two-stage'] ``one-stage`` will use the asymptotically optimal scheme throughout the entire simulation (not recommended due to slow convergence) ``two-stage`` will use a heuristic first stage to achieve flat histograms before switching to the asymptotically optimal scheme - flatness: float, default=None + histogram_flatness: float, default=None Histogram relative flatness threshold to use in first stage of two-stage scheme. - round_trips : int, default=None - Mininum number of round trips to use in first stage of two-stage scheme. + minimum_round_trips : int, default=None + Minimum number of round trips to use in first stage of two-stage scheme. minimum_visits : int, default=None - Mininum number of visits in each state to use in first stage of two-stage scheme. + Minimum number of visits in each state to use in first stage of two-stage scheme. minimum_logZ : float, default=None - Mininum logZ value to use in first stage of two-stage scheme. + Minimum logZ value to use in first stage of two-stage scheme. beta_factor : float, optional, default=0.8 Exponent for tunning the decaying rate of the gain factor. adapt_target_probabilities : bool, optional, default=False @@ -237,6 +237,10 @@ def __init__(self, self.weight_update = weight_update self.update_stages = update_stages self.weight_update_method = weight_update_method + self.histogram_flatness = histogram_flatness + self.minimum_round_trips = minimum_round_trips + self.minimum_visits = minimum_visits + self.minimum_logZ = minimum_logZ self.beta_factor = beta_factor self.adapt_target_probabilities = adapt_target_probabilities self.gamma0 = gamma0 @@ -245,12 +249,17 @@ def __init__(self, # self._replica_neighbors[replica_index] is a list of states that form the neighborhood of ``replica_index`` self._replica_neighbors = None self._cached_state_histogram = None - self.criteria = { criteria: value for criteria, value in (('flatness', flatness), ('round_trips', round_trips), - ('minimum_logZ', minimum_logZ), ('minimum_visits', minimum_visits)) - if value is not None} - self.advance = {criteria: False for criteria, value in self.criteria.items() if value is not None} - if (self.update_stages == 'two-stage') and not bool(self.criteria): - raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: flatness, round_trips, minimum_logZ and minimum_visits') + self._advance = {criteria: False for criteria, value in self._criteria.items() if value is not None} + if (self.update_stages == 'two-stage') and not bool(self._criteria): + raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: histogram_flatness, minimum_round_trips, minimum_logZ and minimum_visits') + + @property + def _criteria(self): + return { criteria: value for criteria, value in (('histogram_flatness', self.histogram_flatness), + ('minimum_round_trips', self.minimum_round_trips), + ('minimum_logZ', self.minimum_logZ), + ('minimum_visits', self.minimum_visits)) + if value is not None} class _StoredProperty(multistate.MultiStateSampler._StoredProperty): @@ -271,15 +280,6 @@ def _update_stages_validator(instance, scheme): "are {}.".format(scheme, supported_schemes)) return scheme - @staticmethod - def _criteria_validator(instance, **kwargs): - supported_scheme = ['flatness', 'round_trips', 'minimum_visits', 'minimum_logZ'] - for s,v in kwargs.items(): - if s not in supported_scheme: - raise ValueError("Unknown criteria '{}'. Supported values " - "are {}.".format(s, supported_schemes)) - return kwargs - @staticmethod def _weight_update_method_validator(instance, scheme): supported_schemes = ['optimal', 'rao-blackwellized'] @@ -301,16 +301,22 @@ def _adapt_target_probabilities_validator(instance, scheme): locality = _StoredProperty('locality', validate_function=None) weight_update = _StoredProperty('weight_update', validate_function=None) update_stages = _StoredProperty('update_stages', validate_function=_StoredProperty._update_stages_validator) - if self.update_stages == 'two-stage': - criteria = _StoredProperty('criteria', validate_function=_StoredProperty._criteria_validator) weight_update_method = _StoredProperty('weight_update_method', validate_function=_StoredProperty._weight_update_method_validator) + histogram_flatness = _StoredProperty('histogram_flatness', validate_function=None) + minimum_round_trips = _StoredProperty('minimum_round_trips', validate_function=None) + minimum_visits = _StoredProperty('minimum_visits', validate_function=None) + minimum_logZ = _StoredProperty('minimum_logZ', validate_function=None) beta_factor = _StoredProperty('beta_factor', validate_function=None) adapt_target_probabilities = _StoredProperty('adapt_target_probabilities', validate_function=_StoredProperty._adapt_target_probabilities_validator) gamma0 = _StoredProperty('gamma0', validate_function=None) logZ_guess = _StoredProperty('logZ_guess', validate_function=None) def _initialize_stage(self): - self.round_trips = 0 + + self._round_trips = 0 + # The variable _downhill keeps track of which end state the walker has visited more recently. + # This is used for computing the number of round trips. + # _downhill = False: the walker is going uphill because it has visited the intial state more recently than the final state self._downhill = False self._t0 = 0 # reference iteration to subtract if self.update_stages == 'one-stage': @@ -394,7 +400,7 @@ def _restore_sampler_from_reporter(self, reporter): self._logZ = data['logZ'] self._stage = int(data['stage'][0]) self._t0 = int(data['t0'][0]) - self.round_trips = int(data['round_trips'][0]) + self._round_trips = int(data['round_trips'][0]) self._downhill = bool(int(data['downhill'][0])) # Compute log weights from log target probability and logZ estimate self._update_log_weights() @@ -408,7 +414,7 @@ def _report_iteration_items(self): super(SAMSSampler, self)._report_iteration_items() self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, stage=self._stage, - t0=self._t0, round_trips=self.round_trips, downhill=int(self._downhill)) + t0=self._t0, round_trips=self._round_trips, downhill=int(self._downhill)) # Split into which states and how many samplers are in each state # Trying to do histogram[replica_thermo_states] += 1 does not correctly handle multiple # replicas in the same state. @@ -441,11 +447,10 @@ def _mix_replicas(self): else: raise Exception('Programming error: Unreachable code') - n_replica, n_states = self.n_replicas, self.n_states for replica_index, current_state_index in enumerate(self._replica_thermodynamic_states): if self._downhill: if current_state_index == 0: - self.round_trips += 1 + self._round_trips += 1 self._downhill = False elif current_state_index == self.n_states-1: self._downhill = True @@ -599,35 +604,35 @@ def _update_stage(self): Determine which adaptation stage we're in by checking histogram flatness. """ - + logger.debug('stage is {}'.format(self._stage)) N_k = self._state_histogram logger.debug(' state histogram counts ({} total): {}'.format(self._cached_state_histogram.sum(), self._cached_state_histogram)) if (self.update_stages == 'two-stage') and (self._stage == 0): if N_k.sum() == 0: # No samples yet; don't do anything. return - for criteria,value in self.criteria.items(): - if criteria == 'flatness': + for criteria,value in self._criteria.items(): + if criteria == 'histogram_flatness': # Check histogram flatness empirical_pi_k = N_k[:] / N_k.sum() pi_k = np.exp(self.log_target_probabilities) relative_error_k = np.abs(pi_k - empirical_pi_k) / pi_k if np.all(relative_error_k < value): - self.advance['flatness'] = True - elif criteria == 'round_trips' and self.round_trips >= value: + self._advance['histogram_flatness'] = True + elif criteria == 'minimum_round_trips' and self._round_trips >= value: # Check number of round_trips - self.advance['round_trips'] = True + self._advance['minimum_round_trips'] = True elif criteria == 'minimum_visits' and np.all(N_k >= value): # Check number of visits - self.advance['mimimum_visits'] = True + self._advance['mimimum_visits'] = True elif criteria == 'minimum_logZ': # Check logZ values criteria = np.abs(self._logZ / self.gamma0) > value logger.debug('minimum_logZ criteria met (%d total): %s' % (np.sum(criteria), str(np.array(criteria, 'i1')))) if np.all(criteria): - self.advance['minimum_logZ'] = True + self._advance['minimum_logZ'] = True - if np.all(self.advance.values()) or ((self._t0 > 0) and (self._iteration > self._t0)): + if all(v == True for v in self._advance.values()) or ((self._t0 > 0) and (self._iteration > self._t0)): # switch to asymptotically optimal scheme self._stage = 1 # asymptotically optimal self._t0 = self._iteration - 1 From f8318c1d5e078d56c48c685c78f61d5836c3d879 Mon Sep 17 00:00:00 2001 From: Ana Silveira Date: Fri, 31 May 2019 16:16:49 -0400 Subject: [PATCH 033/152] fix in error statement --- openmmtools/multistate/sams.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 1a1a8e4ea..d838b07c6 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -250,7 +250,7 @@ def __init__(self, self._replica_neighbors = None self._cached_state_histogram = None self._advance = {criteria: False for criteria, value in self._criteria.items() if value is not None} - if (self.update_stages == 'two-stage') and not bool(self._criteria): + if self.weight_update and (self.update_stages == 'two-stage') and not bool(self._criteria): raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: histogram_flatness, minimum_round_trips, minimum_logZ and minimum_visits') @property @@ -404,7 +404,7 @@ def _restore_sampler_from_reporter(self, reporter): self._downhill = bool(int(data['downhill'][0])) # Compute log weights from log target probability and logZ estimate self._update_log_weights() - if (self.weight_update): + if self.weight_update: # Determine t0 self._update_stage() @@ -464,7 +464,7 @@ def _mix_replicas(self): swap_fraction_accepted = float(n_swaps_accepted) / n_swaps_proposed logger.debug("Accepted {}/{} attempted swaps ({:.1f}%)".format(n_swaps_accepted, n_swaps_proposed, swap_fraction_accepted * 100.0)) - if (self.weight_update): + if self.weight_update: # Update logZ estimates self._update_logZ_estimates(replicas_log_P_k) From 4d2c17668cf758ed441e3fe80e6f94a72c2dfdcf Mon Sep 17 00:00:00 2001 From: Silveira Date: Sat, 1 Jun 2019 19:16:49 -0400 Subject: [PATCH 034/152] delete debug statement --- openmmtools/multistate/sams.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index d838b07c6..cdc8a1413 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -104,7 +104,7 @@ class SAMSSampler(multistate.MultiStateSampler): >>> move = mcmc.GHMCMove(timestep=2.0*unit.femtoseconds, n_steps=50) >>> simulation = SAMSSampler(mcmc_moves=move, number_of_iterations=2, ... state_update_scheme='global-jump', locality=5, - ... update_stages='two-stage', flatness=0.5, + ... update_stages='two-stage', histogram_flatness=0.5, ... weight_update_method='rao-blackwellized', ... adapt_target_probabilities=False) @@ -604,7 +604,6 @@ def _update_stage(self): Determine which adaptation stage we're in by checking histogram flatness. """ - logger.debug('stage is {}'.format(self._stage)) N_k = self._state_histogram logger.debug(' state histogram counts ({} total): {}'.format(self._cached_state_histogram.sum(), self._cached_state_histogram)) if (self.update_stages == 'two-stage') and (self._stage == 0): From 250da6887bfe340177c738c158e57095f9caa468 Mon Sep 17 00:00:00 2001 From: Ana Silveira Date: Thu, 6 Jun 2019 13:11:16 -0400 Subject: [PATCH 035/152] add histogram flatness as default criteria fix if statement --- openmmtools/multistate/sams.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index cdc8a1413..39f314c72 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -175,7 +175,7 @@ def __init__(self, weight_update=True, weight_update_method='rao-blackwellized', update_stages='two-stage', - histogram_flatness = None, + histogram_flatness = 0.3, minimum_visits = None, minimum_round_trips = None, minimum_logZ = None, @@ -210,7 +210,7 @@ def __init__(self, One of ['one-stage', 'two-stage'] ``one-stage`` will use the asymptotically optimal scheme throughout the entire simulation (not recommended due to slow convergence) ``two-stage`` will use a heuristic first stage to achieve flat histograms before switching to the asymptotically optimal scheme - histogram_flatness: float, default=None + histogram_flatness: float, default=0.3 Histogram relative flatness threshold to use in first stage of two-stage scheme. minimum_round_trips : int, default=None Minimum number of round trips to use in first stage of two-stage scheme. @@ -249,9 +249,6 @@ def __init__(self, # self._replica_neighbors[replica_index] is a list of states that form the neighborhood of ``replica_index`` self._replica_neighbors = None self._cached_state_histogram = None - self._advance = {criteria: False for criteria, value in self._criteria.items() if value is not None} - if self.weight_update and (self.update_stages == 'two-stage') and not bool(self._criteria): - raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: histogram_flatness, minimum_round_trips, minimum_logZ and minimum_visits') @property def _criteria(self): @@ -260,6 +257,9 @@ def _criteria(self): ('minimum_logZ', self.minimum_logZ), ('minimum_visits', self.minimum_visits)) if value is not None} + @property + def _advance(self): + return {criteria: False for criteria, value in self._criteria.items() if value is not None} class _StoredProperty(multistate.MultiStateSampler._StoredProperty): @@ -312,6 +312,8 @@ def _adapt_target_probabilities_validator(instance, scheme): logZ_guess = _StoredProperty('logZ_guess', validate_function=None) def _initialize_stage(self): + if self.weight_update and (self.update_stages == 'two-stage') and not bool(self._criteria): + raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: histogram_flatness, minimum_round_trips, minimum_visits, minimum_logZ') self._round_trips = 0 # The variable _downhill keeps track of which end state the walker has visited more recently. @@ -396,12 +398,12 @@ def _restore_sampler_from_reporter(self, reporter): super()._restore_sampler_from_reporter(reporter) self._cached_state_histogram = self._compute_state_histogram(reporter=reporter) logger.debug('Restored state histogram: {}'.format(self._cached_state_histogram)) - data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'stage', 't0', 'round_trips', 'downhill') + data = reporter.read_online_analysis_data(self._iteration, 'logZ', 'round_trips', 'downhill', 't0', 'stage') self._logZ = data['logZ'] - self._stage = int(data['stage'][0]) - self._t0 = int(data['t0'][0]) self._round_trips = int(data['round_trips'][0]) self._downhill = bool(int(data['downhill'][0])) + self._stage = int(data['stage'][0]) + self._t0 = int(data['t0'][0]) # Compute log weights from log target probability and logZ estimate self._update_log_weights() if self.weight_update: @@ -413,8 +415,8 @@ def _restore_sampler_from_reporter(self, reporter): def _report_iteration_items(self): super(SAMSSampler, self)._report_iteration_items() - self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, stage=self._stage, - t0=self._t0, round_trips=self._round_trips, downhill=int(self._downhill)) + self._reporter.write_online_data_dynamic_and_static(self._iteration, logZ=self._logZ, + round_trips=self._round_trips, downhill=int(self._downhill), t0=self._t0, stage=self._stage) # Split into which states and how many samplers are in each state # Trying to do histogram[replica_thermo_states] += 1 does not correctly handle multiple # replicas in the same state. @@ -631,7 +633,7 @@ def _update_stage(self): if np.all(criteria): self._advance['minimum_logZ'] = True - if all(v == True for v in self._advance.values()) or ((self._t0 > 0) and (self._iteration > self._t0)): + if (bool(self._advance) and all(v == True for v in self._advance.values())) or ((self._t0 > 0) and (self._iteration > self._t0)): # switch to asymptotically optimal scheme self._stage = 1 # asymptotically optimal self._t0 = self._iteration - 1 From 38f5eabe4988e3113cef6a6cfa5c7dc74f60ed99 Mon Sep 17 00:00:00 2001 From: Ana Silveira Date: Fri, 7 Jun 2019 12:20:29 -0400 Subject: [PATCH 036/152] fix bug in the advance dict --- docs/releasehistory.rst | 7 +++++-- openmmtools/multistate/sams.py | 18 +++++++----------- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index a80f2cb1c..43006507d 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -1,14 +1,17 @@ Release History *************** -0.18.2 - Bugfix release -======================= +0.19.0 +====================== Enhancements ------------ - ``SAMSSampler`` supports expanded ensemble simulations - ``SAMSSampler`` accepts multiple criteria for switching the stage +0.18.2 - Bugfix release +======================= + Bugfixes -------- - A bug in the multistate samplers where``logsumexp`` was imported from ``scipy.misc`` (now in ``scipy.special``) was fixed (`#423 `_). diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 39f314c72..6378e3c14 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -257,9 +257,6 @@ def _criteria(self): ('minimum_logZ', self.minimum_logZ), ('minimum_visits', self.minimum_visits)) if value is not None} - @property - def _advance(self): - return {criteria: False for criteria, value in self._criteria.items() if value is not None} class _StoredProperty(multistate.MultiStateSampler._StoredProperty): @@ -312,9 +309,7 @@ def _adapt_target_probabilities_validator(instance, scheme): logZ_guess = _StoredProperty('logZ_guess', validate_function=None) def _initialize_stage(self): - if self.weight_update and (self.update_stages == 'two-stage') and not bool(self._criteria): - raise Exception('One or multiple criteria for switching stages must be specified. Supported criteria are: histogram_flatness, minimum_round_trips, minimum_visits, minimum_logZ') - + self._round_trips = 0 # The variable _downhill keeps track of which end state the walker has visited more recently. # This is used for computing the number of round trips. @@ -606,6 +601,7 @@ def _update_stage(self): Determine which adaptation stage we're in by checking histogram flatness. """ + advance = {criteria: False for criteria, value in self._criteria.items() if value is not None} N_k = self._state_histogram logger.debug(' state histogram counts ({} total): {}'.format(self._cached_state_histogram.sum(), self._cached_state_histogram)) if (self.update_stages == 'two-stage') and (self._stage == 0): @@ -619,21 +615,21 @@ def _update_stage(self): pi_k = np.exp(self.log_target_probabilities) relative_error_k = np.abs(pi_k - empirical_pi_k) / pi_k if np.all(relative_error_k < value): - self._advance['histogram_flatness'] = True + advance['histogram_flatness'] = True elif criteria == 'minimum_round_trips' and self._round_trips >= value: # Check number of round_trips - self._advance['minimum_round_trips'] = True + advance['minimum_round_trips'] = True elif criteria == 'minimum_visits' and np.all(N_k >= value): # Check number of visits - self._advance['mimimum_visits'] = True + advance['mimimum_visits'] = True elif criteria == 'minimum_logZ': # Check logZ values criteria = np.abs(self._logZ / self.gamma0) > value logger.debug('minimum_logZ criteria met (%d total): %s' % (np.sum(criteria), str(np.array(criteria, 'i1')))) if np.all(criteria): - self._advance['minimum_logZ'] = True + advance['minimum_logZ'] = True - if (bool(self._advance) and all(v == True for v in self._advance.values())) or ((self._t0 > 0) and (self._iteration > self._t0)): + if (bool(advance) and all(v == True for v in advance.values())) or ((self._t0 > 0) and (self._iteration > self._t0)): # switch to asymptotically optimal scheme self._stage = 1 # asymptotically optimal self._t0 = self._iteration - 1 From 6f0717fb5c5bd00fb3aae13b110811e27d4fdc31 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Thu, 13 Jun 2019 14:08:22 +0100 Subject: [PATCH 037/152] [WIP] Changes to update multi region from 0.15 to 0.18 At least electrostatics are not working --- openmmtools/alchemy.py | 1007 +++++++++++++++++++++++++--------------- 1 file changed, 632 insertions(+), 375 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index ac1168bf1..0f780817a 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -38,6 +38,7 @@ import copy import logging import collections +import itertools import numpy as np from simtk import openmm, unit @@ -416,7 +417,8 @@ def apply_to_context(self, context): ('annihilate_electrostatics', True), ('annihilate_sterics', False), ('softcore_alpha', 0.5), ('softcore_a', 1), ('softcore_b', 1), ('softcore_c', 6), - ('softcore_beta', 0.0), ('softcore_d', 1), ('softcore_e', 1), ('softcore_f', 2) + ('softcore_beta', 0.0), ('softcore_d', 1), ('softcore_e', 1), ('softcore_f', 2), + ('region_name', None) ]) @@ -536,6 +538,8 @@ class AbsoluteAlchemicalFactory(object): will be split in different force groups. All non-alchemical forces will maintain their original force group. If more than 32 force groups are required, an error is thrown. + noninteracting_pairs : list, default empty + List of tuples of indexes of non-interacting alchemical regions Examples -------- @@ -617,7 +621,8 @@ class AbsoluteAlchemicalFactory(object): def __init__(self, consistent_exceptions=False, switch_width=1.0*unit.angstroms, alchemical_pme_treatment='exact', alchemical_rf_treatment='switched', - disable_alchemical_dispersion_correction=False, split_alchemical_forces=True): + disable_alchemical_dispersion_correction=False, split_alchemical_forces=True, + noninteracting_pairs=[]): self.consistent_exceptions = consistent_exceptions self.switch_width = switch_width @@ -625,6 +630,8 @@ def __init__(self, consistent_exceptions=False, switch_width=1.0*unit.angstroms, self.alchemical_rf_treatment = alchemical_rf_treatment self.disable_alchemical_dispersion_correction = disable_alchemical_dispersion_correction self.split_alchemical_forces = split_alchemical_forces + self.noninteracting_pairs = noninteracting_pairs + self.interactions = {} def create_alchemical_system(self, reference_system, alchemical_regions): """Create an alchemically modified version of the reference system. @@ -638,6 +645,8 @@ def create_alchemical_system(self, reference_system, alchemical_regions): alchemical system. This will not be modified. alchemical_regions : AlchemicalRegion The region of the reference system to alchemically soften. + noninteracting_pairs : list, default empty + List of tuples of indexes of non-interacting alchemical regions Returns ------- @@ -645,13 +654,56 @@ def create_alchemical_system(self, reference_system, alchemical_regions): Alchemically-modified version of reference_system. """ - # TODO implement multiple alchemical regions support. if not isinstance(alchemical_regions, AlchemicalRegion): - raise NotImplemented('There is no support for multiple alchemical regions yet.') - alchemical_region = alchemical_regions + logger.debug('Using %s alchemical regions' % (len(alchemical_regions))) + else: + alchemical_regions = [alchemical_regions] # Resolve alchemical region. - alchemical_region = self._resolve_alchemical_region(reference_system, alchemical_region) + alchemical_regions = [self._resolve_alchemical_region(reference_system, alchemical_region) + for alchemical_region in alchemical_regions] + + # Check for duplicate alchemical atoms/bonds/angles/torsions. + + all_alchemical_elements = {element_type: set() for element_type in ['atoms', 'bonds', 'angles', 'torsions']} + + for alchemical_region in alchemical_regions: + for element_type, all_elements in all_alchemical_elements.items(): + # Ignore None alchemical elements. + region_elements = getattr(alchemical_region, 'alchemical_' + element_type) + if region_elements is None: + continue + + # Check if there are duplicates with previous regions. + duplicate_elements = all_elements & region_elements + if len(duplicate_elements) > 0: + raise ValueError('Two regions have duplicate {}.'.format(element_type)) + + # Update all alchemical elements. + all_alchemical_elements[element_type].update(region_elements) + + # Check for duplicate names + alchemical_region_names = {alchemical_region.region_name for alchemical_region in alchemical_regions} + if len(alchemical_region_names) != len(alchemical_regions): + raise ValueError('Two alchemical regions have the same name') + + # generating the dictionary of interactions + self.noninteracting_pairs = [sorted(x) for x in self.noninteracting_pairs] # make sure the ordering of pairs is consistent + all_pairs = itertools.combinations_with_replacement(range(len(alchemical_regions)), 2) + for pair in all_pairs: + if pair[0] == pair[1]: + # all intra-alchemical region interations must be set to true + if pair in self.noninteracting_pairs: + logger.error('Intra-alchemical region interactions must be on.' + ' Pair {} cannot be in noninteracting_pairs'.format(pair)) + self.interactions[pair] = True + else: # inter-region interactions + if sorted(pair) not in self.noninteracting_pairs: + self.interactions[pair] = True # by default, alchemical regions will 'see' eachother + else: + self.interactions[pair] = False # interactions between pairs in noninteracting_pairs should be set to False + + logger.debug('Dictionary of if alchemical regions are interacting: {}'.format(self.interactions)) # Record timing statistics. timer = utils.Timer() @@ -663,10 +715,12 @@ def create_alchemical_system(self, reference_system, alchemical_regions): alchemical_system = copy.deepcopy(reference_system) # Check that there are no virtual sites to alchemically modify. - for particle_index in range(reference_system.getNumParticles()): - if (reference_system.isVirtualSite(particle_index) and - particle_index in alchemical_region.alchemical_atoms): - raise ValueError('Alchemically modified virtual sites are not supported') + for i, alchemical_region in enumerate(alchemical_regions): + for particle_index in range(reference_system.getNumParticles()): + if (reference_system.isVirtualSite(particle_index) and + particle_index in alchemical_region.alchemical_atoms): + raise ValueError('Virtual atoms in region {}.' + 'Alchemically modified virtual sites are not supported'.format(i)) # Modify forces as appropriate. We delete the forces that # have been processed modified at the end of the for loop. @@ -684,7 +738,7 @@ def create_alchemical_system(self, reference_system, alchemical_regions): # The reference system force will be deleted. forces_to_remove.append(force_index) # Collect all the Force objects modeling the reference force. - alchemical_forces = alchemical_force_creator_func(reference_force, alchemical_region) + alchemical_forces = alchemical_force_creator_func(reference_force, alchemical_regions) for lambda_variable_name, lambda_forces in alchemical_forces.items(): try: alchemical_forces_by_lambda[lambda_variable_name].extend(lambda_forces) @@ -1041,7 +1095,7 @@ def _add_alchemical_forces(self, alchemical_system, alchemical_forces_by_lambda) alchemical_system.addForce(force) @staticmethod - def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region): + def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_regions): """Create alchemically-modified version of PeriodicTorsionForce. Parameters @@ -1062,37 +1116,50 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region in alchemical_region. """ + alchemical_forces = {} + all_alchemical_torsions = set() + # Don't create a force if there are no alchemical torsions. - if len(alchemical_region.alchemical_torsions) == 0: + for alchemical_region in alchemical_regions: + all_alchemical_torsions.update(alchemical_region.alchemical_torsions) + if len(all_alchemical_torsions) == 0: return {'': [copy.deepcopy(reference_force)]} # Create PeriodicTorsionForce to handle unmodified torsions. force = openmm.PeriodicTorsionForce() force.setForceGroup(reference_force.getForceGroup()) - - # Create CustomTorsionForce to handle alchemically modified torsions. - energy_function = "lambda_torsions*k*(1+cos(periodicity*theta-phase))" - custom_force = openmm.CustomTorsionForce(energy_function) - custom_force.addGlobalParameter('lambda_torsions', 1.0) - custom_force.addPerTorsionParameter('periodicity') - custom_force.addPerTorsionParameter('phase') - custom_force.addPerTorsionParameter('k') - # Process reference torsions. for torsion_index in range(reference_force.getNumTorsions()): - # Retrieve parameters. - particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) - # Create torsions. - if torsion_index in alchemical_region.alchemical_torsions: - # Alchemically modified torsion. - custom_force.addTorsion(particle1, particle2, particle3, particle4, [periodicity, phase, k]) - else: - # Standard torsion. + if torsion_index not in all_alchemical_torsions: + particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) - return {'': [force], 'lambda_torsions': [custom_force]} + # Create CustomTorsionForce to handle alchemically modified torsions. + for alchemical_region in alchemical_regions: + if not len(alchemical_region.alchemical_torsions) == 0: + if alchemical_region.region_name is None: + region_name = '' + else: + region_name = '_' + alchemical_region.region_name + # Create CustomTorsionForce to handle alchemically modified torsions. + energy_function = "lambda_torsions{}*k*(1+cos(periodicity*theta-phase))".format(region_name) + custom_force = openmm.CustomTorsionForce(energy_function) + custom_force.addGlobalParameter('lambda_torsions{}'.format(region_name), 1.0) + custom_force.addPerTorsionParameter('periodicity') + custom_force.addPerTorsionParameter('phase') + custom_force.addPerTorsionParameter('k') + # Process reference torsions. + for torsion_index in sorted(alchemical_region.alchemical_torsions): + # Retrieve parameters. + particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) + # Create torsions. + custom_force.addTorsion(particle1, particle2, particle3, particle4, [periodicity, phase, k]) + alchemical_forces.update({'lambda_torsions{}'.format(region_name): [custom_force]}) + + alchemical_forces.update({'': [force]}) + return alchemical_forces @staticmethod - def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_region): + def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions): """Create alchemically-modified version of HarmonicAngleForce Parameters @@ -1113,35 +1180,47 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_region): in alchemical_region. """ + alchemical_forces = {} + all_alchemical_angles = set() + # Don't create a force if there are no alchemical angles. - if len(alchemical_region.alchemical_angles) == 0: + for alchemical_region in alchemical_regions: + all_alchemical_angles.update(alchemical_region.alchemical_angles) + if len(all_alchemical_angles) == 0: return {'': [copy.deepcopy(reference_force)]} # Create standard HarmonicAngleForce to handle unmodified angles. force = openmm.HarmonicAngleForce() force.setForceGroup(reference_force.getForceGroup()) - - # Create CustomAngleForce to handle alchemically modified angles. - energy_function = "lambda_angles*(K/2)*(theta-theta0)^2;" - custom_force = openmm.CustomAngleForce(energy_function) - custom_force.addGlobalParameter('lambda_angles', 1.0) - custom_force.addPerAngleParameter('theta0') - custom_force.addPerAngleParameter('K') - # Process reference angles. for angle_index in range(reference_force.getNumAngles()): - # Retrieve parameters. - [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) - if angle_index in alchemical_region.alchemical_angles: - # Alchemically modified angle. - custom_force.addAngle(particle1, particle2, particle3, [theta0, K]) - else: - # Standard angle. + if angle_index not in all_alchemical_angles: + [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) force.addAngle(particle1, particle2, particle3, theta0, K) - return {'': [force], 'lambda_angles': [custom_force]} + # Create CustomAngleForce to handle alchemically modified angles. + for alchemical_region in alchemical_regions: + if not len(alchemical_region.alchemical_angles) == 0: + if alchemical_region.region_name is None: + region_name = '' + else: + region_name = '_' + alchemical_region.region_name + # Create CustomAngleForce to handle alchemically modified angles. + energy_function = "lambda_angles{}*(K/2)*(theta-theta0)^2;".format(region_name) + custom_force = openmm.CustomAngleForce(energy_function) + custom_force.addGlobalParameter('lambda_angles{}'.format(region_name), 1.0) + custom_force.addPerAngleParameter('theta0') + custom_force.addPerAngleParameter('K') + # Process reference angles. + for angle_index in sorted(alchemical_region.alchemical_angles): + [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) + custom_force.addAngle(particle1, particle2, particle3, [theta0, K]) + alchemical_forces.update({'lambda_bonds{}'.format(region_name): [custom_force]}) + + alchemical_forces.update({'': [force]}) + return alchemical_forces @staticmethod - def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_region): + def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions): """Create alchemically-modified version of HarmonicBondForce Parameters @@ -1162,34 +1241,69 @@ def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_region): in alchemical_region. """ + alchemical_forces = {} + all_alchemical_bonds = set() + # Don't create a force if there are no alchemical bonds. - if len(alchemical_region.alchemical_bonds) == 0: + for alchemical_region in alchemical_regions: + all_alchemical_bonds.update(alchemical_region.alchemical_bonds) + if len(all_alchemical_bonds) == 0: return {'': [copy.deepcopy(reference_force)]} # Create standard HarmonicBondForce to handle unmodified bonds. force = openmm.HarmonicBondForce() force.setForceGroup(reference_force.getForceGroup()) - - # Create CustomBondForce to handle alchemically modified bonds. - energy_function = "lambda_bonds*(K/2)*(r-r0)^2;" - custom_force = openmm.CustomBondForce(energy_function) - custom_force.addGlobalParameter('lambda_bonds', 1.0) - custom_force.addPerBondParameter('r0') - custom_force.addPerBondParameter('K') - # Process reference bonds. for bond_index in range(reference_force.getNumBonds()): - # Retrieve parameters. - [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) - if bond_index in alchemical_region.alchemical_bonds: - # Alchemically modified bond. - custom_force.addBond(particle1, particle2, [theta0, K]) - else: - # Standard bond. + if bond_index not in all_alchemical_bonds: + [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) force.addBond(particle1, particle2, theta0, K) - return {'': [force], 'lambda_bonds': [custom_force]} + for alchemical_region in alchemical_regions: + if not len(alchemical_region.alchemical_bonds) == 0: + if alchemical_region.region_name is None: + region_name = '' + else: + region_name = '_' + alchemical_region.region_name + # Define force here so that it is over writen saving only one copy. + # Create CustomBondForce to handle alchemically modified bonds. + energy_function = "lambda_bonds{}*(K/2)*(r-r0)^2;".format(region_name) + custom_force = openmm.CustomBondForce(energy_function) + custom_force.addGlobalParameter('lambda_bonds{}'.format(region_name), 1.0) + custom_force.addPerBondParameter('r0') + custom_force.addPerBondParameter('K') + # Process reference bonds. + for bond_index in sorted(alchemical_region.alchemical_bonds): + [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) + custom_force.addBond(particle1, particle2, [theta0, K]) + alchemical_forces.update({'lambda_bonds{}'.format(region_name): [custom_force]}) + + alchemical_forces.update({'': [force]}) + return alchemical_forces + + def _get_sterics_energy_expressions(self, alchemical_region_indices): + # Sterics mixing rules. + if alchemical_region_indices[0] == '': + lambda_variable_name = 'lambda_sterics' + else: + if len(alchemical_region_indices) > 1: + lambda_variable_name = 'lambda_sterics{0}*lambda_sterics{1}'.format(alchemical_region_indices[0], alchemical_region_indices[1]) + else: + lambda_variable_name = 'lambda_sterics{}'.format(alchemical_region_indices[0]) + + sterics_mixing_rules = ('epsilon = sqrt(epsilon1*epsilon2);' # Mixing rule for epsilon. + 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. - def _get_electrostatics_energy_expressions(self, reference_force): + # Soft-core Lennard-Jones. + exceptions_sterics_energy_expression = ('U_sterics;' + 'U_sterics = (({0})^softcore_a)*4*epsilon*x*(x-1.0);' + 'x = (sigma/reff_sterics)^6;' + # Effective softcore distance for sterics. + 'reff_sterics = sigma*((softcore_alpha*(1.0-({0}))^softcore_b + (r/sigma)^softcore_c))^(1/softcore_c);')\ + .format(lambda_variable_name) + # Define energy expression for electrostatics. + return sterics_mixing_rules, exceptions_sterics_energy_expression + + def _get_electrostatics_energy_expressions(self, reference_force, alchemical_region_indices): """Return the energy expressions for electrostatics. This private function assumes self._alchemical_pme_treatment != 'exact' @@ -1197,18 +1311,25 @@ def _get_electrostatics_energy_expressions(self, reference_force): lambda_electrostatics is modeled through an offset parameter in a NonbondedForce. """ + if alchemical_region_indices[0] == '': + lambda_variable_name = 'lambda_electrostatics' + else: + if len(alchemical_region_indices) > 1: + lambda_variable_name = 'lambda_electrostatics{0}*lambda_electrostatics{1}'.format(alchemical_region_indices[0], alchemical_region_indices[1]) + else: + lambda_variable_name = 'lambda_electrostatics{}'.format(alchemical_region_indices[0]) # The final expression will be prefix + method + suffix. electrostatics_prefix = ('U_electrostatics;' - 'U_electrostatics=(lambda_electrostatics^softcore_d)*ONE_4PI_EPS0*chargeprod') + 'U_electrostatics=(({})^softcore_d)*ONE_4PI_EPS0*chargeprod').format(lambda_variable_name) # Effective softcore distance for electrostatics (common to all methods). - electrostatics_suffix = ('reff_electrostatics = sigma*((softcore_beta*(1.0-lambda_electrostatics)^softcore_e + (r/sigma)^softcore_f))^(1/softcore_f);' - 'ONE_4PI_EPS0 = {};').format(ONE_4PI_EPS0) # Already in OpenMM units. + electrostatics_suffix = ('reff_electrostatics = sigma*((softcore_beta*(1.0-({0}))^softcore_e + (r/sigma)^softcore_f))^(1/softcore_f);' + 'ONE_4PI_EPS0 = {1};').format(lambda_variable_name, ONE_4PI_EPS0) # Already in OpenMM units. # Define mixing rules. electrostatics_mixing_rules = ('chargeprod = charge1*charge2;' # Mixing rule for charges. - 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. + 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. # Standard Coulomb expression with softened core. This is used # - When the nonbonded method of the reference force is NoCutoff. @@ -1319,7 +1440,7 @@ def _get_pme_direct_space_unique_expression(self, reference_force): "alpha_ewald = {};").format(alpha_ewald) return pme_expression - def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region): + def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_regions): """Create alchemically-modified version of NonbondedForce. Parameters @@ -1365,206 +1486,37 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # TODO Change softcore_beta to a dimensionless scalar to multiply some intrinsic length-scale, like Lennard-Jones alpha. # TODO Try using a single, common "reff" effective softcore distance for both Lennard-Jones and Coulomb. + forces_by_lambda = {} + all_alchemical_atoms = set() + populated_region_ids = [] + non_pairs = [] + + # Don't create a force if there are no alchemical atoms. + for region_id, alchemical_region in enumerate(alchemical_regions): + if not len(alchemical_region.alchemical_atoms) == 0: + non_pairs.append((region_id, region_id)) + populated_region_ids.append(region_id) + all_alchemical_atoms.update(alchemical_region.alchemical_atoms) # Don't create a force if there are no alchemical atoms. - if len(alchemical_region.alchemical_atoms) == 0: + if len(all_alchemical_atoms) == 0: return {'': [copy.deepcopy(reference_force)]} - # -------------------------------------------------- - # Determine energy expression for all custom forces - # -------------------------------------------------- - - # Sterics mixing rules. - sterics_mixing_rules = ('epsilon = sqrt(epsilon1*epsilon2);' # Mixing rule for epsilon. - 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. - - # Soft-core Lennard-Jones. - exceptions_sterics_energy_expression = ('U_sterics;' - 'U_sterics = (lambda_sterics^softcore_a)*4*epsilon*x*(x-1.0);' - 'x = (sigma/reff_sterics)^6;' - # Effective softcore distance for sterics. - 'reff_sterics = sigma*((softcore_alpha*(1.0-lambda_sterics)^softcore_b + (r/sigma)^softcore_c))^(1/softcore_c);') - - # Define energy expression for sterics. - sterics_energy_expression = exceptions_sterics_energy_expression + sterics_mixing_rules - - # Define energy expression for electrostatics based on nonbonded method. - nonbonded_method = reference_force.getNonbondedMethod() - is_ewald_method = nonbonded_method in [openmm.NonbondedForce.Ewald, - openmm.NonbondedForce.PME] - is_rf_method = nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, - openmm.NonbondedForce.CutoffNonPeriodic] - is_periodic_method = is_ewald_method or nonbonded_method == openmm.NonbondedForce.CutoffPeriodic - use_exact_pme_treatment = is_ewald_method and self.alchemical_pme_treatment == 'exact' - - # Warn about reaction field. - if is_rf_method: - logger.warning('Reaction field support is still experimental. For free energy ' - 'calculations in explicit solvent, we suggest using PME for now.') - - # Check that PME treatment is supported with the region's parameters. - if use_exact_pme_treatment: - err_msg = ' not supported with exact treatment of Ewald electrostatics.' - if not alchemical_region.annihilate_electrostatics: - raise ValueError('Decoupled electrostatics is' + err_msg) - if self.consistent_exceptions: - raise ValueError('Consistent exceptions are' + err_msg) - if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): - raise ValueError('Softcore electrostatics is' + err_msg) - else: - # There's no CustomNonbondedForce that models electrostatics if we use exact - # PME treatment. Electrostatics is modeled through offset parameters. - energy_expressions = self._get_electrostatics_energy_expressions(reference_force) - (electrostatics_energy_expression, - exceptions_electrostatics_energy_expression) = energy_expressions # Unpack tuple. - - # ------------------------------------------------------------ - # Create and configure all forces to add to alchemical system - # ------------------------------------------------------------ - - # Interactions and exceptions will be distributed according to the following table. - - # -------------------------------------------------------------------------------------------------- - # FORCE | INTERACTION GROUP | - # -------------------------------------------------------------------------------------------------- - # nonbonded_force (unmodified) | all interactions nonalchemical/nonalchemical | - # | all exceptions nonalchemical/nonalchemical | - # -------------------------------------------------------------------------------------------------- - # aa_sterics_custom_nonbonded_force | sterics interactions alchemical/alchemical | - # -------------------------------------------------------------------------------------------------- - # aa_electrostatics_custom_nonbonded_force | electrostatics interactions alchemical/alchemical | - # | (only without exact PME treatment) | - # -------------------------------------------------------------------------------------------------- - # na_sterics_custom_nonbonded_force | sterics interactions non-alchemical/alchemical | - # -------------------------------------------------------------------------------------------------- - # na_electrostatics_custom_nonbonded_force | electrostatics interactions non-alchemical/alchemical | - # | (only without exact PME treatment) | - # -------------------------------------------------------------------------------------------------- - # aa_sterics_custom_bond_force | sterics exceptions alchemical/alchemical | - # -------------------------------------------------------------------------------------------------- - # aa_electrostatics_custom_bond_force | electrostatics exceptions alchemical/alchemical | - # | (only without exact PME treatment) | - # -------------------------------------------------------------------------------------------------- - # na_sterics_custom_bond_force | sterics exceptions non-alchemical/alchemical | - # -------------------------------------------------------------------------------------------------- - # na_electrostatics_custom_bond_force | electrostatics exceptions non-alchemical/alchemical | - # | (only without exact PME treatment) | - # -------------------------------------------------------------------------------------------------- - - # Create a copy of the NonbondedForce to handle particle interactions and - # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). - nonbonded_force = copy.deepcopy(reference_force) - - def create_force(force_cls, energy_expression, lambda_variable_name, is_lambda_controlled): - """Shortcut to create a lambda-controlled custom forces.""" - if is_lambda_controlled: - force = force_cls(energy_expression) - force.addGlobalParameter(lambda_variable_name, 1.0) - else: # fix lambda variable to 1.0 - energy_expression = energy_expression + lambda_variable_name + '=1.0;' - force = force_cls(energy_expression) - return force - - # Create CustomNonbondedForces to handle sterics particle interactions between - # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda - # to 1.0 for decoupled interactions in alchemical/alchemical force. - na_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', is_lambda_controlled=True) - aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', alchemical_region.annihilate_sterics) - all_sterics_custom_nonbonded_forces = [na_sterics_custom_nonbonded_force, aa_sterics_custom_nonbonded_force] - - # Add parameters and configure CustomNonbondedForces to match reference force - for force in all_sterics_custom_nonbonded_forces: - force.addPerParticleParameter("sigma") # Lennard-Jones sigma - force.addPerParticleParameter("epsilon") # Lennard-Jones epsilon - force.setUseSwitchingFunction(nonbonded_force.getUseSwitchingFunction()) - force.setCutoffDistance(nonbonded_force.getCutoffDistance()) - force.setSwitchingDistance(nonbonded_force.getSwitchingDistance()) - if self.disable_alchemical_dispersion_correction: - force.setUseLongRangeCorrection(False) - else: - force.setUseLongRangeCorrection(nonbonded_force.getUseDispersionCorrection()) - - if is_periodic_method: - force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) - else: - force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) - - # With exact PME treatment, particle electrostatics is handled through offset parameters. - if use_exact_pme_treatment: - nonbonded_force.addGlobalParameter('lambda_electrostatics', 1.0) - all_electrostatics_custom_nonbonded_forces = [] - else: - # Create CustomNonbondedForces to handle electrostatics particle interactions between - # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda - # to 1.0 for decoupled interactions in alchemical/alchemical force. - na_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', is_lambda_controlled=True) - aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', alchemical_region.annihilate_electrostatics) - all_electrostatics_custom_nonbonded_forces = [na_electrostatics_custom_nonbonded_force, - aa_electrostatics_custom_nonbonded_force] - - # Common parameters and configuration for electrostatics CustomNonbondedForces. - for force in all_electrostatics_custom_nonbonded_forces: - force.addPerParticleParameter("charge") # partial charge - force.addPerParticleParameter("sigma") # Lennard-Jones sigma - if ((is_ewald_method and self.alchemical_pme_treatment == 'coulomb') or - (is_rf_method and self.alchemical_rf_treatment == 'switched')): - # Use switching function for alchemical electrostatics to ensure force continuity at cutoff. - force.setUseSwitchingFunction(True) - else: - force.setUseSwitchingFunction(False) - force.setSwitchingDistance(nonbonded_force.getCutoffDistance() - self.switch_width) - force.setCutoffDistance(nonbonded_force.getCutoffDistance()) - force.setUseLongRangeCorrection(False) # long-range dispersion correction is meaningless for electrostatics - - if is_periodic_method: - force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) - else: - force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) - - # Create CustomBondForces to handle sterics 1,4 exceptions interactions between - # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda - # to 1.0 for decoupled interactions in alchemical/alchemical force. - na_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', is_lambda_controlled=True) - aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', alchemical_region.annihilate_sterics) - all_sterics_custom_bond_forces = [na_sterics_custom_bond_force, aa_sterics_custom_bond_force] - - for force in all_sterics_custom_bond_forces: - force.addPerBondParameter("sigma") # Lennard-Jones effective sigma - force.addPerBondParameter("epsilon") # Lennard-Jones effective epsilon - - # With exact PME treatment, exception electrostatics is handled through offset parameters. - if use_exact_pme_treatment: - all_electrostatics_custom_bond_forces = [] - else: - # Create CustomBondForces to handle electrostatics 1,4 exceptions interactions between - # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda - # to 1.0 for decoupled interactions in alchemical/alchemical force. - na_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', is_lambda_controlled=True) - aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', alchemical_region.annihilate_electrostatics) - all_electrostatics_custom_bond_forces = [na_electrostatics_custom_bond_force, aa_electrostatics_custom_bond_force] - - # Create CustomBondForce to handle exceptions for electrostatics - for force in all_electrostatics_custom_bond_forces: - force.addPerBondParameter("chargeprod") # charge product - force.addPerBondParameter("sigma") # Lennard-Jones effective sigma - - # ------------------------------------------------------------------------------- - # Distribute particle interactions contributions in appropriate nonbonded forces - # ------------------------------------------------------------------------------- - - # Create atom groups. - alchemical_atomset = alchemical_region.alchemical_atoms - all_atomset = set(range(reference_force.getNumParticles())) # all atoms, including alchemical region - nonalchemical_atomset = all_atomset.difference(alchemical_atomset) - + #Generate all pair of regions + region_permus = non_pairs + if len(populated_region_ids) > 1: + for alchemical_region in alchemical_regions: + if alchemical_region.region_name == None: + raise ValueError('For a alchemical calculation with multiple regions interacting via Nonbonded Forces ' + 'all regions populated with atoms should be named') + #Region_permus is all permutations of alchemical regions so we can deal with interactions between + # alchemical regions (aa)(pairs). And the standard interactions of the individual alchemical regions (non_pairs) + #with themselves (aa)(non_pair) and the non-alcemical regions (na)(non_pair) + pairs = (list(itertools.combinations(populated_region_ids, 2))) + region_permus += pairs + + #Perform tasks that do not need to be repeated for all regions i.e.Fix any NonbondedForce issues with Lennard-Jones sigma = 0 # Fix any NonbondedForce issues with Lennard-Jones sigma = 0 (epsilon = 0), which should have sigma > 0. + nonbonded_force = copy.deepcopy(reference_force) for particle_index in range(nonbonded_force.getNumParticles()): # Retrieve parameters. [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) @@ -1587,117 +1539,422 @@ def create_force(force_cls, energy_expression, lambda_variable_name, is_lambda_c # Fix it. nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) - # Copy NonbondedForce particle terms for alchemically-modified particles - # to CustomNonbondedForces, and/or add the charge offsets for exact PME. - # On CUDA, for efficiency reasons, all nonbonded forces (custom and not) - # must have the same particles. - for particle_index in range(nonbonded_force.getNumParticles()): - # Retrieve nonbonded parameters. - [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) - # Set sterics parameters in CustomNonbondedForces. - for force in all_sterics_custom_nonbonded_forces: - force.addParticle([sigma, epsilon]) - # Set electrostatics parameters in CustomNonbondedForces. - for force in all_electrostatics_custom_nonbonded_forces: - force.addParticle([charge, sigma]) - # Set offset parameters in NonbondedForce. - if use_exact_pme_treatment and particle_index in alchemical_atomset: - nonbonded_force.addParticleParameterOffset('lambda_electrostatics', particle_index, - charge, 0.0, 0.0) - - # Turn off interactions contribution from alchemically-modified particles in unmodified - # NonbondedForce that will be handled by all other forces - for particle_index in range(nonbonded_force.getNumParticles()): - # Retrieve parameters. - [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) - # Even with exact treatment of the PME electrostatics, we turn off - # the NonbondedForce charge which is modeled by the offset parameter. - if particle_index in alchemical_atomset: - nonbonded_force.setParticleParameters(particle_index, abs(0.0*charge), sigma, abs(0*epsilon)) - - # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. - na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset) - aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset, alchemical_atomset) - if not use_exact_pme_treatment: - na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset) - aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset, alchemical_atomset) + for region_ids in region_permus: + alchemical_region_0 = alchemical_regions[region_ids[0]] + alchemical_region_1 = alchemical_regions[region_ids[1]] + #Generate region names + if alchemical_region_0.alchemical_atoms == alchemical_region_1.alchemical_atoms: + if alchemical_region_0.region_name == None: + #case where only single populated region which is unnamed + region_names = [''] + else: + region_names = ['_' + alchemical_region_0.region_name] + else: + region_names = ['_' + alchemical_region_0.region_name, '_' + alchemical_region_1.region_name] + + + # -------------------------------------------------- + # Determine energy expression for all custom forces + # -------------------------------------------------- + + sterics_mixing_rules, exceptions_sterics_energy_expression = self._get_sterics_energy_expressions(region_names) + + # Define energy expression for sterics. + sterics_energy_expression = exceptions_sterics_energy_expression + sterics_mixing_rules + + # Define energy expression for electrostatics based on nonbonded method. + nonbonded_method = reference_force.getNonbondedMethod() + is_ewald_method = nonbonded_method in [openmm.NonbondedForce.Ewald, + openmm.NonbondedForce.PME] + is_rf_method = nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, + openmm.NonbondedForce.CutoffNonPeriodic] + is_periodic_method = is_ewald_method or nonbonded_method == openmm.NonbondedForce.CutoffPeriodic + use_exact_pme_treatment = is_ewald_method and self.alchemical_pme_treatment == 'exact' + + # Warn about reaction field. + if is_rf_method: + logger.warning('Reaction field support is still experimental. For free energy ' + 'calculations in explicit solvent, we suggest using PME for now.') + + # Check that PME treatment is supported with the region's parameters. + if use_exact_pme_treatment: + err_msg = ' not supported with exact treatment of Ewald electrostatics.' + if not alchemical_region.annihilate_electrostatics: + raise ValueError('Decoupled electrostatics is' + err_msg) + if self.consistent_exceptions: + raise ValueError('Consistent exceptions are' + err_msg) + if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): + raise ValueError('Softcore electrostatics is' + err_msg) + else: + # There's no CustomNonbondedForce that models electrostatics if we use exact + # PME treatment. Electrostatics is modeled through offset parameters. + energy_expressions = self._get_electrostatics_energy_expressions(reference_force, region_names) + (electrostatics_energy_expression, + exceptions_electrostatics_energy_expression) = energy_expressions # Unpack tuple. + + # ------------------------------------------------------------ + # Create and configure all forces to add to alchemical system + # ------------------------------------------------------------ + + # Interactions and exceptions will be distributed according to the following table. + + # -------------------------------------------------------------------------------------------------- + # FORCE | INTERACTION GROUP | + # -------------------------------------------------------------------------------------------------- + # nonbonded_force (unmodified) | all interactions nonalchemical/nonalchemical | + # | all exceptions nonalchemical/nonalchemical | + # -------------------------------------------------------------------------------------------------- + # aa_sterics_custom_nonbonded_force | sterics interactions alchemical/alchemical | + # -------------------------------------------------------------------------------------------------- + # aa_electrostatics_custom_nonbonded_force | electrostatics interactions alchemical/alchemical | + # | (only without exact PME treatment) | + # -------------------------------------------------------------------------------------------------- + # na_sterics_custom_nonbonded_force | sterics interactions non-alchemical/alchemical | + # -------------------------------------------------------------------------------------------------- + # na_electrostatics_custom_nonbonded_force | electrostatics interactions non-alchemical/alchemical | + # | (only without exact PME treatment) | + # -------------------------------------------------------------------------------------------------- + # aa_sterics_custom_bond_force | sterics exceptions alchemical/alchemical | + # -------------------------------------------------------------------------------------------------- + # aa_electrostatics_custom_bond_force | electrostatics exceptions alchemical/alchemical | + # | (only without exact PME treatment) | + # -------------------------------------------------------------------------------------------------- + # na_sterics_custom_bond_force | sterics exceptions non-alchemical/alchemical | + # -------------------------------------------------------------------------------------------------- + # na_electrostatics_custom_bond_force | electrostatics exceptions non-alchemical/alchemical | + # | (only without exact PME treatment) | + # -------------------------------------------------------------------------------------------------- + + # Create a copy of the NonbondedForce to handle particle interactions and + # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). + nonbonded_force = copy.deepcopy(reference_force) + + def create_force(force_cls, energy_expression, lambda_variable_name, region_names, is_lambda_controlled): + """Shortcut to create a lambda-controlled custom forces.""" + if is_lambda_controlled: + force = force_cls(energy_expression) + for region_name in region_names: + name = (lambda_variable_name + region_name) + force.addGlobalParameter(name, 1.0) + else: # fix lambda variable to 1.0 + for region_name in region_names: + name = (lambda_variable_name + region_name) + energy_expression = energy_expression + name + '=1.0;' + force = force_cls(energy_expression) + return force + + # Create CustomNonbondedForces to handle sterics particle interactions between + # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda + # to 1.0 for decoupled interactions in alchemical/alchemical force. + if len(region_names) >1: + aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, + 'lambda_sterics', region_names, is_lambda_controlled=True) + all_sterics_custom_nonbonded_forces = [aa_sterics_custom_nonbonded_force] + else: + na_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, + 'lambda_sterics', region_names, is_lambda_controlled=True) + aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, + 'lambda_sterics', region_names, alchemical_region.annihilate_sterics) + all_sterics_custom_nonbonded_forces = [na_sterics_custom_nonbonded_force, aa_sterics_custom_nonbonded_force] - # --------------------------------------------------------------- - # Distribute exceptions contributions in appropriate bond forces - # --------------------------------------------------------------- + # Add parameters and configure CustomNonbondedForces to match reference force + for force in all_sterics_custom_nonbonded_forces: + force.addPerParticleParameter("sigma") # Lennard-Jones sigma + force.addPerParticleParameter("epsilon") # Lennard-Jones epsilon + force.setUseSwitchingFunction(nonbonded_force.getUseSwitchingFunction()) + force.setCutoffDistance(nonbonded_force.getCutoffDistance()) + force.setSwitchingDistance(nonbonded_force.getSwitchingDistance()) + if self.disable_alchemical_dispersion_correction: + force.setUseLongRangeCorrection(False) + else: + force.setUseLongRangeCorrection(nonbonded_force.getUseDispersionCorrection()) - all_custom_nonbonded_forces = all_sterics_custom_nonbonded_forces + all_electrostatics_custom_nonbonded_forces + if is_periodic_method: + force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) + else: + force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) + + # With exact PME treatment, particle electrostatics is handled through offset parameters. + if use_exact_pme_treatment: + for region_name in region_names: + nonbonded_force.addGlobalParameter('lambda_electrostatics{}'.format(region_name), 1.0) + if len(region_names) > 1: + nonbonded_force.addGlobalParameter('lambda_electrostatics{}{}'.format(region_names[0], + region_names[1]), 1.0) + all_electrostatics_custom_nonbonded_forces = [] + else: + # Create CustomNonbondedForces to handle electrostatics particle interactions between + # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda + # to 1.0 for decoupled interactions in alchemical/alchemical force. + if len(region_names) > 1: + aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, + 'lambda_electrostatics', region_names, alchemical_region.annihilate_electrostatics) + all_electrostatics_custom_nonbonded_forces = [aa_electrostatics_custom_nonbonded_force] + else: + na_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, + 'lambda_electrostatics', region_names, is_lambda_controlled=True) + aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, + 'lambda_electrostatics', region_names, alchemical_region.annihilate_electrostatics) + all_electrostatics_custom_nonbonded_forces = [na_electrostatics_custom_nonbonded_force, + aa_electrostatics_custom_nonbonded_force] + + # Common parameters and configuration for electrostatics CustomNonbondedForces. + for force in all_electrostatics_custom_nonbonded_forces: + force.addPerParticleParameter("charge") # partial charge + force.addPerParticleParameter("sigma") # Lennard-Jones sigma + if ((is_ewald_method and self.alchemical_pme_treatment == 'coulomb') or + (is_rf_method and self.alchemical_rf_treatment == 'switched')): + # Use switching function for alchemical electrostatics to ensure force continuity at cutoff. + force.setUseSwitchingFunction(True) + else: + force.setUseSwitchingFunction(False) + force.setSwitchingDistance(nonbonded_force.getCutoffDistance() - self.switch_width) + force.setCutoffDistance(nonbonded_force.getCutoffDistance()) + force.setUseLongRangeCorrection(False) # long-range dispersion correction is meaningless for electrostatics - # Move all NonbondedForce exception terms for alchemically-modified particles to CustomBondForces. - for exception_index in range(nonbonded_force.getNumExceptions()): - # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + if is_periodic_method: + force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) + else: + force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) - # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces - # must have the same number of exceptions/exclusions on CUDA platform. - for force in all_custom_nonbonded_forces: - force.addExclusion(iatom, jatom) - - # Check how many alchemical atoms we have - both_alchemical = iatom in alchemical_atomset and jatom in alchemical_atomset - at_least_one_alchemical = iatom in alchemical_atomset or jatom in alchemical_atomset - only_one_alchemical = at_least_one_alchemical and not both_alchemical - - # Check if this is an exception or an exclusion - is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 - is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 - - # If this is an electrostatic exception and we're using exact PME, - # we just have to add the exception offset to the NonbondedForce. - if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: - nonbonded_force.addExceptionParameterOffset('lambda_electrostatics', exception_index, - chargeprod, 0.0, 0.0) - - # If exception (and not exclusion), add special CustomBondForce terms to - # handle alchemically-modified Lennard-Jones and electrostatics exceptions - if both_alchemical: - if is_exception_epsilon: - aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) - if is_exception_chargeprod and not use_exact_pme_treatment: - aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - elif only_one_alchemical: - if is_exception_epsilon: - na_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) - if is_exception_chargeprod and not use_exact_pme_treatment: - na_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - # else: both particles are non-alchemical, leave them in the unmodified NonbondedForce - - # Turn off all exception contributions from alchemical atoms in the NonbondedForce - # modelling non-alchemical atoms only - if at_least_one_alchemical: - nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, - abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) - - # Add global parameters to forces. - def add_global_parameters(force): - force.addGlobalParameter('softcore_alpha', alchemical_region.softcore_alpha) - force.addGlobalParameter('softcore_beta', alchemical_region.softcore_beta) - force.addGlobalParameter('softcore_a', alchemical_region.softcore_a) - force.addGlobalParameter('softcore_b', alchemical_region.softcore_b) - force.addGlobalParameter('softcore_c', alchemical_region.softcore_c) - force.addGlobalParameter('softcore_d', alchemical_region.softcore_d) - force.addGlobalParameter('softcore_e', alchemical_region.softcore_e) - force.addGlobalParameter('softcore_f', alchemical_region.softcore_f) - - all_custom_forces = (all_custom_nonbonded_forces + - all_sterics_custom_bond_forces + - all_electrostatics_custom_bond_forces) - for force in all_custom_forces: - add_global_parameters(force) - - # With exact treatment of PME electrostatics, the NonbondedForce - # is affected by lambda electrostatics as well. - forces_by_lambda = { - 'lambda_electrostatics': all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces, - 'lambda_sterics': all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces, - } + # Create CustomBondForces to handle sterics 1,4 exceptions interactions between + # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda + # to 1.0 for decoupled interactions in alchemical/alchemical force. + if len(region_names) > 1: + aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, + 'lambda_sterics', region_names, alchemical_region.annihilate_sterics) + all_sterics_custom_bond_forces = [aa_sterics_custom_bond_force] + else: + na_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, + 'lambda_sterics', region_names, is_lambda_controlled=True) + aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, + 'lambda_sterics', region_names, alchemical_region.annihilate_sterics) + all_sterics_custom_bond_forces = [na_sterics_custom_bond_force, aa_sterics_custom_bond_force] + + for force in all_sterics_custom_bond_forces: + force.addPerBondParameter("sigma") # Lennard-Jones effective sigma + force.addPerBondParameter("epsilon") # Lennard-Jones effective epsilon + + # With exact PME treatment, exception electrostatics is handled through offset parameters. + if use_exact_pme_treatment: + all_electrostatics_custom_bond_forces = [] + else: + # Create CustomBondForces to handle electrostatics 1,4 exceptions interactions between + # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda + # to 1.0 for decoupled interactions in alchemical/alchemical force. + if len(region_names) > 1: + aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, + 'lambda_electrostatics', alchemical_region.annihilate_electrostatics) + all_electrostatics_custom_bond_forces = [aa_electrostatics_custom_bond_force] + else: + na_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, + 'lambda_electrostatics', is_lambda_controlled=True) + aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, + 'lambda_electrostatics', alchemical_region.annihilate_electrostatics) + all_electrostatics_custom_bond_forces = [na_electrostatics_custom_bond_force, aa_electrostatics_custom_bond_force] + + # Create CustomBondForce to handle exceptions for electrostatics + for force in all_electrostatics_custom_bond_forces: + force.addPerBondParameter("chargeprod") # charge product + force.addPerBondParameter("sigma") # Lennard-Jones effective sigma + + # ------------------------------------------------------------------------------- + # Distribute particle interactions contributions in appropriate nonbonded forces + # ------------------------------------------------------------------------------- + + # Create atom groups. + alchemical_atomset_0 = alchemical_region_0.alchemical_atoms + alchemical_atomset_1 = alchemical_region_1.alchemical_atoms + + all_atomset = set(range(reference_force.getNumParticles())) # all atoms, including alchemical region + nonalchemical_atomset = all_atomset.difference(all_alchemical_atoms) + + # Copy NonbondedForce particle terms for alchemically-modified particles + # to CustomNonbondedForces, and/or add the charge offsets for exact PME. + # On CUDA, for efficiency reasons, all nonbonded forces (custom and not) + # must have the same particles. + for particle_index in range(nonbonded_force.getNumParticles()): + # Retrieve nonbonded parameters. + [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + # Set sterics parameters in CustomNonbondedForces. + for force in all_sterics_custom_nonbonded_forces: + force.addParticle([sigma, epsilon]) + # Set electrostatics parameters in CustomNonbondedForces. + for force in all_electrostatics_custom_nonbonded_forces: + force.addParticle([charge, sigma]) + # Set offset parameters in NonbondedForce. + if use_exact_pme_treatment: + if len(region_names) > 1: + if particle_index in alchemical_atomset_0: + nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[0], particle_index, + charge, 0.0, 0.0) + elif particle_index in alchemical_atomset_1: + nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[1], particle_index, + charge, 0.0, 0.0) + else: + if use_exact_pme_treatment and particle_index in alchemical_atomset_0: + nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[0], particle_index, + charge, 0.0, 0.0) + + # Turn off interactions contribution from alchemically-modified particles in unmodified + # NonbondedForce that will be handled by all other forces + for particle_index in range(nonbonded_force.getNumParticles()): + # Retrieve parameters. + [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + # Even with exact treatment of the PME electrostatics, we turn off + # the NonbondedForce charge which is modeled by the offset parameter. + if particle_index in alchemical_atomset_0 or particle_index in alchemical_atomset_1: + nonbonded_force.setParticleParameters(particle_index, abs(0.0*charge), sigma, abs(0*epsilon)) + + # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. + #Sterics + if len(region_names) > 1: #Multi region + if self.interactions[region_ids]: #Regions interacting + logger.debug('Adding a steric interaction group between groups {}.'.format(region_ids)) + aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) + else: #Regions noninteracting + logger.debug('Skipping steric interaction group for {} as they are non-interacting.'.format(region_ids)) + else: #One region + logger.debug('Adding steric interaction groups between {0} and the environment,' + ' and {0} with itself.'.format(region_ids[0])) + na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) + aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) + #Electrostatics + if not use_exact_pme_treatment: + if len(region_names) > 1: #Multi region + if self.interactions[region_ids]: #Regions interacting + logger.debug('Adding a electrostatic interaction group between groups {}.'.format(region_ids)) + aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) + else: #Regions noninteracting + logger.debug('Skipping electrelectrostatic interaction group for {}' + ' as they are non-interacting.'.format(region_ids)) + else: #One region + logger.debug('Adding electrostatic interaction groups between {0} and the environment,' + ' and {0} with itself.'.format(region_ids[0])) + na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) + aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) + + #Need to handle interactions between non interacting alchemical regions if we are using excat PME + + # --------------------------------------------------------------- + # Distribute exceptions contributions in appropriate bond forces + # --------------------------------------------------------------- + + all_custom_nonbonded_forces = all_sterics_custom_nonbonded_forces + all_electrostatics_custom_nonbonded_forces + + # Move all NonbondedForce exception terms for alchemically-modified particles to CustomBondForces. + if len(region_names) > 1: + for exception_index in range(nonbonded_force.getNumExceptions()): + # Retrieve parameters. + [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + + # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces + # must have the same number of exceptions/exclusions on CUDA platform. + for force in all_custom_nonbonded_forces: + force.addExclusion(iatom, jatom) + + # Check how many alchemical atoms we have + both_alchemical = iatom in alchemical_atomset_0 and jatom in alchemical_atomset_1 + at_least_one_alchemical = iatom in alchemical_atomset_0 or jatom in alchemical_atomset_1 + + # Check if this is an exception or an exclusion + is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 + is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 + + # If this is an electrostatic exception and we're using exact PME, + # we just have to add the exception offset to the NonbondedForce. + if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: + for region_name in region_names: + nonbonded_force.addExceptionParameterOffset('lambda_electrostatics'+region_name, exception_index, + chargeprod, 0.0, 0.0) + + # If exception (and not exclusion), add special CustomBondForce terms to + # handle alchemically-modified Lennard-Jones and electrostatics exceptions + if both_alchemical: + if is_exception_epsilon: + aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) + if is_exception_chargeprod and not use_exact_pme_treatment: + aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) + + # Turn off all exception contributions from alchemical atoms in the NonbondedForce + # modelling non-alchemical atoms only + if at_least_one_alchemical: + nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, + abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) + else: + for exception_index in range(nonbonded_force.getNumExceptions()): + # Retrieve parameters. + [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + + # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces + # must have the same number of exceptions/exclusions on CUDA platform. + for force in all_custom_nonbonded_forces: + force.addExclusion(iatom, jatom) + + # Check how many alchemical atoms we have + both_alchemical = iatom in alchemical_atomset_0 and jatom in alchemical_atomset_0 + at_least_one_alchemical = iatom in alchemical_atomset_0 or jatom in alchemical_atomset_0 + only_one_alchemical = at_least_one_alchemical and not both_alchemical + + # Check if this is an exception or an exclusion + is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 + is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 + + # If this is an electrostatic exception and we're using exact PME, + # we just have to add the exception offset to the NonbondedForce. + if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: + nonbonded_force.addExceptionParameterOffset('lambda_electrostatics'+region_names[0], exception_index, + chargeprod, 0.0, 0.0) + + # If exception (and not exclusion), add special CustomBondForce terms to + # handle alchemically-modified Lennard-Jones and electrostatics exceptions + if both_alchemical: + if is_exception_epsilon: + aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) + if is_exception_chargeprod and not use_exact_pme_treatment: + aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) + elif only_one_alchemical: + if is_exception_epsilon: + na_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) + if is_exception_chargeprod and not use_exact_pme_treatment: + na_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) + # else: both particles are non-alchemical, leave them in the unmodified NonbondedForce + + # Turn off all exception contributions from alchemical atoms in the NonbondedForce + # modelling non-alchemical atoms only + if at_least_one_alchemical: + nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, + abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) + + # Add global parameters to forces. + def add_global_parameters(force): + force.addGlobalParameter('softcore_alpha', alchemical_region.softcore_alpha) + force.addGlobalParameter('softcore_beta', alchemical_region.softcore_beta) + force.addGlobalParameter('softcore_a', alchemical_region.softcore_a) + force.addGlobalParameter('softcore_b', alchemical_region.softcore_b) + force.addGlobalParameter('softcore_c', alchemical_region.softcore_c) + force.addGlobalParameter('softcore_d', alchemical_region.softcore_d) + force.addGlobalParameter('softcore_e', alchemical_region.softcore_e) + force.addGlobalParameter('softcore_f', alchemical_region.softcore_f) + + all_custom_forces = (all_custom_nonbonded_forces + + all_sterics_custom_bond_forces + + all_electrostatics_custom_bond_forces) + for force in all_custom_forces: + add_global_parameters(force) + + # With exact treatment of PME electrostatics, the NonbondedForce + # is affected by lambda electrostatics as well. + if 'lambda_sterics{}'.format(region_names[0]) not in forces_by_lambda: + forces_by_lambda = { + 'lambda_electrostatics{}'.format(region_names[0]): all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces, + 'lambda_sterics{}'.format(region_names[0]): all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces, + } + else: + forces_by_lambda['lambda_electrostatics{}'.format(region_names[0])].extend(all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces) + forces_by_lambda['lambda_sterics{}'.format(region_names[0])].extend(all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces) if use_exact_pme_treatment: - forces_by_lambda['lambda_electrostatics'].append(nonbonded_force) + forces_by_lambda['lambda_electrostatics{}'.format(region_names[0])].append(nonbonded_force) else: forces_by_lambda[''] = [nonbonded_force] return forces_by_lambda From cdcd7ba666339d0b42b8c5122efb5e54678fcb26 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Thu, 13 Jun 2019 16:07:14 +0100 Subject: [PATCH 038/152] fix bugs --- openmmtools/alchemy.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 0f780817a..1afa9a31f 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1514,9 +1514,11 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region pairs = (list(itertools.combinations(populated_region_ids, 2))) region_permus += pairs + # Create a copy of the NonbondedForce to handle particle interactions and + # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). + nonbonded_force = copy.deepcopy(reference_force) #Perform tasks that do not need to be repeated for all regions i.e.Fix any NonbondedForce issues with Lennard-Jones sigma = 0 # Fix any NonbondedForce issues with Lennard-Jones sigma = 0 (epsilon = 0), which should have sigma > 0. - nonbonded_force = copy.deepcopy(reference_force) for particle_index in range(nonbonded_force.getNumParticles()): # Retrieve parameters. [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) @@ -1552,7 +1554,6 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region else: region_names = ['_' + alchemical_region_0.region_name, '_' + alchemical_region_1.region_name] - # -------------------------------------------------- # Determine energy expression for all custom forces # -------------------------------------------------- @@ -1625,10 +1626,6 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # | (only without exact PME treatment) | # -------------------------------------------------------------------------------------------------- - # Create a copy of the NonbondedForce to handle particle interactions and - # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). - nonbonded_force = copy.deepcopy(reference_force) - def create_force(force_cls, energy_expression, lambda_variable_name, region_names, is_lambda_controlled): """Shortcut to create a lambda-controlled custom forces.""" if is_lambda_controlled: @@ -1678,6 +1675,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name if use_exact_pme_treatment: for region_name in region_names: nonbonded_force.addGlobalParameter('lambda_electrostatics{}'.format(region_name), 1.0) + #Do i need to add cross terms? if len(region_names) > 1: nonbonded_force.addGlobalParameter('lambda_electrostatics{}{}'.format(region_names[0], region_names[1]), 1.0) @@ -1744,13 +1742,13 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # to 1.0 for decoupled interactions in alchemical/alchemical force. if len(region_names) > 1: aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', alchemical_region.annihilate_electrostatics) + 'lambda_electrostatics', region_names, alchemical_region.annihilate_electrostatics) all_electrostatics_custom_bond_forces = [aa_electrostatics_custom_bond_force] else: na_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', is_lambda_controlled=True) + 'lambda_electrostatics', region_names, is_lambda_controlled=True) aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', alchemical_region.annihilate_electrostatics) + 'lambda_electrostatics', region_names, alchemical_region.annihilate_electrostatics) all_electrostatics_custom_bond_forces = [na_electrostatics_custom_bond_force, aa_electrostatics_custom_bond_force] # Create CustomBondForce to handle exceptions for electrostatics @@ -1832,9 +1830,10 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name logger.debug('Adding electrostatic interaction groups between {0} and the environment,' ' and {0} with itself.'.format(region_ids[0])) na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) - aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) + aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) #Need to handle interactions between non interacting alchemical regions if we are using excat PME + # can't use interaction groups for nonbonded # --------------------------------------------------------------- # Distribute exceptions contributions in appropriate bond forces From c61bd9712fb3fb9d723b2670e2c680ed9e4c72a4 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Tue, 18 Jun 2019 16:09:12 +0100 Subject: [PATCH 039/152] [WIP] PME not working --- openmmtools/alchemy.py | 83 +++++++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 38 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 1afa9a31f..9afa18ba6 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -34,7 +34,6 @@ # ============================================================================= # GLOBAL IMPORTS # ============================================================================= - import copy import logging import collections @@ -1541,6 +1540,8 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # Fix it. nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) + #should copy nonbonded back into reference as reference is used later + nonbonded_globalparams = [] for region_ids in region_permus: alchemical_region_0 = alchemical_regions[region_ids[0]] alchemical_region_1 = alchemical_regions[region_ids[1]] @@ -1579,6 +1580,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # Check that PME treatment is supported with the region's parameters. if use_exact_pme_treatment: + print('PME') err_msg = ' not supported with exact treatment of Ewald electrostatics.' if not alchemical_region.annihilate_electrostatics: raise ValueError('Decoupled electrostatics is' + err_msg) @@ -1643,7 +1645,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Create CustomNonbondedForces to handle sterics particle interactions between # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(region_names) >1: + if len(region_names) > 1: aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, 'lambda_sterics', region_names, is_lambda_controlled=True) all_sterics_custom_nonbonded_forces = [aa_sterics_custom_nonbonded_force] @@ -1653,7 +1655,6 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, 'lambda_sterics', region_names, alchemical_region.annihilate_sterics) all_sterics_custom_nonbonded_forces = [na_sterics_custom_nonbonded_force, aa_sterics_custom_nonbonded_force] - # Add parameters and configure CustomNonbondedForces to match reference force for force in all_sterics_custom_nonbonded_forces: force.addPerParticleParameter("sigma") # Lennard-Jones sigma @@ -1674,19 +1675,18 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # With exact PME treatment, particle electrostatics is handled through offset parameters. if use_exact_pme_treatment: for region_name in region_names: - nonbonded_force.addGlobalParameter('lambda_electrostatics{}'.format(region_name), 1.0) - #Do i need to add cross terms? - if len(region_names) > 1: - nonbonded_force.addGlobalParameter('lambda_electrostatics{}{}'.format(region_names[0], - region_names[1]), 1.0) + if 'lambda_electrostatics{}'.format(region_name) not in nonbonded_globalparams: + nonbonded_globalparams.append('lambda_electrostatics{}'.format(region_name)) + nonbonded_force.addGlobalParameter('lambda_electrostatics{}'.format(region_name), 1.0) all_electrostatics_custom_nonbonded_forces = [] + else: # Create CustomNonbondedForces to handle electrostatics particle interactions between # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda # to 1.0 for decoupled interactions in alchemical/alchemical force. if len(region_names) > 1: aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', region_names, alchemical_region.annihilate_electrostatics) + 'lambda_electrostatics', region_names, is_lambda_controlled=True) all_electrostatics_custom_nonbonded_forces = [aa_electrostatics_custom_nonbonded_force] else: na_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, @@ -1720,7 +1720,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # to 1.0 for decoupled interactions in alchemical/alchemical force. if len(region_names) > 1: aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', region_names, alchemical_region.annihilate_sterics) + 'lambda_sterics', region_names, is_lambda_controlled=True) all_sterics_custom_bond_forces = [aa_sterics_custom_bond_force] else: na_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, @@ -1742,7 +1742,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # to 1.0 for decoupled interactions in alchemical/alchemical force. if len(region_names) > 1: aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', region_names, alchemical_region.annihilate_electrostatics) + 'lambda_electrostatics', region_names, is_lambda_controlled=True) all_electrostatics_custom_bond_forces = [aa_electrostatics_custom_bond_force] else: na_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, @@ -1773,7 +1773,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # must have the same particles. for particle_index in range(nonbonded_force.getNumParticles()): # Retrieve nonbonded parameters. - [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) # Set sterics parameters in CustomNonbondedForces. for force in all_sterics_custom_nonbonded_forces: force.addParticle([sigma, epsilon]) @@ -1783,22 +1783,24 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Set offset parameters in NonbondedForce. if use_exact_pme_treatment: if len(region_names) > 1: - if particle_index in alchemical_atomset_0: - nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[0], particle_index, - charge, 0.0, 0.0) - elif particle_index in alchemical_atomset_1: - nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[1], particle_index, - charge, 0.0, 0.0) + pass + #if particle_index in alchemical_atomset_0: + # nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[0], particle_index, + # charge, 0.0, 0.0) + #elif particle_index in alchemical_atomset_1: + # nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[1], particle_index, + # charge, 0.0, 0.0) else: if use_exact_pme_treatment and particle_index in alchemical_atomset_0: - nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[0], particle_index, - charge, 0.0, 0.0) + print(particle_index, 'lambda_electrostatics{}'.format(region_names[0])) + nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(region_names[0]), + particle_index, charge, 0.0, 0.0) # Turn off interactions contribution from alchemically-modified particles in unmodified # NonbondedForce that will be handled by all other forces for particle_index in range(nonbonded_force.getNumParticles()): # Retrieve parameters. - [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) # Even with exact treatment of the PME electrostatics, we turn off # the NonbondedForce charge which is modeled by the offset parameter. if particle_index in alchemical_atomset_0 or particle_index in alchemical_atomset_1: @@ -1810,6 +1812,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name if self.interactions[region_ids]: #Regions interacting logger.debug('Adding a steric interaction group between groups {}.'.format(region_ids)) aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) + else: #Regions noninteracting logger.debug('Skipping steric interaction group for {} as they are non-interacting.'.format(region_ids)) else: #One region @@ -1831,9 +1834,11 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name ' and {0} with itself.'.format(region_ids[0])) na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) - - #Need to handle interactions between non interacting alchemical regions if we are using excat PME - # can't use interaction groups for nonbonded + else: + pass + #add exclusions + #Need to handle interactions between non interacting alchemical regions if we are using excat PME + # can't use interaction groups for nonbonded # --------------------------------------------------------------- # Distribute exceptions contributions in appropriate bond forces @@ -1845,7 +1850,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name if len(region_names) > 1: for exception_index in range(nonbonded_force.getNumExceptions()): # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces # must have the same number of exceptions/exclusions on CUDA platform. @@ -1856,16 +1861,17 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name both_alchemical = iatom in alchemical_atomset_0 and jatom in alchemical_atomset_1 at_least_one_alchemical = iatom in alchemical_atomset_0 or jatom in alchemical_atomset_1 + # Check if this is an exception or an exclusion is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 # If this is an electrostatic exception and we're using exact PME, # we just have to add the exception offset to the NonbondedForce. - if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: - for region_name in region_names: - nonbonded_force.addExceptionParameterOffset('lambda_electrostatics'+region_name, exception_index, - chargeprod, 0.0, 0.0) + #if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: + # for region_name in region_names: + # nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_name), + # exception_index, chargeprod, 0.0, 0.0) # If exception (and not exclusion), add special CustomBondForce terms to # handle alchemically-modified Lennard-Jones and electrostatics exceptions @@ -1883,7 +1889,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name else: for exception_index in range(nonbonded_force.getNumExceptions()): # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces # must have the same number of exceptions/exclusions on CUDA platform. @@ -1902,8 +1908,9 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # If this is an electrostatic exception and we're using exact PME, # we just have to add the exception offset to the NonbondedForce. if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: - nonbonded_force.addExceptionParameterOffset('lambda_electrostatics'+region_names[0], exception_index, - chargeprod, 0.0, 0.0) + print(exception_index, 'lambda_electrostatics{}'.format(region_names[0])) + nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_names[0]), + exception_index, chargeprod, 0.0, 0.0) # If exception (and not exclusion), add special CustomBondForce terms to # handle alchemically-modified Lennard-Jones and electrostatics exceptions @@ -1944,18 +1951,18 @@ def add_global_parameters(force): # With exact treatment of PME electrostatics, the NonbondedForce # is affected by lambda electrostatics as well. - if 'lambda_sterics{}'.format(region_names[0]) not in forces_by_lambda: - forces_by_lambda = { - 'lambda_electrostatics{}'.format(region_names[0]): all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces, - 'lambda_sterics{}'.format(region_names[0]): all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces, - } - else: + if 'lambda_sterics{}'.format(region_names[0]) in forces_by_lambda: forces_by_lambda['lambda_electrostatics{}'.format(region_names[0])].extend(all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces) forces_by_lambda['lambda_sterics{}'.format(region_names[0])].extend(all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces) + else: + forces_by_lambda.update({'lambda_electrostatics{}'.format(region_names[0]): all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces}) + forces_by_lambda.update({'lambda_sterics{}'.format(region_names[0]): all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces}) if use_exact_pme_treatment: forces_by_lambda['lambda_electrostatics{}'.format(region_names[0])].append(nonbonded_force) else: forces_by_lambda[''] = [nonbonded_force] + for k, v in forces_by_lambda.items(): + print(k, v) return forces_by_lambda def _alchemically_modify_AmoebaMultipoleForce(self, reference_force, alchemical_region): From 399e4f416fe2efd9d1e773eaaee314301b2be2d3 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Mon, 24 Jun 2019 15:21:09 +0100 Subject: [PATCH 040/152] [WIP] PME working --- openmmtools/alchemy.py | 246 ++++++++++++++++++----------------------- 1 file changed, 109 insertions(+), 137 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 9afa18ba6..895900645 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -620,8 +620,7 @@ class AbsoluteAlchemicalFactory(object): def __init__(self, consistent_exceptions=False, switch_width=1.0*unit.angstroms, alchemical_pme_treatment='exact', alchemical_rf_treatment='switched', - disable_alchemical_dispersion_correction=False, split_alchemical_forces=True, - noninteracting_pairs=[]): + disable_alchemical_dispersion_correction=False, split_alchemical_forces=True): self.consistent_exceptions = consistent_exceptions self.switch_width = switch_width @@ -629,10 +628,8 @@ def __init__(self, consistent_exceptions=False, switch_width=1.0*unit.angstroms, self.alchemical_rf_treatment = alchemical_rf_treatment self.disable_alchemical_dispersion_correction = disable_alchemical_dispersion_correction self.split_alchemical_forces = split_alchemical_forces - self.noninteracting_pairs = noninteracting_pairs - self.interactions = {} - def create_alchemical_system(self, reference_system, alchemical_regions): + def create_alchemical_system(self, reference_system, alchemical_regions, alchemical_regions_interactions=None): """Create an alchemically modified version of the reference system. To alter the alchemical state of the returned system use AlchemicalState. @@ -644,8 +641,8 @@ def create_alchemical_system(self, reference_system, alchemical_regions): alchemical system. This will not be modified. alchemical_regions : AlchemicalRegion The region of the reference system to alchemically soften. - noninteracting_pairs : list, default empty - List of tuples of indexes of non-interacting alchemical regions + alchemical_regions_interactions : + set of pairs for interacting regions Returns ------- @@ -653,11 +650,15 @@ def create_alchemical_system(self, reference_system, alchemical_regions): Alchemically-modified version of reference_system. """ + logger.debug('Dictionary of if alchemical regions are interacting: {}'.format(alchemical_regions_interactions)) if not isinstance(alchemical_regions, AlchemicalRegion): logger.debug('Using %s alchemical regions' % (len(alchemical_regions))) else: alchemical_regions = [alchemical_regions] + if alchemical_regions_interactions is None: + alchemical_regions_interactions = set() + # Resolve alchemical region. alchemical_regions = [self._resolve_alchemical_region(reference_system, alchemical_region) for alchemical_region in alchemical_regions] @@ -686,24 +687,6 @@ def create_alchemical_system(self, reference_system, alchemical_regions): if len(alchemical_region_names) != len(alchemical_regions): raise ValueError('Two alchemical regions have the same name') - # generating the dictionary of interactions - self.noninteracting_pairs = [sorted(x) for x in self.noninteracting_pairs] # make sure the ordering of pairs is consistent - all_pairs = itertools.combinations_with_replacement(range(len(alchemical_regions)), 2) - for pair in all_pairs: - if pair[0] == pair[1]: - # all intra-alchemical region interations must be set to true - if pair in self.noninteracting_pairs: - logger.error('Intra-alchemical region interactions must be on.' - ' Pair {} cannot be in noninteracting_pairs'.format(pair)) - self.interactions[pair] = True - else: # inter-region interactions - if sorted(pair) not in self.noninteracting_pairs: - self.interactions[pair] = True # by default, alchemical regions will 'see' eachother - else: - self.interactions[pair] = False # interactions between pairs in noninteracting_pairs should be set to False - - logger.debug('Dictionary of if alchemical regions are interacting: {}'.format(self.interactions)) - # Record timing statistics. timer = utils.Timer() timer.start('Create alchemically modified system') @@ -737,7 +720,8 @@ def create_alchemical_system(self, reference_system, alchemical_regions): # The reference system force will be deleted. forces_to_remove.append(force_index) # Collect all the Force objects modeling the reference force. - alchemical_forces = alchemical_force_creator_func(reference_force, alchemical_regions) + alchemical_forces = alchemical_force_creator_func(reference_force, alchemical_regions, + alchemical_regions_interactions) for lambda_variable_name, lambda_forces in alchemical_forces.items(): try: alchemical_forces_by_lambda[lambda_variable_name].extend(lambda_forces) @@ -1094,7 +1078,7 @@ def _add_alchemical_forces(self, alchemical_system, alchemical_forces_by_lambda) alchemical_system.addForce(force) @staticmethod - def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_regions): + def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of PeriodicTorsionForce. Parameters @@ -1158,7 +1142,7 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region return alchemical_forces @staticmethod - def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions): + def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of HarmonicAngleForce Parameters @@ -1219,7 +1203,7 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions) return alchemical_forces @staticmethod - def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions): + def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of HarmonicBondForce Parameters @@ -1439,7 +1423,7 @@ def _get_pme_direct_space_unique_expression(self, reference_force): "alpha_ewald = {};").format(alpha_ewald) return pme_expression - def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_regions): + def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of NonbondedForce. Parameters @@ -1487,108 +1471,113 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region forces_by_lambda = {} all_alchemical_atoms = set() - populated_region_ids = [] - non_pairs = [] + all_alchemical_atoms_by_region = [] # Don't create a force if there are no alchemical atoms. - for region_id, alchemical_region in enumerate(alchemical_regions): + for alchemical_region in alchemical_regions: if not len(alchemical_region.alchemical_atoms) == 0: - non_pairs.append((region_id, region_id)) - populated_region_ids.append(region_id) all_alchemical_atoms.update(alchemical_region.alchemical_atoms) + all_alchemical_atoms_by_region.append(alchemical_region.alchemical_atoms) # Don't create a force if there are no alchemical atoms. if len(all_alchemical_atoms) == 0: return {'': [copy.deepcopy(reference_force)]} - #Generate all pair of regions - region_permus = non_pairs - if len(populated_region_ids) > 1: - for alchemical_region in alchemical_regions: - if alchemical_region.region_name == None: - raise ValueError('For a alchemical calculation with multiple regions interacting via Nonbonded Forces ' - 'all regions populated with atoms should be named') - #Region_permus is all permutations of alchemical regions so we can deal with interactions between - # alchemical regions (aa)(pairs). And the standard interactions of the individual alchemical regions (non_pairs) - #with themselves (aa)(non_pair) and the non-alcemical regions (na)(non_pair) - pairs = (list(itertools.combinations(populated_region_ids, 2))) - region_permus += pairs - - # Create a copy of the NonbondedForce to handle particle interactions and - # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). - nonbonded_force = copy.deepcopy(reference_force) - #Perform tasks that do not need to be repeated for all regions i.e.Fix any NonbondedForce issues with Lennard-Jones sigma = 0 + #Perform tasks that do not need to be repeated for all alchemical regions # Fix any NonbondedForce issues with Lennard-Jones sigma = 0 (epsilon = 0), which should have sigma > 0. - for particle_index in range(nonbonded_force.getNumParticles()): + for particle_index in range(reference_force.getNumParticles()): # Retrieve parameters. - [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) # Check particle sigma is not zero. if (sigma == 0.0 * unit.angstrom): warning_msg = 'particle %d has Lennard-Jones sigma = 0 (charge=%s, sigma=%s, epsilon=%s); setting sigma=1A' logger.warning(warning_msg % (particle_index, str(charge), str(sigma), str(epsilon))) sigma = 1.0 * unit.angstrom # Fix it. - nonbonded_force.setParticleParameters(particle_index, charge, sigma, epsilon) + reference_force.setParticleParameters(particle_index, charge, sigma, epsilon) - for exception_index in range(nonbonded_force.getNumExceptions()): + for exception_index in range(reference_force.getNumExceptions()): # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) # Check particle sigma is not zero. if (sigma == 0.0 * unit.angstrom): warning_msg = 'exception %d has Lennard-Jones sigma = 0 (iatom=%d, jatom=%d, chargeprod=%s, sigma=%s, epsilon=%s); setting sigma=1A' logger.warning(warning_msg % (exception_index, iatom, jatom, str(chargeprod), str(sigma), str(epsilon))) sigma = 1.0 * unit.angstrom # Fix it. - nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) - - #should copy nonbonded back into reference as reference is used later - nonbonded_globalparams = [] - for region_ids in region_permus: - alchemical_region_0 = alchemical_regions[region_ids[0]] - alchemical_region_1 = alchemical_regions[region_ids[1]] - #Generate region names - if alchemical_region_0.alchemical_atoms == alchemical_region_1.alchemical_atoms: - if alchemical_region_0.region_name == None: - #case where only single populated region which is unnamed - region_names = [''] + reference_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) + + # Define energy expression for electrostatics based on nonbonded method. + nonbonded_method = reference_force.getNonbondedMethod() + is_ewald_method = nonbonded_method in [openmm.NonbondedForce.Ewald, + openmm.NonbondedForce.PME] + is_rf_method = nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, + openmm.NonbondedForce.CutoffNonPeriodic] + is_periodic_method = is_ewald_method or nonbonded_method == openmm.NonbondedForce.CutoffPeriodic + use_exact_pme_treatment = is_ewald_method and self.alchemical_pme_treatment == 'exact' + + # Warn about reaction field. + if is_rf_method: + logger.warning('Reaction field support is still experimental. For free energy ' + 'calculations in explicit solvent, we suggest using PME for now.') + + # Check that PME treatment is supported with the region's parameters. + if use_exact_pme_treatment: + for alchemical_region in alchemical_regions: + err_msg = ' not supported with exact treatment of Ewald electrostatics.' + if not alchemical_region.annihilate_electrostatics: + raise ValueError('Decoupled electrostatics is' + err_msg) + if self.consistent_exceptions: + raise ValueError('Consistent exceptions are' + err_msg) + if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): + raise ValueError('Softcore electrostatics is' + err_msg) + + if use_exact_pme_treatment: + # Exclude noninteracting alchemical regions from seeing each other in the nonbonded + for x, y in itertools.combinations(range(len(alchemical_regions)), 2): + if (x, y) not in alchemical_regions_interactions: + for atom1 in alchemical_regions[x].alchemical_atoms: + for atom2 in alchemical_regions[y].alchemical_atoms: + reference_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) else: - region_names = ['_' + alchemical_region_0.region_name] - else: - region_names = ['_' + alchemical_region_0.region_name, '_' + alchemical_region_1.region_name] + region_names = ('_'+alchemical_regions[x].region_name, '_'+alchemical_regions[y].region_name) + logger.debug('Adding a electrostatic interaction group between groups {}.'.format(region_names)) + del region_names + # Create a copy of the NonbondedForce to handle particle interactions and + # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). + nonbonded_force = copy.deepcopy(reference_force) + + # With exact PME treatment, particle electrostatics is handled through offset parameters. + if use_exact_pme_treatment: + for alchemical_region in alchemical_regions: + nonbonded_force.addGlobalParameter('lambda_electrostatics_{}'.format(alchemical_region.region_name), 1.0) + + #Make of list of all single and double permutations of alchemical regions + single_regions = [[alchemical_region] for alchemical_region in alchemical_regions] + if alchemical_regions_interactions == set(): + pair_regions = [] + else: + #Only generate pairs of alchemical regions specified by alchemical_regions_interactions + pair_regions = [[alchemical_regions[x[0]], alchemical_regions[x[1]]] for x in + alchemical_regions_interactions] + + #Iterate over all single and double permutations of alchemical regions to build all interactions + for alchemical_regions_pairs in single_regions+pair_regions: + #Make a list of region names for the alchemical regions interactions which are being built + region_names = [] + for alchemical_region in alchemical_regions_pairs: + region_names.append('_'+alchemical_region.region_name) # -------------------------------------------------- # Determine energy expression for all custom forces # -------------------------------------------------- + #Get steric energy exspressions sterics_mixing_rules, exceptions_sterics_energy_expression = self._get_sterics_energy_expressions(region_names) # Define energy expression for sterics. sterics_energy_expression = exceptions_sterics_energy_expression + sterics_mixing_rules - # Define energy expression for electrostatics based on nonbonded method. - nonbonded_method = reference_force.getNonbondedMethod() - is_ewald_method = nonbonded_method in [openmm.NonbondedForce.Ewald, - openmm.NonbondedForce.PME] - is_rf_method = nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, - openmm.NonbondedForce.CutoffNonPeriodic] - is_periodic_method = is_ewald_method or nonbonded_method == openmm.NonbondedForce.CutoffPeriodic - use_exact_pme_treatment = is_ewald_method and self.alchemical_pme_treatment == 'exact' - - # Warn about reaction field. - if is_rf_method: - logger.warning('Reaction field support is still experimental. For free energy ' - 'calculations in explicit solvent, we suggest using PME for now.') - - # Check that PME treatment is supported with the region's parameters. - if use_exact_pme_treatment: - print('PME') - err_msg = ' not supported with exact treatment of Ewald electrostatics.' - if not alchemical_region.annihilate_electrostatics: - raise ValueError('Decoupled electrostatics is' + err_msg) - if self.consistent_exceptions: - raise ValueError('Consistent exceptions are' + err_msg) - if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): - raise ValueError('Softcore electrostatics is' + err_msg) - else: + if not use_exact_pme_treatment: # There's no CustomNonbondedForce that models electrostatics if we use exact # PME treatment. Electrostatics is modeled through offset parameters. energy_expressions = self._get_electrostatics_energy_expressions(reference_force, region_names) @@ -1672,14 +1661,9 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name else: force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) - # With exact PME treatment, particle electrostatics is handled through offset parameters. if use_exact_pme_treatment: - for region_name in region_names: - if 'lambda_electrostatics{}'.format(region_name) not in nonbonded_globalparams: - nonbonded_globalparams.append('lambda_electrostatics{}'.format(region_name)) - nonbonded_force.addGlobalParameter('lambda_electrostatics{}'.format(region_name), 1.0) + #electrostatics are handled by offset all_electrostatics_custom_nonbonded_forces = [] - else: # Create CustomNonbondedForces to handle electrostatics particle interactions between # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda @@ -1761,8 +1745,12 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # ------------------------------------------------------------------------------- # Create atom groups. - alchemical_atomset_0 = alchemical_region_0.alchemical_atoms - alchemical_atomset_1 = alchemical_region_1.alchemical_atoms + if len(region_names) > 1: + alchemical_atomset_0 = alchemical_regions_pairs[0].alchemical_atoms + alchemical_atomset_1 = alchemical_regions_pairs[1].alchemical_atoms + else: + alchemical_atomset_0 = alchemical_regions_pairs[0].alchemical_atoms + alchemical_atomset_1 = alchemical_regions_pairs[0].alchemical_atoms all_atomset = set(range(reference_force.getNumParticles())) # all atoms, including alchemical region nonalchemical_atomset = all_atomset.difference(all_alchemical_atoms) @@ -1783,16 +1771,12 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Set offset parameters in NonbondedForce. if use_exact_pme_treatment: if len(region_names) > 1: + #What if regions can see each other? Can't scale by lam0 and lam1 here otherwise lam0 will turn region + # one off an vice versa + #going to have to use a custom for when region sees region pass - #if particle_index in alchemical_atomset_0: - # nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[0], particle_index, - # charge, 0.0, 0.0) - #elif particle_index in alchemical_atomset_1: - # nonbonded_force.addParticleParameterOffset('lambda_electrostatics'+region_names[1], particle_index, - # charge, 0.0, 0.0) else: if use_exact_pme_treatment and particle_index in alchemical_atomset_0: - print(particle_index, 'lambda_electrostatics{}'.format(region_names[0])) nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(region_names[0]), particle_index, charge, 0.0, 0.0) @@ -1809,36 +1793,27 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. #Sterics if len(region_names) > 1: #Multi region - if self.interactions[region_ids]: #Regions interacting - logger.debug('Adding a steric interaction group between groups {}.'.format(region_ids)) - aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) - - else: #Regions noninteracting - logger.debug('Skipping steric interaction group for {} as they are non-interacting.'.format(region_ids)) + logger.debug('Adding a steric interaction group between groups {}.'.format(region_names)) + aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) else: #One region logger.debug('Adding steric interaction groups between {0} and the environment,' - ' and {0} with itself.'.format(region_ids[0])) + ' and {0} with itself.'.format(region_names)) na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) #Electrostatics if not use_exact_pme_treatment: if len(region_names) > 1: #Multi region - if self.interactions[region_ids]: #Regions interacting - logger.debug('Adding a electrostatic interaction group between groups {}.'.format(region_ids)) - aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) - else: #Regions noninteracting - logger.debug('Skipping electrelectrostatic interaction group for {}' - ' as they are non-interacting.'.format(region_ids)) + logger.debug('Adding a electrostatic interaction group between groups {}.'.format(region_names)) + aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) else: #One region logger.debug('Adding electrostatic interaction groups between {0} and the environment,' - ' and {0} with itself.'.format(region_ids[0])) + ' and {0} with itself.'.format(region_names)) na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) else: + #Using the nonbonded force to handle electrostatics + # and the "interaction groups" in the nonbonded have already been handled by exclusions. pass - #add exclusions - #Need to handle interactions between non interacting alchemical regions if we are using excat PME - # can't use interaction groups for nonbonded # --------------------------------------------------------------- # Distribute exceptions contributions in appropriate bond forces @@ -1861,17 +1836,17 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name both_alchemical = iatom in alchemical_atomset_0 and jatom in alchemical_atomset_1 at_least_one_alchemical = iatom in alchemical_atomset_0 or jatom in alchemical_atomset_1 - # Check if this is an exception or an exclusion is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 + #NOT SURE ABOUT THIS CAN WE HAVE MULTIPLE OFFSETS FOR ONE EXCLUSION? # If this is an electrostatic exception and we're using exact PME, # we just have to add the exception offset to the NonbondedForce. - #if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: - # for region_name in region_names: - # nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_name), - # exception_index, chargeprod, 0.0, 0.0) + if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: + for region_name in region_names: + nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_name), + exception_index, chargeprod, 0.0, 0.0) # If exception (and not exclusion), add special CustomBondForce terms to # handle alchemically-modified Lennard-Jones and electrostatics exceptions @@ -1908,7 +1883,6 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # If this is an electrostatic exception and we're using exact PME, # we just have to add the exception offset to the NonbondedForce. if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: - print(exception_index, 'lambda_electrostatics{}'.format(region_names[0])) nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_names[0]), exception_index, chargeprod, 0.0, 0.0) @@ -1961,8 +1935,6 @@ def add_global_parameters(force): forces_by_lambda['lambda_electrostatics{}'.format(region_names[0])].append(nonbonded_force) else: forces_by_lambda[''] = [nonbonded_force] - for k, v in forces_by_lambda.items(): - print(k, v) return forces_by_lambda def _alchemically_modify_AmoebaMultipoleForce(self, reference_force, alchemical_region): From e367907733a163cec8fa084bfa85b37a2625eace Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Mon, 24 Jun 2019 16:58:04 +0100 Subject: [PATCH 041/152] change offset behaviour --- openmmtools/alchemy.py | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 895900645..e3a6f4289 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1750,7 +1750,6 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name alchemical_atomset_1 = alchemical_regions_pairs[1].alchemical_atoms else: alchemical_atomset_0 = alchemical_regions_pairs[0].alchemical_atoms - alchemical_atomset_1 = alchemical_regions_pairs[0].alchemical_atoms all_atomset = set(range(reference_force.getNumParticles())) # all atoms, including alchemical region nonalchemical_atomset = all_atomset.difference(all_alchemical_atoms) @@ -1769,16 +1768,9 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name for force in all_electrostatics_custom_nonbonded_forces: force.addParticle([charge, sigma]) # Set offset parameters in NonbondedForce. - if use_exact_pme_treatment: - if len(region_names) > 1: - #What if regions can see each other? Can't scale by lam0 and lam1 here otherwise lam0 will turn region - # one off an vice versa - #going to have to use a custom for when region sees region - pass - else: - if use_exact_pme_treatment and particle_index in alchemical_atomset_0: - nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(region_names[0]), - particle_index, charge, 0.0, 0.0) + if use_exact_pme_treatment and particle_index in alchemical_atomset_0 and len(region_names) == 1: + nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(region_names[0]), + particle_index, charge, 0.0, 0.0) # Turn off interactions contribution from alchemically-modified particles in unmodified # NonbondedForce that will be handled by all other forces @@ -1787,7 +1779,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) # Even with exact treatment of the PME electrostatics, we turn off # the NonbondedForce charge which is modeled by the offset parameter. - if particle_index in alchemical_atomset_0 or particle_index in alchemical_atomset_1: + if particle_index in alchemical_atomset_0: nonbonded_force.setParticleParameters(particle_index, abs(0.0*charge), sigma, abs(0*epsilon)) # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. @@ -1840,13 +1832,10 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 - #NOT SURE ABOUT THIS CAN WE HAVE MULTIPLE OFFSETS FOR ONE EXCLUSION? - # If this is an electrostatic exception and we're using exact PME, - # we just have to add the exception offset to the NonbondedForce. - if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: - for region_name in region_names: - nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_name), - exception_index, chargeprod, 0.0, 0.0) + if use_exact_pme_treatment and both_alchemical and is_exception_chargeprod: + # Not sure how to deal with this case. Exception should be scaled by lam0*lam1. + # However we can only have one Offset parameter per exception? + raise ValueError('Cannot have exception that straddles two alchemical regions') # If exception (and not exclusion), add special CustomBondForce terms to # handle alchemically-modified Lennard-Jones and electrostatics exceptions @@ -1882,7 +1871,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # If this is an electrostatic exception and we're using exact PME, # we just have to add the exception offset to the NonbondedForce. - if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: + if use_exact_pme_treatment and only_one_alchemical and is_exception_chargeprod: nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_names[0]), exception_index, chargeprod, 0.0, 0.0) From a5492542dde2f8c8c8bdcdcc645841c8e4825487 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Mon, 24 Jun 2019 17:09:11 +0100 Subject: [PATCH 042/152] correct error in exceptions --- openmmtools/alchemy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index e3a6f4289..84a466099 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1871,7 +1871,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # If this is an electrostatic exception and we're using exact PME, # we just have to add the exception offset to the NonbondedForce. - if use_exact_pme_treatment and only_one_alchemical and is_exception_chargeprod: + if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_names[0]), exception_index, chargeprod, 0.0, 0.0) From fbaeb11d4d744a4c6d1b25e3535590a9e076ecff Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 26 Jun 2019 15:19:58 +0200 Subject: [PATCH 043/152] Few simplifications/style changes --- openmmtools/alchemy.py | 229 +++++++++++++++++++++++------------------ 1 file changed, 129 insertions(+), 100 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 84a466099..fa1bdec5b 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -537,8 +537,6 @@ class AbsoluteAlchemicalFactory(object): will be split in different force groups. All non-alchemical forces will maintain their original force group. If more than 32 force groups are required, an error is thrown. - noninteracting_pairs : list, default empty - List of tuples of indexes of non-interacting alchemical regions Examples -------- @@ -629,7 +627,8 @@ def __init__(self, consistent_exceptions=False, switch_width=1.0*unit.angstroms, self.disable_alchemical_dispersion_correction = disable_alchemical_dispersion_correction self.split_alchemical_forces = split_alchemical_forces - def create_alchemical_system(self, reference_system, alchemical_regions, alchemical_regions_interactions=None): + def create_alchemical_system(self, reference_system, alchemical_regions, + alchemical_regions_interactions=frozenset()): """Create an alchemically modified version of the reference system. To alter the alchemical state of the returned system use AlchemicalState. @@ -641,8 +640,10 @@ def create_alchemical_system(self, reference_system, alchemical_regions, alchemi alchemical system. This will not be modified. alchemical_regions : AlchemicalRegion The region of the reference system to alchemically soften. - alchemical_regions_interactions : - set of pairs for interacting regions + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. Returns ------- @@ -650,18 +651,14 @@ def create_alchemical_system(self, reference_system, alchemical_regions, alchemi Alchemically-modified version of reference_system. """ - logger.debug('Dictionary of if alchemical regions are interacting: {}'.format(alchemical_regions_interactions)) - if not isinstance(alchemical_regions, AlchemicalRegion): - logger.debug('Using %s alchemical regions' % (len(alchemical_regions))) - else: + logger.debug(f'Dictionary of interacting alchemical regions: {alchemical_regions_interactions}') + if isinstance(alchemical_regions, AlchemicalRegion): alchemical_regions = [alchemical_regions] + logger.debug(f'Using {len(alchemical_regions)} alchemical regions') - if alchemical_regions_interactions is None: - alchemical_regions_interactions = set() - - # Resolve alchemical region. + # Resolve alchemical regions. alchemical_regions = [self._resolve_alchemical_region(reference_system, alchemical_region) - for alchemical_region in alchemical_regions] + for alchemical_region in alchemical_regions] # Check for duplicate alchemical atoms/bonds/angles/torsions. @@ -697,12 +694,11 @@ def create_alchemical_system(self, reference_system, alchemical_regions, alchemi alchemical_system = copy.deepcopy(reference_system) # Check that there are no virtual sites to alchemically modify. - for i, alchemical_region in enumerate(alchemical_regions): - for particle_index in range(reference_system.getNumParticles()): - if (reference_system.isVirtualSite(particle_index) and - particle_index in alchemical_region.alchemical_atoms): - raise ValueError('Virtual atoms in region {}.' - 'Alchemically modified virtual sites are not supported'.format(i)) + for alchemical_region in alchemical_regions: + for particle_index in alchemical_region.atoms: + if reference_system.isVirtualSite(particle_index): + raise ValueError(f'Virtual atoms in region {alchemical_region.region_name}.' + 'Alchemically modified virtual sites are not supported') # Modify forces as appropriate. We delete the forces that # have been processed modified at the end of the for loop. @@ -1078,7 +1074,7 @@ def _add_alchemical_forces(self, alchemical_system, alchemical_forces_by_lambda) alchemical_system.addForce(force) @staticmethod - def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_regions, alchemical_regions_interactions): + def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_regions, _): """Create alchemically-modified version of PeriodicTorsionForce. Parameters @@ -1116,33 +1112,42 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) + # Update the returned value with the non-alchemical force. + alchemical_forces[''] = [force] + # Create CustomTorsionForce to handle alchemically modified torsions. for alchemical_region in alchemical_regions: - if not len(alchemical_region.alchemical_torsions) == 0: - if alchemical_region.region_name is None: - region_name = '' - else: - region_name = '_' + alchemical_region.region_name - # Create CustomTorsionForce to handle alchemically modified torsions. - energy_function = "lambda_torsions{}*k*(1+cos(periodicity*theta-phase))".format(region_name) - custom_force = openmm.CustomTorsionForce(energy_function) - custom_force.addGlobalParameter('lambda_torsions{}'.format(region_name), 1.0) - custom_force.addPerTorsionParameter('periodicity') - custom_force.addPerTorsionParameter('phase') - custom_force.addPerTorsionParameter('k') - # Process reference torsions. - for torsion_index in sorted(alchemical_region.alchemical_torsions): - # Retrieve parameters. - particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) - # Create torsions. - custom_force.addTorsion(particle1, particle2, particle3, particle4, [periodicity, phase, k]) - alchemical_forces.update({'lambda_torsions{}'.format(region_name): [custom_force]}) + # This region may not have torsions to modify. + if len(alchemical_region.alchemical_torsions) == 0: + continue + + # Check if the lambda variable needs a suffix to identify the region. + lambda_variable_name = 'lambda_torsions' + if alchemical_region.region_name is not None: + lambda_variable_name += '_' + alchemical_region.region_name + + # Create CustomTorsionForce to handle alchemically modified torsions. + energy_function = f"{lambda_variable_name}*k*(1+cos(periodicity*theta-phase))" + custom_force = openmm.CustomTorsionForce(energy_function) + custom_force.addGlobalParameter(lambda_variable_name, 1.0) + custom_force.addPerTorsionParameter('periodicity') + custom_force.addPerTorsionParameter('phase') + custom_force.addPerTorsionParameter('k') + + # Process reference torsions. + for torsion_index in sorted(alchemical_region.alchemical_torsions): + # Retrieve parameters. + particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) + # Create torsions. + custom_force.addTorsion(particle1, particle2, particle3, particle4, [periodicity, phase, k]) + + # Update the returned value with the alchemical force. + alchemical_forces.update({lambda_variable_name: [custom_force]}) - alchemical_forces.update({'': [force]}) return alchemical_forces @staticmethod - def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, alchemical_regions_interactions): + def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, _): """Create alchemically-modified version of HarmonicAngleForce Parameters @@ -1180,30 +1185,39 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) force.addAngle(particle1, particle2, particle3, theta0, K) + # Update the returned value with the non-alchemical force. + alchemical_forces[''] = [force] + # Create CustomAngleForce to handle alchemically modified angles. for alchemical_region in alchemical_regions: - if not len(alchemical_region.alchemical_angles) == 0: - if alchemical_region.region_name is None: - region_name = '' - else: - region_name = '_' + alchemical_region.region_name - # Create CustomAngleForce to handle alchemically modified angles. - energy_function = "lambda_angles{}*(K/2)*(theta-theta0)^2;".format(region_name) - custom_force = openmm.CustomAngleForce(energy_function) - custom_force.addGlobalParameter('lambda_angles{}'.format(region_name), 1.0) - custom_force.addPerAngleParameter('theta0') - custom_force.addPerAngleParameter('K') - # Process reference angles. - for angle_index in sorted(alchemical_region.alchemical_angles): - [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) - custom_force.addAngle(particle1, particle2, particle3, [theta0, K]) - alchemical_forces.update({'lambda_bonds{}'.format(region_name): [custom_force]}) - - alchemical_forces.update({'': [force]}) + # This region may not have angles to modify. + if len(alchemical_region.alchemical_angles) == 0: + continue + + # Check if the lambda variable needs a suffix to identify the region. + lambda_variable_name = 'lambda_angles' + if alchemical_region.region_name is not None: + lambda_variable_name += '_' + alchemical_region.region_name + + # Create CustomAngleForce to handle alchemically modified angles. + energy_function = f"{lambda_variable_name}*(K/2)*(theta-theta0)^2;" + custom_force = openmm.CustomAngleForce(energy_function) + custom_force.addGlobalParameter(lambda_variable_name, 1.0) + custom_force.addPerAngleParameter('theta0') + custom_force.addPerAngleParameter('K') + + # Process reference angles. + for angle_index in sorted(alchemical_region.alchemical_angles): + [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) + custom_force.addAngle(particle1, particle2, particle3, [theta0, K]) + + # Update the returned value with the alchemical force. + alchemical_forces.update({lambda_variable_name: [custom_force]}) + return alchemical_forces @staticmethod - def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, alchemical_regions_interactions): + def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, _): """Create alchemically-modified version of HarmonicBondForce Parameters @@ -1241,37 +1255,46 @@ def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) force.addBond(particle1, particle2, theta0, K) + # Update the returned value with the non-alchemical force. + alchemical_forces[''] = [force] + for alchemical_region in alchemical_regions: - if not len(alchemical_region.alchemical_bonds) == 0: - if alchemical_region.region_name is None: - region_name = '' - else: - region_name = '_' + alchemical_region.region_name - # Define force here so that it is over writen saving only one copy. - # Create CustomBondForce to handle alchemically modified bonds. - energy_function = "lambda_bonds{}*(K/2)*(r-r0)^2;".format(region_name) - custom_force = openmm.CustomBondForce(energy_function) - custom_force.addGlobalParameter('lambda_bonds{}'.format(region_name), 1.0) - custom_force.addPerBondParameter('r0') - custom_force.addPerBondParameter('K') - # Process reference bonds. - for bond_index in sorted(alchemical_region.alchemical_bonds): - [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) - custom_force.addBond(particle1, particle2, [theta0, K]) - alchemical_forces.update({'lambda_bonds{}'.format(region_name): [custom_force]}) - - alchemical_forces.update({'': [force]}) + # This region may not have bonds to modify. + if len(alchemical_region.alchemical_bonds) == 0: + continue + + # Check if the lambda variable needs a suffix to identify the region. + lambda_variable_name = 'lambda_bonds' + if alchemical_region.region_name is not None: + lambda_variable_name += '_' + alchemical_region.region_name + + # Define force here so that it is over writen saving only one copy. + # Create CustomBondForce to handle alchemically modified bonds. + energy_function = f"{lambda_variable_name}*(K/2)*(r-r0)^2;" + custom_force = openmm.CustomBondForce(energy_function) + custom_force.addGlobalParameter(lambda_variable_name, 1.0) + custom_force.addPerBondParameter('r0') + custom_force.addPerBondParameter('K') + # Process reference bonds. + for bond_index in sorted(alchemical_region.alchemical_bonds): + [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) + custom_force.addBond(particle1, particle2, [theta0, K]) + + # Update the returned value with the alchemical force. + alchemical_forces.update({lambda_variable_name: [custom_force]}) + return alchemical_forces - def _get_sterics_energy_expressions(self, alchemical_region_indices): + def _get_sterics_energy_expressions(self, lambda_variable_suffixes): # Sterics mixing rules. - if alchemical_region_indices[0] == '': + if lambda_variable_suffixes[0] == '': lambda_variable_name = 'lambda_sterics' else: - if len(alchemical_region_indices) > 1: - lambda_variable_name = 'lambda_sterics{0}*lambda_sterics{1}'.format(alchemical_region_indices[0], alchemical_region_indices[1]) + if len(lambda_variable_suffixes) > 1: + lambda_variable_name = 'lambda_sterics{0}*lambda_sterics{1}'.format( + lambda_variable_suffixes[0], lambda_variable_suffixes[1]) else: - lambda_variable_name = 'lambda_sterics{}'.format(alchemical_region_indices[0]) + lambda_variable_name = 'lambda_sterics{}'.format(lambda_variable_suffixes[0]) sterics_mixing_rules = ('epsilon = sqrt(epsilon1*epsilon2);' # Mixing rule for epsilon. 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. @@ -1286,7 +1309,7 @@ def _get_sterics_energy_expressions(self, alchemical_region_indices): # Define energy expression for electrostatics. return sterics_mixing_rules, exceptions_sterics_energy_expression - def _get_electrostatics_energy_expressions(self, reference_force, alchemical_region_indices): + def _get_electrostatics_energy_expressions(self, reference_force, lambda_variable_suffixes): """Return the energy expressions for electrostatics. This private function assumes self._alchemical_pme_treatment != 'exact' @@ -1294,13 +1317,14 @@ def _get_electrostatics_energy_expressions(self, reference_force, alchemical_reg lambda_electrostatics is modeled through an offset parameter in a NonbondedForce. """ - if alchemical_region_indices[0] == '': + if lambda_variable_suffixes[0] == '': lambda_variable_name = 'lambda_electrostatics' else: - if len(alchemical_region_indices) > 1: - lambda_variable_name = 'lambda_electrostatics{0}*lambda_electrostatics{1}'.format(alchemical_region_indices[0], alchemical_region_indices[1]) + if len(lambda_variable_suffixes) > 1: + lambda_variable_name = 'lambda_electrostatics{0}*lambda_electrostatics{1}'.format( + lambda_variable_suffixes[0], lambda_variable_suffixes[1]) else: - lambda_variable_name = 'lambda_electrostatics{}'.format(alchemical_region_indices[0]) + lambda_variable_name = 'lambda_electrostatics{}'.format(lambda_variable_suffixes[0]) # The final expression will be prefix + method + suffix. electrostatics_prefix = ('U_electrostatics;' @@ -1471,18 +1495,20 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region forces_by_lambda = {} all_alchemical_atoms = set() - all_alchemical_atoms_by_region = [] # Don't create a force if there are no alchemical atoms. for alchemical_region in alchemical_regions: if not len(alchemical_region.alchemical_atoms) == 0: all_alchemical_atoms.update(alchemical_region.alchemical_atoms) - all_alchemical_atoms_by_region.append(alchemical_region.alchemical_atoms) + # Don't create a force if there are no alchemical atoms. if len(all_alchemical_atoms) == 0: return {'': [copy.deepcopy(reference_force)]} - #Perform tasks that do not need to be repeated for all alchemical regions + # ------------------------------------------------------------- + # Perform tasks that do not need to be repeated for all regions. + # ------------------------------------------------------------- + # Fix any NonbondedForce issues with Lennard-Jones sigma = 0 (epsilon = 0), which should have sigma > 0. for particle_index in range(reference_force.getNumParticles()): # Retrieve parameters. @@ -1550,28 +1576,30 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # With exact PME treatment, particle electrostatics is handled through offset parameters. if use_exact_pme_treatment: for alchemical_region in alchemical_regions: - nonbonded_force.addGlobalParameter('lambda_electrostatics_{}'.format(alchemical_region.region_name), 1.0) + nonbonded_force.addGlobalParameter(f'lambda_electrostatics_{alchemical_region.region_name}', 1.0) - #Make of list of all single and double permutations of alchemical regions + # Make of list of all single and double permutations of alchemical regions. single_regions = [[alchemical_region] for alchemical_region in alchemical_regions] if alchemical_regions_interactions == set(): pair_regions = [] else: - #Only generate pairs of alchemical regions specified by alchemical_regions_interactions + # Only generate pairs of alchemical regions specified by alchemical_regions_interactions. pair_regions = [[alchemical_regions[x[0]], alchemical_regions[x[1]]] for x in alchemical_regions_interactions] - #Iterate over all single and double permutations of alchemical regions to build all interactions + # Iterate over all single and double permutations of alchemical regions to build all interactions. for alchemical_regions_pairs in single_regions+pair_regions: - #Make a list of region names for the alchemical regions interactions which are being built + + # Make a list of region names for the alchemical regions interactions which are being built. region_names = [] for alchemical_region in alchemical_regions_pairs: region_names.append('_'+alchemical_region.region_name) + # -------------------------------------------------- # Determine energy expression for all custom forces # -------------------------------------------------- - #Get steric energy exspressions + # Get steric energy expressions. sterics_mixing_rules, exceptions_sterics_energy_expression = self._get_sterics_energy_expressions(region_names) # Define energy expression for sterics. @@ -1644,7 +1672,8 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, 'lambda_sterics', region_names, alchemical_region.annihilate_sterics) all_sterics_custom_nonbonded_forces = [na_sterics_custom_nonbonded_force, aa_sterics_custom_nonbonded_force] - # Add parameters and configure CustomNonbondedForces to match reference force + + # Add parameters and configure CustomNonbondedForces to match reference force. for force in all_sterics_custom_nonbonded_forces: force.addPerParticleParameter("sigma") # Lennard-Jones sigma force.addPerParticleParameter("epsilon") # Lennard-Jones epsilon From d4d496ed8ee6c7035d6f9b1db19daea0fc2ee93b Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 26 Jun 2019 15:20:51 +0200 Subject: [PATCH 044/152] Rename AlchemicalRegion.region_name to AlchemicalRegion.name --- openmmtools/alchemy.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index fa1bdec5b..faff8b9be 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -417,7 +417,7 @@ def apply_to_context(self, context): ('annihilate_sterics', False), ('softcore_alpha', 0.5), ('softcore_a', 1), ('softcore_b', 1), ('softcore_c', 6), ('softcore_beta', 0.0), ('softcore_d', 1), ('softcore_e', 1), ('softcore_f', 2), - ('region_name', None) + ('name', None) ]) @@ -680,7 +680,7 @@ def create_alchemical_system(self, reference_system, alchemical_regions, all_alchemical_elements[element_type].update(region_elements) # Check for duplicate names - alchemical_region_names = {alchemical_region.region_name for alchemical_region in alchemical_regions} + alchemical_region_names = {alchemical_region.name for alchemical_region in alchemical_regions} if len(alchemical_region_names) != len(alchemical_regions): raise ValueError('Two alchemical regions have the same name') @@ -697,7 +697,7 @@ def create_alchemical_system(self, reference_system, alchemical_regions, for alchemical_region in alchemical_regions: for particle_index in alchemical_region.atoms: if reference_system.isVirtualSite(particle_index): - raise ValueError(f'Virtual atoms in region {alchemical_region.region_name}.' + raise ValueError(f'Virtual atoms in region {alchemical_region.name}.' 'Alchemically modified virtual sites are not supported') # Modify forces as appropriate. We delete the forces that @@ -1123,8 +1123,8 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region # Check if the lambda variable needs a suffix to identify the region. lambda_variable_name = 'lambda_torsions' - if alchemical_region.region_name is not None: - lambda_variable_name += '_' + alchemical_region.region_name + if alchemical_region.name is not None: + lambda_variable_name += '_' + alchemical_region.name # Create CustomTorsionForce to handle alchemically modified torsions. energy_function = f"{lambda_variable_name}*k*(1+cos(periodicity*theta-phase))" @@ -1196,8 +1196,8 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, # Check if the lambda variable needs a suffix to identify the region. lambda_variable_name = 'lambda_angles' - if alchemical_region.region_name is not None: - lambda_variable_name += '_' + alchemical_region.region_name + if alchemical_region.name is not None: + lambda_variable_name += '_' + alchemical_region.name # Create CustomAngleForce to handle alchemically modified angles. energy_function = f"{lambda_variable_name}*(K/2)*(theta-theta0)^2;" @@ -1265,8 +1265,8 @@ def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, # Check if the lambda variable needs a suffix to identify the region. lambda_variable_name = 'lambda_bonds' - if alchemical_region.region_name is not None: - lambda_variable_name += '_' + alchemical_region.region_name + if alchemical_region.name is not None: + lambda_variable_name += '_' + alchemical_region.name # Define force here so that it is over writen saving only one copy. # Create CustomBondForce to handle alchemically modified bonds. @@ -1565,7 +1565,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region for atom2 in alchemical_regions[y].alchemical_atoms: reference_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) else: - region_names = ('_'+alchemical_regions[x].region_name, '_'+alchemical_regions[y].region_name) + region_names = ('_'+alchemical_regions[x].name, '_'+alchemical_regions[y].name) logger.debug('Adding a electrostatic interaction group between groups {}.'.format(region_names)) del region_names @@ -1576,7 +1576,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # With exact PME treatment, particle electrostatics is handled through offset parameters. if use_exact_pme_treatment: for alchemical_region in alchemical_regions: - nonbonded_force.addGlobalParameter(f'lambda_electrostatics_{alchemical_region.region_name}', 1.0) + nonbonded_force.addGlobalParameter(f'lambda_electrostatics_{alchemical_region.name}', 1.0) # Make of list of all single and double permutations of alchemical regions. single_regions = [[alchemical_region] for alchemical_region in alchemical_regions] @@ -1593,7 +1593,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # Make a list of region names for the alchemical regions interactions which are being built. region_names = [] for alchemical_region in alchemical_regions_pairs: - region_names.append('_'+alchemical_region.region_name) + region_names.append('_'+alchemical_region.name) # -------------------------------------------------- # Determine energy expression for all custom forces From e6a9a30ea3d0533c3d766f01790603261291ee48 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 26 Jun 2019 15:21:27 +0200 Subject: [PATCH 045/152] Fix bug where reference force is modified instead of copy --- openmmtools/alchemy.py | 48 ++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index faff8b9be..07a25f7c2 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1509,29 +1509,6 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # Perform tasks that do not need to be repeated for all regions. # ------------------------------------------------------------- - # Fix any NonbondedForce issues with Lennard-Jones sigma = 0 (epsilon = 0), which should have sigma > 0. - for particle_index in range(reference_force.getNumParticles()): - # Retrieve parameters. - [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) - # Check particle sigma is not zero. - if (sigma == 0.0 * unit.angstrom): - warning_msg = 'particle %d has Lennard-Jones sigma = 0 (charge=%s, sigma=%s, epsilon=%s); setting sigma=1A' - logger.warning(warning_msg % (particle_index, str(charge), str(sigma), str(epsilon))) - sigma = 1.0 * unit.angstrom - # Fix it. - reference_force.setParticleParameters(particle_index, charge, sigma, epsilon) - - for exception_index in range(reference_force.getNumExceptions()): - # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) - # Check particle sigma is not zero. - if (sigma == 0.0 * unit.angstrom): - warning_msg = 'exception %d has Lennard-Jones sigma = 0 (iatom=%d, jatom=%d, chargeprod=%s, sigma=%s, epsilon=%s); setting sigma=1A' - logger.warning(warning_msg % (exception_index, iatom, jatom, str(chargeprod), str(sigma), str(epsilon))) - sigma = 1.0 * unit.angstrom - # Fix it. - reference_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) - # Define energy expression for electrostatics based on nonbonded method. nonbonded_method = reference_force.getNonbondedMethod() is_ewald_method = nonbonded_method in [openmm.NonbondedForce.Ewald, @@ -1573,6 +1550,31 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). nonbonded_force = copy.deepcopy(reference_force) + # Fix any NonbondedForce issues with Lennard-Jones sigma = 0 (epsilon = 0), + # which should have sigma > 0. + for particle_index in range(nonbonded_force.getNumParticles()): + # Retrieve parameters. + [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + # Check particle sigma is not zero. + if sigma == 0.0 * unit.angstrom: + warning_msg = 'particle %d has Lennard-Jones sigma = 0 (charge=%s, sigma=%s, epsilon=%s); setting sigma=1A' + logger.warning(warning_msg % (particle_index, str(charge), str(sigma), str(epsilon))) + sigma = 1.0 * unit.angstrom + # Fix it. + nonbonded_force.setParticleParameters(particle_index, charge, sigma, epsilon) + + # Same for the exceptions. + for exception_index in range(nonbonded_force.getNumExceptions()): + # Retrieve parameters. + [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + # Check particle sigma is not zero. + if sigma == 0.0 * unit.angstrom: + warning_msg = 'exception %d has Lennard-Jones sigma = 0 (iatom=%d, jatom=%d, chargeprod=%s, sigma=%s, epsilon=%s); setting sigma=1A' + logger.warning(warning_msg % (exception_index, iatom, jatom, str(chargeprod), str(sigma), str(epsilon))) + sigma = 1.0 * unit.angstrom + # Fix it. + nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) + # With exact PME treatment, particle electrostatics is handled through offset parameters. if use_exact_pme_treatment: for alchemical_region in alchemical_regions: From 664f89f93ebded03c2a84fc919267fbaca8e80b4 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 26 Jun 2019 15:29:45 +0200 Subject: [PATCH 046/152] More style fixes --- openmmtools/alchemy.py | 88 +++++++++++++++++++++--------------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 07a25f7c2..2d2b6689f 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1542,8 +1542,8 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region for atom2 in alchemical_regions[y].alchemical_atoms: reference_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) else: - region_names = ('_'+alchemical_regions[x].name, '_'+alchemical_regions[y].name) - logger.debug('Adding a electrostatic interaction group between groups {}.'.format(region_names)) + region_names = (alchemical_regions[x].name, alchemical_regions[y].name) + logger.debug(f'Adding a electrostatic interaction group between groups {region_names}.') del region_names # Create a copy of the NonbondedForce to handle particle interactions and @@ -1593,16 +1593,16 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region for alchemical_regions_pairs in single_regions+pair_regions: # Make a list of region names for the alchemical regions interactions which are being built. - region_names = [] + lambda_var_suffixes = [] for alchemical_region in alchemical_regions_pairs: - region_names.append('_'+alchemical_region.name) + lambda_var_suffixes.append('_'+alchemical_region.name) # -------------------------------------------------- # Determine energy expression for all custom forces # -------------------------------------------------- # Get steric energy expressions. - sterics_mixing_rules, exceptions_sterics_energy_expression = self._get_sterics_energy_expressions(region_names) + sterics_mixing_rules, exceptions_sterics_energy_expression = self._get_sterics_energy_expressions(lambda_var_suffixes) # Define energy expression for sterics. sterics_energy_expression = exceptions_sterics_energy_expression + sterics_mixing_rules @@ -1610,7 +1610,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region if not use_exact_pme_treatment: # There's no CustomNonbondedForce that models electrostatics if we use exact # PME treatment. Electrostatics is modeled through offset parameters. - energy_expressions = self._get_electrostatics_energy_expressions(reference_force, region_names) + energy_expressions = self._get_electrostatics_energy_expressions(reference_force, lambda_var_suffixes) (electrostatics_energy_expression, exceptions_electrostatics_energy_expression) = energy_expressions # Unpack tuple. @@ -1647,16 +1647,16 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # | (only without exact PME treatment) | # -------------------------------------------------------------------------------------------------- - def create_force(force_cls, energy_expression, lambda_variable_name, region_names, is_lambda_controlled): + def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_suffixes, is_lambda_controlled): """Shortcut to create a lambda-controlled custom forces.""" if is_lambda_controlled: force = force_cls(energy_expression) - for region_name in region_names: - name = (lambda_variable_name + region_name) + for suffix in lambda_var_suffixes: + name = (lambda_variable_name + suffix) force.addGlobalParameter(name, 1.0) else: # fix lambda variable to 1.0 - for region_name in region_names: - name = (lambda_variable_name + region_name) + for suffix in lambda_var_suffixes: + name = (lambda_variable_name + suffix) energy_expression = energy_expression + name + '=1.0;' force = force_cls(energy_expression) return force @@ -1664,15 +1664,15 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Create CustomNonbondedForces to handle sterics particle interactions between # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(region_names) > 1: + if len(lambda_var_suffixes) > 1: aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', region_names, is_lambda_controlled=True) + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) all_sterics_custom_nonbonded_forces = [aa_sterics_custom_nonbonded_force] else: na_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', region_names, is_lambda_controlled=True) + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', region_names, alchemical_region.annihilate_sterics) + 'lambda_sterics', lambda_var_suffixes, alchemical_region.annihilate_sterics) all_sterics_custom_nonbonded_forces = [na_sterics_custom_nonbonded_force, aa_sterics_custom_nonbonded_force] # Add parameters and configure CustomNonbondedForces to match reference force. @@ -1699,15 +1699,15 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Create CustomNonbondedForces to handle electrostatics particle interactions between # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(region_names) > 1: + if len(lambda_var_suffixes) > 1: aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', region_names, is_lambda_controlled=True) + 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) all_electrostatics_custom_nonbonded_forces = [aa_electrostatics_custom_nonbonded_force] else: na_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', region_names, is_lambda_controlled=True) + 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', region_names, alchemical_region.annihilate_electrostatics) + 'lambda_electrostatics', lambda_var_suffixes, alchemical_region.annihilate_electrostatics) all_electrostatics_custom_nonbonded_forces = [na_electrostatics_custom_nonbonded_force, aa_electrostatics_custom_nonbonded_force] @@ -1733,15 +1733,15 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Create CustomBondForces to handle sterics 1,4 exceptions interactions between # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(region_names) > 1: + if len(lambda_var_suffixes) > 1: aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', region_names, is_lambda_controlled=True) + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) all_sterics_custom_bond_forces = [aa_sterics_custom_bond_force] else: na_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', region_names, is_lambda_controlled=True) + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', region_names, alchemical_region.annihilate_sterics) + 'lambda_sterics', lambda_var_suffixes, alchemical_region.annihilate_sterics) all_sterics_custom_bond_forces = [na_sterics_custom_bond_force, aa_sterics_custom_bond_force] for force in all_sterics_custom_bond_forces: @@ -1755,15 +1755,15 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Create CustomBondForces to handle electrostatics 1,4 exceptions interactions between # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(region_names) > 1: + if len(lambda_var_suffixes) > 1: aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', region_names, is_lambda_controlled=True) + 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) all_electrostatics_custom_bond_forces = [aa_electrostatics_custom_bond_force] else: na_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', region_names, is_lambda_controlled=True) + 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', region_names, alchemical_region.annihilate_electrostatics) + 'lambda_electrostatics', lambda_var_suffixes, alchemical_region.annihilate_electrostatics) all_electrostatics_custom_bond_forces = [na_electrostatics_custom_bond_force, aa_electrostatics_custom_bond_force] # Create CustomBondForce to handle exceptions for electrostatics @@ -1776,7 +1776,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # ------------------------------------------------------------------------------- # Create atom groups. - if len(region_names) > 1: + if len(lambda_var_suffixes) > 1: alchemical_atomset_0 = alchemical_regions_pairs[0].alchemical_atoms alchemical_atomset_1 = alchemical_regions_pairs[1].alchemical_atoms else: @@ -1799,8 +1799,8 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name for force in all_electrostatics_custom_nonbonded_forces: force.addParticle([charge, sigma]) # Set offset parameters in NonbondedForce. - if use_exact_pme_treatment and particle_index in alchemical_atomset_0 and len(region_names) == 1: - nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(region_names[0]), + if use_exact_pme_treatment and particle_index in alchemical_atomset_0 and len(lambda_var_suffixes) == 1: + nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(lambda_var_suffixes[0]), particle_index, charge, 0.0, 0.0) # Turn off interactions contribution from alchemically-modified particles in unmodified @@ -1815,22 +1815,22 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. #Sterics - if len(region_names) > 1: #Multi region - logger.debug('Adding a steric interaction group between groups {}.'.format(region_names)) + if len(lambda_var_suffixes) > 1: # Multi region + logger.debug('Adding a steric interaction group between groups {}.'.format(lambda_var_suffixes)) aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) else: #One region logger.debug('Adding steric interaction groups between {0} and the environment,' - ' and {0} with itself.'.format(region_names)) + ' and {0} with itself.'.format(lambda_var_suffixes)) na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) #Electrostatics if not use_exact_pme_treatment: - if len(region_names) > 1: #Multi region - logger.debug('Adding a electrostatic interaction group between groups {}.'.format(region_names)) + if len(lambda_var_suffixes) > 1: #Multi region + logger.debug('Adding a electrostatic interaction group between groups {}.'.format(lambda_var_suffixes)) aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) else: #One region logger.debug('Adding electrostatic interaction groups between {0} and the environment,' - ' and {0} with itself.'.format(region_names)) + ' and {0} with itself.'.format(lambda_var_suffixes)) na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) else: @@ -1845,7 +1845,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name all_custom_nonbonded_forces = all_sterics_custom_nonbonded_forces + all_electrostatics_custom_nonbonded_forces # Move all NonbondedForce exception terms for alchemically-modified particles to CustomBondForces. - if len(region_names) > 1: + if len(lambda_var_suffixes) > 1: for exception_index in range(nonbonded_force.getNumExceptions()): # Retrieve parameters. [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) @@ -1903,7 +1903,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, region_name # If this is an electrostatic exception and we're using exact PME, # we just have to add the exception offset to the NonbondedForce. if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: - nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(region_names[0]), + nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(lambda_var_suffixes[0]), exception_index, chargeprod, 0.0, 0.0) # If exception (and not exclusion), add special CustomBondForce terms to @@ -1945,14 +1945,14 @@ def add_global_parameters(force): # With exact treatment of PME electrostatics, the NonbondedForce # is affected by lambda electrostatics as well. - if 'lambda_sterics{}'.format(region_names[0]) in forces_by_lambda: - forces_by_lambda['lambda_electrostatics{}'.format(region_names[0])].extend(all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces) - forces_by_lambda['lambda_sterics{}'.format(region_names[0])].extend(all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces) + if 'lambda_sterics{}'.format(lambda_var_suffixes[0]) in forces_by_lambda: + forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])].extend(all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces) + forces_by_lambda['lambda_sterics{}'.format(lambda_var_suffixes[0])].extend(all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces) else: - forces_by_lambda.update({'lambda_electrostatics{}'.format(region_names[0]): all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces}) - forces_by_lambda.update({'lambda_sterics{}'.format(region_names[0]): all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces}) + forces_by_lambda.update({'lambda_electrostatics{}'.format(lambda_var_suffixes[0]): all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces}) + forces_by_lambda.update({'lambda_sterics{}'.format(lambda_var_suffixes[0]): all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces}) if use_exact_pme_treatment: - forces_by_lambda['lambda_electrostatics{}'.format(region_names[0])].append(nonbonded_force) + forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])].append(nonbonded_force) else: forces_by_lambda[''] = [nonbonded_force] return forces_by_lambda From 97b8c77f90e59a8f71f9026d1e647e051e531b6a Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 26 Jun 2019 15:30:15 +0200 Subject: [PATCH 047/152] Fix bug in determining nonbonded lambda variables --- openmmtools/alchemy.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 2d2b6689f..486492f41 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1595,7 +1595,10 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # Make a list of region names for the alchemical regions interactions which are being built. lambda_var_suffixes = [] for alchemical_region in alchemical_regions_pairs: - lambda_var_suffixes.append('_'+alchemical_region.name) + if alchemical_region.name is None: + lambda_var_suffixes.append('') + else: + lambda_var_suffixes.append('_' + alchemical_region.name) # -------------------------------------------------- # Determine energy expression for all custom forces From 0947a762254e4742f9d3d0d446125e407d6d75ae Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 26 Jun 2019 15:46:55 +0200 Subject: [PATCH 048/152] More PEP8 fixes --- openmmtools/alchemy.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 486492f41..eff138cac 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1669,13 +1669,13 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ # to 1.0 for decoupled interactions in alchemical/alchemical force. if len(lambda_var_suffixes) > 1: aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) all_sterics_custom_nonbonded_forces = [aa_sterics_custom_nonbonded_force] else: na_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, alchemical_region.annihilate_sterics) + 'lambda_sterics', lambda_var_suffixes, alchemical_region.annihilate_sterics) all_sterics_custom_nonbonded_forces = [na_sterics_custom_nonbonded_force, aa_sterics_custom_nonbonded_force] # Add parameters and configure CustomNonbondedForces to match reference force. @@ -1817,27 +1817,28 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ nonbonded_force.setParticleParameters(particle_index, abs(0.0*charge), sigma, abs(0*epsilon)) # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. - #Sterics + # Sterics if len(lambda_var_suffixes) > 1: # Multi region logger.debug('Adding a steric interaction group between groups {}.'.format(lambda_var_suffixes)) aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) - else: #One region + else: # One region logger.debug('Adding steric interaction groups between {0} and the environment,' ' and {0} with itself.'.format(lambda_var_suffixes)) na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) - #Electrostatics + + # Electrostatics if not use_exact_pme_treatment: - if len(lambda_var_suffixes) > 1: #Multi region + if len(lambda_var_suffixes) > 1: # Multi region logger.debug('Adding a electrostatic interaction group between groups {}.'.format(lambda_var_suffixes)) aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) - else: #One region + else: # One region logger.debug('Adding electrostatic interaction groups between {0} and the environment,' ' and {0} with itself.'.format(lambda_var_suffixes)) na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) else: - #Using the nonbonded force to handle electrostatics + # Using the nonbonded force to handle electrostatics # and the "interaction groups" in the nonbonded have already been handled by exclusions. pass @@ -1952,8 +1953,9 @@ def add_global_parameters(force): forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])].extend(all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces) forces_by_lambda['lambda_sterics{}'.format(lambda_var_suffixes[0])].extend(all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces) else: - forces_by_lambda.update({'lambda_electrostatics{}'.format(lambda_var_suffixes[0]): all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces}) - forces_by_lambda.update({'lambda_sterics{}'.format(lambda_var_suffixes[0]): all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces}) + forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])] = all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces + forces_by_lambda['lambda_sterics{}'.format(lambda_var_suffixes[0])] = all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces + if use_exact_pme_treatment: forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])].append(nonbonded_force) else: From f02ed2b742f0b78300a7df33376052a3311656fe Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 26 Jun 2019 15:56:30 +0200 Subject: [PATCH 049/152] Fix bug where exceptions where added to the reference force instead of its copy. --- openmmtools/alchemy.py | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index eff138cac..452ce486a 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1534,18 +1534,6 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): raise ValueError('Softcore electrostatics is' + err_msg) - if use_exact_pme_treatment: - # Exclude noninteracting alchemical regions from seeing each other in the nonbonded - for x, y in itertools.combinations(range(len(alchemical_regions)), 2): - if (x, y) not in alchemical_regions_interactions: - for atom1 in alchemical_regions[x].alchemical_atoms: - for atom2 in alchemical_regions[y].alchemical_atoms: - reference_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) - else: - region_names = (alchemical_regions[x].name, alchemical_regions[y].name) - logger.debug(f'Adding a electrostatic interaction group between groups {region_names}.') - del region_names - # Create a copy of the NonbondedForce to handle particle interactions and # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). nonbonded_force = copy.deepcopy(reference_force) @@ -1575,8 +1563,19 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # Fix it. nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) - # With exact PME treatment, particle electrostatics is handled through offset parameters. if use_exact_pme_treatment: + # Exclude noninteracting alchemical regions from seeing each other in the nonbonded + for x, y in itertools.combinations(range(len(alchemical_regions)), 2): + if (x, y) not in alchemical_regions_interactions: + for atom1 in alchemical_regions[x].alchemical_atoms: + for atom2 in alchemical_regions[y].alchemical_atoms: + nonbonded_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) + else: + region_names = (alchemical_regions[x].name, alchemical_regions[y].name) + logger.debug(f'Adding a exact PME electrostatic interaction group between groups {region_names}.') + del region_names + + # With exact PME treatment, particle electrostatics is handled through offset parameters. for alchemical_region in alchemical_regions: nonbonded_force.addGlobalParameter(f'lambda_electrostatics_{alchemical_region.name}', 1.0) From 675e7af14c894f87805a492347a987fec530d835 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 26 Jun 2019 17:49:50 +0100 Subject: [PATCH 050/152] variables mis named --- openmmtools/alchemy.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 452ce486a..43916e9ed 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -695,7 +695,7 @@ def create_alchemical_system(self, reference_system, alchemical_regions, # Check that there are no virtual sites to alchemically modify. for alchemical_region in alchemical_regions: - for particle_index in alchemical_region.atoms: + for particle_index in alchemical_region.alchemical_atoms: if reference_system.isVirtualSite(particle_index): raise ValueError(f'Virtual atoms in region {alchemical_region.name}.' 'Alchemically modified virtual sites are not supported') @@ -1887,7 +1887,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ else: for exception_index in range(nonbonded_force.getNumExceptions()): # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) + [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces # must have the same number of exceptions/exclusions on CUDA platform. From b988a8c9d20ac38e5344d30ed305407f3724616c Mon Sep 17 00:00:00 2001 From: Ana Silveira Date: Mon, 8 Jul 2019 16:34:28 -0400 Subject: [PATCH 051/152] check for flatness criteria --- openmmtools/multistate/sams.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/openmmtools/multistate/sams.py b/openmmtools/multistate/sams.py index 6378e3c14..a58a6466b 100644 --- a/openmmtools/multistate/sams.py +++ b/openmmtools/multistate/sams.py @@ -309,7 +309,11 @@ def _adapt_target_probabilities_validator(instance, scheme): logZ_guess = _StoredProperty('logZ_guess', validate_function=None) def _initialize_stage(self): - + if self.weight_update and (self.update_stages == 'two-stage'): + for key in self._criteria.keys(): + if key not in ['histogram_flatness', 'minimum_round_trips', 'minimum_visits', 'minimum_logZ']: + raise Exception('Unkown {} criteria. Supported values are: histogram_flatness, minimum_round_trips, minimum_logZ and minimum_visits'.format(key)) + self._round_trips = 0 # The variable _downhill keeps track of which end state the walker has visited more recently. # This is used for computing the number of round trips. From d04d4166e99ad44a92b91bcb538f12cd80f79afc Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 14:03:22 -0400 Subject: [PATCH 052/152] FIx module path --- openmmtools/multistate/multistateanalyzer.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openmmtools/multistate/multistateanalyzer.py b/openmmtools/multistate/multistateanalyzer.py index 4b0e0b1a1..fc484bd58 100644 --- a/openmmtools/multistate/multistateanalyzer.py +++ b/openmmtools/multistate/multistateanalyzer.py @@ -1067,7 +1067,7 @@ def _combine_phases(self, other, operator='+'): # Reset self._sign self._sign = '+' if self.name is None: - names.append(utils.generate_phase_name(self.name, [])) + names.append(multistate.utils.generate_phase_name(self.name, [])) else: names.append(self.name) if isinstance(other, MultiPhaseAnalyzer): @@ -1077,7 +1077,7 @@ def _combine_phases(self, other, operator='+'): final_new_names = [] for name in new_names: other_names = [n for n in new_names if n != name] - final_new_names.append(utils.generate_phase_name(name, other_names + names)) + final_new_names.append(multistate.utils.generate_phase_name(name, other_names + names)) names.extend(final_new_names) for new_sign in new_signs: if operator != '+' and new_sign == '+': @@ -1086,7 +1086,7 @@ def _combine_phases(self, other, operator='+'): signs.append('+') phases.extend(new_phases) elif isinstance(other, PhaseAnalyzer): - names.append(utils.generate_phase_name(other.name, names)) + names.append(multistate.utils.generate_phase_name(other.name, names)) if operator != '+' and other._sign == '+': signs.append('-') else: From c16fc7d7ccdd1484ea1f8a13e2979becbf45b4fb Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 14:06:42 -0400 Subject: [PATCH 053/152] Update releasehistory.rst --- docs/releasehistory.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 89abc4eb4..1365a4be7 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -1,6 +1,13 @@ Release History *************** +Current development +=================== + +Bugfixes +-------- +- Fixed a bug in ``multistateanalyzer.py`` where a function was imported from ``openmmtools.utils`` instead of ``openmmtools.multistate.utils`` (`#430 `_). + 0.18.2 - Bugfix release ======================= From c6413854fa24cb1e85dffcfa66c361a9dc631f80 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 15:04:20 -0400 Subject: [PATCH 054/152] Temporarily allow macOS tests to fail --- .travis.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 110cf623e..a9f83e37e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,8 @@ language: python # Run jobs on container-based infrastructure, can be overridden per job matrix: - include: + # TODO: Move macOS tests back to "include:" if they stop segfaulting after switching from nose to pytest (see also #402 and #430). + allow_failures: # Extra includes for OSX since python language is not available by default on OSX - os: osx language: generic @@ -12,7 +13,7 @@ matrix: language: generic env: PYTHON_VER=3.7 - + include: - os: linux language: generic # No need to set Python version since its conda env: PYTHON_VER=3.6 From 1cc66de144ec6fc3eb60ad0e954e91f39f3bc641 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 15:36:47 -0400 Subject: [PATCH 055/152] Temporarily allow macOS tests to fail --- .travis.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index a9f83e37e..a89948e51 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,8 +3,7 @@ language: python # Run jobs on container-based infrastructure, can be overridden per job matrix: - # TODO: Move macOS tests back to "include:" if they stop segfaulting after switching from nose to pytest (see also #402 and #430). - allow_failures: + include: # Extra includes for OSX since python language is not available by default on OSX - os: osx language: generic @@ -13,7 +12,6 @@ matrix: language: generic env: PYTHON_VER=3.7 - include: - os: linux language: generic # No need to set Python version since its conda env: PYTHON_VER=3.6 @@ -21,6 +19,10 @@ matrix: language: generic env: PYTHON_VER=3.7 + # TODO: Reactivate macOS tests if they stop segfaulting after switching from nose to pytest (see also #402 and #430). + allow_failures: + os: osx + env: global: - OPENMM_CPU_THREADS="1" # only use one CPU thread for determinism From 7712c07be3a19c5d8a1216a9ab7fea2a0399c855 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 16:38:32 -0400 Subject: [PATCH 056/152] Fix YAML dict -> list --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a89948e51..d409a8f04 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,7 +21,7 @@ matrix: # TODO: Reactivate macOS tests if they stop segfaulting after switching from nose to pytest (see also #402 and #430). allow_failures: - os: osx + - os: osx env: global: From c01b5b00014148641b921a31b9f49e41b1c4ed39 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 17:47:16 -0400 Subject: [PATCH 057/152] Fix #409: rename restart_attempts in docstring --- openmmtools/mcmc.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmmtools/mcmc.py b/openmmtools/mcmc.py index 1d73335c0..6f555c084 100644 --- a/openmmtools/mcmc.py +++ b/openmmtools/mcmc.py @@ -570,7 +570,7 @@ class BaseIntegratorMove(MCMCMove): reassign_velocities : bool, optional If True, the velocities will be reassigned from the Maxwell-Boltzmann distribution at the beginning of the move (default is False). - restart_attempts : int, optional + n_restart_attempts : int, optional When greater than 0, if after the integration there are NaNs in energies, the move will restart. When the integrator has a random component, this may help recovering. On the last attempt, the ``Context`` is @@ -583,7 +583,7 @@ class BaseIntegratorMove(MCMCMove): n_steps : int context_cache : openmmtools.cache.ContextCache reassign_velocities : bool - restart_attempts : int or None + n_restart_attempts : int or None Examples -------- From 0a39769e4a31836002006d1a3906dfea8c8b589a Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 17:54:24 -0400 Subject: [PATCH 058/152] Fix #418: Fix tutorial comment Rename references to T4Lysozyme+p-xylene to host-guest. --- docs/gettingstarted.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/gettingstarted.rst b/docs/gettingstarted.rst index ab6112a73..affa7e9fc 100644 --- a/docs/gettingstarted.rst +++ b/docs/gettingstarted.rst @@ -761,7 +761,7 @@ part of a system. .. doctest:: - >>> # Prepare the T4 Lysozyme + p-xylene system for alchemical modification. + >>> # Prepare the host-guest system for alchemical modification. >>> guest_atoms = host_guest.mdtraj_topology.select('resname B2') >>> alchemical_region = alchemy.AlchemicalRegion(alchemical_atoms=guest_atoms) >>> factory = alchemy.AbsoluteAlchemicalFactory() @@ -786,8 +786,8 @@ Finally, let's mix Monte Carlo and dynamics for propagation. .. doctest:: >>> sequence_move = mcmc.SequenceMove(move_list=[ - ... mcmc.MCDisplacementMove(atom_subset=pxylene_atoms), - ... mcmc.MCRotationMove(atom_subset=pxylene_atoms), + ... mcmc.MCDisplacementMove(atom_subset=guest_atoms), + ... mcmc.MCRotationMove(atom_subset=guest_atoms), ... mcmc.LangevinSplittingDynamicsMove(timestep=2.0*unit.femtoseconds, n_steps=n_steps, ... reassign_velocities=True, n_restart_attempts=6) ... ]) From c831c146cfb3e234df8800a072c305ee639c16bc Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 20:03:40 -0400 Subject: [PATCH 059/152] Fix #408: Add util function to API sphinx docs --- docs/states.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/states.rst b/docs/states.rst index de73f6457..f9f2e3096 100644 --- a/docs/states.rst +++ b/docs/states.rst @@ -25,3 +25,15 @@ States IComposableState GlobalParameterFunction GlobalParameterState + +| + +Utility functions +----------------- + +.. currentmodule:: openmmtools.states +.. autosummary:: + :nosignatures: + :toctree: api/generated/ + + create_thermodynamic_state_protocol From 92fe2f28659e47aaa5d192c8dadcd3d030d9b616 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 20:08:46 -0400 Subject: [PATCH 060/152] Remove duplicate pyyaml requirement --- devtools/conda-envs/test_env.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/devtools/conda-envs/test_env.yaml b/devtools/conda-envs/test_env.yaml index 6566224c7..84d3b6427 100644 --- a/devtools/conda-envs/test_env.yaml +++ b/devtools/conda-envs/test_env.yaml @@ -25,7 +25,6 @@ dependencies: - sphinxcontrib-bibtex - mpiplus - pymbar - - pyyaml # Testing - nose From 3c30819025b51da32d2146de9a6e1100aab6055a Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 20:36:54 -0400 Subject: [PATCH 061/152] Fix #400: dummy cache cannot replace ContextCache --- openmmtools/cache.py | 49 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/openmmtools/cache.py b/openmmtools/cache.py index 346ee2549..3bd0ffe94 100644 --- a/openmmtools/cache.py +++ b/openmmtools/cache.py @@ -650,12 +650,57 @@ class DummyContextCache(object): The OpenMM platform to use. If None, OpenMM tries to select the fastest one available. + Examples + -------- + Create a new ``Context`` object for alanine dipeptide in vacuum in NPT. + + >>> from simtk import openmm, unit + >>> from openmmtools import states, testsystems + >>> system = testsystems.AlanineDipeptideVacuum().system + >>> thermo_state = states.ThermodynamicState(system, temperature=300*unit.kelvin) + + >>> context_cache = DummyContextCache() + >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) + >>> context, context_integrator = context_cache.get_context(thermo_state, integrator) + + Or create a ``Context`` with an arbitrary integrator (when you only + need to compute energies, for example). + + >>> context, context_integrator = context_cache.get_context(thermo_state) + """ def __init__(self, platform=None): self.platform = platform - def get_context(self, thermodynamic_state, integrator): - """Create a new context in the given thermodynamic state.""" + def get_context(self, thermodynamic_state, integrator=None): + """Create a new context in the given thermodynamic state. + + Parameters + ---------- + thermodynamic_state : states.ThermodynamicState + The thermodynamic state of the system. + integrator : simtk.openmm.Integrator, optional + The integrator to bind to the new context. If ``None``, an arbitrary + integrator is used. Currently, this is a ``LangevinIntegrator`` with + "V R O R V" splitting, but this might change in the future. Default + is ``None``. + + Returns + ------- + context : simtk.openmm.Context + The new context in the given thermodynamic system. + context_integrator : simtk.openmm.Integrator + The integrator bound to the context that can be used for + propagation. This is identical to the ``integrator`` argument + if it was passed. + + """ + if integrator is None: + integrator = integrators.LangevinIntegrator( + timestep=1.0*unit.femtoseconds, + splitting="V R O R V", + temperature=thermodynamic_state.temperature + ) context = thermodynamic_state.create_context(integrator, self.platform) return context, integrator From bc83976eca239ea9f2fccc414ced9b1eb1fad5cb Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 19 Jul 2019 21:07:46 -0400 Subject: [PATCH 062/152] PEP8 --- openmmtools/integrators.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 01b6d9598..87169d707 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -2125,22 +2125,29 @@ def __init__(self, *args, **kwargs): kwargs['splitting'] = "O { V R V } O" super(GHMCIntegrator, self).__init__(*args, **kwargs) + class FIREMinimizationIntegrator(mm.CustomIntegrator): """Fast Internal Relaxation Engine (FIRE) minimization. + Notes ----- This integrator is taken verbatim from Peter Eastman's example appearing in the CustomIntegrator header file documentation. + References ---------- Erik Bitzek, Pekka Koskinen, Franz Gaehler, Michael Moseler, and Peter Gumbsch. Structural Relaxation Made Simple. PRL 97:170201, 2006. http://dx.doi.org/10.1103/PhysRevLett.97.170201 + Examples -------- >>> from openmmtools import testsystems >>> from simtk import openmm >>> t = testsystems.AlanineDipeptideVacuum() >>> system, positions = t.system, t.positions + + Create a FIRE integrator with default parameters and minimize for 100 steps + >>> integrator = FIREMinimizationIntegrator() >>> context = openmm.Context(system, integrator) >>> context.setPositions(positions) From 15bfeb11a39352c46a3383053c5e62c5edff641d Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Sun, 21 Jul 2019 10:47:32 -0400 Subject: [PATCH 063/152] Fix #422: Set chunksize=1 for iteration dimension --- openmmtools/multistate/multistatereporter.py | 147 ++++++++----------- 1 file changed, 60 insertions(+), 87 deletions(-) diff --git a/openmmtools/multistate/multistatereporter.py b/openmmtools/multistate/multistatereporter.py index b1ee7d4af..44aa08705 100644 --- a/openmmtools/multistate/multistatereporter.py +++ b/openmmtools/multistate/multistatereporter.py @@ -733,12 +733,13 @@ def write_replica_thermodynamic_states(self, state_indices, iteration): self._ensure_dimension_exists('replica', n_replicas) # Create variables and attach units and description. - ncvar_states = self._storage_analysis.createVariable('states', 'i4', ('iteration', 'replica'), - zlib=False, - chunksizes=(self._checkpoint_interval, n_replicas)) - setattr(ncvar_states, 'units', 'none') - setattr(ncvar_states, "long_name", ("states[iteration][replica] is the thermodynamic state index " - "(0..n_states-1) of replica 'replica' of iteration 'iteration'.")) + ncvar_states = self._storage_analysis.createVariable( + 'states', 'i4', ('iteration', 'replica'), + zlib=False, chunksizes=(1, n_replicas) + ) + ncvar_states.units = 'none' + ncvar_states.long_name = ("states[iteration][replica] is the thermodynamic state index " + "(0..n_states-1) of replica 'replica' of iteration 'iteration'.") # Store thermodynamic states indices. self._storage_analysis.variables['states'][iteration, :] = state_indices[:] @@ -837,29 +838,23 @@ def write_energies(self, energy_thermodynamic_states, energy_neighborhoods, ener self._ensure_dimension_exists('replica', n_replicas) self._ensure_dimension_exists('state', n_states) if 'energies' not in self._storage_analysis.variables: - ncvar_energies = self._storage_analysis.createVariable('energies', - 'f8', - ('iteration', 'replica', 'state'), - zlib=False, - chunksizes=(self._checkpoint_interval, - n_replicas, - n_states)) + ncvar_energies = self._storage_analysis.createVariable( + 'energies', 'f8', ('iteration', 'replica', 'state'), + zlib=False, chunksizes=(1, n_replicas, n_states) + ) ncvar_energies.units = 'kT' ncvar_energies.long_name = ("energies[iteration][replica][state] is the reduced (unitless) " "energy of replica 'replica' from iteration 'iteration' evaluated " "at the thermodynamic state 'state'.") if 'neighborhoods' not in self._storage_analysis.variables: - ncvar_neighborhoods = self._storage_analysis.createVariable('neighborhoods', - 'i1', - ('iteration', 'replica', 'state'), - zlib=False, - fill_value=1, # old-style files will be upgraded to have all states - chunksizes=(self._checkpoint_interval, - n_replicas, - n_states)) - ncvar_neighborhoods.long_name = ("neighborhoods[iteration][replica][state] is 1 if this energy was computed " - "during this iteration.") + ncvar_neighborhoods = self._storage_analysis.createVariable( + 'neighborhoods', 'i1', ('iteration', 'replica', 'state'), + zlib=False, fill_value=1, # old-style files will be upgraded to have all states + chunksizes=(1, n_replicas, n_states) + ) + ncvar_neighborhoods.long_name = ("neighborhoods[iteration][replica][state] is 1 if " + "this energy was computed during this iteration.") if 'unsampled_energies' not in self._storage_analysis.variables: # Check if we have unsampled states. @@ -870,14 +865,10 @@ def write_energies(self, energy_thermodynamic_states, energy_neighborhoods, ener if 'unsampled_energies' not in self._storage_analysis.variables: # Create variable for thermodynamic state energies with units and descriptions. - ncvar_unsampled = self._storage_analysis.createVariable('unsampled_energies', - 'f8', - ('iteration', 'replica', 'unsampled'), - zlib=False, - chunksizes=(self._checkpoint_interval, - n_replicas, - n_unsampled_states) - ) + ncvar_unsampled = self._storage_analysis.createVariable( + 'unsampled_energies', 'f8', ('iteration', 'replica', 'unsampled'), + zlib=False, chunksizes=(1, n_replicas, n_unsampled_states) + ) ncvar_unsampled.units = 'kT' ncvar_unsampled.long_name = ("unsampled_energies[iteration][replica][state] is the reduced " "(unitless) energy of replica 'replica' from iteration 'iteration' " @@ -940,28 +931,20 @@ def write_mixing_statistics(self, n_accepted_matrix, n_proposed_matrix, iteratio self._ensure_dimension_exists('state', n_states) # Create variables with units and descriptions. - ncvar_accepted = self._storage_analysis.createVariable('accepted', - 'i4', - ('iteration', 'state', 'state'), - zlib=False, - chunksizes=(self._checkpoint_interval, - n_states, - n_states) - ) - ncvar_proposed = self._storage_analysis.createVariable('proposed', - 'i4', - ('iteration', 'state', 'state'), - zlib=False, - chunksizes=(self._checkpoint_interval, - n_states, - n_states) - ) - setattr(ncvar_accepted, 'units', 'none') - setattr(ncvar_proposed, 'units', 'none') - setattr(ncvar_accepted, 'long_name', ("accepted[iteration][i][j] is the number of proposed transitions " - "between states i and j from iteration 'iteration-1'.")) - setattr(ncvar_proposed, 'long_name', ("proposed[iteration][i][j] is the number of proposed transitions " - "between states i and j from iteration 'iteration-1'.")) + ncvar_accepted = self._storage_analysis.createVariable( + 'accepted', 'i4', ('iteration', 'state', 'state'), + zlib=False, chunksizes=(1, n_states, n_states) + ) + ncvar_proposed = self._storage_analysis.createVariable( + 'proposed', 'i4', ('iteration', 'state', 'state'), + zlib=False, chunksizes=(1, n_states, n_states) + ) + ncvar_accepted.units = 'none' + ncvar_proposed.units = 'none' + ncvar_accepted.long_name = ("accepted[iteration][i][j] is the number of proposed transitions " + "between states i and j from iteration 'iteration-1'.") + ncvar_proposed.long_name = ("proposed[iteration][i][j] is the number of proposed transitions " + "between states i and j from iteration 'iteration-1'.") # Store statistics. self._storage_analysis.variables['accepted'][iteration, :, :] = n_accepted_matrix[:, :] @@ -1000,9 +983,8 @@ def write_timestamp(self, iteration: int): # Create variable if needed. for storage_key, storage in self._storage_dict.items(): if 'timestamp' not in storage.variables: - timestamp = storage.createVariable('timestamp', str, ('iteration',), - zlib=False, - chunksizes=(self._storage_chunks[storage_key],)) + storage.createVariable('timestamp', str, ('iteration',), + zlib=False, chunksizes=(1,)) timestamp = time.ctime() self._storage_analysis.variables['timestamp'][iteration] = timestamp @@ -1331,10 +1313,10 @@ def _write_1d_online_data(self, iteration, variable, data, storage): if variable not in storage.variables: variable_parameters = self._determine_netcdf_variable_parameters(iteration, data, storage) logger.debug('Creating new NetCDF variable %s with parameters: %s' % (variable, variable_parameters)) # DEBUG - nc_var = storage.createVariable(variable, variable_parameters['dtype'], - dimensions=variable_parameters['dims'], - chunksizes=variable_parameters['chunksizes'], - zlib=False) + storage.createVariable(variable, variable_parameters['dtype'], + dimensions=variable_parameters['dims'], + chunksizes=variable_parameters['chunksizes'], + zlib=False) # Get the variable nc_var = storage[variable] @@ -1401,7 +1383,7 @@ def _determine_netcdf_variable_parameters(self, iteration, data, storage): if iteration is not None: dims = ("iteration", data_dim) - chunks = (self._checkpoint_interval, size) + chunks = (1, size) else: dims = (data_dim,) chunks = (size,) @@ -1536,7 +1518,7 @@ def _ensure_group_exists_and_get(self, group_name, storage=None): return storage.groups[group_name] @staticmethod - def _initialize_sampler_variables_on_file(dataset, n_atoms, n_replicas, is_periodic, iteration_chunk=1): + def _initialize_sampler_variables_on_file(dataset, n_atoms, n_replicas, is_periodic): """ Initialize the NetCDF variables on the storage file needed to store sampler states. Does nothing if file already initialized @@ -1551,8 +1533,6 @@ def _initialize_sampler_variables_on_file(dataset, n_atoms, n_replicas, is_perio Number of Sampler states which will be written is_periodic : bool True if system is periodic; False otherwise. - iteration_chunk : int, Optional, Default: 1 - What chunksize to use for the iteration dimension """ if 'positions' not in dataset.variables: @@ -1561,31 +1541,30 @@ def _initialize_sampler_variables_on_file(dataset, n_atoms, n_replicas, is_perio if 'replica' not in dataset.dimensions: dataset.createDimension('replica', n_replicas) - # Define position variables + # Define position variables. ncvar_positions = dataset.createVariable('positions', 'f4', ('iteration', 'replica', 'atom', 'spatial'), - zlib=True, chunksizes=(iteration_chunk, n_replicas, n_atoms, 3)) - setattr(ncvar_positions, 'units', 'nm') - setattr(ncvar_positions, "long_name", ("positions[iteration][replica][atom][spatial] is position of " - "coordinate 'spatial' of atom 'atom' from replica 'replica' for " - "iteration 'iteration'.")) + zlib=True, chunksizes=(1, n_replicas, n_atoms, 3)) + ncvar_positions.units = 'nm' + ncvar_positions.long_name = ("positions[iteration][replica][atom][spatial] is position of " + "coordinate 'spatial' of atom 'atom' from replica 'replica' for " + "iteration 'iteration'.") # Define variables for periodic systems if is_periodic: ncvar_box_vectors = dataset.createVariable('box_vectors', 'f4', ('iteration', 'replica', 'spatial', 'spatial'), - zlib=False, chunksizes=(iteration_chunk, n_replicas, 3, 3)) + zlib=False, chunksizes=(1, n_replicas, 3, 3)) ncvar_volumes = dataset.createVariable('volumes', 'f8', ('iteration', 'replica'), - zlib=False, chunksizes=(iteration_chunk, n_replicas)) + zlib=False, chunksizes=(1, n_replicas)) - setattr(ncvar_box_vectors, 'units', 'nm') - setattr(ncvar_volumes, 'units', 'nm**3') - - setattr(ncvar_box_vectors, "long_name", ("box_vectors[iteration][replica][i][j] is dimension j of box " - "vector i for replica 'replica' from iteration " - "'iteration-1'.")) - setattr(ncvar_volumes, "long_name", ("volume[iteration][replica] is the box volume for replica " - "'replica' from iteration 'iteration-1'.")) + ncvar_box_vectors.units = 'nm' + ncvar_volumes.units = 'nm**3' + ncvar_box_vectors.long_name = ("box_vectors[iteration][replica][i][j] is dimension j of box " + "vector i for replica 'replica' from iteration " + "'iteration-1'.") + ncvar_volumes.long_name = ("volume[iteration][replica] is the box volume for replica " + "'replica' from iteration 'iteration-1'.") def _write_sampler_states_to_given_file(self, sampler_states: list, iteration: int, storage_file='checkpoint', obey_checkpoint_interval=True): @@ -1612,8 +1591,7 @@ def _write_sampler_states_to_given_file(self, sampler_states: list, iteration: i n_particles = sampler_states[0].n_particles n_replicas = len(sampler_states) self._initialize_sampler_variables_on_file(storage, n_particles, - n_replicas, is_periodic, - iteration_chunk=self._storage_chunks[storage_file]) + n_replicas, is_periodic) if obey_checkpoint_interval: write_iteration = self._calculate_checkpoint_iteration(iteration) else: @@ -1769,11 +1747,6 @@ def _write_dict(self, path, data, storage_name='analysis', packed_data[0] = data_str nc_variable[:] = packed_data - @ property - def _storage_chunks(self): - """Known NetCDF storage chunk sizes""" - return {'checkpoint': 1, 'analysis': self._checkpoint_interval} - # ============================================================================== # MODULE INTERNAL USAGE UTILITIES From 7a9dd32e2843060182d5992544913195cf715fbb Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Sun, 21 Jul 2019 10:58:44 -0400 Subject: [PATCH 064/152] Update releasehistory.rst --- docs/releasehistory.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 89abc4eb4..1150f33e7 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -1,6 +1,17 @@ Release History *************** +0.18.3 - Disk writing enhancements and bugfixes +=============================================== + +Bugfixes +-------- +- Fixed a few imprecisions in the documentation (`#432 `_). + +Enhancements +------------ +- Disk writing speed is much faster for multi-state samplers when the `checkpoint_interval` is large. This was due to the dimension of the netcdf chunk size increasing with the checkpoint interval and surpassing the dimension of the netcdf chunk cache. The chunk size of the iteration dimension is now always set to 1 (`#432 `_). + 0.18.2 - Bugfix release ======================= From 14adf7b67aec480c84d22a17c04975b9b2d76938 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Sun, 21 Jul 2019 14:27:21 -0400 Subject: [PATCH 065/152] Update releasehistory.rst --- docs/releasehistory.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index cc5ee6609..f9d429a57 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -1,8 +1,8 @@ Release History *************** -0.18.3 - Disk writing enhancements and bugfixes -=============================================== +0.18.3 - Storage enhancements and bugfixes +========================================== Bugfixes -------- @@ -11,7 +11,9 @@ Bugfixes Enhancements ------------ -- Disk writing speed is much faster for multi-state samplers when the `checkpoint_interval` is large. This was due to the dimension of the netcdf chunk size increasing with the checkpoint interval and surpassing the dimension of the netcdf chunk cache. The chunk size of the iteration dimension is now always set to 1 (`#432 `_). +- Writing on disk is much faster when the `checkpoint_interval` of multi-state samplers is large. This was due + to the dimension of the netcdf chunk size increasing with the checkpoint interval and surpassing the dimension + of the netcdf chunk cache. The chunk size of the iteration dimension is now always set to 1 (`#432 `_). 0.18.2 - Bugfix release ======================= From a66b01358d1d408c3ba9cdaf033c9bc44d7cbd84 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Thu, 25 Jul 2019 09:32:02 +0100 Subject: [PATCH 066/152] Corrections for current tests These corrections allow for current tests to run. Note, TolueneImplicitOBC2 is failing. --- openmmtools/alchemy.py | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 43916e9ed..39aaf076e 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1577,7 +1577,10 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # With exact PME treatment, particle electrostatics is handled through offset parameters. for alchemical_region in alchemical_regions: - nonbonded_force.addGlobalParameter(f'lambda_electrostatics_{alchemical_region.name}', 1.0) + if alchemical_region.name is None: + nonbonded_force.addGlobalParameter('lambda_electrostatics', 1.0) + else: + nonbonded_force.addGlobalParameter(f'lambda_electrostatics_{alchemical_region.name}', 1.0) # Make of list of all single and double permutations of alchemical regions. single_regions = [[alchemical_region] for alchemical_region in alchemical_regions] @@ -1961,10 +1964,14 @@ def add_global_parameters(force): forces_by_lambda[''] = [nonbonded_force] return forces_by_lambda - def _alchemically_modify_AmoebaMultipoleForce(self, reference_force, alchemical_region): + def _alchemically_modify_AmoebaMultipoleForce(self, reference_force, alchemical_region, _): + if len(alchemical_region) > 1: + raise NotImplemented("Multiple regions does not work with AmoebaMultipoleForce") + else: + alchemical_region = alchemical_region[0] raise Exception("Not implemented; needs CustomMultipleForce") - def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region): + def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region, _): """Create alchemically-modified version of AmoebaVdwForce. Not implemented. @@ -1976,6 +1983,10 @@ def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region """ # This feature is incompletely implemented, so raise an exception. + if len(alchemical_region) > 1: + raise NotImplemented("Multiple regions does not work with AmoebaMultipoleForce") + else: + alchemical_region = alchemical_region[0] raise NotImplemented('Alchemical modification of Amoeba VdW Forces is not supported.') # Softcore Halgren potential from Eq. 3 of @@ -2026,7 +2037,7 @@ def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region return [softcore_force] @staticmethod - def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, sasa_model='ACE'): + def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, sasa_model='ACE', _=None): """Create alchemically-modified version of GBSAOBCForce. Parameters @@ -2050,6 +2061,11 @@ def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, sasa_m * Can we more generally modify any CustomGBSAForce? """ + if len(alchemical_region) > 1: + raise NotImplemented("Multiple regions does not work with AmoebaMultipoleForce") + else: + alchemical_region = alchemical_region[0] + # TODO make sasa_model a Factory attribute? custom_force = openmm.CustomGBForce() @@ -2100,7 +2116,7 @@ def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, sasa_m return {'lambda_electrostatics': [custom_force]} - def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region): + def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region, _): """Create alchemically-modified version of CustomGBForce. The GB functions are meta-programmed using the following rules: @@ -2139,6 +2155,11 @@ def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region) The alchemical version of the reference force. """ + if len(alchemical_region) > 1: + raise NotImplemented("Multiple regions does not work with AmoebaMultipoleForce") + else: + alchemical_region = alchemical_region[0] + custom_force = openmm.CustomGBForce() # Add global parameters From 56d2eba646a1972c31eb93dc30fb2cb1e947b976 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Thu, 25 Jul 2019 15:59:25 +0100 Subject: [PATCH 067/152] Fix TolueneImplicitOBC2 --- openmmtools/alchemy.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 39aaf076e..68e1d9519 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1984,7 +1984,7 @@ def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region """ # This feature is incompletely implemented, so raise an exception. if len(alchemical_region) > 1: - raise NotImplemented("Multiple regions does not work with AmoebaMultipoleForce") + raise NotImplemented("Multiple regions does not work with AmoebaVdwForce") else: alchemical_region = alchemical_region[0] raise NotImplemented('Alchemical modification of Amoeba VdW Forces is not supported.') @@ -2037,7 +2037,7 @@ def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region return [softcore_force] @staticmethod - def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, sasa_model='ACE', _=None): + def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, _, sasa_model='ACE'): """Create alchemically-modified version of GBSAOBCForce. Parameters @@ -2062,7 +2062,7 @@ def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, sasa_m """ if len(alchemical_region) > 1: - raise NotImplemented("Multiple regions does not work with AmoebaMultipoleForce") + raise NotImplemented("Multiple regions does not work with GBSAOBCForce") else: alchemical_region = alchemical_region[0] @@ -2097,6 +2097,7 @@ def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, sasa_m "psi=I*or; or=radius-offset", openmm.CustomGBForce.SingleParticle) custom_force.addEnergyTerm("-0.5*138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical+(1-alchemical))*charge^2/B", openmm.CustomGBForce.SingleParticle) + print(sasa_model) if sasa_model == 'ACE': custom_force.addEnergyTerm("(lambda_electrostatics*alchemical+(1-alchemical))*28.3919551*(radius+0.14)^2*(radius/B)^6", openmm.CustomGBForce.SingleParticle) @@ -2156,7 +2157,7 @@ def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region, """ if len(alchemical_region) > 1: - raise NotImplemented("Multiple regions does not work with AmoebaMultipoleForce") + raise NotImplemented("Multiple regions does not work with CustomGBForce") else: alchemical_region = alchemical_region[0] From 3e44c9454158c773c95e59978546555d95699bda Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Thu, 25 Jul 2019 16:00:49 +0100 Subject: [PATCH 068/152] remove print --- openmmtools/alchemy.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 68e1d9519..80fccdb3e 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -2096,8 +2096,7 @@ def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, _, sas custom_force.addComputedValue("B", "1/(1/or-tanh(psi-0.8*psi^2+4.85*psi^3)/radius);" "psi=I*or; or=radius-offset", openmm.CustomGBForce.SingleParticle) - custom_force.addEnergyTerm("-0.5*138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical+(1-alchemical))*charge^2/B", openmm.CustomGBForce.SingleParticle) - print(sasa_model) + custom_force.addEnergyTerm("-0.5*138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical+(1-alchemical))*charge^2/B", openmm.CustomGBForce.SingleParticle) if sasa_model == 'ACE': custom_force.addEnergyTerm("(lambda_electrostatics*alchemical+(1-alchemical))*28.3919551*(radius+0.14)^2*(radius/B)^6", openmm.CustomGBForce.SingleParticle) From 11fda474ae42597ff15cf8130f12b465cf44485a Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 26 Jul 2019 17:53:42 +0100 Subject: [PATCH 069/152] Compatabilty for MultiReg tests --- openmmtools/alchemy.py | 127 +++++++++++++++++++++++++++-------------- 1 file changed, 84 insertions(+), 43 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 80fccdb3e..47612fe95 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -2267,8 +2267,14 @@ def check_energy_expression(custom_force, parameter): force_labels = {} nonbonded_forces = [] - sterics_bond_forces = [] - electro_bond_forces = [] + sterics_none_bond_forces = [] + electro_none_bond_forces = [] + sterics_zero_bond_forces = [] + electro_zero_bond_forces = [] + sterics_one_bond_forces = [] + electro_one_bond_forces = [] + sterics_two_bond_forces = [] + electro_two_bond_forces = [] # We save CustomBondForces and CustomNonbondedForces used for nonbonded # forces and exceptions to distinguish them later @@ -2285,18 +2291,42 @@ def check_energy_expression(custom_force, parameter): else: add_label('alchemically modified GBSAOBCForce', force_index) elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda'): - if check_energy_expression(force, 'lambda_sterics'): - sterics_bond_forces.append([force_index, force]) - else: - electro_bond_forces.append([force_index, force]) + if check_energy_expression(force, 'lambda_sterics_zero'): + sterics_zero_bond_forces.append([force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_one'): + sterics_one_bond_forces.append([force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_two'): + sterics_two_bond_forces.append([force_index, force]) + elif check_energy_expression(force, 'lambda_sterics'): + sterics_none_bond_forces.append([force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_zero'): + electro_zero_bond_forces.append([force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_one'): + electro_one_bond_forces.append([force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_two'): + electro_two_bond_forces.append([force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics'): + electro_none_bond_forces.append([force_index, force]) elif (isinstance(force, openmm.CustomNonbondedForce) and force.getEnergyFunction() == '0.0;' and force.getGlobalParameterName(0) == 'lambda_electrostatics'): add_label('CustomNonbondedForce holding alchemical atoms unmodified charges', force_index) elif isinstance(force, openmm.CustomNonbondedForce) and check_energy_expression(force, 'lambda'): - if check_energy_expression(force, 'lambda_sterics'): - nonbonded_forces.append(['sterics', force_index, force]) - else: - nonbonded_forces.append(['electrostatics', force_index, force]) + if check_energy_expression(force, 'lambda_sterics_zero'): + nonbonded_forces.append(['sterics_zero', force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_one'): + nonbonded_forces.append(['sterics_one', force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_two'): + nonbonded_forces.append(['sterics_two', force_index, force]) + elif check_energy_expression(force, 'lambda_sterics'): + nonbonded_forces.append(['sterics_None', force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_zero'): + nonbonded_forces.append(['electrostatics_zero', force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_one'): + nonbonded_forces.append(['electrostatics_one', force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_two'): + nonbonded_forces.append(['electrostatics_two', force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics'): + nonbonded_forces.append(['electrostatics_None', force_index, force]) else: add_label('unmodified ' + force.__class__.__name__, force_index) @@ -2309,45 +2339,56 @@ def check_energy_expression(custom_force, parameter): else: add_label(label.format('non-'), force_index) + region_names = ['None', 'zero', 'one', 'two'] + steric_bonds_by_region = [sterics_none_bond_forces, sterics_zero_bond_forces, + sterics_one_bond_forces, sterics_two_bond_forces] + electro_bond_by_region = [electro_none_bond_forces, electro_zero_bond_forces, + electro_one_bond_forces, electro_two_bond_forces] + # Differentiate between na/aa bond forces for exceptions. - for force_type, bond_forces in [('sterics', sterics_bond_forces), ('electrostatics', electro_bond_forces)]: - # With exact PME there are no CustomBondForces modeling electrostatics exceptions. - if force_type == 'electrostatics' and len(bond_forces) == 0: + for i, (sterics_bond_forces, electro_bond_forces) in enumerate(zip(steric_bonds_by_region, electro_bond_by_region)): + if len(sterics_bond_forces) == 0: continue - # Otherwise there should be two CustomBondForce. - assert len(bond_forces) == 2 - label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type + ' exceptions' - - # Sort forces by number of bonds. - bond_forces = sorted(bond_forces, key=lambda x: x[1].getNumBonds()) - (force_index1, force1), (force_index2, force2) = bond_forces - - # Check if both define their parameters (with decoupling the lambda - # parameter doesn't exist in the alchemical-alchemical force) - parameter_name = 'lambda_' + force_type - if check_parameter(force1, parameter_name) != check_parameter(force2, parameter_name): - if check_parameter(force1, parameter_name): - add_label(label.format('non-'), force_index1) - add_label(label.format(''), force_index2) - else: + region_name = region_names[i] + for force_type, bond_forces in [('sterics', sterics_bond_forces), ('electrostatics', electro_bond_forces)]: + # With exact PME there are no CustomBondForces modeling electrostatics exceptions. + if force_type == 'electrostatics' and len(bond_forces) == 0: + continue + # Otherwise there should be two CustomBondForce. + assert len(bond_forces) == 2 + label = 'alchemically modified BondForce for {}alchemical/alchemical '\ + + force_type + '_{}'.format(region_name) + ' exceptions' + + # Sort forces by number of bonds. + bond_forces = sorted(bond_forces, key=lambda x: x[1].getNumBonds()) + (force_index1, force1), (force_index2, force2) = bond_forces + + # Check if both define their parameters (with decoupling the lambda + # parameter doesn't exist in the alchemical-alchemical force) + parameter_name = 'lambda_' + force_type + '_{}'.format(region_name) + if check_parameter(force1, parameter_name) != check_parameter(force2, parameter_name): + if check_parameter(force1, parameter_name): + add_label(label.format('non-'), force_index1) + add_label(label.format(''), force_index2) + else: + add_label(label.format(''), force_index1) + add_label(label.format('non-'), force_index2) + + # If they are both empty they are identical and any label works. + elif force1.getNumBonds() == 0 and force2.getNumBonds() == 0: add_label(label.format(''), force_index1) add_label(label.format('non-'), force_index2) - # If they are both empty they are identical and any label works. - elif force1.getNumBonds() == 0 and force2.getNumBonds() == 0: - add_label(label.format(''), force_index1) - add_label(label.format('non-'), force_index2) - - # We check that the bond atoms are both alchemical or not. - else: - atom_i, atom_j, _ = force2.getBondParameters(0) - both_alchemical = atom_i in alchemical_atoms and atom_j in alchemical_atoms - if both_alchemical: - add_label(label.format(''), force_index2) - add_label(label.format('non-'), force_index1) + # We check that the bond atoms are both alchemical or not. else: - add_label(label.format('non-'), force_index2) - add_label(label.format(''), force_index1) + atom_i, atom_j, _ = force2.getBondParameters(0) + both_alchemical = atom_i in alchemical_atoms and atom_j in alchemical_atoms + if both_alchemical: + add_label(label.format(''), force_index2) + add_label(label.format('non-'), force_index1) + else: + add_label(label.format('non-'), force_index2) + add_label(label.format(''), force_index1) return force_labels From cba7cc54672bd1a558f9c1d7d9f8f3831592cc42 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 26 Jul 2019 17:54:48 +0100 Subject: [PATCH 070/152] MultiReg TIP3P Box test --- openmmtools/tests/test_alchemy.py | 445 +++++++++++++++++++++++------- 1 file changed, 339 insertions(+), 106 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 37383ebfd..05924e888 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -695,120 +695,134 @@ def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_system = copy.deepcopy(alchemical_system) is_exact_pme = is_alchemical_pme_treatment_exact(alchemical_system) + energy_components = {} # Set state to non-interacting. - alchemical_state = AlchemicalState.from_system(alchemical_system) - alchemical_state.set_alchemical_parameters(0.0) - energy_components = AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, - positions, platform=GLOBAL_ALCHEMY_PLATFORM) + for region in alchemical_regions: + alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix = region.name) + alchemical_state.set_alchemical_parameters(0.0) + energy_components.update({region.name : AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, + positions, platform=GLOBAL_ALCHEMY_PLATFORM)}) - def assert_zero_energy(label): + def assert_zero_energy(label, region_name): print('testing {}'.format(label)) - value = energy_components[label] + value = energy_components[region_name][label] assert abs(value / GLOBAL_ENERGY_UNIT) == 0.0, ("'{}' should have zero energy in annihilated alchemical" " state, but energy is {}").format(label, str(value)) - - # Check that non-alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated - assert_zero_energy('alchemically modified BondForce for non-alchemical/alchemical sterics exceptions') - assert_zero_energy('alchemically modified NonbondedForce for non-alchemical/alchemical sterics') - if is_exact_pme: - assert 'alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics' not in energy_components - assert 'alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions' not in energy_components - else: - assert_zero_energy('alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics') - assert_zero_energy('alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions') - - # Check that alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated - if alchemical_regions.annihilate_sterics: - assert_zero_energy('alchemically modified NonbondedForce for alchemical/alchemical sterics') - assert_zero_energy('alchemically modified BondForce for alchemical/alchemical sterics exceptions') - if alchemical_regions.annihilate_electrostatics: + for region in alchemical_regions: + # Check that non-alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated + assert_zero_energy('alchemically modified BondForce for' + ' non-alchemical/alchemical sterics_{} exceptions'.format(region.name), region.name) + assert_zero_energy('alchemically modified NonbondedForce for' + ' non-alchemical/alchemical sterics_{}'.format(region.name), region.name) if is_exact_pme: - assert 'alchemically modified NonbondedForce for alchemical/alchemical electrostatics' not in energy_components - assert 'alchemically modified BondForce for alchemical/alchemical electrostatics exceptions' not in energy_components + assert 'alchemically modified NonbondedForce for' \ + ' non-alchemical/alchemical electrostatics_{}'.format(region.name) not in energy_components + assert 'alchemically modified BondForce for' \ + ' non-alchemical/alchemical electrostatics_{} exceptions'.format(region.name) not in energy_components else: - assert_zero_energy('alchemically modified NonbondedForce for alchemical/alchemical electrostatics') - assert_zero_energy('alchemically modified BondForce for alchemical/alchemical electrostatics exceptions') - - # Check valence terms - for force_name in ['HarmonicBondForce', 'HarmonicAngleForce', 'PeriodicTorsionForce']: - force_label = 'alchemically modified ' + force_name - if force_label in energy_components: - assert_zero_energy(force_label) - - # Check implicit solvent force. - for force_name in ['CustomGBForce', 'GBSAOBCForce']: - label = 'alchemically modified ' + force_name - - # Check if the system has an implicit solvent force. - try: - alchemical_energy = energy_components[label] - except KeyError: # No implicit solvent. - continue + assert_zero_energy('alchemically modified NonbondedForce for' + ' non-alchemical/alchemical electrostatics_{}'.format(region.name), region.name) + assert_zero_energy('alchemically modified BondForce for' + ' non-alchemical/alchemical electrostatics_{} exceptions'.format(region.name), region.name) + + # Check that alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated + if region.annihilate_sterics: + assert_zero_energy('alchemically modified NonbondedForce for' + ' alchemical/alchemical sterics_{}'.format(region.name), region.name) + assert_zero_energy('alchemically modified BondForce for' + ' alchemical/alchemical sterics_{} exceptions'.format(region.name), region.name) + if region.annihilate_electrostatics: + if is_exact_pme: + assert 'alchemically modified NonbondedForce for' \ + ' alchemical/alchemical electrostatics_{}'.format(region.name) not in energy_components + assert 'alchemically modified BondForce for' \ + ' alchemical/alchemical electrostatics_{} exceptions'.format(region.name) not in energy_components + else: + assert_zero_energy('alchemically modified NonbondedForce for' + ' alchemical/alchemical electrostatics_{}'.format(region.name), region.name) + assert_zero_energy('alchemically modified BondForce for' + ' alchemical/alchemical electrostatics_{} exceptions'.format(region.name), region.name) + + # Check valence terms + for force_name in ['HarmonicBondForce', 'HarmonicAngleForce', 'PeriodicTorsionForce']: + force_label = 'alchemically modified ' + force_name + if force_label in energy_components: + assert_zero_energy(force_label, region.name) + + # Check implicit solvent force. + for force_name in ['CustomGBForce', 'GBSAOBCForce']: + label = 'alchemically modified ' + force_name + + # Check if the system has an implicit solvent force. + try: + alchemical_energy = energy_components[label] + except KeyError: # No implicit solvent. + continue - # If all alchemical particles are modified, the alchemical energy should be zero. - if len(alchemical_regions.alchemical_atoms) == reference_system.getNumParticles(): - assert_zero_energy(label) - continue + # If all alchemical particles are modified, the alchemical energy should be zero. + if len(region.alchemical_atoms) == reference_system.getNumParticles(): + assert_zero_energy(label, region.name) + continue - # Otherwise compare the alchemical energy with a - # reference system with only non-alchemical particles. - # Find implicit solvent force in reference system. - for reference_force in reference_system.getForces(): - if reference_force.__class__.__name__ == force_name: - break + # Otherwise compare the alchemical energy with a + # reference system with only non-alchemical particles. + # Find implicit solvent force in reference system. + for reference_force in reference_system.getForces(): + if reference_force.__class__.__name__ == force_name: + break - system = openmm.System() - force = reference_force.__class__() - - # For custom GB forces, we need to copy all computed values, - # energy terms, parameters, tabulated functions and exclusions. - if isinstance(force, openmm.CustomGBForce): - for index in range(reference_force.getNumPerParticleParameters()): - name = reference_force.getPerParticleParameterName(index) - force.addPerParticleParameter(name) - for index in range(reference_force.getNumComputedValues()): - computed_value = reference_force.getComputedValueParameters(index) - force.addComputedValue(*computed_value) - for index in range(reference_force.getNumEnergyTerms()): - energy_term = reference_force.getEnergyTermParameters(index) - force.addEnergyTerm(*energy_term) - for index in range(reference_force.getNumGlobalParameters()): - name = reference_force.getGlobalParameterName(index) - default_value = reference_force.getGlobalParameterDefaultValue(index) - force.addGlobalParameter(name, default_value) - for function_index in range(reference_force.getNumTabulatedFunctions()): - name = reference_force.getTabulatedFunctionName(function_index) - function = reference_force.getTabulatedFunction(function_index) - function_copy = copy.deepcopy(function) - force.addTabulatedFunction(name, function_copy) - for exclusion_index in range(reference_force.getNumExclusions()): - particles = reference_force.getExclusionParticles(exclusion_index) - force.addExclusion(*particles) - - # Create a system with only the non-alchemical particles. - for particle_index in range(reference_system.getNumParticles()): - if particle_index not in alchemical_regions.alchemical_atoms: - # Add particle to System. - mass = reference_system.getParticleMass(particle_index) - system.addParticle(mass) - - # Add particle to Force.. - parameters = reference_force.getParticleParameters(particle_index) - try: # GBSAOBCForce - force.addParticle(*parameters) - except NotImplementedError: # CustomGBForce - force.addParticle(parameters) - - system.addForce(force) - - # Get positions for all non-alchemical particles. - non_alchemical_positions = [pos for i, pos in enumerate(positions) - if i not in alchemical_regions.alchemical_atoms] - - # Compute reference force energy. - reference_force_energy = compute_force_energy(system, non_alchemical_positions, force_name) - assert_almost_equal(reference_force_energy, alchemical_energy, - 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) + system = openmm.System() + force = reference_force.__class__() + + # For custom GB forces, we need to copy all computed values, + # energy terms, parameters, tabulated functions and exclusions. + if isinstance(force, openmm.CustomGBForce): + for index in range(reference_force.getNumPerParticleParameters()): + name = reference_force.getPerParticleParameterName(index) + force.addPerParticleParameter(name) + for index in range(reference_force.getNumComputedValues()): + computed_value = reference_force.getComputedValueParameters(index) + force.addComputedValue(*computed_value) + for index in range(reference_force.getNumEnergyTerms()): + energy_term = reference_force.getEnergyTermParameters(index) + force.addEnergyTerm(*energy_term) + for index in range(reference_force.getNumGlobalParameters()): + name = reference_force.getGlobalParameterName(index) + default_value = reference_force.getGlobalParameterDefaultValue(index) + force.addGlobalParameter(name, default_value) + for function_index in range(reference_force.getNumTabulatedFunctions()): + name = reference_force.getTabulatedFunctionName(function_index) + function = reference_force.getTabulatedFunction(function_index) + function_copy = copy.deepcopy(function) + force.addTabulatedFunction(name, function_copy) + for exclusion_index in range(reference_force.getNumExclusions()): + particles = reference_force.getExclusionParticles(exclusion_index) + force.addExclusion(*particles) + + # Create a system with only the non-alchemical particles. + for particle_index in range(reference_system.getNumParticles()): + if particle_index not in region.alchemical_atoms: + # Add particle to System. + mass = reference_system.getParticleMass(particle_index) + system.addParticle(mass) + + # Add particle to Force.. + parameters = reference_force.getParticleParameters(particle_index) + try: # GBSAOBCForce + force.addParticle(*parameters) + except NotImplementedError: # CustomGBForce + force.addParticle(parameters) + + system.addForce(force) + + # Get positions for all non-alchemical particles. + non_alchemical_positions = [pos for i, pos in enumerate(positions) + if i not in region.alchemical_atoms] + + # Compute reference force energy. + reference_force_energy = compute_force_energy(system, non_alchemical_positions, force_name) + assert_almost_equal(reference_force_energy, alchemical_energy, + 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) def check_split_force_groups(system): @@ -1221,6 +1235,225 @@ def test_resolve_alchemical_region(): with nose.tools.assert_raises(ValueError): AbsoluteAlchemicalFactory._resolve_alchemical_region(system, alchemical_region) +class TestMultiRegionAbsoluteAlchemicalFactory(object): + """Test AbsoluteAlchemicalFactory class using multiple regions.""" + + @classmethod + def setup_class(cls): + """Create test systems and shared objects.""" + cls.define_systems() + cls.define_regions() + cls.generate_cases() + + @classmethod + def define_systems(cls): + """Create shared test systems in cls.test_systems for the test suite.""" + cls.test_systems = dict() + + # Basic test systems: Lennard-Jones and water particles only. + # Test also dispersion correction and switch off ("on" values + # for these options are tested in HostGuestExplicit system). + cls.test_systems['TIP3P WaterBox with reaction field, no switch, no dispersion correction'] = \ + testsystems.WaterBox(dispersion_correction=False, switch=False, nonbondedMethod=openmm.app.CutoffPeriodic) + + @classmethod + def define_regions(cls): + """Create shared AlchemicalRegions for test systems in cls.test_regions.""" + cls.test_region_zero = dict() + cls.test_region_one = dict() + cls.test_region_two = dict() + + cls.test_region_zero['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3), name='zero') + cls.test_region_one['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3,6), name='one') + cls.test_region_two['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(6,9), name='two') + + @classmethod + def generate_cases(cls): + """Generate all test cases in cls.test_cases combinatorially.""" + cls.test_cases = dict() + direct_space_factory = AbsoluteAlchemicalFactory(alchemical_pme_treatment='direct-space', + alchemical_rf_treatment='switched') + exact_pme_factory = AbsoluteAlchemicalFactory(alchemical_pme_treatment='exact') + + # We generate all possible combinations of annihilate_sterics/electrostatics + # for each test system. We also annihilate bonds, angles and torsions every + # 3 test cases so that we test it at least one for each test system and for + # each combination of annihilate_sterics/electrostatics. + n_test_cases = 0 + for test_system_name, test_system in cls.test_systems.items(): + + # Find standard alchemical region zero. + for region_name_zero, region_zero in cls.test_region_zero.items(): + if region_name_zero in test_system_name: + break + assert region_name_zero in test_system_name, test_system_name + + # Find standard alchemical region one. + for region_name_one, region_one in cls.test_region_one.items(): + if region_name_one in test_system_name: + break + assert region_name_one in test_system_name, test_system_name + + # Find standard alchemical region two. + for region_name_two, region_two in cls.test_region_two.items(): + if region_name_two in test_system_name: + break + assert region_name_two in test_system_name, test_system_name + + assert region_name_zero == region_name_one and region_name_one == region_name_two + test_regions = [region_zero, region_one, region_two] + + # Find nonbonded method. + force_idx, nonbonded_force = forces.find_forces(test_system.system, openmm.NonbondedForce, only_one=True) + nonbonded_method = nonbonded_force.getNonbondedMethod() + + # Create all combinations of annihilate_sterics/electrostatics. + for annihilate_sterics, annihilate_electrostatics in itertools.product((True, False), repeat=2): + # Create new region that we can modify. + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(annihilate_sterics=annihilate_sterics, + annihilate_electrostatics=annihilate_electrostatics) + + # Create test name. + test_case_name = test_system_name[:] + if annihilate_sterics: + test_case_name += ', annihilated sterics' + if annihilate_electrostatics: + test_case_name += ', annihilated electrostatics' + + # Annihilate bonds and angles every three test_cases. + if n_test_cases % 3 == 0: + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(alchemical_bonds=True, alchemical_angles=True, + alchemical_torsions=True) + test_case_name += ', annihilated bonds, angles and torsions' + + # Add different softcore parameters every five test_cases. + if n_test_cases % 5 == 0: + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(softcore_alpha=1.0, softcore_beta=1.0, softcore_a=1.0, softcore_b=1.0, + softcore_c=1.0, softcore_d=1.0, softcore_e=1.0, softcore_f=1.0) + test_case_name += ', modified softcore parameters' + + # Pre-generate alchemical system. + alchemical_system = direct_space_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) + + # Add test case. + cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) + n_test_cases += 1 + + # If we don't use softcore electrostatics and we annihilate charges + # we can test also exact PME treatment. We don't increase n_test_cases + # purposely to keep track of which tests are added above. + if (test_regions[1].softcore_beta == 0.0 and annihilate_electrostatics and + nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]): + alchemical_system = exact_pme_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) + test_case_name += ', exact PME' + cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) + + # If the test system uses reaction field replace reaction field + # of the reference system to allow comparisons. + if nonbonded_method == openmm.NonbondedForce.CutoffPeriodic: + forcefactories.replace_reaction_field(test_system.system, return_copy=False, + switch_width=direct_space_factory.switch_width) + + def filter_cases(self, condition_func, max_number=None): + """Return the list of test cases that satisfy condition_func(test_case_name).""" + if max_number is None: + max_number = len(self.test_cases) + + test_cases = {} + for test_name, test_case in self.test_cases.items(): + if condition_func(test_name): + test_cases[test_name] = test_case + if len(test_cases) >= max_number: + break + return test_cases + + def test_build(self): + pass + + def test_split_force_groups(self): + """Forces having different lambda variables should have a different force group.""" + # Select 1 implicit, 1 explicit, and 1 exact PME explicit test case randomly. + test_cases = self.filter_cases(lambda x: 'Implicit' in x, max_number=1) + test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' in x, max_number=1)) + test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' not in x, max_number=1)) + for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): + f = partial(check_split_force_groups, alchemical_system) + f.description = "Testing force splitting among groups of {}".format(test_name) + yield f + + def test_fully_interacting_energy(self): + """Compare the energies of reference and fully interacting alchemical system.""" + for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): + f = partial(compare_system_energies, test_system.system, + alchemical_system, alchemical_region, test_system.positions) + f.description = "Testing fully interacting energy of {}".format(test_name) + yield f + + def test_noninteracting_energy_components(self): + """Check all forces annihilated/decoupled when their lambda variables are zero.""" + for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): + f = partial(check_noninteracting_energy_components, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Testing non-interacting energy of {}".format(test_name) + yield f + + @attr('slow') + def test_fully_interacting_energy_components(self): + """Test interacting state energy by force component.""" + # This is a very expensive but very informative test. We can + # run this locally when test_fully_interacting_energies() fails. + test_cases = self.filter_cases(lambda x: 'Explicit' in x) + for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): + f = partial(check_interacting_energy_components, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Testing energy components of %s..." % test_name + yield f + + @attr('slow') + def test_platforms(self): + """Test interacting and noninteracting energies on all platforms.""" + global GLOBAL_ALCHEMY_PLATFORM + old_global_platform = GLOBAL_ALCHEMY_PLATFORM + + # Do not repeat tests on the platform already tested. + if old_global_platform is None: + default_platform_name = utils.get_fastest_platform().getName() + else: + default_platform_name = old_global_platform.getName() + platforms = [platform for platform in utils.get_available_platforms() + if platform.getName() != default_platform_name] + + # Test interacting and noninteracting energies on all platforms. + for platform in platforms: + GLOBAL_ALCHEMY_PLATFORM = platform + for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): + f = partial(compare_system_energies, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Test fully interacting energy of {} on {}".format(test_name, platform.getName()) + yield f + f = partial(check_noninteracting_energy_components, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Test non-interacting energy of {} on {}".format(test_name, platform.getName()) + yield f + + # Restore global platform + GLOBAL_ALCHEMY_PLATFORM = old_global_platform + + @attr('slow') + def test_overlap(self): + """Tests overlap between reference and alchemical systems.""" + for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): + #cached_trajectory_filename = os.path.join(os.environ['HOME'], '.cache', 'alchemy', 'tests', + # test_name + '.pickle') + cached_trajectory_filename = None + f = partial(overlap_check, test_system.system, alchemical_system, test_system.positions, + cached_trajectory_filename=cached_trajectory_filename, name=test_name) + f.description = "Testing reference/alchemical overlap for {}".format(test_name) + yield f + class TestAbsoluteAlchemicalFactory(object): """Test AbsoluteAlchemicalFactory class.""" @@ -1374,7 +1607,7 @@ def test_fully_interacting_energy(self): """Compare the energies of reference and fully interacting alchemical system.""" for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): f = partial(compare_system_energies, test_system.system, - alchemical_system, alchemical_region, test_system.positions) + alchemical_system, [alchemical_region], test_system.positions) f.description = "Testing fully interacting energy of {}".format(test_name) yield f @@ -1382,7 +1615,7 @@ def test_noninteracting_energy_components(self): """Check all forces annihilated/decoupled when their lambda variables are zero.""" for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): f = partial(check_noninteracting_energy_components, test_system.system, alchemical_system, - alchemical_region, test_system.positions) + [alchemical_region], test_system.positions) f.description = "Testing non-interacting energy of {}".format(test_name) yield f From 412e5ed788595eaf80e18344d247153b04f4de36 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 26 Jul 2019 18:15:12 +0100 Subject: [PATCH 071/152] LennardJonesCluster and LennardJonesFluid --- openmmtools/tests/test_alchemy.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 05924e888..c107f8989 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -1253,6 +1253,9 @@ def define_systems(cls): # Basic test systems: Lennard-Jones and water particles only. # Test also dispersion correction and switch off ("on" values # for these options are tested in HostGuestExplicit system). + cls.test_systems['LennardJonesCluster'] = testsystems.LennardJonesCluster() + cls.test_systems['LennardJonesFluid with dispersion correction'] = \ + testsystems.LennardJonesFluid(nparticles=100, dispersion_correction=True) cls.test_systems['TIP3P WaterBox with reaction field, no switch, no dispersion correction'] = \ testsystems.WaterBox(dispersion_correction=False, switch=False, nonbondedMethod=openmm.app.CutoffPeriodic) @@ -1262,10 +1265,21 @@ def define_regions(cls): cls.test_region_zero = dict() cls.test_region_one = dict() cls.test_region_two = dict() - + cls.test_region_zero['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2), name='zero') + cls.test_region_one['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2,4), name='one') + cls.test_region_two['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(4,6), name='two') + cls.test_region_zero['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10), name='zero') + cls.test_region_one['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10,20), name='one') + cls.test_region_two['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(20,30), name='two') cls.test_region_zero['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3), name='zero') cls.test_region_one['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3,6), name='one') cls.test_region_two['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(6,9), name='two') + #Not sure how to best convert remaining tests + #cls.test_region_zero['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4), name='zero') # Modify ions. + #cls.test_region_zero['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6), name='zero') + #cls.test_region_zero['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22), name='zero') + #cls.test_region_zero['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156), name='zero') + @classmethod def generate_cases(cls): From 17dd9ba5b99f1955dad2d564139f87b6714fa86f Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 2 Aug 2019 16:29:05 +0100 Subject: [PATCH 072/152] make tests clearer --- openmmtools/alchemy.py | 87 ++++++++++++++++++++---------------------- 1 file changed, 42 insertions(+), 45 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 47612fe95..586f33dbb 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -2264,17 +2264,11 @@ def check_energy_expression(custom_force, parameter): found = True break return found - + force_labels = {} - nonbonded_forces = [] - sterics_none_bond_forces = [] - electro_none_bond_forces = [] - sterics_zero_bond_forces = [] - electro_zero_bond_forces = [] - sterics_one_bond_forces = [] - electro_one_bond_forces = [] - sterics_two_bond_forces = [] - electro_two_bond_forces = [] + nonbonded_forces = {'' :[], 'zero': [], 'one': [], 'two': []} + sterics_bond_forces = {'' :[], 'zero': [], 'one': [], 'two': []} + electro_bond_forces = {'' :[], 'zero': [], 'one': [], 'two': []} # We save CustomBondForces and CustomNonbondedForces used for nonbonded # forces and exceptions to distinguish them later @@ -2292,73 +2286,76 @@ def check_energy_expression(custom_force, parameter): add_label('alchemically modified GBSAOBCForce', force_index) elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda'): if check_energy_expression(force, 'lambda_sterics_zero'): - sterics_zero_bond_forces.append([force_index, force]) + sterics_bond_forces['zero'].append([force_index, force]) elif check_energy_expression(force, 'lambda_sterics_one'): - sterics_one_bond_forces.append([force_index, force]) + sterics_bond_forces['one'].append([force_index, force]) elif check_energy_expression(force, 'lambda_sterics_two'): - sterics_two_bond_forces.append([force_index, force]) + sterics_bond_forces['two'].append([force_index, force]) elif check_energy_expression(force, 'lambda_sterics'): - sterics_none_bond_forces.append([force_index, force]) + sterics_bond_forces[''].append([force_index, force]) elif check_energy_expression(force, 'lambda_electrostatics_zero'): - electro_zero_bond_forces.append([force_index, force]) + electro_bond_forces['zero'].append([force_index, force]) elif check_energy_expression(force, 'lambda_electrostatics_one'): - electro_one_bond_forces.append([force_index, force]) + electro_bond_forces['one'].append([force_index, force]) elif check_energy_expression(force, 'lambda_electrostatics_two'): - electro_two_bond_forces.append([force_index, force]) + electro_bond_forces['two'].append([force_index, force]) elif check_energy_expression(force, 'lambda_electrostatics'): - electro_none_bond_forces.append([force_index, force]) + electro_bond_forces[''].append([force_index, force]) elif (isinstance(force, openmm.CustomNonbondedForce) and force.getEnergyFunction() == '0.0;' and force.getGlobalParameterName(0) == 'lambda_electrostatics'): add_label('CustomNonbondedForce holding alchemical atoms unmodified charges', force_index) elif isinstance(force, openmm.CustomNonbondedForce) and check_energy_expression(force, 'lambda'): if check_energy_expression(force, 'lambda_sterics_zero'): - nonbonded_forces.append(['sterics_zero', force_index, force]) + nonbonded_forces['zero'].append(['sterics', force_index, force]) elif check_energy_expression(force, 'lambda_sterics_one'): - nonbonded_forces.append(['sterics_one', force_index, force]) + nonbonded_forces['one'].append(['sterics', force_index, force]) elif check_energy_expression(force, 'lambda_sterics_two'): - nonbonded_forces.append(['sterics_two', force_index, force]) + nonbonded_forces['two'].append(['sterics', force_index, force]) elif check_energy_expression(force, 'lambda_sterics'): - nonbonded_forces.append(['sterics_None', force_index, force]) + nonbonded_forces[''].append(['sterics', force_index, force]) elif check_energy_expression(force, 'lambda_electrostatics_zero'): - nonbonded_forces.append(['electrostatics_zero', force_index, force]) + nonbonded_forces['zero'].append(['electrostatics', force_index, force]) elif check_energy_expression(force, 'lambda_electrostatics_one'): - nonbonded_forces.append(['electrostatics_one', force_index, force]) + nonbonded_forces['one'].append(['electrostatics',force_index, force]) elif check_energy_expression(force, 'lambda_electrostatics_two'): - nonbonded_forces.append(['electrostatics_two', force_index, force]) + nonbonded_forces['two'].append(['electrostatics', force_index, force]) elif check_energy_expression(force, 'lambda_electrostatics'): - nonbonded_forces.append(['electrostatics_None', force_index, force]) + nonbonded_forces[''].append(['electrostatics', force_index, force]) else: add_label('unmodified ' + force.__class__.__name__, force_index) # Differentiate between na/aa nonbonded forces. - for force_type, force_index, force in nonbonded_forces: - label = 'alchemically modified NonbondedForce for {}alchemical/alchemical ' + force_type - interacting_atoms, alchemical_atoms = force.getInteractionGroupParameters(0) - if interacting_atoms == alchemical_atoms: # alchemical-alchemical atoms - add_label(label.format(''), force_index) - else: - add_label(label.format('non-'), force_index) - - region_names = ['None', 'zero', 'one', 'two'] - steric_bonds_by_region = [sterics_none_bond_forces, sterics_zero_bond_forces, - sterics_one_bond_forces, sterics_two_bond_forces] - electro_bond_by_region = [electro_none_bond_forces, electro_zero_bond_forces, - electro_one_bond_forces, electro_two_bond_forces] + for region_name, forces in nonbonded_forces.items(): + for force_type, force_index, force in forces: + if region_name == '': + label = 'alchemically modified NonbondedForce for {}alchemical/alchemical ' + force_type + else: + label = 'alchemically modified NonbondedForce for {}alchemical/alchemical ' + force_type +\ + ' for region ' + region_name + interacting_atoms, alchemical_atoms = force.getInteractionGroupParameters(0) + if interacting_atoms == alchemical_atoms: # alchemical-alchemical atoms + add_label(label.format(''), force_index) + else: + add_label(label.format('non-'), force_index) # Differentiate between na/aa bond forces for exceptions. - for i, (sterics_bond_forces, electro_bond_forces) in enumerate(zip(steric_bonds_by_region, electro_bond_by_region)): - if len(sterics_bond_forces) == 0: + for (region_name, sterics_forces), electro_forces in zip(sterics_bond_forces.items(), electro_bond_forces.values()): + if len(sterics_forces) == 0: continue - region_name = region_names[i] - for force_type, bond_forces in [('sterics', sterics_bond_forces), ('electrostatics', electro_bond_forces)]: + for force_type, bond_forces in [('sterics', sterics_forces), ('electrostatics', electro_forces)]: # With exact PME there are no CustomBondForces modeling electrostatics exceptions. if force_type == 'electrostatics' and len(bond_forces) == 0: continue # Otherwise there should be two CustomBondForce. assert len(bond_forces) == 2 - label = 'alchemically modified BondForce for {}alchemical/alchemical '\ - + force_type + '_{}'.format(region_name) + ' exceptions' + print(region_name) + if region_name == '': + label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type + ' exceptions' + else: + label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type +\ + ' exceptions for region ' + region_name + print(label) # Sort forces by number of bonds. bond_forces = sorted(bond_forces, key=lambda x: x[1].getNumBonds()) (force_index1, force1), (force_index2, force2) = bond_forces From 81755a9634a4e12648ae8d930e527b61498983bd Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 2 Aug 2019 16:29:40 +0100 Subject: [PATCH 073/152] make tests clearer --- openmmtools/tests/test_alchemy.py | 112 +++++++++++++++--------------- 1 file changed, 57 insertions(+), 55 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index c107f8989..f4dd6a9cf 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -564,7 +564,7 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc try: na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics'] aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics'] - na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions'] + na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics_ exceptions'] aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions'] except KeyError: assert is_exact_pme @@ -695,61 +695,64 @@ def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_system = copy.deepcopy(alchemical_system) is_exact_pme = is_alchemical_pme_treatment_exact(alchemical_system) + if isinstance(alchemical_regions, list): + multiple_regions = True + else: + multiple_regions = False + alchemical_regions = [alchemical_regions] + energy_components = {} - # Set state to non-interacting. for region in alchemical_regions: - alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix = region.name) + # Set state to non-interacting. + alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix=region.name) alchemical_state.set_alchemical_parameters(0.0) energy_components.update({region.name : AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, - positions, platform=GLOBAL_ALCHEMY_PLATFORM)}) + positions, + platform=GLOBAL_ALCHEMY_PLATFORM)}) - def assert_zero_energy(label, region_name): - print('testing {}'.format(label)) - value = energy_components[region_name][label] - assert abs(value / GLOBAL_ENERGY_UNIT) == 0.0, ("'{}' should have zero energy in annihilated alchemical" - " state, but energy is {}").format(label, str(value)) - for region in alchemical_regions: - # Check that non-alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated - assert_zero_energy('alchemically modified BondForce for' - ' non-alchemical/alchemical sterics_{} exceptions'.format(region.name), region.name) - assert_zero_energy('alchemically modified NonbondedForce for' - ' non-alchemical/alchemical sterics_{}'.format(region.name), region.name) + def assert_zero_energy(label): + # Handle multiple alchemical regions. + if multiple_regions: + force_labels = [label + ' for region ' + region.name for region in alchemical_regions] + else: + force_labels = [label] + # Testing energy component of each region. + for force_label, region in zip(force_labels, alchemical_regions): + print('testing {}'.format(force_label)) + value = energy_components[region.name][force_label] + assert abs(value / GLOBAL_ENERGY_UNIT) == 0.0, ("'{}' should have zero energy in annihilated alchemical" + " state, but energy is {}").format(region_label, str(value)) + + # Check that non-alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated + assert_zero_energy('alchemically modified BondForce for non-alchemical/alchemical sterics exceptions') + assert_zero_energy('alchemically modified NonbondedForce for non-alchemical/alchemical sterics') + if is_exact_pme: + assert 'alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics' not in energy_components + assert 'alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions' not in energy_components + else: + assert_zero_energy('alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics') + assert_zero_energy('alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions') + + # Check that alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated + if alchemical_regions[0].annihilate_sterics: + assert_zero_energy('alchemically modified NonbondedForce for alchemical/alchemical sterics') + assert_zero_energy('alchemically modified BondForce for alchemical/alchemical sterics exceptions') + if alchemical_regions[0].annihilate_electrostatics: if is_exact_pme: - assert 'alchemically modified NonbondedForce for' \ - ' non-alchemical/alchemical electrostatics_{}'.format(region.name) not in energy_components - assert 'alchemically modified BondForce for' \ - ' non-alchemical/alchemical electrostatics_{} exceptions'.format(region.name) not in energy_components + assert 'alchemically modified NonbondedForce for alchemical/alchemical electrostatics' not in energy_components + assert 'alchemically modified BondForce for alchemical/alchemical electrostatics exceptions' not in energy_components else: - assert_zero_energy('alchemically modified NonbondedForce for' - ' non-alchemical/alchemical electrostatics_{}'.format(region.name), region.name) - assert_zero_energy('alchemically modified BondForce for' - ' non-alchemical/alchemical electrostatics_{} exceptions'.format(region.name), region.name) - - # Check that alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated - if region.annihilate_sterics: - assert_zero_energy('alchemically modified NonbondedForce for' - ' alchemical/alchemical sterics_{}'.format(region.name), region.name) - assert_zero_energy('alchemically modified BondForce for' - ' alchemical/alchemical sterics_{} exceptions'.format(region.name), region.name) - if region.annihilate_electrostatics: - if is_exact_pme: - assert 'alchemically modified NonbondedForce for' \ - ' alchemical/alchemical electrostatics_{}'.format(region.name) not in energy_components - assert 'alchemically modified BondForce for' \ - ' alchemical/alchemical electrostatics_{} exceptions'.format(region.name) not in energy_components - else: - assert_zero_energy('alchemically modified NonbondedForce for' - ' alchemical/alchemical electrostatics_{}'.format(region.name), region.name) - assert_zero_energy('alchemically modified BondForce for' - ' alchemical/alchemical electrostatics_{} exceptions'.format(region.name), region.name) - - # Check valence terms - for force_name in ['HarmonicBondForce', 'HarmonicAngleForce', 'PeriodicTorsionForce']: - force_label = 'alchemically modified ' + force_name - if force_label in energy_components: - assert_zero_energy(force_label, region.name) - - # Check implicit solvent force. + assert_zero_energy('alchemically modified NonbondedForce for alchemical/alchemical electrostatics') + assert_zero_energy('alchemically modified BondForce for alchemical/alchemical electrostatics exceptions') + + # Check valence terms + for force_name in ['HarmonicBondForce', 'HarmonicAngleForce', 'PeriodicTorsionForce']: + force_label = 'alchemically modified ' + force_name + if force_label in energy_components: + assert_zero_energy(force_label) + + # Check implicit solvent force. + for region in alchemical_regions: for force_name in ['CustomGBForce', 'GBSAOBCForce']: label = 'alchemically modified ' + force_name @@ -761,7 +764,7 @@ def assert_zero_energy(label, region_name): # If all alchemical particles are modified, the alchemical energy should be zero. if len(region.alchemical_atoms) == reference_system.getNumParticles(): - assert_zero_energy(label, region.name) + assert_zero_energy(label) continue # Otherwise compare the alchemical energy with a @@ -824,7 +827,6 @@ def assert_zero_energy(label, region_name): assert_almost_equal(reference_force_energy, alchemical_energy, 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) - def check_split_force_groups(system): """Check that force groups are split correctly.""" force_groups_by_lambda = {} @@ -1265,6 +1267,7 @@ def define_regions(cls): cls.test_region_zero = dict() cls.test_region_one = dict() cls.test_region_two = dict() + cls.test_region_zero['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2), name='zero') cls.test_region_one['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2,4), name='one') cls.test_region_two['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(4,6), name='two') @@ -1280,7 +1283,6 @@ def define_regions(cls): #cls.test_region_zero['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22), name='zero') #cls.test_region_zero['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156), name='zero') - @classmethod def generate_cases(cls): """Generate all test cases in cls.test_cases combinatorially.""" @@ -1610,7 +1612,7 @@ def test_split_force_groups(self): """Forces having different lambda variables should have a different force group.""" # Select 1 implicit, 1 explicit, and 1 exact PME explicit test case randomly. test_cases = self.filter_cases(lambda x: 'Implicit' in x, max_number=1) - test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' in x, max_number=1)) + test_cases.update(self.filter_cases(lambda x: 'SrcExplicit ' in x and 'exact PME' in x, max_number=1)) test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' not in x, max_number=1)) for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): f = partial(check_split_force_groups, alchemical_system) @@ -1621,7 +1623,7 @@ def test_fully_interacting_energy(self): """Compare the energies of reference and fully interacting alchemical system.""" for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): f = partial(compare_system_energies, test_system.system, - alchemical_system, [alchemical_region], test_system.positions) + alchemical_system, alchemical_region, test_system.positions) f.description = "Testing fully interacting energy of {}".format(test_name) yield f @@ -1629,7 +1631,7 @@ def test_noninteracting_energy_components(self): """Check all forces annihilated/decoupled when their lambda variables are zero.""" for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): f = partial(check_noninteracting_energy_components, test_system.system, alchemical_system, - [alchemical_region], test_system.positions) + alchemical_region, test_system.positions) f.description = "Testing non-interacting energy of {}".format(test_name) yield f From aeb45eeafa2e2266eebf7f02f91e7c96025de865 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 9 Aug 2019 15:31:01 +0100 Subject: [PATCH 074/152] tests working --- openmmtools/alchemy.py | 176 +++++++++++++++++++++++++++++------------ 1 file changed, 125 insertions(+), 51 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 586f33dbb..ee8827bc6 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -797,7 +797,6 @@ def get_energy_components(cls, alchemical_system, alchemical_state, positions, p groups=2**force_index).getPotentialEnergy() # Clean up del context, integrator - return energy_components # ------------------------------------------------------------------------- @@ -1074,7 +1073,36 @@ def _add_alchemical_forces(self, alchemical_system, alchemical_forces_by_lambda) alchemical_system.addForce(force) @staticmethod - def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_regions, _): + def _is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + """Test if a set of particles are in two regions simultaneously and if these regions are interacting + + Parameters + ---------- + particles: set() + Set of particles to test check if they in two regions + alchemical_region : AlchemicalRegion + The alchemical region containing the indices of the torsions to test. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. + + """ + for i, alchemical_region_A in enumerate(alchemical_regions): + if alchemical_region_A.alchemical_atoms.intersection(particles): + j = 0 + while j < i: + alchemical_region_B = alchemical_regions[j] + if alchemical_region_B.alchemical_atoms.intersection(particles): + if {i, j} in alchemical_regions_interactions: + return False + else: + return True + j += 1 + return False + + @staticmethod + def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of PeriodicTorsionForce. Parameters @@ -1110,7 +1138,16 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region for torsion_index in range(reference_force.getNumTorsions()): if torsion_index not in all_alchemical_torsions: particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) - force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) + particles = set((particle1, particle2, particle3, particle4)) + if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + pass + else: + force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) + else: + # Check there are no alchemical torsions straddling regions + msg = 'No support for alchemical torsions across multiple alchemical regions' + if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + raise NotImplemented(msg) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -1147,7 +1184,7 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region return alchemical_forces @staticmethod - def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, _): + def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of HarmonicAngleForce Parameters @@ -1170,7 +1207,6 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, """ alchemical_forces = {} all_alchemical_angles = set() - # Don't create a force if there are no alchemical angles. for alchemical_region in alchemical_regions: all_alchemical_angles.update(alchemical_region.alchemical_angles) @@ -1183,7 +1219,16 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, for angle_index in range(reference_force.getNumAngles()): if angle_index not in all_alchemical_angles: [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) - force.addAngle(particle1, particle2, particle3, theta0, K) + particles = set((particle1, particle2, particle3)) + if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + pass + else: + force.addAngle(particle1, particle2, particle3, theta0, K) + else: + # Check there are no alchemical angles straddling regions + msg = 'No support for alchemical angles across multiple alchemical regions' + if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + raise NotImplemented(msg) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -1217,7 +1262,7 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, return alchemical_forces @staticmethod - def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, _): + def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of HarmonicBondForce Parameters @@ -1253,7 +1298,16 @@ def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, for bond_index in range(reference_force.getNumBonds()): if bond_index not in all_alchemical_bonds: [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) - force.addBond(particle1, particle2, theta0, K) + particles = set((particle1, particle2)) + if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + pass + else: + force.addBond(particle1, particle2, theta0, K) + else: + # Check there are no alchemical bonds straddling regions + msg = 'No support for alchemical bonds across multiple alchemical regions' + if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + raise NotImplemented(msg) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -2273,58 +2327,78 @@ def check_energy_expression(custom_force, parameter): # We save CustomBondForces and CustomNonbondedForces used for nonbonded # forces and exceptions to distinguish them later for force_index, force in enumerate(alchemical_system.getForces()): - if isinstance(force, openmm.CustomAngleForce) and check_parameter(force, 'lambda_angles'): - add_label('alchemically modified HarmonicAngleForce', force_index) - elif isinstance(force, openmm.CustomBondForce) and check_parameter(force, 'lambda_bonds'): - add_label('alchemically modified HarmonicBondForce', force_index) - elif isinstance(force, openmm.CustomTorsionForce) and check_parameter(force, 'lambda_torsions'): - add_label('alchemically modified PeriodicTorsionForce', force_index) + if isinstance(force, openmm.CustomAngleForce) and check_energy_expression(force, 'lambda_angles'): + if check_parameter(force, 'lambda_angles_zero'): + add_label('alchemically modified HarmonicAngleForce for region zero', force_index) + elif check_parameter(force, 'lambda_angles_one'): + add_label('alchemically modified HarmonicAngleForce for region one', force_index) + elif check_parameter(force, 'lambda_angles_two'): + add_label('alchemically modified HarmonicAngleForce for region two', force_index) + elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda_bonds'): + if check_parameter(force, 'lambda_bonds_zero'): + add_label('alchemically modified HarmonicBondForce for region zero', force_index) + elif check_parameter(force, 'lambda_bonds_one'): + add_label('alchemically modified HarmonicBondForce for region one', force_index) + elif check_parameter(force, 'lambda_bonds_two'): + add_label('alchemically modified HarmonicBondForce for region two', force_index) + elif isinstance(force, openmm.CustomTorsionForce) and check_energy_expression(force, 'lambda_torsions'): + if check_parameter(force, 'lambda_torsions_zero'): + add_label('alchemically modified PeriodicTorsionForce for region zero', force_index) + elif check_parameter(force, 'lambda_torsions_one'): + add_label('alchemically modified PeriodicTorsionForce for region one', force_index) + elif check_parameter(force, 'lambda_torsions_two'): + add_label('alchemically modified PeriodicTorsionForce for region two', force_index) elif isinstance(force, openmm.CustomGBForce) and check_parameter(force, 'lambda_electrostatics'): if check_energy_expression(force, 'unscaled'): add_label('alchemically modified CustomGBForce', force_index) else: add_label('alchemically modified GBSAOBCForce', force_index) elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda'): - if check_energy_expression(force, 'lambda_sterics_zero'): - sterics_bond_forces['zero'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_one'): - sterics_bond_forces['one'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_two'): - sterics_bond_forces['two'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_sterics'): - sterics_bond_forces[''].append([force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_zero'): - electro_bond_forces['zero'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_one'): - electro_bond_forces['one'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_two'): - electro_bond_forces['two'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics'): - electro_bond_forces[''].append([force_index, force]) + if check_energy_expression(force, 'lambda_sterics'): + if check_energy_expression(force, 'lambda_sterics_zero'): + sterics_bond_forces['zero'].append([force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_one'): + sterics_bond_forces['one'].append([force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_two'): + sterics_bond_forces['two'].append([force_index, force]) + else: + sterics_bond_forces[''].append([force_index, force]) + if check_energy_expression(force, 'lambda_electrostatics'): + if check_energy_expression(force, 'lambda_electrostatics_zero'): + electro_bond_forces['zero'].append([force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_one'): + electro_bond_forces['one'].append([force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_two'): + electro_bond_forces['two'].append([force_index, force]) + else: + electro_bond_forces[''].append([force_index, force]) elif (isinstance(force, openmm.CustomNonbondedForce) and force.getEnergyFunction() == '0.0;' and force.getGlobalParameterName(0) == 'lambda_electrostatics'): add_label('CustomNonbondedForce holding alchemical atoms unmodified charges', force_index) elif isinstance(force, openmm.CustomNonbondedForce) and check_energy_expression(force, 'lambda'): - if check_energy_expression(force, 'lambda_sterics_zero'): - nonbonded_forces['zero'].append(['sterics', force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_one'): - nonbonded_forces['one'].append(['sterics', force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_two'): - nonbonded_forces['two'].append(['sterics', force_index, force]) - elif check_energy_expression(force, 'lambda_sterics'): - nonbonded_forces[''].append(['sterics', force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_zero'): - nonbonded_forces['zero'].append(['electrostatics', force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_one'): - nonbonded_forces['one'].append(['electrostatics',force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_two'): - nonbonded_forces['two'].append(['electrostatics', force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics'): - nonbonded_forces[''].append(['electrostatics', force_index, force]) + if check_energy_expression(force, 'lambda_sterics'): + if check_energy_expression(force, 'lambda_sterics_zero'): + nonbonded_forces['zero'].append(['sterics', force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_one'): + nonbonded_forces['one'].append(['sterics', force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_two'): + nonbonded_forces['two'].append(['sterics', force_index, force]) + else: + nonbonded_forces[''].append(['sterics', force_index, force]) + if check_energy_expression(force, 'lambda_electrostatics'): + if check_energy_expression(force, 'lambda_electrostatics_zero'): + nonbonded_forces['zero'].append(['electrostatics', force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_one'): + nonbonded_forces['one'].append(['electrostatics',force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_two'): + nonbonded_forces['two'].append(['electrostatics', force_index, force]) + else: + nonbonded_forces[''].append(['electrostatics', force_index, force]) else: add_label('unmodified ' + force.__class__.__name__, force_index) # Differentiate between na/aa nonbonded forces. + alchemical_atoms_by_region = {} for region_name, forces in nonbonded_forces.items(): for force_type, force_index, force in forces: if region_name == '': @@ -2333,11 +2407,12 @@ def check_energy_expression(custom_force, parameter): label = 'alchemically modified NonbondedForce for {}alchemical/alchemical ' + force_type +\ ' for region ' + region_name interacting_atoms, alchemical_atoms = force.getInteractionGroupParameters(0) + alchemical_atoms_by_region[region_name] = [interacting_atoms, alchemical_atoms] if interacting_atoms == alchemical_atoms: # alchemical-alchemical atoms add_label(label.format(''), force_index) else: add_label(label.format('non-'), force_index) - + # Differentiate between na/aa bond forces for exceptions. for (region_name, sterics_forces), electro_forces in zip(sterics_bond_forces.items(), electro_bond_forces.values()): if len(sterics_forces) == 0: @@ -2348,21 +2423,21 @@ def check_energy_expression(custom_force, parameter): continue # Otherwise there should be two CustomBondForce. assert len(bond_forces) == 2 - print(region_name) if region_name == '': label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type + ' exceptions' else: label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type +\ ' exceptions for region ' + region_name - print(label) # Sort forces by number of bonds. bond_forces = sorted(bond_forces, key=lambda x: x[1].getNumBonds()) (force_index1, force1), (force_index2, force2) = bond_forces - + # Check if both define their parameters (with decoupling the lambda # parameter doesn't exist in the alchemical-alchemical force) parameter_name = 'lambda_' + force_type + '_{}'.format(region_name) + interacting_atoms, alchemical_atoms = alchemical_atoms_by_region[region_name] + if check_parameter(force1, parameter_name) != check_parameter(force2, parameter_name): if check_parameter(force1, parameter_name): add_label(label.format('non-'), force_index1) @@ -2386,7 +2461,6 @@ def check_energy_expression(custom_force, parameter): else: add_label(label.format('non-'), force_index2) add_label(label.format(''), force_index1) - return force_labels From a3534094a52b222a5d69393bb50724bd0d2213e4 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 9 Aug 2019 15:32:15 +0100 Subject: [PATCH 075/152] tests working --- openmmtools/tests/test_alchemy.py | 609 ++++++++++++++++-------------- 1 file changed, 327 insertions(+), 282 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index f4dd6a9cf..59d00b7aa 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -212,7 +212,7 @@ def turn_off_nonbonded(system, sterics=False, electrostatics=False, -def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): +def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, other_alchemical_atoms): """Dissect the nonbonded energy contributions of the reference system by atom group and sterics/electrostatics. @@ -249,7 +249,8 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): na_reciprocal_energy: electrostatics of reciprocal space between nonalchemical-alchemical atoms """ - nonalchemical_atoms = set(range(reference_system.getNumParticles())).difference(alchemical_atoms) + all_alchemical_atoms = set(alchemical_atoms).union(other_alchemical_atoms) + nonalchemical_atoms = set(range(reference_system.getNumParticles())).difference(all_alchemical_atoms) # Remove all forces but NonbondedForce and eventually the # CustomNonbondedForce used to model reaction field. @@ -270,11 +271,15 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): # Compute particle interactions between different groups of atoms # ---------------------------------------------------------------- + #Turn off other alchemical regions + turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, only_atoms=other_alchemical_atoms) + turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, exceptions=True, only_atoms=other_alchemical_atoms) system = copy.deepcopy(reference_system) # Compute total energy from nonbonded interactions tot_energy = compute_energy(system, positions) tot_reciprocal_energy = compute_energy(system, positions, force_group={30}) + system = copy.deepcopy(reference_system) # Restore alchemical sterics/electro of other alch_atoms # Compute contributions from particle sterics turn_off_nonbonded(system, sterics=True, only_atoms=alchemical_atoms) @@ -317,7 +322,7 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): # Compute contributions from exceptions sterics system = copy.deepcopy(reference_system) # Restore particle interactions - turn_off_nonbonded(system, sterics=True, exceptions=True, only_atoms=alchemical_atoms) + turn_off_nonbonded(system, sterics=True, exceptions=True, only_atoms=all_alchemical_atoms) tot_energy_no_alchem_exception_sterics = compute_energy(system, positions) system = copy.deepcopy(reference_system) # Restore alchemical sterics turn_off_nonbonded(system, sterics=True, exceptions=True, only_atoms=nonalchemical_atoms) @@ -332,7 +337,7 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): # Compute contributions from exceptions electrostatics system = copy.deepcopy(reference_system) # Restore exceptions sterics - turn_off_nonbonded(system, electrostatics=True, exceptions=True, only_atoms=alchemical_atoms) + turn_off_nonbonded(system, electrostatics=True, exceptions=True, only_atoms=all_alchemical_atoms) tot_energy_no_alchem_exception_electro = compute_energy(system, positions) system = copy.deepcopy(reference_system) # Restore alchemical electrostatics turn_off_nonbonded(system, electrostatics=True, exceptions=True, only_atoms=nonalchemical_atoms) @@ -436,10 +441,12 @@ def is_alchemical_pme_treatment_exact(alchemical_system): # lambda_electrostatics variable. _, nonbonded_force = forces.find_forces(alchemical_system, openmm.NonbondedForce, only_one=True) + test_electro_suffixes = ['', '_zero', '_one', '_two'] for parameter_idx in range(nonbonded_force.getNumGlobalParameters()): parameter_name = nonbonded_force.getGlobalParameterName(parameter_idx) - if parameter_name == 'lambda_electrostatics': - return True + for suffix in test_electro_suffixes: + if parameter_name == 'lambda_electrostatics{}'.format(suffix): + return True return False @@ -502,8 +509,30 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi err_msg = "Maximum allowable deviation exceeded (was {:.8f} kcal/mol; allowed {:.8f} kcal/mol)." raise Exception(err_msg.format(delta / unit.kilocalories_per_mole, MAX_DELTA / unit.kilocalories_per_mole)) +def check_multi_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): + """wrapper around check_interacting_energy_components for multiple regions -def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): + Parameters + ---------- + reference_system : simtk.openmm.System + The reference system. + alchemical_system : simtk.openmm.System + The alchemically modified system to test. + alchemical_regions : AlchemicalRegion. + The alchemically modified region. + positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity + The positions to test (units of length). + + """ + all_alchemical_atoms = set() + for region in alchemical_regions: + for atom in region.alchemical_atoms: + all_alchemical_atoms.add(atom) + for region in alchemical_regions: + check_interacting_energy_components(reference_system, alchemical_system, region, positions, all_alchemical_atoms, True) + +def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, + all_alchemical_atoms=None, multi_regions=False): """Compare full and alchemically-modified system energies by energy component. Parameters @@ -516,6 +545,8 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc The alchemically modified region. positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity The positions to test (units of length). + multi_regions : boolean + Indicates if mutiple regions are being tested """ energy_unit = unit.kilojoule_per_mole @@ -528,9 +559,15 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc nonbonded_method = nonbonded_force.getNonbondedMethod() # Get energy components of reference system's nonbonded force - print("Dissecting reference system's nonbonded force") + if multi_regions: + other_alchemical_atoms = all_alchemical_atoms.difference(alchemical_regions.alchemical_atoms) + print("Dissecting reference system's nonbonded force for region {}".format(alchemical_regions.name)) + else: + other_alchemical_atoms = set() + print("Dissecting reference system's nonbonded force") + energy_components = dissect_nonbonded_energy(reference_system, positions, - alchemical_regions.alchemical_atoms) + alchemical_regions.alchemical_atoms, other_alchemical_atoms) nn_particle_sterics, aa_particle_sterics, na_particle_sterics,\ nn_particle_electro, aa_particle_electro, na_particle_electro,\ nn_exception_sterics, aa_exception_sterics, na_exception_sterics,\ @@ -538,9 +575,12 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc nn_reciprocal_energy, aa_reciprocal_energy, na_reciprocal_energy = energy_components # Dissect unmodified nonbonded force in alchemical system - print("Dissecting alchemical system's unmodified nonbonded force") + if multi_regions: + print("Dissecting alchemical system's unmodified nonbonded force for region {}".format(alchemical_regions.name)) + else: + print("Dissecting alchemical system's unmodified nonbonded force") energy_components = dissect_nonbonded_energy(alchemical_system, positions, - alchemical_regions.alchemical_atoms) + alchemical_regions.alchemical_atoms, other_alchemical_atoms) unmod_nn_particle_sterics, unmod_aa_particle_sterics, unmod_na_particle_sterics,\ unmod_nn_particle_electro, unmod_aa_particle_electro, unmod_na_particle_electro,\ unmod_nn_exception_sterics, unmod_aa_exception_sterics, unmod_na_exception_sterics,\ @@ -548,24 +588,31 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc unmod_nn_reciprocal_energy, unmod_aa_reciprocal_energy, unmod_na_reciprocal_energy = energy_components # Get alchemically-modified energy components - print("Computing alchemical system components energies") - alchemical_state = AlchemicalState.from_system(alchemical_system) + if multi_regions: + print("Computing alchemical system components energies for region {}".format(alchemical_regions.name)) + else: + print("Computing alchemical system components energies") + alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix=alchemical_regions.name) alchemical_state.set_alchemical_parameters(1.0) energy_components = AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, positions, platform=GLOBAL_ALCHEMY_PLATFORM) + if multi_regions: + region_lable = ' for region {}'.format(alchemical_regions.name) + else: + region_lable = '' # Sterics particle and exception interactions are always modeled with a custom force. - na_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical sterics'] - aa_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for alchemical/alchemical sterics'] - na_custom_exception_sterics = energy_components['alchemically modified BondForce for non-alchemical/alchemical sterics exceptions'] - aa_custom_exception_sterics = energy_components['alchemically modified BondForce for alchemical/alchemical sterics exceptions'] + na_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical sterics' + region_lable] + aa_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for alchemical/alchemical sterics' + region_lable] + na_custom_exception_sterics = energy_components['alchemically modified BondForce for non-alchemical/alchemical sterics exceptions' + region_lable] + aa_custom_exception_sterics = energy_components['alchemically modified BondForce for alchemical/alchemical sterics exceptions' + region_lable] # With exact treatment of PME, we use the NonbondedForce offset for electrostatics. try: - na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics'] - aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics'] - na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics_ exceptions'] - aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions'] + na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics' + region_lable] + aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics' + region_lable] + na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions' + region_lable] + aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions' + region_lable] except KeyError: assert is_exact_pme @@ -589,41 +636,41 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc # Check sterics interactions match assert_almost_equal(nn_particle_sterics, unmod_nn_particle_sterics, - 'Non-alchemical/non-alchemical atoms particle sterics') + 'Non-alchemical/non-alchemical atoms particle sterics' + region_lable) assert_almost_equal(nn_exception_sterics, unmod_nn_exception_sterics, - 'Non-alchemical/non-alchemical atoms exceptions sterics') + 'Non-alchemical/non-alchemical atoms exceptions sterics' + region_lable) assert_almost_equal(aa_particle_sterics, aa_custom_particle_sterics, - 'Alchemical/alchemical atoms particle sterics') + 'Alchemical/alchemical atoms particle sterics' + region_lable) assert_almost_equal(aa_exception_sterics, aa_custom_exception_sterics, - 'Alchemical/alchemical atoms exceptions sterics') + 'Alchemical/alchemical atoms exceptions sterics' + region_lable) assert_almost_equal(na_particle_sterics, na_custom_particle_sterics, - 'Non-alchemical/alchemical atoms particle sterics') + 'Non-alchemical/alchemical atoms particle sterics' + region_lable) assert_almost_equal(na_exception_sterics, na_custom_exception_sterics, - 'Non-alchemical/alchemical atoms exceptions sterics') + 'Non-alchemical/alchemical atoms exceptions sterics' + region_lable) # Check electrostatics interactions assert_almost_equal(nn_particle_electro, unmod_nn_particle_electro, - 'Non-alchemical/non-alchemical atoms particle electrostatics') + 'Non-alchemical/non-alchemical atoms particle electrostatics' + region_lable) assert_almost_equal(nn_exception_electro, unmod_nn_exception_electro, - 'Non-alchemical/non-alchemical atoms exceptions electrostatics') + 'Non-alchemical/non-alchemical atoms exceptions electrostatics' + region_lable) # With exact treatment of PME, the electrostatics of alchemical-alchemical # atoms is modeled with NonbondedForce offsets. if is_exact_pme: # Reciprocal space. assert_almost_equal(aa_reciprocal_energy, unmod_aa_reciprocal_energy, - 'Alchemical/alchemical atoms reciprocal space energy') + 'Alchemical/alchemical atoms reciprocal space energy' + region_lable) assert_almost_equal(na_reciprocal_energy, unmod_na_reciprocal_energy, - 'Non-alchemical/alchemical atoms reciprocal space energy') + 'Non-alchemical/alchemical atoms reciprocal space energy' + region_lable) # Direct space. assert_almost_equal(aa_particle_electro, unmod_aa_particle_electro, - 'Alchemical/alchemical atoms particle electrostatics') + 'Alchemical/alchemical atoms particle electrostatics' + region_lable) assert_almost_equal(na_particle_electro, unmod_na_particle_electro, - 'Non-alchemical/alchemical atoms particle electrostatics') + 'Non-alchemical/alchemical atoms particle electrostatics' + region_lable) # Exceptions. assert_almost_equal(aa_exception_electro, unmod_aa_exception_electro, - 'Alchemical/alchemical atoms exceptions electrostatics') + 'Alchemical/alchemical atoms exceptions electrostatics' + region_lable) assert_almost_equal(na_exception_electro, unmod_na_exception_electro, - 'Non-alchemical/alchemical atoms exceptions electrostatics') + 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_lable) # With direct space PME, the custom forces model only the # direct space of alchemical-alchemical interactions. else: @@ -636,14 +683,14 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc # Check direct space energy assert_almost_equal(aa_particle_electro, aa_custom_particle_electro, - 'Alchemical/alchemical atoms particle electrostatics') + 'Alchemical/alchemical atoms particle electrostatics' + region_lable) assert_almost_equal(na_particle_electro, na_custom_particle_electro, - 'Non-alchemical/alchemical atoms particle electrostatics') + 'Non-alchemical/alchemical atoms particle electrostatics' + region_lable) # Check exceptions. assert_almost_equal(aa_exception_electro, aa_custom_exception_electro, - 'Alchemical/alchemical atoms exceptions electrostatics') + 'Alchemical/alchemical atoms exceptions electrostatics' + region_lable) assert_almost_equal(na_exception_electro, na_custom_exception_electro, - 'Non-alchemical/alchemical atoms exceptions electrostatics') + 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_lable) # With Ewald methods, the NonbondedForce should always hold the # reciprocal space energy of nonalchemical-nonalchemical atoms. @@ -676,10 +723,24 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc assert_almost_equal(reference_force_energy, tot_alchemical_forces_energies, '{} energy '.format(force_name)) +def check_multi_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): + """wrapper around check_noninteracting_energy_components for multiple regions + Parameters + ---------- + reference_system : simtk.openmm.System + The reference system (not alchemically modified). + alchemical_system : simtk.openmm.System + The alchemically modified system to test. + alchemical_regions : AlchemicalRegion. + The alchemically modified region. + positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity + The positions to test (units of length). + """ + for region in alchemical_regions: + check_noninteracting_energy_components(reference_system, alchemical_system, region, positions, True) -def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): +def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, multi_regions=False): """Check non-interacting energy components are zero when appropriate. - Parameters ---------- reference_system : simtk.openmm.System @@ -690,38 +751,27 @@ def check_noninteracting_energy_components(reference_system, alchemical_system, The alchemically modified region. positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity The positions to test (units of length). - + multi_regions : boolean + Indicates if mutiple regions are being tested """ alchemical_system = copy.deepcopy(alchemical_system) is_exact_pme = is_alchemical_pme_treatment_exact(alchemical_system) - if isinstance(alchemical_regions, list): - multiple_regions = True - else: - multiple_regions = False - alchemical_regions = [alchemical_regions] - - energy_components = {} - for region in alchemical_regions: - # Set state to non-interacting. - alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix=region.name) - alchemical_state.set_alchemical_parameters(0.0) - energy_components.update({region.name : AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, - positions, - platform=GLOBAL_ALCHEMY_PLATFORM)}) + # Set state to non-interacting. + alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix=alchemical_regions.name) + alchemical_state.set_alchemical_parameters(0.0) + energy_components = AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, + positions, platform=GLOBAL_ALCHEMY_PLATFORM) def assert_zero_energy(label): # Handle multiple alchemical regions. - if multiple_regions: - force_labels = [label + ' for region ' + region.name for region in alchemical_regions] - else: - force_labels = [label] + if multi_regions: + label = label + ' for region ' + alchemical_regions.name # Testing energy component of each region. - for force_label, region in zip(force_labels, alchemical_regions): - print('testing {}'.format(force_label)) - value = energy_components[region.name][force_label] - assert abs(value / GLOBAL_ENERGY_UNIT) == 0.0, ("'{}' should have zero energy in annihilated alchemical" - " state, but energy is {}").format(region_label, str(value)) + print('testing {}'.format(label)) + value = energy_components[label] + assert abs(value / GLOBAL_ENERGY_UNIT) == 0.0, ("'{}' should have zero energy in annihilated alchemical" + " state, but energy is {}").format(label, str(value)) # Check that non-alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated assert_zero_energy('alchemically modified BondForce for non-alchemical/alchemical sterics exceptions') @@ -734,10 +784,10 @@ def assert_zero_energy(label): assert_zero_energy('alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions') # Check that alchemical/alchemical particle interactions and 1,4 exceptions have been annihilated - if alchemical_regions[0].annihilate_sterics: + if alchemical_regions.annihilate_sterics: assert_zero_energy('alchemically modified NonbondedForce for alchemical/alchemical sterics') assert_zero_energy('alchemically modified BondForce for alchemical/alchemical sterics exceptions') - if alchemical_regions[0].annihilate_electrostatics: + if alchemical_regions.annihilate_electrostatics: if is_exact_pme: assert 'alchemically modified NonbondedForce for alchemical/alchemical electrostatics' not in energy_components assert 'alchemically modified BondForce for alchemical/alchemical electrostatics exceptions' not in energy_components @@ -752,80 +802,119 @@ def assert_zero_energy(label): assert_zero_energy(force_label) # Check implicit solvent force. - for region in alchemical_regions: - for force_name in ['CustomGBForce', 'GBSAOBCForce']: - label = 'alchemically modified ' + force_name + for force_name in ['CustomGBForce', 'GBSAOBCForce']: + label = 'alchemically modified ' + force_name - # Check if the system has an implicit solvent force. - try: - alchemical_energy = energy_components[label] - except KeyError: # No implicit solvent. - continue + # Check if the system has an implicit solvent force. + try: + alchemical_energy = energy_components[label] + except KeyError: # No implicit solvent. + continue - # If all alchemical particles are modified, the alchemical energy should be zero. - if len(region.alchemical_atoms) == reference_system.getNumParticles(): - assert_zero_energy(label) - continue + # If all alchemical particles are modified, the alchemical energy should be zero. + if len(alchemical_regions.alchemical_atoms) == reference_system.getNumParticles(): + assert_zero_energy(label) + continue - # Otherwise compare the alchemical energy with a - # reference system with only non-alchemical particles. - # Find implicit solvent force in reference system. - for reference_force in reference_system.getForces(): - if reference_force.__class__.__name__ == force_name: - break + # Otherwise compare the alchemical energy with a + # reference system with only non-alchemical particles. + # Find implicit solvent force in reference system. + for reference_force in reference_system.getForces(): + if reference_force.__class__.__name__ == force_name: + break + + system = openmm.System() + force = reference_force.__class__() + + # For custom GB forces, we need to copy all computed values, + # energy terms, parameters, tabulated functions and exclusions. + if isinstance(force, openmm.CustomGBForce): + for index in range(reference_force.getNumPerParticleParameters()): + name = reference_force.getPerParticleParameterName(index) + force.addPerParticleParameter(name) + for index in range(reference_force.getNumComputedValues()): + computed_value = reference_force.getComputedValueParameters(index) + force.addComputedValue(*computed_value) + for index in range(reference_force.getNumEnergyTerms()): + energy_term = reference_force.getEnergyTermParameters(index) + force.addEnergyTerm(*energy_term) + for index in range(reference_force.getNumGlobalParameters()): + name = reference_force.getGlobalParameterName(index) + default_value = reference_force.getGlobalParameterDefaultValue(index) + force.addGlobalParameter(name, default_value) + for function_index in range(reference_force.getNumTabulatedFunctions()): + name = reference_force.getTabulatedFunctionName(function_index) + function = reference_force.getTabulatedFunction(function_index) + function_copy = copy.deepcopy(function) + force.addTabulatedFunction(name, function_copy) + for exclusion_index in range(reference_force.getNumExclusions()): + particles = reference_force.getExclusionParticles(exclusion_index) + force.addExclusion(*particles) + + # Create a system with only the non-alchemical particles. + for particle_index in range(reference_system.getNumParticles()): + if particle_index not in alchemical_regions.alchemical_atoms: + # Add particle to System. + mass = reference_system.getParticleMass(particle_index) + system.addParticle(mass) + + # Add particle to Force.. + parameters = reference_force.getParticleParameters(particle_index) + try: # GBSAOBCForce + force.addParticle(*parameters) + except NotImplementedError: # CustomGBForce + force.addParticle(parameters) + + system.addForce(force) + + # Get positions for all non-alchemical particles. + non_alchemical_positions = [pos for i, pos in enumerate(positions) + if i not in alchemical_regions.alchemical_atoms] + + # Compute reference force energy. + reference_force_energy = compute_force_energy(system, non_alchemical_positions, force_name) + assert_almost_equal(reference_force_energy, alchemical_energy, + 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) + + +def check_split_force_groups(system): + """Check that force groups are split correctly.""" + force_groups_by_lambda = {} + lambdas_by_force_group = {} + + # Separate forces groups by lambda parameters that AlchemicalState supports. + for force, lambda_name, _ in AlchemicalState._get_system_controlled_parameters( + system, parameters_name_suffix=None): + force_group = force.getForceGroup() + try: + force_groups_by_lambda[lambda_name].add(force_group) + except KeyError: + force_groups_by_lambda[lambda_name] = {force_group} + try: + lambdas_by_force_group[force_group].add(lambda_name) + except KeyError: + lambdas_by_force_group[force_group] = {lambda_name} + + # Check that force group 0 doesn't hold alchemical forces. + assert 0 not in force_groups_by_lambda + + # There are as many alchemical force groups as not-None lambda variables. + alchemical_state = AlchemicalState.from_system(system) + valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters() + if getattr(alchemical_state, lambda_name) is not None} + assert valid_lambdas == set(force_groups_by_lambda.keys()) + + # Check that force groups and lambda variables are in 1-to-1 correspondence. + assert len(force_groups_by_lambda) == len(lambdas_by_force_group) + for d in [force_groups_by_lambda, lambdas_by_force_group]: + for value in d.values(): + assert len(value) == 1 - system = openmm.System() - force = reference_force.__class__() - - # For custom GB forces, we need to copy all computed values, - # energy terms, parameters, tabulated functions and exclusions. - if isinstance(force, openmm.CustomGBForce): - for index in range(reference_force.getNumPerParticleParameters()): - name = reference_force.getPerParticleParameterName(index) - force.addPerParticleParameter(name) - for index in range(reference_force.getNumComputedValues()): - computed_value = reference_force.getComputedValueParameters(index) - force.addComputedValue(*computed_value) - for index in range(reference_force.getNumEnergyTerms()): - energy_term = reference_force.getEnergyTermParameters(index) - force.addEnergyTerm(*energy_term) - for index in range(reference_force.getNumGlobalParameters()): - name = reference_force.getGlobalParameterName(index) - default_value = reference_force.getGlobalParameterDefaultValue(index) - force.addGlobalParameter(name, default_value) - for function_index in range(reference_force.getNumTabulatedFunctions()): - name = reference_force.getTabulatedFunctionName(function_index) - function = reference_force.getTabulatedFunction(function_index) - function_copy = copy.deepcopy(function) - force.addTabulatedFunction(name, function_copy) - for exclusion_index in range(reference_force.getNumExclusions()): - particles = reference_force.getExclusionParticles(exclusion_index) - force.addExclusion(*particles) - - # Create a system with only the non-alchemical particles. - for particle_index in range(reference_system.getNumParticles()): - if particle_index not in region.alchemical_atoms: - # Add particle to System. - mass = reference_system.getParticleMass(particle_index) - system.addParticle(mass) - - # Add particle to Force.. - parameters = reference_force.getParticleParameters(particle_index) - try: # GBSAOBCForce - force.addParticle(*parameters) - except NotImplementedError: # CustomGBForce - force.addParticle(parameters) - - system.addForce(force) - - # Get positions for all non-alchemical particles. - non_alchemical_positions = [pos for i, pos in enumerate(positions) - if i not in region.alchemical_atoms] - - # Compute reference force energy. - reference_force_energy = compute_force_energy(system, non_alchemical_positions, force_name) - assert_almost_equal(reference_force_energy, alchemical_energy, - 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) + # With exact treatment of PME, the NonbondedForce must + # be in the lambda_electrostatics force group. + if is_alchemical_pme_treatment_exact(system): + force_idx, nonbonded_force = forces.find_forces(system, openmm.NonbondedForce, only_one=True) + assert force_groups_by_lambda['lambda_electrostatics'] == {nonbonded_force.getForceGroup()} def check_split_force_groups(system): """Check that force groups are split correctly.""" @@ -1237,8 +1326,8 @@ def test_resolve_alchemical_region(): with nose.tools.assert_raises(ValueError): AbsoluteAlchemicalFactory._resolve_alchemical_region(system, alchemical_region) -class TestMultiRegionAbsoluteAlchemicalFactory(object): - """Test AbsoluteAlchemicalFactory class using multiple regions.""" +class TestAbsoluteAlchemicalFactory(object): + """Test AbsoluteAlchemicalFactory class.""" @classmethod def setup_class(cls): @@ -1260,28 +1349,34 @@ def define_systems(cls): testsystems.LennardJonesFluid(nparticles=100, dispersion_correction=True) cls.test_systems['TIP3P WaterBox with reaction field, no switch, no dispersion correction'] = \ testsystems.WaterBox(dispersion_correction=False, switch=False, nonbondedMethod=openmm.app.CutoffPeriodic) + cls.test_systems['TIP4P-EW WaterBox and NaCl with PME'] = \ + testsystems.WaterBox(nonbondedMethod=openmm.app.PME, model='tip4pew', ionic_strength=200*unit.millimolar) + + # Vacuum and implicit. + cls.test_systems['AlanineDipeptideVacuum'] = testsystems.AlanineDipeptideVacuum() + cls.test_systems['AlanineDipeptideImplicit'] = testsystems.AlanineDipeptideImplicit() + cls.test_systems['TolueneImplicitOBC2'] = testsystems.TolueneImplicitOBC2() + cls.test_systems['TolueneImplicitGBn'] = testsystems.TolueneImplicitGBn() + + # Explicit test system: PME and CutoffPeriodic. + #cls.test_systems['AlanineDipeptideExplicit with CutoffPeriodic'] = \ + # testsystems.AlanineDipeptideExplicit(nonbondedMethod=openmm.app.CutoffPeriodic) + cls.test_systems['HostGuestExplicit with PME'] = \ + testsystems.HostGuestExplicit(nonbondedMethod=openmm.app.PME) + cls.test_systems['HostGuestExplicit with CutoffPeriodic'] = \ + testsystems.HostGuestExplicit(nonbondedMethod=openmm.app.CutoffPeriodic) @classmethod def define_regions(cls): """Create shared AlchemicalRegions for test systems in cls.test_regions.""" - cls.test_region_zero = dict() - cls.test_region_one = dict() - cls.test_region_two = dict() - - cls.test_region_zero['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2), name='zero') - cls.test_region_one['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2,4), name='one') - cls.test_region_two['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(4,6), name='two') - cls.test_region_zero['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10), name='zero') - cls.test_region_one['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10,20), name='one') - cls.test_region_two['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(20,30), name='two') - cls.test_region_zero['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3), name='zero') - cls.test_region_one['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3,6), name='one') - cls.test_region_two['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(6,9), name='two') - #Not sure how to best convert remaining tests - #cls.test_region_zero['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4), name='zero') # Modify ions. - #cls.test_region_zero['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6), name='zero') - #cls.test_region_zero['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22), name='zero') - #cls.test_region_zero['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156), name='zero') + cls.test_regions = dict() + cls.test_regions['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2)) + cls.test_regions['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10)) + cls.test_regions['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3)) + cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4)) # Modify ions. + cls.test_regions['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6)) # Only partially modified. + cls.test_regions['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22)) + cls.test_regions['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156)) @classmethod def generate_cases(cls): @@ -1298,26 +1393,11 @@ def generate_cases(cls): n_test_cases = 0 for test_system_name, test_system in cls.test_systems.items(): - # Find standard alchemical region zero. - for region_name_zero, region_zero in cls.test_region_zero.items(): - if region_name_zero in test_system_name: - break - assert region_name_zero in test_system_name, test_system_name - - # Find standard alchemical region one. - for region_name_one, region_one in cls.test_region_one.items(): - if region_name_one in test_system_name: - break - assert region_name_one in test_system_name, test_system_name - - # Find standard alchemical region two. - for region_name_two, region_two in cls.test_region_two.items(): - if region_name_two in test_system_name: + # Find standard alchemical region. + for region_name, region in cls.test_regions.items(): + if region_name in test_system_name: break - assert region_name_two in test_system_name, test_system_name - - assert region_name_zero == region_name_one and region_name_one == region_name_two - test_regions = [region_zero, region_one, region_two] + assert region_name in test_system_name, test_system_name # Find nonbonded method. force_idx, nonbonded_force = forces.find_forces(test_system.system, openmm.NonbondedForce, only_one=True) @@ -1326,9 +1406,8 @@ def generate_cases(cls): # Create all combinations of annihilate_sterics/electrostatics. for annihilate_sterics, annihilate_electrostatics in itertools.product((True, False), repeat=2): # Create new region that we can modify. - for i, test_region in enumerate(test_regions): - test_regions[i] = test_region._replace(annihilate_sterics=annihilate_sterics, - annihilate_electrostatics=annihilate_electrostatics) + test_region = region._replace(annihilate_sterics=annihilate_sterics, + annihilate_electrostatics=annihilate_electrostatics) # Create test name. test_case_name = test_system_name[:] @@ -1339,33 +1418,31 @@ def generate_cases(cls): # Annihilate bonds and angles every three test_cases. if n_test_cases % 3 == 0: - for i, test_region in enumerate(test_regions): - test_regions[i] = test_region._replace(alchemical_bonds=True, alchemical_angles=True, + test_region = test_region._replace(alchemical_bonds=True, alchemical_angles=True, alchemical_torsions=True) test_case_name += ', annihilated bonds, angles and torsions' # Add different softcore parameters every five test_cases. if n_test_cases % 5 == 0: - for i, test_region in enumerate(test_regions): - test_regions[i] = test_region._replace(softcore_alpha=1.0, softcore_beta=1.0, softcore_a=1.0, softcore_b=1.0, + test_region = test_region._replace(softcore_alpha=1.0, softcore_beta=1.0, softcore_a=1.0, softcore_b=1.0, softcore_c=1.0, softcore_d=1.0, softcore_e=1.0, softcore_f=1.0) test_case_name += ', modified softcore parameters' # Pre-generate alchemical system. - alchemical_system = direct_space_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) + alchemical_system = direct_space_factory.create_alchemical_system(test_system.system, test_region) # Add test case. - cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) + cls.test_cases[test_case_name] = (test_system, alchemical_system, test_region) n_test_cases += 1 # If we don't use softcore electrostatics and we annihilate charges # we can test also exact PME treatment. We don't increase n_test_cases # purposely to keep track of which tests are added above. - if (test_regions[1].softcore_beta == 0.0 and annihilate_electrostatics and + if (test_region.softcore_beta == 0.0 and annihilate_electrostatics and nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]): - alchemical_system = exact_pme_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) + alchemical_system = exact_pme_factory.create_alchemical_system(test_system.system, test_region) test_case_name += ', exact PME' - cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) + cls.test_cases[test_case_name] = (test_system, alchemical_system, test_region) # If the test system uses reaction field replace reaction field # of the reference system to allow comparisons. @@ -1386,9 +1463,6 @@ def filter_cases(self, condition_func, max_number=None): break return test_cases - def test_build(self): - pass - def test_split_force_groups(self): """Forces having different lambda variables should have a different force group.""" # Select 1 implicit, 1 explicit, and 1 exact PME explicit test case randomly. @@ -1470,16 +1544,8 @@ def test_overlap(self): f.description = "Testing reference/alchemical overlap for {}".format(test_name) yield f - -class TestAbsoluteAlchemicalFactory(object): - """Test AbsoluteAlchemicalFactory class.""" - - @classmethod - def setup_class(cls): - """Create test systems and shared objects.""" - cls.define_systems() - cls.define_regions() - cls.generate_cases() +class TestMultiRegionAbsoluteAlchemicalFactory(TestAbsoluteAlchemicalFactory): + """Test AbsoluteAlchemicalFactory class using multiple regions.""" @classmethod def define_systems(cls): @@ -1494,18 +1560,6 @@ def define_systems(cls): testsystems.LennardJonesFluid(nparticles=100, dispersion_correction=True) cls.test_systems['TIP3P WaterBox with reaction field, no switch, no dispersion correction'] = \ testsystems.WaterBox(dispersion_correction=False, switch=False, nonbondedMethod=openmm.app.CutoffPeriodic) - cls.test_systems['TIP4P-EW WaterBox and NaCl with PME'] = \ - testsystems.WaterBox(nonbondedMethod=openmm.app.PME, model='tip4pew', ionic_strength=200*unit.millimolar) - - # Vacuum and implicit. - cls.test_systems['AlanineDipeptideVacuum'] = testsystems.AlanineDipeptideVacuum() - cls.test_systems['AlanineDipeptideImplicit'] = testsystems.AlanineDipeptideImplicit() - cls.test_systems['TolueneImplicitOBC2'] = testsystems.TolueneImplicitOBC2() - cls.test_systems['TolueneImplicitGBn'] = testsystems.TolueneImplicitGBn() - - # Explicit test system: PME and CutoffPeriodic. - #cls.test_systems['AlanineDipeptideExplicit with CutoffPeriodic'] = \ - # testsystems.AlanineDipeptideExplicit(nonbondedMethod=openmm.app.CutoffPeriodic) cls.test_systems['HostGuestExplicit with PME'] = \ testsystems.HostGuestExplicit(nonbondedMethod=openmm.app.PME) cls.test_systems['HostGuestExplicit with CutoffPeriodic'] = \ @@ -1514,14 +1568,27 @@ def define_systems(cls): @classmethod def define_regions(cls): """Create shared AlchemicalRegions for test systems in cls.test_regions.""" - cls.test_regions = dict() - cls.test_regions['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2)) - cls.test_regions['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10)) - cls.test_regions['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3)) - cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4)) # Modify ions. - cls.test_regions['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6)) # Only partially modified. - cls.test_regions['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22)) - cls.test_regions['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156)) + cls.test_region_zero = dict() + cls.test_region_one = dict() + cls.test_region_two = dict() + + cls.test_region_zero['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2), name='zero') + cls.test_region_one['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2,4), name='one') + cls.test_region_two['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(4,6), name='two') + cls.test_region_zero['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10), name='zero') + cls.test_region_one['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10,20), name='one') + cls.test_region_two['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(20,30), name='two') + cls.test_region_zero['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3), name='zero') + cls.test_region_one['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3,6), name='one') + cls.test_region_two['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(6,9), name='two') + #Not sure how to best convert remaining tests + #cls.test_region_zero['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4), name='zero') # Modify ions. + #cls.test_region_zero['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6), name='zero') + #cls.test_region_zero['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22), name='zero') + #Three regions push this system beyhond 32 force groups + cls.test_region_zero['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156), name='zero') + cls.test_region_one['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(156,160), name='one') + cls.test_region_two['HostGuestExplicit'] = None @classmethod def generate_cases(cls): @@ -1538,11 +1605,30 @@ def generate_cases(cls): n_test_cases = 0 for test_system_name, test_system in cls.test_systems.items(): - # Find standard alchemical region. - for region_name, region in cls.test_regions.items(): - if region_name in test_system_name: + # Find standard alchemical region zero. + for region_name_zero, region_zero in cls.test_region_zero.items(): + if region_name_zero in test_system_name: break - assert region_name in test_system_name, test_system_name + assert region_name_zero in test_system_name, test_system_name + + # Find standard alchemical region one. + for region_name_one, region_one in cls.test_region_one.items(): + if region_name_one in test_system_name: + break + assert region_name_one in test_system_name, test_system_name + + # Find standard alchemical region two. + for region_name_two, region_two in cls.test_region_two.items(): + if region_name_two in test_system_name: + break + assert region_name_two in test_system_name, test_system_name + + assert region_name_zero == region_name_one and region_name_one == region_name_two + #We only want two regions for HostGuest or we get too many force groups + if 'HostGuestExplicit' in region_name_one: + test_regions = [region_zero, region_one] + else: + test_regions = [region_zero, region_one, region_two] # Find nonbonded method. force_idx, nonbonded_force = forces.find_forces(test_system.system, openmm.NonbondedForce, only_one=True) @@ -1551,8 +1637,9 @@ def generate_cases(cls): # Create all combinations of annihilate_sterics/electrostatics. for annihilate_sterics, annihilate_electrostatics in itertools.product((True, False), repeat=2): # Create new region that we can modify. - test_region = region._replace(annihilate_sterics=annihilate_sterics, - annihilate_electrostatics=annihilate_electrostatics) + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(annihilate_sterics=annihilate_sterics, + annihilate_electrostatics=annihilate_electrostatics) # Create test name. test_case_name = test_system_name[:] @@ -1563,31 +1650,34 @@ def generate_cases(cls): # Annihilate bonds and angles every three test_cases. if n_test_cases % 3 == 0: - test_region = test_region._replace(alchemical_bonds=True, alchemical_angles=True, + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(alchemical_bonds=True, alchemical_angles=True, alchemical_torsions=True) test_case_name += ', annihilated bonds, angles and torsions' # Add different softcore parameters every five test_cases. if n_test_cases % 5 == 0: - test_region = test_region._replace(softcore_alpha=1.0, softcore_beta=1.0, softcore_a=1.0, softcore_b=1.0, + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(softcore_alpha=1.0, softcore_beta=1.0, softcore_a=1.0, softcore_b=1.0, softcore_c=1.0, softcore_d=1.0, softcore_e=1.0, softcore_f=1.0) test_case_name += ', modified softcore parameters' + #region_interactions = frozenset(itertools.combinations(range(len(test_regions)), 2)) # Pre-generate alchemical system. - alchemical_system = direct_space_factory.create_alchemical_system(test_system.system, test_region) + alchemical_system = direct_space_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) # Add test case. - cls.test_cases[test_case_name] = (test_system, alchemical_system, test_region) + cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) n_test_cases += 1 # If we don't use softcore electrostatics and we annihilate charges # we can test also exact PME treatment. We don't increase n_test_cases # purposely to keep track of which tests are added above. - if (test_region.softcore_beta == 0.0 and annihilate_electrostatics and + if (test_regions[1].softcore_beta == 0.0 and annihilate_electrostatics and nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]): - alchemical_system = exact_pme_factory.create_alchemical_system(test_system.system, test_region) + alchemical_system = exact_pme_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) test_case_name += ', exact PME' - cls.test_cases[test_case_name] = (test_system, alchemical_system, test_region) + cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) # If the test system uses reaction field replace reaction field # of the reference system to allow comparisons. @@ -1595,42 +1685,10 @@ def generate_cases(cls): forcefactories.replace_reaction_field(test_system.system, return_copy=False, switch_width=direct_space_factory.switch_width) - def filter_cases(self, condition_func, max_number=None): - """Return the list of test cases that satisfy condition_func(test_case_name).""" - if max_number is None: - max_number = len(self.test_cases) - - test_cases = {} - for test_name, test_case in self.test_cases.items(): - if condition_func(test_name): - test_cases[test_name] = test_case - if len(test_cases) >= max_number: - break - return test_cases - - def test_split_force_groups(self): - """Forces having different lambda variables should have a different force group.""" - # Select 1 implicit, 1 explicit, and 1 exact PME explicit test case randomly. - test_cases = self.filter_cases(lambda x: 'Implicit' in x, max_number=1) - test_cases.update(self.filter_cases(lambda x: 'SrcExplicit ' in x and 'exact PME' in x, max_number=1)) - test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' not in x, max_number=1)) - for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): - f = partial(check_split_force_groups, alchemical_system) - f.description = "Testing force splitting among groups of {}".format(test_name) - yield f - - def test_fully_interacting_energy(self): - """Compare the energies of reference and fully interacting alchemical system.""" - for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): - f = partial(compare_system_energies, test_system.system, - alchemical_system, alchemical_region, test_system.positions) - f.description = "Testing fully interacting energy of {}".format(test_name) - yield f - def test_noninteracting_energy_components(self): """Check all forces annihilated/decoupled when their lambda variables are zero.""" for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): - f = partial(check_noninteracting_energy_components, test_system.system, alchemical_system, + f = partial(check_multi_noninteracting_energy_components, test_system.system, alchemical_system, alchemical_region, test_system.positions) f.description = "Testing non-interacting energy of {}".format(test_name) yield f @@ -1642,7 +1700,7 @@ def test_fully_interacting_energy_components(self): # run this locally when test_fully_interacting_energies() fails. test_cases = self.filter_cases(lambda x: 'Explicit' in x) for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): - f = partial(check_interacting_energy_components, test_system.system, alchemical_system, + f = partial(check_multi_interacting_energy_components, test_system.system, alchemical_system, alchemical_region, test_system.positions) f.description = "Testing energy components of %s..." % test_name yield f @@ -1669,7 +1727,7 @@ def test_platforms(self): alchemical_region, test_system.positions) f.description = "Test fully interacting energy of {} on {}".format(test_name, platform.getName()) yield f - f = partial(check_noninteracting_energy_components, test_system.system, alchemical_system, + f = partial(check_multi_noninteracting_energy_components, test_system.system, alchemical_system, alchemical_region, test_system.positions) f.description = "Test non-interacting energy of {} on {}".format(test_name, platform.getName()) yield f @@ -1677,19 +1735,6 @@ def test_platforms(self): # Restore global platform GLOBAL_ALCHEMY_PLATFORM = old_global_platform - @attr('slow') - def test_overlap(self): - """Tests overlap between reference and alchemical systems.""" - for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): - #cached_trajectory_filename = os.path.join(os.environ['HOME'], '.cache', 'alchemy', 'tests', - # test_name + '.pickle') - cached_trajectory_filename = None - f = partial(overlap_check, test_system.system, alchemical_system, test_system.positions, - cached_trajectory_filename=cached_trajectory_filename, name=test_name) - f.description = "Testing reference/alchemical overlap for {}".format(test_name) - yield f - - class TestDispersionlessAlchemicalFactory(object): """ Only test overlap for dispersionless alchemical factory, since energy agreement From eb032f19933b3f2326f196542c5b678398dca047 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 9 Aug 2019 15:38:49 +0100 Subject: [PATCH 076/152] remove extra lines From 5ea2b1c95e49f9c8a52d3ebea5264a06202ac56d Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Fri, 9 Aug 2019 15:40:44 +0100 Subject: [PATCH 077/152] remove extra lines --- openmmtools/tests/test_alchemy.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 59d00b7aa..229e87fb4 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -279,7 +279,6 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe # Compute total energy from nonbonded interactions tot_energy = compute_energy(system, positions) tot_reciprocal_energy = compute_energy(system, positions, force_group={30}) - system = copy.deepcopy(reference_system) # Restore alchemical sterics/electro of other alch_atoms # Compute contributions from particle sterics turn_off_nonbonded(system, sterics=True, only_atoms=alchemical_atoms) @@ -322,7 +321,7 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe # Compute contributions from exceptions sterics system = copy.deepcopy(reference_system) # Restore particle interactions - turn_off_nonbonded(system, sterics=True, exceptions=True, only_atoms=all_alchemical_atoms) + turn_off_nonbonded(system, sterics=True, exceptions=True, only_atoms=alchemical_atoms) tot_energy_no_alchem_exception_sterics = compute_energy(system, positions) system = copy.deepcopy(reference_system) # Restore alchemical sterics turn_off_nonbonded(system, sterics=True, exceptions=True, only_atoms=nonalchemical_atoms) @@ -337,7 +336,7 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe # Compute contributions from exceptions electrostatics system = copy.deepcopy(reference_system) # Restore exceptions sterics - turn_off_nonbonded(system, electrostatics=True, exceptions=True, only_atoms=all_alchemical_atoms) + turn_off_nonbonded(system, electrostatics=True, exceptions=True, only_atoms=alchemical_atoms) tot_energy_no_alchem_exception_electro = compute_energy(system, positions) system = copy.deepcopy(reference_system) # Restore alchemical electrostatics turn_off_nonbonded(system, electrostatics=True, exceptions=True, only_atoms=nonalchemical_atoms) From d9fd7432e2d5440fe410412254db7ccd0c120c8a Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Sat, 10 Aug 2019 14:34:47 +0100 Subject: [PATCH 078/152] fix single region tests --- openmmtools/alchemy.py | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index ee8827bc6..8a8a96c52 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1088,6 +1088,7 @@ def _is_straddling_noninteracting_regions(particles, alchemical_regions, alchemi non-alchemical environment. """ + logging.debug(len(alchemical_regions)) for i, alchemical_region_A in enumerate(alchemical_regions): if alchemical_region_A.alchemical_atoms.intersection(particles): j = 0 @@ -1136,18 +1137,14 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region force = openmm.PeriodicTorsionForce() force.setForceGroup(reference_force.getForceGroup()) for torsion_index in range(reference_force.getNumTorsions()): + particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters( + torsion_index) + particles = set((particle1, particle2, particle3, particle4)) if torsion_index not in all_alchemical_torsions: - particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) - particles = set((particle1, particle2, particle3, particle4)) if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): pass else: force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) - else: - # Check there are no alchemical torsions straddling regions - msg = 'No support for alchemical torsions across multiple alchemical regions' - if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): - raise NotImplemented(msg) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -1217,18 +1214,13 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, force = openmm.HarmonicAngleForce() force.setForceGroup(reference_force.getForceGroup()) for angle_index in range(reference_force.getNumAngles()): + [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) + particles = set((particle1, particle2, particle3)) if angle_index not in all_alchemical_angles: - [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) - particles = set((particle1, particle2, particle3)) if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): pass else: force.addAngle(particle1, particle2, particle3, theta0, K) - else: - # Check there are no alchemical angles straddling regions - msg = 'No support for alchemical angles across multiple alchemical regions' - if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): - raise NotImplemented(msg) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -1296,18 +1288,13 @@ def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, force = openmm.HarmonicBondForce() force.setForceGroup(reference_force.getForceGroup()) for bond_index in range(reference_force.getNumBonds()): + [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) + particles = set((particle1, particle2)) if bond_index not in all_alchemical_bonds: - [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) - particles = set((particle1, particle2)) if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): pass else: force.addBond(particle1, particle2, theta0, K) - else: - # Check there are no alchemical bonds straddling regions - msg = 'No support for alchemical bonds across multiple alchemical regions' - if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): - raise NotImplemented(msg) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -2334,6 +2321,8 @@ def check_energy_expression(custom_force, parameter): add_label('alchemically modified HarmonicAngleForce for region one', force_index) elif check_parameter(force, 'lambda_angles_two'): add_label('alchemically modified HarmonicAngleForce for region two', force_index) + else: + add_label('alchemically modified HarmonicAngleForce', force_index) elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda_bonds'): if check_parameter(force, 'lambda_bonds_zero'): add_label('alchemically modified HarmonicBondForce for region zero', force_index) @@ -2341,6 +2330,8 @@ def check_energy_expression(custom_force, parameter): add_label('alchemically modified HarmonicBondForce for region one', force_index) elif check_parameter(force, 'lambda_bonds_two'): add_label('alchemically modified HarmonicBondForce for region two', force_index) + else: + add_label('alchemically modified HarmonicBondForce', force_index) elif isinstance(force, openmm.CustomTorsionForce) and check_energy_expression(force, 'lambda_torsions'): if check_parameter(force, 'lambda_torsions_zero'): add_label('alchemically modified PeriodicTorsionForce for region zero', force_index) @@ -2348,6 +2339,8 @@ def check_energy_expression(custom_force, parameter): add_label('alchemically modified PeriodicTorsionForce for region one', force_index) elif check_parameter(force, 'lambda_torsions_two'): add_label('alchemically modified PeriodicTorsionForce for region two', force_index) + else: + add_label('alchemically modified PeriodicTorsionForce', force_index) elif isinstance(force, openmm.CustomGBForce) and check_parameter(force, 'lambda_electrostatics'): if check_energy_expression(force, 'unscaled'): add_label('alchemically modified CustomGBForce', force_index) From 192a5874571d47a85c592cd46071529756145b22 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Sat, 10 Aug 2019 14:35:08 +0100 Subject: [PATCH 079/152] fix single region tests --- openmmtools/tests/test_alchemy.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 229e87fb4..7326d23c1 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -272,8 +272,9 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe # Compute particle interactions between different groups of atoms # ---------------------------------------------------------------- #Turn off other alchemical regions - turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, only_atoms=other_alchemical_atoms) - turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, exceptions=True, only_atoms=other_alchemical_atoms) + if len(other_alchemical_atoms) > 0: + turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, only_atoms=other_alchemical_atoms) + turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, exceptions=True, only_atoms=other_alchemical_atoms) system = copy.deepcopy(reference_system) # Compute total energy from nonbonded interactions @@ -522,7 +523,12 @@ def check_multi_interacting_energy_components(reference_system, alchemical_syste positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity The positions to test (units of length). + Note + ---------- + Interactions between alchemical regions are not tested here. + Alchemical regions are assumed to be non interacting. """ + all_alchemical_atoms = set() for region in alchemical_regions: for atom in region.alchemical_atoms: @@ -562,7 +568,7 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc other_alchemical_atoms = all_alchemical_atoms.difference(alchemical_regions.alchemical_atoms) print("Dissecting reference system's nonbonded force for region {}".format(alchemical_regions.name)) else: - other_alchemical_atoms = set() + other_alchemical_atoms = {} print("Dissecting reference system's nonbonded force") energy_components = dissect_nonbonded_energy(reference_system, positions, @@ -1580,11 +1586,7 @@ def define_regions(cls): cls.test_region_zero['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3), name='zero') cls.test_region_one['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3,6), name='one') cls.test_region_two['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(6,9), name='two') - #Not sure how to best convert remaining tests - #cls.test_region_zero['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4), name='zero') # Modify ions. - #cls.test_region_zero['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6), name='zero') - #cls.test_region_zero['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22), name='zero') - #Three regions push this system beyhond 32 force groups + #Three regions push HostGuest system beyond 32 force groups cls.test_region_zero['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156), name='zero') cls.test_region_one['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(156,160), name='one') cls.test_region_two['HostGuestExplicit'] = None From ece15eaabf85aa55a3510e5419abfd0117b103b7 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Sat, 10 Aug 2019 16:13:44 +0100 Subject: [PATCH 080/152] compare_system_energies working --- openmmtools/tests/test_alchemy.py | 52 ++++++------------------------- 1 file changed, 10 insertions(+), 42 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 7326d23c1..0ea7e8641 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -461,6 +461,8 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi method is an Ewald method. """ + if not isinstance(alchemical_regions, list): + alchemical_regions = [alchemical_regions] force_group = -1 # Default we compare the energy of all groups. # Check nonbonded method. Comparing with PME is more complicated @@ -486,8 +488,13 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi # Compute the reciprocal space correction added to the direct space # energy due to the exceptions of the alchemical atoms. - alchemical_atoms = alchemical_regions.alchemical_atoms - aa_correction, na_correction = compute_direct_space_correction(nonbonded_force, alchemical_atoms, positions) + aa_correction = 0.0 * unit.kilojoule_per_mole + na_correction = 0.0 * unit.kilojoule_per_mole + for region in alchemical_regions: + alchemical_atoms = region.alchemical_atoms + aa, na = compute_direct_space_correction(nonbonded_force, alchemical_atoms, positions) + aa_correction += aa + na_correction += na # Compute potential of the direct space. potentials = [compute_energy(system, positions, force_group=force_group) @@ -568,7 +575,7 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc other_alchemical_atoms = all_alchemical_atoms.difference(alchemical_regions.alchemical_atoms) print("Dissecting reference system's nonbonded force for region {}".format(alchemical_regions.name)) else: - other_alchemical_atoms = {} + other_alchemical_atoms = set() print("Dissecting reference system's nonbonded force") energy_components = dissect_nonbonded_energy(reference_system, positions, @@ -882,45 +889,6 @@ def assert_zero_energy(label): 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) -def check_split_force_groups(system): - """Check that force groups are split correctly.""" - force_groups_by_lambda = {} - lambdas_by_force_group = {} - - # Separate forces groups by lambda parameters that AlchemicalState supports. - for force, lambda_name, _ in AlchemicalState._get_system_controlled_parameters( - system, parameters_name_suffix=None): - force_group = force.getForceGroup() - try: - force_groups_by_lambda[lambda_name].add(force_group) - except KeyError: - force_groups_by_lambda[lambda_name] = {force_group} - try: - lambdas_by_force_group[force_group].add(lambda_name) - except KeyError: - lambdas_by_force_group[force_group] = {lambda_name} - - # Check that force group 0 doesn't hold alchemical forces. - assert 0 not in force_groups_by_lambda - - # There are as many alchemical force groups as not-None lambda variables. - alchemical_state = AlchemicalState.from_system(system) - valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters() - if getattr(alchemical_state, lambda_name) is not None} - assert valid_lambdas == set(force_groups_by_lambda.keys()) - - # Check that force groups and lambda variables are in 1-to-1 correspondence. - assert len(force_groups_by_lambda) == len(lambdas_by_force_group) - for d in [force_groups_by_lambda, lambdas_by_force_group]: - for value in d.values(): - assert len(value) == 1 - - # With exact treatment of PME, the NonbondedForce must - # be in the lambda_electrostatics force group. - if is_alchemical_pme_treatment_exact(system): - force_idx, nonbonded_force = forces.find_forces(system, openmm.NonbondedForce, only_one=True) - assert force_groups_by_lambda['lambda_electrostatics'] == {nonbonded_force.getForceGroup()} - def check_split_force_groups(system): """Check that force groups are split correctly.""" force_groups_by_lambda = {} From fcaacb93eef48fcf6bd95bdf63c817f381572b29 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Mon, 12 Aug 2019 11:47:27 +0100 Subject: [PATCH 081/152] all fast test working --- openmmtools/alchemy.py | 1 - 1 file changed, 1 deletion(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 8a8a96c52..03d44ae62 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1088,7 +1088,6 @@ def _is_straddling_noninteracting_regions(particles, alchemical_regions, alchemi non-alchemical environment. """ - logging.debug(len(alchemical_regions)) for i, alchemical_region_A in enumerate(alchemical_regions): if alchemical_region_A.alchemical_atoms.intersection(particles): j = 0 From 8c4793b8b75fabc8436c16e9c5dce8a2776b6c73 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Mon, 12 Aug 2019 11:47:53 +0100 Subject: [PATCH 082/152] all fast tests working --- openmmtools/tests/test_alchemy.py | 90 +++++++++++++++++++------------ 1 file changed, 55 insertions(+), 35 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 0ea7e8641..c4560c1a5 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -889,44 +889,49 @@ def assert_zero_energy(label): 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) -def check_split_force_groups(system): +def check_split_force_groups(system, region_names=None): """Check that force groups are split correctly.""" - force_groups_by_lambda = {} - lambdas_by_force_group = {} + if region_names is None: + region_names = [] + print(region_names) # Separate forces groups by lambda parameters that AlchemicalState supports. - for force, lambda_name, _ in AlchemicalState._get_system_controlled_parameters( - system, parameters_name_suffix=None): - force_group = force.getForceGroup() - try: - force_groups_by_lambda[lambda_name].add(force_group) - except KeyError: - force_groups_by_lambda[lambda_name] = {force_group} - try: - lambdas_by_force_group[force_group].add(lambda_name) - except KeyError: - lambdas_by_force_group[force_group] = {lambda_name} - - # Check that force group 0 doesn't hold alchemical forces. - assert 0 not in force_groups_by_lambda - - # There are as many alchemical force groups as not-None lambda variables. - alchemical_state = AlchemicalState.from_system(system) - valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters() - if getattr(alchemical_state, lambda_name) is not None} - assert valid_lambdas == set(force_groups_by_lambda.keys()) - - # Check that force groups and lambda variables are in 1-to-1 correspondence. - assert len(force_groups_by_lambda) == len(lambdas_by_force_group) - for d in [force_groups_by_lambda, lambdas_by_force_group]: - for value in d.values(): - assert len(value) == 1 - - # With exact treatment of PME, the NonbondedForce must - # be in the lambda_electrostatics force group. - if is_alchemical_pme_treatment_exact(system): - force_idx, nonbonded_force = forces.find_forces(system, openmm.NonbondedForce, only_one=True) - assert force_groups_by_lambda['lambda_electrostatics'] == {nonbonded_force.getForceGroup()} + for region in region_names: + force_groups_by_lambda = {} + lambdas_by_force_group = {} + for force, lambda_name, _ in AlchemicalState._get_system_controlled_parameters( + system, parameters_name_suffix=region): + force_group = force.getForceGroup() + try: + force_groups_by_lambda[lambda_name].add(force_group) + except KeyError: + force_groups_by_lambda[lambda_name] = {force_group} + try: + lambdas_by_force_group[force_group].add(lambda_name) + except KeyError: + lambdas_by_force_group[force_group] = {lambda_name} + + # Check that force group 0 doesn't hold alchemical forces. + assert 0 not in force_groups_by_lambda + + # There are as many alchemical force groups as not-None lambda variables. + alchemical_state = AlchemicalState.from_system(system, parameters_name_suffix=region) + valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters(parameters_name_suffix=region) + if getattr(alchemical_state, lambda_name) is not None} + print(valid_lambdas, force_groups_by_lambda.keys()) + assert valid_lambdas == set(force_groups_by_lambda.keys()) + + # Check that force groups and lambda variables are in 1-to-1 correspondence. + assert len(force_groups_by_lambda) == len(lambdas_by_force_group) + for d in [force_groups_by_lambda, lambdas_by_force_group]: + for value in d.values(): + assert len(value) == 1 + + # With exact treatment of PME, the NonbondedForce must + # be in the lambda_electrostatics force group. + if is_alchemical_pme_treatment_exact(system): + force_idx, nonbonded_force = forces.find_forces(system, openmm.NonbondedForce, only_one=True) + assert force_groups_by_lambda['lambda_electrostatics_{}'.format(region)] == {nonbonded_force.getForceGroup()} # ============================================================================= @@ -1637,6 +1642,7 @@ def generate_cases(cls): # Add test case. cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) + n_test_cases += 1 # If we don't use softcore electrostatics and we annihilate charges @@ -1654,6 +1660,20 @@ def generate_cases(cls): forcefactories.replace_reaction_field(test_system.system, return_copy=False, switch_width=direct_space_factory.switch_width) + def test_split_force_groups(self): + """Forces having different lambda variables should have a different force group.""" + # Select 1 implicit, 1 explicit, and 1 exact PME explicit test case randomly. + test_cases = self.filter_cases(lambda x: 'Implicit' in x, max_number=1) + test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' in x, max_number=1)) + test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' not in x, max_number=1)) + for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): + region_names = [] + for region in alchemical_region: + region_names.append(region.name) + f = partial(check_split_force_groups, alchemical_system, region_names) + f.description = "Testing force splitting among groups of {}".format(test_name) + yield f + def test_noninteracting_energy_components(self): """Check all forces annihilated/decoupled when their lambda variables are zero.""" for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): From 805ba45c53e00daa68fdfabaf9befc315ca30abe Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 4 Sep 2019 15:35:10 +0100 Subject: [PATCH 083/152] fix for Long range correction did not converge --- openmmtools/alchemy.py | 47 +++++++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 03d44ae62..2094a8265 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -651,6 +651,9 @@ def create_alchemical_system(self, reference_system, alchemical_regions, Alchemically-modified version of reference_system. """ + if alchemical_regions_interactions != frozenset(): + raise NotImplemented('Interactions between alchemcial regions is untested') + logger.debug(f'Dictionary of interacting alchemical regions: {alchemical_regions_interactions}') if isinstance(alchemical_regions, AlchemicalRegion): alchemical_regions = [alchemical_regions] @@ -661,7 +664,6 @@ def create_alchemical_system(self, reference_system, alchemical_regions, for alchemical_region in alchemical_regions] # Check for duplicate alchemical atoms/bonds/angles/torsions. - all_alchemical_elements = {element_type: set() for element_type in ['atoms', 'bonds', 'angles', 'torsions']} for alchemical_region in alchemical_regions: @@ -794,7 +796,8 @@ def get_energy_components(cls, alchemical_system, alchemical_state, positions, p energy_components = collections.OrderedDict() for force_label, force_index in force_labels.items(): energy_components[force_label] = context.getState(getEnergy=True, - groups=2**force_index).getPotentialEnergy() + groups=2**force_index).getPotentialEnergy() + # Clean up del context, integrator return energy_components @@ -1112,6 +1115,10 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region alchemical_region : AlchemicalRegion The alchemical region containing the indices of the torsions to alchemically modify. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. Returns ------- @@ -1190,6 +1197,10 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, alchemical_region : AlchemicalRegion The alchemical region containing the indices of the angles to alchemically modify. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. Returns ------- @@ -1263,6 +1274,10 @@ def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, alchemical_region : AlchemicalRegion The alchemical region containing the indices of the bonds to alchemically modify. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. Returns ------- @@ -1497,6 +1512,10 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region alchemical_region : AlchemicalRegion The alchemical region containing the indices of the atoms to alchemically modify. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. Returns ------- @@ -1574,34 +1593,34 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): raise ValueError('Softcore electrostatics is' + err_msg) - # Create a copy of the NonbondedForce to handle particle interactions and - # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). - nonbonded_force = copy.deepcopy(reference_force) - - # Fix any NonbondedForce issues with Lennard-Jones sigma = 0 (epsilon = 0), + # Fix any issues in reference force with Lennard-Jones sigma = 0 (epsilon = 0), # which should have sigma > 0. - for particle_index in range(nonbonded_force.getNumParticles()): + for particle_index in range(reference_force.getNumParticles()): # Retrieve parameters. - [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) # Check particle sigma is not zero. if sigma == 0.0 * unit.angstrom: warning_msg = 'particle %d has Lennard-Jones sigma = 0 (charge=%s, sigma=%s, epsilon=%s); setting sigma=1A' logger.warning(warning_msg % (particle_index, str(charge), str(sigma), str(epsilon))) sigma = 1.0 * unit.angstrom # Fix it. - nonbonded_force.setParticleParameters(particle_index, charge, sigma, epsilon) + reference_force.setParticleParameters(particle_index, charge, sigma, epsilon) # Same for the exceptions. - for exception_index in range(nonbonded_force.getNumExceptions()): + for exception_index in range(reference_force.getNumExceptions()): # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) # Check particle sigma is not zero. if sigma == 0.0 * unit.angstrom: warning_msg = 'exception %d has Lennard-Jones sigma = 0 (iatom=%d, jatom=%d, chargeprod=%s, sigma=%s, epsilon=%s); setting sigma=1A' logger.warning(warning_msg % (exception_index, iatom, jatom, str(chargeprod), str(sigma), str(epsilon))) sigma = 1.0 * unit.angstrom # Fix it. - nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) + reference_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) + + # Create a copy of the NonbondedForce to handle particle interactions and + # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). + nonbonded_force = copy.deepcopy(reference_force) if use_exact_pme_treatment: # Exclude noninteracting alchemical regions from seeing each other in the nonbonded @@ -1609,7 +1628,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region if (x, y) not in alchemical_regions_interactions: for atom1 in alchemical_regions[x].alchemical_atoms: for atom2 in alchemical_regions[y].alchemical_atoms: - nonbonded_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) + reference_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) else: region_names = (alchemical_regions[x].name, alchemical_regions[y].name) logger.debug(f'Adding a exact PME electrostatic interaction group between groups {region_names}.') From 938a34b79233705101cce650492f78555d8dec99 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 4 Sep 2019 15:41:23 +0100 Subject: [PATCH 084/152] correct typo ,switches nonbonded and reference --- openmmtools/alchemy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 2094a8265..aec56374e 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1628,7 +1628,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region if (x, y) not in alchemical_regions_interactions: for atom1 in alchemical_regions[x].alchemical_atoms: for atom2 in alchemical_regions[y].alchemical_atoms: - reference_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) + nonbonded_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) else: region_names = (alchemical_regions[x].name, alchemical_regions[y].name) logger.debug(f'Adding a exact PME electrostatic interaction group between groups {region_names}.') From 62fa036d6409a02316c59545ae5c31920e6e5d71 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 11 Sep 2019 09:12:19 +0100 Subject: [PATCH 085/152] All test working --- openmmtools/alchemy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index aec56374e..0b1dda626 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -699,7 +699,7 @@ def create_alchemical_system(self, reference_system, alchemical_regions, for alchemical_region in alchemical_regions: for particle_index in alchemical_region.alchemical_atoms: if reference_system.isVirtualSite(particle_index): - raise ValueError(f'Virtual atoms in region {alchemical_region.name}.' + raise ValueError(f'Virtual atoms in region {alchemical_region.name}. ' 'Alchemically modified virtual sites are not supported') # Modify forces as appropriate. We delete the forces that From 793b6c47da88eecc20134ec878f67f33c97de044 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 11 Sep 2019 09:13:07 +0100 Subject: [PATCH 086/152] all tests working --- openmmtools/tests/test_alchemy.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index c4560c1a5..2f38712b9 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -211,7 +211,6 @@ def turn_off_nonbonded(system, sterics=False, electrostatics=False, epsilon_coeff*epsilon_scale) - def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, other_alchemical_atoms): """Dissect the nonbonded energy contributions of the reference system by atom group and sterics/electrostatics. @@ -227,6 +226,8 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe The positions to test. alchemical_atoms : set of int The indices of the alchemical atoms. + other_alchemical_atoms : set of int + The indices of the alchemical atoms in other alchemical regions Returns ------- @@ -543,6 +544,7 @@ def check_multi_interacting_energy_components(reference_system, alchemical_syste for region in alchemical_regions: check_interacting_energy_components(reference_system, alchemical_system, region, positions, all_alchemical_atoms, True) + def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, all_alchemical_atoms=None, multi_regions=False): """Compare full and alchemically-modified system energies by energy component. @@ -894,7 +896,6 @@ def check_split_force_groups(system, region_names=None): if region_names is None: region_names = [] - print(region_names) # Separate forces groups by lambda parameters that AlchemicalState supports. for region in region_names: force_groups_by_lambda = {} @@ -918,7 +919,6 @@ def check_split_force_groups(system, region_names=None): alchemical_state = AlchemicalState.from_system(system, parameters_name_suffix=region) valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters(parameters_name_suffix=region) if getattr(alchemical_state, lambda_name) is not None} - print(valid_lambdas, force_groups_by_lambda.keys()) assert valid_lambdas == set(force_groups_by_lambda.keys()) # Check that force groups and lambda variables are in 1-to-1 correspondence. @@ -1682,18 +1682,6 @@ def test_noninteracting_energy_components(self): f.description = "Testing non-interacting energy of {}".format(test_name) yield f - @attr('slow') - def test_fully_interacting_energy_components(self): - """Test interacting state energy by force component.""" - # This is a very expensive but very informative test. We can - # run this locally when test_fully_interacting_energies() fails. - test_cases = self.filter_cases(lambda x: 'Explicit' in x) - for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): - f = partial(check_multi_interacting_energy_components, test_system.system, alchemical_system, - alchemical_region, test_system.positions) - f.description = "Testing energy components of %s..." % test_name - yield f - @attr('slow') def test_platforms(self): """Test interacting and noninteracting energies on all platforms.""" @@ -1724,6 +1712,18 @@ def test_platforms(self): # Restore global platform GLOBAL_ALCHEMY_PLATFORM = old_global_platform + @attr('slow') + def test_fully_interacting_energy_components(self): + """Test interacting state energy by force component.""" + # This is a very expensive but very informative test. We can + # run this locally when test_fully_interacting_energies() fails. + test_cases = self.filter_cases(lambda x: 'Explicit' in x) + for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): + f = partial(check_multi_interacting_energy_components, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Testing energy components of %s..." % test_name + yield f + class TestDispersionlessAlchemicalFactory(object): """ Only test overlap for dispersionless alchemical factory, since energy agreement From b11fc6a6fe8cfea632ef0fdad831c3d446e02c8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Tue, 24 Sep 2019 11:55:45 -0400 Subject: [PATCH 087/152] ThermodynamicState support for more barostats - supports MonteCarloAnistropicBarostat with same pressure along all axes - supports MonteCarloMembraneBarostat with zero surface tension --- openmmtools/states.py | 67 +++++++++++++--- openmmtools/tests/test_states.py | 126 +++++++++++++++++++++++-------- 2 files changed, 151 insertions(+), 42 deletions(-) diff --git a/openmmtools/states.py b/openmmtools/states.py index aad42e21c..0456aa55f 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -281,11 +281,13 @@ class ThermodynamicsError(Exception): MULTIPLE_BAROSTATS, NO_BAROSTAT, UNSUPPORTED_BAROSTAT, + UNSUPPORTED_ANISOTROPIC_BAROSTAT, + UNSUPPORTED_MEMBRANE_BAROSTAT, INCONSISTENT_BAROSTAT, BAROSTATED_NONPERIODIC, INCONSISTENT_INTEGRATOR, INCOMPATIBLE_SAMPLER_STATE, - INCOMPATIBLE_ENSEMBLE) = range(12) + INCOMPATIBLE_ENSEMBLE) = range(14) error_messages = { MULTIPLE_THERMOSTATS: "System has multiple thermostats.", @@ -294,6 +296,10 @@ class ThermodynamicsError(Exception): INCONSISTENT_THERMOSTAT: "System thermostat is inconsistent with thermodynamic state.", MULTIPLE_BAROSTATS: "System has multiple barostats.", UNSUPPORTED_BAROSTAT: "Found unsupported barostat {} in system.", + UNSUPPORTED_ANISOTROPIC_BAROSTAT: + "MonteCarloAnisotropicBarostat is only supported if the pressure along all scaled axes is the same.", + UNSUPPORTED_MEMBRANE_BAROSTAT: + "MonteCarloAnisotropicBarostat is only supported if the surface tension is zero.", NO_BAROSTAT: "System does not have a barostat specifying the pressure.", INCONSISTENT_BAROSTAT: "System barostat is inconsistent with thermodynamic state.", BAROSTATED_NONPERIODIC: "Non-periodic systems cannot have a barostat.", @@ -696,7 +702,7 @@ def barostat(self, new_barostat): # Update the internally stored standard system, and restore the old # pressure if something goes wrong (e.g. the system is not periodic). try: - self._pressure = new_barostat.getDefaultPressure() + self._pressure = self._get_barostat_pressure(new_barostat) self._unsafe_set_system(system, fix_state=False) except ThermodynamicsError: self._pressure = old_pressure @@ -1235,9 +1241,12 @@ def _initialize(self, system, temperature=None, pressure=None): # If pressure is None, we try to infer the pressure from the barostat. barostat = self._find_barostat(system) if pressure is None and barostat is not None: - self._pressure = barostat.getDefaultPressure() + self._pressure = self._get_barostat_pressure(barostat) else: self._pressure = pressure # Pressure here can also be None. + self._barostat_type = openmm.MonteCarloBarostat + if barostat is not None: + self._barostat_type = type(barostat) # If temperature is None, we infer the temperature from a thermostat. if temperature is None: @@ -1386,7 +1395,7 @@ def _standardize_system(self, system): # Here we push the barostat at the end. barostat = self._pop_barostat(system) if barostat is not None: - barostat.setDefaultPressure(self._STANDARD_PRESSURE) + self._set_barostat_pressure(barostat, self._STANDARD_PRESSURE) system.addForce(barostat) def _compute_standard_system_hash(self, standard_system): @@ -1422,7 +1431,7 @@ def _set_context_barostat(self, context, update_pressure, update_temperature): # Apply pressure and temperature to barostat. if update_pressure: self._set_barostat_pressure(barostat, self.pressure) - context.setParameter(barostat.Pressure(), self.pressure) + self._set_barostat_pressure_in_context(barostat, self.pressure, context) if update_temperature: self._set_barostat_temperature(barostat, self.temperature) # TODO remove try except when drop openmm7.0 support @@ -1544,7 +1553,7 @@ def set_temp(_integrator): # Internal-usage: barostat handling # ------------------------------------------------------------------------- - _SUPPORTED_BAROSTATS = {'MonteCarloBarostat'} + _SUPPORTED_BAROSTATS = {'MonteCarloBarostat', 'MonteCarloAnisotropicBarostat', 'MonteCarloMembraneBarostat'} @classmethod def _find_barostat(cls, system, get_index=False): @@ -1573,6 +1582,19 @@ def _find_barostat(cls, system, get_index=False): if barostat.__class__.__name__ not in cls._SUPPORTED_BAROSTATS: raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_BAROSTAT, barostat.__class__.__name__) + elif isinstance(barostat, openmm.MonteCarloAnisotropicBarostat): + # support only if pressure in all scaled directions is equal + pressures = barostat.getDefaultPressure().value_in_unit(unit.bar) + scaled = [barostat.getScaleX(), barostat.getScaleY(), barostat.getScaleY()] + if sum(scaled) == 0: + raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT) + active_pressures = [pressure for pressure, active in zip(pressures, scaled)] + if any(abs(pressure - active_pressures[0]) > 0 for pressure in active_pressures): + raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT) + elif isinstance(barostat, openmm.MonteCarloMembraneBarostat): + surface_tension = barostat.getDefaultSurfaceTension() + if abs(surface_tension.value_in_unit(unit.bar*unit.nanometer)) > 0: + raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_MEMBRANE_BAROSTAT) if get_index: return force_idx, barostat return barostat @@ -1596,13 +1618,14 @@ def _pop_barostat(cls, system): return None def _is_barostat_consistent(self, barostat): - """Check the barostat's temperature and pressure.""" + """Check the barostat's type, temperature and pressure.""" try: barostat_temperature = barostat.getDefaultTemperature() except AttributeError: # versions previous to OpenMM 7.1 barostat_temperature = barostat.getTemperature() - barostat_pressure = barostat.getDefaultPressure() - is_consistent = utils.is_quantity_close(barostat_temperature, self.temperature) + barostat_pressure = self._get_barostat_pressure(barostat) + is_consistent = (type(barostat) is self._barostat_type) + is_consistent = is_consistent and utils.is_quantity_close(barostat_temperature, self.temperature) is_consistent = is_consistent and utils.is_quantity_close(barostat_pressure, self.pressure) return is_consistent @@ -1644,7 +1667,31 @@ def _set_system_pressure(self, system, pressure): @staticmethod def _set_barostat_pressure(barostat, pressure): """Set barostat pressure.""" - barostat.setDefaultPressure(pressure) + if isinstance(pressure, unit.Quantity): + pressure = pressure.value_in_unit(unit.bar) + if isinstance(barostat, openmm.MonteCarloAnisotropicBarostat): + barostat.setDefaultPressure(openmm.Vec3(pressure, pressure, pressure)*unit.bar) + else: + barostat.setDefaultPressure(pressure*unit.bar) + + @staticmethod + def _set_barostat_pressure_in_context(barostat, pressure, context): + """Set barostat pressure.""" + if isinstance(barostat, openmm.MonteCarloAnisotropicBarostat): + p = pressure.value_in_unit(unit.bar) + context.setParameter(barostat.Pressure(), openmm.Vec3(p, p, p)*unit.bar) + else: + context.setParameter(barostat.Pressure(), pressure) + + @staticmethod + def _get_barostat_pressure(barostat): + """Set barostat pressure.""" + if isinstance(barostat, openmm.MonteCarloAnisotropicBarostat): + scaled = [barostat.getScaleX(), barostat.getScaleY(), barostat.getScaleZ()] + first_scaled_axis = scaled.index(True) + return barostat.getDefaultPressure()[first_scaled_axis] + else: + return barostat.getDefaultPressure() @staticmethod def _set_barostat_temperature(barostat, temperature): diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index 008a94a7d..18ba4d02c 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -94,13 +94,36 @@ def setup_class(cls): cls.multiple_barostat_alanine.addForce(barostat) # A system with an unsupported MonteCarloAnisotropicBarostat - cls.unsupported_barostat_alanine = copy.deepcopy(cls.alanine_explicit) + cls.unsupported_anisotropic_barostat_alanine = copy.deepcopy(cls.alanine_explicit) + pressure_in_bars = cls.std_pressure / unit.bar + anisotropic_pressure = openmm.Vec3(pressure_in_bars, pressure_in_bars, + 1.0+pressure_in_bars) + cls.unsupported_anisotropic_barostat = openmm.MonteCarloAnisotropicBarostat(anisotropic_pressure, cls.std_temperature) + cls.unsupported_anisotropic_barostat_alanine.addForce(cls.unsupported_anisotropic_barostat) + + # A system with an unsupported MonteCarloMembraneBarostat + cls.unsupported_membrane_barostat_alanine = copy.deepcopy(cls.alanine_explicit) + cls.unsupported_membrane_barostat = openmm.MonteCarloMembraneBarostat( + cls.std_pressure, 1.0 * unit.bar * unit.nanometer, cls.std_temperature, + openmm.MonteCarloMembraneBarostat.XYIsotropic, openmm.MonteCarloMembraneBarostat.ZFree + ) + cls.unsupported_membrane_barostat_alanine.addForce(cls.unsupported_membrane_barostat) + + # A system with a supported MonteCarloAnisotropicBarostat + cls.supported_anisotropic_barostat_alanine = copy.deepcopy(cls.alanine_explicit) pressure_in_bars = cls.std_pressure / unit.bar anisotropic_pressure = openmm.Vec3(pressure_in_bars, pressure_in_bars, pressure_in_bars) - cls.anisotropic_barostat = openmm.MonteCarloAnisotropicBarostat(anisotropic_pressure, - cls.std_temperature) - cls.unsupported_barostat_alanine.addForce(cls.anisotropic_barostat) + cls.supported_anisotropic_barostat = openmm.MonteCarloAnisotropicBarostat(anisotropic_pressure, cls.std_temperature) + cls.supported_anisotropic_barostat_alanine.addForce(cls.supported_anisotropic_barostat) + + # A system with a supported MonteCarloMembraneBarostat + cls.supported_membrane_barostat_alanine = copy.deepcopy(cls.alanine_explicit) + cls.supported_membrane_barostat = openmm.MonteCarloMembraneBarostat( + cls.std_pressure, 0.0 * unit.bar * unit.nanometer, cls.std_temperature, + openmm.MonteCarloMembraneBarostat.XYIsotropic, openmm.MonteCarloMembraneBarostat.ZFree + ) + cls.supported_membrane_barostat_alanine.addForce(cls.supported_membrane_barostat) # A system with an inconsistent pressure in the barostat. cls.inconsistent_pressure_alanine = copy.deepcopy(cls.alanine_explicit) @@ -166,10 +189,17 @@ def test_method_find_barostat(self): barostat = ThermodynamicState._find_barostat(self.barostated_alanine) assert isinstance(barostat, openmm.MonteCarloBarostat) + barostat = ThermodynamicState._find_barostat(self.supported_anisotropic_barostat_alanine) + assert isinstance(barostat, openmm.MonteCarloAnisotropicBarostat) + + barostat = ThermodynamicState._find_barostat(self.supported_membrane_barostat_alanine) + assert isinstance(barostat, openmm.MonteCarloMembraneBarostat) + # Raise exception if multiple or unsupported barostats found TE = ThermodynamicsError # shortcut test_cases = [(self.multiple_barostat_alanine, TE.MULTIPLE_BAROSTATS), - (self.unsupported_barostat_alanine, TE.UNSUPPORTED_BAROSTAT)] + (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT), + (self.unsupported_membrane_barostat_alanine, TE.UNSUPPORTED_MEMBRANE_BAROSTAT)] for system, err_code in test_cases: with nose.tools.assert_raises(ThermodynamicsError) as cm: ThermodynamicState._find_barostat(system) @@ -205,6 +235,9 @@ def test_method_is_barostat_consistent(self): barostat = openmm.MonteCarloBarostat(pressure, temperature + 10*unit.kelvin) assert not state._is_barostat_consistent(barostat) + assert not state._is_barostat_consistent(self.supported_anisotropic_barostat) + assert not state._is_barostat_consistent(self.supported_membrane_barostat) + def test_method_set_system_temperature(self): """ThermodynamicState._set_system_temperature() method.""" system = copy.deepcopy(self.alanine_no_thermostat) @@ -222,29 +255,35 @@ def test_method_set_system_temperature(self): def test_property_temperature(self): """ThermodynamicState.temperature property.""" - state = ThermodynamicState(self.barostated_alanine, - self.std_temperature) - assert state.temperature == self.std_temperature - - temperature = self.std_temperature + 10.0*unit.kelvin - state.temperature = temperature - assert state.temperature == temperature - assert get_barostat_temperature(state.barostat) == temperature - - # Setting temperature to None raise error. - with nose.tools.assert_raises(ThermodynamicsError) as cm: - state.temperature = None - assert cm.exception.code == ThermodynamicsError.NONE_TEMPERATURE + for system in [self.barostated_alanine, + self.supported_anisotropic_barostat_alanine, + self.supported_membrane_barostat_alanine]: + state = ThermodynamicState(system, + self.std_temperature) + assert state.temperature == self.std_temperature + + temperature = self.std_temperature + 10.0*unit.kelvin + state.temperature = temperature + assert state.temperature == temperature + assert get_barostat_temperature(state.barostat) == temperature + + # Setting temperature to None raise error. + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state.temperature = None + assert cm.exception.code == ThermodynamicsError.NONE_TEMPERATURE def test_method_set_system_pressure(self): """ThermodynamicState._set_system_pressure() method.""" - state = ThermodynamicState(self.alanine_explicit, self.std_temperature) - system = state.system - assert state._find_barostat(system) is None - state._set_system_pressure(system, self.std_pressure) - assert state._find_barostat(system).getDefaultPressure() == self.std_pressure - state._set_system_pressure(system, None) - assert state._find_barostat(system) is None + for system in [self.barostated_alanine, + self.supported_anisotropic_barostat_alanine, + self.supported_membrane_barostat_alanine]: + state = ThermodynamicState(self.alanine_explicit, self.std_temperature) + system = state.system + assert state._find_barostat(system) is None + state._set_system_pressure(system, self.std_pressure) + assert state._find_barostat(system).getDefaultPressure() == self.std_pressure + state._set_system_pressure(system, None) + assert state._find_barostat(system) is None def test_property_pressure_barostat(self): """ThermodynamicState.pressure and barostat properties.""" @@ -268,11 +307,14 @@ def test_property_pressure_barostat(self): assert state.barostat is None # Correctly reads and set system pressures - periodic_testcases = [self.alanine_explicit] + periodic_testcases = [self.alanine_explicit, + self.supported_anisotropic_barostat_alanine, + self.supported_membrane_barostat_alanine] for system in periodic_testcases: - state = ThermodynamicState(system, self.std_temperature) - assert state.pressure is None - assert state.barostat is None + if system is self.alanine_explicit: + state = ThermodynamicState(system, self.std_temperature) + assert state.pressure is None + assert state.barostat is None # Setting pressure adds a barostat state.pressure = self.std_pressure @@ -319,8 +361,23 @@ def test_property_pressure_barostat(self): # Assign incompatible barostat raise error with nose.tools.assert_raises(ThermodynamicsError) as cm: - state.barostat = self.anisotropic_barostat - assert cm.exception.code == ThermodynamicsError.UNSUPPORTED_BAROSTAT + state.barostat = self.unsupported_anisotropic_barostat + assert cm.exception.code == ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT + + # Assign non-standard barostat raise error + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state.barostat = self.supported_anisotropic_barostat + assert cm.exception.code == ThermodynamicsError.INCONSISTENT_BAROSTAT + + # Assign incompatible barostat raise error + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state.barostat = self.unsupported_membrane_barostat + assert cm.exception.code == ThermodynamicsError.UNSUPPORTED_MEMBRANE_BAROSTAT + + # Assign non-standard barostat raise error + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state.barostat = self.supported_membrane_barostat + assert cm.exception.code == ThermodynamicsError.INCONSISTENT_BAROSTAT # After exception, state is left consistent assert state.pressure is None @@ -355,6 +412,10 @@ def test_property_system(self): test_cases = [(self.toluene_vacuum, TE.NO_BAROSTAT), (self.barostated_toluene, TE.BAROSTATED_NONPERIODIC), (self.multiple_barostat_alanine, TE.MULTIPLE_BAROSTATS), + (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT), + (self.unsupported_membrane_barostat_alanine, TE.UNSUPPORTED_MEMBRANE_BAROSTAT), + (self.supported_anisotropic_barostat_alanine, TE.INCONSISTENT_BAROSTAT), + (self.supported_membrane_barostat_alanine, TE.INCONSISTENT_BAROSTAT), (self.inconsistent_pressure_alanine, TE.INCONSISTENT_BAROSTAT), (self.inconsistent_temperature_alanine, TE.INCONSISTENT_THERMOSTAT), (inconsistent_barostat_temperature, TE.INCONSISTENT_BAROSTAT)] @@ -422,7 +483,8 @@ def test_constructor_unsupported_barostat(self): TE = ThermodynamicsError # shortcut test_cases = [(self.barostated_toluene, TE.BAROSTATED_NONPERIODIC), (self.multiple_barostat_alanine, TE.MULTIPLE_BAROSTATS), - (self.unsupported_barostat_alanine, TE.UNSUPPORTED_BAROSTAT)] + (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT), + (self.unsupported_membrane_barostat_alanine, TE.UNSUPPORTED_MEMBRANE_BAROSTAT)] for i, (system, err_code) in enumerate(test_cases): with nose.tools.assert_raises(TE) as cm: ThermodynamicState(system=system, temperature=self.std_temperature) From 548e7796f1817c7bcdf1d127d9b63be0a6549863 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 25 Sep 2019 16:04:51 +0100 Subject: [PATCH 088/152] Add files via upload --- openmmtools/alchemy.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 0b1dda626..801384c34 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -694,14 +694,14 @@ def create_alchemical_system(self, reference_system, alchemical_regions, # constraints, box vectors and all the forces. We'll later remove # the forces that we remodel to be alchemically modified. alchemical_system = copy.deepcopy(reference_system) - + # Check that there are no virtual sites to alchemically modify. for alchemical_region in alchemical_regions: for particle_index in alchemical_region.alchemical_atoms: if reference_system.isVirtualSite(particle_index): raise ValueError(f'Virtual atoms in region {alchemical_region.name}. ' 'Alchemically modified virtual sites are not supported') - + # Modify forces as appropriate. We delete the forces that # have been processed modified at the end of the for loop. forces_to_remove = [] From 25df3cff2f8173d8d5e05901841e84fa67dd3973 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 25 Sep 2019 16:05:23 +0100 Subject: [PATCH 089/152] Add files via upload --- openmmtools/tests/test_alchemy.py | 445 ++++++++++++++++++++++++------ 1 file changed, 364 insertions(+), 81 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 37383ebfd..6007c4c78 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -211,8 +211,7 @@ def turn_off_nonbonded(system, sterics=False, electrostatics=False, epsilon_coeff*epsilon_scale) - -def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): +def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, other_alchemical_atoms): """Dissect the nonbonded energy contributions of the reference system by atom group and sterics/electrostatics. @@ -227,6 +226,8 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): The positions to test. alchemical_atoms : set of int The indices of the alchemical atoms. + other_alchemical_atoms : set of int + The indices of the alchemical atoms in other alchemical regions Returns ------- @@ -249,7 +250,8 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): na_reciprocal_energy: electrostatics of reciprocal space between nonalchemical-alchemical atoms """ - nonalchemical_atoms = set(range(reference_system.getNumParticles())).difference(alchemical_atoms) + all_alchemical_atoms = set(alchemical_atoms).union(other_alchemical_atoms) + nonalchemical_atoms = set(range(reference_system.getNumParticles())).difference(all_alchemical_atoms) # Remove all forces but NonbondedForce and eventually the # CustomNonbondedForce used to model reaction field. @@ -270,6 +272,10 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): # Compute particle interactions between different groups of atoms # ---------------------------------------------------------------- + #Turn off other alchemical regions + if len(other_alchemical_atoms) > 0: + turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, only_atoms=other_alchemical_atoms) + turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, exceptions=True, only_atoms=other_alchemical_atoms) system = copy.deepcopy(reference_system) # Compute total energy from nonbonded interactions @@ -436,10 +442,12 @@ def is_alchemical_pme_treatment_exact(alchemical_system): # lambda_electrostatics variable. _, nonbonded_force = forces.find_forces(alchemical_system, openmm.NonbondedForce, only_one=True) + test_electro_suffixes = ['', '_zero', '_one', '_two'] for parameter_idx in range(nonbonded_force.getNumGlobalParameters()): parameter_name = nonbonded_force.getGlobalParameterName(parameter_idx) - if parameter_name == 'lambda_electrostatics': - return True + for suffix in test_electro_suffixes: + if parameter_name == 'lambda_electrostatics{}'.format(suffix): + return True return False @@ -454,6 +462,8 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi method is an Ewald method. """ + if not isinstance(alchemical_regions, list): + alchemical_regions = [alchemical_regions] force_group = -1 # Default we compare the energy of all groups. # Check nonbonded method. Comparing with PME is more complicated @@ -479,8 +489,13 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi # Compute the reciprocal space correction added to the direct space # energy due to the exceptions of the alchemical atoms. - alchemical_atoms = alchemical_regions.alchemical_atoms - aa_correction, na_correction = compute_direct_space_correction(nonbonded_force, alchemical_atoms, positions) + aa_correction = 0.0 * unit.kilojoule_per_mole + na_correction = 0.0 * unit.kilojoule_per_mole + for region in alchemical_regions: + alchemical_atoms = region.alchemical_atoms + aa, na = compute_direct_space_correction(nonbonded_force, alchemical_atoms, positions) + aa_correction += aa + na_correction += na # Compute potential of the direct space. potentials = [compute_energy(system, positions, force_group=force_group) @@ -502,8 +517,36 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi err_msg = "Maximum allowable deviation exceeded (was {:.8f} kcal/mol; allowed {:.8f} kcal/mol)." raise Exception(err_msg.format(delta / unit.kilocalories_per_mole, MAX_DELTA / unit.kilocalories_per_mole)) +def check_multi_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): + """wrapper around check_interacting_energy_components for multiple regions + + Parameters + ---------- + reference_system : simtk.openmm.System + The reference system. + alchemical_system : simtk.openmm.System + The alchemically modified system to test. + alchemical_regions : AlchemicalRegion. + The alchemically modified region. + positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity + The positions to test (units of length). + + Note + ---------- + Interactions between alchemical regions are not tested here. + Alchemical regions are assumed to be non interacting. + """ + + all_alchemical_atoms = set() + for region in alchemical_regions: + for atom in region.alchemical_atoms: + all_alchemical_atoms.add(atom) + for region in alchemical_regions: + check_interacting_energy_components(reference_system, alchemical_system, region, positions, all_alchemical_atoms, True) + -def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): +def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, + all_alchemical_atoms=None, multi_regions=False): """Compare full and alchemically-modified system energies by energy component. Parameters @@ -516,6 +559,8 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc The alchemically modified region. positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity The positions to test (units of length). + multi_regions : boolean + Indicates if mutiple regions are being tested """ energy_unit = unit.kilojoule_per_mole @@ -528,9 +573,15 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc nonbonded_method = nonbonded_force.getNonbondedMethod() # Get energy components of reference system's nonbonded force - print("Dissecting reference system's nonbonded force") + if multi_regions: + other_alchemical_atoms = all_alchemical_atoms.difference(alchemical_regions.alchemical_atoms) + print("Dissecting reference system's nonbonded force for region {}".format(alchemical_regions.name)) + else: + other_alchemical_atoms = set() + print("Dissecting reference system's nonbonded force") + energy_components = dissect_nonbonded_energy(reference_system, positions, - alchemical_regions.alchemical_atoms) + alchemical_regions.alchemical_atoms, other_alchemical_atoms) nn_particle_sterics, aa_particle_sterics, na_particle_sterics,\ nn_particle_electro, aa_particle_electro, na_particle_electro,\ nn_exception_sterics, aa_exception_sterics, na_exception_sterics,\ @@ -538,9 +589,12 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc nn_reciprocal_energy, aa_reciprocal_energy, na_reciprocal_energy = energy_components # Dissect unmodified nonbonded force in alchemical system - print("Dissecting alchemical system's unmodified nonbonded force") + if multi_regions: + print("Dissecting alchemical system's unmodified nonbonded force for region {}".format(alchemical_regions.name)) + else: + print("Dissecting alchemical system's unmodified nonbonded force") energy_components = dissect_nonbonded_energy(alchemical_system, positions, - alchemical_regions.alchemical_atoms) + alchemical_regions.alchemical_atoms, other_alchemical_atoms) unmod_nn_particle_sterics, unmod_aa_particle_sterics, unmod_na_particle_sterics,\ unmod_nn_particle_electro, unmod_aa_particle_electro, unmod_na_particle_electro,\ unmod_nn_exception_sterics, unmod_aa_exception_sterics, unmod_na_exception_sterics,\ @@ -548,24 +602,31 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc unmod_nn_reciprocal_energy, unmod_aa_reciprocal_energy, unmod_na_reciprocal_energy = energy_components # Get alchemically-modified energy components - print("Computing alchemical system components energies") - alchemical_state = AlchemicalState.from_system(alchemical_system) + if multi_regions: + print("Computing alchemical system components energies for region {}".format(alchemical_regions.name)) + else: + print("Computing alchemical system components energies") + alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix=alchemical_regions.name) alchemical_state.set_alchemical_parameters(1.0) energy_components = AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, positions, platform=GLOBAL_ALCHEMY_PLATFORM) + if multi_regions: + region_lable = ' for region {}'.format(alchemical_regions.name) + else: + region_lable = '' # Sterics particle and exception interactions are always modeled with a custom force. - na_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical sterics'] - aa_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for alchemical/alchemical sterics'] - na_custom_exception_sterics = energy_components['alchemically modified BondForce for non-alchemical/alchemical sterics exceptions'] - aa_custom_exception_sterics = energy_components['alchemically modified BondForce for alchemical/alchemical sterics exceptions'] + na_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical sterics' + region_lable] + aa_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for alchemical/alchemical sterics' + region_lable] + na_custom_exception_sterics = energy_components['alchemically modified BondForce for non-alchemical/alchemical sterics exceptions' + region_lable] + aa_custom_exception_sterics = energy_components['alchemically modified BondForce for alchemical/alchemical sterics exceptions' + region_lable] # With exact treatment of PME, we use the NonbondedForce offset for electrostatics. try: - na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics'] - aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics'] - na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions'] - aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions'] + na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics' + region_lable] + aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics' + region_lable] + na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions' + region_lable] + aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions' + region_lable] except KeyError: assert is_exact_pme @@ -589,41 +650,41 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc # Check sterics interactions match assert_almost_equal(nn_particle_sterics, unmod_nn_particle_sterics, - 'Non-alchemical/non-alchemical atoms particle sterics') + 'Non-alchemical/non-alchemical atoms particle sterics' + region_lable) assert_almost_equal(nn_exception_sterics, unmod_nn_exception_sterics, - 'Non-alchemical/non-alchemical atoms exceptions sterics') + 'Non-alchemical/non-alchemical atoms exceptions sterics' + region_lable) assert_almost_equal(aa_particle_sterics, aa_custom_particle_sterics, - 'Alchemical/alchemical atoms particle sterics') + 'Alchemical/alchemical atoms particle sterics' + region_lable) assert_almost_equal(aa_exception_sterics, aa_custom_exception_sterics, - 'Alchemical/alchemical atoms exceptions sterics') + 'Alchemical/alchemical atoms exceptions sterics' + region_lable) assert_almost_equal(na_particle_sterics, na_custom_particle_sterics, - 'Non-alchemical/alchemical atoms particle sterics') + 'Non-alchemical/alchemical atoms particle sterics' + region_lable) assert_almost_equal(na_exception_sterics, na_custom_exception_sterics, - 'Non-alchemical/alchemical atoms exceptions sterics') + 'Non-alchemical/alchemical atoms exceptions sterics' + region_lable) # Check electrostatics interactions assert_almost_equal(nn_particle_electro, unmod_nn_particle_electro, - 'Non-alchemical/non-alchemical atoms particle electrostatics') + 'Non-alchemical/non-alchemical atoms particle electrostatics' + region_lable) assert_almost_equal(nn_exception_electro, unmod_nn_exception_electro, - 'Non-alchemical/non-alchemical atoms exceptions electrostatics') + 'Non-alchemical/non-alchemical atoms exceptions electrostatics' + region_lable) # With exact treatment of PME, the electrostatics of alchemical-alchemical # atoms is modeled with NonbondedForce offsets. if is_exact_pme: # Reciprocal space. assert_almost_equal(aa_reciprocal_energy, unmod_aa_reciprocal_energy, - 'Alchemical/alchemical atoms reciprocal space energy') + 'Alchemical/alchemical atoms reciprocal space energy' + region_lable) assert_almost_equal(na_reciprocal_energy, unmod_na_reciprocal_energy, - 'Non-alchemical/alchemical atoms reciprocal space energy') + 'Non-alchemical/alchemical atoms reciprocal space energy' + region_lable) # Direct space. assert_almost_equal(aa_particle_electro, unmod_aa_particle_electro, - 'Alchemical/alchemical atoms particle electrostatics') + 'Alchemical/alchemical atoms particle electrostatics' + region_lable) assert_almost_equal(na_particle_electro, unmod_na_particle_electro, - 'Non-alchemical/alchemical atoms particle electrostatics') + 'Non-alchemical/alchemical atoms particle electrostatics' + region_lable) # Exceptions. assert_almost_equal(aa_exception_electro, unmod_aa_exception_electro, - 'Alchemical/alchemical atoms exceptions electrostatics') + 'Alchemical/alchemical atoms exceptions electrostatics' + region_lable) assert_almost_equal(na_exception_electro, unmod_na_exception_electro, - 'Non-alchemical/alchemical atoms exceptions electrostatics') + 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_lable) # With direct space PME, the custom forces model only the # direct space of alchemical-alchemical interactions. else: @@ -636,14 +697,14 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc # Check direct space energy assert_almost_equal(aa_particle_electro, aa_custom_particle_electro, - 'Alchemical/alchemical atoms particle electrostatics') + 'Alchemical/alchemical atoms particle electrostatics' + region_lable) assert_almost_equal(na_particle_electro, na_custom_particle_electro, - 'Non-alchemical/alchemical atoms particle electrostatics') + 'Non-alchemical/alchemical atoms particle electrostatics' + region_lable) # Check exceptions. assert_almost_equal(aa_exception_electro, aa_custom_exception_electro, - 'Alchemical/alchemical atoms exceptions electrostatics') + 'Alchemical/alchemical atoms exceptions electrostatics' + region_lable) assert_almost_equal(na_exception_electro, na_custom_exception_electro, - 'Non-alchemical/alchemical atoms exceptions electrostatics') + 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_lable) # With Ewald methods, the NonbondedForce should always hold the # reciprocal space energy of nonalchemical-nonalchemical atoms. @@ -676,10 +737,24 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc assert_almost_equal(reference_force_energy, tot_alchemical_forces_energies, '{} energy '.format(force_name)) +def check_multi_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): + """wrapper around check_noninteracting_energy_components for multiple regions + Parameters + ---------- + reference_system : simtk.openmm.System + The reference system (not alchemically modified). + alchemical_system : simtk.openmm.System + The alchemically modified system to test. + alchemical_regions : AlchemicalRegion. + The alchemically modified region. + positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity + The positions to test (units of length). + """ + for region in alchemical_regions: + check_noninteracting_energy_components(reference_system, alchemical_system, region, positions, True) -def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): +def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, multi_regions=False): """Check non-interacting energy components are zero when appropriate. - Parameters ---------- reference_system : simtk.openmm.System @@ -690,18 +765,23 @@ def check_noninteracting_energy_components(reference_system, alchemical_system, The alchemically modified region. positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity The positions to test (units of length). - + multi_regions : boolean + Indicates if mutiple regions are being tested """ alchemical_system = copy.deepcopy(alchemical_system) is_exact_pme = is_alchemical_pme_treatment_exact(alchemical_system) # Set state to non-interacting. - alchemical_state = AlchemicalState.from_system(alchemical_system) + alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix=alchemical_regions.name) alchemical_state.set_alchemical_parameters(0.0) energy_components = AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, positions, platform=GLOBAL_ALCHEMY_PLATFORM) def assert_zero_energy(label): + # Handle multiple alchemical regions. + if multi_regions: + label = label + ' for region ' + alchemical_regions.name + # Testing energy component of each region. print('testing {}'.format(label)) value = energy_components[label] assert abs(value / GLOBAL_ENERGY_UNIT) == 0.0, ("'{}' should have zero energy in annihilated alchemical" @@ -811,44 +891,47 @@ def assert_zero_energy(label): 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) -def check_split_force_groups(system): +def check_split_force_groups(system, region_names=None): """Check that force groups are split correctly.""" - force_groups_by_lambda = {} - lambdas_by_force_group = {} + if region_names is None: + region_names = [] # Separate forces groups by lambda parameters that AlchemicalState supports. - for force, lambda_name, _ in AlchemicalState._get_system_controlled_parameters( - system, parameters_name_suffix=None): - force_group = force.getForceGroup() - try: - force_groups_by_lambda[lambda_name].add(force_group) - except KeyError: - force_groups_by_lambda[lambda_name] = {force_group} - try: - lambdas_by_force_group[force_group].add(lambda_name) - except KeyError: - lambdas_by_force_group[force_group] = {lambda_name} - - # Check that force group 0 doesn't hold alchemical forces. - assert 0 not in force_groups_by_lambda - - # There are as many alchemical force groups as not-None lambda variables. - alchemical_state = AlchemicalState.from_system(system) - valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters() - if getattr(alchemical_state, lambda_name) is not None} - assert valid_lambdas == set(force_groups_by_lambda.keys()) - - # Check that force groups and lambda variables are in 1-to-1 correspondence. - assert len(force_groups_by_lambda) == len(lambdas_by_force_group) - for d in [force_groups_by_lambda, lambdas_by_force_group]: - for value in d.values(): - assert len(value) == 1 - - # With exact treatment of PME, the NonbondedForce must - # be in the lambda_electrostatics force group. - if is_alchemical_pme_treatment_exact(system): - force_idx, nonbonded_force = forces.find_forces(system, openmm.NonbondedForce, only_one=True) - assert force_groups_by_lambda['lambda_electrostatics'] == {nonbonded_force.getForceGroup()} + for region in region_names: + force_groups_by_lambda = {} + lambdas_by_force_group = {} + for force, lambda_name, _ in AlchemicalState._get_system_controlled_parameters( + system, parameters_name_suffix=region): + force_group = force.getForceGroup() + try: + force_groups_by_lambda[lambda_name].add(force_group) + except KeyError: + force_groups_by_lambda[lambda_name] = {force_group} + try: + lambdas_by_force_group[force_group].add(lambda_name) + except KeyError: + lambdas_by_force_group[force_group] = {lambda_name} + + # Check that force group 0 doesn't hold alchemical forces. + assert 0 not in force_groups_by_lambda + + # There are as many alchemical force groups as not-None lambda variables. + alchemical_state = AlchemicalState.from_system(system, parameters_name_suffix=region) + valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters(parameters_name_suffix=region) + if getattr(alchemical_state, lambda_name) is not None} + assert valid_lambdas == set(force_groups_by_lambda.keys()) + + # Check that force groups and lambda variables are in 1-to-1 correspondence. + assert len(force_groups_by_lambda) == len(lambdas_by_force_group) + for d in [force_groups_by_lambda, lambdas_by_force_group]: + for value in d.values(): + assert len(value) == 1 + + # With exact treatment of PME, the NonbondedForce must + # be in the lambda_electrostatics force group. + if is_alchemical_pme_treatment_exact(system): + force_idx, nonbonded_force = forces.find_forces(system, openmm.NonbondedForce, only_one=True) + assert force_groups_by_lambda['lambda_electrostatics_{}'.format(region)] == {nonbonded_force.getForceGroup()} # ============================================================================= @@ -1221,7 +1304,6 @@ def test_resolve_alchemical_region(): with nose.tools.assert_raises(ValueError): AbsoluteAlchemicalFactory._resolve_alchemical_region(system, alchemical_region) - class TestAbsoluteAlchemicalFactory(object): """Test AbsoluteAlchemicalFactory class.""" @@ -1269,7 +1351,7 @@ def define_regions(cls): cls.test_regions['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2)) cls.test_regions['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10)) cls.test_regions['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3)) - cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4)) # Modify ions. + cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(3)) # Modify ions. cls.test_regions['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6)) # Only partially modified. cls.test_regions['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22)) cls.test_regions['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156)) @@ -1440,6 +1522,207 @@ def test_overlap(self): f.description = "Testing reference/alchemical overlap for {}".format(test_name) yield f +class TestMultiRegionAbsoluteAlchemicalFactory(TestAbsoluteAlchemicalFactory): + """Test AbsoluteAlchemicalFactory class using multiple regions.""" + + @classmethod + def define_systems(cls): + """Create shared test systems in cls.test_systems for the test suite.""" + cls.test_systems = dict() + + # Basic test systems: Lennard-Jones and water particles only. + # Test also dispersion correction and switch off ("on" values + # for these options are tested in HostGuestExplicit system). + cls.test_systems['LennardJonesCluster'] = testsystems.LennardJonesCluster() + cls.test_systems['LennardJonesFluid with dispersion correction'] = \ + testsystems.LennardJonesFluid(nparticles=100, dispersion_correction=True) + cls.test_systems['TIP3P WaterBox with reaction field, no switch, no dispersion correction'] = \ + testsystems.WaterBox(dispersion_correction=False, switch=False, nonbondedMethod=openmm.app.CutoffPeriodic) + cls.test_systems['HostGuestExplicit with PME'] = \ + testsystems.HostGuestExplicit(nonbondedMethod=openmm.app.PME) + cls.test_systems['HostGuestExplicit with CutoffPeriodic'] = \ + testsystems.HostGuestExplicit(nonbondedMethod=openmm.app.CutoffPeriodic) + + @classmethod + def define_regions(cls): + """Create shared AlchemicalRegions for test systems in cls.test_regions.""" + cls.test_region_zero = dict() + cls.test_region_one = dict() + cls.test_region_two = dict() + + cls.test_region_zero['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2), name='zero') + cls.test_region_one['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2,4), name='one') + cls.test_region_two['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(4,6), name='two') + cls.test_region_zero['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10), name='zero') + cls.test_region_one['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10,20), name='one') + cls.test_region_two['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(20,30), name='two') + cls.test_region_zero['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3), name='zero') + cls.test_region_one['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3,6), name='one') + cls.test_region_two['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(6,9), name='two') + #Three regions push HostGuest system beyond 32 force groups + cls.test_region_zero['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156), name='zero') + cls.test_region_one['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(156,160), name='one') + cls.test_region_two['HostGuestExplicit'] = None + + @classmethod + def generate_cases(cls): + """Generate all test cases in cls.test_cases combinatorially.""" + cls.test_cases = dict() + direct_space_factory = AbsoluteAlchemicalFactory(alchemical_pme_treatment='direct-space', + alchemical_rf_treatment='switched') + exact_pme_factory = AbsoluteAlchemicalFactory(alchemical_pme_treatment='exact') + + # We generate all possible combinations of annihilate_sterics/electrostatics + # for each test system. We also annihilate bonds, angles and torsions every + # 3 test cases so that we test it at least one for each test system and for + # each combination of annihilate_sterics/electrostatics. + n_test_cases = 0 + for test_system_name, test_system in cls.test_systems.items(): + + # Find standard alchemical region zero. + for region_name_zero, region_zero in cls.test_region_zero.items(): + if region_name_zero in test_system_name: + break + assert region_name_zero in test_system_name, test_system_name + + # Find standard alchemical region one. + for region_name_one, region_one in cls.test_region_one.items(): + if region_name_one in test_system_name: + break + assert region_name_one in test_system_name, test_system_name + + # Find standard alchemical region two. + for region_name_two, region_two in cls.test_region_two.items(): + if region_name_two in test_system_name: + break + assert region_name_two in test_system_name, test_system_name + + assert region_name_zero == region_name_one and region_name_one == region_name_two + #We only want two regions for HostGuest or we get too many force groups + if 'HostGuestExplicit' in region_name_one: + test_regions = [region_zero, region_one] + else: + test_regions = [region_zero, region_one, region_two] + + # Find nonbonded method. + force_idx, nonbonded_force = forces.find_forces(test_system.system, openmm.NonbondedForce, only_one=True) + nonbonded_method = nonbonded_force.getNonbondedMethod() + + # Create all combinations of annihilate_sterics/electrostatics. + for annihilate_sterics, annihilate_electrostatics in itertools.product((True, False), repeat=2): + # Create new region that we can modify. + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(annihilate_sterics=annihilate_sterics, + annihilate_electrostatics=annihilate_electrostatics) + + # Create test name. + test_case_name = test_system_name[:] + if annihilate_sterics: + test_case_name += ', annihilated sterics' + if annihilate_electrostatics: + test_case_name += ', annihilated electrostatics' + + # Annihilate bonds and angles every three test_cases. + if n_test_cases % 3 == 0: + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(alchemical_bonds=True, alchemical_angles=True, + alchemical_torsions=True) + test_case_name += ', annihilated bonds, angles and torsions' + + # Add different softcore parameters every five test_cases. + if n_test_cases % 5 == 0: + for i, test_region in enumerate(test_regions): + test_regions[i] = test_region._replace(softcore_alpha=1.0, softcore_beta=1.0, softcore_a=1.0, softcore_b=1.0, + softcore_c=1.0, softcore_d=1.0, softcore_e=1.0, softcore_f=1.0) + test_case_name += ', modified softcore parameters' + + #region_interactions = frozenset(itertools.combinations(range(len(test_regions)), 2)) + # Pre-generate alchemical system. + alchemical_system = direct_space_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) + + # Add test case. + cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) + + n_test_cases += 1 + + # If we don't use softcore electrostatics and we annihilate charges + # we can test also exact PME treatment. We don't increase n_test_cases + # purposely to keep track of which tests are added above. + if (test_regions[1].softcore_beta == 0.0 and annihilate_electrostatics and + nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]): + alchemical_system = exact_pme_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) + test_case_name += ', exact PME' + cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) + + # If the test system uses reaction field replace reaction field + # of the reference system to allow comparisons. + if nonbonded_method == openmm.NonbondedForce.CutoffPeriodic: + forcefactories.replace_reaction_field(test_system.system, return_copy=False, + switch_width=direct_space_factory.switch_width) + + def test_split_force_groups(self): + """Forces having different lambda variables should have a different force group.""" + # Select 1 implicit, 1 explicit, and 1 exact PME explicit test case randomly. + test_cases = self.filter_cases(lambda x: 'Implicit' in x, max_number=1) + test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' in x, max_number=1)) + test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' not in x, max_number=1)) + for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): + region_names = [] + for region in alchemical_region: + region_names.append(region.name) + f = partial(check_split_force_groups, alchemical_system, region_names) + f.description = "Testing force splitting among groups of {}".format(test_name) + yield f + + def test_noninteracting_energy_components(self): + """Check all forces annihilated/decoupled when their lambda variables are zero.""" + for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): + f = partial(check_multi_noninteracting_energy_components, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Testing non-interacting energy of {}".format(test_name) + yield f + + @attr('slow') + def test_platforms(self): + """Test interacting and noninteracting energies on all platforms.""" + global GLOBAL_ALCHEMY_PLATFORM + old_global_platform = GLOBAL_ALCHEMY_PLATFORM + + # Do not repeat tests on the platform already tested. + if old_global_platform is None: + default_platform_name = utils.get_fastest_platform().getName() + else: + default_platform_name = old_global_platform.getName() + platforms = [platform for platform in utils.get_available_platforms() + if platform.getName() != default_platform_name] + + # Test interacting and noninteracting energies on all platforms. + for platform in platforms: + GLOBAL_ALCHEMY_PLATFORM = platform + for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): + f = partial(compare_system_energies, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Test fully interacting energy of {} on {}".format(test_name, platform.getName()) + yield f + f = partial(check_multi_noninteracting_energy_components, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Test non-interacting energy of {} on {}".format(test_name, platform.getName()) + yield f + + # Restore global platform + GLOBAL_ALCHEMY_PLATFORM = old_global_platform + + @attr('slow') + def test_fully_interacting_energy_components(self): + """Test interacting state energy by force component.""" + # This is a very expensive but very informative test. We can + # run this locally when test_fully_interacting_energies() fails. + test_cases = self.filter_cases(lambda x: 'Explicit' in x) + for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): + f = partial(check_multi_interacting_energy_components, test_system.system, alchemical_system, + alchemical_region, test_system.positions) + f.description = "Testing energy components of %s..." % test_name + yield f class TestDispersionlessAlchemicalFactory(object): """ From f26e55c5cd9f0e5d1f7e597cf7dd1b8dc284e78e Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 25 Sep 2019 16:31:21 +0100 Subject: [PATCH 090/152] Correct mistaken push --- openmmtools/tests/test_alchemy.py | 445 ++++++------------------------ 1 file changed, 81 insertions(+), 364 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 6007c4c78..37383ebfd 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -211,7 +211,8 @@ def turn_off_nonbonded(system, sterics=False, electrostatics=False, epsilon_coeff*epsilon_scale) -def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, other_alchemical_atoms): + +def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms): """Dissect the nonbonded energy contributions of the reference system by atom group and sterics/electrostatics. @@ -226,8 +227,6 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe The positions to test. alchemical_atoms : set of int The indices of the alchemical atoms. - other_alchemical_atoms : set of int - The indices of the alchemical atoms in other alchemical regions Returns ------- @@ -250,8 +249,7 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe na_reciprocal_energy: electrostatics of reciprocal space between nonalchemical-alchemical atoms """ - all_alchemical_atoms = set(alchemical_atoms).union(other_alchemical_atoms) - nonalchemical_atoms = set(range(reference_system.getNumParticles())).difference(all_alchemical_atoms) + nonalchemical_atoms = set(range(reference_system.getNumParticles())).difference(alchemical_atoms) # Remove all forces but NonbondedForce and eventually the # CustomNonbondedForce used to model reaction field. @@ -272,10 +270,6 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe # Compute particle interactions between different groups of atoms # ---------------------------------------------------------------- - #Turn off other alchemical regions - if len(other_alchemical_atoms) > 0: - turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, only_atoms=other_alchemical_atoms) - turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, exceptions=True, only_atoms=other_alchemical_atoms) system = copy.deepcopy(reference_system) # Compute total energy from nonbonded interactions @@ -442,12 +436,10 @@ def is_alchemical_pme_treatment_exact(alchemical_system): # lambda_electrostatics variable. _, nonbonded_force = forces.find_forces(alchemical_system, openmm.NonbondedForce, only_one=True) - test_electro_suffixes = ['', '_zero', '_one', '_two'] for parameter_idx in range(nonbonded_force.getNumGlobalParameters()): parameter_name = nonbonded_force.getGlobalParameterName(parameter_idx) - for suffix in test_electro_suffixes: - if parameter_name == 'lambda_electrostatics{}'.format(suffix): - return True + if parameter_name == 'lambda_electrostatics': + return True return False @@ -462,8 +454,6 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi method is an Ewald method. """ - if not isinstance(alchemical_regions, list): - alchemical_regions = [alchemical_regions] force_group = -1 # Default we compare the energy of all groups. # Check nonbonded method. Comparing with PME is more complicated @@ -489,13 +479,8 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi # Compute the reciprocal space correction added to the direct space # energy due to the exceptions of the alchemical atoms. - aa_correction = 0.0 * unit.kilojoule_per_mole - na_correction = 0.0 * unit.kilojoule_per_mole - for region in alchemical_regions: - alchemical_atoms = region.alchemical_atoms - aa, na = compute_direct_space_correction(nonbonded_force, alchemical_atoms, positions) - aa_correction += aa - na_correction += na + alchemical_atoms = alchemical_regions.alchemical_atoms + aa_correction, na_correction = compute_direct_space_correction(nonbonded_force, alchemical_atoms, positions) # Compute potential of the direct space. potentials = [compute_energy(system, positions, force_group=force_group) @@ -517,36 +502,8 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi err_msg = "Maximum allowable deviation exceeded (was {:.8f} kcal/mol; allowed {:.8f} kcal/mol)." raise Exception(err_msg.format(delta / unit.kilocalories_per_mole, MAX_DELTA / unit.kilocalories_per_mole)) -def check_multi_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): - """wrapper around check_interacting_energy_components for multiple regions - - Parameters - ---------- - reference_system : simtk.openmm.System - The reference system. - alchemical_system : simtk.openmm.System - The alchemically modified system to test. - alchemical_regions : AlchemicalRegion. - The alchemically modified region. - positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity - The positions to test (units of length). - - Note - ---------- - Interactions between alchemical regions are not tested here. - Alchemical regions are assumed to be non interacting. - """ - - all_alchemical_atoms = set() - for region in alchemical_regions: - for atom in region.alchemical_atoms: - all_alchemical_atoms.add(atom) - for region in alchemical_regions: - check_interacting_energy_components(reference_system, alchemical_system, region, positions, all_alchemical_atoms, True) - -def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, - all_alchemical_atoms=None, multi_regions=False): +def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): """Compare full and alchemically-modified system energies by energy component. Parameters @@ -559,8 +516,6 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc The alchemically modified region. positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity The positions to test (units of length). - multi_regions : boolean - Indicates if mutiple regions are being tested """ energy_unit = unit.kilojoule_per_mole @@ -573,15 +528,9 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc nonbonded_method = nonbonded_force.getNonbondedMethod() # Get energy components of reference system's nonbonded force - if multi_regions: - other_alchemical_atoms = all_alchemical_atoms.difference(alchemical_regions.alchemical_atoms) - print("Dissecting reference system's nonbonded force for region {}".format(alchemical_regions.name)) - else: - other_alchemical_atoms = set() - print("Dissecting reference system's nonbonded force") - + print("Dissecting reference system's nonbonded force") energy_components = dissect_nonbonded_energy(reference_system, positions, - alchemical_regions.alchemical_atoms, other_alchemical_atoms) + alchemical_regions.alchemical_atoms) nn_particle_sterics, aa_particle_sterics, na_particle_sterics,\ nn_particle_electro, aa_particle_electro, na_particle_electro,\ nn_exception_sterics, aa_exception_sterics, na_exception_sterics,\ @@ -589,12 +538,9 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc nn_reciprocal_energy, aa_reciprocal_energy, na_reciprocal_energy = energy_components # Dissect unmodified nonbonded force in alchemical system - if multi_regions: - print("Dissecting alchemical system's unmodified nonbonded force for region {}".format(alchemical_regions.name)) - else: - print("Dissecting alchemical system's unmodified nonbonded force") + print("Dissecting alchemical system's unmodified nonbonded force") energy_components = dissect_nonbonded_energy(alchemical_system, positions, - alchemical_regions.alchemical_atoms, other_alchemical_atoms) + alchemical_regions.alchemical_atoms) unmod_nn_particle_sterics, unmod_aa_particle_sterics, unmod_na_particle_sterics,\ unmod_nn_particle_electro, unmod_aa_particle_electro, unmod_na_particle_electro,\ unmod_nn_exception_sterics, unmod_aa_exception_sterics, unmod_na_exception_sterics,\ @@ -602,31 +548,24 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc unmod_nn_reciprocal_energy, unmod_aa_reciprocal_energy, unmod_na_reciprocal_energy = energy_components # Get alchemically-modified energy components - if multi_regions: - print("Computing alchemical system components energies for region {}".format(alchemical_regions.name)) - else: - print("Computing alchemical system components energies") - alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix=alchemical_regions.name) + print("Computing alchemical system components energies") + alchemical_state = AlchemicalState.from_system(alchemical_system) alchemical_state.set_alchemical_parameters(1.0) energy_components = AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, positions, platform=GLOBAL_ALCHEMY_PLATFORM) - if multi_regions: - region_lable = ' for region {}'.format(alchemical_regions.name) - else: - region_lable = '' # Sterics particle and exception interactions are always modeled with a custom force. - na_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical sterics' + region_lable] - aa_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for alchemical/alchemical sterics' + region_lable] - na_custom_exception_sterics = energy_components['alchemically modified BondForce for non-alchemical/alchemical sterics exceptions' + region_lable] - aa_custom_exception_sterics = energy_components['alchemically modified BondForce for alchemical/alchemical sterics exceptions' + region_lable] + na_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical sterics'] + aa_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for alchemical/alchemical sterics'] + na_custom_exception_sterics = energy_components['alchemically modified BondForce for non-alchemical/alchemical sterics exceptions'] + aa_custom_exception_sterics = energy_components['alchemically modified BondForce for alchemical/alchemical sterics exceptions'] # With exact treatment of PME, we use the NonbondedForce offset for electrostatics. try: - na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics' + region_lable] - aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics' + region_lable] - na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions' + region_lable] - aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions' + region_lable] + na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics'] + aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics'] + na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions'] + aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions'] except KeyError: assert is_exact_pme @@ -650,41 +589,41 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc # Check sterics interactions match assert_almost_equal(nn_particle_sterics, unmod_nn_particle_sterics, - 'Non-alchemical/non-alchemical atoms particle sterics' + region_lable) + 'Non-alchemical/non-alchemical atoms particle sterics') assert_almost_equal(nn_exception_sterics, unmod_nn_exception_sterics, - 'Non-alchemical/non-alchemical atoms exceptions sterics' + region_lable) + 'Non-alchemical/non-alchemical atoms exceptions sterics') assert_almost_equal(aa_particle_sterics, aa_custom_particle_sterics, - 'Alchemical/alchemical atoms particle sterics' + region_lable) + 'Alchemical/alchemical atoms particle sterics') assert_almost_equal(aa_exception_sterics, aa_custom_exception_sterics, - 'Alchemical/alchemical atoms exceptions sterics' + region_lable) + 'Alchemical/alchemical atoms exceptions sterics') assert_almost_equal(na_particle_sterics, na_custom_particle_sterics, - 'Non-alchemical/alchemical atoms particle sterics' + region_lable) + 'Non-alchemical/alchemical atoms particle sterics') assert_almost_equal(na_exception_sterics, na_custom_exception_sterics, - 'Non-alchemical/alchemical atoms exceptions sterics' + region_lable) + 'Non-alchemical/alchemical atoms exceptions sterics') # Check electrostatics interactions assert_almost_equal(nn_particle_electro, unmod_nn_particle_electro, - 'Non-alchemical/non-alchemical atoms particle electrostatics' + region_lable) + 'Non-alchemical/non-alchemical atoms particle electrostatics') assert_almost_equal(nn_exception_electro, unmod_nn_exception_electro, - 'Non-alchemical/non-alchemical atoms exceptions electrostatics' + region_lable) + 'Non-alchemical/non-alchemical atoms exceptions electrostatics') # With exact treatment of PME, the electrostatics of alchemical-alchemical # atoms is modeled with NonbondedForce offsets. if is_exact_pme: # Reciprocal space. assert_almost_equal(aa_reciprocal_energy, unmod_aa_reciprocal_energy, - 'Alchemical/alchemical atoms reciprocal space energy' + region_lable) + 'Alchemical/alchemical atoms reciprocal space energy') assert_almost_equal(na_reciprocal_energy, unmod_na_reciprocal_energy, - 'Non-alchemical/alchemical atoms reciprocal space energy' + region_lable) + 'Non-alchemical/alchemical atoms reciprocal space energy') # Direct space. assert_almost_equal(aa_particle_electro, unmod_aa_particle_electro, - 'Alchemical/alchemical atoms particle electrostatics' + region_lable) + 'Alchemical/alchemical atoms particle electrostatics') assert_almost_equal(na_particle_electro, unmod_na_particle_electro, - 'Non-alchemical/alchemical atoms particle electrostatics' + region_lable) + 'Non-alchemical/alchemical atoms particle electrostatics') # Exceptions. assert_almost_equal(aa_exception_electro, unmod_aa_exception_electro, - 'Alchemical/alchemical atoms exceptions electrostatics' + region_lable) + 'Alchemical/alchemical atoms exceptions electrostatics') assert_almost_equal(na_exception_electro, unmod_na_exception_electro, - 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_lable) + 'Non-alchemical/alchemical atoms exceptions electrostatics') # With direct space PME, the custom forces model only the # direct space of alchemical-alchemical interactions. else: @@ -697,14 +636,14 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc # Check direct space energy assert_almost_equal(aa_particle_electro, aa_custom_particle_electro, - 'Alchemical/alchemical atoms particle electrostatics' + region_lable) + 'Alchemical/alchemical atoms particle electrostatics') assert_almost_equal(na_particle_electro, na_custom_particle_electro, - 'Non-alchemical/alchemical atoms particle electrostatics' + region_lable) + 'Non-alchemical/alchemical atoms particle electrostatics') # Check exceptions. assert_almost_equal(aa_exception_electro, aa_custom_exception_electro, - 'Alchemical/alchemical atoms exceptions electrostatics' + region_lable) + 'Alchemical/alchemical atoms exceptions electrostatics') assert_almost_equal(na_exception_electro, na_custom_exception_electro, - 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_lable) + 'Non-alchemical/alchemical atoms exceptions electrostatics') # With Ewald methods, the NonbondedForce should always hold the # reciprocal space energy of nonalchemical-nonalchemical atoms. @@ -737,24 +676,10 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc assert_almost_equal(reference_force_energy, tot_alchemical_forces_energies, '{} energy '.format(force_name)) -def check_multi_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): - """wrapper around check_noninteracting_energy_components for multiple regions - Parameters - ---------- - reference_system : simtk.openmm.System - The reference system (not alchemically modified). - alchemical_system : simtk.openmm.System - The alchemically modified system to test. - alchemical_regions : AlchemicalRegion. - The alchemically modified region. - positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity - The positions to test (units of length). - """ - for region in alchemical_regions: - check_noninteracting_energy_components(reference_system, alchemical_system, region, positions, True) -def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, multi_regions=False): +def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): """Check non-interacting energy components are zero when appropriate. + Parameters ---------- reference_system : simtk.openmm.System @@ -765,23 +690,18 @@ def check_noninteracting_energy_components(reference_system, alchemical_system, The alchemically modified region. positions : n_particlesx3 array-like of simtk.openmm.unit.Quantity The positions to test (units of length). - multi_regions : boolean - Indicates if mutiple regions are being tested + """ alchemical_system = copy.deepcopy(alchemical_system) is_exact_pme = is_alchemical_pme_treatment_exact(alchemical_system) # Set state to non-interacting. - alchemical_state = AlchemicalState.from_system(alchemical_system, parameters_name_suffix=alchemical_regions.name) + alchemical_state = AlchemicalState.from_system(alchemical_system) alchemical_state.set_alchemical_parameters(0.0) energy_components = AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, positions, platform=GLOBAL_ALCHEMY_PLATFORM) def assert_zero_energy(label): - # Handle multiple alchemical regions. - if multi_regions: - label = label + ' for region ' + alchemical_regions.name - # Testing energy component of each region. print('testing {}'.format(label)) value = energy_components[label] assert abs(value / GLOBAL_ENERGY_UNIT) == 0.0, ("'{}' should have zero energy in annihilated alchemical" @@ -891,47 +811,44 @@ def assert_zero_energy(label): 'reference {}, alchemical {}'.format(reference_force_energy, alchemical_energy)) -def check_split_force_groups(system, region_names=None): +def check_split_force_groups(system): """Check that force groups are split correctly.""" + force_groups_by_lambda = {} + lambdas_by_force_group = {} - if region_names is None: - region_names = [] # Separate forces groups by lambda parameters that AlchemicalState supports. - for region in region_names: - force_groups_by_lambda = {} - lambdas_by_force_group = {} - for force, lambda_name, _ in AlchemicalState._get_system_controlled_parameters( - system, parameters_name_suffix=region): - force_group = force.getForceGroup() - try: - force_groups_by_lambda[lambda_name].add(force_group) - except KeyError: - force_groups_by_lambda[lambda_name] = {force_group} - try: - lambdas_by_force_group[force_group].add(lambda_name) - except KeyError: - lambdas_by_force_group[force_group] = {lambda_name} - - # Check that force group 0 doesn't hold alchemical forces. - assert 0 not in force_groups_by_lambda - - # There are as many alchemical force groups as not-None lambda variables. - alchemical_state = AlchemicalState.from_system(system, parameters_name_suffix=region) - valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters(parameters_name_suffix=region) - if getattr(alchemical_state, lambda_name) is not None} - assert valid_lambdas == set(force_groups_by_lambda.keys()) - - # Check that force groups and lambda variables are in 1-to-1 correspondence. - assert len(force_groups_by_lambda) == len(lambdas_by_force_group) - for d in [force_groups_by_lambda, lambdas_by_force_group]: - for value in d.values(): - assert len(value) == 1 - - # With exact treatment of PME, the NonbondedForce must - # be in the lambda_electrostatics force group. - if is_alchemical_pme_treatment_exact(system): - force_idx, nonbonded_force = forces.find_forces(system, openmm.NonbondedForce, only_one=True) - assert force_groups_by_lambda['lambda_electrostatics_{}'.format(region)] == {nonbonded_force.getForceGroup()} + for force, lambda_name, _ in AlchemicalState._get_system_controlled_parameters( + system, parameters_name_suffix=None): + force_group = force.getForceGroup() + try: + force_groups_by_lambda[lambda_name].add(force_group) + except KeyError: + force_groups_by_lambda[lambda_name] = {force_group} + try: + lambdas_by_force_group[force_group].add(lambda_name) + except KeyError: + lambdas_by_force_group[force_group] = {lambda_name} + + # Check that force group 0 doesn't hold alchemical forces. + assert 0 not in force_groups_by_lambda + + # There are as many alchemical force groups as not-None lambda variables. + alchemical_state = AlchemicalState.from_system(system) + valid_lambdas = {lambda_name for lambda_name in alchemical_state._get_controlled_parameters() + if getattr(alchemical_state, lambda_name) is not None} + assert valid_lambdas == set(force_groups_by_lambda.keys()) + + # Check that force groups and lambda variables are in 1-to-1 correspondence. + assert len(force_groups_by_lambda) == len(lambdas_by_force_group) + for d in [force_groups_by_lambda, lambdas_by_force_group]: + for value in d.values(): + assert len(value) == 1 + + # With exact treatment of PME, the NonbondedForce must + # be in the lambda_electrostatics force group. + if is_alchemical_pme_treatment_exact(system): + force_idx, nonbonded_force = forces.find_forces(system, openmm.NonbondedForce, only_one=True) + assert force_groups_by_lambda['lambda_electrostatics'] == {nonbonded_force.getForceGroup()} # ============================================================================= @@ -1304,6 +1221,7 @@ def test_resolve_alchemical_region(): with nose.tools.assert_raises(ValueError): AbsoluteAlchemicalFactory._resolve_alchemical_region(system, alchemical_region) + class TestAbsoluteAlchemicalFactory(object): """Test AbsoluteAlchemicalFactory class.""" @@ -1351,7 +1269,7 @@ def define_regions(cls): cls.test_regions['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2)) cls.test_regions['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10)) cls.test_regions['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3)) - cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(3)) # Modify ions. + cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4)) # Modify ions. cls.test_regions['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6)) # Only partially modified. cls.test_regions['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22)) cls.test_regions['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156)) @@ -1522,207 +1440,6 @@ def test_overlap(self): f.description = "Testing reference/alchemical overlap for {}".format(test_name) yield f -class TestMultiRegionAbsoluteAlchemicalFactory(TestAbsoluteAlchemicalFactory): - """Test AbsoluteAlchemicalFactory class using multiple regions.""" - - @classmethod - def define_systems(cls): - """Create shared test systems in cls.test_systems for the test suite.""" - cls.test_systems = dict() - - # Basic test systems: Lennard-Jones and water particles only. - # Test also dispersion correction and switch off ("on" values - # for these options are tested in HostGuestExplicit system). - cls.test_systems['LennardJonesCluster'] = testsystems.LennardJonesCluster() - cls.test_systems['LennardJonesFluid with dispersion correction'] = \ - testsystems.LennardJonesFluid(nparticles=100, dispersion_correction=True) - cls.test_systems['TIP3P WaterBox with reaction field, no switch, no dispersion correction'] = \ - testsystems.WaterBox(dispersion_correction=False, switch=False, nonbondedMethod=openmm.app.CutoffPeriodic) - cls.test_systems['HostGuestExplicit with PME'] = \ - testsystems.HostGuestExplicit(nonbondedMethod=openmm.app.PME) - cls.test_systems['HostGuestExplicit with CutoffPeriodic'] = \ - testsystems.HostGuestExplicit(nonbondedMethod=openmm.app.CutoffPeriodic) - - @classmethod - def define_regions(cls): - """Create shared AlchemicalRegions for test systems in cls.test_regions.""" - cls.test_region_zero = dict() - cls.test_region_one = dict() - cls.test_region_two = dict() - - cls.test_region_zero['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2), name='zero') - cls.test_region_one['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2,4), name='one') - cls.test_region_two['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(4,6), name='two') - cls.test_region_zero['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10), name='zero') - cls.test_region_one['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10,20), name='one') - cls.test_region_two['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(20,30), name='two') - cls.test_region_zero['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3), name='zero') - cls.test_region_one['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3,6), name='one') - cls.test_region_two['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(6,9), name='two') - #Three regions push HostGuest system beyond 32 force groups - cls.test_region_zero['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156), name='zero') - cls.test_region_one['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(156,160), name='one') - cls.test_region_two['HostGuestExplicit'] = None - - @classmethod - def generate_cases(cls): - """Generate all test cases in cls.test_cases combinatorially.""" - cls.test_cases = dict() - direct_space_factory = AbsoluteAlchemicalFactory(alchemical_pme_treatment='direct-space', - alchemical_rf_treatment='switched') - exact_pme_factory = AbsoluteAlchemicalFactory(alchemical_pme_treatment='exact') - - # We generate all possible combinations of annihilate_sterics/electrostatics - # for each test system. We also annihilate bonds, angles and torsions every - # 3 test cases so that we test it at least one for each test system and for - # each combination of annihilate_sterics/electrostatics. - n_test_cases = 0 - for test_system_name, test_system in cls.test_systems.items(): - - # Find standard alchemical region zero. - for region_name_zero, region_zero in cls.test_region_zero.items(): - if region_name_zero in test_system_name: - break - assert region_name_zero in test_system_name, test_system_name - - # Find standard alchemical region one. - for region_name_one, region_one in cls.test_region_one.items(): - if region_name_one in test_system_name: - break - assert region_name_one in test_system_name, test_system_name - - # Find standard alchemical region two. - for region_name_two, region_two in cls.test_region_two.items(): - if region_name_two in test_system_name: - break - assert region_name_two in test_system_name, test_system_name - - assert region_name_zero == region_name_one and region_name_one == region_name_two - #We only want two regions for HostGuest or we get too many force groups - if 'HostGuestExplicit' in region_name_one: - test_regions = [region_zero, region_one] - else: - test_regions = [region_zero, region_one, region_two] - - # Find nonbonded method. - force_idx, nonbonded_force = forces.find_forces(test_system.system, openmm.NonbondedForce, only_one=True) - nonbonded_method = nonbonded_force.getNonbondedMethod() - - # Create all combinations of annihilate_sterics/electrostatics. - for annihilate_sterics, annihilate_electrostatics in itertools.product((True, False), repeat=2): - # Create new region that we can modify. - for i, test_region in enumerate(test_regions): - test_regions[i] = test_region._replace(annihilate_sterics=annihilate_sterics, - annihilate_electrostatics=annihilate_electrostatics) - - # Create test name. - test_case_name = test_system_name[:] - if annihilate_sterics: - test_case_name += ', annihilated sterics' - if annihilate_electrostatics: - test_case_name += ', annihilated electrostatics' - - # Annihilate bonds and angles every three test_cases. - if n_test_cases % 3 == 0: - for i, test_region in enumerate(test_regions): - test_regions[i] = test_region._replace(alchemical_bonds=True, alchemical_angles=True, - alchemical_torsions=True) - test_case_name += ', annihilated bonds, angles and torsions' - - # Add different softcore parameters every five test_cases. - if n_test_cases % 5 == 0: - for i, test_region in enumerate(test_regions): - test_regions[i] = test_region._replace(softcore_alpha=1.0, softcore_beta=1.0, softcore_a=1.0, softcore_b=1.0, - softcore_c=1.0, softcore_d=1.0, softcore_e=1.0, softcore_f=1.0) - test_case_name += ', modified softcore parameters' - - #region_interactions = frozenset(itertools.combinations(range(len(test_regions)), 2)) - # Pre-generate alchemical system. - alchemical_system = direct_space_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) - - # Add test case. - cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) - - n_test_cases += 1 - - # If we don't use softcore electrostatics and we annihilate charges - # we can test also exact PME treatment. We don't increase n_test_cases - # purposely to keep track of which tests are added above. - if (test_regions[1].softcore_beta == 0.0 and annihilate_electrostatics and - nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]): - alchemical_system = exact_pme_factory.create_alchemical_system(test_system.system, alchemical_regions = test_regions) - test_case_name += ', exact PME' - cls.test_cases[test_case_name] = (test_system, alchemical_system, test_regions) - - # If the test system uses reaction field replace reaction field - # of the reference system to allow comparisons. - if nonbonded_method == openmm.NonbondedForce.CutoffPeriodic: - forcefactories.replace_reaction_field(test_system.system, return_copy=False, - switch_width=direct_space_factory.switch_width) - - def test_split_force_groups(self): - """Forces having different lambda variables should have a different force group.""" - # Select 1 implicit, 1 explicit, and 1 exact PME explicit test case randomly. - test_cases = self.filter_cases(lambda x: 'Implicit' in x, max_number=1) - test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' in x, max_number=1)) - test_cases.update(self.filter_cases(lambda x: 'Explicit ' in x and 'exact PME' not in x, max_number=1)) - for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): - region_names = [] - for region in alchemical_region: - region_names.append(region.name) - f = partial(check_split_force_groups, alchemical_system, region_names) - f.description = "Testing force splitting among groups of {}".format(test_name) - yield f - - def test_noninteracting_energy_components(self): - """Check all forces annihilated/decoupled when their lambda variables are zero.""" - for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): - f = partial(check_multi_noninteracting_energy_components, test_system.system, alchemical_system, - alchemical_region, test_system.positions) - f.description = "Testing non-interacting energy of {}".format(test_name) - yield f - - @attr('slow') - def test_platforms(self): - """Test interacting and noninteracting energies on all platforms.""" - global GLOBAL_ALCHEMY_PLATFORM - old_global_platform = GLOBAL_ALCHEMY_PLATFORM - - # Do not repeat tests on the platform already tested. - if old_global_platform is None: - default_platform_name = utils.get_fastest_platform().getName() - else: - default_platform_name = old_global_platform.getName() - platforms = [platform for platform in utils.get_available_platforms() - if platform.getName() != default_platform_name] - - # Test interacting and noninteracting energies on all platforms. - for platform in platforms: - GLOBAL_ALCHEMY_PLATFORM = platform - for test_name, (test_system, alchemical_system, alchemical_region) in self.test_cases.items(): - f = partial(compare_system_energies, test_system.system, alchemical_system, - alchemical_region, test_system.positions) - f.description = "Test fully interacting energy of {} on {}".format(test_name, platform.getName()) - yield f - f = partial(check_multi_noninteracting_energy_components, test_system.system, alchemical_system, - alchemical_region, test_system.positions) - f.description = "Test non-interacting energy of {} on {}".format(test_name, platform.getName()) - yield f - - # Restore global platform - GLOBAL_ALCHEMY_PLATFORM = old_global_platform - - @attr('slow') - def test_fully_interacting_energy_components(self): - """Test interacting state energy by force component.""" - # This is a very expensive but very informative test. We can - # run this locally when test_fully_interacting_energies() fails. - test_cases = self.filter_cases(lambda x: 'Explicit' in x) - for test_name, (test_system, alchemical_system, alchemical_region) in test_cases.items(): - f = partial(check_multi_interacting_energy_components, test_system.system, alchemical_system, - alchemical_region, test_system.positions) - f.description = "Testing energy components of %s..." % test_name - yield f class TestDispersionlessAlchemicalFactory(object): """ From 25162ae7987e6934f4c2e636a6746f6a24b14195 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Wed, 25 Sep 2019 16:35:34 +0100 Subject: [PATCH 091/152] Add files via upload --- openmmtools/tests/test_alchemy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 2f38712b9..6007c4c78 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -1351,7 +1351,7 @@ def define_regions(cls): cls.test_regions['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2)) cls.test_regions['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10)) cls.test_regions['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3)) - cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4)) # Modify ions. + cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(3)) # Modify ions. cls.test_regions['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6)) # Only partially modified. cls.test_regions['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22)) cls.test_regions['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156)) From 37f4cf64fa0b9606269b17cb31ea1b3e0e69a449 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Thu, 26 Sep 2019 16:00:55 -0400 Subject: [PATCH 092/152] added ThermodynamicState support for non-zero surface tension --- docs/releasehistory.rst | 5 ++ openmmtools/states.py | 107 ++++++++++++++++++++++++----- openmmtools/tests/test_states.py | 111 ++++++++++++++++++++++++------- 3 files changed, 181 insertions(+), 42 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index f9d429a57..808ffa119 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -1,6 +1,11 @@ Release History *************** +Enhancements +------------ +- Added support for anisotropic and membrane barostats in `ThermodynamicState` + + 0.18.3 - Storage enhancements and bugfixes ========================================== diff --git a/openmmtools/states.py b/openmmtools/states.py index 0456aa55f..4b5b2d904 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -242,6 +242,23 @@ def _box_vectors_volume(box_vectors): return np.linalg.det(box_matrix) * a.unit**3 +def _box_vectors_area(box_vectors): + """Return the xy-area of the box vectors. + + Parameters + ---------- + box_vectors : simtk.unit.Quantity + Vectors defining the box. + + Returns + ------- + + area : simtk.unit.Quantity + The box area in units of length^2. + """ + return box_vectors[0][0] * box_vectors[1][1] + + # ============================================================================= # CUSTOM EXCEPTIONS # ============================================================================= @@ -282,7 +299,7 @@ class ThermodynamicsError(Exception): NO_BAROSTAT, UNSUPPORTED_BAROSTAT, UNSUPPORTED_ANISOTROPIC_BAROSTAT, - UNSUPPORTED_MEMBRANE_BAROSTAT, + SURFACE_TENSION_NOT_SUPPORTED, INCONSISTENT_BAROSTAT, BAROSTATED_NONPERIODIC, INCONSISTENT_INTEGRATOR, @@ -298,8 +315,8 @@ class ThermodynamicsError(Exception): UNSUPPORTED_BAROSTAT: "Found unsupported barostat {} in system.", UNSUPPORTED_ANISOTROPIC_BAROSTAT: "MonteCarloAnisotropicBarostat is only supported if the pressure along all scaled axes is the same.", - UNSUPPORTED_MEMBRANE_BAROSTAT: - "MonteCarloAnisotropicBarostat is only supported if the surface tension is zero.", + SURFACE_TENSION_NOT_SUPPORTED: + "Surface tension can only be set for states that have a system with a MonteCarloBarostat.", NO_BAROSTAT: "System does not have a barostat specifying the pressure.", INCONSISTENT_BAROSTAT: "System barostat is inconsistent with thermodynamic state.", BAROSTATED_NONPERIODIC: "Non-periodic systems cannot have a barostat.", @@ -368,11 +385,19 @@ class ThermodynamicState(object): state. It can be used to create new OpenMM Contexts, or to convert an existing Context to this particular thermodynamic state. - Only NVT and NPT ensembles are supported. The temperature must + NVT, NPT and NPgammaT ensembles are supported. The temperature must be specified in the constructor, either implicitly via a thermostat force in the system, or explicitly through the temperature parameter, which overrides an eventual thermostat indication. + To set a ThermodynamicState up in the NPgammaT ensemble, the system + passed to the constructor has to have a MonteCarloMembraneBarostat. + + To set a ThermodynamicState up with anisotropic pressure control, + the system passed to the constructor has to have a MonteCarloAnisotropicBarostat. + Currently the MonteCarloAnisotropicBarostat is only supported if + the pressure is equal for all axes that are under pressure control. + Parameters ---------- system : simtk.openmm.System @@ -394,6 +419,7 @@ class ThermodynamicState(object): system temperature pressure + surface_tension volume n_particles @@ -756,6 +782,26 @@ def is_periodic(self): """True if the system is in a periodic box (read-only).""" return self._standard_system.usesPeriodicBoundaryConditions() + @property + def surface_tension(self): + """Surface tension; None if the barostat is not a MonteCarloMembraneBarostat""" + barostat = self._find_barostat(self._standard_system) + if isinstance(barostat, openmm.MonteCarloMembraneBarostat): + return barostat.getDefaultSurfaceTension() + else: + return None + + @surface_tension.setter + def surface_tension(self, gamma): + # working around a bug in the unit conversion https://github.com/openmm/openmm/issues/2406 + if isinstance(gamma, unit.Quantity): + gamma = gamma.value_in_unit(unit.bar * unit.nanometer) + barostat = self._find_barostat(self._standard_system) + if isinstance(barostat, openmm.MonteCarloMembraneBarostat): + barostat.setDefaultSurfaceTension(gamma) + else: + raise ThermodynamicsError(ThermodynamicsError.SURFACE_TENSION_NOT_SUPPORTED) + def reduced_potential(self, context_state): """Reduced potential in this thermodynamic state. @@ -772,15 +818,17 @@ def reduced_potential(self, context_state): Notes ----- - The reduced potential is defined as in Ref. [1] + The reduced potential is defined as in Ref. [1], + with a additional term for the surface tension - u = \beta [U(x) + p V(x) + \mu N(x)] + u = \beta [U(x) + p V(x) + \mu N(x) - \gamma A] where the thermodynamic parameters are \beta = 1/(kB T) is the inverse temperature p is the pressure \mu is the chemical potential + \gamma is the surface tension and the configurational properties are @@ -789,6 +837,7 @@ def reduced_potential(self, context_state): V(x) is the instantaneous box volume N(x) the numbers of various particle species (e.g. protons of titratible groups) + A(x) is the xy-area of the box. References ---------- @@ -833,17 +882,18 @@ def reduced_potential(self, context_state): openmm_state = context_state.getState(getEnergy=True) potential_energy = openmm_state.getPotentialEnergy() volume = openmm_state.getPeriodicBoxVolume() + area = _box_vectors_area(openmm_state.getPeriodicBoxVectors()) else: n_particles = context_state.n_particles potential_energy = context_state.potential_energy volume = context_state.volume + area = context_state.area # Check compatibility. if n_particles != self.n_particles: raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_SAMPLER_STATE) - return self._compute_reduced_potential(potential_energy, self.temperature, - volume, self.pressure) + volume, self.pressure, area, self.surface_tension) @classmethod def reduced_potential_at_states(cls, context, thermodynamic_states): @@ -1147,7 +1197,7 @@ def apply_to_context(self, context): 310.0 """ - self._set_context_barostat(context, update_pressure=True, update_temperature=True) + self._set_context_barostat(context, update_pressure=True, update_temperature=True, update_surface_tension=True) self._set_context_thermostat(context) # ------------------------------------------------------------------------- @@ -1416,7 +1466,7 @@ def _update_standard_system(self, standard_system): # Internal-usage: context handling # ------------------------------------------------------------------------- - def _set_context_barostat(self, context, update_pressure, update_temperature): + def _set_context_barostat(self, context, update_pressure, update_temperature, update_surface_tension): """Set the barostat parameters in the Context.""" barostat = self._find_barostat(context.getSystem()) @@ -1432,6 +1482,9 @@ def _set_context_barostat(self, context, update_pressure, update_temperature): if update_pressure: self._set_barostat_pressure(barostat, self.pressure) self._set_barostat_pressure_in_context(barostat, self.pressure, context) + if self.surface_tension is not None and update_surface_tension: + self._set_barostat_surface_tension_in_context(barostat, self.surface_tension, context) + if update_temperature: self._set_barostat_temperature(barostat, self.temperature) # TODO remove try except when drop openmm7.0 support @@ -1470,9 +1523,10 @@ def _apply_to_context_in_state(self, context, thermodynamic_state): """ update_pressure = self.pressure != thermodynamic_state.pressure update_temperature = self.temperature != thermodynamic_state.temperature + update_surface_tension = self.surface_tension != thermodynamic_state.surface_tension if update_pressure or update_temperature: - self._set_context_barostat(context, update_pressure, update_temperature) + self._set_context_barostat(context, update_pressure, update_temperature, update_surface_tension) if update_temperature: self._set_context_thermostat(context) @@ -1588,13 +1642,13 @@ def _find_barostat(cls, system, get_index=False): scaled = [barostat.getScaleX(), barostat.getScaleY(), barostat.getScaleY()] if sum(scaled) == 0: raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT) - active_pressures = [pressure for pressure, active in zip(pressures, scaled)] + active_pressures = [pressure for pressure, active in zip(pressures, scaled) if active] if any(abs(pressure - active_pressures[0]) > 0 for pressure in active_pressures): raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT) - elif isinstance(barostat, openmm.MonteCarloMembraneBarostat): - surface_tension = barostat.getDefaultSurfaceTension() - if abs(surface_tension.value_in_unit(unit.bar*unit.nanometer)) > 0: - raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_MEMBRANE_BAROSTAT) + #elif isinstance(barostat, openmm.MonteCarloMembraneBarostat): + # surface_tension = barostat.getDefaultSurfaceTension() + # if abs(surface_tension.value_in_unit(unit.bar*unit.nanometer)) > 0: + # raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_MEMBRANE_BAROSTAT) if get_index: return force_idx, barostat return barostat @@ -1698,6 +1752,18 @@ def _set_barostat_temperature(barostat, temperature): """Set barostat temperature.""" barostat.setDefaultTemperature(temperature) + @staticmethod + def _set_barostat_surface_tension_in_context(barostat, surface_tension, context): + """Set barostat surface tension.""" + # work around a unit conversion issue in openmm + if isinstance(surface_tension, unit.Quantity): + surface_tension = surface_tension.value_in_unit(unit.nanometer*unit.bar) + try: + context.getParameter(barostat.SurfaceTension()) + except Exception as e: + raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) + context.setParameter(barostat.SurfaceTension(), surface_tension) + # ------------------------------------------------------------------------- # Internal-usage: thermostat handling # ------------------------------------------------------------------------- @@ -1762,12 +1828,14 @@ def _set_system_temperature(cls, system, temperature): # ------------------------------------------------------------------------- @staticmethod - def _compute_reduced_potential(potential_energy, temperature, volume, pressure): + def _compute_reduced_potential(potential_energy, temperature, volume, pressure, area=None, surface_tension=None): """Convert potential energy into reduced potential.""" beta = 1.0 / (unit.BOLTZMANN_CONSTANT_kB * temperature) reduced_potential = potential_energy / unit.AVOGADRO_CONSTANT_NA if pressure is not None: reduced_potential += pressure * volume + if area is not None and surface_tension is not None: + reduced_potential -= surface_tension * area return beta * reduced_potential def _find_force_groups_to_update(self, context, thermodynamic_state, memo): @@ -2032,6 +2100,11 @@ def volume(self): """The volume of the box (read-only)""" return _box_vectors_volume(self.box_vectors) + @property + def area(self): + """The xy-area of the box (read-only)""" + return _box_vectors_area(self.box_vectors) + @property def n_particles(self): """Number of particles (read-only).""" diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index 18ba4d02c..f78a18d68 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -59,6 +59,7 @@ def setup_class(cls): """Create the test systems used in the test suite.""" cls.std_pressure = ThermodynamicState._STANDARD_PRESSURE cls.std_temperature = ThermodynamicState._STANDARD_TEMPERATURE + cls.std_surface_tension = 100.0 * unit.bar * unit.nanometer alanine_explicit = testsystems.AlanineDipeptideExplicit() cls.alanine_positions = alanine_explicit.positions @@ -102,12 +103,13 @@ def setup_class(cls): cls.unsupported_anisotropic_barostat_alanine.addForce(cls.unsupported_anisotropic_barostat) # A system with an unsupported MonteCarloMembraneBarostat - cls.unsupported_membrane_barostat_alanine = copy.deepcopy(cls.alanine_explicit) - cls.unsupported_membrane_barostat = openmm.MonteCarloMembraneBarostat( - cls.std_pressure, 1.0 * unit.bar * unit.nanometer, cls.std_temperature, + cls.membrane_barostat_alanine_gamma_nonzero = copy.deepcopy(cls.alanine_explicit) + # working around a bug in the unit conversion https://github.com/openmm/openmm/issues/2406 + cls.membrane_barostat_gamma_nonzero = openmm.MonteCarloMembraneBarostat( + cls.std_pressure, cls.std_surface_tension.value_in_unit(unit.bar*unit.nanometer), cls.std_temperature, openmm.MonteCarloMembraneBarostat.XYIsotropic, openmm.MonteCarloMembraneBarostat.ZFree ) - cls.unsupported_membrane_barostat_alanine.addForce(cls.unsupported_membrane_barostat) + cls.membrane_barostat_alanine_gamma_nonzero.addForce(cls.membrane_barostat_gamma_nonzero) # A system with a supported MonteCarloAnisotropicBarostat cls.supported_anisotropic_barostat_alanine = copy.deepcopy(cls.alanine_explicit) @@ -118,12 +120,12 @@ def setup_class(cls): cls.supported_anisotropic_barostat_alanine.addForce(cls.supported_anisotropic_barostat) # A system with a supported MonteCarloMembraneBarostat - cls.supported_membrane_barostat_alanine = copy.deepcopy(cls.alanine_explicit) - cls.supported_membrane_barostat = openmm.MonteCarloMembraneBarostat( - cls.std_pressure, 0.0 * unit.bar * unit.nanometer, cls.std_temperature, + cls.membrane_barostat_alanine_gamma_zero = copy.deepcopy(cls.alanine_explicit) + cls.membrane_barostat_gamma_zero = openmm.MonteCarloMembraneBarostat( + cls.std_pressure, 0.0, cls.std_temperature, openmm.MonteCarloMembraneBarostat.XYIsotropic, openmm.MonteCarloMembraneBarostat.ZFree ) - cls.supported_membrane_barostat_alanine.addForce(cls.supported_membrane_barostat) + cls.membrane_barostat_alanine_gamma_zero.addForce(cls.membrane_barostat_gamma_zero) # A system with an inconsistent pressure in the barostat. cls.inconsistent_pressure_alanine = copy.deepcopy(cls.alanine_explicit) @@ -192,14 +194,13 @@ def test_method_find_barostat(self): barostat = ThermodynamicState._find_barostat(self.supported_anisotropic_barostat_alanine) assert isinstance(barostat, openmm.MonteCarloAnisotropicBarostat) - barostat = ThermodynamicState._find_barostat(self.supported_membrane_barostat_alanine) + barostat = ThermodynamicState._find_barostat(self.membrane_barostat_alanine_gamma_zero) assert isinstance(barostat, openmm.MonteCarloMembraneBarostat) # Raise exception if multiple or unsupported barostats found TE = ThermodynamicsError # shortcut test_cases = [(self.multiple_barostat_alanine, TE.MULTIPLE_BAROSTATS), - (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT), - (self.unsupported_membrane_barostat_alanine, TE.UNSUPPORTED_MEMBRANE_BAROSTAT)] + (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT)] for system, err_code in test_cases: with nose.tools.assert_raises(ThermodynamicsError) as cm: ThermodynamicState._find_barostat(system) @@ -236,7 +237,7 @@ def test_method_is_barostat_consistent(self): assert not state._is_barostat_consistent(barostat) assert not state._is_barostat_consistent(self.supported_anisotropic_barostat) - assert not state._is_barostat_consistent(self.supported_membrane_barostat) + assert not state._is_barostat_consistent(self.membrane_barostat_gamma_zero) def test_method_set_system_temperature(self): """ThermodynamicState._set_system_temperature() method.""" @@ -257,7 +258,7 @@ def test_property_temperature(self): """ThermodynamicState.temperature property.""" for system in [self.barostated_alanine, self.supported_anisotropic_barostat_alanine, - self.supported_membrane_barostat_alanine]: + self.membrane_barostat_alanine_gamma_zero]: state = ThermodynamicState(system, self.std_temperature) assert state.temperature == self.std_temperature @@ -276,7 +277,7 @@ def test_method_set_system_pressure(self): """ThermodynamicState._set_system_pressure() method.""" for system in [self.barostated_alanine, self.supported_anisotropic_barostat_alanine, - self.supported_membrane_barostat_alanine]: + self.membrane_barostat_alanine_gamma_zero]: state = ThermodynamicState(self.alanine_explicit, self.std_temperature) system = state.system assert state._find_barostat(system) is None @@ -309,7 +310,7 @@ def test_property_pressure_barostat(self): # Correctly reads and set system pressures periodic_testcases = [self.alanine_explicit, self.supported_anisotropic_barostat_alanine, - self.supported_membrane_barostat_alanine] + self.membrane_barostat_alanine_gamma_zero] for system in periodic_testcases: if system is self.alanine_explicit: state = ThermodynamicState(system, self.std_temperature) @@ -369,19 +370,42 @@ def test_property_pressure_barostat(self): state.barostat = self.supported_anisotropic_barostat assert cm.exception.code == ThermodynamicsError.INCONSISTENT_BAROSTAT - # Assign incompatible barostat raise error - with nose.tools.assert_raises(ThermodynamicsError) as cm: - state.barostat = self.unsupported_membrane_barostat - assert cm.exception.code == ThermodynamicsError.UNSUPPORTED_MEMBRANE_BAROSTAT - # Assign non-standard barostat raise error with nose.tools.assert_raises(ThermodynamicsError) as cm: - state.barostat = self.supported_membrane_barostat + state.barostat = self.membrane_barostat_gamma_zero assert cm.exception.code == ThermodynamicsError.INCONSISTENT_BAROSTAT # After exception, state is left consistent assert state.pressure is None + def test_surface_tension(self): + """Test querying and setting surface tension""" + # test setting and getting surface tension for a system without barostat + state = ThermodynamicState(self.alanine_explicit, self.std_temperature) + assert state.surface_tension is None + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state.surface_tension = self.std_surface_tension + assert cm.exception.code == ThermodynamicsError.SURFACE_TENSION_NOT_SUPPORTED + + # test setting and getting surface tension for a system with a non-membrane barostat + state = ThermodynamicState(self.barostated_alanine, self.std_temperature) + assert state.surface_tension is None + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state.surface_tension = self.std_surface_tension + assert cm.exception.code == ThermodynamicsError.SURFACE_TENSION_NOT_SUPPORTED + + # test setting and getting surface tension + state = ThermodynamicState(self.membrane_barostat_alanine_gamma_zero, self.std_temperature) + assert utils.is_quantity_close(state.surface_tension, 0.0 * unit.bar * unit.nanometer) + state.surface_tension = self.std_surface_tension + assert utils.is_quantity_close(state.surface_tension, self.std_surface_tension) + state.surface_tension = 0.0 * unit.bar * unit.nanometer + assert utils.is_quantity_close(state.surface_tension, 0.0 * unit.bar * unit.nanometer) + + # test initial surface tension of nonzero-gamma barostat + state = ThermodynamicState(self.membrane_barostat_alanine_gamma_nonzero, self.std_temperature) + assert utils.is_quantity_close(state.surface_tension, self.std_surface_tension) + def test_property_volume(self): """Check that volume is computed correctly.""" # For volume-fluctuating systems volume is None. @@ -413,9 +437,8 @@ def test_property_system(self): (self.barostated_toluene, TE.BAROSTATED_NONPERIODIC), (self.multiple_barostat_alanine, TE.MULTIPLE_BAROSTATS), (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT), - (self.unsupported_membrane_barostat_alanine, TE.UNSUPPORTED_MEMBRANE_BAROSTAT), (self.supported_anisotropic_barostat_alanine, TE.INCONSISTENT_BAROSTAT), - (self.supported_membrane_barostat_alanine, TE.INCONSISTENT_BAROSTAT), + (self.membrane_barostat_alanine_gamma_zero, TE.INCONSISTENT_BAROSTAT), (self.inconsistent_pressure_alanine, TE.INCONSISTENT_BAROSTAT), (self.inconsistent_temperature_alanine, TE.INCONSISTENT_THERMOSTAT), (inconsistent_barostat_temperature, TE.INCONSISTENT_BAROSTAT)] @@ -483,8 +506,8 @@ def test_constructor_unsupported_barostat(self): TE = ThermodynamicsError # shortcut test_cases = [(self.barostated_toluene, TE.BAROSTATED_NONPERIODIC), (self.multiple_barostat_alanine, TE.MULTIPLE_BAROSTATS), - (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT), - (self.unsupported_membrane_barostat_alanine, TE.UNSUPPORTED_MEMBRANE_BAROSTAT)] + (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT) + ] for i, (system, err_code) in enumerate(test_cases): with nose.tools.assert_raises(TE) as cm: ThermodynamicState(system=system, temperature=self.std_temperature) @@ -743,9 +766,26 @@ def test_method_apply_to_context(self): state2.apply_to_context(context) assert cm.exception.code == ThermodynamicsError.INCOMPATIBLE_ENSEMBLE + state3 = ThermodynamicState(self.membrane_barostat_alanine_gamma_zero, self.std_temperature) + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state3.apply_to_context(context) + assert cm.exception.code == ThermodynamicsError.INCOMPATIBLE_ENSEMBLE + + # apply surface tension + gamma_context = openmm.Context(self.membrane_barostat_alanine_gamma_zero, openmm.VerletIntegrator(0.001)) + state3.apply_to_context(gamma_context) + assert gamma_context.getParameter(self.membrane_barostat_gamma_nonzero.SurfaceTension()) == 0.0 + state3.surface_tension = self.std_surface_tension + state3.apply_to_context(gamma_context) + assert (gamma_context.getParameter(self.membrane_barostat_gamma_nonzero.SurfaceTension()) + == self.std_surface_tension.value_in_unit(unit.nanometer*unit.bar)) + state3.surface_tension = 0.0 * unit.nanometer * unit.bar + + # Clean up contexts. del context, langevin_integrator del thermostated_context, verlet_integrator + del gamma_context verlet_integrator = openmm.VerletIntegrator(time_step) nvt_context = create_default_context(state2, verlet_integrator) @@ -754,6 +794,9 @@ def test_method_apply_to_context(self): assert cm.exception.code == ThermodynamicsError.INCOMPATIBLE_ENSEMBLE del nvt_context, verlet_integrator + + + def test_method_reduced_potential(self): """ThermodynamicState.reduced_potential() method.""" kj_mol = unit.kilojoule_per_mole @@ -785,6 +828,23 @@ def test_method_reduced_potential(self): state.reduced_potential(incompatible_sampler_state) assert cm.exception.code == ThermodynamicsError.INCOMPATIBLE_SAMPLER_STATE + # Compute constant surface tension reduced potential. + state = ThermodynamicState(self.membrane_barostat_alanine_gamma_nonzero, self.std_temperature) + integrator = openmm.VerletIntegrator(1.0 * unit.femtosecond) + context = create_default_context(state, integrator) + context.setPositions(self.alanine_positions) + sampler_state = SamplerState.from_context(context) + state.pressure = self.std_pressure + reduced_potential = state.reduced_potential(sampler_state) + pressure_volume_work = (self.std_pressure * sampler_state.volume * + unit.AVOGADRO_CONSTANT_NA) + surface_work = (self.std_surface_tension * sampler_state.area * + unit.AVOGADRO_CONSTANT_NA) + potential_energy = (reduced_potential / beta - pressure_volume_work + surface_work) / kj_mol + + assert np.isclose(sampler_state.potential_energy / kj_mol, potential_energy) + assert np.isclose(reduced_potential, state.reduced_potential(context)) + def test_method_reduced_potential_at_states(self): """ThermodynamicState.reduced_potential_at_states() method. @@ -1036,6 +1096,7 @@ def test_operator_getitem(self): # The other attributes are copied correctly. assert sliced_sampler_state.volume == sampler_state.volume + assert sliced_sampler_state.area == sampler_state.area # Energies are undefined for as subset of atoms. assert sliced_sampler_state.kinetic_energy is None From e75f21286082be53f66125c687c4824216b16381 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Thu, 26 Sep 2019 16:04:52 -0400 Subject: [PATCH 093/152] removed old comment --- openmmtools/states.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/openmmtools/states.py b/openmmtools/states.py index 4b5b2d904..40ce870ce 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -1645,10 +1645,6 @@ def _find_barostat(cls, system, get_index=False): active_pressures = [pressure for pressure, active in zip(pressures, scaled) if active] if any(abs(pressure - active_pressures[0]) > 0 for pressure in active_pressures): raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT) - #elif isinstance(barostat, openmm.MonteCarloMembraneBarostat): - # surface_tension = barostat.getDefaultSurfaceTension() - # if abs(surface_tension.value_in_unit(unit.bar*unit.nanometer)) > 0: - # raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_MEMBRANE_BAROSTAT) if get_index: return force_idx, barostat return barostat From a6f1f386aabd39ddea7082755893f7d439e5b046 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Fri, 27 Sep 2019 10:43:15 -0400 Subject: [PATCH 094/152] enable platform properties in ThermodynamicState.create_context --- openmmtools/states.py | 13 +++++++++++-- openmmtools/tests/test_states.py | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/openmmtools/states.py b/openmmtools/states.py index 40ce870ce..3933b9d52 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -1074,7 +1074,7 @@ def is_context_compatible(self, context): is_compatible = self._standard_system_hash == context_system_hash return is_compatible - def create_context(self, integrator, platform=None): + def create_context(self, integrator, platform=None, platform_properties=None): """Create a context in this ThermodynamicState. The context contains a copy of the system. If the integrator @@ -1098,6 +1098,9 @@ def create_context(self, integrator, platform=None): platform : simtk.openmm.Platform, optional Platform to use. If None, OpenMM tries to select the fastest available platform. Default is None. + platform_properties : dict, optional + A dictionary of platform properties. Requires platform to be + specified. Returns ------- @@ -1109,6 +1112,8 @@ def create_context(self, integrator, platform=None): ThermodynamicsError If the integrator has a temperature different from this ThermodynamicState. + ValueError + If platform_properties is specified, but platform is None Examples -------- @@ -1149,9 +1154,13 @@ def create_context(self, integrator, platform=None): # Create context. if platform is None: + if platform_properties is not None: + raise ValueError("To set platform_properties, you need to also specify the platform.") return openmm.Context(system, integrator) - else: + elif platform_properties is None: return openmm.Context(system, integrator, platform) + else: + return openmm.Context(system, integrator, platform, platform_properties) def apply_to_context(self, context): """Apply this ThermodynamicState to the context. diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index f78a18d68..1c1dd91c1 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -669,6 +669,27 @@ def test_method_create_context(self): # Get rid of old context. This test can create a lot of them. del context, integrator + # test platform properties + state = ThermodynamicState(self.toluene_vacuum, self.std_temperature) + platform_properties = {"CpuThreads": "2"} + with nose.tools.assert_raises(ValueError) as cm: + state.create_context( + openmm.VerletIntegrator(0.001), + platform=None, + platform_properties=platform_properties + ) + assert str(cm.exception) == "To set platform_properties, you need to also specify the platform." + + platform = openmm.Platform.getPlatformByName("CPU") + context = state.create_context( + openmm.VerletIntegrator(0.001), + platform=platform, + platform_properties=platform_properties + ) + assert context.getPlatform().getPropertyValue(context, "CpuThreads") == "2" + del context + + def test_method_is_compatible(self): """ThermodynamicState context and state compatibility methods.""" From b6a60d6e6a21f681e7243686e5c6ba7a5fd33c06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Fri, 27 Sep 2019 11:01:17 -0400 Subject: [PATCH 095/152] enable platform properties in ContextCache --- docs/releasehistory.rst | 2 +- openmmtools/cache.py | 10 ++++++++-- openmmtools/tests/test_cache.py | 19 +++++++++++++++++++ 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 808ffa119..3aa6a6ba2 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -4,7 +4,7 @@ Release History Enhancements ------------ - Added support for anisotropic and membrane barostats in `ThermodynamicState` - +- Added support for platform properties in ContextCache (e.g. for mixed and double precision CUDA in multistate sampler) 0.18.3 - Storage enhancements and bugfixes ========================================== diff --git a/openmmtools/cache.py b/openmmtools/cache.py index 3bd0ffe94..12ab7449b 100644 --- a/openmmtools/cache.py +++ b/openmmtools/cache.py @@ -229,6 +229,9 @@ class ContextCache(object): platform : simtk.openmm.Platform, optional The OpenMM platform to use to create Contexts. If None, OpenMM tries to select the fastest one available (default is None). + platform_properties : dict, optional + A dictionary of platform properties for the OpenMM platform. + Only valid if the platform is not None (default is None). **kwargs Parameters to pass to the underlying LRUCache constructor such as capacity and time_to_live. @@ -303,8 +306,11 @@ class ContextCache(object): """ - def __init__(self, platform=None, **kwargs): + def __init__(self, platform=None, platform_properties=None, **kwargs): self._platform = platform + self._platform_properties = platform_properties + if platform_properties is not None and platform is None: + raise ValueError("To set platform_properties, you need to also specify the platform.") self._lru = LRUCache(**kwargs) def __len__(self): @@ -429,7 +435,7 @@ def get_context(self, thermodynamic_state, integrator=None): try: context = self._lru[context_id] except KeyError: - context = thermodynamic_state.create_context(integrator, self._platform) + context = thermodynamic_state.create_context(integrator, self._platform, self._platform_properties) self._lru[context_id] = context context_integrator = context.getIntegrator() diff --git a/openmmtools/tests/test_cache.py b/openmmtools/tests/test_cache.py index bc74fa2f8..eeeeca4e0 100644 --- a/openmmtools/tests/test_cache.py +++ b/openmmtools/tests/test_cache.py @@ -357,3 +357,22 @@ def test_platform_property(self): cache.get_context(self.compatible_states[0], integrator) with nose.tools.assert_raises(RuntimeError): cache.platform = platforms[0] + + def test_platform_properties(self): + platform_properties = {"CpuThreads": "2"} + with nose.tools.assert_raises(ValueError) as cm: + ContextCache(platform=None, platform_properties=platform_properties) + assert str(cm.exception) == "To set platform_properties, you need to also specify the platform." + + platform = openmm.Platform.getPlatformByName("CPU") + cache = ContextCache( + platform=platform, + platform_properties=platform_properties + ) + + thermodynamic_state = copy.deepcopy(self.water_300k) + integrator = integrators.LangevinIntegrator(temperature=300 * unit.kelvin, measure_heat=True, + measure_shadow_work=True) + context, _ = cache.get_context(thermodynamic_state, integrator) + assert context.getPlatform().getPropertyValue(context, "CpuThreads") == "2" + del context From 03158ef0af6b971bf30ea4d0c18a66c670721113 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Fri, 27 Sep 2019 18:07:46 -0400 Subject: [PATCH 096/152] added platform properties to ContextCache serialization --- openmmtools/cache.py | 6 +++++- openmmtools/tests/test_cache.py | 13 ++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/openmmtools/cache.py b/openmmtools/cache.py index 12ab7449b..62f1f86c7 100644 --- a/openmmtools/cache.py +++ b/openmmtools/cache.py @@ -453,13 +453,17 @@ def __getstate__(self): else: platform_serialization = None return dict(platform=platform_serialization, capacity=self.capacity, - time_to_live=self.time_to_live) + time_to_live=self.time_to_live, platform_properties=self._platform_properties) def __setstate__(self, serialization): if serialization['platform'] is None: self._platform = None else: self._platform = openmm.Platform.getPlatformByName(serialization['platform']) + if not 'platform_properties' in serialization: + self._platform_properties = None + else: + self._platform_properties = serialization["platform_properties"] self._lru = LRUCache(serialization['capacity'], serialization['time_to_live']) # ------------------------------------------------------------------------- diff --git a/openmmtools/tests/test_cache.py b/openmmtools/tests/test_cache.py index eeeeca4e0..1d62248eb 100644 --- a/openmmtools/tests/test_cache.py +++ b/openmmtools/tests/test_cache.py @@ -359,20 +359,31 @@ def test_platform_property(self): cache.platform = platforms[0] def test_platform_properties(self): + # Failure test platform_properties = {"CpuThreads": "2"} with nose.tools.assert_raises(ValueError) as cm: ContextCache(platform=None, platform_properties=platform_properties) assert str(cm.exception) == "To set platform_properties, you need to also specify the platform." + # test platform = openmm.Platform.getPlatformByName("CPU") cache = ContextCache( platform=platform, platform_properties=platform_properties ) - thermodynamic_state = copy.deepcopy(self.water_300k) integrator = integrators.LangevinIntegrator(temperature=300 * unit.kelvin, measure_heat=True, measure_shadow_work=True) context, _ = cache.get_context(thermodynamic_state, integrator) assert context.getPlatform().getPropertyValue(context, "CpuThreads") == "2" + + # test serialization + cache.__setstate__(cache.__getstate__()) + assert cache._platform_properties == {"CpuThreads": "2"} + + # test serialization no 2 + state = cache.__getstate__() + state["platform_properties"] = {"CpuThreads": "3"} + cache.__setstate__(state) + assert cache._platform_properties == {"CpuThreads": "3"} del context From b7a9e7e599b9141dfba0e7ebe39299ebee51b3a3 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Mon, 14 Oct 2019 16:19:30 +0200 Subject: [PATCH 097/152] Avoid modifying reference nonbonded force and more docs --- openmmtools/alchemy.py | 124 +++++++++++++++++++++++++---------------- 1 file changed, 76 insertions(+), 48 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 801384c34..e91342a26 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -652,7 +652,7 @@ def create_alchemical_system(self, reference_system, alchemical_regions, """ if alchemical_regions_interactions != frozenset(): - raise NotImplemented('Interactions between alchemcial regions is untested') + raise NotImplementedError('Interactions between alchemical regions is untested') logger.debug(f'Dictionary of interacting alchemical regions: {alchemical_regions_interactions}') if isinstance(alchemical_regions, AlchemicalRegion): @@ -694,14 +694,14 @@ def create_alchemical_system(self, reference_system, alchemical_regions, # constraints, box vectors and all the forces. We'll later remove # the forces that we remodel to be alchemically modified. alchemical_system = copy.deepcopy(reference_system) - + # Check that there are no virtual sites to alchemically modify. for alchemical_region in alchemical_regions: for particle_index in alchemical_region.alchemical_atoms: if reference_system.isVirtualSite(particle_index): raise ValueError(f'Virtual atoms in region {alchemical_region.name}. ' 'Alchemically modified virtual sites are not supported') - + # Modify forces as appropriate. We delete the forces that # have been processed modified at the end of the for loop. forces_to_remove = [] @@ -1076,13 +1076,13 @@ def _add_alchemical_forces(self, alchemical_system, alchemical_forces_by_lambda) alchemical_system.addForce(force) @staticmethod - def _is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): - """Test if a set of particles are in two regions simultaneously and if these regions are interacting + def _are_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + """Test if a set of particles are in two regions simultaneously and if these regions are interacting. Parameters ---------- - particles: set() - Set of particles to test check if they in two regions + particles: set + Set of particles to check if they are in two noninteracting alchemical regions. alchemical_region : AlchemicalRegion The alchemical region containing the indices of the torsions to test. alchemical_regions_interactions : Set[Tuple[int, int]], optional @@ -1104,8 +1104,8 @@ def _is_straddling_noninteracting_regions(particles, alchemical_regions, alchemi j += 1 return False - @staticmethod - def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_regions, alchemical_regions_interactions): + @classmethod + def _alchemically_modify_PeriodicTorsionForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of PeriodicTorsionForce. Parameters @@ -1146,11 +1146,13 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters( torsion_index) particles = set((particle1, particle2, particle3, particle4)) - if torsion_index not in all_alchemical_torsions: - if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): - pass - else: - force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) + + # We don't connect through a torsion two particles that belong + # to two different and noninteracting alchemical regions. + are_straddling = cls._are_straddling_noninteracting_regions( + particles, alchemical_regions, alchemical_regions_interactions) + if (torsion_index not in all_alchemical_torsions) and (not are_straddling): + force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -1186,8 +1188,8 @@ def _alchemically_modify_PeriodicTorsionForce(reference_force, alchemical_region return alchemical_forces - @staticmethod - def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, alchemical_regions_interactions): + @classmethod + def _alchemically_modify_HarmonicAngleForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of HarmonicAngleForce Parameters @@ -1226,11 +1228,13 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, for angle_index in range(reference_force.getNumAngles()): [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) particles = set((particle1, particle2, particle3)) - if angle_index not in all_alchemical_angles: - if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): - pass - else: - force.addAngle(particle1, particle2, particle3, theta0, K) + + # We don't connect through an angle two particles that belong + # to two different and noninteracting alchemical regions. + are_straddling = cls._are_straddling_noninteracting_regions( + particles, alchemical_regions, alchemical_regions_interactions) + if (angle_index not in all_alchemical_angles) and (not are_straddling): + force.addAngle(particle1, particle2, particle3, theta0, K) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -1263,8 +1267,8 @@ def _alchemically_modify_HarmonicAngleForce(reference_force, alchemical_regions, return alchemical_forces - @staticmethod - def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, alchemical_regions_interactions): + @classmethod + def _alchemically_modify_HarmonicBondForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): """Create alchemically-modified version of HarmonicBondForce Parameters @@ -1304,11 +1308,13 @@ def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, for bond_index in range(reference_force.getNumBonds()): [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) particles = set((particle1, particle2)) - if bond_index not in all_alchemical_bonds: - if AbsoluteAlchemicalFactory._is_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): - pass - else: - force.addBond(particle1, particle2, theta0, K) + + # We don't connect through a bond two particles that belong + # to two different and noninteracting alchemical regions. + are_straddling = cls._are_straddling_noninteracting_regions( + particles, alchemical_regions, alchemical_regions_interactions) + if (bond_index not in all_alchemical_bonds) and (not are_straddling): + force.addBond(particle1, particle2, theta0, K) # Update the returned value with the non-alchemical force. alchemical_forces[''] = [force] @@ -1341,6 +1347,18 @@ def _alchemically_modify_HarmonicBondForce(reference_force, alchemical_regions, return alchemical_forces def _get_sterics_energy_expressions(self, lambda_variable_suffixes): + """Return the energy expressions for sterics. + + Parameters + ---------- + lambda_variable_suffixes : List[str] + A list with suffixes for the global variable "lambda_sterics" that + will control the energy. If no suffix is necessary (i.e. there are + no multiple alchemical regions) just set lambda_variable_suffixes[0] = ''. + If the list has more than one element, the energy is controlled by + the multiplication of lambda_sterics_suffix1 * lambda_sterics_suffix2. + """ + # Sterics mixing rules. if lambda_variable_suffixes[0] == '': lambda_variable_name = 'lambda_sterics' @@ -1371,6 +1389,15 @@ def _get_electrostatics_energy_expressions(self, reference_force, lambda_variabl as there's no electrostatics CustomNondondedForce in this case, and lambda_electrostatics is modeled through an offset parameter in a NonbondedForce. + + Parameters + ---------- + lambda_variable_suffixes : List[str] + A list with suffixes for the global variable "lambda_electrostatics" that + will control the energy. If no suffix is necessary (i.e. there are + no multiple alchemical regions) just set lambda_variable_suffixes[0] = ''. + If the list has more than one element, the energy is controlled by + the multiplication of lambda_electrostatics_suffix1 * lambda_electrostatics_suffix2. """ if lambda_variable_suffixes[0] == '': lambda_variable_name = 'lambda_electrostatics' @@ -1391,7 +1418,7 @@ def _get_electrostatics_energy_expressions(self, reference_force, lambda_variabl # Define mixing rules. electrostatics_mixing_rules = ('chargeprod = charge1*charge2;' # Mixing rule for charges. - 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. + 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. # Standard Coulomb expression with softened core. This is used # - When the nonbonded method of the reference force is NoCutoff. @@ -1564,6 +1591,10 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region if len(all_alchemical_atoms) == 0: return {'': [copy.deepcopy(reference_force)]} + # Create a set of all the non-alchemical atoms only. + all_atomset = set(range(reference_force.getNumParticles())) + nonalchemical_atomset = all_atomset.difference(all_alchemical_atoms) + # ------------------------------------------------------------- # Perform tasks that do not need to be repeated for all regions. # ------------------------------------------------------------- @@ -1593,6 +1624,10 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): raise ValueError('Softcore electrostatics is' + err_msg) + # Create a copy of the NonbondedForce to handle particle interactions and + # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). + nonbonded_force = copy.deepcopy(reference_force) + # Fix any issues in reference force with Lennard-Jones sigma = 0 (epsilon = 0), # which should have sigma > 0. for particle_index in range(reference_force.getNumParticles()): @@ -1604,7 +1639,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region logger.warning(warning_msg % (particle_index, str(charge), str(sigma), str(epsilon))) sigma = 1.0 * unit.angstrom # Fix it. - reference_force.setParticleParameters(particle_index, charge, sigma, epsilon) + nonbonded_force.setParticleParameters(particle_index, charge, sigma, epsilon) # Same for the exceptions. for exception_index in range(reference_force.getNumExceptions()): @@ -1616,11 +1651,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region logger.warning(warning_msg % (exception_index, iatom, jatom, str(chargeprod), str(sigma), str(epsilon))) sigma = 1.0 * unit.angstrom # Fix it. - reference_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) - - # Create a copy of the NonbondedForce to handle particle interactions and - # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). - nonbonded_force = copy.deepcopy(reference_force) + nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) if use_exact_pme_treatment: # Exclude noninteracting alchemical regions from seeing each other in the nonbonded @@ -1643,7 +1674,7 @@ def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_region # Make of list of all single and double permutations of alchemical regions. single_regions = [[alchemical_region] for alchemical_region in alchemical_regions] - if alchemical_regions_interactions == set(): + if len(alchemical_regions_interactions) == 0: pair_regions = [] else: # Only generate pairs of alchemical regions specified by alchemical_regions_interactions. @@ -1846,16 +1877,13 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ else: alchemical_atomset_0 = alchemical_regions_pairs[0].alchemical_atoms - all_atomset = set(range(reference_force.getNumParticles())) # all atoms, including alchemical region - nonalchemical_atomset = all_atomset.difference(all_alchemical_atoms) - # Copy NonbondedForce particle terms for alchemically-modified particles # to CustomNonbondedForces, and/or add the charge offsets for exact PME. # On CUDA, for efficiency reasons, all nonbonded forces (custom and not) # must have the same particles. for particle_index in range(nonbonded_force.getNumParticles()): # Retrieve nonbonded parameters. - [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) + [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) # Set sterics parameters in CustomNonbondedForces. for force in all_sterics_custom_nonbonded_forces: force.addParticle([sigma, epsilon]) @@ -1871,7 +1899,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ # NonbondedForce that will be handled by all other forces for particle_index in range(nonbonded_force.getNumParticles()): # Retrieve parameters. - [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) + [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) # Even with exact treatment of the PME electrostatics, we turn off # the NonbondedForce charge which is modeled by the offset parameter. if particle_index in alchemical_atomset_0: @@ -1913,7 +1941,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ if len(lambda_var_suffixes) > 1: for exception_index in range(nonbonded_force.getNumExceptions()): # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) + [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces # must have the same number of exceptions/exclusions on CUDA platform. @@ -2025,7 +2053,7 @@ def add_global_parameters(force): def _alchemically_modify_AmoebaMultipoleForce(self, reference_force, alchemical_region, _): if len(alchemical_region) > 1: - raise NotImplemented("Multiple regions does not work with AmoebaMultipoleForce") + raise NotImplementedError("Multiple regions does not work with AmoebaMultipoleForce") else: alchemical_region = alchemical_region[0] raise Exception("Not implemented; needs CustomMultipleForce") @@ -2043,10 +2071,10 @@ def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region """ # This feature is incompletely implemented, so raise an exception. if len(alchemical_region) > 1: - raise NotImplemented("Multiple regions does not work with AmoebaVdwForce") + raise NotImplementedError("Multiple regions does not work with AmoebaVdwForce") else: alchemical_region = alchemical_region[0] - raise NotImplemented('Alchemical modification of Amoeba VdW Forces is not supported.') + raise NotImplementedError('Alchemical modification of Amoeba VdW Forces is not supported.') # Softcore Halgren potential from Eq. 3 of # Shi, Y., Jiao, D., Schnieders, M.J., and Ren, P. (2009). Trypsin-ligand binding free @@ -2121,7 +2149,7 @@ def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, _, sas """ if len(alchemical_region) > 1: - raise NotImplemented("Multiple regions does not work with GBSAOBCForce") + raise NotImplementedError("Multiple regions does not work with GBSAOBCForce") else: alchemical_region = alchemical_region[0] @@ -2155,7 +2183,7 @@ def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, _, sas custom_force.addComputedValue("B", "1/(1/or-tanh(psi-0.8*psi^2+4.85*psi^3)/radius);" "psi=I*or; or=radius-offset", openmm.CustomGBForce.SingleParticle) - custom_force.addEnergyTerm("-0.5*138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical+(1-alchemical))*charge^2/B", openmm.CustomGBForce.SingleParticle) + custom_force.addEnergyTerm("-0.5*138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical+(1-alchemical))*charge^2/B", openmm.CustomGBForce.SingleParticle) if sasa_model == 'ACE': custom_force.addEnergyTerm("(lambda_electrostatics*alchemical+(1-alchemical))*28.3919551*(radius+0.14)^2*(radius/B)^6", openmm.CustomGBForce.SingleParticle) @@ -2215,7 +2243,7 @@ def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region, """ if len(alchemical_region) > 1: - raise NotImplemented("Multiple regions does not work with CustomGBForce") + raise NotImplementedError("Multiple regions does not work with CustomGBForce") else: alchemical_region = alchemical_region[0] From f5a6557ffec085b6b07618c250517c61560555dc Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Mon, 14 Oct 2019 23:06:48 +0200 Subject: [PATCH 098/152] Style fixes --- openmmtools/tests/test_alchemy.py | 78 +++++++++++++++++-------------- 1 file changed, 43 insertions(+), 35 deletions(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 6007c4c78..513fb6b91 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -272,10 +272,11 @@ def dissect_nonbonded_energy(reference_system, positions, alchemical_atoms, othe # Compute particle interactions between different groups of atoms # ---------------------------------------------------------------- - #Turn off other alchemical regions + # Turn off other alchemical regions if len(other_alchemical_atoms) > 0: turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, only_atoms=other_alchemical_atoms) turn_off_nonbonded(reference_system, sterics=True, electrostatics=True, exceptions=True, only_atoms=other_alchemical_atoms) + system = copy.deepcopy(reference_system) # Compute total energy from nonbonded interactions @@ -442,12 +443,11 @@ def is_alchemical_pme_treatment_exact(alchemical_system): # lambda_electrostatics variable. _, nonbonded_force = forces.find_forces(alchemical_system, openmm.NonbondedForce, only_one=True) - test_electro_suffixes = ['', '_zero', '_one', '_two'] for parameter_idx in range(nonbonded_force.getNumGlobalParameters()): parameter_name = nonbonded_force.getGlobalParameterName(parameter_idx) - for suffix in test_electro_suffixes: - if parameter_name == 'lambda_electrostatics{}'.format(suffix): - return True + # With multiple alchemical regions, lambda_electrostatics might have a suffix. + if parameter_name.startswith('lambda_electrostatics'): + return True return False @@ -464,7 +464,9 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi """ if not isinstance(alchemical_regions, list): alchemical_regions = [alchemical_regions] - force_group = -1 # Default we compare the energy of all groups. + + # Default we compare the energy of all groups. + force_group = -1 # Check nonbonded method. Comparing with PME is more complicated # because the alchemical system with direct-space treatment of PME @@ -517,6 +519,7 @@ def compare_system_energies(reference_system, alchemical_system, alchemical_regi err_msg = "Maximum allowable deviation exceeded (was {:.8f} kcal/mol; allowed {:.8f} kcal/mol)." raise Exception(err_msg.format(delta / unit.kilocalories_per_mole, MAX_DELTA / unit.kilocalories_per_mole)) + def check_multi_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): """wrapper around check_interacting_energy_components for multiple regions @@ -542,7 +545,9 @@ def check_multi_interacting_energy_components(reference_system, alchemical_syste for atom in region.alchemical_atoms: all_alchemical_atoms.add(atom) for region in alchemical_regions: - check_interacting_energy_components(reference_system, alchemical_system, region, positions, all_alchemical_atoms, True) + check_interacting_energy_components( + reference_system, alchemical_system, region, positions, + all_alchemical_atoms, multi_regions=True) def check_interacting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, @@ -611,22 +616,22 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc energy_components = AbsoluteAlchemicalFactory.get_energy_components(alchemical_system, alchemical_state, positions, platform=GLOBAL_ALCHEMY_PLATFORM) if multi_regions: - region_lable = ' for region {}'.format(alchemical_regions.name) + region_label = ' for region {}'.format(alchemical_regions.name) else: - region_lable = '' + region_label = '' # Sterics particle and exception interactions are always modeled with a custom force. - na_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical sterics' + region_lable] - aa_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for alchemical/alchemical sterics' + region_lable] - na_custom_exception_sterics = energy_components['alchemically modified BondForce for non-alchemical/alchemical sterics exceptions' + region_lable] - aa_custom_exception_sterics = energy_components['alchemically modified BondForce for alchemical/alchemical sterics exceptions' + region_lable] + na_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical sterics' + region_label] + aa_custom_particle_sterics = energy_components['alchemically modified NonbondedForce for alchemical/alchemical sterics' + region_label] + na_custom_exception_sterics = energy_components['alchemically modified BondForce for non-alchemical/alchemical sterics exceptions' + region_label] + aa_custom_exception_sterics = energy_components['alchemically modified BondForce for alchemical/alchemical sterics exceptions' + region_label] # With exact treatment of PME, we use the NonbondedForce offset for electrostatics. try: - na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics' + region_lable] - aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics' + region_lable] - na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions' + region_lable] - aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions' + region_lable] + na_custom_particle_electro = energy_components['alchemically modified NonbondedForce for non-alchemical/alchemical electrostatics' + region_label] + aa_custom_particle_electro = energy_components['alchemically modified NonbondedForce for alchemical/alchemical electrostatics' + region_label] + na_custom_exception_electro = energy_components['alchemically modified BondForce for non-alchemical/alchemical electrostatics exceptions' + region_label] + aa_custom_exception_electro = energy_components['alchemically modified BondForce for alchemical/alchemical electrostatics exceptions' + region_label] except KeyError: assert is_exact_pme @@ -650,41 +655,41 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc # Check sterics interactions match assert_almost_equal(nn_particle_sterics, unmod_nn_particle_sterics, - 'Non-alchemical/non-alchemical atoms particle sterics' + region_lable) + 'Non-alchemical/non-alchemical atoms particle sterics' + region_label) assert_almost_equal(nn_exception_sterics, unmod_nn_exception_sterics, - 'Non-alchemical/non-alchemical atoms exceptions sterics' + region_lable) + 'Non-alchemical/non-alchemical atoms exceptions sterics' + region_label) assert_almost_equal(aa_particle_sterics, aa_custom_particle_sterics, - 'Alchemical/alchemical atoms particle sterics' + region_lable) + 'Alchemical/alchemical atoms particle sterics' + region_label) assert_almost_equal(aa_exception_sterics, aa_custom_exception_sterics, - 'Alchemical/alchemical atoms exceptions sterics' + region_lable) + 'Alchemical/alchemical atoms exceptions sterics' + region_label) assert_almost_equal(na_particle_sterics, na_custom_particle_sterics, - 'Non-alchemical/alchemical atoms particle sterics' + region_lable) + 'Non-alchemical/alchemical atoms particle sterics' + region_label) assert_almost_equal(na_exception_sterics, na_custom_exception_sterics, - 'Non-alchemical/alchemical atoms exceptions sterics' + region_lable) + 'Non-alchemical/alchemical atoms exceptions sterics' + region_label) # Check electrostatics interactions assert_almost_equal(nn_particle_electro, unmod_nn_particle_electro, - 'Non-alchemical/non-alchemical atoms particle electrostatics' + region_lable) + 'Non-alchemical/non-alchemical atoms particle electrostatics' + region_label) assert_almost_equal(nn_exception_electro, unmod_nn_exception_electro, - 'Non-alchemical/non-alchemical atoms exceptions electrostatics' + region_lable) + 'Non-alchemical/non-alchemical atoms exceptions electrostatics' + region_label) # With exact treatment of PME, the electrostatics of alchemical-alchemical # atoms is modeled with NonbondedForce offsets. if is_exact_pme: # Reciprocal space. assert_almost_equal(aa_reciprocal_energy, unmod_aa_reciprocal_energy, - 'Alchemical/alchemical atoms reciprocal space energy' + region_lable) + 'Alchemical/alchemical atoms reciprocal space energy' + region_label) assert_almost_equal(na_reciprocal_energy, unmod_na_reciprocal_energy, - 'Non-alchemical/alchemical atoms reciprocal space energy' + region_lable) + 'Non-alchemical/alchemical atoms reciprocal space energy' + region_label) # Direct space. assert_almost_equal(aa_particle_electro, unmod_aa_particle_electro, - 'Alchemical/alchemical atoms particle electrostatics' + region_lable) + 'Alchemical/alchemical atoms particle electrostatics' + region_label) assert_almost_equal(na_particle_electro, unmod_na_particle_electro, - 'Non-alchemical/alchemical atoms particle electrostatics' + region_lable) + 'Non-alchemical/alchemical atoms particle electrostatics' + region_label) # Exceptions. assert_almost_equal(aa_exception_electro, unmod_aa_exception_electro, - 'Alchemical/alchemical atoms exceptions electrostatics' + region_lable) + 'Alchemical/alchemical atoms exceptions electrostatics' + region_label) assert_almost_equal(na_exception_electro, unmod_na_exception_electro, - 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_lable) + 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_label) # With direct space PME, the custom forces model only the # direct space of alchemical-alchemical interactions. else: @@ -697,14 +702,14 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc # Check direct space energy assert_almost_equal(aa_particle_electro, aa_custom_particle_electro, - 'Alchemical/alchemical atoms particle electrostatics' + region_lable) + 'Alchemical/alchemical atoms particle electrostatics' + region_label) assert_almost_equal(na_particle_electro, na_custom_particle_electro, - 'Non-alchemical/alchemical atoms particle electrostatics' + region_lable) + 'Non-alchemical/alchemical atoms particle electrostatics' + region_label) # Check exceptions. assert_almost_equal(aa_exception_electro, aa_custom_exception_electro, - 'Alchemical/alchemical atoms exceptions electrostatics' + region_lable) + 'Alchemical/alchemical atoms exceptions electrostatics' + region_label) assert_almost_equal(na_exception_electro, na_custom_exception_electro, - 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_lable) + 'Non-alchemical/alchemical atoms exceptions electrostatics' + region_label) # With Ewald methods, the NonbondedForce should always hold the # reciprocal space energy of nonalchemical-nonalchemical atoms. @@ -737,6 +742,7 @@ def check_interacting_energy_components(reference_system, alchemical_system, alc assert_almost_equal(reference_force_energy, tot_alchemical_forces_energies, '{} energy '.format(force_name)) + def check_multi_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions): """wrapper around check_noninteracting_energy_components for multiple regions Parameters @@ -753,6 +759,7 @@ def check_multi_noninteracting_energy_components(reference_system, alchemical_sy for region in alchemical_regions: check_noninteracting_energy_components(reference_system, alchemical_system, region, positions, True) + def check_noninteracting_energy_components(reference_system, alchemical_system, alchemical_regions, positions, multi_regions=False): """Check non-interacting energy components are zero when appropriate. Parameters @@ -1724,6 +1731,7 @@ def test_fully_interacting_energy_components(self): f.description = "Testing energy components of %s..." % test_name yield f + class TestDispersionlessAlchemicalFactory(object): """ Only test overlap for dispersionless alchemical factory, since energy agreement From 6d9c6e392ced507a7ddc5fda660bd32f5865bf1a Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Tue, 15 Oct 2019 11:11:22 +0100 Subject: [PATCH 099/152] Comments from review #1 --- alchemy.py | 2503 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 2503 insertions(+) create mode 100644 alchemy.py diff --git a/alchemy.py b/alchemy.py new file mode 100644 index 000000000..3af02de28 --- /dev/null +++ b/alchemy.py @@ -0,0 +1,2503 @@ +#!/usr/bin/python + +# ============================================================================= +# MODULE DOCSTRING +# ============================================================================= + +""" +Alchemical factory for free energy calculations that operates directly on OpenMM System objects. + +DESCRIPTION + +This module contains enumerative factories for generating alchemically-modified System objects +usable for the calculation of free energy differences of hydration or ligand binding. + +* `AbsoluteAlchemicalFactory` uses fused elecrostatic and steric alchemical modifications. + +""" + +# TODO +# - Generalize treatment of nonbonded sterics/electrostatics intra-alchemical +# forces to support arbitrary mixing rules. Can we eliminate decoupling to something simpler? +# - Add support for other GBSA models. +# - Add functions for the automatic optimization of alchemical states? +# - Can we store serialized form of Force objects so that we can save time in reconstituting +# Force objects when we make copies? We can even manipulate the XML representation directly. +# - Allow protocols to automatically be resized to arbitrary number of states, to +# allow number of states to be enlarged to be an integral multiple of number of GPUs. +# - Finish AMOEBA support. +# - Can alchemically-modified System objects share unmodified Force objects to avoid overhead +# of duplicating Forces that are not modified? +# - Add support for arbitrary softcore reprogramming of all Custom*Force classes + + +# ============================================================================= +# GLOBAL IMPORTS +# ============================================================================= +import copy +import logging +import collections +import itertools + +import numpy as np +from simtk import openmm, unit + +from openmmtools import states, forcefactories, utils +from openmmtools.constants import ONE_4PI_EPS0 + +logger = logging.getLogger(__name__) + + +# ============================================================================= +# ALCHEMICAL STATE +# ============================================================================= + +class AlchemicalStateError(states.GlobalParameterError): + """Error raised by an AlchemicalState.""" + pass + + +class AlchemicalFunction(states.GlobalParameterFunction): + """A function of alchemical variables. + + Parameters + ---------- + expression : str + A mathematical expression involving alchemical variables. + + Examples + -------- + >>> alchemical_state = AlchemicalState(lambda_sterics=1.0, lambda_angles=1.0) + >>> alchemical_state.set_alchemical_variable('lambda', 0.5) + >>> alchemical_state.set_alchemical_variable('lambda2', 1.0) + >>> alchemical_state.lambda_sterics = AlchemicalFunction('lambda**2') + >>> alchemical_state.lambda_sterics + 0.25 + >>> alchemical_state.lambda_angles = AlchemicalFunction('(lambda + lambda2) / 2') + >>> alchemical_state.lambda_angles + 0.75 + + """ + # This class just provides an alternative name to GlobalParameterFunction. + pass + + +class AlchemicalState(states.GlobalParameterState): + """Represent an alchemical state. + + The alchemical parameters modify the Hamiltonian and affect the + computation of the energy. Alchemical parameters that have value + None are considered undefined, which means that applying this + state to System and Context that have that parameter as a global + variable will raise an AlchemicalStateError. + + Parameters + ---------- + parameters_name_suffix : str, optional + If specified, the state will control a modified version of the global + parameters with the name ``parameter_name + '_' + parameters_name_suffix``. + When this is the case, the normal parameters are not accessible. + lambda_sterics : float, optional + Scaling factor for ligand sterics (Lennard-Jones and Halgren) + interactions (default is 1.0). + lambda_electrostatics : float, optional + Scaling factor for ligand charges, intrinsic Born radii, and surface + area term (default is 1.0). + lambda_bonds : float, optional + Scaling factor for alchemically-softened bonds (default is 1.0). + lambda_angles : float, optional + Scaling factor for alchemically-softened angles (default is 1.0). + lambda_torsions : float, optional + Scaling factor for alchemically-softened torsions (default is 1.0). + + Attributes + ---------- + lambda_sterics + lambda_electrostatics + lambda_bonds + lambda_angles + lambda_torsions + + Examples + -------- + Create an alchemically modified system. + + >>> from openmmtools import testsystems + >>> factory = AbsoluteAlchemicalFactory(consistent_exceptions=False) + >>> alanine_vacuum = testsystems.AlanineDipeptideVacuum().system + >>> alchemical_region = AlchemicalRegion(alchemical_atoms=range(22)) + >>> alanine_alchemical_system = factory.create_alchemical_system(reference_system=alanine_vacuum, + ... alchemical_regions=alchemical_region) + + Create a completely undefined alchemical state. + + >>> alchemical_state = AlchemicalState() + >>> print(alchemical_state.lambda_sterics) + None + >>> alchemical_state.apply_to_system(alanine_alchemical_system) + Traceback (most recent call last): + ... + openmmtools.alchemy.AlchemicalStateError: The system parameter lambda_electrostatics is not defined in this state. + + Create an AlchemicalState that matches the parameters defined in + the System. + + >>> alchemical_state = AlchemicalState.from_system(alanine_alchemical_system) + >>> alchemical_state.lambda_sterics + 1.0 + >>> alchemical_state.lambda_electrostatics + 1.0 + >>> print(alchemical_state.lambda_angles) + None + + AlchemicalState implement the IComposableState interface, so it can be + used with CompoundThermodynamicState. All the alchemical parameters are + accessible through the compound state. + + >>> from simtk import openmm, unit + >>> thermodynamic_state = states.ThermodynamicState(system=alanine_alchemical_system, + ... temperature=300*unit.kelvin) + >>> compound_state = states.CompoundThermodynamicState(thermodynamic_state=thermodynamic_state, + ... composable_states=[alchemical_state]) + >>> compound_state.lambda_sterics + 1.0 + + You can control the parameters in the OpenMM Context in this state by + setting the state attributes. + + >>> compound_state.lambda_sterics = 0.5 + >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) + >>> context = compound_state.create_context(integrator) + >>> context.getParameter('lambda_sterics') + 0.5 + >>> compound_state.lambda_sterics = 1.0 + >>> compound_state.apply_to_context(context) + >>> context.getParameter('lambda_sterics') + 1.0 + + You can express the alchemical parameters as a mathematical expression + involving alchemical variables. Here is an example for a two-stage function. + + >>> compound_state.set_alchemical_variable('lambda', 1.0) + >>> compound_state.lambda_sterics = AlchemicalFunction('step_hm(lambda - 0.5) + 2*lambda * step_hm(0.5 - lambda)') + >>> compound_state.lambda_electrostatics = AlchemicalFunction('2*(lambda - 0.5) * step(lambda - 0.5)') + >>> for l in [0.0, 0.25, 0.5, 0.75, 1.0]: + ... compound_state.set_alchemical_variable('lambda', l) + ... print(compound_state.lambda_sterics) + 0.0 + 0.5 + 1.0 + 1.0 + 1.0 + + """ + + _GLOBAL_PARAMETER_ERROR = AlchemicalStateError + + # ------------------------------------------------------------------------- + # Lambda properties + # ------------------------------------------------------------------------- + + class _LambdaParameter(states.GlobalParameterState.GlobalParameter): + """A global parameter in the interval [0, 1] with standard value 1.""" + + def __init__(self, parameter_name): + super().__init__(parameter_name, standard_value=1.0, validator=self.lambda_validator) + + @staticmethod + def lambda_validator(self, instance, parameter_value): + if parameter_value is None: + return parameter_value + if not (0.0 <= parameter_value <= 1.0): + raise ValueError('{} must be between 0 and 1.'.format(self.parameter_name)) + return float(parameter_value) + + lambda_sterics = _LambdaParameter('lambda_sterics') + lambda_electrostatics = _LambdaParameter('lambda_electrostatics') + lambda_bonds = _LambdaParameter('lambda_bonds') + lambda_angles = _LambdaParameter('lambda_angles') + lambda_torsions = _LambdaParameter('lambda_torsions') + + @classmethod + def from_system(cls, system, *args, **kwargs): + """Constructor reading the state from an alchemical system. + + Parameters + ---------- + system : simtk.openmm.System + An alchemically modified system in a defined alchemical state. + parameters_name_suffix : str, optional + If specified, the state will search for a modified + version of the alchemical parameters with the name + ``parameter_name + '_' + parameters_name_suffix``. + + Returns + ------- + The AlchemicalState object representing the alchemical state of + the system. + + Raises + ------ + AlchemicalStateError + If the same parameter has different values in the system, or + if the system has no lambda parameters. + + """ + # The function is redefined here only to provide more specific documentation for this method. + return super().from_system(system, *args, **kwargs) + + def set_alchemical_parameters(self, new_value): + """Set all defined lambda parameters to the given value. + + The undefined parameters (i.e. those being set to None) remain + undefined. + + Parameters + ---------- + new_value : float + The new value for all defined parameters. + + """ + for parameter_name in self._parameters: + if self._parameters[parameter_name] is not None: + setattr(self, parameter_name, new_value) + + # ------------------------------------------------------------------------- + # Function variables + # ------------------------------------------------------------------------- + + def get_function_variable(self, variable_name): + """Return the value of the function variable. + + Function variables are variables entering mathematical expressions + specified with ``AlchemicalFunction``, which can be use to enslave + a lambda parameter to arbitrary variables. + + Parameters + ---------- + variable_name : str + The name of the function variable. + + Returns + ------- + variable_value : float + The value of the function variable. + + """ + # The function is redefined here only to provide more specific documentation for this method. + return super().get_function_variable(variable_name) + + def set_function_variable(self, variable_name, new_value): + """Set the value of the function variable. + + Function variables are variables entering mathematical expressions + specified with ``AlchemicalFunction``, which can be use to enslave + a lambda parameter to arbitrary variables. + + Parameters + ---------- + variable_name : str + The name of the function variable. + new_value : float + The new value for the variable. + + """ + # The function is redefined here only to provide more specific documentation for this method. + super().set_function_variable(variable_name, new_value) + + def get_alchemical_variable(self, variable_name): + """Return the value of the alchemical parameter. + + .. warning: + This is deprecated. Use ``get_function_variable`` instead. + + Parameters + ---------- + variable_name : str + The name of the alchemical variable. + + Returns + ------- + variable_value : float + The value of the alchemical variable. + """ + import warnings + warnings.warn('AlchemicalState.get_alchemical_variable is deprecated. ' + 'Use AlchemicalState.get_function_variable instead.') + return super().get_function_variable(variable_name) + + def set_alchemical_variable(self, variable_name, new_value): + """Set the value of the alchemical variable. + + .. warning: + This is deprecated. Use ``set_function_variable`` instead. + + Parameters + ---------- + variable_name : str + The name of the alchemical variable. + new_value : float + The new value for the variable. + + """ + import warnings + warnings.warn('AlchemicalState.get_alchemical_variable is deprecated. ' + 'Use AlchemicalState.get_function_variable instead.') + super().set_function_variable(variable_name, new_value) + + # ------------------------------------------------------------------------- + # IComposableState interface + # ------------------------------------------------------------------------- + + def apply_to_system(self, system): + """Set the alchemical state of the system to this. + + Parameters + ---------- + system : simtk.openmm.System + The system to modify. + + Raises + ------ + AlchemicalStateError + If the system does not have the required lambda global variables. + + """ + # The function is redefined here only to provide more specific documentation for this method. + super().apply_to_system(system) + + def check_system_consistency(self, system): + """Check if the system is in this alchemical state. + + It raises a AlchemicalStateError if the system is not consistent + with the alchemical state. + + Parameters + ---------- + system : simtk.openmm.System + The system to test. + + Raises + ------ + AlchemicalStateError + If the system is not consistent with this state. + + """ + # The function is redefined here only to provide more specific documentation for this method. + super().check_system_consistency(system) + + def apply_to_context(self, context): + """Put the Context into this AlchemicalState. + + Parameters + ---------- + context : simtk.openmm.Context + The context to set. + + Raises + ------ + AlchemicalStateError + If the context does not have the required lambda global variables. + + """ + # The function is redefined here only to provide more specific documentation for this method. + super().apply_to_context(context) + + +# ============================================================================= +# ALCHEMICAL REGION +# ============================================================================= + +_ALCHEMICAL_REGION_ARGS = collections.OrderedDict([ + ('alchemical_atoms', None), + ('alchemical_bonds', None), + ('alchemical_angles', None), + ('alchemical_torsions', None), + ('annihilate_electrostatics', True), + ('annihilate_sterics', False), + ('softcore_alpha', 0.5), ('softcore_a', 1), ('softcore_b', 1), ('softcore_c', 6), + ('softcore_beta', 0.0), ('softcore_d', 1), ('softcore_e', 1), ('softcore_f', 2), + ('name', None) +]) + + +# The class is just a way to document the namedtuple. +class AlchemicalRegion(collections.namedtuple('AlchemicalRegion', _ALCHEMICAL_REGION_ARGS.keys())): + """Alchemical region. + + This is a namedtuple used to tell the AbsoluteAlchemicalFactory which + region of the system to alchemically modify and how. + + Parameters + ---------- + alchemical_atoms : list of int, optional + List of atoms to be designated for which the nonbonded forces (both + sterics and electrostatics components) have to be alchemically + modified (default is None). + alchemical_bonds : bool or list of int, optional + If a list of bond indices are specified, these HarmonicBondForce + entries are softened with 'lambda_bonds'. If set to True, this list + is auto-generated to include all bonds involving any alchemical + atoms (default is None). + alchemical_angles : bool or list of int, optional + If a list of angle indices are specified, these HarmonicAngleForce + entries are softened with 'lambda_angles'. If set to True, this + list is auto-generated to include all angles involving any alchemical + atoms (default is None). + alchemical_torsions : bool or list of int, optional + If a list of torsion indices are specified, these PeriodicTorsionForce + entries are softened with 'lambda_torsions'. If set to True, this list + is auto-generated to include al proper torsions involving any alchemical + atoms. Improper torsions are not softened (default is None). + annihilate_electrostatics : bool, optional + If True, electrostatics should be annihilated, rather than decoupled + (default is True). + annihilate_sterics : bool, optional + If True, sterics (Lennard-Jones or Halgren potential) will be annihilated, + rather than decoupled (default is False). + softcore_alpha : float, optional + Alchemical softcore parameter for Lennard-Jones (default is 0.5). + softcore_a, softcore_b, softcore_c : float, optional + Parameters modifying softcore Lennard-Jones form. Introduced in + Eq. 13 of Ref. [1] (default is 1). + softcore_beta : float, optional + Alchemical softcore parameter for electrostatics. Set this to zero + to recover standard electrostatic scaling (default is 0.0). + softcore_d, softcore_e, softcore_f : float, optional + Parameters modifying softcore electrostatics form (default is 1). + + Notes + ----- + The parameters softcore_e and softcore_f determine the effective distance + between point charges according to + + r_eff = sigma*((softcore_beta*(lambda_electrostatics-1)^softcore_e + (r/sigma)^softcore_f))^(1/softcore_f) + + References + ---------- + [1] Pham TT and Shirts MR. Identifying low variance pathways for free + energy calculations of molecular transformations in solution phase. + JCP 135:034114, 2011. http://dx.doi.org/10.1063/1.3607597 + + """ +AlchemicalRegion.__new__.__defaults__ = tuple(_ALCHEMICAL_REGION_ARGS.values()) + + +# ============================================================================= +# ABSOLUTE ALCHEMICAL FACTORY +# ============================================================================= + +class AbsoluteAlchemicalFactory(object): + """Factory of alchemically modified OpenMM Systems. + + The context parameters created are: + - softcore_alpha: factor controlling softcore lengthscale for Lennard-Jones + - softcore_beta: factor controlling softcore lengthscale for Coulomb + - softcore_a: softcore Lennard-Jones parameter from Eq. 13 of Ref [1] + - softcore_b: softcore Lennard-Jones parameter from Eq. 13 of Ref [1] + - softcore_c: softcore Lennard-Jones parameter from Eq. 13 of Ref [1] + - softcore_d: softcore electrostatics parameter + - softcore_e: softcore electrostatics parameter + - softcore_f: softcore electrostatics parameter + + Parameters + ---------- + consistent_exceptions : bool, optional, default = False + If True, the same functional form of the System's nonbonded + method will be use to determine the electrostatics contribution + to the potential energy of 1,4 exceptions instead of the + classical q1*q2/(4*epsilon*epsilon0*pi*r). + switch_width : float, optional, default = 1.0 * angstroms + Default switch width for electrostatics in periodic cutoff systems + used in alchemical interactions only. + alchemical_pme_treatment : str, optional, default = 'direct-space' + Controls how alchemical region electrostatics are treated when PME is used. + Options are ['direct-space', 'coulomb', 'exact']. + - 'direct-space' only models the direct space contribution + - 'coulomb' includes switched Coulomb interaction + - 'exact' includes also the reciprocal space contribution, but it's + only possible to annihilate the charges and the softcore parameters + controlling the electrostatics are deactivated. Also, with this + method, modifying the global variable `lambda_electrostatics` is + not sufficient to control the charges. The recommended way to change + them is through the `AlchemicalState` class. + alchemical_rf_treatment : str, optional, default = 'switched' + Controls how alchemical region electrostatics are treated when RF is used + Options are ['switched', 'shifted'] + 'switched' sets c_rf = 0 for all reaction-field interactions and ensures continuity with a switch + 'shifted' retains c_rf != 0 but can give erroneous results for hydration free energies + disable_alchemical_dispersion_correction : bool, optional, default=False + If True, the long-range dispersion correction will not be included for the alchemical + region to avoid the need to recompute the correction (a CPU operation that takes ~ 0.5 s) + every time 'lambda_sterics' is changed. If using nonequilibrium protocols, it is recommended + that this be set to True since this can lead to enormous (100x) slowdowns if the correction + must be recomputed every time step. + split_alchemical_forces : bool, optional, default=True + If True, forces that are altered to different alchemical variables + will be split in different force groups. All non-alchemical forces + will maintain their original force group. If more than 32 force + groups are required, an error is thrown. + + Examples + -------- + + Create an alchemical factory to alchemically modify OpenMM System objects. + + >>> factory = AbsoluteAlchemicalFactory(consistent_exceptions=False) + + Create an alchemically modified version of p-xylene in T4 lysozyme L99A in GBSA. + + >>> # Create a reference system. + >>> from openmmtools import testsystems + >>> reference_system = testsystems.LysozymeImplicit().system + >>> # Alchemically soften the pxylene atoms + >>> pxylene_atoms = range(2603,2621) # p-xylene + >>> alchemical_region = AlchemicalRegion(alchemical_atoms=pxylene_atoms) + >>> alchemical_system = factory.create_alchemical_system(reference_system, alchemical_region) + + Alchemically modify one water in a water box. + + >>> reference_system = testsystems.WaterBox().system + >>> alchemical_region = AlchemicalRegion(alchemical_atoms=[0, 1, 2]) + >>> alchemical_system = factory.create_alchemical_system(reference_system, alchemical_region) + + Alchemically modify some angles and torsions in alanine dipeptide and + annihilate both sterics and electrostatics. + + >>> reference_system = testsystems.AlanineDipeptideVacuum().system + >>> alchemical_region = AlchemicalRegion(alchemical_atoms=[0], alchemical_torsions=[0,1,2], + ... alchemical_angles=[0,1,2], annihilate_sterics=True, + ... annihilate_electrostatics=True) + >>> alchemical_system = factory.create_alchemical_system(reference_system, alchemical_region) + + Alchemically modify a bond, angles, and torsions in toluene by automatically + selecting bonds involving alchemical atoms. + + >>> toluene_implicit = testsystems.TolueneImplicit() + >>> alchemical_region = AlchemicalRegion(alchemical_atoms=[0,1], alchemical_torsions=True, + ... alchemical_angles=True, annihilate_sterics=True) + >>> alchemical_system = factory.create_alchemical_system(reference_system, alchemical_region) + + Once the alchemical system is created, you can modify its Hamiltonian + through AlchemicalState + + >>> alchemical_state = AlchemicalState.from_system(alchemical_system) + >>> alchemical_state.lambda_sterics + 1.0 + >>> alchemical_state.lambda_electrostatics = 0.5 + >>> alchemical_state.apply_to_system(alchemical_system) + + You can also modify its Hamiltonian directly into a context + + >>> from simtk import openmm, unit + >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) + >>> context = openmm.Context(alchemical_system, integrator) + >>> alchemical_state.set_alchemical_parameters(0.0) # Set all lambda to 0 + >>> alchemical_state.apply_to_context(context) + + Neglecting the long-range dispersion correction for the alchemical region + (for nonequilibrium switching, for example) requires instantiating a factory + with the appropriate options: + + >>> new_factory = AbsoluteAlchemicalFactory(consistent_exceptions=False, disable_alchemical_dispersion_correction=True) + >>> reference_system = testsystems.WaterBox().system + >>> alchemical_region = AlchemicalRegion(alchemical_atoms=[0, 1, 2]) + >>> alchemical_system = new_factory.create_alchemical_system(reference_system, alchemical_region) + + References + ---------- + [1] Pham TT and Shirts MR. Identifying low variance pathways for free + energy calculations of molecular transformations in solution phase. + JCP 135:034114, 2011. http://dx.doi.org/10.1063/1.3607597 + + """ + + # ------------------------------------------------------------------------- + # Public interface + # ------------------------------------------------------------------------- + + def __init__(self, consistent_exceptions=False, switch_width=1.0*unit.angstroms, + alchemical_pme_treatment='exact', alchemical_rf_treatment='switched', + disable_alchemical_dispersion_correction=False, split_alchemical_forces=True): + + self.consistent_exceptions = consistent_exceptions + self.switch_width = switch_width + self.alchemical_pme_treatment = alchemical_pme_treatment + self.alchemical_rf_treatment = alchemical_rf_treatment + self.disable_alchemical_dispersion_correction = disable_alchemical_dispersion_correction + self.split_alchemical_forces = split_alchemical_forces + + def create_alchemical_system(self, reference_system, alchemical_regions, + alchemical_regions_interactions=frozenset()): + """Create an alchemically modified version of the reference system. + + To alter the alchemical state of the returned system use AlchemicalState. + + Parameters + ---------- + reference_system : simtk.openmm.System + The system to use as a reference for the creation of the + alchemical system. This will not be modified. + alchemical_regions : AlchemicalRegion + The region of the reference system to alchemically soften. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. + + Returns + ------- + alchemical_system : simtk.openmm.System + Alchemically-modified version of reference_system. + + """ + if alchemical_regions_interactions != frozenset(): + raise NotImplementedError('Interactions between alchemical regions is untested') + + logger.debug(f'Dictionary of interacting alchemical regions: {alchemical_regions_interactions}') + if isinstance(alchemical_regions, AlchemicalRegion): + alchemical_regions = [alchemical_regions] + logger.debug(f'Using {len(alchemical_regions)} alchemical regions') + + # Resolve alchemical regions. + alchemical_regions = [self._resolve_alchemical_region(reference_system, alchemical_region) + for alchemical_region in alchemical_regions] + + # Check for duplicate alchemical atoms/bonds/angles/torsions. + all_alchemical_elements = {element_type: set() for element_type in ['atoms', 'bonds', 'angles', 'torsions']} + + for alchemical_region in alchemical_regions: + for element_type, all_elements in all_alchemical_elements.items(): + # Ignore None alchemical elements. + region_elements = getattr(alchemical_region, 'alchemical_' + element_type) + if region_elements is None: + continue + + # Check if there are duplicates with previous regions. + duplicate_elements = all_elements & region_elements + if len(duplicate_elements) > 0: + raise ValueError('Two regions have duplicate {}.'.format(element_type)) + + # Update all alchemical elements. + all_alchemical_elements[element_type].update(region_elements) + + # Check for duplicate names + alchemical_region_names = {alchemical_region.name for alchemical_region in alchemical_regions} + if len(alchemical_region_names) != len(alchemical_regions): + raise ValueError('Two alchemical regions have the same name') + + # Record timing statistics. + timer = utils.Timer() + timer.start('Create alchemically modified system') + + # Build alchemical system to modify. This copies particles, vsites, + # constraints, box vectors and all the forces. We'll later remove + # the forces that we remodel to be alchemically modified. + alchemical_system = copy.deepcopy(reference_system) + + # Check that there are no virtual sites to alchemically modify. + for alchemical_region in alchemical_regions: + for particle_index in alchemical_region.alchemical_atoms: + if reference_system.isVirtualSite(particle_index): + raise ValueError(f'Virtual atoms in region {alchemical_region.name}. ' + 'Alchemically modified virtual sites are not supported') + + # Modify forces as appropriate. We delete the forces that + # have been processed modified at the end of the for loop. + forces_to_remove = [] + alchemical_forces_by_lambda = {} + for force_index, reference_force in enumerate(reference_system.getForces()): + # TODO switch to functools.singledispatch when we drop Python2 support + reference_force_name = reference_force.__class__.__name__ + alchemical_force_creator_name = '_alchemically_modify_{}'.format(reference_force_name) + try: + alchemical_force_creator_func = getattr(self, alchemical_force_creator_name) + except AttributeError: + pass + else: + # The reference system force will be deleted. + forces_to_remove.append(force_index) + # Collect all the Force objects modeling the reference force. + alchemical_forces = alchemical_force_creator_func(reference_force, alchemical_regions, + alchemical_regions_interactions) + for lambda_variable_name, lambda_forces in alchemical_forces.items(): + try: + alchemical_forces_by_lambda[lambda_variable_name].extend(lambda_forces) + except KeyError: + alchemical_forces_by_lambda[lambda_variable_name] = lambda_forces + + # Remove original forces that have been alchemically modified. + for force_index in reversed(forces_to_remove): + alchemical_system.removeForce(force_index) + + # Add forces and split groups if necessary. + self._add_alchemical_forces(alchemical_system, alchemical_forces_by_lambda) + + # Record timing statistics. + timer.stop('Create alchemically modified system') + timer.report_timing() + + # If the System uses a NonbondedForce, replace its NonbondedForce implementation of reaction field + # with a Custom*Force implementation that uses c_rf = 0. + # NOTE: This adds an additional CustomNonbondedForce + if self.alchemical_rf_treatment == 'switched': + forcefactories.replace_reaction_field(alchemical_system, return_copy=False, + switch_width=self.switch_width) + + return alchemical_system + + @classmethod + def get_energy_components(cls, alchemical_system, alchemical_state, positions, platform=None): + """Compute potential energy of the alchemical system by Force. + + This can be useful for debug and analysis. + + Parameters + ---------- + alchemical_system : simtk.openmm.AlchemicalSystem + An alchemically modified system. + alchemical_state : AlchemicalState + The alchemical state to set the Context to. + positions : simtk.unit.Quantity of dimension (natoms, 3) + Coordinates to use for energy test (units of distance). + platform : simtk.openmm.Platform, optional + The OpenMM platform to use to compute the energy. If None, + OpenMM tries to select the fastest available. + + Returns + ------- + energy_components : dict str: simtk.unit.Quantity + A string label describing the role of the force associated to + its contribution to the potential energy. + + """ + # Find and label all forces. + force_labels = cls._find_force_components(alchemical_system) + assert len(force_labels) <= 32, ("The alchemical system has more than 32 force groups; " + "can't compute individual force component energies.") + + # Create deep copy of alchemical system. + system = copy.deepcopy(alchemical_system) + + # Separate all forces into separate force groups. + for force_index, force in enumerate(system.getForces()): + force.setForceGroup(force_index) + + # Create a Context in the given state. + integrator = openmm.VerletIntegrator(1.0 * unit.femtoseconds) + if platform is None: + context = openmm.Context(system, integrator) + else: + context = openmm.Context(system, integrator, platform) + context.setPositions(positions) + alchemical_state.apply_to_context(context) + + # Get energy components + energy_components = collections.OrderedDict() + for force_label, force_index in force_labels.items(): + energy_components[force_label] = context.getState(getEnergy=True, + groups=2**force_index).getPotentialEnergy() + + # Clean up + del context, integrator + return energy_components + + # ------------------------------------------------------------------------- + # Internal usage: AlchemicalRegion + # ------------------------------------------------------------------------- + + @classmethod + def _resolve_alchemical_region(cls, system, alchemical_region): + """Return a new AlchemicalRegion with sets of bonds/angles/torsions resolved. + + Also transform any list of indices into a frozenset. + + Parameters + ---------- + system : simtk.openmm.System + The system. + alchemical_region : AlchemicalRegion + The alchemical region of the system. + + Returns + ------- + AlchemicalRegion + A new AlchemicalRegion object in which all alchemical_X (where X is + atoms, bonds, angles, or torsions) have been converted to a frozenset + of indices that belong to the System. + + Raises + ------ + ValueError + If the indices in the AlchemicalRegion can't be found in the system. + + """ + # TODO move to AlchemicalRegion? + # TODO process also custom forces? (also in _build_alchemical_X_list methods) + # Find and cache the reference forces. + reference_forces = {force.__class__.__name__: force for force in system.getForces()} + + # Count number of particles, angles, etc. in system. Atoms + # must be processed first since the others build on that. + reference_counts = collections.OrderedDict([ + ('atom', system.getNumParticles()), + ('bond', reference_forces['HarmonicBondForce'].getNumBonds() + if 'HarmonicBondForce' in reference_forces else 0), + ('angle', reference_forces['HarmonicAngleForce'].getNumAngles() + if 'HarmonicAngleForce' in reference_forces else 0), + ('torsion', reference_forces['PeriodicTorsionForce'].getNumTorsions() + if 'PeriodicTorsionForce' in reference_forces else 0) + ]) + + # Transform named tuple to dict for easy modification. + alchemical_region = alchemical_region._asdict() + + for region in reference_counts: + region_name = 'alchemical_' + region + 's' + region_indices = alchemical_region[region_name] + + # Convert None and False to empty lists. + if region_indices is None or region_indices is False: + region_indices = set() + + # Automatically build indices list if True. + elif region_indices is True: + if reference_counts[region] == 0: + region_indices = set() + else: + # TODO switch to functools.singledispatch when drop Python2 + builder_function = getattr(cls, '_build_alchemical_{}_list'.format(region)) + region_indices = builder_function(alchemical_region['alchemical_atoms'], + reference_forces, system) + + # Convert numpy arrays to Python lists since SWIG + # have problems with np.int (see openmm#1650). + elif isinstance(region_indices, np.ndarray): + region_indices = region_indices.tolist() + + # Convert to set and update alchemical region. + region_indices = frozenset(region_indices) + alchemical_region[region_name] = region_indices + + # Check that the given indices are in the system. + indices_diff = region_indices - set(range(reference_counts[region])) + if len(indices_diff) > 0: + err_msg = 'Indices {} in {} cannot be found in the system' + raise ValueError(err_msg.format(indices_diff, region_name)) + + # Check that an alchemical region is defined. + total_alchemically_modified = 0 + for region in reference_counts: + total_alchemically_modified += len(alchemical_region['alchemical_' + region + 's']) + if total_alchemically_modified == 0: + raise ValueError('The AlchemicalRegion is empty.') + + # Return a new AlchemicalRegion with the resolved indices lists. + return AlchemicalRegion(**alchemical_region) + + @staticmethod + def _tabulate_bonds(system): + """ + Tabulate bonds for the specified system. + + Parameters + ---------- + system : simtk.openmm.System + The system for which bonds are to be tabulated. + + Returns + ------- + bonds : list of set + bonds[i] is the set of bonds to atom i + + TODO: + * Could we use a Topology object to simplify this? + + """ + bonds = [set() for _ in range(system.getNumParticles())] + + forces = {system.getForce(index).__class__.__name__: system.getForce(index) + for index in range(system.getNumForces())} + + # Process HarmonicBondForce + bond_force = forces['HarmonicBondForce'] + for bond_index in range(bond_force.getNumBonds()): + [particle1, particle2, r, K] = bond_force.getBondParameters(bond_index) + bonds[particle1].add(particle2) + bonds[particle2].add(particle1) + # Process constraints. + for constraint_index in range(system.getNumConstraints()): + [particle1, particle2, r] = system.getConstraintParameters(constraint_index) + bonds[particle1].add(particle2) + bonds[particle2].add(particle1) + + # TODO: Process CustomBondForce? + + return bonds + + @classmethod + def _build_alchemical_torsion_list(cls, alchemical_atoms, reference_forces, system): + """ + Build a list of proper torsion indices that involve any alchemical atom. + + Parameters + ---------- + alchemical_atoms : set of int + The set of alchemically modified atoms. + reference_forces : dict str: force + A dictionary of cached forces in the system accessible by names. + system : simtk.openmm.System + The system. + + Returns + ------- + torsion_list : list of int + The list of torsion indices that should be alchemically softened + + """ + + # Tabulate all bonds + bonds = cls._tabulate_bonds(system) + + def is_bonded(i, j): + if j in bonds[i]: + return True + return False + + def is_proper_torsion(i, j, k, l): + if is_bonded(i, j) and is_bonded(j, k) and is_bonded(k, l): + return True + return False + + # Create a list of proper torsions that involve any alchemical atom. + torsion_list = list() + force = reference_forces['PeriodicTorsionForce'] + for torsion_index in range(force.getNumTorsions()): + particle1, particle2, particle3, particle4, periodicity, phase, k = force.getTorsionParameters(torsion_index) + if set([particle1, particle2, particle3, particle4]).intersection(alchemical_atoms): + if is_proper_torsion(particle1, particle2, particle3, particle4): + torsion_list.append(torsion_index) + + return torsion_list + + @staticmethod + def _build_alchemical_angle_list(alchemical_atoms, reference_forces, system): + """ + Build a list of angle indices that involve any alchemical atom. + + Parameters + ---------- + alchemical_atoms : set of int + The set of alchemically modified atoms. + reference_forces : dict str: force + A dictionary of cached forces in the system accessible by names. + system : simtk.openmm.System + The system (unused). + + Returns + ------- + angle_list : list of int + The list of angle indices that should be alchemically softened + + """ + angle_list = list() + force = reference_forces['HarmonicAngleForce'] + for angle_index in range(force.getNumAngles()): + [particle1, particle2, particle3, theta0, K] = force.getAngleParameters(angle_index) + if set([particle1, particle2, particle3]).intersection(alchemical_atoms): + angle_list.append(angle_index) + + return angle_list + + @staticmethod + def _build_alchemical_bond_list(alchemical_atoms, reference_forces, system): + """ + Build a list of bond indices that involve any alchemical atom, allowing a list of bonds to override. + + Parameters + ---------- + alchemical_atoms : set of int + The set of alchemically modified atoms. + reference_forces : dict str: force + A dictionary of cached forces in the system accessible by names. + system : simtk.openmm.System + The system (unused). + + Returns + ------- + bond_list : list of int + The list of bond indices that should be alchemically softened + + """ + bond_list = list() + force = reference_forces['HarmonicBondForce'] + for bond_index in range(force.getNumBonds()): + [particle1, particle2, r, K] = force.getBondParameters(bond_index) + if set([particle1, particle2]).intersection(alchemical_atoms): + bond_list.append(bond_index) + + return bond_list + + # ------------------------------------------------------------------------- + # Internal usage: Alchemical forces + # ------------------------------------------------------------------------- + + def _add_alchemical_forces(self, alchemical_system, alchemical_forces_by_lambda): + """Add the forces to the alchemical system and eventually split the force groups.""" + # OpenMM can have a maximum of 32 groups. + available_force_groups = set(range(32)) + + # Add non-alchemical groups. New forces will have force group 0, and we don't + # want to modify the force group of forces that have been copied from the reference. + non_alchemical_forces = alchemical_forces_by_lambda.pop('', []) + for non_alchemical_force in non_alchemical_forces: + alchemical_system.addForce(non_alchemical_force) + + # Find which force groups are still available for alchemical forces. + for force in alchemical_system.getForces(): + available_force_groups.discard(force.getForceGroup()) + + # Check if there are enough force groups to split alchemical forces. + if (self.split_alchemical_forces and + len(available_force_groups) < len(alchemical_forces_by_lambda)): + raise RuntimeError('There are not enough force groups to split alchemical forces.\n' + 'Consider merging some non-alchemical forces in a single group ' + 'or set split_alchemical_forces to False.') + + # Add the alchemical forces in a deterministic way (just to be safe). + for lambda_variable in sorted(alchemical_forces_by_lambda): + if self.split_alchemical_forces: + # Assign to these forces the smallest force group index available. + force_group = min(available_force_groups) + available_force_groups.remove(force_group) + for force in alchemical_forces_by_lambda[lambda_variable]: + if self.split_alchemical_forces: + force.setForceGroup(force_group) + alchemical_system.addForce(force) + + @staticmethod + def _are_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): + """Test if a set of particles are in two regions simultaneously and if these regions are interacting. + + Parameters + ---------- + particles: set + Set of particles to check if they are in two noninteracting alchemical regions. + alchemical_region : AlchemicalRegion + The alchemical region containing the indices of the torsions to test. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. + + """ + for i, alchemical_region_A in enumerate(alchemical_regions): + if alchemical_region_A.alchemical_atoms.intersection(particles): + j = 0 + while j < i: + alchemical_region_B = alchemical_regions[j] + if alchemical_region_B.alchemical_atoms.intersection(particles): + if {i, j} in alchemical_regions_interactions: + return False + else: + return True + j += 1 + return False + + @classmethod + def _alchemically_modify_PeriodicTorsionForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): + """Create alchemically-modified version of PeriodicTorsionForce. + + Parameters + ---------- + reference_force : simtk.openmm.PeriodicTorsionForce + The reference PeriodicTorsionForce to be alchemically modify. + alchemical_region : AlchemicalRegion + The alchemical region containing the indices of the torsions to + alchemically modify. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. + + Returns + ------- + force : simtk.openmm.PeriodicTorsionForce + The force responsible for the non-alchemical torsions. + custom_force : simtk.openmm.CustomTorsionForce + The force responsible for the alchemically-softened torsions. + This will not be present if there are not alchemical torsions + in alchemical_region. + + """ + alchemical_forces = {} + all_alchemical_torsions = set() + + # Don't create a force if there are no alchemical torsions. + for alchemical_region in alchemical_regions: + all_alchemical_torsions.update(alchemical_region.alchemical_torsions) + if len(all_alchemical_torsions) == 0: + return {'': [copy.deepcopy(reference_force)]} + + # Create PeriodicTorsionForce to handle unmodified torsions. + force = openmm.PeriodicTorsionForce() + force.setForceGroup(reference_force.getForceGroup()) + for torsion_index in range(reference_force.getNumTorsions()): + particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters( + torsion_index) + particles = set((particle1, particle2, particle3, particle4)) + + # We don't connect through a torsion two particles that belong + # to two different and noninteracting alchemical regions. + are_straddling = cls._are_straddling_noninteracting_regions( + particles, alchemical_regions, alchemical_regions_interactions) + if (torsion_index not in all_alchemical_torsions) and (not are_straddling): + force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) + + # Update the returned value with the non-alchemical force. + alchemical_forces[''] = [force] + + # Create CustomTorsionForce to handle alchemically modified torsions. + for alchemical_region in alchemical_regions: + # This region may not have torsions to modify. + if len(alchemical_region.alchemical_torsions) == 0: + continue + + # Check if the lambda variable needs a suffix to identify the region. + lambda_variable_name = 'lambda_torsions' + if alchemical_region.name is not None: + lambda_variable_name += '_' + alchemical_region.name + + # Create CustomTorsionForce to handle alchemically modified torsions. + energy_function = f"{lambda_variable_name}*k*(1+cos(periodicity*theta-phase))" + custom_force = openmm.CustomTorsionForce(energy_function) + custom_force.addGlobalParameter(lambda_variable_name, 1.0) + custom_force.addPerTorsionParameter('periodicity') + custom_force.addPerTorsionParameter('phase') + custom_force.addPerTorsionParameter('k') + + # Process reference torsions. + for torsion_index in sorted(alchemical_region.alchemical_torsions): + # Retrieve parameters. + particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) + # Create torsions. + custom_force.addTorsion(particle1, particle2, particle3, particle4, [periodicity, phase, k]) + + # Update the returned value with the alchemical force. + alchemical_forces.update({lambda_variable_name: [custom_force]}) + + return alchemical_forces + + @classmethod + def _alchemically_modify_HarmonicAngleForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): + """Create alchemically-modified version of HarmonicAngleForce + + Parameters + ---------- + reference_force : simtk.openmm.HarmonicAngleForce + The reference HarmonicAngleForce to be alchemically modify. + alchemical_region : AlchemicalRegion + The alchemical region containing the indices of the angles to + alchemically modify. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. + + Returns + ------- + force : simtk.openmm.HarmonicAngleForce + The force responsible for the non-alchemical angles. + custom_force : simtk.openmm.CustomAngleForce + The force responsible for the alchemically-softened angles. + This will not be present if there are not alchemical angles + in alchemical_region. + + """ + alchemical_forces = {} + all_alchemical_angles = set() + # Don't create a force if there are no alchemical angles. + for alchemical_region in alchemical_regions: + all_alchemical_angles.update(alchemical_region.alchemical_angles) + if len(all_alchemical_angles) == 0: + return {'': [copy.deepcopy(reference_force)]} + + # Create standard HarmonicAngleForce to handle unmodified angles. + force = openmm.HarmonicAngleForce() + force.setForceGroup(reference_force.getForceGroup()) + for angle_index in range(reference_force.getNumAngles()): + [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) + particles = set((particle1, particle2, particle3)) + + # We don't connect through an angle two particles that belong + # to two different and noninteracting alchemical regions. + are_straddling = cls._are_straddling_noninteracting_regions( + particles, alchemical_regions, alchemical_regions_interactions) + if (angle_index not in all_alchemical_angles) and (not are_straddling): + force.addAngle(particle1, particle2, particle3, theta0, K) + + # Update the returned value with the non-alchemical force. + alchemical_forces[''] = [force] + + # Create CustomAngleForce to handle alchemically modified angles. + for alchemical_region in alchemical_regions: + # This region may not have angles to modify. + if len(alchemical_region.alchemical_angles) == 0: + continue + + # Check if the lambda variable needs a suffix to identify the region. + lambda_variable_name = 'lambda_angles' + if alchemical_region.name is not None: + lambda_variable_name += '_' + alchemical_region.name + + # Create CustomAngleForce to handle alchemically modified angles. + energy_function = f"{lambda_variable_name}*(K/2)*(theta-theta0)^2;" + custom_force = openmm.CustomAngleForce(energy_function) + custom_force.addGlobalParameter(lambda_variable_name, 1.0) + custom_force.addPerAngleParameter('theta0') + custom_force.addPerAngleParameter('K') + + # Process reference angles. + for angle_index in sorted(alchemical_region.alchemical_angles): + [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) + custom_force.addAngle(particle1, particle2, particle3, [theta0, K]) + + # Update the returned value with the alchemical force. + alchemical_forces.update({lambda_variable_name: [custom_force]}) + + return alchemical_forces + + @classmethod + def _alchemically_modify_HarmonicBondForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): + """Create alchemically-modified version of HarmonicBondForce + + Parameters + ---------- + reference_force : simtk.openmm.HarmonicBondForce + The reference HarmonicBondForce to be alchemically modify. + alchemical_region : AlchemicalRegion + The alchemical region containing the indices of the bonds to + alchemically modify. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. + + Returns + ------- + force : simtk.openmm.HarmonicBondForce + The force responsible for the non-alchemical bonds. + custom_force : simtk.openmm.CustomBondForce + The force responsible for the alchemically-softened bonds. + This will not be present if there are not alchemical bonds + in alchemical_region. + + """ + alchemical_forces = {} + all_alchemical_bonds = set() + + # Don't create a force if there are no alchemical bonds. + for alchemical_region in alchemical_regions: + all_alchemical_bonds.update(alchemical_region.alchemical_bonds) + if len(all_alchemical_bonds) == 0: + return {'': [copy.deepcopy(reference_force)]} + + # Create standard HarmonicBondForce to handle unmodified bonds. + force = openmm.HarmonicBondForce() + force.setForceGroup(reference_force.getForceGroup()) + for bond_index in range(reference_force.getNumBonds()): + [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) + particles = set((particle1, particle2)) + + # We don't connect through a bond two particles that belong + # to two different and noninteracting alchemical regions. + are_straddling = cls._are_straddling_noninteracting_regions( + particles, alchemical_regions, alchemical_regions_interactions) + if (bond_index not in all_alchemical_bonds) and (not are_straddling): + force.addBond(particle1, particle2, theta0, K) + + # Update the returned value with the non-alchemical force. + alchemical_forces[''] = [force] + + for alchemical_region in alchemical_regions: + # This region may not have bonds to modify. + if len(alchemical_region.alchemical_bonds) == 0: + continue + + # Check if the lambda variable needs a suffix to identify the region. + lambda_variable_name = 'lambda_bonds' + if alchemical_region.name is not None: + lambda_variable_name += '_' + alchemical_region.name + + # Define force here so that it is over writen saving only one copy. + # Create CustomBondForce to handle alchemically modified bonds. + energy_function = f"{lambda_variable_name}*(K/2)*(r-r0)^2;" + custom_force = openmm.CustomBondForce(energy_function) + custom_force.addGlobalParameter(lambda_variable_name, 1.0) + custom_force.addPerBondParameter('r0') + custom_force.addPerBondParameter('K') + # Process reference bonds. + for bond_index in sorted(alchemical_region.alchemical_bonds): + [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) + custom_force.addBond(particle1, particle2, [theta0, K]) + + # Update the returned value with the alchemical force. + alchemical_forces.update({lambda_variable_name: [custom_force]}) + + return alchemical_forces + + def _get_sterics_energy_expressions(self, lambda_variable_suffixes): + """Return the energy expressions for sterics. + + Parameters + ---------- + lambda_variable_suffixes : List[str] + A list with suffixes for the global variable "lambda_sterics" that + will control the energy. If no suffix is necessary (i.e. there are + no multiple alchemical regions) just set lambda_variable_suffixes[0] = ''. + If the list has more than one element, the energy is controlled by + the multiplication of lambda_sterics_suffix1 * lambda_sterics_suffix2. + """ + + # Sterics mixing rules. + if lambda_variable_suffixes[0] == '': + lambda_variable_name = 'lambda_sterics' + else: + if len(lambda_variable_suffixes) > 1: + lambda_variable_name = 'lambda_sterics{0}*lambda_sterics{1}'.format( + lambda_variable_suffixes[0], lambda_variable_suffixes[1]) + else: + lambda_variable_name = 'lambda_sterics{}'.format(lambda_variable_suffixes[0]) + + sterics_mixing_rules = ('epsilon = sqrt(epsilon1*epsilon2);' # Mixing rule for epsilon. + 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. + + # Soft-core Lennard-Jones. + exceptions_sterics_energy_expression = ('U_sterics;' + 'U_sterics = (({0})^softcore_a)*4*epsilon*x*(x-1.0);' + 'x = (sigma/reff_sterics)^6;' + # Effective softcore distance for sterics. + 'reff_sterics = sigma*((softcore_alpha*(1.0-({0}))^softcore_b + (r/sigma)^softcore_c))^(1/softcore_c);')\ + .format(lambda_variable_name) + # Define energy expression for electrostatics. + return sterics_mixing_rules, exceptions_sterics_energy_expression + + def _get_electrostatics_energy_expressions(self, reference_force, lambda_variable_suffixes): + """Return the energy expressions for electrostatics. + + This private function assumes self._alchemical_pme_treatment != 'exact' + as there's no electrostatics CustomNondondedForce in this case, and + lambda_electrostatics is modeled through an offset parameter in a + NonbondedForce. + + Parameters + ---------- + lambda_variable_suffixes : List[str] + A list with suffixes for the global variable "lambda_electrostatics" that + will control the energy. If no suffix is necessary (i.e. there are + no multiple alchemical regions) just set lambda_variable_suffixes[0] = ''. + If the list has more than one element, the energy is controlled by + the multiplication of lambda_electrostatics_suffix1 * lambda_electrostatics_suffix2. + """ + if lambda_variable_suffixes[0] == '': + lambda_variable_name = 'lambda_electrostatics' + else: + if len(lambda_variable_suffixes) > 1: + lambda_variable_name = 'lambda_electrostatics{0}*lambda_electrostatics{1}'.format( + lambda_variable_suffixes[0], lambda_variable_suffixes[1]) + else: + lambda_variable_name = 'lambda_electrostatics{}'.format(lambda_variable_suffixes[0]) + + # The final expression will be prefix + method + suffix. + electrostatics_prefix = ('U_electrostatics;' + 'U_electrostatics=(({})^softcore_d)*ONE_4PI_EPS0*chargeprod').format(lambda_variable_name) + + # Effective softcore distance for electrostatics (common to all methods). + electrostatics_suffix = ('reff_electrostatics = sigma*((softcore_beta*(1.0-({0}))^softcore_e + (r/sigma)^softcore_f))^(1/softcore_f);' + 'ONE_4PI_EPS0 = {1};').format(lambda_variable_name, ONE_4PI_EPS0) # Already in OpenMM units. + + # Define mixing rules. + electrostatics_mixing_rules = ('chargeprod = charge1*charge2;' # Mixing rule for charges. + 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. + + # Standard Coulomb expression with softened core. This is used + # - When the nonbonded method of the reference force is NoCutoff. + # - When alchemical_pme_treatment is set to 'coulomb'. + # - With 1-4 exceptions, unless self.consistent_exceptions is True. + coulomb_expression = '/reff_electrostatics;' + + # Select electrostatics functional form based on nonbonded method. + nonbonded_method = reference_force.getNonbondedMethod() + + # Soft-core Coulomb. + if nonbonded_method in [openmm.NonbondedForce.NoCutoff]: + electrostatics_method_expression = coulomb_expression + # Reaction-field electrostatics. + elif nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, openmm.NonbondedForce.CutoffNonPeriodic]: + electrostatics_method_expression = self._get_reaction_field_unique_expression(reference_force) + # PME electrostatics. + elif nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]: + # Ewald direct-space electrostatics. + if self.alchemical_pme_treatment == 'direct-space': + electrostatics_method_expression = self._get_pme_direct_space_unique_expression(reference_force) + # Use switched standard Coulomb potential, following MTS scheme described in + # http://dx.doi.org/10.1063/1.1385159 + elif self.alchemical_pme_treatment == 'coulomb': + electrostatics_method_expression = coulomb_expression + else: + raise ValueError("Unknown alchemical_pme_treatment scheme '{}'".format(self.alchemical_pme_treatment)) + else: + raise ValueError("Nonbonded method {} not supported yet.".format(nonbonded_method)) + + # Define energy expression for 1,4 electrostatic exceptions. + exceptions_electrostatics_energy_expression = electrostatics_prefix + if self.consistent_exceptions: + exceptions_electrostatics_energy_expression += electrostatics_method_expression + else: + exceptions_electrostatics_energy_expression += coulomb_expression + exceptions_electrostatics_energy_expression += electrostatics_suffix + + # Define energy expression for electrostatics. + electrostatics_energy_expression = (electrostatics_prefix + electrostatics_method_expression + + electrostatics_suffix + electrostatics_mixing_rules) + + return electrostatics_energy_expression, exceptions_electrostatics_energy_expression + + def _get_reaction_field_unique_expression(self, reference_force): + """Unique part of the expression for reaction-field electrostatics. + + Parameters + ---------- + reference_force : openmm.NonbondedForce + The reference force including the reaction-field parameters. + + Returns + ------- + rf_expression : str + The unique expression for reaction-field electrostatics. + + See Also + -------- + _get_nonbonded_energy_expressions + """ + epsilon_solvent = reference_force.getReactionFieldDielectric() + r_cutoff = reference_force.getCutoffDistance() + + # Determine reaction fields parameters. + k_rf = r_cutoff**(-3) * ((epsilon_solvent - 1) / (2*epsilon_solvent + 1)) + if self.alchemical_rf_treatment == 'switched': + c_rf = 0.0 / unit.nanometers + elif self.alchemical_rf_treatment == 'shifted': + # WARNING: Setting c_rf != 0 can cause large errors in DeltaG for hydration free energies + c_rf = r_cutoff**(-1) * ((3*epsilon_solvent) / (2*epsilon_solvent + 1)) + else: + raise ValueError("Unknown alchemical_rf_treatment scheme '{}'".format(self.alchemical_rf_treatment)) + + k_rf = k_rf.value_in_unit_system(unit.md_unit_system) + c_rf = c_rf.value_in_unit_system(unit.md_unit_system) + rf_expression = ('*(reff_electrostatics^(-1) + k_rf*reff_electrostatics^2 - c_rf);' + 'k_rf = {k_rf};' + 'c_rf = {c_rf};').format(k_rf=k_rf, c_rf=c_rf) + return rf_expression + + def _get_pme_direct_space_unique_expression(self, reference_force): + """Unique part of the expression for Ewald direct-space electrostatics. + + Parameters + ---------- + reference_force : openmm.NonbondedForce + The reference force including the Ewald parameters. + + Returns + ------- + rf_expression : str + The unique expression for Ewald direct-space electrostatics. + + See Also + -------- + _get_nonbonded_energy_expressions + """ + # Determine PME parameters. + [alpha_ewald, nx, ny, nz] = reference_force.getPMEParameters() + if (alpha_ewald/alpha_ewald.unit) == 0.0: + # If alpha is 0.0, alpha_ewald is computed by OpenMM from from the error tolerance. + tol = reference_force.getEwaldErrorTolerance() + alpha_ewald = (1.0/reference_force.getCutoffDistance()) * np.sqrt(-np.log(2.0*tol)) + + alpha_ewald = alpha_ewald.value_in_unit_system(unit.md_unit_system) + pme_expression = ("*erfc(alpha_ewald*reff_electrostatics)/reff_electrostatics;" + "alpha_ewald = {};").format(alpha_ewald) + return pme_expression + + def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_regions, alchemical_regions_interactions): + """Create alchemically-modified version of NonbondedForce. + + Parameters + ---------- + reference_force : simtk.openmm.NonbondedForce + The reference NonbondedForce to be alchemically modify. + alchemical_region : AlchemicalRegion + The alchemical region containing the indices of the atoms to + alchemically modify. + alchemical_regions_interactions : Set[Tuple[int, int]], optional + Set of alchemical region index pairs for interacting regions. + By default, all alchemical regions interact only with the + non-alchemical environment. + + Returns + ------- + nonbonded_force : simtk.openmm.NonbondedForce + The force responsible for interactions and exceptions of non-alchemical atoms. + aa_sterics_custom_nonbonded_force : simtk.openmm.CustomNonbondedForce + The force responsible for sterics interactions of alchemical/alchemical atoms. + aa_electrostatics_custom_nonbonded_force : simtk.openmm.CustomNonbondedForce + The force responsible for electrostatics interactions of alchemical/alchemical + atoms. + na_sterics_custom_nonbonded_force : simtk.openmm.CustomNonbondedForce + The force responsible for sterics interactions of non-alchemical/alchemical atoms. + na_electrostatics_custom_nonbonded_force : simtk.openmm.CustomNonbondedForce + The force responsible for electrostatics interactions of non-alchemical/alchemical + atoms. + aa_sterics_custom_bond_force : simtk.openmm.CustomBondForce + The force responsible for sterics exceptions of alchemical/alchemical atoms. + aa_electrostatics_custom_bond_force : simtk.openmm.CustomBondForce + The force responsible for electrostatics exceptions of alchemical/alchemical + atoms. + na_sterics_custom_bond_force : simtk.openmm.CustomBondForce + The force responsible for sterics exceptions of non-alchemical/alchemical atoms. + na_electrostatics_custom_bond_force : simtk.openmm.CustomBondForce + The force responsible for electrostatics exceptions of non-alchemical/alchemical + atoms. + + References + ---------- + [1] Pham TT and Shirts MR. Identifying low variance pathways for free + energy calculations of molecular transformations in solution phase. + JCP 135:034114, 2011. http://dx.doi.org/10.1063/1.3607597 + + """ + # TODO Change softcore_beta to a dimensionless scalar to multiply some intrinsic length-scale, like Lennard-Jones alpha. + # TODO Try using a single, common "reff" effective softcore distance for both Lennard-Jones and Coulomb. + + forces_by_lambda = {} + all_alchemical_atoms = set() + + # Don't create a force if there are no alchemical atoms. + for alchemical_region in alchemical_regions: + if not len(alchemical_region.alchemical_atoms) == 0: + all_alchemical_atoms.update(alchemical_region.alchemical_atoms) + + # Don't create a force if there are no alchemical atoms. + if len(all_alchemical_atoms) == 0: + return {'': [copy.deepcopy(reference_force)]} + + # Create a set of all the non-alchemical atoms only. + all_atomset = set(range(reference_force.getNumParticles())) + nonalchemical_atomset = all_atomset.difference(all_alchemical_atoms) + + # ------------------------------------------------------------- + # Perform tasks that do not need to be repeated for all regions. + # ------------------------------------------------------------- + + # Define energy expression for electrostatics based on nonbonded method. + nonbonded_method = reference_force.getNonbondedMethod() + is_ewald_method = nonbonded_method in [openmm.NonbondedForce.Ewald, + openmm.NonbondedForce.PME] + is_rf_method = nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, + openmm.NonbondedForce.CutoffNonPeriodic] + is_periodic_method = is_ewald_method or nonbonded_method == openmm.NonbondedForce.CutoffPeriodic + use_exact_pme_treatment = is_ewald_method and self.alchemical_pme_treatment == 'exact' + + # Warn about reaction field. + if is_rf_method: + logger.warning('Reaction field support is still experimental. For free energy ' + 'calculations in explicit solvent, we suggest using PME for now.') + + # Check that PME treatment is supported with the region's parameters. + if use_exact_pme_treatment: + for alchemical_region in alchemical_regions: + err_msg = ' not supported with exact treatment of Ewald electrostatics.' + if not alchemical_region.annihilate_electrostatics: + raise ValueError('Decoupled electrostatics is' + err_msg) + if self.consistent_exceptions: + raise ValueError('Consistent exceptions are' + err_msg) + if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): + raise ValueError('Softcore electrostatics is' + err_msg) + + # Create a copy of the NonbondedForce to handle particle interactions and + # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). + nonbonded_force = copy.deepcopy(reference_force) + + # Fix any issues in reference force with Lennard-Jones sigma = 0 (epsilon = 0), + # which should have sigma > 0. + for particle_index in range(reference_force.getNumParticles()): + # Retrieve parameters. + [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) + # Check particle sigma is not zero. + if sigma == 0.0 * unit.angstrom: + warning_msg = 'particle %d has Lennard-Jones sigma = 0 (charge=%s, sigma=%s, epsilon=%s); setting sigma=1A' + logger.warning(warning_msg % (particle_index, str(charge), str(sigma), str(epsilon))) + sigma = 1.0 * unit.angstrom + # Fix it. + nonbonded_force.setParticleParameters(particle_index, charge, sigma, epsilon) + + # Same for the exceptions. + for exception_index in range(reference_force.getNumExceptions()): + # Retrieve parameters. + [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) + # Check particle sigma is not zero. + if sigma == 0.0 * unit.angstrom: + warning_msg = 'exception %d has Lennard-Jones sigma = 0 (iatom=%d, jatom=%d, chargeprod=%s, sigma=%s, epsilon=%s); setting sigma=1A' + logger.warning(warning_msg % (exception_index, iatom, jatom, str(chargeprod), str(sigma), str(epsilon))) + sigma = 1.0 * unit.angstrom + # Fix it. + nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) + + if use_exact_pme_treatment: + # Exclude noninteracting alchemical regions from seeing each other in the nonbonded + for x, y in itertools.combinations(range(len(alchemical_regions)), 2): + if (x, y) not in alchemical_regions_interactions: + for atom1 in alchemical_regions[x].alchemical_atoms: + for atom2 in alchemical_regions[y].alchemical_atoms: + nonbonded_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) + else: + region_names = (alchemical_regions[x].name, alchemical_regions[y].name) + logger.debug(f'Adding a exact PME electrostatic interaction group between groups {region_names}.') + del region_names + + # With exact PME treatment, particle electrostatics is handled through offset parameters. + for alchemical_region in alchemical_regions: + if alchemical_region.name is None: + nonbonded_force.addGlobalParameter('lambda_electrostatics', 1.0) + else: + nonbonded_force.addGlobalParameter(f'lambda_electrostatics_{alchemical_region.name}', 1.0) + + # Make of list of all single and double permutations of alchemical regions. + single_regions = [[alchemical_region] for alchemical_region in alchemical_regions] + if len(alchemical_regions_interactions) == 0: + pair_regions = [] + else: + # Only generate pairs of alchemical regions specified by alchemical_regions_interactions. + pair_regions = [[alchemical_regions[x[0]], alchemical_regions[x[1]]] for x in + alchemical_regions_interactions] + + # Iterate over all single and double permutations of alchemical regions to build all interactions. + for alchemical_regions_pairs in single_regions+pair_regions: + + # Make a list of region names for the alchemical regions interactions which are being built. + lambda_var_suffixes = [] + for alchemical_region in alchemical_regions_pairs: + if alchemical_region.name is None: + lambda_var_suffixes.append('') + else: + lambda_var_suffixes.append('_' + alchemical_region.name) + + # -------------------------------------------------- + # Determine energy expression for all custom forces + # -------------------------------------------------- + + # Get steric energy expressions. + sterics_mixing_rules, exceptions_sterics_energy_expression = self._get_sterics_energy_expressions(lambda_var_suffixes) + + # Define energy expression for sterics. + sterics_energy_expression = exceptions_sterics_energy_expression + sterics_mixing_rules + + if not use_exact_pme_treatment: + # There's no CustomNonbondedForce that models electrostatics if we use exact + # PME treatment. Electrostatics is modeled through offset parameters. + energy_expressions = self._get_electrostatics_energy_expressions(reference_force, lambda_var_suffixes) + (electrostatics_energy_expression, + exceptions_electrostatics_energy_expression) = energy_expressions # Unpack tuple. + + # ------------------------------------------------------------ + # Create and configure all forces to add to alchemical system + # ------------------------------------------------------------ + + # Interactions and exceptions will be distributed according to the following table. + + # -------------------------------------------------------------------------------------------------- + # FORCE | INTERACTION GROUP | + # -------------------------------------------------------------------------------------------------- + # nonbonded_force (unmodified) | all interactions nonalchemical/nonalchemical | + # | all exceptions nonalchemical/nonalchemical | + # -------------------------------------------------------------------------------------------------- + # aa_sterics_custom_nonbonded_force | sterics interactions alchemical/alchemical | + # -------------------------------------------------------------------------------------------------- + # aa_electrostatics_custom_nonbonded_force | electrostatics interactions alchemical/alchemical | + # | (only without exact PME treatment) | + # -------------------------------------------------------------------------------------------------- + # na_sterics_custom_nonbonded_force | sterics interactions non-alchemical/alchemical | + # -------------------------------------------------------------------------------------------------- + # na_electrostatics_custom_nonbonded_force | electrostatics interactions non-alchemical/alchemical | + # | (only without exact PME treatment) | + # -------------------------------------------------------------------------------------------------- + # aa_sterics_custom_bond_force | sterics exceptions alchemical/alchemical | + # -------------------------------------------------------------------------------------------------- + # aa_electrostatics_custom_bond_force | electrostatics exceptions alchemical/alchemical | + # | (only without exact PME treatment) | + # -------------------------------------------------------------------------------------------------- + # na_sterics_custom_bond_force | sterics exceptions non-alchemical/alchemical | + # -------------------------------------------------------------------------------------------------- + # na_electrostatics_custom_bond_force | electrostatics exceptions non-alchemical/alchemical | + # | (only without exact PME treatment) | + # -------------------------------------------------------------------------------------------------- + + def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_suffixes, is_lambda_controlled): + """Shortcut to create a lambda-controlled custom forces.""" + if is_lambda_controlled: + force = force_cls(energy_expression) + for suffix in lambda_var_suffixes: + name = (lambda_variable_name + suffix) + force.addGlobalParameter(name, 1.0) + else: # fix lambda variable to 1.0 + for suffix in lambda_var_suffixes: + name = (lambda_variable_name + suffix) + energy_expression = energy_expression + name + '=1.0;' + force = force_cls(energy_expression) + return force + + # Create CustomNonbondedForces to handle sterics particle interactions between + # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda + # to 1.0 for decoupled interactions in alchemical/alchemical force. + if len(lambda_var_suffixes) > 1: + aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) + all_sterics_custom_nonbonded_forces = [aa_sterics_custom_nonbonded_force] + else: + na_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) + aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, + 'lambda_sterics', lambda_var_suffixes, alchemical_region.annihilate_sterics) + all_sterics_custom_nonbonded_forces = [na_sterics_custom_nonbonded_force, aa_sterics_custom_nonbonded_force] + + # Add parameters and configure CustomNonbondedForces to match reference force. + for force in all_sterics_custom_nonbonded_forces: + force.addPerParticleParameter("sigma") # Lennard-Jones sigma + force.addPerParticleParameter("epsilon") # Lennard-Jones epsilon + force.setUseSwitchingFunction(nonbonded_force.getUseSwitchingFunction()) + force.setCutoffDistance(nonbonded_force.getCutoffDistance()) + force.setSwitchingDistance(nonbonded_force.getSwitchingDistance()) + if self.disable_alchemical_dispersion_correction: + force.setUseLongRangeCorrection(False) + else: + force.setUseLongRangeCorrection(nonbonded_force.getUseDispersionCorrection()) + + if is_periodic_method: + force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) + else: + force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) + + if use_exact_pme_treatment: + #electrostatics are handled by offset + all_electrostatics_custom_nonbonded_forces = [] + else: + # Create CustomNonbondedForces to handle electrostatics particle interactions between + # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda + # to 1.0 for decoupled interactions in alchemical/alchemical force. + if len(lambda_var_suffixes) > 1: + aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, + 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) + all_electrostatics_custom_nonbonded_forces = [aa_electrostatics_custom_nonbonded_force] + else: + na_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, + 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) + aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, + 'lambda_electrostatics', lambda_var_suffixes, alchemical_region.annihilate_electrostatics) + all_electrostatics_custom_nonbonded_forces = [na_electrostatics_custom_nonbonded_force, + aa_electrostatics_custom_nonbonded_force] + + # Common parameters and configuration for electrostatics CustomNonbondedForces. + for force in all_electrostatics_custom_nonbonded_forces: + force.addPerParticleParameter("charge") # partial charge + force.addPerParticleParameter("sigma") # Lennard-Jones sigma + if ((is_ewald_method and self.alchemical_pme_treatment == 'coulomb') or + (is_rf_method and self.alchemical_rf_treatment == 'switched')): + # Use switching function for alchemical electrostatics to ensure force continuity at cutoff. + force.setUseSwitchingFunction(True) + else: + force.setUseSwitchingFunction(False) + force.setSwitchingDistance(nonbonded_force.getCutoffDistance() - self.switch_width) + force.setCutoffDistance(nonbonded_force.getCutoffDistance()) + force.setUseLongRangeCorrection(False) # long-range dispersion correction is meaningless for electrostatics + + if is_periodic_method: + force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) + else: + force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) + + # Create CustomBondForces to handle sterics 1,4 exceptions interactions between + # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda + # to 1.0 for decoupled interactions in alchemical/alchemical force. + if len(lambda_var_suffixes) > 1: + aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) + all_sterics_custom_bond_forces = [aa_sterics_custom_bond_force] + else: + na_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, + 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) + aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, + 'lambda_sterics', lambda_var_suffixes, alchemical_region.annihilate_sterics) + all_sterics_custom_bond_forces = [na_sterics_custom_bond_force, aa_sterics_custom_bond_force] + + for force in all_sterics_custom_bond_forces: + force.addPerBondParameter("sigma") # Lennard-Jones effective sigma + force.addPerBondParameter("epsilon") # Lennard-Jones effective epsilon + + # With exact PME treatment, exception electrostatics is handled through offset parameters. + if use_exact_pme_treatment: + all_electrostatics_custom_bond_forces = [] + else: + # Create CustomBondForces to handle electrostatics 1,4 exceptions interactions between + # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda + # to 1.0 for decoupled interactions in alchemical/alchemical force. + if len(lambda_var_suffixes) > 1: + aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, + 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) + all_electrostatics_custom_bond_forces = [aa_electrostatics_custom_bond_force] + else: + na_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, + 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) + aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, + 'lambda_electrostatics', lambda_var_suffixes, alchemical_region.annihilate_electrostatics) + all_electrostatics_custom_bond_forces = [na_electrostatics_custom_bond_force, aa_electrostatics_custom_bond_force] + + # Create CustomBondForce to handle exceptions for electrostatics + for force in all_electrostatics_custom_bond_forces: + force.addPerBondParameter("chargeprod") # charge product + force.addPerBondParameter("sigma") # Lennard-Jones effective sigma + + # ------------------------------------------------------------------------------- + # Distribute particle interactions contributions in appropriate nonbonded forces + # ------------------------------------------------------------------------------- + + # Create atom groups. + if len(lambda_var_suffixes) > 1: # Multi region + alchemical_atomsets = [alchemical_regions_pairs[0].alchemical_atoms, + alchemical_regions_pairs[1].alchemical_atoms] + else: # One region + alchemical_atomsets = [alchemical_regions_pairs[0].alchemical_atoms] + + # Copy NonbondedForce particle terms for alchemically-modified particles + # to CustomNonbondedForces, and/or add the charge offsets for exact PME. + # On CUDA, for efficiency reasons, all nonbonded forces (custom and not) + # must have the same particles. + for particle_index in range(nonbonded_force.getNumParticles()): + # Retrieve nonbonded parameters. + [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + # Set sterics parameters in CustomNonbondedForces. + for force in all_sterics_custom_nonbonded_forces: + force.addParticle([sigma, epsilon]) + # Set electrostatics parameters in CustomNonbondedForces. + for force in all_electrostatics_custom_nonbonded_forces: + force.addParticle([charge, sigma]) + # Set offset parameters in NonbondedForce. + if use_exact_pme_treatment and particle_index in alchemical_atomsets[0] and len(lambda_var_suffixes) == 1: + nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(lambda_var_suffixes[0]), + particle_index, charge, 0.0, 0.0) + + # Turn off interactions contribution from alchemically-modified particles in unmodified + # NonbondedForce that will be handled by all other forces + for particle_index in range(nonbonded_force.getNumParticles()): + # Retrieve parameters. + [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) + # Even with exact treatment of the PME electrostatics, we turn off + # the NonbondedForce charge which is modeled by the offset parameter. + if particle_index in alchemical_atomsets[0]: + nonbonded_force.setParticleParameters(particle_index, abs(0.0*charge), sigma, abs(0*epsilon)) + + # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. + # Sterics + if len(lambda_var_suffixes) == 1: + logger.debug('Adding steric interaction groups between {} and the environment.'.format(lambda_var_suffixes[0])) + na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomsets[0]) + + logger.debug('Adding a steric interaction group between group {0} and {1}.'.format(lambda_var_suffixes[0], + lambda_var_suffixes[-1])) + aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomsets[0], alchemical_atomsets[-1]) + + # Electrostatics + if not use_exact_pme_treatment: + if len(lambda_var_suffixes) == 1: + logger.debug('Adding electrostatic interaction groups between {} and the environment.'.format(lambda_var_suffixes[0])) + na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomsets[0]) + + logger.debug('Adding a electrostatic interaction group between group {0} and {1}.'.format(lambda_var_suffixes[0], + lambda_var_suffixes[-1])) + aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomsets[0], alchemical_atomsets[-1]) + + else: + # Using the nonbonded force to handle electrostatics + # and the "interaction groups" in the nonbonded have already been handled by exclusions. + pass + + # --------------------------------------------------------------- + # Distribute exceptions contributions in appropriate bond forces + # --------------------------------------------------------------- + + all_custom_nonbonded_forces = all_sterics_custom_nonbonded_forces + all_electrostatics_custom_nonbonded_forces + + # Move all NonbondedForce exception terms for alchemically-modified particles to CustomBondForces. + if len(lambda_var_suffixes) > 1: + for exception_index in range(nonbonded_force.getNumExceptions()): + # Retrieve parameters. + [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + + # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces + # must have the same number of exceptions/exclusions on CUDA platform. + for force in all_custom_nonbonded_forces: + force.addExclusion(iatom, jatom) + + # Check how many alchemical atoms we have + both_alchemical = iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[1] or\ + jatom in alchemical_atomsets[0] and iatom in alchemical_atomsets[1] + + # Check if this is an exception or an exclusion + is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 + is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 + + if use_exact_pme_treatment and both_alchemical and is_exception_chargeprod: + # Exceptions here should be scaled by lam0*lam1. + # This can be implemented in the future using a CustomBondForce. + raise ValueError('Cannot have exception that straddles two alchemical regions') + + # If exception (and not exclusion), add special CustomBondForce terms to + # handle alchemically-modified Lennard-Jones and electrostatics exceptions + if both_alchemical: + if is_exception_epsilon: + aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) + if is_exception_chargeprod and not use_exact_pme_treatment: + aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) + + else: + for exception_index in range(nonbonded_force.getNumExceptions()): + # Retrieve parameters. + [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + + # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces + # must have the same number of exceptions/exclusions on CUDA platform. + for force in all_custom_nonbonded_forces: + force.addExclusion(iatom, jatom) + + # Check how many alchemical atoms we have + both_alchemical = iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[0] + at_least_one_alchemical = iatom in alchemical_atomsets[0] or jatom in alchemical_atomsets[0] + only_one_alchemical = at_least_one_alchemical and not both_alchemical + + # Check if this is an exception or an exclusion + is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 + is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 + + # If this is an electrostatic exception and we're using exact PME, + # we just have to add the exception offset to the NonbondedForce. + if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: + nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(lambda_var_suffixes[0]), + exception_index, chargeprod, 0.0, 0.0) + + # If exception (and not exclusion), add special CustomBondForce terms to + # handle alchemically-modified Lennard-Jones and electrostatics exceptions + if both_alchemical: + if is_exception_epsilon: + aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) + if is_exception_chargeprod and not use_exact_pme_treatment: + aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) + elif only_one_alchemical: + if is_exception_epsilon: + na_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) + if is_exception_chargeprod and not use_exact_pme_treatment: + na_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) + # else: both particles are non-alchemical, leave them in the unmodified NonbondedForce + + # Turn off all exception contributions from alchemical atoms in the NonbondedForce + # modelling non-alchemical atoms only + if at_least_one_alchemical: + nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, + abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) + + # Add global parameters to forces. + def add_global_parameters(force): + force.addGlobalParameter('softcore_alpha', alchemical_region.softcore_alpha) + force.addGlobalParameter('softcore_beta', alchemical_region.softcore_beta) + force.addGlobalParameter('softcore_a', alchemical_region.softcore_a) + force.addGlobalParameter('softcore_b', alchemical_region.softcore_b) + force.addGlobalParameter('softcore_c', alchemical_region.softcore_c) + force.addGlobalParameter('softcore_d', alchemical_region.softcore_d) + force.addGlobalParameter('softcore_e', alchemical_region.softcore_e) + force.addGlobalParameter('softcore_f', alchemical_region.softcore_f) + + all_custom_forces = (all_custom_nonbonded_forces + + all_sterics_custom_bond_forces + + all_electrostatics_custom_bond_forces) + for force in all_custom_forces: + add_global_parameters(force) + + # With exact treatment of PME electrostatics, the NonbondedForce + # is affected by lambda electrostatics as well. + if 'lambda_sterics{}'.format(lambda_var_suffixes[0]) in forces_by_lambda: + forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])].extend(all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces) + forces_by_lambda['lambda_sterics{}'.format(lambda_var_suffixes[0])].extend(all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces) + else: + forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])] = all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces + forces_by_lambda['lambda_sterics{}'.format(lambda_var_suffixes[0])] = all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces + + if use_exact_pme_treatment: + forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])].append(nonbonded_force) + else: + forces_by_lambda[''] = [nonbonded_force] + return forces_by_lambda + + def _alchemically_modify_AmoebaMultipoleForce(self, reference_force, alchemical_region, _): + if len(alchemical_region) > 1: + raise NotImplementedError("Multiple regions does not work with AmoebaMultipoleForce") + else: + alchemical_region = alchemical_region[0] + raise Exception("Not implemented; needs CustomMultipleForce") + + def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region, _): + """Create alchemically-modified version of AmoebaVdwForce. + + Not implemented. + + TODO + ---- + * Supported periodic boundary conditions need to be handled correctly. + * Exceptions/exclusions need to be dealt with. + + """ + # This feature is incompletely implemented, so raise an exception. + if len(alchemical_region) > 1: + raise NotImplementedError("Multiple regions does not work with AmoebaVdwForce") + else: + alchemical_region = alchemical_region[0] + raise NotImplementedError('Alchemical modification of Amoeba VdW Forces is not supported.') + + # Softcore Halgren potential from Eq. 3 of + # Shi, Y., Jiao, D., Schnieders, M.J., and Ren, P. (2009). Trypsin-ligand binding free + # energy calculation with AMOEBA. Conf Proc IEEE Eng Med Biol Soc 2009, 2328-2331. + energy_expression = 'lambda^5 * epsilon * (1.07^7 / (0.7*(1-lambda)^2+(rho+0.07)^7)) * (1.12 / (0.7*(1-lambda)^2 + rho^7 + 0.12) - 2);' + energy_expression += 'epsilon = 4*epsilon1*epsilon2 / (sqrt(epsilon1) + sqrt(epsilon2))^2;' + energy_expression += 'rho = r / R0;' + energy_expression += 'R0 = (R01^3 + R02^3) / (R01^2 + R02^2);' + energy_expression += 'lambda = vdw_lambda * (ligand1*(1-ligand2) + ligand2*(1-ligand1)) + ligand1*ligand2;' + energy_expression += 'vdw_lambda = %f;' % vdw_lambda + + softcore_force = openmm.CustomNonbondedForce(energy_expression) + softcore_force.addPerParticleParameter('epsilon') + softcore_force.addPerParticleParameter('R0') + softcore_force.addPerParticleParameter('ligand') + + for particle_index in range(system.getNumParticles()): + # Retrieve parameters from vdW force. + [parentIndex, sigma, epsilon, reductionFactor] = force.getParticleParameters(particle_index) + # Add parameters to CustomNonbondedForce. + if particle_index in alchemical_region.alchemical_atoms: + softcore_force.addParticle([epsilon, sigma, 1]) + else: + softcore_force.addParticle([epsilon, sigma, 0]) + + # Deal with exclusions. + excluded_atoms = force.getParticleExclusions(particle_index) + for jatom in excluded_atoms: + if (particle_index < jatom): + softcore_force.addExclusion(particle_index, jatom) + + # Make sure periodic boundary conditions are treated the same way. + # TODO: Handle PBC correctly. + softcore_force.setNonbondedMethod( openmm.CustomNonbondedForce.CutoffPeriodic ) + softcore_force.setCutoffDistance( force.getCutoff() ) + + # Turn off vdW interactions for alchemically-modified atoms. + for particle_index in ligand_atoms: + # Retrieve parameters. + [parentIndex, sigma, epsilon, reductionFactor] = force.getParticleParameters(particle_index) + epsilon = 1.0e-6 * epsilon # TODO: For some reason, we cannot set epsilon to 0. + force.setParticleParameters(particle_index, parentIndex, sigma, epsilon, reductionFactor) + + # Deal with exceptions here. + # TODO + + return [softcore_force] + + @staticmethod + def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, _, sasa_model='ACE'): + """Create alchemically-modified version of GBSAOBCForce. + + Parameters + ---------- + reference_force : simtk.openmm.GBSAOBCForce + The reference GBSAOBCForce to be alchemically modify. + alchemical_region : AlchemicalRegion + The alchemical region containing the indices of the atoms to + alchemically modify. + sasa_model : str, optional, default='ACE' + Solvent accessible surface area model. + + Returns + ------- + custom_force : simtk.openmm.CustomGBForce + The alchemical version of the reference force. + + TODO + ---- + * Add support for all types of GBSA forces supported by OpenMM. + * Can we more generally modify any CustomGBSAForce? + + """ + if len(alchemical_region) > 1: + raise NotImplementedError("Multiple regions does not work with GBSAOBCForce") + else: + alchemical_region = alchemical_region[0] + + # TODO make sasa_model a Factory attribute? + custom_force = openmm.CustomGBForce() + + # Add per-particle parameters. + custom_force.addGlobalParameter("lambda_electrostatics", 1.0) + custom_force.addPerParticleParameter("charge") + custom_force.addPerParticleParameter("radius") + custom_force.addPerParticleParameter("scale") + custom_force.addPerParticleParameter("alchemical") + + # Set nonbonded method. + custom_force.setNonbondedMethod(reference_force.getNonbondedMethod()) + custom_force.setCutoffDistance(reference_force.getCutoffDistance()) + + # Add global parameters. + custom_force.addGlobalParameter("solventDielectric", reference_force.getSolventDielectric()) + custom_force.addGlobalParameter("soluteDielectric", reference_force.getSoluteDielectric()) + custom_force.addGlobalParameter("offset", 0.009) + + custom_force.addComputedValue("I", "(lambda_electrostatics*alchemical2 + (1-alchemical2))*step(r+sr2-or1)*0.5*(1/L-1/U+0.25*(r-sr2^2/r)*(1/(U^2)-1/(L^2))+0.5*log(L/U)/r+C);" + "U=r+sr2;" + "C=2*(1/or1-1/L)*step(sr2-r-or1);" + "L=max(or1, D);" + "D=abs(r-sr2);" + "sr2 = scale2*or2;" + "or1 = radius1-offset; or2 = radius2-offset", openmm.CustomGBForce.ParticlePairNoExclusions) + + custom_force.addComputedValue("B", "1/(1/or-tanh(psi-0.8*psi^2+4.85*psi^3)/radius);" + "psi=I*or; or=radius-offset", openmm.CustomGBForce.SingleParticle) + + custom_force.addEnergyTerm("-0.5*138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical+(1-alchemical))*charge^2/B", openmm.CustomGBForce.SingleParticle) + if sasa_model == 'ACE': + custom_force.addEnergyTerm("(lambda_electrostatics*alchemical+(1-alchemical))*28.3919551*(radius+0.14)^2*(radius/B)^6", openmm.CustomGBForce.SingleParticle) + + custom_force.addEnergyTerm("-138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical1+(1-alchemical1))*charge1*(lambda_electrostatics*alchemical2+(1-alchemical2))*charge2/f;" + "f=sqrt(r^2+B1*B2*exp(-r^2/(4*B1*B2)))", openmm.CustomGBForce.ParticlePairNoExclusions); + + # Add particle parameters. + for particle_index in range(reference_force.getNumParticles()): + # Retrieve parameters. + [charge, radius, scaling_factor] = reference_force.getParticleParameters(particle_index) + # Set particle parameters. + if particle_index in alchemical_region.alchemical_atoms: + parameters = [charge, radius, scaling_factor, 1.0] + else: + parameters = [charge, radius, scaling_factor, 0.0] + custom_force.addParticle(parameters) + + return {'lambda_electrostatics': [custom_force]} + + def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region, _): + """Create alchemically-modified version of CustomGBForce. + + The GB functions are meta-programmed using the following rules: + - 'lambda_electrostatics' is added as a global parameter. + - 'alchemical' is added as a per-particle parameter. All atoms in + the alchemical group have this parameter set to 1; otherwise 0. + - Any single-particle energy term (`CustomGBForce.SingleParticle`) + is scaled by `(lambda_electrostatics*alchemical+(1-alchemical))` + - Any two-particle energy term (`CustomGBForce.ParticlePairNoExclusions`) + has charge 1 (`charge1`) replaced by `(lambda_electrostatics*alchemical1+(1-alchemical1))*charge1` + and charge 2 (`charge2`) replaced by `(lambda_electrostatics*alchemical2+(1-alchemical2))*charge2`. + - Any single-particle computed value (`CustomGBForce.SingleParticle`) + remains unmodified + - Any two-particle computed value (`CustomGBForce.ParticlePairNoExclusions`) + is scaled by `(lambda_electrostatics*alchemical2 + (1-alchemical2))` + + Scaling of a term should always prepend and capture the value with + an intermediate variable. For example, prepending `scaling * unscaled; unscaled =` + will capture the value of the expression as `unscaled` and multiple by `scaled`. + This avoids the need to identify the head expression and add parentheses. + + .. warning:: + This may not work correctly for all GB models. + + Parameters + ---------- + reference_force : simtk.openmm.GBSAOBCForce + The reference GBSAOBCForce to be alchemically modify. + alchemical_region : AlchemicalRegion + The alchemical region containing the indices of the atoms to + alchemically modify. + + Returns + ------- + custom_force : simtk.openmm.CustomGBForce + The alchemical version of the reference force. + + """ + if len(alchemical_region) > 1: + raise NotImplementedError("Multiple regions does not work with CustomGBForce") + else: + alchemical_region = alchemical_region[0] + + custom_force = openmm.CustomGBForce() + + # Add global parameters + for index in range(reference_force.getNumGlobalParameters()): + name = reference_force.getGlobalParameterName(index) + default_value = reference_force.getGlobalParameterDefaultValue(index) + custom_force.addGlobalParameter(name, default_value) + custom_force.addGlobalParameter("lambda_electrostatics", 1.0) + + # Add per-particle parameters. + for index in range(reference_force.getNumPerParticleParameters()): + name = reference_force.getPerParticleParameterName(index) + custom_force.addPerParticleParameter(name) + custom_force.addPerParticleParameter("alchemical") + + # Set nonbonded methods. + custom_force.setNonbondedMethod(reference_force.getNonbondedMethod()) + custom_force.setCutoffDistance(reference_force.getCutoffDistance()) + + # Add computations. + for index in range(reference_force.getNumComputedValues()): + name, expression, computation_type = reference_force.getComputedValueParameters(index) + + # Alter expression for particle pair terms only. + if computation_type is not openmm.CustomGBForce.SingleParticle: + prepend = ('alchemical_scaling*unscaled; ' + 'alchemical_scaling = (lambda_electrostatics*alchemical2 + (1-alchemical2)); ' + 'unscaled = ') + expression = prepend + expression + + custom_force.addComputedValue(name, expression, computation_type) + + # Add energy terms. + for index in range(reference_force.getNumEnergyTerms()): + expression, computation_type = reference_force.getEnergyTermParameters(index) + + # Alter expressions + if computation_type is openmm.CustomGBForce.SingleParticle: + prepend = ('alchemical_scaling*unscaled; ' + 'alchemical_scaling = (lambda_electrostatics*alchemical + (1-alchemical)); ' + 'unscaled = ') + expression = prepend + expression + else: + expression = expression.replace('charge1', 'alchemically_scaled_charge1') + expression = expression.replace('charge2', 'alchemically_scaled_charge2') + expression += ' ; alchemically_scaled_charge1 = (lambda_electrostatics*alchemical1+(1-alchemical1)) * charge1;' + expression += ' ; alchemically_scaled_charge2 = (lambda_electrostatics*alchemical2+(1-alchemical2)) * charge2;' + + custom_force.addEnergyTerm(expression, computation_type) + + # Add particle parameters + for particle_index in range(reference_force.getNumParticles()): + parameters = reference_force.getParticleParameters(particle_index) + # Append alchemical parameter + parameters = list(parameters) + if particle_index in alchemical_region.alchemical_atoms: + parameters.append(1.0) + else: + parameters.append(0.0) + custom_force.addParticle(parameters) + + # Add tabulated functions + for function_index in range(reference_force.getNumTabulatedFunctions()): + name = reference_force.getTabulatedFunctionName(function_index) + function = reference_force.getTabulatedFunction(function_index) + function_copy = copy.deepcopy(function) + custom_force.addTabulatedFunction(name, function_copy) + + # Add exclusions + for exclusion_index in range(reference_force.getNumExclusions()): + [particle1, particle2] = reference_force.getExclusionParticles(exclusion_index) + custom_force.addExclusion(particle1, particle2) + + return {'lambda_electrostatics': [custom_force]} + + # ------------------------------------------------------------------------- + # Internal usage: Infer force labels + # ------------------------------------------------------------------------- + + @staticmethod + def _find_force_components(alchemical_system): + """Return force labels and indices for each force.""" + def add_label(label, index): + assert label not in force_labels + force_labels[label] = index + + def check_parameter(custom_force, parameter): + for parameter_id in range(custom_force.getNumGlobalParameters()): + parameter_name = custom_force.getGlobalParameterName(parameter_id) + if parameter == parameter_name: + return True + return False + + def check_energy_expression(custom_force, parameter): + try: + found = parameter in custom_force.getEnergyFunction() + except AttributeError: # CustomGBForce + found = False + for index in range(custom_force.getNumEnergyTerms()): + expression, _ = custom_force.getEnergyTermParameters(index) + if parameter in expression: + found = True + break + return found + + force_labels = {} + nonbonded_forces = {'' :[], 'zero': [], 'one': [], 'two': []} + sterics_bond_forces = {'' :[], 'zero': [], 'one': [], 'two': []} + electro_bond_forces = {'' :[], 'zero': [], 'one': [], 'two': []} + + # We save CustomBondForces and CustomNonbondedForces used for nonbonded + # forces and exceptions to distinguish them later + for force_index, force in enumerate(alchemical_system.getForces()): + if isinstance(force, openmm.CustomAngleForce) and check_energy_expression(force, 'lambda_angles'): + if check_parameter(force, 'lambda_angles_zero'): + add_label('alchemically modified HarmonicAngleForce for region zero', force_index) + elif check_parameter(force, 'lambda_angles_one'): + add_label('alchemically modified HarmonicAngleForce for region one', force_index) + elif check_parameter(force, 'lambda_angles_two'): + add_label('alchemically modified HarmonicAngleForce for region two', force_index) + else: + add_label('alchemically modified HarmonicAngleForce', force_index) + elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda_bonds'): + if check_parameter(force, 'lambda_bonds_zero'): + add_label('alchemically modified HarmonicBondForce for region zero', force_index) + elif check_parameter(force, 'lambda_bonds_one'): + add_label('alchemically modified HarmonicBondForce for region one', force_index) + elif check_parameter(force, 'lambda_bonds_two'): + add_label('alchemically modified HarmonicBondForce for region two', force_index) + else: + add_label('alchemically modified HarmonicBondForce', force_index) + elif isinstance(force, openmm.CustomTorsionForce) and check_energy_expression(force, 'lambda_torsions'): + if check_parameter(force, 'lambda_torsions_zero'): + add_label('alchemically modified PeriodicTorsionForce for region zero', force_index) + elif check_parameter(force, 'lambda_torsions_one'): + add_label('alchemically modified PeriodicTorsionForce for region one', force_index) + elif check_parameter(force, 'lambda_torsions_two'): + add_label('alchemically modified PeriodicTorsionForce for region two', force_index) + else: + add_label('alchemically modified PeriodicTorsionForce', force_index) + elif isinstance(force, openmm.CustomGBForce) and check_parameter(force, 'lambda_electrostatics'): + if check_energy_expression(force, 'unscaled'): + add_label('alchemically modified CustomGBForce', force_index) + else: + add_label('alchemically modified GBSAOBCForce', force_index) + elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda'): + if check_energy_expression(force, 'lambda_sterics'): + if check_energy_expression(force, 'lambda_sterics_zero'): + sterics_bond_forces['zero'].append([force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_one'): + sterics_bond_forces['one'].append([force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_two'): + sterics_bond_forces['two'].append([force_index, force]) + else: + sterics_bond_forces[''].append([force_index, force]) + if check_energy_expression(force, 'lambda_electrostatics'): + if check_energy_expression(force, 'lambda_electrostatics_zero'): + electro_bond_forces['zero'].append([force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_one'): + electro_bond_forces['one'].append([force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_two'): + electro_bond_forces['two'].append([force_index, force]) + else: + electro_bond_forces[''].append([force_index, force]) + elif (isinstance(force, openmm.CustomNonbondedForce) and force.getEnergyFunction() == '0.0;' and + force.getGlobalParameterName(0) == 'lambda_electrostatics'): + add_label('CustomNonbondedForce holding alchemical atoms unmodified charges', force_index) + elif isinstance(force, openmm.CustomNonbondedForce) and check_energy_expression(force, 'lambda'): + if check_energy_expression(force, 'lambda_sterics'): + if check_energy_expression(force, 'lambda_sterics_zero'): + nonbonded_forces['zero'].append(['sterics', force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_one'): + nonbonded_forces['one'].append(['sterics', force_index, force]) + elif check_energy_expression(force, 'lambda_sterics_two'): + nonbonded_forces['two'].append(['sterics', force_index, force]) + else: + nonbonded_forces[''].append(['sterics', force_index, force]) + if check_energy_expression(force, 'lambda_electrostatics'): + if check_energy_expression(force, 'lambda_electrostatics_zero'): + nonbonded_forces['zero'].append(['electrostatics', force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_one'): + nonbonded_forces['one'].append(['electrostatics',force_index, force]) + elif check_energy_expression(force, 'lambda_electrostatics_two'): + nonbonded_forces['two'].append(['electrostatics', force_index, force]) + else: + nonbonded_forces[''].append(['electrostatics', force_index, force]) + else: + add_label('unmodified ' + force.__class__.__name__, force_index) + + # Differentiate between na/aa nonbonded forces. + alchemical_atoms_by_region = {} + for region_name, forces in nonbonded_forces.items(): + for force_type, force_index, force in forces: + if region_name == '': + label = 'alchemically modified NonbondedForce for {}alchemical/alchemical ' + force_type + else: + label = 'alchemically modified NonbondedForce for {}alchemical/alchemical ' + force_type +\ + ' for region ' + region_name + interacting_atoms, alchemical_atoms = force.getInteractionGroupParameters(0) + alchemical_atoms_by_region[region_name] = [interacting_atoms, alchemical_atoms] + if interacting_atoms == alchemical_atoms: # alchemical-alchemical atoms + add_label(label.format(''), force_index) + else: + add_label(label.format('non-'), force_index) + + # Differentiate between na/aa bond forces for exceptions. + for (region_name, sterics_forces), electro_forces in zip(sterics_bond_forces.items(), electro_bond_forces.values()): + if len(sterics_forces) == 0: + continue + for force_type, bond_forces in [('sterics', sterics_forces), ('electrostatics', electro_forces)]: + # With exact PME there are no CustomBondForces modeling electrostatics exceptions. + if force_type == 'electrostatics' and len(bond_forces) == 0: + continue + # Otherwise there should be two CustomBondForce. + assert len(bond_forces) == 2 + if region_name == '': + label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type + ' exceptions' + else: + label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type +\ + ' exceptions for region ' + region_name + + # Sort forces by number of bonds. + bond_forces = sorted(bond_forces, key=lambda x: x[1].getNumBonds()) + (force_index1, force1), (force_index2, force2) = bond_forces + + # Check if both define their parameters (with decoupling the lambda + # parameter doesn't exist in the alchemical-alchemical force) + parameter_name = 'lambda_' + force_type + '_{}'.format(region_name) + interacting_atoms, alchemical_atoms = alchemical_atoms_by_region[region_name] + + if check_parameter(force1, parameter_name) != check_parameter(force2, parameter_name): + if check_parameter(force1, parameter_name): + add_label(label.format('non-'), force_index1) + add_label(label.format(''), force_index2) + else: + add_label(label.format(''), force_index1) + add_label(label.format('non-'), force_index2) + + # If they are both empty they are identical and any label works. + elif force1.getNumBonds() == 0 and force2.getNumBonds() == 0: + add_label(label.format(''), force_index1) + add_label(label.format('non-'), force_index2) + + # We check that the bond atoms are both alchemical or not. + else: + atom_i, atom_j, _ = force2.getBondParameters(0) + both_alchemical = atom_i in alchemical_atoms and atom_j in alchemical_atoms + if both_alchemical: + add_label(label.format(''), force_index2) + add_label(label.format('non-'), force_index1) + else: + add_label(label.format('non-'), force_index2) + add_label(label.format(''), force_index1) + return force_labels + + +if __name__ == '__main__': + import doctest + doctest.testmod() + # doctest.run_docstring_examples(AlchemicalFunction, globals()) From 1b88dc9f92ca99e51cc9d4fd0cf91d6e3ea4cab9 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Tue, 15 Oct 2019 11:11:53 +0100 Subject: [PATCH 100/152] Delete alchemy.py --- alchemy.py | 2503 ---------------------------------------------------- 1 file changed, 2503 deletions(-) delete mode 100644 alchemy.py diff --git a/alchemy.py b/alchemy.py deleted file mode 100644 index 3af02de28..000000000 --- a/alchemy.py +++ /dev/null @@ -1,2503 +0,0 @@ -#!/usr/bin/python - -# ============================================================================= -# MODULE DOCSTRING -# ============================================================================= - -""" -Alchemical factory for free energy calculations that operates directly on OpenMM System objects. - -DESCRIPTION - -This module contains enumerative factories for generating alchemically-modified System objects -usable for the calculation of free energy differences of hydration or ligand binding. - -* `AbsoluteAlchemicalFactory` uses fused elecrostatic and steric alchemical modifications. - -""" - -# TODO -# - Generalize treatment of nonbonded sterics/electrostatics intra-alchemical -# forces to support arbitrary mixing rules. Can we eliminate decoupling to something simpler? -# - Add support for other GBSA models. -# - Add functions for the automatic optimization of alchemical states? -# - Can we store serialized form of Force objects so that we can save time in reconstituting -# Force objects when we make copies? We can even manipulate the XML representation directly. -# - Allow protocols to automatically be resized to arbitrary number of states, to -# allow number of states to be enlarged to be an integral multiple of number of GPUs. -# - Finish AMOEBA support. -# - Can alchemically-modified System objects share unmodified Force objects to avoid overhead -# of duplicating Forces that are not modified? -# - Add support for arbitrary softcore reprogramming of all Custom*Force classes - - -# ============================================================================= -# GLOBAL IMPORTS -# ============================================================================= -import copy -import logging -import collections -import itertools - -import numpy as np -from simtk import openmm, unit - -from openmmtools import states, forcefactories, utils -from openmmtools.constants import ONE_4PI_EPS0 - -logger = logging.getLogger(__name__) - - -# ============================================================================= -# ALCHEMICAL STATE -# ============================================================================= - -class AlchemicalStateError(states.GlobalParameterError): - """Error raised by an AlchemicalState.""" - pass - - -class AlchemicalFunction(states.GlobalParameterFunction): - """A function of alchemical variables. - - Parameters - ---------- - expression : str - A mathematical expression involving alchemical variables. - - Examples - -------- - >>> alchemical_state = AlchemicalState(lambda_sterics=1.0, lambda_angles=1.0) - >>> alchemical_state.set_alchemical_variable('lambda', 0.5) - >>> alchemical_state.set_alchemical_variable('lambda2', 1.0) - >>> alchemical_state.lambda_sterics = AlchemicalFunction('lambda**2') - >>> alchemical_state.lambda_sterics - 0.25 - >>> alchemical_state.lambda_angles = AlchemicalFunction('(lambda + lambda2) / 2') - >>> alchemical_state.lambda_angles - 0.75 - - """ - # This class just provides an alternative name to GlobalParameterFunction. - pass - - -class AlchemicalState(states.GlobalParameterState): - """Represent an alchemical state. - - The alchemical parameters modify the Hamiltonian and affect the - computation of the energy. Alchemical parameters that have value - None are considered undefined, which means that applying this - state to System and Context that have that parameter as a global - variable will raise an AlchemicalStateError. - - Parameters - ---------- - parameters_name_suffix : str, optional - If specified, the state will control a modified version of the global - parameters with the name ``parameter_name + '_' + parameters_name_suffix``. - When this is the case, the normal parameters are not accessible. - lambda_sterics : float, optional - Scaling factor for ligand sterics (Lennard-Jones and Halgren) - interactions (default is 1.0). - lambda_electrostatics : float, optional - Scaling factor for ligand charges, intrinsic Born radii, and surface - area term (default is 1.0). - lambda_bonds : float, optional - Scaling factor for alchemically-softened bonds (default is 1.0). - lambda_angles : float, optional - Scaling factor for alchemically-softened angles (default is 1.0). - lambda_torsions : float, optional - Scaling factor for alchemically-softened torsions (default is 1.0). - - Attributes - ---------- - lambda_sterics - lambda_electrostatics - lambda_bonds - lambda_angles - lambda_torsions - - Examples - -------- - Create an alchemically modified system. - - >>> from openmmtools import testsystems - >>> factory = AbsoluteAlchemicalFactory(consistent_exceptions=False) - >>> alanine_vacuum = testsystems.AlanineDipeptideVacuum().system - >>> alchemical_region = AlchemicalRegion(alchemical_atoms=range(22)) - >>> alanine_alchemical_system = factory.create_alchemical_system(reference_system=alanine_vacuum, - ... alchemical_regions=alchemical_region) - - Create a completely undefined alchemical state. - - >>> alchemical_state = AlchemicalState() - >>> print(alchemical_state.lambda_sterics) - None - >>> alchemical_state.apply_to_system(alanine_alchemical_system) - Traceback (most recent call last): - ... - openmmtools.alchemy.AlchemicalStateError: The system parameter lambda_electrostatics is not defined in this state. - - Create an AlchemicalState that matches the parameters defined in - the System. - - >>> alchemical_state = AlchemicalState.from_system(alanine_alchemical_system) - >>> alchemical_state.lambda_sterics - 1.0 - >>> alchemical_state.lambda_electrostatics - 1.0 - >>> print(alchemical_state.lambda_angles) - None - - AlchemicalState implement the IComposableState interface, so it can be - used with CompoundThermodynamicState. All the alchemical parameters are - accessible through the compound state. - - >>> from simtk import openmm, unit - >>> thermodynamic_state = states.ThermodynamicState(system=alanine_alchemical_system, - ... temperature=300*unit.kelvin) - >>> compound_state = states.CompoundThermodynamicState(thermodynamic_state=thermodynamic_state, - ... composable_states=[alchemical_state]) - >>> compound_state.lambda_sterics - 1.0 - - You can control the parameters in the OpenMM Context in this state by - setting the state attributes. - - >>> compound_state.lambda_sterics = 0.5 - >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) - >>> context = compound_state.create_context(integrator) - >>> context.getParameter('lambda_sterics') - 0.5 - >>> compound_state.lambda_sterics = 1.0 - >>> compound_state.apply_to_context(context) - >>> context.getParameter('lambda_sterics') - 1.0 - - You can express the alchemical parameters as a mathematical expression - involving alchemical variables. Here is an example for a two-stage function. - - >>> compound_state.set_alchemical_variable('lambda', 1.0) - >>> compound_state.lambda_sterics = AlchemicalFunction('step_hm(lambda - 0.5) + 2*lambda * step_hm(0.5 - lambda)') - >>> compound_state.lambda_electrostatics = AlchemicalFunction('2*(lambda - 0.5) * step(lambda - 0.5)') - >>> for l in [0.0, 0.25, 0.5, 0.75, 1.0]: - ... compound_state.set_alchemical_variable('lambda', l) - ... print(compound_state.lambda_sterics) - 0.0 - 0.5 - 1.0 - 1.0 - 1.0 - - """ - - _GLOBAL_PARAMETER_ERROR = AlchemicalStateError - - # ------------------------------------------------------------------------- - # Lambda properties - # ------------------------------------------------------------------------- - - class _LambdaParameter(states.GlobalParameterState.GlobalParameter): - """A global parameter in the interval [0, 1] with standard value 1.""" - - def __init__(self, parameter_name): - super().__init__(parameter_name, standard_value=1.0, validator=self.lambda_validator) - - @staticmethod - def lambda_validator(self, instance, parameter_value): - if parameter_value is None: - return parameter_value - if not (0.0 <= parameter_value <= 1.0): - raise ValueError('{} must be between 0 and 1.'.format(self.parameter_name)) - return float(parameter_value) - - lambda_sterics = _LambdaParameter('lambda_sterics') - lambda_electrostatics = _LambdaParameter('lambda_electrostatics') - lambda_bonds = _LambdaParameter('lambda_bonds') - lambda_angles = _LambdaParameter('lambda_angles') - lambda_torsions = _LambdaParameter('lambda_torsions') - - @classmethod - def from_system(cls, system, *args, **kwargs): - """Constructor reading the state from an alchemical system. - - Parameters - ---------- - system : simtk.openmm.System - An alchemically modified system in a defined alchemical state. - parameters_name_suffix : str, optional - If specified, the state will search for a modified - version of the alchemical parameters with the name - ``parameter_name + '_' + parameters_name_suffix``. - - Returns - ------- - The AlchemicalState object representing the alchemical state of - the system. - - Raises - ------ - AlchemicalStateError - If the same parameter has different values in the system, or - if the system has no lambda parameters. - - """ - # The function is redefined here only to provide more specific documentation for this method. - return super().from_system(system, *args, **kwargs) - - def set_alchemical_parameters(self, new_value): - """Set all defined lambda parameters to the given value. - - The undefined parameters (i.e. those being set to None) remain - undefined. - - Parameters - ---------- - new_value : float - The new value for all defined parameters. - - """ - for parameter_name in self._parameters: - if self._parameters[parameter_name] is not None: - setattr(self, parameter_name, new_value) - - # ------------------------------------------------------------------------- - # Function variables - # ------------------------------------------------------------------------- - - def get_function_variable(self, variable_name): - """Return the value of the function variable. - - Function variables are variables entering mathematical expressions - specified with ``AlchemicalFunction``, which can be use to enslave - a lambda parameter to arbitrary variables. - - Parameters - ---------- - variable_name : str - The name of the function variable. - - Returns - ------- - variable_value : float - The value of the function variable. - - """ - # The function is redefined here only to provide more specific documentation for this method. - return super().get_function_variable(variable_name) - - def set_function_variable(self, variable_name, new_value): - """Set the value of the function variable. - - Function variables are variables entering mathematical expressions - specified with ``AlchemicalFunction``, which can be use to enslave - a lambda parameter to arbitrary variables. - - Parameters - ---------- - variable_name : str - The name of the function variable. - new_value : float - The new value for the variable. - - """ - # The function is redefined here only to provide more specific documentation for this method. - super().set_function_variable(variable_name, new_value) - - def get_alchemical_variable(self, variable_name): - """Return the value of the alchemical parameter. - - .. warning: - This is deprecated. Use ``get_function_variable`` instead. - - Parameters - ---------- - variable_name : str - The name of the alchemical variable. - - Returns - ------- - variable_value : float - The value of the alchemical variable. - """ - import warnings - warnings.warn('AlchemicalState.get_alchemical_variable is deprecated. ' - 'Use AlchemicalState.get_function_variable instead.') - return super().get_function_variable(variable_name) - - def set_alchemical_variable(self, variable_name, new_value): - """Set the value of the alchemical variable. - - .. warning: - This is deprecated. Use ``set_function_variable`` instead. - - Parameters - ---------- - variable_name : str - The name of the alchemical variable. - new_value : float - The new value for the variable. - - """ - import warnings - warnings.warn('AlchemicalState.get_alchemical_variable is deprecated. ' - 'Use AlchemicalState.get_function_variable instead.') - super().set_function_variable(variable_name, new_value) - - # ------------------------------------------------------------------------- - # IComposableState interface - # ------------------------------------------------------------------------- - - def apply_to_system(self, system): - """Set the alchemical state of the system to this. - - Parameters - ---------- - system : simtk.openmm.System - The system to modify. - - Raises - ------ - AlchemicalStateError - If the system does not have the required lambda global variables. - - """ - # The function is redefined here only to provide more specific documentation for this method. - super().apply_to_system(system) - - def check_system_consistency(self, system): - """Check if the system is in this alchemical state. - - It raises a AlchemicalStateError if the system is not consistent - with the alchemical state. - - Parameters - ---------- - system : simtk.openmm.System - The system to test. - - Raises - ------ - AlchemicalStateError - If the system is not consistent with this state. - - """ - # The function is redefined here only to provide more specific documentation for this method. - super().check_system_consistency(system) - - def apply_to_context(self, context): - """Put the Context into this AlchemicalState. - - Parameters - ---------- - context : simtk.openmm.Context - The context to set. - - Raises - ------ - AlchemicalStateError - If the context does not have the required lambda global variables. - - """ - # The function is redefined here only to provide more specific documentation for this method. - super().apply_to_context(context) - - -# ============================================================================= -# ALCHEMICAL REGION -# ============================================================================= - -_ALCHEMICAL_REGION_ARGS = collections.OrderedDict([ - ('alchemical_atoms', None), - ('alchemical_bonds', None), - ('alchemical_angles', None), - ('alchemical_torsions', None), - ('annihilate_electrostatics', True), - ('annihilate_sterics', False), - ('softcore_alpha', 0.5), ('softcore_a', 1), ('softcore_b', 1), ('softcore_c', 6), - ('softcore_beta', 0.0), ('softcore_d', 1), ('softcore_e', 1), ('softcore_f', 2), - ('name', None) -]) - - -# The class is just a way to document the namedtuple. -class AlchemicalRegion(collections.namedtuple('AlchemicalRegion', _ALCHEMICAL_REGION_ARGS.keys())): - """Alchemical region. - - This is a namedtuple used to tell the AbsoluteAlchemicalFactory which - region of the system to alchemically modify and how. - - Parameters - ---------- - alchemical_atoms : list of int, optional - List of atoms to be designated for which the nonbonded forces (both - sterics and electrostatics components) have to be alchemically - modified (default is None). - alchemical_bonds : bool or list of int, optional - If a list of bond indices are specified, these HarmonicBondForce - entries are softened with 'lambda_bonds'. If set to True, this list - is auto-generated to include all bonds involving any alchemical - atoms (default is None). - alchemical_angles : bool or list of int, optional - If a list of angle indices are specified, these HarmonicAngleForce - entries are softened with 'lambda_angles'. If set to True, this - list is auto-generated to include all angles involving any alchemical - atoms (default is None). - alchemical_torsions : bool or list of int, optional - If a list of torsion indices are specified, these PeriodicTorsionForce - entries are softened with 'lambda_torsions'. If set to True, this list - is auto-generated to include al proper torsions involving any alchemical - atoms. Improper torsions are not softened (default is None). - annihilate_electrostatics : bool, optional - If True, electrostatics should be annihilated, rather than decoupled - (default is True). - annihilate_sterics : bool, optional - If True, sterics (Lennard-Jones or Halgren potential) will be annihilated, - rather than decoupled (default is False). - softcore_alpha : float, optional - Alchemical softcore parameter for Lennard-Jones (default is 0.5). - softcore_a, softcore_b, softcore_c : float, optional - Parameters modifying softcore Lennard-Jones form. Introduced in - Eq. 13 of Ref. [1] (default is 1). - softcore_beta : float, optional - Alchemical softcore parameter for electrostatics. Set this to zero - to recover standard electrostatic scaling (default is 0.0). - softcore_d, softcore_e, softcore_f : float, optional - Parameters modifying softcore electrostatics form (default is 1). - - Notes - ----- - The parameters softcore_e and softcore_f determine the effective distance - between point charges according to - - r_eff = sigma*((softcore_beta*(lambda_electrostatics-1)^softcore_e + (r/sigma)^softcore_f))^(1/softcore_f) - - References - ---------- - [1] Pham TT and Shirts MR. Identifying low variance pathways for free - energy calculations of molecular transformations in solution phase. - JCP 135:034114, 2011. http://dx.doi.org/10.1063/1.3607597 - - """ -AlchemicalRegion.__new__.__defaults__ = tuple(_ALCHEMICAL_REGION_ARGS.values()) - - -# ============================================================================= -# ABSOLUTE ALCHEMICAL FACTORY -# ============================================================================= - -class AbsoluteAlchemicalFactory(object): - """Factory of alchemically modified OpenMM Systems. - - The context parameters created are: - - softcore_alpha: factor controlling softcore lengthscale for Lennard-Jones - - softcore_beta: factor controlling softcore lengthscale for Coulomb - - softcore_a: softcore Lennard-Jones parameter from Eq. 13 of Ref [1] - - softcore_b: softcore Lennard-Jones parameter from Eq. 13 of Ref [1] - - softcore_c: softcore Lennard-Jones parameter from Eq. 13 of Ref [1] - - softcore_d: softcore electrostatics parameter - - softcore_e: softcore electrostatics parameter - - softcore_f: softcore electrostatics parameter - - Parameters - ---------- - consistent_exceptions : bool, optional, default = False - If True, the same functional form of the System's nonbonded - method will be use to determine the electrostatics contribution - to the potential energy of 1,4 exceptions instead of the - classical q1*q2/(4*epsilon*epsilon0*pi*r). - switch_width : float, optional, default = 1.0 * angstroms - Default switch width for electrostatics in periodic cutoff systems - used in alchemical interactions only. - alchemical_pme_treatment : str, optional, default = 'direct-space' - Controls how alchemical region electrostatics are treated when PME is used. - Options are ['direct-space', 'coulomb', 'exact']. - - 'direct-space' only models the direct space contribution - - 'coulomb' includes switched Coulomb interaction - - 'exact' includes also the reciprocal space contribution, but it's - only possible to annihilate the charges and the softcore parameters - controlling the electrostatics are deactivated. Also, with this - method, modifying the global variable `lambda_electrostatics` is - not sufficient to control the charges. The recommended way to change - them is through the `AlchemicalState` class. - alchemical_rf_treatment : str, optional, default = 'switched' - Controls how alchemical region electrostatics are treated when RF is used - Options are ['switched', 'shifted'] - 'switched' sets c_rf = 0 for all reaction-field interactions and ensures continuity with a switch - 'shifted' retains c_rf != 0 but can give erroneous results for hydration free energies - disable_alchemical_dispersion_correction : bool, optional, default=False - If True, the long-range dispersion correction will not be included for the alchemical - region to avoid the need to recompute the correction (a CPU operation that takes ~ 0.5 s) - every time 'lambda_sterics' is changed. If using nonequilibrium protocols, it is recommended - that this be set to True since this can lead to enormous (100x) slowdowns if the correction - must be recomputed every time step. - split_alchemical_forces : bool, optional, default=True - If True, forces that are altered to different alchemical variables - will be split in different force groups. All non-alchemical forces - will maintain their original force group. If more than 32 force - groups are required, an error is thrown. - - Examples - -------- - - Create an alchemical factory to alchemically modify OpenMM System objects. - - >>> factory = AbsoluteAlchemicalFactory(consistent_exceptions=False) - - Create an alchemically modified version of p-xylene in T4 lysozyme L99A in GBSA. - - >>> # Create a reference system. - >>> from openmmtools import testsystems - >>> reference_system = testsystems.LysozymeImplicit().system - >>> # Alchemically soften the pxylene atoms - >>> pxylene_atoms = range(2603,2621) # p-xylene - >>> alchemical_region = AlchemicalRegion(alchemical_atoms=pxylene_atoms) - >>> alchemical_system = factory.create_alchemical_system(reference_system, alchemical_region) - - Alchemically modify one water in a water box. - - >>> reference_system = testsystems.WaterBox().system - >>> alchemical_region = AlchemicalRegion(alchemical_atoms=[0, 1, 2]) - >>> alchemical_system = factory.create_alchemical_system(reference_system, alchemical_region) - - Alchemically modify some angles and torsions in alanine dipeptide and - annihilate both sterics and electrostatics. - - >>> reference_system = testsystems.AlanineDipeptideVacuum().system - >>> alchemical_region = AlchemicalRegion(alchemical_atoms=[0], alchemical_torsions=[0,1,2], - ... alchemical_angles=[0,1,2], annihilate_sterics=True, - ... annihilate_electrostatics=True) - >>> alchemical_system = factory.create_alchemical_system(reference_system, alchemical_region) - - Alchemically modify a bond, angles, and torsions in toluene by automatically - selecting bonds involving alchemical atoms. - - >>> toluene_implicit = testsystems.TolueneImplicit() - >>> alchemical_region = AlchemicalRegion(alchemical_atoms=[0,1], alchemical_torsions=True, - ... alchemical_angles=True, annihilate_sterics=True) - >>> alchemical_system = factory.create_alchemical_system(reference_system, alchemical_region) - - Once the alchemical system is created, you can modify its Hamiltonian - through AlchemicalState - - >>> alchemical_state = AlchemicalState.from_system(alchemical_system) - >>> alchemical_state.lambda_sterics - 1.0 - >>> alchemical_state.lambda_electrostatics = 0.5 - >>> alchemical_state.apply_to_system(alchemical_system) - - You can also modify its Hamiltonian directly into a context - - >>> from simtk import openmm, unit - >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) - >>> context = openmm.Context(alchemical_system, integrator) - >>> alchemical_state.set_alchemical_parameters(0.0) # Set all lambda to 0 - >>> alchemical_state.apply_to_context(context) - - Neglecting the long-range dispersion correction for the alchemical region - (for nonequilibrium switching, for example) requires instantiating a factory - with the appropriate options: - - >>> new_factory = AbsoluteAlchemicalFactory(consistent_exceptions=False, disable_alchemical_dispersion_correction=True) - >>> reference_system = testsystems.WaterBox().system - >>> alchemical_region = AlchemicalRegion(alchemical_atoms=[0, 1, 2]) - >>> alchemical_system = new_factory.create_alchemical_system(reference_system, alchemical_region) - - References - ---------- - [1] Pham TT and Shirts MR. Identifying low variance pathways for free - energy calculations of molecular transformations in solution phase. - JCP 135:034114, 2011. http://dx.doi.org/10.1063/1.3607597 - - """ - - # ------------------------------------------------------------------------- - # Public interface - # ------------------------------------------------------------------------- - - def __init__(self, consistent_exceptions=False, switch_width=1.0*unit.angstroms, - alchemical_pme_treatment='exact', alchemical_rf_treatment='switched', - disable_alchemical_dispersion_correction=False, split_alchemical_forces=True): - - self.consistent_exceptions = consistent_exceptions - self.switch_width = switch_width - self.alchemical_pme_treatment = alchemical_pme_treatment - self.alchemical_rf_treatment = alchemical_rf_treatment - self.disable_alchemical_dispersion_correction = disable_alchemical_dispersion_correction - self.split_alchemical_forces = split_alchemical_forces - - def create_alchemical_system(self, reference_system, alchemical_regions, - alchemical_regions_interactions=frozenset()): - """Create an alchemically modified version of the reference system. - - To alter the alchemical state of the returned system use AlchemicalState. - - Parameters - ---------- - reference_system : simtk.openmm.System - The system to use as a reference for the creation of the - alchemical system. This will not be modified. - alchemical_regions : AlchemicalRegion - The region of the reference system to alchemically soften. - alchemical_regions_interactions : Set[Tuple[int, int]], optional - Set of alchemical region index pairs for interacting regions. - By default, all alchemical regions interact only with the - non-alchemical environment. - - Returns - ------- - alchemical_system : simtk.openmm.System - Alchemically-modified version of reference_system. - - """ - if alchemical_regions_interactions != frozenset(): - raise NotImplementedError('Interactions between alchemical regions is untested') - - logger.debug(f'Dictionary of interacting alchemical regions: {alchemical_regions_interactions}') - if isinstance(alchemical_regions, AlchemicalRegion): - alchemical_regions = [alchemical_regions] - logger.debug(f'Using {len(alchemical_regions)} alchemical regions') - - # Resolve alchemical regions. - alchemical_regions = [self._resolve_alchemical_region(reference_system, alchemical_region) - for alchemical_region in alchemical_regions] - - # Check for duplicate alchemical atoms/bonds/angles/torsions. - all_alchemical_elements = {element_type: set() for element_type in ['atoms', 'bonds', 'angles', 'torsions']} - - for alchemical_region in alchemical_regions: - for element_type, all_elements in all_alchemical_elements.items(): - # Ignore None alchemical elements. - region_elements = getattr(alchemical_region, 'alchemical_' + element_type) - if region_elements is None: - continue - - # Check if there are duplicates with previous regions. - duplicate_elements = all_elements & region_elements - if len(duplicate_elements) > 0: - raise ValueError('Two regions have duplicate {}.'.format(element_type)) - - # Update all alchemical elements. - all_alchemical_elements[element_type].update(region_elements) - - # Check for duplicate names - alchemical_region_names = {alchemical_region.name for alchemical_region in alchemical_regions} - if len(alchemical_region_names) != len(alchemical_regions): - raise ValueError('Two alchemical regions have the same name') - - # Record timing statistics. - timer = utils.Timer() - timer.start('Create alchemically modified system') - - # Build alchemical system to modify. This copies particles, vsites, - # constraints, box vectors and all the forces. We'll later remove - # the forces that we remodel to be alchemically modified. - alchemical_system = copy.deepcopy(reference_system) - - # Check that there are no virtual sites to alchemically modify. - for alchemical_region in alchemical_regions: - for particle_index in alchemical_region.alchemical_atoms: - if reference_system.isVirtualSite(particle_index): - raise ValueError(f'Virtual atoms in region {alchemical_region.name}. ' - 'Alchemically modified virtual sites are not supported') - - # Modify forces as appropriate. We delete the forces that - # have been processed modified at the end of the for loop. - forces_to_remove = [] - alchemical_forces_by_lambda = {} - for force_index, reference_force in enumerate(reference_system.getForces()): - # TODO switch to functools.singledispatch when we drop Python2 support - reference_force_name = reference_force.__class__.__name__ - alchemical_force_creator_name = '_alchemically_modify_{}'.format(reference_force_name) - try: - alchemical_force_creator_func = getattr(self, alchemical_force_creator_name) - except AttributeError: - pass - else: - # The reference system force will be deleted. - forces_to_remove.append(force_index) - # Collect all the Force objects modeling the reference force. - alchemical_forces = alchemical_force_creator_func(reference_force, alchemical_regions, - alchemical_regions_interactions) - for lambda_variable_name, lambda_forces in alchemical_forces.items(): - try: - alchemical_forces_by_lambda[lambda_variable_name].extend(lambda_forces) - except KeyError: - alchemical_forces_by_lambda[lambda_variable_name] = lambda_forces - - # Remove original forces that have been alchemically modified. - for force_index in reversed(forces_to_remove): - alchemical_system.removeForce(force_index) - - # Add forces and split groups if necessary. - self._add_alchemical_forces(alchemical_system, alchemical_forces_by_lambda) - - # Record timing statistics. - timer.stop('Create alchemically modified system') - timer.report_timing() - - # If the System uses a NonbondedForce, replace its NonbondedForce implementation of reaction field - # with a Custom*Force implementation that uses c_rf = 0. - # NOTE: This adds an additional CustomNonbondedForce - if self.alchemical_rf_treatment == 'switched': - forcefactories.replace_reaction_field(alchemical_system, return_copy=False, - switch_width=self.switch_width) - - return alchemical_system - - @classmethod - def get_energy_components(cls, alchemical_system, alchemical_state, positions, platform=None): - """Compute potential energy of the alchemical system by Force. - - This can be useful for debug and analysis. - - Parameters - ---------- - alchemical_system : simtk.openmm.AlchemicalSystem - An alchemically modified system. - alchemical_state : AlchemicalState - The alchemical state to set the Context to. - positions : simtk.unit.Quantity of dimension (natoms, 3) - Coordinates to use for energy test (units of distance). - platform : simtk.openmm.Platform, optional - The OpenMM platform to use to compute the energy. If None, - OpenMM tries to select the fastest available. - - Returns - ------- - energy_components : dict str: simtk.unit.Quantity - A string label describing the role of the force associated to - its contribution to the potential energy. - - """ - # Find and label all forces. - force_labels = cls._find_force_components(alchemical_system) - assert len(force_labels) <= 32, ("The alchemical system has more than 32 force groups; " - "can't compute individual force component energies.") - - # Create deep copy of alchemical system. - system = copy.deepcopy(alchemical_system) - - # Separate all forces into separate force groups. - for force_index, force in enumerate(system.getForces()): - force.setForceGroup(force_index) - - # Create a Context in the given state. - integrator = openmm.VerletIntegrator(1.0 * unit.femtoseconds) - if platform is None: - context = openmm.Context(system, integrator) - else: - context = openmm.Context(system, integrator, platform) - context.setPositions(positions) - alchemical_state.apply_to_context(context) - - # Get energy components - energy_components = collections.OrderedDict() - for force_label, force_index in force_labels.items(): - energy_components[force_label] = context.getState(getEnergy=True, - groups=2**force_index).getPotentialEnergy() - - # Clean up - del context, integrator - return energy_components - - # ------------------------------------------------------------------------- - # Internal usage: AlchemicalRegion - # ------------------------------------------------------------------------- - - @classmethod - def _resolve_alchemical_region(cls, system, alchemical_region): - """Return a new AlchemicalRegion with sets of bonds/angles/torsions resolved. - - Also transform any list of indices into a frozenset. - - Parameters - ---------- - system : simtk.openmm.System - The system. - alchemical_region : AlchemicalRegion - The alchemical region of the system. - - Returns - ------- - AlchemicalRegion - A new AlchemicalRegion object in which all alchemical_X (where X is - atoms, bonds, angles, or torsions) have been converted to a frozenset - of indices that belong to the System. - - Raises - ------ - ValueError - If the indices in the AlchemicalRegion can't be found in the system. - - """ - # TODO move to AlchemicalRegion? - # TODO process also custom forces? (also in _build_alchemical_X_list methods) - # Find and cache the reference forces. - reference_forces = {force.__class__.__name__: force for force in system.getForces()} - - # Count number of particles, angles, etc. in system. Atoms - # must be processed first since the others build on that. - reference_counts = collections.OrderedDict([ - ('atom', system.getNumParticles()), - ('bond', reference_forces['HarmonicBondForce'].getNumBonds() - if 'HarmonicBondForce' in reference_forces else 0), - ('angle', reference_forces['HarmonicAngleForce'].getNumAngles() - if 'HarmonicAngleForce' in reference_forces else 0), - ('torsion', reference_forces['PeriodicTorsionForce'].getNumTorsions() - if 'PeriodicTorsionForce' in reference_forces else 0) - ]) - - # Transform named tuple to dict for easy modification. - alchemical_region = alchemical_region._asdict() - - for region in reference_counts: - region_name = 'alchemical_' + region + 's' - region_indices = alchemical_region[region_name] - - # Convert None and False to empty lists. - if region_indices is None or region_indices is False: - region_indices = set() - - # Automatically build indices list if True. - elif region_indices is True: - if reference_counts[region] == 0: - region_indices = set() - else: - # TODO switch to functools.singledispatch when drop Python2 - builder_function = getattr(cls, '_build_alchemical_{}_list'.format(region)) - region_indices = builder_function(alchemical_region['alchemical_atoms'], - reference_forces, system) - - # Convert numpy arrays to Python lists since SWIG - # have problems with np.int (see openmm#1650). - elif isinstance(region_indices, np.ndarray): - region_indices = region_indices.tolist() - - # Convert to set and update alchemical region. - region_indices = frozenset(region_indices) - alchemical_region[region_name] = region_indices - - # Check that the given indices are in the system. - indices_diff = region_indices - set(range(reference_counts[region])) - if len(indices_diff) > 0: - err_msg = 'Indices {} in {} cannot be found in the system' - raise ValueError(err_msg.format(indices_diff, region_name)) - - # Check that an alchemical region is defined. - total_alchemically_modified = 0 - for region in reference_counts: - total_alchemically_modified += len(alchemical_region['alchemical_' + region + 's']) - if total_alchemically_modified == 0: - raise ValueError('The AlchemicalRegion is empty.') - - # Return a new AlchemicalRegion with the resolved indices lists. - return AlchemicalRegion(**alchemical_region) - - @staticmethod - def _tabulate_bonds(system): - """ - Tabulate bonds for the specified system. - - Parameters - ---------- - system : simtk.openmm.System - The system for which bonds are to be tabulated. - - Returns - ------- - bonds : list of set - bonds[i] is the set of bonds to atom i - - TODO: - * Could we use a Topology object to simplify this? - - """ - bonds = [set() for _ in range(system.getNumParticles())] - - forces = {system.getForce(index).__class__.__name__: system.getForce(index) - for index in range(system.getNumForces())} - - # Process HarmonicBondForce - bond_force = forces['HarmonicBondForce'] - for bond_index in range(bond_force.getNumBonds()): - [particle1, particle2, r, K] = bond_force.getBondParameters(bond_index) - bonds[particle1].add(particle2) - bonds[particle2].add(particle1) - # Process constraints. - for constraint_index in range(system.getNumConstraints()): - [particle1, particle2, r] = system.getConstraintParameters(constraint_index) - bonds[particle1].add(particle2) - bonds[particle2].add(particle1) - - # TODO: Process CustomBondForce? - - return bonds - - @classmethod - def _build_alchemical_torsion_list(cls, alchemical_atoms, reference_forces, system): - """ - Build a list of proper torsion indices that involve any alchemical atom. - - Parameters - ---------- - alchemical_atoms : set of int - The set of alchemically modified atoms. - reference_forces : dict str: force - A dictionary of cached forces in the system accessible by names. - system : simtk.openmm.System - The system. - - Returns - ------- - torsion_list : list of int - The list of torsion indices that should be alchemically softened - - """ - - # Tabulate all bonds - bonds = cls._tabulate_bonds(system) - - def is_bonded(i, j): - if j in bonds[i]: - return True - return False - - def is_proper_torsion(i, j, k, l): - if is_bonded(i, j) and is_bonded(j, k) and is_bonded(k, l): - return True - return False - - # Create a list of proper torsions that involve any alchemical atom. - torsion_list = list() - force = reference_forces['PeriodicTorsionForce'] - for torsion_index in range(force.getNumTorsions()): - particle1, particle2, particle3, particle4, periodicity, phase, k = force.getTorsionParameters(torsion_index) - if set([particle1, particle2, particle3, particle4]).intersection(alchemical_atoms): - if is_proper_torsion(particle1, particle2, particle3, particle4): - torsion_list.append(torsion_index) - - return torsion_list - - @staticmethod - def _build_alchemical_angle_list(alchemical_atoms, reference_forces, system): - """ - Build a list of angle indices that involve any alchemical atom. - - Parameters - ---------- - alchemical_atoms : set of int - The set of alchemically modified atoms. - reference_forces : dict str: force - A dictionary of cached forces in the system accessible by names. - system : simtk.openmm.System - The system (unused). - - Returns - ------- - angle_list : list of int - The list of angle indices that should be alchemically softened - - """ - angle_list = list() - force = reference_forces['HarmonicAngleForce'] - for angle_index in range(force.getNumAngles()): - [particle1, particle2, particle3, theta0, K] = force.getAngleParameters(angle_index) - if set([particle1, particle2, particle3]).intersection(alchemical_atoms): - angle_list.append(angle_index) - - return angle_list - - @staticmethod - def _build_alchemical_bond_list(alchemical_atoms, reference_forces, system): - """ - Build a list of bond indices that involve any alchemical atom, allowing a list of bonds to override. - - Parameters - ---------- - alchemical_atoms : set of int - The set of alchemically modified atoms. - reference_forces : dict str: force - A dictionary of cached forces in the system accessible by names. - system : simtk.openmm.System - The system (unused). - - Returns - ------- - bond_list : list of int - The list of bond indices that should be alchemically softened - - """ - bond_list = list() - force = reference_forces['HarmonicBondForce'] - for bond_index in range(force.getNumBonds()): - [particle1, particle2, r, K] = force.getBondParameters(bond_index) - if set([particle1, particle2]).intersection(alchemical_atoms): - bond_list.append(bond_index) - - return bond_list - - # ------------------------------------------------------------------------- - # Internal usage: Alchemical forces - # ------------------------------------------------------------------------- - - def _add_alchemical_forces(self, alchemical_system, alchemical_forces_by_lambda): - """Add the forces to the alchemical system and eventually split the force groups.""" - # OpenMM can have a maximum of 32 groups. - available_force_groups = set(range(32)) - - # Add non-alchemical groups. New forces will have force group 0, and we don't - # want to modify the force group of forces that have been copied from the reference. - non_alchemical_forces = alchemical_forces_by_lambda.pop('', []) - for non_alchemical_force in non_alchemical_forces: - alchemical_system.addForce(non_alchemical_force) - - # Find which force groups are still available for alchemical forces. - for force in alchemical_system.getForces(): - available_force_groups.discard(force.getForceGroup()) - - # Check if there are enough force groups to split alchemical forces. - if (self.split_alchemical_forces and - len(available_force_groups) < len(alchemical_forces_by_lambda)): - raise RuntimeError('There are not enough force groups to split alchemical forces.\n' - 'Consider merging some non-alchemical forces in a single group ' - 'or set split_alchemical_forces to False.') - - # Add the alchemical forces in a deterministic way (just to be safe). - for lambda_variable in sorted(alchemical_forces_by_lambda): - if self.split_alchemical_forces: - # Assign to these forces the smallest force group index available. - force_group = min(available_force_groups) - available_force_groups.remove(force_group) - for force in alchemical_forces_by_lambda[lambda_variable]: - if self.split_alchemical_forces: - force.setForceGroup(force_group) - alchemical_system.addForce(force) - - @staticmethod - def _are_straddling_noninteracting_regions(particles, alchemical_regions, alchemical_regions_interactions): - """Test if a set of particles are in two regions simultaneously and if these regions are interacting. - - Parameters - ---------- - particles: set - Set of particles to check if they are in two noninteracting alchemical regions. - alchemical_region : AlchemicalRegion - The alchemical region containing the indices of the torsions to test. - alchemical_regions_interactions : Set[Tuple[int, int]], optional - Set of alchemical region index pairs for interacting regions. - By default, all alchemical regions interact only with the - non-alchemical environment. - - """ - for i, alchemical_region_A in enumerate(alchemical_regions): - if alchemical_region_A.alchemical_atoms.intersection(particles): - j = 0 - while j < i: - alchemical_region_B = alchemical_regions[j] - if alchemical_region_B.alchemical_atoms.intersection(particles): - if {i, j} in alchemical_regions_interactions: - return False - else: - return True - j += 1 - return False - - @classmethod - def _alchemically_modify_PeriodicTorsionForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): - """Create alchemically-modified version of PeriodicTorsionForce. - - Parameters - ---------- - reference_force : simtk.openmm.PeriodicTorsionForce - The reference PeriodicTorsionForce to be alchemically modify. - alchemical_region : AlchemicalRegion - The alchemical region containing the indices of the torsions to - alchemically modify. - alchemical_regions_interactions : Set[Tuple[int, int]], optional - Set of alchemical region index pairs for interacting regions. - By default, all alchemical regions interact only with the - non-alchemical environment. - - Returns - ------- - force : simtk.openmm.PeriodicTorsionForce - The force responsible for the non-alchemical torsions. - custom_force : simtk.openmm.CustomTorsionForce - The force responsible for the alchemically-softened torsions. - This will not be present if there are not alchemical torsions - in alchemical_region. - - """ - alchemical_forces = {} - all_alchemical_torsions = set() - - # Don't create a force if there are no alchemical torsions. - for alchemical_region in alchemical_regions: - all_alchemical_torsions.update(alchemical_region.alchemical_torsions) - if len(all_alchemical_torsions) == 0: - return {'': [copy.deepcopy(reference_force)]} - - # Create PeriodicTorsionForce to handle unmodified torsions. - force = openmm.PeriodicTorsionForce() - force.setForceGroup(reference_force.getForceGroup()) - for torsion_index in range(reference_force.getNumTorsions()): - particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters( - torsion_index) - particles = set((particle1, particle2, particle3, particle4)) - - # We don't connect through a torsion two particles that belong - # to two different and noninteracting alchemical regions. - are_straddling = cls._are_straddling_noninteracting_regions( - particles, alchemical_regions, alchemical_regions_interactions) - if (torsion_index not in all_alchemical_torsions) and (not are_straddling): - force.addTorsion(particle1, particle2, particle3, particle4, periodicity, phase, k) - - # Update the returned value with the non-alchemical force. - alchemical_forces[''] = [force] - - # Create CustomTorsionForce to handle alchemically modified torsions. - for alchemical_region in alchemical_regions: - # This region may not have torsions to modify. - if len(alchemical_region.alchemical_torsions) == 0: - continue - - # Check if the lambda variable needs a suffix to identify the region. - lambda_variable_name = 'lambda_torsions' - if alchemical_region.name is not None: - lambda_variable_name += '_' + alchemical_region.name - - # Create CustomTorsionForce to handle alchemically modified torsions. - energy_function = f"{lambda_variable_name}*k*(1+cos(periodicity*theta-phase))" - custom_force = openmm.CustomTorsionForce(energy_function) - custom_force.addGlobalParameter(lambda_variable_name, 1.0) - custom_force.addPerTorsionParameter('periodicity') - custom_force.addPerTorsionParameter('phase') - custom_force.addPerTorsionParameter('k') - - # Process reference torsions. - for torsion_index in sorted(alchemical_region.alchemical_torsions): - # Retrieve parameters. - particle1, particle2, particle3, particle4, periodicity, phase, k = reference_force.getTorsionParameters(torsion_index) - # Create torsions. - custom_force.addTorsion(particle1, particle2, particle3, particle4, [periodicity, phase, k]) - - # Update the returned value with the alchemical force. - alchemical_forces.update({lambda_variable_name: [custom_force]}) - - return alchemical_forces - - @classmethod - def _alchemically_modify_HarmonicAngleForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): - """Create alchemically-modified version of HarmonicAngleForce - - Parameters - ---------- - reference_force : simtk.openmm.HarmonicAngleForce - The reference HarmonicAngleForce to be alchemically modify. - alchemical_region : AlchemicalRegion - The alchemical region containing the indices of the angles to - alchemically modify. - alchemical_regions_interactions : Set[Tuple[int, int]], optional - Set of alchemical region index pairs for interacting regions. - By default, all alchemical regions interact only with the - non-alchemical environment. - - Returns - ------- - force : simtk.openmm.HarmonicAngleForce - The force responsible for the non-alchemical angles. - custom_force : simtk.openmm.CustomAngleForce - The force responsible for the alchemically-softened angles. - This will not be present if there are not alchemical angles - in alchemical_region. - - """ - alchemical_forces = {} - all_alchemical_angles = set() - # Don't create a force if there are no alchemical angles. - for alchemical_region in alchemical_regions: - all_alchemical_angles.update(alchemical_region.alchemical_angles) - if len(all_alchemical_angles) == 0: - return {'': [copy.deepcopy(reference_force)]} - - # Create standard HarmonicAngleForce to handle unmodified angles. - force = openmm.HarmonicAngleForce() - force.setForceGroup(reference_force.getForceGroup()) - for angle_index in range(reference_force.getNumAngles()): - [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) - particles = set((particle1, particle2, particle3)) - - # We don't connect through an angle two particles that belong - # to two different and noninteracting alchemical regions. - are_straddling = cls._are_straddling_noninteracting_regions( - particles, alchemical_regions, alchemical_regions_interactions) - if (angle_index not in all_alchemical_angles) and (not are_straddling): - force.addAngle(particle1, particle2, particle3, theta0, K) - - # Update the returned value with the non-alchemical force. - alchemical_forces[''] = [force] - - # Create CustomAngleForce to handle alchemically modified angles. - for alchemical_region in alchemical_regions: - # This region may not have angles to modify. - if len(alchemical_region.alchemical_angles) == 0: - continue - - # Check if the lambda variable needs a suffix to identify the region. - lambda_variable_name = 'lambda_angles' - if alchemical_region.name is not None: - lambda_variable_name += '_' + alchemical_region.name - - # Create CustomAngleForce to handle alchemically modified angles. - energy_function = f"{lambda_variable_name}*(K/2)*(theta-theta0)^2;" - custom_force = openmm.CustomAngleForce(energy_function) - custom_force.addGlobalParameter(lambda_variable_name, 1.0) - custom_force.addPerAngleParameter('theta0') - custom_force.addPerAngleParameter('K') - - # Process reference angles. - for angle_index in sorted(alchemical_region.alchemical_angles): - [particle1, particle2, particle3, theta0, K] = reference_force.getAngleParameters(angle_index) - custom_force.addAngle(particle1, particle2, particle3, [theta0, K]) - - # Update the returned value with the alchemical force. - alchemical_forces.update({lambda_variable_name: [custom_force]}) - - return alchemical_forces - - @classmethod - def _alchemically_modify_HarmonicBondForce(cls, reference_force, alchemical_regions, alchemical_regions_interactions): - """Create alchemically-modified version of HarmonicBondForce - - Parameters - ---------- - reference_force : simtk.openmm.HarmonicBondForce - The reference HarmonicBondForce to be alchemically modify. - alchemical_region : AlchemicalRegion - The alchemical region containing the indices of the bonds to - alchemically modify. - alchemical_regions_interactions : Set[Tuple[int, int]], optional - Set of alchemical region index pairs for interacting regions. - By default, all alchemical regions interact only with the - non-alchemical environment. - - Returns - ------- - force : simtk.openmm.HarmonicBondForce - The force responsible for the non-alchemical bonds. - custom_force : simtk.openmm.CustomBondForce - The force responsible for the alchemically-softened bonds. - This will not be present if there are not alchemical bonds - in alchemical_region. - - """ - alchemical_forces = {} - all_alchemical_bonds = set() - - # Don't create a force if there are no alchemical bonds. - for alchemical_region in alchemical_regions: - all_alchemical_bonds.update(alchemical_region.alchemical_bonds) - if len(all_alchemical_bonds) == 0: - return {'': [copy.deepcopy(reference_force)]} - - # Create standard HarmonicBondForce to handle unmodified bonds. - force = openmm.HarmonicBondForce() - force.setForceGroup(reference_force.getForceGroup()) - for bond_index in range(reference_force.getNumBonds()): - [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) - particles = set((particle1, particle2)) - - # We don't connect through a bond two particles that belong - # to two different and noninteracting alchemical regions. - are_straddling = cls._are_straddling_noninteracting_regions( - particles, alchemical_regions, alchemical_regions_interactions) - if (bond_index not in all_alchemical_bonds) and (not are_straddling): - force.addBond(particle1, particle2, theta0, K) - - # Update the returned value with the non-alchemical force. - alchemical_forces[''] = [force] - - for alchemical_region in alchemical_regions: - # This region may not have bonds to modify. - if len(alchemical_region.alchemical_bonds) == 0: - continue - - # Check if the lambda variable needs a suffix to identify the region. - lambda_variable_name = 'lambda_bonds' - if alchemical_region.name is not None: - lambda_variable_name += '_' + alchemical_region.name - - # Define force here so that it is over writen saving only one copy. - # Create CustomBondForce to handle alchemically modified bonds. - energy_function = f"{lambda_variable_name}*(K/2)*(r-r0)^2;" - custom_force = openmm.CustomBondForce(energy_function) - custom_force.addGlobalParameter(lambda_variable_name, 1.0) - custom_force.addPerBondParameter('r0') - custom_force.addPerBondParameter('K') - # Process reference bonds. - for bond_index in sorted(alchemical_region.alchemical_bonds): - [particle1, particle2, theta0, K] = reference_force.getBondParameters(bond_index) - custom_force.addBond(particle1, particle2, [theta0, K]) - - # Update the returned value with the alchemical force. - alchemical_forces.update({lambda_variable_name: [custom_force]}) - - return alchemical_forces - - def _get_sterics_energy_expressions(self, lambda_variable_suffixes): - """Return the energy expressions for sterics. - - Parameters - ---------- - lambda_variable_suffixes : List[str] - A list with suffixes for the global variable "lambda_sterics" that - will control the energy. If no suffix is necessary (i.e. there are - no multiple alchemical regions) just set lambda_variable_suffixes[0] = ''. - If the list has more than one element, the energy is controlled by - the multiplication of lambda_sterics_suffix1 * lambda_sterics_suffix2. - """ - - # Sterics mixing rules. - if lambda_variable_suffixes[0] == '': - lambda_variable_name = 'lambda_sterics' - else: - if len(lambda_variable_suffixes) > 1: - lambda_variable_name = 'lambda_sterics{0}*lambda_sterics{1}'.format( - lambda_variable_suffixes[0], lambda_variable_suffixes[1]) - else: - lambda_variable_name = 'lambda_sterics{}'.format(lambda_variable_suffixes[0]) - - sterics_mixing_rules = ('epsilon = sqrt(epsilon1*epsilon2);' # Mixing rule for epsilon. - 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. - - # Soft-core Lennard-Jones. - exceptions_sterics_energy_expression = ('U_sterics;' - 'U_sterics = (({0})^softcore_a)*4*epsilon*x*(x-1.0);' - 'x = (sigma/reff_sterics)^6;' - # Effective softcore distance for sterics. - 'reff_sterics = sigma*((softcore_alpha*(1.0-({0}))^softcore_b + (r/sigma)^softcore_c))^(1/softcore_c);')\ - .format(lambda_variable_name) - # Define energy expression for electrostatics. - return sterics_mixing_rules, exceptions_sterics_energy_expression - - def _get_electrostatics_energy_expressions(self, reference_force, lambda_variable_suffixes): - """Return the energy expressions for electrostatics. - - This private function assumes self._alchemical_pme_treatment != 'exact' - as there's no electrostatics CustomNondondedForce in this case, and - lambda_electrostatics is modeled through an offset parameter in a - NonbondedForce. - - Parameters - ---------- - lambda_variable_suffixes : List[str] - A list with suffixes for the global variable "lambda_electrostatics" that - will control the energy. If no suffix is necessary (i.e. there are - no multiple alchemical regions) just set lambda_variable_suffixes[0] = ''. - If the list has more than one element, the energy is controlled by - the multiplication of lambda_electrostatics_suffix1 * lambda_electrostatics_suffix2. - """ - if lambda_variable_suffixes[0] == '': - lambda_variable_name = 'lambda_electrostatics' - else: - if len(lambda_variable_suffixes) > 1: - lambda_variable_name = 'lambda_electrostatics{0}*lambda_electrostatics{1}'.format( - lambda_variable_suffixes[0], lambda_variable_suffixes[1]) - else: - lambda_variable_name = 'lambda_electrostatics{}'.format(lambda_variable_suffixes[0]) - - # The final expression will be prefix + method + suffix. - electrostatics_prefix = ('U_electrostatics;' - 'U_electrostatics=(({})^softcore_d)*ONE_4PI_EPS0*chargeprod').format(lambda_variable_name) - - # Effective softcore distance for electrostatics (common to all methods). - electrostatics_suffix = ('reff_electrostatics = sigma*((softcore_beta*(1.0-({0}))^softcore_e + (r/sigma)^softcore_f))^(1/softcore_f);' - 'ONE_4PI_EPS0 = {1};').format(lambda_variable_name, ONE_4PI_EPS0) # Already in OpenMM units. - - # Define mixing rules. - electrostatics_mixing_rules = ('chargeprod = charge1*charge2;' # Mixing rule for charges. - 'sigma = 0.5*(sigma1 + sigma2);') # Mixing rule for sigma. - - # Standard Coulomb expression with softened core. This is used - # - When the nonbonded method of the reference force is NoCutoff. - # - When alchemical_pme_treatment is set to 'coulomb'. - # - With 1-4 exceptions, unless self.consistent_exceptions is True. - coulomb_expression = '/reff_electrostatics;' - - # Select electrostatics functional form based on nonbonded method. - nonbonded_method = reference_force.getNonbondedMethod() - - # Soft-core Coulomb. - if nonbonded_method in [openmm.NonbondedForce.NoCutoff]: - electrostatics_method_expression = coulomb_expression - # Reaction-field electrostatics. - elif nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, openmm.NonbondedForce.CutoffNonPeriodic]: - electrostatics_method_expression = self._get_reaction_field_unique_expression(reference_force) - # PME electrostatics. - elif nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]: - # Ewald direct-space electrostatics. - if self.alchemical_pme_treatment == 'direct-space': - electrostatics_method_expression = self._get_pme_direct_space_unique_expression(reference_force) - # Use switched standard Coulomb potential, following MTS scheme described in - # http://dx.doi.org/10.1063/1.1385159 - elif self.alchemical_pme_treatment == 'coulomb': - electrostatics_method_expression = coulomb_expression - else: - raise ValueError("Unknown alchemical_pme_treatment scheme '{}'".format(self.alchemical_pme_treatment)) - else: - raise ValueError("Nonbonded method {} not supported yet.".format(nonbonded_method)) - - # Define energy expression for 1,4 electrostatic exceptions. - exceptions_electrostatics_energy_expression = electrostatics_prefix - if self.consistent_exceptions: - exceptions_electrostatics_energy_expression += electrostatics_method_expression - else: - exceptions_electrostatics_energy_expression += coulomb_expression - exceptions_electrostatics_energy_expression += electrostatics_suffix - - # Define energy expression for electrostatics. - electrostatics_energy_expression = (electrostatics_prefix + electrostatics_method_expression + - electrostatics_suffix + electrostatics_mixing_rules) - - return electrostatics_energy_expression, exceptions_electrostatics_energy_expression - - def _get_reaction_field_unique_expression(self, reference_force): - """Unique part of the expression for reaction-field electrostatics. - - Parameters - ---------- - reference_force : openmm.NonbondedForce - The reference force including the reaction-field parameters. - - Returns - ------- - rf_expression : str - The unique expression for reaction-field electrostatics. - - See Also - -------- - _get_nonbonded_energy_expressions - """ - epsilon_solvent = reference_force.getReactionFieldDielectric() - r_cutoff = reference_force.getCutoffDistance() - - # Determine reaction fields parameters. - k_rf = r_cutoff**(-3) * ((epsilon_solvent - 1) / (2*epsilon_solvent + 1)) - if self.alchemical_rf_treatment == 'switched': - c_rf = 0.0 / unit.nanometers - elif self.alchemical_rf_treatment == 'shifted': - # WARNING: Setting c_rf != 0 can cause large errors in DeltaG for hydration free energies - c_rf = r_cutoff**(-1) * ((3*epsilon_solvent) / (2*epsilon_solvent + 1)) - else: - raise ValueError("Unknown alchemical_rf_treatment scheme '{}'".format(self.alchemical_rf_treatment)) - - k_rf = k_rf.value_in_unit_system(unit.md_unit_system) - c_rf = c_rf.value_in_unit_system(unit.md_unit_system) - rf_expression = ('*(reff_electrostatics^(-1) + k_rf*reff_electrostatics^2 - c_rf);' - 'k_rf = {k_rf};' - 'c_rf = {c_rf};').format(k_rf=k_rf, c_rf=c_rf) - return rf_expression - - def _get_pme_direct_space_unique_expression(self, reference_force): - """Unique part of the expression for Ewald direct-space electrostatics. - - Parameters - ---------- - reference_force : openmm.NonbondedForce - The reference force including the Ewald parameters. - - Returns - ------- - rf_expression : str - The unique expression for Ewald direct-space electrostatics. - - See Also - -------- - _get_nonbonded_energy_expressions - """ - # Determine PME parameters. - [alpha_ewald, nx, ny, nz] = reference_force.getPMEParameters() - if (alpha_ewald/alpha_ewald.unit) == 0.0: - # If alpha is 0.0, alpha_ewald is computed by OpenMM from from the error tolerance. - tol = reference_force.getEwaldErrorTolerance() - alpha_ewald = (1.0/reference_force.getCutoffDistance()) * np.sqrt(-np.log(2.0*tol)) - - alpha_ewald = alpha_ewald.value_in_unit_system(unit.md_unit_system) - pme_expression = ("*erfc(alpha_ewald*reff_electrostatics)/reff_electrostatics;" - "alpha_ewald = {};").format(alpha_ewald) - return pme_expression - - def _alchemically_modify_NonbondedForce(self, reference_force, alchemical_regions, alchemical_regions_interactions): - """Create alchemically-modified version of NonbondedForce. - - Parameters - ---------- - reference_force : simtk.openmm.NonbondedForce - The reference NonbondedForce to be alchemically modify. - alchemical_region : AlchemicalRegion - The alchemical region containing the indices of the atoms to - alchemically modify. - alchemical_regions_interactions : Set[Tuple[int, int]], optional - Set of alchemical region index pairs for interacting regions. - By default, all alchemical regions interact only with the - non-alchemical environment. - - Returns - ------- - nonbonded_force : simtk.openmm.NonbondedForce - The force responsible for interactions and exceptions of non-alchemical atoms. - aa_sterics_custom_nonbonded_force : simtk.openmm.CustomNonbondedForce - The force responsible for sterics interactions of alchemical/alchemical atoms. - aa_electrostatics_custom_nonbonded_force : simtk.openmm.CustomNonbondedForce - The force responsible for electrostatics interactions of alchemical/alchemical - atoms. - na_sterics_custom_nonbonded_force : simtk.openmm.CustomNonbondedForce - The force responsible for sterics interactions of non-alchemical/alchemical atoms. - na_electrostatics_custom_nonbonded_force : simtk.openmm.CustomNonbondedForce - The force responsible for electrostatics interactions of non-alchemical/alchemical - atoms. - aa_sterics_custom_bond_force : simtk.openmm.CustomBondForce - The force responsible for sterics exceptions of alchemical/alchemical atoms. - aa_electrostatics_custom_bond_force : simtk.openmm.CustomBondForce - The force responsible for electrostatics exceptions of alchemical/alchemical - atoms. - na_sterics_custom_bond_force : simtk.openmm.CustomBondForce - The force responsible for sterics exceptions of non-alchemical/alchemical atoms. - na_electrostatics_custom_bond_force : simtk.openmm.CustomBondForce - The force responsible for electrostatics exceptions of non-alchemical/alchemical - atoms. - - References - ---------- - [1] Pham TT and Shirts MR. Identifying low variance pathways for free - energy calculations of molecular transformations in solution phase. - JCP 135:034114, 2011. http://dx.doi.org/10.1063/1.3607597 - - """ - # TODO Change softcore_beta to a dimensionless scalar to multiply some intrinsic length-scale, like Lennard-Jones alpha. - # TODO Try using a single, common "reff" effective softcore distance for both Lennard-Jones and Coulomb. - - forces_by_lambda = {} - all_alchemical_atoms = set() - - # Don't create a force if there are no alchemical atoms. - for alchemical_region in alchemical_regions: - if not len(alchemical_region.alchemical_atoms) == 0: - all_alchemical_atoms.update(alchemical_region.alchemical_atoms) - - # Don't create a force if there are no alchemical atoms. - if len(all_alchemical_atoms) == 0: - return {'': [copy.deepcopy(reference_force)]} - - # Create a set of all the non-alchemical atoms only. - all_atomset = set(range(reference_force.getNumParticles())) - nonalchemical_atomset = all_atomset.difference(all_alchemical_atoms) - - # ------------------------------------------------------------- - # Perform tasks that do not need to be repeated for all regions. - # ------------------------------------------------------------- - - # Define energy expression for electrostatics based on nonbonded method. - nonbonded_method = reference_force.getNonbondedMethod() - is_ewald_method = nonbonded_method in [openmm.NonbondedForce.Ewald, - openmm.NonbondedForce.PME] - is_rf_method = nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, - openmm.NonbondedForce.CutoffNonPeriodic] - is_periodic_method = is_ewald_method or nonbonded_method == openmm.NonbondedForce.CutoffPeriodic - use_exact_pme_treatment = is_ewald_method and self.alchemical_pme_treatment == 'exact' - - # Warn about reaction field. - if is_rf_method: - logger.warning('Reaction field support is still experimental. For free energy ' - 'calculations in explicit solvent, we suggest using PME for now.') - - # Check that PME treatment is supported with the region's parameters. - if use_exact_pme_treatment: - for alchemical_region in alchemical_regions: - err_msg = ' not supported with exact treatment of Ewald electrostatics.' - if not alchemical_region.annihilate_electrostatics: - raise ValueError('Decoupled electrostatics is' + err_msg) - if self.consistent_exceptions: - raise ValueError('Consistent exceptions are' + err_msg) - if (alchemical_region.softcore_beta, alchemical_region.softcore_d, alchemical_region.softcore_e) != (0, 1, 1): - raise ValueError('Softcore electrostatics is' + err_msg) - - # Create a copy of the NonbondedForce to handle particle interactions and - # 1,4 exceptions between non-alchemical/non-alchemical atoms (nn). - nonbonded_force = copy.deepcopy(reference_force) - - # Fix any issues in reference force with Lennard-Jones sigma = 0 (epsilon = 0), - # which should have sigma > 0. - for particle_index in range(reference_force.getNumParticles()): - # Retrieve parameters. - [charge, sigma, epsilon] = reference_force.getParticleParameters(particle_index) - # Check particle sigma is not zero. - if sigma == 0.0 * unit.angstrom: - warning_msg = 'particle %d has Lennard-Jones sigma = 0 (charge=%s, sigma=%s, epsilon=%s); setting sigma=1A' - logger.warning(warning_msg % (particle_index, str(charge), str(sigma), str(epsilon))) - sigma = 1.0 * unit.angstrom - # Fix it. - nonbonded_force.setParticleParameters(particle_index, charge, sigma, epsilon) - - # Same for the exceptions. - for exception_index in range(reference_force.getNumExceptions()): - # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = reference_force.getExceptionParameters(exception_index) - # Check particle sigma is not zero. - if sigma == 0.0 * unit.angstrom: - warning_msg = 'exception %d has Lennard-Jones sigma = 0 (iatom=%d, jatom=%d, chargeprod=%s, sigma=%s, epsilon=%s); setting sigma=1A' - logger.warning(warning_msg % (exception_index, iatom, jatom, str(chargeprod), str(sigma), str(epsilon))) - sigma = 1.0 * unit.angstrom - # Fix it. - nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, chargeprod, sigma, epsilon) - - if use_exact_pme_treatment: - # Exclude noninteracting alchemical regions from seeing each other in the nonbonded - for x, y in itertools.combinations(range(len(alchemical_regions)), 2): - if (x, y) not in alchemical_regions_interactions: - for atom1 in alchemical_regions[x].alchemical_atoms: - for atom2 in alchemical_regions[y].alchemical_atoms: - nonbonded_force.addException(atom1, atom2, 0.0, 1.0, 0.0, True) - else: - region_names = (alchemical_regions[x].name, alchemical_regions[y].name) - logger.debug(f'Adding a exact PME electrostatic interaction group between groups {region_names}.') - del region_names - - # With exact PME treatment, particle electrostatics is handled through offset parameters. - for alchemical_region in alchemical_regions: - if alchemical_region.name is None: - nonbonded_force.addGlobalParameter('lambda_electrostatics', 1.0) - else: - nonbonded_force.addGlobalParameter(f'lambda_electrostatics_{alchemical_region.name}', 1.0) - - # Make of list of all single and double permutations of alchemical regions. - single_regions = [[alchemical_region] for alchemical_region in alchemical_regions] - if len(alchemical_regions_interactions) == 0: - pair_regions = [] - else: - # Only generate pairs of alchemical regions specified by alchemical_regions_interactions. - pair_regions = [[alchemical_regions[x[0]], alchemical_regions[x[1]]] for x in - alchemical_regions_interactions] - - # Iterate over all single and double permutations of alchemical regions to build all interactions. - for alchemical_regions_pairs in single_regions+pair_regions: - - # Make a list of region names for the alchemical regions interactions which are being built. - lambda_var_suffixes = [] - for alchemical_region in alchemical_regions_pairs: - if alchemical_region.name is None: - lambda_var_suffixes.append('') - else: - lambda_var_suffixes.append('_' + alchemical_region.name) - - # -------------------------------------------------- - # Determine energy expression for all custom forces - # -------------------------------------------------- - - # Get steric energy expressions. - sterics_mixing_rules, exceptions_sterics_energy_expression = self._get_sterics_energy_expressions(lambda_var_suffixes) - - # Define energy expression for sterics. - sterics_energy_expression = exceptions_sterics_energy_expression + sterics_mixing_rules - - if not use_exact_pme_treatment: - # There's no CustomNonbondedForce that models electrostatics if we use exact - # PME treatment. Electrostatics is modeled through offset parameters. - energy_expressions = self._get_electrostatics_energy_expressions(reference_force, lambda_var_suffixes) - (electrostatics_energy_expression, - exceptions_electrostatics_energy_expression) = energy_expressions # Unpack tuple. - - # ------------------------------------------------------------ - # Create and configure all forces to add to alchemical system - # ------------------------------------------------------------ - - # Interactions and exceptions will be distributed according to the following table. - - # -------------------------------------------------------------------------------------------------- - # FORCE | INTERACTION GROUP | - # -------------------------------------------------------------------------------------------------- - # nonbonded_force (unmodified) | all interactions nonalchemical/nonalchemical | - # | all exceptions nonalchemical/nonalchemical | - # -------------------------------------------------------------------------------------------------- - # aa_sterics_custom_nonbonded_force | sterics interactions alchemical/alchemical | - # -------------------------------------------------------------------------------------------------- - # aa_electrostatics_custom_nonbonded_force | electrostatics interactions alchemical/alchemical | - # | (only without exact PME treatment) | - # -------------------------------------------------------------------------------------------------- - # na_sterics_custom_nonbonded_force | sterics interactions non-alchemical/alchemical | - # -------------------------------------------------------------------------------------------------- - # na_electrostatics_custom_nonbonded_force | electrostatics interactions non-alchemical/alchemical | - # | (only without exact PME treatment) | - # -------------------------------------------------------------------------------------------------- - # aa_sterics_custom_bond_force | sterics exceptions alchemical/alchemical | - # -------------------------------------------------------------------------------------------------- - # aa_electrostatics_custom_bond_force | electrostatics exceptions alchemical/alchemical | - # | (only without exact PME treatment) | - # -------------------------------------------------------------------------------------------------- - # na_sterics_custom_bond_force | sterics exceptions non-alchemical/alchemical | - # -------------------------------------------------------------------------------------------------- - # na_electrostatics_custom_bond_force | electrostatics exceptions non-alchemical/alchemical | - # | (only without exact PME treatment) | - # -------------------------------------------------------------------------------------------------- - - def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_suffixes, is_lambda_controlled): - """Shortcut to create a lambda-controlled custom forces.""" - if is_lambda_controlled: - force = force_cls(energy_expression) - for suffix in lambda_var_suffixes: - name = (lambda_variable_name + suffix) - force.addGlobalParameter(name, 1.0) - else: # fix lambda variable to 1.0 - for suffix in lambda_var_suffixes: - name = (lambda_variable_name + suffix) - energy_expression = energy_expression + name + '=1.0;' - force = force_cls(energy_expression) - return force - - # Create CustomNonbondedForces to handle sterics particle interactions between - # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda - # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(lambda_var_suffixes) > 1: - aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) - all_sterics_custom_nonbonded_forces = [aa_sterics_custom_nonbonded_force] - else: - na_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) - aa_sterics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, alchemical_region.annihilate_sterics) - all_sterics_custom_nonbonded_forces = [na_sterics_custom_nonbonded_force, aa_sterics_custom_nonbonded_force] - - # Add parameters and configure CustomNonbondedForces to match reference force. - for force in all_sterics_custom_nonbonded_forces: - force.addPerParticleParameter("sigma") # Lennard-Jones sigma - force.addPerParticleParameter("epsilon") # Lennard-Jones epsilon - force.setUseSwitchingFunction(nonbonded_force.getUseSwitchingFunction()) - force.setCutoffDistance(nonbonded_force.getCutoffDistance()) - force.setSwitchingDistance(nonbonded_force.getSwitchingDistance()) - if self.disable_alchemical_dispersion_correction: - force.setUseLongRangeCorrection(False) - else: - force.setUseLongRangeCorrection(nonbonded_force.getUseDispersionCorrection()) - - if is_periodic_method: - force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) - else: - force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) - - if use_exact_pme_treatment: - #electrostatics are handled by offset - all_electrostatics_custom_nonbonded_forces = [] - else: - # Create CustomNonbondedForces to handle electrostatics particle interactions between - # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda - # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(lambda_var_suffixes) > 1: - aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) - all_electrostatics_custom_nonbonded_forces = [aa_electrostatics_custom_nonbonded_force] - else: - na_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) - aa_electrostatics_custom_nonbonded_force = create_force(openmm.CustomNonbondedForce, electrostatics_energy_expression, - 'lambda_electrostatics', lambda_var_suffixes, alchemical_region.annihilate_electrostatics) - all_electrostatics_custom_nonbonded_forces = [na_electrostatics_custom_nonbonded_force, - aa_electrostatics_custom_nonbonded_force] - - # Common parameters and configuration for electrostatics CustomNonbondedForces. - for force in all_electrostatics_custom_nonbonded_forces: - force.addPerParticleParameter("charge") # partial charge - force.addPerParticleParameter("sigma") # Lennard-Jones sigma - if ((is_ewald_method and self.alchemical_pme_treatment == 'coulomb') or - (is_rf_method and self.alchemical_rf_treatment == 'switched')): - # Use switching function for alchemical electrostatics to ensure force continuity at cutoff. - force.setUseSwitchingFunction(True) - else: - force.setUseSwitchingFunction(False) - force.setSwitchingDistance(nonbonded_force.getCutoffDistance() - self.switch_width) - force.setCutoffDistance(nonbonded_force.getCutoffDistance()) - force.setUseLongRangeCorrection(False) # long-range dispersion correction is meaningless for electrostatics - - if is_periodic_method: - force.setNonbondedMethod(openmm.CustomNonbondedForce.CutoffPeriodic) - else: - force.setNonbondedMethod(nonbonded_force.getNonbondedMethod()) - - # Create CustomBondForces to handle sterics 1,4 exceptions interactions between - # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda - # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(lambda_var_suffixes) > 1: - aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) - all_sterics_custom_bond_forces = [aa_sterics_custom_bond_force] - else: - na_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, is_lambda_controlled=True) - aa_sterics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_sterics_energy_expression, - 'lambda_sterics', lambda_var_suffixes, alchemical_region.annihilate_sterics) - all_sterics_custom_bond_forces = [na_sterics_custom_bond_force, aa_sterics_custom_bond_force] - - for force in all_sterics_custom_bond_forces: - force.addPerBondParameter("sigma") # Lennard-Jones effective sigma - force.addPerBondParameter("epsilon") # Lennard-Jones effective epsilon - - # With exact PME treatment, exception electrostatics is handled through offset parameters. - if use_exact_pme_treatment: - all_electrostatics_custom_bond_forces = [] - else: - # Create CustomBondForces to handle electrostatics 1,4 exceptions interactions between - # non-alchemical/alchemical atoms (na) and alchemical/alchemical atoms (aa). Fix lambda - # to 1.0 for decoupled interactions in alchemical/alchemical force. - if len(lambda_var_suffixes) > 1: - aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) - all_electrostatics_custom_bond_forces = [aa_electrostatics_custom_bond_force] - else: - na_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', lambda_var_suffixes, is_lambda_controlled=True) - aa_electrostatics_custom_bond_force = create_force(openmm.CustomBondForce, exceptions_electrostatics_energy_expression, - 'lambda_electrostatics', lambda_var_suffixes, alchemical_region.annihilate_electrostatics) - all_electrostatics_custom_bond_forces = [na_electrostatics_custom_bond_force, aa_electrostatics_custom_bond_force] - - # Create CustomBondForce to handle exceptions for electrostatics - for force in all_electrostatics_custom_bond_forces: - force.addPerBondParameter("chargeprod") # charge product - force.addPerBondParameter("sigma") # Lennard-Jones effective sigma - - # ------------------------------------------------------------------------------- - # Distribute particle interactions contributions in appropriate nonbonded forces - # ------------------------------------------------------------------------------- - - # Create atom groups. - if len(lambda_var_suffixes) > 1: # Multi region - alchemical_atomsets = [alchemical_regions_pairs[0].alchemical_atoms, - alchemical_regions_pairs[1].alchemical_atoms] - else: # One region - alchemical_atomsets = [alchemical_regions_pairs[0].alchemical_atoms] - - # Copy NonbondedForce particle terms for alchemically-modified particles - # to CustomNonbondedForces, and/or add the charge offsets for exact PME. - # On CUDA, for efficiency reasons, all nonbonded forces (custom and not) - # must have the same particles. - for particle_index in range(nonbonded_force.getNumParticles()): - # Retrieve nonbonded parameters. - [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) - # Set sterics parameters in CustomNonbondedForces. - for force in all_sterics_custom_nonbonded_forces: - force.addParticle([sigma, epsilon]) - # Set electrostatics parameters in CustomNonbondedForces. - for force in all_electrostatics_custom_nonbonded_forces: - force.addParticle([charge, sigma]) - # Set offset parameters in NonbondedForce. - if use_exact_pme_treatment and particle_index in alchemical_atomsets[0] and len(lambda_var_suffixes) == 1: - nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(lambda_var_suffixes[0]), - particle_index, charge, 0.0, 0.0) - - # Turn off interactions contribution from alchemically-modified particles in unmodified - # NonbondedForce that will be handled by all other forces - for particle_index in range(nonbonded_force.getNumParticles()): - # Retrieve parameters. - [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) - # Even with exact treatment of the PME electrostatics, we turn off - # the NonbondedForce charge which is modeled by the offset parameter. - if particle_index in alchemical_atomsets[0]: - nonbonded_force.setParticleParameters(particle_index, abs(0.0*charge), sigma, abs(0*epsilon)) - - # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. - # Sterics - if len(lambda_var_suffixes) == 1: - logger.debug('Adding steric interaction groups between {} and the environment.'.format(lambda_var_suffixes[0])) - na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomsets[0]) - - logger.debug('Adding a steric interaction group between group {0} and {1}.'.format(lambda_var_suffixes[0], - lambda_var_suffixes[-1])) - aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomsets[0], alchemical_atomsets[-1]) - - # Electrostatics - if not use_exact_pme_treatment: - if len(lambda_var_suffixes) == 1: - logger.debug('Adding electrostatic interaction groups between {} and the environment.'.format(lambda_var_suffixes[0])) - na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomsets[0]) - - logger.debug('Adding a electrostatic interaction group between group {0} and {1}.'.format(lambda_var_suffixes[0], - lambda_var_suffixes[-1])) - aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomsets[0], alchemical_atomsets[-1]) - - else: - # Using the nonbonded force to handle electrostatics - # and the "interaction groups" in the nonbonded have already been handled by exclusions. - pass - - # --------------------------------------------------------------- - # Distribute exceptions contributions in appropriate bond forces - # --------------------------------------------------------------- - - all_custom_nonbonded_forces = all_sterics_custom_nonbonded_forces + all_electrostatics_custom_nonbonded_forces - - # Move all NonbondedForce exception terms for alchemically-modified particles to CustomBondForces. - if len(lambda_var_suffixes) > 1: - for exception_index in range(nonbonded_force.getNumExceptions()): - # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) - - # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces - # must have the same number of exceptions/exclusions on CUDA platform. - for force in all_custom_nonbonded_forces: - force.addExclusion(iatom, jatom) - - # Check how many alchemical atoms we have - both_alchemical = iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[1] or\ - jatom in alchemical_atomsets[0] and iatom in alchemical_atomsets[1] - - # Check if this is an exception or an exclusion - is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 - is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 - - if use_exact_pme_treatment and both_alchemical and is_exception_chargeprod: - # Exceptions here should be scaled by lam0*lam1. - # This can be implemented in the future using a CustomBondForce. - raise ValueError('Cannot have exception that straddles two alchemical regions') - - # If exception (and not exclusion), add special CustomBondForce terms to - # handle alchemically-modified Lennard-Jones and electrostatics exceptions - if both_alchemical: - if is_exception_epsilon: - aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) - if is_exception_chargeprod and not use_exact_pme_treatment: - aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - - else: - for exception_index in range(nonbonded_force.getNumExceptions()): - # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) - - # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces - # must have the same number of exceptions/exclusions on CUDA platform. - for force in all_custom_nonbonded_forces: - force.addExclusion(iatom, jatom) - - # Check how many alchemical atoms we have - both_alchemical = iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[0] - at_least_one_alchemical = iatom in alchemical_atomsets[0] or jatom in alchemical_atomsets[0] - only_one_alchemical = at_least_one_alchemical and not both_alchemical - - # Check if this is an exception or an exclusion - is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 - is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 - - # If this is an electrostatic exception and we're using exact PME, - # we just have to add the exception offset to the NonbondedForce. - if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: - nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(lambda_var_suffixes[0]), - exception_index, chargeprod, 0.0, 0.0) - - # If exception (and not exclusion), add special CustomBondForce terms to - # handle alchemically-modified Lennard-Jones and electrostatics exceptions - if both_alchemical: - if is_exception_epsilon: - aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) - if is_exception_chargeprod and not use_exact_pme_treatment: - aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - elif only_one_alchemical: - if is_exception_epsilon: - na_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) - if is_exception_chargeprod and not use_exact_pme_treatment: - na_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - # else: both particles are non-alchemical, leave them in the unmodified NonbondedForce - - # Turn off all exception contributions from alchemical atoms in the NonbondedForce - # modelling non-alchemical atoms only - if at_least_one_alchemical: - nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, - abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) - - # Add global parameters to forces. - def add_global_parameters(force): - force.addGlobalParameter('softcore_alpha', alchemical_region.softcore_alpha) - force.addGlobalParameter('softcore_beta', alchemical_region.softcore_beta) - force.addGlobalParameter('softcore_a', alchemical_region.softcore_a) - force.addGlobalParameter('softcore_b', alchemical_region.softcore_b) - force.addGlobalParameter('softcore_c', alchemical_region.softcore_c) - force.addGlobalParameter('softcore_d', alchemical_region.softcore_d) - force.addGlobalParameter('softcore_e', alchemical_region.softcore_e) - force.addGlobalParameter('softcore_f', alchemical_region.softcore_f) - - all_custom_forces = (all_custom_nonbonded_forces + - all_sterics_custom_bond_forces + - all_electrostatics_custom_bond_forces) - for force in all_custom_forces: - add_global_parameters(force) - - # With exact treatment of PME electrostatics, the NonbondedForce - # is affected by lambda electrostatics as well. - if 'lambda_sterics{}'.format(lambda_var_suffixes[0]) in forces_by_lambda: - forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])].extend(all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces) - forces_by_lambda['lambda_sterics{}'.format(lambda_var_suffixes[0])].extend(all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces) - else: - forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])] = all_electrostatics_custom_nonbonded_forces + all_electrostatics_custom_bond_forces - forces_by_lambda['lambda_sterics{}'.format(lambda_var_suffixes[0])] = all_sterics_custom_nonbonded_forces + all_sterics_custom_bond_forces - - if use_exact_pme_treatment: - forces_by_lambda['lambda_electrostatics{}'.format(lambda_var_suffixes[0])].append(nonbonded_force) - else: - forces_by_lambda[''] = [nonbonded_force] - return forces_by_lambda - - def _alchemically_modify_AmoebaMultipoleForce(self, reference_force, alchemical_region, _): - if len(alchemical_region) > 1: - raise NotImplementedError("Multiple regions does not work with AmoebaMultipoleForce") - else: - alchemical_region = alchemical_region[0] - raise Exception("Not implemented; needs CustomMultipleForce") - - def _alchemically_modify_AmoebaVdwForce(self, reference_force, alchemical_region, _): - """Create alchemically-modified version of AmoebaVdwForce. - - Not implemented. - - TODO - ---- - * Supported periodic boundary conditions need to be handled correctly. - * Exceptions/exclusions need to be dealt with. - - """ - # This feature is incompletely implemented, so raise an exception. - if len(alchemical_region) > 1: - raise NotImplementedError("Multiple regions does not work with AmoebaVdwForce") - else: - alchemical_region = alchemical_region[0] - raise NotImplementedError('Alchemical modification of Amoeba VdW Forces is not supported.') - - # Softcore Halgren potential from Eq. 3 of - # Shi, Y., Jiao, D., Schnieders, M.J., and Ren, P. (2009). Trypsin-ligand binding free - # energy calculation with AMOEBA. Conf Proc IEEE Eng Med Biol Soc 2009, 2328-2331. - energy_expression = 'lambda^5 * epsilon * (1.07^7 / (0.7*(1-lambda)^2+(rho+0.07)^7)) * (1.12 / (0.7*(1-lambda)^2 + rho^7 + 0.12) - 2);' - energy_expression += 'epsilon = 4*epsilon1*epsilon2 / (sqrt(epsilon1) + sqrt(epsilon2))^2;' - energy_expression += 'rho = r / R0;' - energy_expression += 'R0 = (R01^3 + R02^3) / (R01^2 + R02^2);' - energy_expression += 'lambda = vdw_lambda * (ligand1*(1-ligand2) + ligand2*(1-ligand1)) + ligand1*ligand2;' - energy_expression += 'vdw_lambda = %f;' % vdw_lambda - - softcore_force = openmm.CustomNonbondedForce(energy_expression) - softcore_force.addPerParticleParameter('epsilon') - softcore_force.addPerParticleParameter('R0') - softcore_force.addPerParticleParameter('ligand') - - for particle_index in range(system.getNumParticles()): - # Retrieve parameters from vdW force. - [parentIndex, sigma, epsilon, reductionFactor] = force.getParticleParameters(particle_index) - # Add parameters to CustomNonbondedForce. - if particle_index in alchemical_region.alchemical_atoms: - softcore_force.addParticle([epsilon, sigma, 1]) - else: - softcore_force.addParticle([epsilon, sigma, 0]) - - # Deal with exclusions. - excluded_atoms = force.getParticleExclusions(particle_index) - for jatom in excluded_atoms: - if (particle_index < jatom): - softcore_force.addExclusion(particle_index, jatom) - - # Make sure periodic boundary conditions are treated the same way. - # TODO: Handle PBC correctly. - softcore_force.setNonbondedMethod( openmm.CustomNonbondedForce.CutoffPeriodic ) - softcore_force.setCutoffDistance( force.getCutoff() ) - - # Turn off vdW interactions for alchemically-modified atoms. - for particle_index in ligand_atoms: - # Retrieve parameters. - [parentIndex, sigma, epsilon, reductionFactor] = force.getParticleParameters(particle_index) - epsilon = 1.0e-6 * epsilon # TODO: For some reason, we cannot set epsilon to 0. - force.setParticleParameters(particle_index, parentIndex, sigma, epsilon, reductionFactor) - - # Deal with exceptions here. - # TODO - - return [softcore_force] - - @staticmethod - def _alchemically_modify_GBSAOBCForce(reference_force, alchemical_region, _, sasa_model='ACE'): - """Create alchemically-modified version of GBSAOBCForce. - - Parameters - ---------- - reference_force : simtk.openmm.GBSAOBCForce - The reference GBSAOBCForce to be alchemically modify. - alchemical_region : AlchemicalRegion - The alchemical region containing the indices of the atoms to - alchemically modify. - sasa_model : str, optional, default='ACE' - Solvent accessible surface area model. - - Returns - ------- - custom_force : simtk.openmm.CustomGBForce - The alchemical version of the reference force. - - TODO - ---- - * Add support for all types of GBSA forces supported by OpenMM. - * Can we more generally modify any CustomGBSAForce? - - """ - if len(alchemical_region) > 1: - raise NotImplementedError("Multiple regions does not work with GBSAOBCForce") - else: - alchemical_region = alchemical_region[0] - - # TODO make sasa_model a Factory attribute? - custom_force = openmm.CustomGBForce() - - # Add per-particle parameters. - custom_force.addGlobalParameter("lambda_electrostatics", 1.0) - custom_force.addPerParticleParameter("charge") - custom_force.addPerParticleParameter("radius") - custom_force.addPerParticleParameter("scale") - custom_force.addPerParticleParameter("alchemical") - - # Set nonbonded method. - custom_force.setNonbondedMethod(reference_force.getNonbondedMethod()) - custom_force.setCutoffDistance(reference_force.getCutoffDistance()) - - # Add global parameters. - custom_force.addGlobalParameter("solventDielectric", reference_force.getSolventDielectric()) - custom_force.addGlobalParameter("soluteDielectric", reference_force.getSoluteDielectric()) - custom_force.addGlobalParameter("offset", 0.009) - - custom_force.addComputedValue("I", "(lambda_electrostatics*alchemical2 + (1-alchemical2))*step(r+sr2-or1)*0.5*(1/L-1/U+0.25*(r-sr2^2/r)*(1/(U^2)-1/(L^2))+0.5*log(L/U)/r+C);" - "U=r+sr2;" - "C=2*(1/or1-1/L)*step(sr2-r-or1);" - "L=max(or1, D);" - "D=abs(r-sr2);" - "sr2 = scale2*or2;" - "or1 = radius1-offset; or2 = radius2-offset", openmm.CustomGBForce.ParticlePairNoExclusions) - - custom_force.addComputedValue("B", "1/(1/or-tanh(psi-0.8*psi^2+4.85*psi^3)/radius);" - "psi=I*or; or=radius-offset", openmm.CustomGBForce.SingleParticle) - - custom_force.addEnergyTerm("-0.5*138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical+(1-alchemical))*charge^2/B", openmm.CustomGBForce.SingleParticle) - if sasa_model == 'ACE': - custom_force.addEnergyTerm("(lambda_electrostatics*alchemical+(1-alchemical))*28.3919551*(radius+0.14)^2*(radius/B)^6", openmm.CustomGBForce.SingleParticle) - - custom_force.addEnergyTerm("-138.935485*(1/soluteDielectric-1/solventDielectric)*(lambda_electrostatics*alchemical1+(1-alchemical1))*charge1*(lambda_electrostatics*alchemical2+(1-alchemical2))*charge2/f;" - "f=sqrt(r^2+B1*B2*exp(-r^2/(4*B1*B2)))", openmm.CustomGBForce.ParticlePairNoExclusions); - - # Add particle parameters. - for particle_index in range(reference_force.getNumParticles()): - # Retrieve parameters. - [charge, radius, scaling_factor] = reference_force.getParticleParameters(particle_index) - # Set particle parameters. - if particle_index in alchemical_region.alchemical_atoms: - parameters = [charge, radius, scaling_factor, 1.0] - else: - parameters = [charge, radius, scaling_factor, 0.0] - custom_force.addParticle(parameters) - - return {'lambda_electrostatics': [custom_force]} - - def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region, _): - """Create alchemically-modified version of CustomGBForce. - - The GB functions are meta-programmed using the following rules: - - 'lambda_electrostatics' is added as a global parameter. - - 'alchemical' is added as a per-particle parameter. All atoms in - the alchemical group have this parameter set to 1; otherwise 0. - - Any single-particle energy term (`CustomGBForce.SingleParticle`) - is scaled by `(lambda_electrostatics*alchemical+(1-alchemical))` - - Any two-particle energy term (`CustomGBForce.ParticlePairNoExclusions`) - has charge 1 (`charge1`) replaced by `(lambda_electrostatics*alchemical1+(1-alchemical1))*charge1` - and charge 2 (`charge2`) replaced by `(lambda_electrostatics*alchemical2+(1-alchemical2))*charge2`. - - Any single-particle computed value (`CustomGBForce.SingleParticle`) - remains unmodified - - Any two-particle computed value (`CustomGBForce.ParticlePairNoExclusions`) - is scaled by `(lambda_electrostatics*alchemical2 + (1-alchemical2))` - - Scaling of a term should always prepend and capture the value with - an intermediate variable. For example, prepending `scaling * unscaled; unscaled =` - will capture the value of the expression as `unscaled` and multiple by `scaled`. - This avoids the need to identify the head expression and add parentheses. - - .. warning:: - This may not work correctly for all GB models. - - Parameters - ---------- - reference_force : simtk.openmm.GBSAOBCForce - The reference GBSAOBCForce to be alchemically modify. - alchemical_region : AlchemicalRegion - The alchemical region containing the indices of the atoms to - alchemically modify. - - Returns - ------- - custom_force : simtk.openmm.CustomGBForce - The alchemical version of the reference force. - - """ - if len(alchemical_region) > 1: - raise NotImplementedError("Multiple regions does not work with CustomGBForce") - else: - alchemical_region = alchemical_region[0] - - custom_force = openmm.CustomGBForce() - - # Add global parameters - for index in range(reference_force.getNumGlobalParameters()): - name = reference_force.getGlobalParameterName(index) - default_value = reference_force.getGlobalParameterDefaultValue(index) - custom_force.addGlobalParameter(name, default_value) - custom_force.addGlobalParameter("lambda_electrostatics", 1.0) - - # Add per-particle parameters. - for index in range(reference_force.getNumPerParticleParameters()): - name = reference_force.getPerParticleParameterName(index) - custom_force.addPerParticleParameter(name) - custom_force.addPerParticleParameter("alchemical") - - # Set nonbonded methods. - custom_force.setNonbondedMethod(reference_force.getNonbondedMethod()) - custom_force.setCutoffDistance(reference_force.getCutoffDistance()) - - # Add computations. - for index in range(reference_force.getNumComputedValues()): - name, expression, computation_type = reference_force.getComputedValueParameters(index) - - # Alter expression for particle pair terms only. - if computation_type is not openmm.CustomGBForce.SingleParticle: - prepend = ('alchemical_scaling*unscaled; ' - 'alchemical_scaling = (lambda_electrostatics*alchemical2 + (1-alchemical2)); ' - 'unscaled = ') - expression = prepend + expression - - custom_force.addComputedValue(name, expression, computation_type) - - # Add energy terms. - for index in range(reference_force.getNumEnergyTerms()): - expression, computation_type = reference_force.getEnergyTermParameters(index) - - # Alter expressions - if computation_type is openmm.CustomGBForce.SingleParticle: - prepend = ('alchemical_scaling*unscaled; ' - 'alchemical_scaling = (lambda_electrostatics*alchemical + (1-alchemical)); ' - 'unscaled = ') - expression = prepend + expression - else: - expression = expression.replace('charge1', 'alchemically_scaled_charge1') - expression = expression.replace('charge2', 'alchemically_scaled_charge2') - expression += ' ; alchemically_scaled_charge1 = (lambda_electrostatics*alchemical1+(1-alchemical1)) * charge1;' - expression += ' ; alchemically_scaled_charge2 = (lambda_electrostatics*alchemical2+(1-alchemical2)) * charge2;' - - custom_force.addEnergyTerm(expression, computation_type) - - # Add particle parameters - for particle_index in range(reference_force.getNumParticles()): - parameters = reference_force.getParticleParameters(particle_index) - # Append alchemical parameter - parameters = list(parameters) - if particle_index in alchemical_region.alchemical_atoms: - parameters.append(1.0) - else: - parameters.append(0.0) - custom_force.addParticle(parameters) - - # Add tabulated functions - for function_index in range(reference_force.getNumTabulatedFunctions()): - name = reference_force.getTabulatedFunctionName(function_index) - function = reference_force.getTabulatedFunction(function_index) - function_copy = copy.deepcopy(function) - custom_force.addTabulatedFunction(name, function_copy) - - # Add exclusions - for exclusion_index in range(reference_force.getNumExclusions()): - [particle1, particle2] = reference_force.getExclusionParticles(exclusion_index) - custom_force.addExclusion(particle1, particle2) - - return {'lambda_electrostatics': [custom_force]} - - # ------------------------------------------------------------------------- - # Internal usage: Infer force labels - # ------------------------------------------------------------------------- - - @staticmethod - def _find_force_components(alchemical_system): - """Return force labels and indices for each force.""" - def add_label(label, index): - assert label not in force_labels - force_labels[label] = index - - def check_parameter(custom_force, parameter): - for parameter_id in range(custom_force.getNumGlobalParameters()): - parameter_name = custom_force.getGlobalParameterName(parameter_id) - if parameter == parameter_name: - return True - return False - - def check_energy_expression(custom_force, parameter): - try: - found = parameter in custom_force.getEnergyFunction() - except AttributeError: # CustomGBForce - found = False - for index in range(custom_force.getNumEnergyTerms()): - expression, _ = custom_force.getEnergyTermParameters(index) - if parameter in expression: - found = True - break - return found - - force_labels = {} - nonbonded_forces = {'' :[], 'zero': [], 'one': [], 'two': []} - sterics_bond_forces = {'' :[], 'zero': [], 'one': [], 'two': []} - electro_bond_forces = {'' :[], 'zero': [], 'one': [], 'two': []} - - # We save CustomBondForces and CustomNonbondedForces used for nonbonded - # forces and exceptions to distinguish them later - for force_index, force in enumerate(alchemical_system.getForces()): - if isinstance(force, openmm.CustomAngleForce) and check_energy_expression(force, 'lambda_angles'): - if check_parameter(force, 'lambda_angles_zero'): - add_label('alchemically modified HarmonicAngleForce for region zero', force_index) - elif check_parameter(force, 'lambda_angles_one'): - add_label('alchemically modified HarmonicAngleForce for region one', force_index) - elif check_parameter(force, 'lambda_angles_two'): - add_label('alchemically modified HarmonicAngleForce for region two', force_index) - else: - add_label('alchemically modified HarmonicAngleForce', force_index) - elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda_bonds'): - if check_parameter(force, 'lambda_bonds_zero'): - add_label('alchemically modified HarmonicBondForce for region zero', force_index) - elif check_parameter(force, 'lambda_bonds_one'): - add_label('alchemically modified HarmonicBondForce for region one', force_index) - elif check_parameter(force, 'lambda_bonds_two'): - add_label('alchemically modified HarmonicBondForce for region two', force_index) - else: - add_label('alchemically modified HarmonicBondForce', force_index) - elif isinstance(force, openmm.CustomTorsionForce) and check_energy_expression(force, 'lambda_torsions'): - if check_parameter(force, 'lambda_torsions_zero'): - add_label('alchemically modified PeriodicTorsionForce for region zero', force_index) - elif check_parameter(force, 'lambda_torsions_one'): - add_label('alchemically modified PeriodicTorsionForce for region one', force_index) - elif check_parameter(force, 'lambda_torsions_two'): - add_label('alchemically modified PeriodicTorsionForce for region two', force_index) - else: - add_label('alchemically modified PeriodicTorsionForce', force_index) - elif isinstance(force, openmm.CustomGBForce) and check_parameter(force, 'lambda_electrostatics'): - if check_energy_expression(force, 'unscaled'): - add_label('alchemically modified CustomGBForce', force_index) - else: - add_label('alchemically modified GBSAOBCForce', force_index) - elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda'): - if check_energy_expression(force, 'lambda_sterics'): - if check_energy_expression(force, 'lambda_sterics_zero'): - sterics_bond_forces['zero'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_one'): - sterics_bond_forces['one'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_two'): - sterics_bond_forces['two'].append([force_index, force]) - else: - sterics_bond_forces[''].append([force_index, force]) - if check_energy_expression(force, 'lambda_electrostatics'): - if check_energy_expression(force, 'lambda_electrostatics_zero'): - electro_bond_forces['zero'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_one'): - electro_bond_forces['one'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_two'): - electro_bond_forces['two'].append([force_index, force]) - else: - electro_bond_forces[''].append([force_index, force]) - elif (isinstance(force, openmm.CustomNonbondedForce) and force.getEnergyFunction() == '0.0;' and - force.getGlobalParameterName(0) == 'lambda_electrostatics'): - add_label('CustomNonbondedForce holding alchemical atoms unmodified charges', force_index) - elif isinstance(force, openmm.CustomNonbondedForce) and check_energy_expression(force, 'lambda'): - if check_energy_expression(force, 'lambda_sterics'): - if check_energy_expression(force, 'lambda_sterics_zero'): - nonbonded_forces['zero'].append(['sterics', force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_one'): - nonbonded_forces['one'].append(['sterics', force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_two'): - nonbonded_forces['two'].append(['sterics', force_index, force]) - else: - nonbonded_forces[''].append(['sterics', force_index, force]) - if check_energy_expression(force, 'lambda_electrostatics'): - if check_energy_expression(force, 'lambda_electrostatics_zero'): - nonbonded_forces['zero'].append(['electrostatics', force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_one'): - nonbonded_forces['one'].append(['electrostatics',force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_two'): - nonbonded_forces['two'].append(['electrostatics', force_index, force]) - else: - nonbonded_forces[''].append(['electrostatics', force_index, force]) - else: - add_label('unmodified ' + force.__class__.__name__, force_index) - - # Differentiate between na/aa nonbonded forces. - alchemical_atoms_by_region = {} - for region_name, forces in nonbonded_forces.items(): - for force_type, force_index, force in forces: - if region_name == '': - label = 'alchemically modified NonbondedForce for {}alchemical/alchemical ' + force_type - else: - label = 'alchemically modified NonbondedForce for {}alchemical/alchemical ' + force_type +\ - ' for region ' + region_name - interacting_atoms, alchemical_atoms = force.getInteractionGroupParameters(0) - alchemical_atoms_by_region[region_name] = [interacting_atoms, alchemical_atoms] - if interacting_atoms == alchemical_atoms: # alchemical-alchemical atoms - add_label(label.format(''), force_index) - else: - add_label(label.format('non-'), force_index) - - # Differentiate between na/aa bond forces for exceptions. - for (region_name, sterics_forces), electro_forces in zip(sterics_bond_forces.items(), electro_bond_forces.values()): - if len(sterics_forces) == 0: - continue - for force_type, bond_forces in [('sterics', sterics_forces), ('electrostatics', electro_forces)]: - # With exact PME there are no CustomBondForces modeling electrostatics exceptions. - if force_type == 'electrostatics' and len(bond_forces) == 0: - continue - # Otherwise there should be two CustomBondForce. - assert len(bond_forces) == 2 - if region_name == '': - label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type + ' exceptions' - else: - label = 'alchemically modified BondForce for {}alchemical/alchemical ' + force_type +\ - ' exceptions for region ' + region_name - - # Sort forces by number of bonds. - bond_forces = sorted(bond_forces, key=lambda x: x[1].getNumBonds()) - (force_index1, force1), (force_index2, force2) = bond_forces - - # Check if both define their parameters (with decoupling the lambda - # parameter doesn't exist in the alchemical-alchemical force) - parameter_name = 'lambda_' + force_type + '_{}'.format(region_name) - interacting_atoms, alchemical_atoms = alchemical_atoms_by_region[region_name] - - if check_parameter(force1, parameter_name) != check_parameter(force2, parameter_name): - if check_parameter(force1, parameter_name): - add_label(label.format('non-'), force_index1) - add_label(label.format(''), force_index2) - else: - add_label(label.format(''), force_index1) - add_label(label.format('non-'), force_index2) - - # If they are both empty they are identical and any label works. - elif force1.getNumBonds() == 0 and force2.getNumBonds() == 0: - add_label(label.format(''), force_index1) - add_label(label.format('non-'), force_index2) - - # We check that the bond atoms are both alchemical or not. - else: - atom_i, atom_j, _ = force2.getBondParameters(0) - both_alchemical = atom_i in alchemical_atoms and atom_j in alchemical_atoms - if both_alchemical: - add_label(label.format(''), force_index2) - add_label(label.format('non-'), force_index1) - else: - add_label(label.format('non-'), force_index2) - add_label(label.format(''), force_index1) - return force_labels - - -if __name__ == '__main__': - import doctest - doctest.testmod() - # doctest.run_docstring_examples(AlchemicalFunction, globals()) From 315492a9549f8798995bcf0f6f925492bd5267e1 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Tue, 15 Oct 2019 11:12:25 +0100 Subject: [PATCH 101/152] Comments from review #1 --- openmmtools/alchemy.py | 62 +++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 34 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index e91342a26..3af02de28 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1871,11 +1871,11 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ # ------------------------------------------------------------------------------- # Create atom groups. - if len(lambda_var_suffixes) > 1: - alchemical_atomset_0 = alchemical_regions_pairs[0].alchemical_atoms - alchemical_atomset_1 = alchemical_regions_pairs[1].alchemical_atoms - else: - alchemical_atomset_0 = alchemical_regions_pairs[0].alchemical_atoms + if len(lambda_var_suffixes) > 1: # Multi region + alchemical_atomsets = [alchemical_regions_pairs[0].alchemical_atoms, + alchemical_regions_pairs[1].alchemical_atoms] + else: # One region + alchemical_atomsets = [alchemical_regions_pairs[0].alchemical_atoms] # Copy NonbondedForce particle terms for alchemically-modified particles # to CustomNonbondedForces, and/or add the charge offsets for exact PME. @@ -1891,7 +1891,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ for force in all_electrostatics_custom_nonbonded_forces: force.addParticle([charge, sigma]) # Set offset parameters in NonbondedForce. - if use_exact_pme_treatment and particle_index in alchemical_atomset_0 and len(lambda_var_suffixes) == 1: + if use_exact_pme_treatment and particle_index in alchemical_atomsets[0] and len(lambda_var_suffixes) == 1: nonbonded_force.addParticleParameterOffset('lambda_electrostatics{}'.format(lambda_var_suffixes[0]), particle_index, charge, 0.0, 0.0) @@ -1902,30 +1902,29 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ [charge, sigma, epsilon] = nonbonded_force.getParticleParameters(particle_index) # Even with exact treatment of the PME electrostatics, we turn off # the NonbondedForce charge which is modeled by the offset parameter. - if particle_index in alchemical_atomset_0: + if particle_index in alchemical_atomsets[0]: nonbonded_force.setParticleParameters(particle_index, abs(0.0*charge), sigma, abs(0*epsilon)) # Restrict interaction evaluation of CustomNonbondedForces to their respective atom groups. # Sterics - if len(lambda_var_suffixes) > 1: # Multi region - logger.debug('Adding a steric interaction group between groups {}.'.format(lambda_var_suffixes)) - aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) - else: # One region - logger.debug('Adding steric interaction groups between {0} and the environment,' - ' and {0} with itself.'.format(lambda_var_suffixes)) - na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) - aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) + if len(lambda_var_suffixes) == 1: + logger.debug('Adding steric interaction groups between {} and the environment.'.format(lambda_var_suffixes[0])) + na_sterics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomsets[0]) + + logger.debug('Adding a steric interaction group between group {0} and {1}.'.format(lambda_var_suffixes[0], + lambda_var_suffixes[-1])) + aa_sterics_custom_nonbonded_force.addInteractionGroup(alchemical_atomsets[0], alchemical_atomsets[-1]) # Electrostatics if not use_exact_pme_treatment: - if len(lambda_var_suffixes) > 1: # Multi region - logger.debug('Adding a electrostatic interaction group between groups {}.'.format(lambda_var_suffixes)) - aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_1) - else: # One region - logger.debug('Adding electrostatic interaction groups between {0} and the environment,' - ' and {0} with itself.'.format(lambda_var_suffixes)) - na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomset_0) - aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomset_0, alchemical_atomset_0) + if len(lambda_var_suffixes) == 1: + logger.debug('Adding electrostatic interaction groups between {} and the environment.'.format(lambda_var_suffixes[0])) + na_electrostatics_custom_nonbonded_force.addInteractionGroup(nonalchemical_atomset, alchemical_atomsets[0]) + + logger.debug('Adding a electrostatic interaction group between group {0} and {1}.'.format(lambda_var_suffixes[0], + lambda_var_suffixes[-1])) + aa_electrostatics_custom_nonbonded_force.addInteractionGroup(alchemical_atomsets[0], alchemical_atomsets[-1]) + else: # Using the nonbonded force to handle electrostatics # and the "interaction groups" in the nonbonded have already been handled by exclusions. @@ -1949,16 +1948,16 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ force.addExclusion(iatom, jatom) # Check how many alchemical atoms we have - both_alchemical = iatom in alchemical_atomset_0 and jatom in alchemical_atomset_1 - at_least_one_alchemical = iatom in alchemical_atomset_0 or jatom in alchemical_atomset_1 + both_alchemical = iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[1] or\ + jatom in alchemical_atomsets[0] and iatom in alchemical_atomsets[1] # Check if this is an exception or an exclusion is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 if use_exact_pme_treatment and both_alchemical and is_exception_chargeprod: - # Not sure how to deal with this case. Exception should be scaled by lam0*lam1. - # However we can only have one Offset parameter per exception? + # Exceptions here should be scaled by lam0*lam1. + # This can be implemented in the future using a CustomBondForce. raise ValueError('Cannot have exception that straddles two alchemical regions') # If exception (and not exclusion), add special CustomBondForce terms to @@ -1969,11 +1968,6 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ if is_exception_chargeprod and not use_exact_pme_treatment: aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - # Turn off all exception contributions from alchemical atoms in the NonbondedForce - # modelling non-alchemical atoms only - if at_least_one_alchemical: - nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, - abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) else: for exception_index in range(nonbonded_force.getNumExceptions()): # Retrieve parameters. @@ -1985,8 +1979,8 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ force.addExclusion(iatom, jatom) # Check how many alchemical atoms we have - both_alchemical = iatom in alchemical_atomset_0 and jatom in alchemical_atomset_0 - at_least_one_alchemical = iatom in alchemical_atomset_0 or jatom in alchemical_atomset_0 + both_alchemical = iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[0] + at_least_one_alchemical = iatom in alchemical_atomsets[0] or jatom in alchemical_atomsets[0] only_one_alchemical = at_least_one_alchemical and not both_alchemical # Check if this is an exception or an exclusion From 03034c49eab218e9a82bfd4176be9d5e13e5d6e3 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Tue, 15 Oct 2019 13:31:42 +0200 Subject: [PATCH 102/152] Small code simplification --- openmmtools/alchemy.py | 83 ++++++++++++++++-------------------------- 1 file changed, 32 insertions(+), 51 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 3af02de28..60d793091 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1871,11 +1871,7 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ # ------------------------------------------------------------------------------- # Create atom groups. - if len(lambda_var_suffixes) > 1: # Multi region - alchemical_atomsets = [alchemical_regions_pairs[0].alchemical_atoms, - alchemical_regions_pairs[1].alchemical_atoms] - else: # One region - alchemical_atomsets = [alchemical_regions_pairs[0].alchemical_atoms] + alchemical_atomsets = [region.alchemical_atoms for region in alchemical_regions_pairs] # Copy NonbondedForce particle terms for alchemically-modified particles # to CustomNonbondedForces, and/or add the charge offsets for exact PME. @@ -1937,70 +1933,54 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ all_custom_nonbonded_forces = all_sterics_custom_nonbonded_forces + all_electrostatics_custom_nonbonded_forces # Move all NonbondedForce exception terms for alchemically-modified particles to CustomBondForces. - if len(lambda_var_suffixes) > 1: - for exception_index in range(nonbonded_force.getNumExceptions()): - # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) + for exception_index in range(nonbonded_force.getNumExceptions()): + # Retrieve parameters. + iatom, jatom, chargeprod, sigma, epsilon = nonbonded_force.getExceptionParameters(exception_index) - # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces - # must have the same number of exceptions/exclusions on CUDA platform. - for force in all_custom_nonbonded_forces: - force.addExclusion(iatom, jatom) + # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces + # must have the same number of exceptions/exclusions on CUDA platform. + for force in all_custom_nonbonded_forces: + force.addExclusion(iatom, jatom) - # Check how many alchemical atoms we have - both_alchemical = iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[1] or\ - jatom in alchemical_atomsets[0] and iatom in alchemical_atomsets[1] + # Check if this is an exception or an exclusion + is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 + is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 - # Check if this is an exception or an exclusion - is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 - is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 + # Check how many alchemical atoms we have in the exception. + if len(lambda_var_suffixes) > 1: + # Pair of interacting regions + both_alchemical = ((iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[1]) or + (jatom in alchemical_atomsets[0] and iatom in alchemical_atomsets[1])) if use_exact_pme_treatment and both_alchemical and is_exception_chargeprod: # Exceptions here should be scaled by lam0*lam1. # This can be implemented in the future using a CustomBondForce. raise ValueError('Cannot have exception that straddles two alchemical regions') - # If exception (and not exclusion), add special CustomBondForce terms to - # handle alchemically-modified Lennard-Jones and electrostatics exceptions - if both_alchemical: - if is_exception_epsilon: - aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) - if is_exception_chargeprod and not use_exact_pme_treatment: - aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - - else: - for exception_index in range(nonbonded_force.getNumExceptions()): - # Retrieve parameters. - [iatom, jatom, chargeprod, sigma, epsilon] = nonbonded_force.getExceptionParameters(exception_index) - - # Exclude this atom pair in CustomNonbondedForces. All nonbonded forces - # must have the same number of exceptions/exclusions on CUDA platform. - for force in all_custom_nonbonded_forces: - force.addExclusion(iatom, jatom) - - # Check how many alchemical atoms we have + else: + # Single alchemical region. both_alchemical = iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[0] at_least_one_alchemical = iatom in alchemical_atomsets[0] or jatom in alchemical_atomsets[0] only_one_alchemical = at_least_one_alchemical and not both_alchemical - # Check if this is an exception or an exclusion - is_exception_epsilon = abs(epsilon.value_in_unit_system(unit.md_unit_system)) > 0.0 - is_exception_chargeprod = abs(chargeprod.value_in_unit_system(unit.md_unit_system)) > 0.0 - # If this is an electrostatic exception and we're using exact PME, # we just have to add the exception offset to the NonbondedForce. if use_exact_pme_treatment and at_least_one_alchemical and is_exception_chargeprod: nonbonded_force.addExceptionParameterOffset('lambda_electrostatics{}'.format(lambda_var_suffixes[0]), exception_index, chargeprod, 0.0, 0.0) - # If exception (and not exclusion), add special CustomBondForce terms to - # handle alchemically-modified Lennard-Jones and electrostatics exceptions - if both_alchemical: - if is_exception_epsilon: - aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) - if is_exception_chargeprod and not use_exact_pme_treatment: - aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - elif only_one_alchemical: + # If exception (and not exclusion), add special CustomBondForce terms to + # handle alchemically-modified Lennard-Jones and electrostatics exceptions + if both_alchemical: + if is_exception_epsilon: + aa_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) + if is_exception_chargeprod and not use_exact_pme_treatment: + aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) + + # When this is a single region, we model the exception between alchemical + # and non-alchemical particles using a single custom bond. + if len(lambda_var_suffixes) == 1: + if only_one_alchemical: if is_exception_epsilon: na_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) if is_exception_chargeprod and not use_exact_pme_treatment: @@ -2008,7 +1988,8 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ # else: both particles are non-alchemical, leave them in the unmodified NonbondedForce # Turn off all exception contributions from alchemical atoms in the NonbondedForce - # modelling non-alchemical atoms only + # modelling non-alchemical atoms only. We need to do it only once per single + # region so we don't repeat it when dealing with pairs of interacting regions. if at_least_one_alchemical: nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) From eb7e305920055a3b97c73a16f18a0fb16c70a3fb Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Tue, 15 Oct 2019 13:07:47 +0100 Subject: [PATCH 103/152] remove one if in `Distribute exceptions contributions in appropriate bond forces` --- openmmtools/alchemy.py | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 60d793091..d7b3cd195 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1948,9 +1948,11 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ # Check how many alchemical atoms we have in the exception. if len(lambda_var_suffixes) > 1: - # Pair of interacting regions + # Pair of interacting alchemical regions, therefore they are both alchemical or neither alchemical. both_alchemical = ((iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[1]) or (jatom in alchemical_atomsets[0] and iatom in alchemical_atomsets[1])) + at_least_one_alchemical = both_alchemical + only_one_alchemical = False if use_exact_pme_treatment and both_alchemical and is_exception_chargeprod: # Exceptions here should be scaled by lam0*lam1. @@ -1977,22 +1979,21 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ if is_exception_chargeprod and not use_exact_pme_treatment: aa_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - # When this is a single region, we model the exception between alchemical + # When this is a single region we model the exception between alchemical # and non-alchemical particles using a single custom bond. - if len(lambda_var_suffixes) == 1: - if only_one_alchemical: - if is_exception_epsilon: - na_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) - if is_exception_chargeprod and not use_exact_pme_treatment: - na_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) - # else: both particles are non-alchemical, leave them in the unmodified NonbondedForce - - # Turn off all exception contributions from alchemical atoms in the NonbondedForce - # modelling non-alchemical atoms only. We need to do it only once per single - # region so we don't repeat it when dealing with pairs of interacting regions. - if at_least_one_alchemical: - nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, - abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) + elif only_one_alchemical: + if is_exception_epsilon: + na_sterics_custom_bond_force.addBond(iatom, jatom, [sigma, epsilon]) + if is_exception_chargeprod and not use_exact_pme_treatment: + na_electrostatics_custom_bond_force.addBond(iatom, jatom, [chargeprod, sigma]) + # else: both particles are non-alchemical, leave them in the unmodified NonbondedForce + + # Turn off all exception contributions from alchemical atoms in the NonbondedForce + # modelling non-alchemical atoms only. We need to do it only once per single + # region so we don't repeat it when dealing with pairs of interacting regions. + if at_least_one_alchemical: + nonbonded_force.setExceptionParameters(exception_index, iatom, jatom, + abs(0.0*chargeprod), sigma, abs(0.0*epsilon)) # Add global parameters to forces. def add_global_parameters(force): From 02c97468a6d2aa24e4eb1e120ae605978c22b284 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Tue, 15 Oct 2019 13:31:09 +0100 Subject: [PATCH 104/152] stop at_least_one_alchemical being treated multiple times --- openmmtools/alchemy.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index d7b3cd195..ff2b4a9cf 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -1951,8 +1951,11 @@ def create_force(force_cls, energy_expression, lambda_variable_name, lambda_var_ # Pair of interacting alchemical regions, therefore they are both alchemical or neither alchemical. both_alchemical = ((iatom in alchemical_atomsets[0] and jatom in alchemical_atomsets[1]) or (jatom in alchemical_atomsets[0] and iatom in alchemical_atomsets[1])) - at_least_one_alchemical = both_alchemical only_one_alchemical = False + #The condition of at_least_one_alchemical is treated only once per single + # region so we don't repeat it when dealing with pairs of interacting regions. + at_least_one_alchemical = False + if use_exact_pme_treatment and both_alchemical and is_exception_chargeprod: # Exceptions here should be scaled by lam0*lam1. From 47e027bbcd354264a493f8ba7c7764e132b34d2f Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Tue, 15 Oct 2019 20:53:54 +0100 Subject: [PATCH 105/152] rework _find_force_components --- openmmtools/alchemy.py | 171 +++++++++++++++++++++++------------------ 1 file changed, 95 insertions(+), 76 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index ff2b4a9cf..73074e884 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -2307,6 +2307,7 @@ def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region, @staticmethod def _find_force_components(alchemical_system): + import re """Return force labels and indices for each force.""" def add_label(label, index): assert label not in force_labels @@ -2315,9 +2316,12 @@ def add_label(label, index): def check_parameter(custom_force, parameter): for parameter_id in range(custom_force.getNumGlobalParameters()): parameter_name = custom_force.getGlobalParameterName(parameter_id) - if parameter == parameter_name: - return True - return False + if parameter_name.startswith(parameter): + region_name = parameter_name[len(parameter)+1:] if len(parameter_name) > len(parameter) else None + return True, region_name + return False, None + + ''' def check_energy_expression(custom_force, parameter): try: @@ -2330,88 +2334,103 @@ def check_energy_expression(custom_force, parameter): found = True break return found - + ''' + + def check_energy_expression(custom_force, parameter): + energy_expression = custom_force.getEnergyFunction() + try: + found = parameter in energy_expression + except AttributeError: # CustomGBForce + found = False + for index in range(custom_force.getNumEnergyTerms()): + expression, _ = custom_force.getEnergyTermParameters(index) + if parameter in expression: + found = True + break + if not found: + return [found, None] # param not found + p = re.compile(r'{}_([A-Za-z0-9]+)'.format(parameter)) + try: + suffix = p.search(energy_expression).group(1) + return [found, suffix] + except AttributeError: + return [found, None] # no suffix found + force_labels = {} - nonbonded_forces = {'' :[], 'zero': [], 'one': [], 'two': []} - sterics_bond_forces = {'' :[], 'zero': [], 'one': [], 'two': []} - electro_bond_forces = {'' :[], 'zero': [], 'one': [], 'two': []} + nonbonded_forces = {} + sterics_bond_forces = {} + electro_bond_forces = {} # We save CustomBondForces and CustomNonbondedForces used for nonbonded # forces and exceptions to distinguish them later for force_index, force in enumerate(alchemical_system.getForces()): - if isinstance(force, openmm.CustomAngleForce) and check_energy_expression(force, 'lambda_angles'): - if check_parameter(force, 'lambda_angles_zero'): - add_label('alchemically modified HarmonicAngleForce for region zero', force_index) - elif check_parameter(force, 'lambda_angles_one'): - add_label('alchemically modified HarmonicAngleForce for region one', force_index) - elif check_parameter(force, 'lambda_angles_two'): - add_label('alchemically modified HarmonicAngleForce for region two', force_index) - else: - add_label('alchemically modified HarmonicAngleForce', force_index) - elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda_bonds'): - if check_parameter(force, 'lambda_bonds_zero'): - add_label('alchemically modified HarmonicBondForce for region zero', force_index) - elif check_parameter(force, 'lambda_bonds_one'): - add_label('alchemically modified HarmonicBondForce for region one', force_index) - elif check_parameter(force, 'lambda_bonds_two'): - add_label('alchemically modified HarmonicBondForce for region two', force_index) - else: - add_label('alchemically modified HarmonicBondForce', force_index) - elif isinstance(force, openmm.CustomTorsionForce) and check_energy_expression(force, 'lambda_torsions'): - if check_parameter(force, 'lambda_torsions_zero'): - add_label('alchemically modified PeriodicTorsionForce for region zero', force_index) - elif check_parameter(force, 'lambda_torsions_one'): - add_label('alchemically modified PeriodicTorsionForce for region one', force_index) - elif check_parameter(force, 'lambda_torsions_two'): - add_label('alchemically modified PeriodicTorsionForce for region two', force_index) - else: - add_label('alchemically modified PeriodicTorsionForce', force_index) - elif isinstance(force, openmm.CustomGBForce) and check_parameter(force, 'lambda_electrostatics'): - if check_energy_expression(force, 'unscaled'): - add_label('alchemically modified CustomGBForce', force_index) + if isinstance(force, openmm.CustomAngleForce): + parameter_found, region_name = check_parameter(force, 'lambda_angles') + if parameter_found: + label = 'alchemically modified HarmonicAngleForce' + if region_name is not None: + label = label + ' for region ' + region_name + add_label(label, force_index) + + elif isinstance(force, openmm.CustomBondForce): + #look for bond + parameter_found, region_name = check_parameter(force, 'lambda_bonds') + if parameter_found: + label = 'alchemically modified HarmonicBondForce' + if region_name is not None: + label = label + ' for region ' + region_name + add_label(label, force_index) else: - add_label('alchemically modified GBSAOBCForce', force_index) - elif isinstance(force, openmm.CustomBondForce) and check_energy_expression(force, 'lambda'): - if check_energy_expression(force, 'lambda_sterics'): - if check_energy_expression(force, 'lambda_sterics_zero'): - sterics_bond_forces['zero'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_one'): - sterics_bond_forces['one'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_two'): - sterics_bond_forces['two'].append([force_index, force]) + #if bond not found look for steric or electro + parameter_found, region_type_suffix = check_energy_expression(force, 'lambda') + if parameter_found: + _, region_name_suffix = check_energy_expression(force, 'lambda_{}'.format(region_type_suffix)) + if region_type_suffix == 'sterics': + try: + sterics_bond_forces[region_name_suffix].append([force_index, force]) + except KeyError: + sterics_bond_forces.update({region_name_suffix: [[force_index, force]]}) + if region_type_suffix == 'electrostatics': + try: + electro_bond_forces[region_name_suffix].append([force_index, force]) + except KeyError: + electro_bond_forces.update({region_name_suffix: [[force_index, force]]}) + + elif isinstance(force, openmm.CustomTorsionForce): + parameter_found, region_name = check_parameter(force, 'lambda_torsions') + if parameter_found: + label = 'alchemically modified PeriodicTorsionForce' + if region_name is not None: + label = label + ' for region ' + region_name + add_label(label, force_index) + + elif isinstance(force, openmm.CustomGBForce): + parameter_found, _ = check_parameter(force, 'lambda_electrostatics') + if parameter_found: + #No multi region for GBForce + if check_energy_expression(force, 'unscaled')[0]: + add_label('alchemically modified CustomGBForce', force_index) else: - sterics_bond_forces[''].append([force_index, force]) - if check_energy_expression(force, 'lambda_electrostatics'): - if check_energy_expression(force, 'lambda_electrostatics_zero'): - electro_bond_forces['zero'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_one'): - electro_bond_forces['one'].append([force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_two'): - electro_bond_forces['two'].append([force_index, force]) - else: - electro_bond_forces[''].append([force_index, force]) + add_label('alchemically modified GBSAOBCForce', force_index) + elif (isinstance(force, openmm.CustomNonbondedForce) and force.getEnergyFunction() == '0.0;' and force.getGlobalParameterName(0) == 'lambda_electrostatics'): add_label('CustomNonbondedForce holding alchemical atoms unmodified charges', force_index) - elif isinstance(force, openmm.CustomNonbondedForce) and check_energy_expression(force, 'lambda'): - if check_energy_expression(force, 'lambda_sterics'): - if check_energy_expression(force, 'lambda_sterics_zero'): - nonbonded_forces['zero'].append(['sterics', force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_one'): - nonbonded_forces['one'].append(['sterics', force_index, force]) - elif check_energy_expression(force, 'lambda_sterics_two'): - nonbonded_forces['two'].append(['sterics', force_index, force]) - else: - nonbonded_forces[''].append(['sterics', force_index, force]) - if check_energy_expression(force, 'lambda_electrostatics'): - if check_energy_expression(force, 'lambda_electrostatics_zero'): - nonbonded_forces['zero'].append(['electrostatics', force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_one'): - nonbonded_forces['one'].append(['electrostatics',force_index, force]) - elif check_energy_expression(force, 'lambda_electrostatics_two'): - nonbonded_forces['two'].append(['electrostatics', force_index, force]) - else: - nonbonded_forces[''].append(['electrostatics', force_index, force]) + + elif isinstance(force, openmm.CustomNonbondedForce): + parameter_found, region_type_suffix = check_energy_expression(force, 'lambda') + if parameter_found: + _, region_name_suffix = check_energy_expression(force, 'lambda_{}'.format(region_type_suffix)) + if region_type_suffix=='sterics': + try: + nonbonded_forces[region_name_suffix].append(['sterics', force_index, force]) + except KeyError: + nonbonded_forces.update({region_name_suffix: [['sterics', force_index, force]]}) + if region_type_suffix=='electrostatics': + try: + nonbonded_forces[region_name_suffix].append(['electrostatics', force_index, force]) + except KeyError: + nonbonded_forces.update({region_name_suffix: [['electrostatics', force_index, force]]}) else: add_label('unmodified ' + force.__class__.__name__, force_index) @@ -2430,7 +2449,7 @@ def check_energy_expression(custom_force, parameter): add_label(label.format(''), force_index) else: add_label(label.format('non-'), force_index) - + # Differentiate between na/aa bond forces for exceptions. for (region_name, sterics_forces), electro_forces in zip(sterics_bond_forces.items(), electro_bond_forces.values()): if len(sterics_forces) == 0: From 1212447ba3eada2684a3c07b9ae349135f65fc42 Mon Sep 17 00:00:00 2001 From: adw62 <38112687+adw62@users.noreply.github.com> Date: Thu, 17 Oct 2019 12:21:04 +0100 Subject: [PATCH 106/152] _find_force_components reworked --- openmmtools/alchemy.py | 103 +++++++++++++++++++++-------------------- 1 file changed, 52 insertions(+), 51 deletions(-) diff --git a/openmmtools/alchemy.py b/openmmtools/alchemy.py index 73074e884..b60618422 100644 --- a/openmmtools/alchemy.py +++ b/openmmtools/alchemy.py @@ -38,6 +38,7 @@ import logging import collections import itertools +import re import numpy as np from simtk import openmm, unit @@ -2307,7 +2308,6 @@ def _alchemically_modify_CustomGBForce(self, reference_force, alchemical_region, @staticmethod def _find_force_components(alchemical_system): - import re """Return force labels and indices for each force.""" def add_label(label, index): assert label not in force_labels @@ -2318,28 +2318,12 @@ def check_parameter(custom_force, parameter): parameter_name = custom_force.getGlobalParameterName(parameter_id) if parameter_name.startswith(parameter): region_name = parameter_name[len(parameter)+1:] if len(parameter_name) > len(parameter) else None - return True, region_name - return False, None - - ''' + return [True, region_name] + return [False, None] def check_energy_expression(custom_force, parameter): try: - found = parameter in custom_force.getEnergyFunction() - except AttributeError: # CustomGBForce - found = False - for index in range(custom_force.getNumEnergyTerms()): - expression, _ = custom_force.getEnergyTermParameters(index) - if parameter in expression: - found = True - break - return found - ''' - - def check_energy_expression(custom_force, parameter): - energy_expression = custom_force.getEnergyFunction() - try: - found = parameter in energy_expression + energy_expression = custom_force.getEnergyFunction() except AttributeError: # CustomGBForce found = False for index in range(custom_force.getNumEnergyTerms()): @@ -2347,14 +2331,17 @@ def check_energy_expression(custom_force, parameter): if parameter in expression: found = True break + return [found, ''] # CustomGBForce will not have a parameter suffix + found = parameter in energy_expression if not found: - return [found, None] # param not found + return [found, ''] # param not found and by extension no parameter suffix + #Look for parameter suffix p = re.compile(r'{}_([A-Za-z0-9]+)'.format(parameter)) try: suffix = p.search(energy_expression).group(1) return [found, suffix] except AttributeError: - return [found, None] # no suffix found + return [found, ''] # no parameter suffix found force_labels = {} nonbonded_forces = {} @@ -2372,29 +2359,14 @@ def check_energy_expression(custom_force, parameter): label = label + ' for region ' + region_name add_label(label, force_index) - elif isinstance(force, openmm.CustomBondForce): - #look for bond + elif isinstance(force, openmm.CustomBondForce) and check_parameter(force, 'lambda_bonds')[0]: + #Need extra check for 'lambda_bonds' in the if to differntiate from exceptions parameter_found, region_name = check_parameter(force, 'lambda_bonds') if parameter_found: label = 'alchemically modified HarmonicBondForce' if region_name is not None: label = label + ' for region ' + region_name add_label(label, force_index) - else: - #if bond not found look for steric or electro - parameter_found, region_type_suffix = check_energy_expression(force, 'lambda') - if parameter_found: - _, region_name_suffix = check_energy_expression(force, 'lambda_{}'.format(region_type_suffix)) - if region_type_suffix == 'sterics': - try: - sterics_bond_forces[region_name_suffix].append([force_index, force]) - except KeyError: - sterics_bond_forces.update({region_name_suffix: [[force_index, force]]}) - if region_type_suffix == 'electrostatics': - try: - electro_bond_forces[region_name_suffix].append([force_index, force]) - except KeyError: - electro_bond_forces.update({region_name_suffix: [[force_index, force]]}) elif isinstance(force, openmm.CustomTorsionForce): parameter_found, region_name = check_parameter(force, 'lambda_torsions') @@ -2413,6 +2385,21 @@ def check_energy_expression(custom_force, parameter): else: add_label('alchemically modified GBSAOBCForce', force_index) + elif isinstance(force, openmm.CustomBondForce): + parameter_found, region_type_suffix = check_energy_expression(force, 'lambda') + if parameter_found: + _, region_name_suffix = check_energy_expression(force, 'lambda_{}'.format(region_type_suffix)) + if region_type_suffix == 'sterics': + if region_name_suffix in sterics_bond_forces: + sterics_bond_forces[region_name_suffix].append([force_index, force]) + else: + sterics_bond_forces[region_name_suffix] = [[force_index, force]] + if region_type_suffix == 'electrostatics': + if region_name_suffix in electro_bond_forces: + electro_bond_forces[region_name_suffix].append([force_index, force]) + else: + electro_bond_forces[region_name_suffix] = [[force_index, force]] + elif (isinstance(force, openmm.CustomNonbondedForce) and force.getEnergyFunction() == '0.0;' and force.getGlobalParameterName(0) == 'lambda_electrostatics'): add_label('CustomNonbondedForce holding alchemical atoms unmodified charges', force_index) @@ -2421,16 +2408,16 @@ def check_energy_expression(custom_force, parameter): parameter_found, region_type_suffix = check_energy_expression(force, 'lambda') if parameter_found: _, region_name_suffix = check_energy_expression(force, 'lambda_{}'.format(region_type_suffix)) - if region_type_suffix=='sterics': - try: + if region_type_suffix == 'sterics': + if region_name_suffix in nonbonded_forces: nonbonded_forces[region_name_suffix].append(['sterics', force_index, force]) - except KeyError: - nonbonded_forces.update({region_name_suffix: [['sterics', force_index, force]]}) - if region_type_suffix=='electrostatics': - try: + else: + nonbonded_forces[region_name_suffix] = [['sterics', force_index, force]] + if region_type_suffix == 'electrostatics': + if region_name_suffix in nonbonded_forces: nonbonded_forces[region_name_suffix].append(['electrostatics', force_index, force]) - except KeyError: - nonbonded_forces.update({region_name_suffix: [['electrostatics', force_index, force]]}) + else: + nonbonded_forces[region_name_suffix] = [['electrostatics', force_index, force]] else: add_label('unmodified ' + force.__class__.__name__, force_index) @@ -2450,6 +2437,18 @@ def check_energy_expression(custom_force, parameter): else: add_label(label.format('non-'), force_index) + # Initialize sterics_bond_forces or electro_bond_forces for regions which did not have forces, as empty lists + for k in sterics_bond_forces.keys(): + if k in electro_bond_forces: + pass + else: + electro_bond_forces[k] = [] + for k in electro_bond_forces.keys(): + if k in sterics_bond_forces: + pass + else: + sterics_bond_forces[k] = [] + # Differentiate between na/aa bond forces for exceptions. for (region_name, sterics_forces), electro_forces in zip(sterics_bond_forces.items(), electro_bond_forces.values()): if len(sterics_forces) == 0: @@ -2472,11 +2471,13 @@ def check_energy_expression(custom_force, parameter): # Check if both define their parameters (with decoupling the lambda # parameter doesn't exist in the alchemical-alchemical force) - parameter_name = 'lambda_' + force_type + '_{}'.format(region_name) + parameter_name = 'lambda_' + force_type + if region_name != '': + parameter_name = parameter_name + '_{}'.format(region_name) interacting_atoms, alchemical_atoms = alchemical_atoms_by_region[region_name] - - if check_parameter(force1, parameter_name) != check_parameter(force2, parameter_name): - if check_parameter(force1, parameter_name): + + if check_parameter(force1, parameter_name)[0] != check_parameter(force2, parameter_name)[0]: + if check_parameter(force1, parameter_name)[0]: add_label(label.format('non-'), force_index1) add_label(label.format(''), force_index2) else: From 587955835b7437d794ae5ad18e15a8839ac4d9c0 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Fri, 18 Oct 2019 23:05:54 -0400 Subject: [PATCH 107/152] Test nightly and conda-forge openmm builds on travis --- .travis.yml | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index d409a8f04..b7fb5fcc6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,14 +14,25 @@ matrix: - os: linux language: generic # No need to set Python version since its conda - env: PYTHON_VER=3.6 + env: PYTHON_VER=3.6 OPENMM="latest" - os: linux language: generic - env: PYTHON_VER=3.7 + env: PYTHON_VER=3.7 OPENMM="latest" + + - os: linux + language: generic + env: PYTHON_VER=3.7 OPENMM="nightly" + - os: linux + language: generic + env: PYTHON_VER=3.7 OPENMM="conda-forge" - # TODO: Reactivate macOS tests if they stop segfaulting after switching from nose to pytest (see also #402 and #430). allow_failures: + # TODO: Reactivate macOS tests if they stop segfaulting after switching from nose to pytest (see also #402 and #430). - os: osx + # Allow conda-forge failure + - os: linux + language: generic + env: PYTHON_VER=3.7 OPENMM="conda-forge" env: global: @@ -45,6 +56,11 @@ install: - conda activate test # Build and install package - python setup.py develop --no-deps + # Install desired OpenMM version + - if [ "$OPENMM" == "latest" ]; then echo "Using latest release OpenMM."; conda remove --yes --force openmm; conda clean -tipsy; conda install --yes -c omnia openmm; fi + - if [ "$OPENMM" == "beta" ]; then echo "Using OpenMM beta"; conda remove --yes --force openmm; conda clean -tipsy; conda install --yes --override-channels -c omnia/label/beta openmm; fi + - if [ "$OPENMM" == "nightly" ]; then echo "Using OpenMM nightly dev build."; conda remove --yes --force openmm; conda clean -tipsy; conda install --yes --override-channels -c omnia-dev openmm; fi + - if [ "$OPENMM" == "conda-forge" ]; then echo "Using OpenMM conda-forge testing build."; conda remove --yes --force openmm; conda clean -tipsy; conda install --yes --override-channels -c conda-forge/label/testing openmm; fi script: From 3b630f68c1817ef32b1d7289964eae1ccd2ee4a4 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Fri, 18 Oct 2019 23:56:25 -0400 Subject: [PATCH 108/152] Update force-install of openmm --- .travis.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index b7fb5fcc6..9bdc3f45f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,10 +57,10 @@ install: # Build and install package - python setup.py develop --no-deps # Install desired OpenMM version - - if [ "$OPENMM" == "latest" ]; then echo "Using latest release OpenMM."; conda remove --yes --force openmm; conda clean -tipsy; conda install --yes -c omnia openmm; fi - - if [ "$OPENMM" == "beta" ]; then echo "Using OpenMM beta"; conda remove --yes --force openmm; conda clean -tipsy; conda install --yes --override-channels -c omnia/label/beta openmm; fi - - if [ "$OPENMM" == "nightly" ]; then echo "Using OpenMM nightly dev build."; conda remove --yes --force openmm; conda clean -tipsy; conda install --yes --override-channels -c omnia-dev openmm; fi - - if [ "$OPENMM" == "conda-forge" ]; then echo "Using OpenMM conda-forge testing build."; conda remove --yes --force openmm; conda clean -tipsy; conda install --yes --override-channels -c conda-forge/label/testing openmm; fi + - if [ "$OPENMM" == "latest" ]; then echo "Using latest release OpenMM."; conda install --yes -c omnia openmm; fi + - if [ "$OPENMM" == "beta" ]; then echo "Using OpenMM beta"; conda install --yes -c omnia/label/beta openmm; fi + - if [ "$OPENMM" == "nightly" ]; then echo "Using OpenMM nightly dev build."; conda install --yes -c omnia-dev openmm; fi + - if [ "$OPENMM" == "conda-forge" ]; then echo "Using OpenMM conda-forge testing build."; conda install --yes -c conda-forge/label/testing openmm; fi script: From 6ab23d57aef8abea2dfc716972195211e37f0cd6 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Sat, 19 Oct 2019 00:09:02 -0400 Subject: [PATCH 109/152] Make sure to use 'latest' openmm for osx --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9bdc3f45f..43592938b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,10 +7,10 @@ matrix: # Extra includes for OSX since python language is not available by default on OSX - os: osx language: generic - env: PYTHON_VER=3.6 + env: PYTHON_VER=3.6 OPENMM="latest" - os: osx language: generic - env: PYTHON_VER=3.7 + env: PYTHON_VER=3.7 OPENMM="latest" - os: linux language: generic # No need to set Python version since its conda From e7090e009972e5ada993454187c705fd2521bbf1 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Sat, 19 Oct 2019 00:17:14 -0400 Subject: [PATCH 110/152] Fix alchemy test that was previously trying to alchemically modify only part of a TIP4P-Ew molecule --- openmmtools/tests/test_alchemy.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index 37383ebfd..f9a82877d 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -1269,11 +1269,16 @@ def define_regions(cls): cls.test_regions['LennardJonesCluster'] = AlchemicalRegion(alchemical_atoms=range(2)) cls.test_regions['LennardJonesFluid'] = AlchemicalRegion(alchemical_atoms=range(10)) cls.test_regions['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(3)) - cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(4)) # Modify ions. cls.test_regions['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6)) # Only partially modified. cls.test_regions['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22)) cls.test_regions['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156)) + # Modify ions. + for atom in cls.test_systems['TIP4P-EW WaterBox and NaCl with PME'].topology.atoms(): + if atom.name in ['Na', 'Cl']: + cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(atom.index, atom.index+1)) + + @classmethod def generate_cases(cls): """Generate all test cases in cls.test_cases combinatorially.""" From debcf2bc4d996c925d8a947c7f57e71a04bcdea7 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Sat, 19 Oct 2019 00:25:18 -0400 Subject: [PATCH 111/152] Clean up contexts in test that is segfaulting --- openmmtools/tests/test_alchemy.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index f9a82877d..2a380adb7 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -1720,12 +1720,14 @@ def test_apply_to_context(self): context = self.full_alanine_state.create_context(copy.deepcopy(integrator)) with nose.tools.assert_raises(AlchemicalStateError): alchemical_state.apply_to_context(context) + del context # Raise error if AlchemicalState is applied to a Context with missing parameters. alchemical_state = AlchemicalState.from_system(self.full_alanine_state.system) context = self.alanine_state.create_context(copy.deepcopy(integrator)) with nose.tools.assert_raises(AlchemicalStateError): alchemical_state.apply_to_context(context) + del context # Correctly sets Context's parameters. for state in [self.full_alanine_state, self.alanine_state_exact_pme]: From 28a429d4e7dbb35cedd3c2f27215d6dc83082995 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Sat, 19 Oct 2019 12:42:19 +0200 Subject: [PATCH 112/152] Update releasehistory.rst --- docs/releasehistory.rst | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 89abc4eb4..da37970b3 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -1,12 +1,20 @@ Release History *************** +0.19.0 - Multiple alchemical regions +==================================== + +New features +------------ +- Added support in ``AbsoluteAlchemicalFactory`` for handling multiple independent alchemical regions (`#438 `_). + + 0.18.2 - Bugfix release ======================= Bugfixes -------- -- A bug in the multistate samplers where``logsumexp`` was imported from ``scipy.misc`` (now in ``scipy.special``) was fixed (`#423 `_). +- A bug in the multistate samplers where``logsumexp`` was imported from ``scipy.misc`` (now in ``scipy.special``) was fixed (`#423 `_). - Improve the robustness of opening the netcdf file on resuming of the multi-state samplers by setting the environment variable HDF5_USE_FILE_LOCKING to FALSE after 4 failed attempts (`#426 `_). - Fixed a crash during exception handling (`#426 `_). From b500c6d3af51f799bb0d60b3fa8abdb7a8b90d03 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Sat, 19 Oct 2019 19:41:23 +0200 Subject: [PATCH 113/152] Fix reduced_potentials_at_states --- openmmtools/states.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/openmmtools/states.py b/openmmtools/states.py index aad42e21c..bf4159f7d 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -176,6 +176,8 @@ def reduced_potential_at_states(sampler_state, thermodynamic_states, context_cac for energy_idx, state_idx in enumerate(state_indices): reduced_potentials[state_idx] = compatible_energies[energy_idx] + return reduced_potentials + def group_by_compatibility(thermodynamic_states): """Utility function to split the thermodynamic states by compatibility. From 4b8155f9612378c7d73bccfa24307b469798803b Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Sat, 19 Oct 2019 19:45:50 +0200 Subject: [PATCH 114/152] Update releasehistory.rst --- docs/releasehistory.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index c580c78ec..b0b2dbbf9 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -8,6 +8,10 @@ New features ------------ - Added support in ``AbsoluteAlchemicalFactory`` for handling multiple independent alchemical regions (`#438 `_). +Bugfixes +-------- +- Fix return value in ``states.reduced_potential_at_states`` (`#444 `_). + 0.18.3 - Storage enhancements and bugfixes ========================================== From 0704db17f7ea11d726129e30d1c995699d99ac9a Mon Sep 17 00:00:00 2001 From: Chodera Date: Sat, 19 Oct 2019 13:53:59 -0400 Subject: [PATCH 115/152] Force removal of ocl-icd and ocl-icd-system to see if this prevents OpenMM from trying to use OpenCL platform on travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 43592938b..f7c7bcb7d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -60,7 +60,7 @@ install: - if [ "$OPENMM" == "latest" ]; then echo "Using latest release OpenMM."; conda install --yes -c omnia openmm; fi - if [ "$OPENMM" == "beta" ]; then echo "Using OpenMM beta"; conda install --yes -c omnia/label/beta openmm; fi - if [ "$OPENMM" == "nightly" ]; then echo "Using OpenMM nightly dev build."; conda install --yes -c omnia-dev openmm; fi - - if [ "$OPENMM" == "conda-forge" ]; then echo "Using OpenMM conda-forge testing build."; conda install --yes -c conda-forge/label/testing openmm; fi + - if [ "$OPENMM" == "conda-forge" ]; then echo "Using OpenMM conda-forge testing build."; conda install --yes -c conda-forge/label/testing openmm; conda remove --force ocl-icd ocl-icd-system; fi script: From 1de5a17ac16b4bd25b9579b11966a5c396898c75 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Sat, 19 Oct 2019 16:15:04 -0400 Subject: [PATCH 116/152] Fix bug introduced in last commit --- openmmtools/tests/test_alchemy.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openmmtools/tests/test_alchemy.py b/openmmtools/tests/test_alchemy.py index a693eb095..03e11a57b 100644 --- a/openmmtools/tests/test_alchemy.py +++ b/openmmtools/tests/test_alchemy.py @@ -1360,12 +1360,13 @@ def define_regions(cls): cls.test_regions['Toluene'] = AlchemicalRegion(alchemical_atoms=range(6)) # Only partially modified. cls.test_regions['AlanineDipeptide'] = AlchemicalRegion(alchemical_atoms=range(22)) cls.test_regions['HostGuestExplicit'] = AlchemicalRegion(alchemical_atoms=range(126, 156)) + cls.test_regions['TIP3P WaterBox'] = AlchemicalRegion(alchemical_atoms=range(0,3)) # Modify ions. for atom in cls.test_systems['TIP4P-EW WaterBox and NaCl with PME'].topology.atoms(): if atom.name in ['Na', 'Cl']: cls.test_regions['TIP4P-EW WaterBox and NaCl'] = AlchemicalRegion(alchemical_atoms=range(atom.index, atom.index+1)) - + break @classmethod def generate_cases(cls): From ba91110bf032a425ba6621b781df09184582a744 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Mon, 21 Oct 2019 17:15:18 -0400 Subject: [PATCH 117/152] Merge branch 'master' into other_barostats update release history refactor area->area_xy # Conflicts: # docs/releasehistory.rst --- docs/releasehistory.rst | 4 ++-- openmmtools/states.py | 18 +++++++++--------- openmmtools/tests/test_states.py | 6 +++--- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 2b46a0baa..e24eaf8cd 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -7,8 +7,8 @@ Release History New features ------------ - Added support in ``AbsoluteAlchemicalFactory`` for handling multiple independent alchemical regions (`#438 `_). -- Added support for anisotropic and membrane barostats in `ThermodynamicState` -- Added support for platform properties in ContextCache (e.g. for mixed and double precision CUDA in multistate sampler) +- Added support for anisotropic and membrane barostats in `ThermodynamicState` (`#437 `_) +- Added support for platform properties in ContextCache (e.g. for mixed and double precision CUDA in multistate sampler) (`#437 `_) 0.18.3 - Storage enhancements and bugfixes ========================================== diff --git a/openmmtools/states.py b/openmmtools/states.py index 3933b9d52..55906fa2c 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -242,7 +242,7 @@ def _box_vectors_volume(box_vectors): return np.linalg.det(box_matrix) * a.unit**3 -def _box_vectors_area(box_vectors): +def _box_vectors_area_xy(box_vectors): """Return the xy-area of the box vectors. Parameters @@ -253,7 +253,7 @@ def _box_vectors_area(box_vectors): Returns ------- - area : simtk.unit.Quantity + area_xy : simtk.unit.Quantity The box area in units of length^2. """ return box_vectors[0][0] * box_vectors[1][1] @@ -882,12 +882,12 @@ def reduced_potential(self, context_state): openmm_state = context_state.getState(getEnergy=True) potential_energy = openmm_state.getPotentialEnergy() volume = openmm_state.getPeriodicBoxVolume() - area = _box_vectors_area(openmm_state.getPeriodicBoxVectors()) + area = _box_vectors_area_xy(openmm_state.getPeriodicBoxVectors()) else: n_particles = context_state.n_particles potential_energy = context_state.potential_energy volume = context_state.volume - area = context_state.area + area = context_state.area_xy # Check compatibility. if n_particles != self.n_particles: @@ -1833,14 +1833,14 @@ def _set_system_temperature(cls, system, temperature): # ------------------------------------------------------------------------- @staticmethod - def _compute_reduced_potential(potential_energy, temperature, volume, pressure, area=None, surface_tension=None): + def _compute_reduced_potential(potential_energy, temperature, volume, pressure, area_xy=None, surface_tension=None): """Convert potential energy into reduced potential.""" beta = 1.0 / (unit.BOLTZMANN_CONSTANT_kB * temperature) reduced_potential = potential_energy / unit.AVOGADRO_CONSTANT_NA if pressure is not None: reduced_potential += pressure * volume - if area is not None and surface_tension is not None: - reduced_potential -= surface_tension * area + if area_xy is not None and surface_tension is not None: + reduced_potential -= surface_tension * area_xy return beta * reduced_potential def _find_force_groups_to_update(self, context, thermodynamic_state, memo): @@ -2106,9 +2106,9 @@ def volume(self): return _box_vectors_volume(self.box_vectors) @property - def area(self): + def area_xy(self): """The xy-area of the box (read-only)""" - return _box_vectors_area(self.box_vectors) + return _box_vectors_area_xy(self.box_vectors) @property def n_particles(self): diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index 1c1dd91c1..083044714 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -859,8 +859,8 @@ def test_method_reduced_potential(self): reduced_potential = state.reduced_potential(sampler_state) pressure_volume_work = (self.std_pressure * sampler_state.volume * unit.AVOGADRO_CONSTANT_NA) - surface_work = (self.std_surface_tension * sampler_state.area * - unit.AVOGADRO_CONSTANT_NA) + surface_work = (self.std_surface_tension * sampler_state.area_xy * + unit.AVOGADRO_CONSTANT_NA) potential_energy = (reduced_potential / beta - pressure_volume_work + surface_work) / kj_mol assert np.isclose(sampler_state.potential_energy / kj_mol, potential_energy) @@ -1117,7 +1117,7 @@ def test_operator_getitem(self): # The other attributes are copied correctly. assert sliced_sampler_state.volume == sampler_state.volume - assert sliced_sampler_state.area == sampler_state.area + assert sliced_sampler_state.area_xy == sampler_state.area_xy # Energies are undefined for as subset of atoms. assert sliced_sampler_state.kinetic_energy is None From e4b6b06383281aadfe638907fd00d90ba4dfec71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Tue, 22 Oct 2019 16:17:44 -0400 Subject: [PATCH 118/152] ContextCache refactoring --- openmmtools/cache.py | 44 +++++++++++++++++++++++++++++-- openmmtools/tests/test_cache.py | 46 +++++++++++++++++++++++++++++---- 2 files changed, 83 insertions(+), 7 deletions(-) diff --git a/openmmtools/cache.py b/openmmtools/cache.py index 62f1f86c7..619e45530 100644 --- a/openmmtools/cache.py +++ b/openmmtools/cache.py @@ -307,10 +307,9 @@ class ContextCache(object): """ def __init__(self, platform=None, platform_properties=None, **kwargs): + self._validate_platform_properties(platform, platform_properties) self._platform = platform self._platform_properties = platform_properties - if platform_properties is not None and platform is None: - raise ValueError("To set platform_properties, you need to also specify the platform.") self._lru = LRUCache(**kwargs) def __len__(self): @@ -330,7 +329,17 @@ def platform(self): def platform(self, new_platform): if len(self._lru) > 0: raise RuntimeError('Cannot change platform of a non-empty ContextCache') + if new_platform is None: + self._platform_properties = None + self._validate_platform_properties(new_platform, self._platform_properties) + self._platform = new_platform + + def set_platform(self, new_platform, platform_properties=None): + if len(self._lru) > 0: + raise RuntimeError('Cannot change platform of a non-empty ContextCache') + self._validate_platform_properties(new_platform, platform_properties) self._platform = new_platform + self._platform_properties = platform_properties @property def capacity(self): @@ -448,6 +457,7 @@ def get_context(self, thermodynamic_state, integrator=None): return context, context_integrator def __getstate__(self): + # this serialization format was introduced in openmmtools > 0.18.3 (pull request #437) if self.platform is not None: platform_serialization = self.platform.getName() else: @@ -456,6 +466,7 @@ def __getstate__(self): time_to_live=self.time_to_live, platform_properties=self._platform_properties) def __setstate__(self, serialization): + # this serialization format was introduced in openmmtools > 0.18.3 (pull request #437) if serialization['platform'] is None: self._platform = None else: @@ -640,6 +651,35 @@ def _default_integrator_id(cls): return cls._cached_default_integrator_id _cached_default_integrator_id = None + @staticmethod + def _validate_platform_properties(platform=None, platform_properties=None): + """Check if platform properties are valid for the platform; else raise ValueError.""" + if platform_properties is None: + return True + if platform_properties is not None and platform is None: + raise ValueError("To set platform_properties, you need to also specify the platform.") + if not isinstance(platform_properties, dict): + raise ValueError("platform_properties must be a dictionary") + for key, value in platform_properties.items(): + if not isinstance(value, str): + raise ValueError( + "All platform properties must be strings. You supplied {}: {} of type {}".format( + key, value, type(value) + ) + ) + # create a context to check if all properties are + dummy_system = openmm.System() + dummy_system.addParticle(1) + dummy_integrator = openmm.VerletIntegrator(1.0*unit.femtoseconds) + try: + openmm.Context(dummy_system, dummy_integrator, platform, platform_properties) + return True + except Exception as e: + if "Illegal property name" in str(e): + raise ValueError("Invalid platform property for this platform. {}".format(e)) + else: + raise e + # ============================================================================= # DUMMY CONTEXT CACHE diff --git a/openmmtools/tests/test_cache.py b/openmmtools/tests/test_cache.py index 1d62248eb..7fbe4ce3b 100644 --- a/openmmtools/tests/test_cache.py +++ b/openmmtools/tests/test_cache.py @@ -359,16 +359,52 @@ def test_platform_property(self): cache.platform = platforms[0] def test_platform_properties(self): - # Failure test + # Failure tests + # no platform specified platform_properties = {"CpuThreads": "2"} with nose.tools.assert_raises(ValueError) as cm: ContextCache(platform=None, platform_properties=platform_properties) - assert str(cm.exception) == "To set platform_properties, you need to also specify the platform." + # non-string value in properties + cpu_platform = openmm.Platform.getPlatformByName("CPU") + ref_platform = openmm.Platform.getPlatformByName("Reference") + with nose.tools.assert_raises(ValueError) as cm: + ContextCache(platform=cpu_platform, platform_properties={"CpuThreads": 2}) + assert "All platform properties must be strings." in str(cm.exception) + # non-dict properties + with nose.tools.assert_raises(ValueError) as cm: + ContextCache(platform=cpu_platform, platform_properties="jambalaya") + assert str(cm.exception) == "platform_properties must be a dictionary" + # invalid property + with nose.tools.assert_raises(ValueError) as cm: + ContextCache(platform=cpu_platform, platform_properties={"jambalaya": "2"}) + assert "Invalid platform property for this platform." in str(cm.exception) + + # setter + cache = ContextCache( + platform=cpu_platform, + platform_properties=platform_properties + ) + with nose.tools.assert_raises(ValueError) as cm: + cache.platform = ref_platform + assert "Invalid platform property for this platform." in str(cm.exception) + # this should work + cache.set_platform(ref_platform) + assert cache.platform == ref_platform + # assert errors are checked in set_platform + with nose.tools.assert_raises(ValueError) as cm: + cache.set_platform(cpu_platform, platform_properties={"jambalaya": "2"}) + assert "Invalid platform property for this platform." in str(cm.exception) + # assert that resetting the platform resets the properties + cache = ContextCache( + platform=cpu_platform, + platform_properties=platform_properties + ) + cache.platform = None + assert cache._platform_properties is None - # test - platform = openmm.Platform.getPlatformByName("CPU") + # Functionality test cache = ContextCache( - platform=platform, + platform=cpu_platform, platform_properties=platform_properties ) thermodynamic_state = copy.deepcopy(self.water_300k) From fb94572263a1ae5897025ea99aea65c7a2e15be5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Wed, 23 Oct 2019 10:30:24 -0400 Subject: [PATCH 119/152] ThermodynamicState refactoring for surface tension --- openmmtools/states.py | 130 +++++++++++++++++++++++-------- openmmtools/tests/test_states.py | 28 ++++--- 2 files changed, 114 insertions(+), 44 deletions(-) diff --git a/openmmtools/states.py b/openmmtools/states.py index 55906fa2c..5125ea8fb 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -316,7 +316,7 @@ class ThermodynamicsError(Exception): UNSUPPORTED_ANISOTROPIC_BAROSTAT: "MonteCarloAnisotropicBarostat is only supported if the pressure along all scaled axes is the same.", SURFACE_TENSION_NOT_SUPPORTED: - "Surface tension can only be set for states that have a system with a MonteCarloBarostat.", + "Surface tension can only be set for states that have a system with a MonteCarloMembraneBarostat.", NO_BAROSTAT: "System does not have a barostat specifying the pressure.", INCONSISTENT_BAROSTAT: "System barostat is inconsistent with thermodynamic state.", BAROSTATED_NONPERIODIC: "Non-periodic systems cannot have a barostat.", @@ -413,6 +413,11 @@ class ThermodynamicState(object): or just set to this pressure in case it already exists. If None, the pressure is inferred from the system barostat, and NVT ensemble is assumed if there is no barostat. + surface_tension : simtk.unit.Quantity, optional + The surface tension for the system at constant surface tension. + If this is specified, the system must have a MonteCarloMembraneBarostat. + If None, the surface_tension is inferred from the barostat and + NPT/NVT ensemble is assumed if there is no MonteCarloMembraneBarostat. Attributes ---------- @@ -493,8 +498,8 @@ class ThermodynamicState(object): # Public interface # ------------------------------------------------------------------------- - def __init__(self, system, temperature=None, pressure=None): - self._initialize(system, temperature, pressure) + def __init__(self, system, temperature=None, pressure=None, surface_tension=None): + self._initialize(system, temperature, pressure, surface_tension) @property def system(self): @@ -632,6 +637,7 @@ def get_system(self, remove_thermostat=False, remove_barostat=False): self._pop_barostat(system) else: # Set pressure of standard barostat. self._set_system_pressure(system, self.pressure) + self._set_system_surface_tension(system, self.surface_tension) # Set temperature of standard thermostat and barostat. if not (remove_barostat and remove_thermostat): @@ -709,6 +715,8 @@ def barostat(self): if barostat is not None: # NPT ensemble. self._set_barostat_pressure(barostat, self.pressure) self._set_barostat_temperature(barostat, self.temperature) + if self.surface_tension is not None: + self._set_barostat_surface_tension(barostat, self.surface_tension) return barostat @barostat.setter @@ -716,10 +724,15 @@ def barostat(self, new_barostat): # If None, just remove the barostat from the standard system. if new_barostat is None: self.pressure = None + self.surface_tension = None return - # Remember old pressure in case something goes wrong. + # Remember old pressure and surface tension in case something goes wrong. old_pressure = self.pressure + old_surface_tension = self.surface_tension + # make sure that the barostat type does not change + if self.barostat is not None and type(new_barostat) is not type(self.barostat): + raise ThermodynamicsError(ThermodynamicsError.INCONSISTENT_BAROSTAT) # Build the system with the new barostat. system = self.get_system(remove_barostat=True) @@ -729,9 +742,11 @@ def barostat(self, new_barostat): # pressure if something goes wrong (e.g. the system is not periodic). try: self._pressure = self._get_barostat_pressure(new_barostat) + self._surface_tension = self._get_barostat_surface_tension(new_barostat) self._unsafe_set_system(system, fix_state=False) except ThermodynamicsError: self._pressure = old_pressure + self._surface_tension = old_surface_tension raise @property @@ -784,23 +799,15 @@ def is_periodic(self): @property def surface_tension(self): - """Surface tension; None if the barostat is not a MonteCarloMembraneBarostat""" - barostat = self._find_barostat(self._standard_system) - if isinstance(barostat, openmm.MonteCarloMembraneBarostat): - return barostat.getDefaultSurfaceTension() - else: - return None + """Surface tension""" + return self._surface_tension @surface_tension.setter def surface_tension(self, gamma): - # working around a bug in the unit conversion https://github.com/openmm/openmm/issues/2406 - if isinstance(gamma, unit.Quantity): - gamma = gamma.value_in_unit(unit.bar * unit.nanometer) - barostat = self._find_barostat(self._standard_system) - if isinstance(barostat, openmm.MonteCarloMembraneBarostat): - barostat.setDefaultSurfaceTension(gamma) - else: + if (self._surface_tension is None) != (gamma is None): raise ThermodynamicsError(ThermodynamicsError.SURFACE_TENSION_NOT_SUPPORTED) + else: + self._surface_tension = gamma def reduced_potential(self, context_state): """Reduced potential in this thermodynamic state. @@ -934,7 +941,9 @@ def reduced_potential_at_states(cls, context, thermodynamic_states): # In NPT, we'll need also the volume. is_npt = thermodynamic_states[0].pressure is not None + is_npgammat = thermodynamic_states[0].surface_tension is not None volume = None + area_xy = None energy_by_force_group = {force.getForceGroup(): 0.0*unit.kilocalories_per_mole for force in context.getSystem().getForces()} @@ -960,11 +969,13 @@ def reduced_potential_at_states(cls, context, thermodynamic_states): # Compute volume if this is the first time we obtain a state. if is_npt and volume is None: volume = openmm_state.getPeriodicBoxVolume() + if is_npgammat and area_xy is None: + area_xy = _box_vectors_area_xy(openmm_state.getPeriodicBoxVectors()) # Compute the new total reduced potential. potential_energy = unit.sum(list(energy_by_force_group.values())) reduced_potential = cls._compute_reduced_potential(potential_energy, state.temperature, - volume, state.pressure) + volume, state.pressure, area_xy, state.surface_tension) reduced_potentials[state_idx] = reduced_potential # Update groups to compute for next states. @@ -1258,12 +1269,13 @@ def __getstate__(self, skip_system=False): serialized_system = openmm.XmlSerializer.serialize(self._standard_system) serialized_system = zlib.compress(serialized_system.encode(self._ENCODING)) return dict(standard_system=serialized_system, temperature=self.temperature, - pressure=self.pressure) + pressure=self.pressure, surface_tension=self._surface_tension) def __setstate__(self, serialization): """Set the state from a dictionary representation.""" self._temperature = serialization['temperature'] self._pressure = serialization['pressure'] + self._surface_tension = serialization['surface_tension'] serialized_system = serialization['standard_system'] # Decompress system, if need be @@ -1292,7 +1304,7 @@ def __setstate__(self, serialization): # Internal-usage: initialization # ------------------------------------------------------------------------- - def _initialize(self, system, temperature=None, pressure=None): + def _initialize(self, system, temperature=None, pressure=None, surface_tension=None): """Initialize the thermodynamic state.""" # Avoid modifying the original system when setting temperature and pressure. system = copy.deepcopy(system) @@ -1303,9 +1315,15 @@ def _initialize(self, system, temperature=None, pressure=None): self._pressure = self._get_barostat_pressure(barostat) else: self._pressure = pressure # Pressure here can also be None. - self._barostat_type = openmm.MonteCarloBarostat - if barostat is not None: - self._barostat_type = type(barostat) + + # If surface tension is None, we try to infer the pressure from the barostat. + barostat_type = type(barostat) + if surface_tension is None and barostat_type == openmm.MonteCarloMembraneBarostat: + self._surface_tension = barostat.getDefaultSurfaceTension() + elif surface_tension is not None and barostat_type != openmm.MonteCarloMembraneBarostat: + raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) + else: + self._surface_tension = surface_tension # If temperature is None, we infer the temperature from a thermostat. if temperature is None: @@ -1321,6 +1339,8 @@ def _initialize(self, system, temperature=None, pressure=None): self._set_system_temperature(system, temperature) if pressure is not None: self._set_system_pressure(system, pressure) + if surface_tension is not None: + self._set_system_surface_tension(system, surface_tension) # We can use the unsafe set_system since the system has been copied. self._unsafe_set_system(system, fix_state=False) @@ -1336,6 +1356,7 @@ def _initialize(self, system, temperature=None, pressure=None): # caused by unit conversion. _STANDARD_PRESSURE = 1.0*unit.bar _STANDARD_TEMPERATURE = 273.0*unit.kelvin + _STANDARD_SURFACE_TENSION = 0.0*unit.nanometer*unit.bar _NONPERIODIC_NONBONDED_METHODS = {openmm.NonbondedForce.NoCutoff, openmm.NonbondedForce.CutoffNonPeriodic} @@ -1351,12 +1372,13 @@ def _unsafe_set_system(self, system, fix_state): # Configure temperature and pressure. if fix_state: # We just need to add/remove the barostat according to the ensemble. - # Temperature and pressure of thermostat and barostat will be set + # Temperature, pressure, surface tension of thermostat and barostat will be set # to their standard value afterwards. self._set_system_pressure(system, self.pressure) + self._set_system_surface_tension(system, self.surface_tension) else: # If the flag is deactivated, we check that temperature - # and pressure of the system are correct. + # pressure, and surface tension of the system are correct. self._check_system_consistency(system) # Update standard system. @@ -1455,6 +1477,8 @@ def _standardize_system(self, system): barostat = self._pop_barostat(system) if barostat is not None: self._set_barostat_pressure(barostat, self._STANDARD_PRESSURE) + if isinstance(barostat, openmm.MonteCarloMembraneBarostat): + self._set_barostat_surface_tension(barostat, self._STANDARD_SURFACE_TENSION) system.addForce(barostat) def _compute_standard_system_hash(self, standard_system): @@ -1483,15 +1507,20 @@ def _set_context_barostat(self, context, update_pressure, update_temperature, up if (barostat is None) != (self._pressure is None): raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) + if (type(barostat) is openmm.MonteCarloMembraneBarostat) == (self._surface_tension is None): + raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) + # No need to set the barostat if we are in NVT. if self._pressure is None: return - # Apply pressure and temperature to barostat. + # Apply pressure, surface tension, and temperature to barostat. if update_pressure: self._set_barostat_pressure(barostat, self.pressure) self._set_barostat_pressure_in_context(barostat, self.pressure, context) + if self.surface_tension is not None and update_surface_tension: + self._set_barostat_surface_tension(barostat, self.surface_tension) self._set_barostat_surface_tension_in_context(barostat, self.surface_tension, context) if update_temperature: @@ -1534,7 +1563,7 @@ def _apply_to_context_in_state(self, context, thermodynamic_state): update_temperature = self.temperature != thermodynamic_state.temperature update_surface_tension = self.surface_tension != thermodynamic_state.surface_tension - if update_pressure or update_temperature: + if update_pressure or update_temperature or update_surface_tension: self._set_context_barostat(context, update_pressure, update_temperature, update_surface_tension) if update_temperature: self._set_context_thermostat(context) @@ -1618,6 +1647,11 @@ def set_temp(_integrator): _SUPPORTED_BAROSTATS = {'MonteCarloBarostat', 'MonteCarloAnisotropicBarostat', 'MonteCarloMembraneBarostat'} + @property + def _barostat_type(self): + barostat = self._find_barostat(self._standard_system) + return type(barostat) + @classmethod def _find_barostat(cls, system, get_index=False): """Return the first barostat found in the system. @@ -1677,16 +1711,20 @@ def _pop_barostat(cls, system): return None def _is_barostat_consistent(self, barostat): - """Check the barostat's type, temperature and pressure.""" + """Check the barostat's, temperature, pressure, and surface_tension.""" try: barostat_temperature = barostat.getDefaultTemperature() except AttributeError: # versions previous to OpenMM 7.1 barostat_temperature = barostat.getTemperature() barostat_pressure = self._get_barostat_pressure(barostat) - is_consistent = (type(barostat) is self._barostat_type) - is_consistent = is_consistent and utils.is_quantity_close(barostat_temperature, self.temperature) - is_consistent = is_consistent and utils.is_quantity_close(barostat_pressure, - self.pressure) + barostat_surface_tension = self._get_barostat_surface_tension(barostat) + + is_consistent = utils.is_quantity_close(barostat_temperature, self.temperature) + is_consistent = is_consistent and utils.is_quantity_close(barostat_pressure, self.pressure) + if barostat is not None and self._surface_tension is not None: + is_consistent = is_consistent and utils.is_quantity_close(barostat_surface_tension, self._surface_tension) + else: + is_consistent = is_consistent and (barostat_surface_tension == self._surface_tension) # both None return is_consistent def _set_system_pressure(self, system, pressure): @@ -1757,6 +1795,32 @@ def _set_barostat_temperature(barostat, temperature): """Set barostat temperature.""" barostat.setDefaultTemperature(temperature) + def _set_system_surface_tension(self, system, gamma): + """Set system surface tension""" + if gamma is not None and not system.usesPeriodicBoundaryConditions(): + raise ThermodynamicsError(ThermodynamicsError.BAROSTATED_NONPERIODIC) + barostat = self._find_barostat(system) + if (gamma is None) == isinstance(barostat, openmm.MonteCarloMembraneBarostat): + raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) + self._set_barostat_surface_tension(barostat, gamma) + + + def _set_barostat_surface_tension(self, barostat, gamma): + # working around a bug in the unit conversion https://github.com/openmm/openmm/issues/2406 + if isinstance(gamma, unit.Quantity): + gamma = gamma.value_in_unit(unit.bar * unit.nanometer) + # barostat = self._find_barostat(system) + if isinstance(barostat, openmm.MonteCarloMembraneBarostat): + barostat.setDefaultSurfaceTension(gamma) + elif gamma is not None: + raise ThermodynamicsError(ThermodynamicsError.SURFACE_TENSION_NOT_SUPPORTED) + + def _get_barostat_surface_tension(self, barostat): + if isinstance(barostat, openmm.MonteCarloMembraneBarostat): + return barostat.getDefaultSurfaceTension() + else: + return None + @staticmethod def _set_barostat_surface_tension_in_context(barostat, surface_tension, context): """Set barostat surface tension.""" @@ -1765,7 +1829,7 @@ def _set_barostat_surface_tension_in_context(barostat, surface_tension, context) surface_tension = surface_tension.value_in_unit(unit.nanometer*unit.bar) try: context.getParameter(barostat.SurfaceTension()) - except Exception as e: + except Exception: raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) context.setParameter(barostat.SurfaceTension(), surface_tension) diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index 083044714..d5c0753dd 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -236,7 +236,7 @@ def test_method_is_barostat_consistent(self): barostat = openmm.MonteCarloBarostat(pressure, temperature + 10*unit.kelvin) assert not state._is_barostat_consistent(barostat) - assert not state._is_barostat_consistent(self.supported_anisotropic_barostat) + #assert not state._is_barostat_consistent(self.supported_anisotropic_barostat) assert not state._is_barostat_consistent(self.membrane_barostat_gamma_zero) def test_method_set_system_temperature(self): @@ -365,15 +365,15 @@ def test_property_pressure_barostat(self): state.barostat = self.unsupported_anisotropic_barostat assert cm.exception.code == ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT - # Assign non-standard barostat raise error - with nose.tools.assert_raises(ThermodynamicsError) as cm: - state.barostat = self.supported_anisotropic_barostat - assert cm.exception.code == ThermodynamicsError.INCONSISTENT_BAROSTAT - - # Assign non-standard barostat raise error - with nose.tools.assert_raises(ThermodynamicsError) as cm: - state.barostat = self.membrane_barostat_gamma_zero - assert cm.exception.code == ThermodynamicsError.INCONSISTENT_BAROSTAT + # Assign barostat with different type raise error + if state.barostat is not None and type(state.barostat) != type(self.supported_anisotropic_barostat): + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state.barostat = self.supported_anisotropic_barostat + assert cm.exception.code == ThermodynamicsError.INCONSISTENT_BAROSTA + if state.barostat is not None and type(state.barostat) != type(self.membrane_barostat_gamma_zero): + with nose.tools.assert_raises(ThermodynamicsError) as cm: + state.barostat = self.membrane_barostat_gamma_zero + assert cm.exception.code == ThermodynamicsError.INCONSISTENT_BAROSTAT # After exception, state is left consistent assert state.pressure is None @@ -437,7 +437,7 @@ def test_property_system(self): (self.barostated_toluene, TE.BAROSTATED_NONPERIODIC), (self.multiple_barostat_alanine, TE.MULTIPLE_BAROSTATS), (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT), - (self.supported_anisotropic_barostat_alanine, TE.INCONSISTENT_BAROSTAT), + #(self.supported_anisotropic_barostat_alanine, TE.INCONSISTENT_BAROSTAT), (self.membrane_barostat_alanine_gamma_zero, TE.INCONSISTENT_BAROSTAT), (self.inconsistent_pressure_alanine, TE.INCONSISTENT_BAROSTAT), (self.inconsistent_temperature_alanine, TE.INCONSISTENT_THERMOSTAT), @@ -726,6 +726,12 @@ def check_compatibility(state1, state2, is_compatible): barostated_alanine2.pressure = barostated_alanine.pressure + 0.2*unit.bars check_compatibility(barostated_alanine, barostated_alanine2, True) + check_compatibility( + ThermodynamicState(self.membrane_barostat_alanine_gamma_zero), + ThermodynamicState(self.membrane_barostat_alanine_gamma_nonzero), + True + ) + def test_method_apply_to_context(self): """ThermodynamicState.apply_to_context() method.""" friction = 5.0/unit.picosecond From 101915a7c56dd15bac45998a6af1d6023386eba8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Wed, 23 Oct 2019 16:30:00 -0400 Subject: [PATCH 120/152] ThermodynamicState._is_barostat_type_consistent --- openmmtools/states.py | 19 ++++++++++++++----- openmmtools/tests/test_states.py | 7 ++++++- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/openmmtools/states.py b/openmmtools/states.py index 5125ea8fb..a67dcdabe 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -1421,9 +1421,6 @@ def _check_system_consistency(self, system): # This line raises MULTIPLE_BAROSTATS and UNSUPPORTED_BAROSTAT. barostat = self._find_barostat(system) if barostat is not None: - if not self._is_barostat_consistent(barostat): - raise TE(TE.INCONSISTENT_BAROSTAT) - # Check that barostat is not added to non-periodic system. We # cannot use System.usesPeriodicBoundaryConditions() because # in OpenMM < 7.1 that returns True when a barostat is added. @@ -1433,6 +1430,10 @@ def _check_system_consistency(self, system): nonbonded_method = force.getNonbondedMethod() if nonbonded_method in self._NONPERIODIC_NONBONDED_METHODS: raise TE(TE.BAROSTATED_NONPERIODIC) + + if not self._is_barostat_consistent(barostat): + raise TE(TE.INCONSISTENT_BAROSTAT) + elif self.pressure is not None: raise TE(TE.NO_BAROSTAT) @@ -1710,8 +1711,15 @@ def _pop_barostat(cls, system): return barostat return None + def _is_barostat_type_consistent(self, barostat): + # during initialization (standard system not set), any barostat type is OK + if not hasattr(self, "_standard_system"): + return True + system_barostat = self._find_barostat(self._standard_system) + return type(barostat) == type(system_barostat) + def _is_barostat_consistent(self, barostat): - """Check the barostat's, temperature, pressure, and surface_tension.""" + """Check the barostat's temperature, pressure, and surface_tension.""" try: barostat_temperature = barostat.getDefaultTemperature() except AttributeError: # versions previous to OpenMM 7.1 @@ -1719,7 +1727,8 @@ def _is_barostat_consistent(self, barostat): barostat_pressure = self._get_barostat_pressure(barostat) barostat_surface_tension = self._get_barostat_surface_tension(barostat) - is_consistent = utils.is_quantity_close(barostat_temperature, self.temperature) + is_consistent = self._is_barostat_type_consistent(barostat) + is_consistent = is_consistent and utils.is_quantity_close(barostat_temperature, self.temperature) is_consistent = is_consistent and utils.is_quantity_close(barostat_pressure, self.pressure) if barostat is not None and self._surface_tension is not None: is_consistent = is_consistent and utils.is_quantity_close(barostat_surface_tension, self._surface_tension) diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index d5c0753dd..b0a5deb92 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -236,7 +236,7 @@ def test_method_is_barostat_consistent(self): barostat = openmm.MonteCarloBarostat(pressure, temperature + 10*unit.kelvin) assert not state._is_barostat_consistent(barostat) - #assert not state._is_barostat_consistent(self.supported_anisotropic_barostat) + assert not state._is_barostat_consistent(self.supported_anisotropic_barostat) assert not state._is_barostat_consistent(self.membrane_barostat_gamma_zero) def test_method_set_system_temperature(self): @@ -731,6 +731,11 @@ def check_compatibility(state1, state2, is_compatible): ThermodynamicState(self.membrane_barostat_alanine_gamma_nonzero), True ) + check_compatibility( + ThermodynamicState(self.barostated_alanine), + ThermodynamicState(self.membrane_barostat_alanine_gamma_nonzero), + False + ) def test_method_apply_to_context(self): """ThermodynamicState.apply_to_context() method.""" From d1c18125e764b148dc3e2925b53dfb08956a5a37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Sat, 26 Oct 2019 12:02:26 -0400 Subject: [PATCH 121/152] final cleanup of other barostats in ThermodynamicState --- openmmtools/states.py | 9 +-------- openmmtools/tests/test_states.py | 2 +- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/openmmtools/states.py b/openmmtools/states.py index a67dcdabe..df351a888 100644 --- a/openmmtools/states.py +++ b/openmmtools/states.py @@ -1316,7 +1316,7 @@ def _initialize(self, system, temperature=None, pressure=None, surface_tension=N else: self._pressure = pressure # Pressure here can also be None. - # If surface tension is None, we try to infer the pressure from the barostat. + # If surface tension is None, we try to infer the surface tension from the barostat. barostat_type = type(barostat) if surface_tension is None and barostat_type == openmm.MonteCarloMembraneBarostat: self._surface_tension = barostat.getDefaultSurfaceTension() @@ -1648,11 +1648,6 @@ def set_temp(_integrator): _SUPPORTED_BAROSTATS = {'MonteCarloBarostat', 'MonteCarloAnisotropicBarostat', 'MonteCarloMembraneBarostat'} - @property - def _barostat_type(self): - barostat = self._find_barostat(self._standard_system) - return type(barostat) - @classmethod def _find_barostat(cls, system, get_index=False): """Return the first barostat found in the system. @@ -1813,12 +1808,10 @@ def _set_system_surface_tension(self, system, gamma): raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) self._set_barostat_surface_tension(barostat, gamma) - def _set_barostat_surface_tension(self, barostat, gamma): # working around a bug in the unit conversion https://github.com/openmm/openmm/issues/2406 if isinstance(gamma, unit.Quantity): gamma = gamma.value_in_unit(unit.bar * unit.nanometer) - # barostat = self._find_barostat(system) if isinstance(barostat, openmm.MonteCarloMembraneBarostat): barostat.setDefaultSurfaceTension(gamma) elif gamma is not None: diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index b0a5deb92..f230aa93c 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -437,7 +437,7 @@ def test_property_system(self): (self.barostated_toluene, TE.BAROSTATED_NONPERIODIC), (self.multiple_barostat_alanine, TE.MULTIPLE_BAROSTATS), (self.unsupported_anisotropic_barostat_alanine, TE.UNSUPPORTED_ANISOTROPIC_BAROSTAT), - #(self.supported_anisotropic_barostat_alanine, TE.INCONSISTENT_BAROSTAT), + (self.supported_anisotropic_barostat_alanine, TE.INCONSISTENT_BAROSTAT), (self.membrane_barostat_alanine_gamma_zero, TE.INCONSISTENT_BAROSTAT), (self.inconsistent_pressure_alanine, TE.INCONSISTENT_BAROSTAT), (self.inconsistent_temperature_alanine, TE.INCONSISTENT_THERMOSTAT), From 8f614415fcbe65f6b0e78048c2b4ba05b7c6b094 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Sat, 26 Oct 2019 16:14:30 -0700 Subject: [PATCH 122/152] Convert API warnings from warnings.warn() to logger.warn() --- openmmtools/multistate/mixing/_mix_replicas.c | 2120 +++++++++-------- openmmtools/multistate/multistateanalyzer.py | 4 +- openmmtools/multistate/multistatereporter.py | 7 +- openmmtools/multistate/multistatesampler.py | 3 +- 4 files changed, 1112 insertions(+), 1022 deletions(-) diff --git a/openmmtools/multistate/mixing/_mix_replicas.c b/openmmtools/multistate/mixing/_mix_replicas.c index f4edbde40..ffd0c3578 100644 --- a/openmmtools/multistate/mixing/_mix_replicas.c +++ b/openmmtools/multistate/mixing/_mix_replicas.c @@ -1,4 +1,4 @@ -/* Generated by Cython 0.29.4 */ +/* Generated by Cython 0.29.13 */ /* BEGIN: Cython Metadata { @@ -20,8 +20,8 @@ END: Cython Metadata */ #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_4" -#define CYTHON_HEX_VERSION 0x001D04F0 +#define CYTHON_ABI "0_29_13" +#define CYTHON_HEX_VERSION 0x001D0DF0 #define CYTHON_FUTURE_DIVISION 0 #include #ifndef offsetof @@ -323,8 +323,13 @@ END: Cython Metadata */ #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" +#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#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 @@ -359,26 +364,6 @@ END: Cython Metadata */ #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif -#if CYTHON_USE_DICT_VERSIONS -#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);\ - }\ - } -#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 #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) @@ -640,7 +625,8 @@ typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* enc 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_DEFAULT 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 @@ -1014,7 +1000,7 @@ struct __pyx_memoryview_obj { }; -/* "View.MemoryView":961 +/* "View.MemoryView":965 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< @@ -1065,7 +1051,7 @@ struct __pyx_vtabstruct_memoryview { static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; -/* "View.MemoryView":961 +/* "View.MemoryView":965 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< @@ -1257,7 +1243,7 @@ static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObje #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, int nargs, PyObject *kwargs); +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 @@ -1374,6 +1360,32 @@ static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tsta /* GetAttr3.proto */ static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); +/* 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) {\ @@ -5201,7 +5213,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal * 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); @@ -5211,8 +5223,8 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal * def __dealloc__(memoryview self): * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< + * elif (<__pyx_buffer *> &self.view).obj == Py_None: * - * cdef int i */ __Pyx_ReleaseBuffer((&__pyx_v_self->view)); @@ -5221,11 +5233,50 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal * 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":375 + * 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":377 + * 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":378 + * + * (<__pyx_buffer *> &self.view).obj = NULL + * Py_DECREF(Py_None) # <<<<<<<<<<<<<< + * + * cdef int i + */ + Py_DECREF(Py_None); + + /* "View.MemoryView":375 + * 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":378 + /* "View.MemoryView":382 * cdef int i * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< @@ -5235,7 +5286,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); if (__pyx_t_2) { - /* "View.MemoryView":379 + /* "View.MemoryView":383 * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< @@ -5247,7 +5298,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; - /* "View.MemoryView":380 + /* "View.MemoryView":384 * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< @@ -5257,7 +5308,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); if (__pyx_t_2) { - /* "View.MemoryView":381 + /* "View.MemoryView":385 * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< @@ -5266,7 +5317,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal */ __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); - /* "View.MemoryView":382 + /* "View.MemoryView":386 * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< @@ -5276,7 +5327,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); if (__pyx_t_2) { - /* "View.MemoryView":384 + /* "View.MemoryView":388 * 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]) # <<<<<<<<<<<<<< @@ -5286,7 +5337,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); __pyx_t_7 = (__pyx_memoryview_thread_locks[__pyx_v_i]); - /* "View.MemoryView":383 + /* "View.MemoryView":387 * __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] = ( # <<<<<<<<<<<<<< @@ -5296,7 +5347,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_6; (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_7; - /* "View.MemoryView":382 + /* "View.MemoryView":386 * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< @@ -5305,7 +5356,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal */ } - /* "View.MemoryView":385 + /* "View.MemoryView":389 * __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 # <<<<<<<<<<<<<< @@ -5314,7 +5365,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal */ goto __pyx_L6_break; - /* "View.MemoryView":380 + /* "View.MemoryView":384 * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< @@ -5325,7 +5376,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal } /*else*/ { - /* "View.MemoryView":387 + /* "View.MemoryView":391 * break * else: * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< @@ -5336,7 +5387,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal } __pyx_L6_break:; - /* "View.MemoryView":378 + /* "View.MemoryView":382 * cdef int i * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< @@ -5357,7 +5408,7 @@ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__deal __Pyx_RefNannyFinishContext(); } -/* "View.MemoryView":389 +/* "View.MemoryView":393 * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< @@ -5380,7 +5431,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py char *__pyx_t_7; __Pyx_RefNannySetupContext("get_item_pointer", 0); - /* "View.MemoryView":391 + /* "View.MemoryView":395 * cdef char *get_item_pointer(memoryview self, object index) except NULL: * cdef Py_ssize_t dim * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< @@ -5389,7 +5440,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py */ __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); - /* "View.MemoryView":393 + /* "View.MemoryView":397 * cdef char *itemp = self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< @@ -5401,26 +5452,26 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py __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(1, 393, __pyx_L1_error) + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 397, __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(1, 393, __pyx_L1_error) + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 397, __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(1, 393, __pyx_L1_error) + __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(1, 397, __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(1, 393, __pyx_L1_error) + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 397, __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(1, 393, __pyx_L1_error) + __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(1, 397, __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(1, 393, __pyx_L1_error) + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 397, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif } @@ -5430,7 +5481,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 393, __pyx_L1_error) + else __PYX_ERR(1, 397, __pyx_L1_error) } break; } @@ -5441,18 +5492,18 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py __pyx_v_dim = __pyx_t_1; __pyx_t_1 = (__pyx_t_1 + 1); - /* "View.MemoryView":394 + /* "View.MemoryView":398 * * 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(1, 394, __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(1, 394, __pyx_L1_error) + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 398, __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(1, 398, __pyx_L1_error) __pyx_v_itemp = __pyx_t_7; - /* "View.MemoryView":393 + /* "View.MemoryView":397 * cdef char *itemp = self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< @@ -5462,7 +5513,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":396 + /* "View.MemoryView":400 * itemp = pybuffer_index(&self.view, itemp, idx, dim) * * return itemp # <<<<<<<<<<<<<< @@ -5472,7 +5523,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py __pyx_r = __pyx_v_itemp; goto __pyx_L0; - /* "View.MemoryView":389 + /* "View.MemoryView":393 * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< @@ -5492,7 +5543,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py return __pyx_r; } -/* "View.MemoryView":399 +/* "View.MemoryView":403 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< @@ -5527,7 +5578,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ char *__pyx_t_6; __Pyx_RefNannySetupContext("__getitem__", 0); - /* "View.MemoryView":400 + /* "View.MemoryView":404 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< @@ -5538,7 +5589,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":401 + /* "View.MemoryView":405 * def __getitem__(memoryview self, object index): * if index is Ellipsis: * return self # <<<<<<<<<<<<<< @@ -5550,7 +5601,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ __pyx_r = ((PyObject *)__pyx_v_self); goto __pyx_L0; - /* "View.MemoryView":400 + /* "View.MemoryView":404 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< @@ -5559,14 +5610,14 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ */ } - /* "View.MemoryView":403 + /* "View.MemoryView":407 * 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(1, 403, __pyx_L1_error) + __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (likely(__pyx_t_3 != Py_None)) { PyObject* sequence = __pyx_t_3; @@ -5574,7 +5625,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(1, 403, __pyx_L1_error) + __PYX_ERR(1, 407, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); @@ -5582,31 +5633,31 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ __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(1, 403, __pyx_L1_error) + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 403, __pyx_L1_error) + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 403, __pyx_L1_error) + __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 407, __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":406 + /* "View.MemoryView":410 * * 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(1, 406, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 410, __pyx_L1_error) if (__pyx_t_2) { - /* "View.MemoryView":407 + /* "View.MemoryView":411 * cdef char *itemp * if have_slices: * return memview_slice(self, indices) # <<<<<<<<<<<<<< @@ -5614,13 +5665,13 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ * 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(1, 407, __pyx_L1_error) + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 411, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; - /* "View.MemoryView":406 + /* "View.MemoryView":410 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< @@ -5629,7 +5680,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ */ } - /* "View.MemoryView":409 + /* "View.MemoryView":413 * return memview_slice(self, indices) * else: * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< @@ -5637,10 +5688,10 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ * */ /*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(1, 409, __pyx_L1_error) + __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(1, 413, __pyx_L1_error) __pyx_v_itemp = __pyx_t_6; - /* "View.MemoryView":410 + /* "View.MemoryView":414 * else: * itemp = self.get_item_pointer(indices) * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< @@ -5648,14 +5699,14 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ * 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(1, 410, __pyx_L1_error) + __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(1, 414, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } - /* "View.MemoryView":399 + /* "View.MemoryView":403 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< @@ -5678,7 +5729,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4_ return __pyx_r; } -/* "View.MemoryView":412 +/* "View.MemoryView":416 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< @@ -5711,7 +5762,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit __Pyx_RefNannySetupContext("__setitem__", 0); __Pyx_INCREF(__pyx_v_index); - /* "View.MemoryView":413 + /* "View.MemoryView":417 * * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: # <<<<<<<<<<<<<< @@ -5721,20 +5772,20 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit __pyx_t_1 = (__pyx_v_self->view.readonly != 0); if (unlikely(__pyx_t_1)) { - /* "View.MemoryView":414 + /* "View.MemoryView":418 * 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__8, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 414, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 418, __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(1, 414, __pyx_L1_error) + __PYX_ERR(1, 418, __pyx_L1_error) - /* "View.MemoryView":413 + /* "View.MemoryView":417 * * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: # <<<<<<<<<<<<<< @@ -5743,14 +5794,14 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit */ } - /* "View.MemoryView":416 + /* "View.MemoryView":420 * 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(1, 416, __pyx_L1_error) + __pyx_t_2 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (likely(__pyx_t_2 != Py_None)) { PyObject* sequence = __pyx_t_2; @@ -5758,7 +5809,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(1, 416, __pyx_L1_error) + __PYX_ERR(1, 420, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); @@ -5766,67 +5817,67 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit __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(1, 416, __pyx_L1_error) + __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 416, __pyx_L1_error) + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 416, __pyx_L1_error) + __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 420, __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":418 + /* "View.MemoryView":422 * 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(1, 418, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 422, __pyx_L1_error) if (__pyx_t_1) { - /* "View.MemoryView":419 + /* "View.MemoryView":423 * * 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(1, 419, __pyx_L1_error) + __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(1, 423, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_v_obj = __pyx_t_2; __pyx_t_2 = 0; - /* "View.MemoryView":420 + /* "View.MemoryView":424 * 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(1, 420, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 424, __pyx_L1_error) if (__pyx_t_1) { - /* "View.MemoryView":421 + /* "View.MemoryView":425 * 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(1, 421, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 425, __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(1, 421, __pyx_L1_error) + __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(1, 425, __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":420 + /* "View.MemoryView":424 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< @@ -5836,7 +5887,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit goto __pyx_L5; } - /* "View.MemoryView":423 + /* "View.MemoryView":427 * self.setitem_slice_assignment(self[index], obj) * else: * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< @@ -5844,17 +5895,17 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit * 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(1, 423, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 427, __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(1, 423, __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(1, 423, __pyx_L1_error) + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_memoryview_type))))) __PYX_ERR(1, 427, __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(1, 427, __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":418 + /* "View.MemoryView":422 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< @@ -5864,7 +5915,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit goto __pyx_L4; } - /* "View.MemoryView":425 + /* "View.MemoryView":429 * self.setitem_slice_assign_scalar(self[index], value) * else: * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< @@ -5872,13 +5923,13 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit * 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(1, 425, __pyx_L1_error) + __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(1, 429, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L4:; - /* "View.MemoryView":412 + /* "View.MemoryView":416 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< @@ -5903,7 +5954,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setit return __pyx_r; } -/* "View.MemoryView":427 +/* "View.MemoryView":431 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< @@ -5926,7 +5977,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __Pyx_RefNannySetupContext("is_slice", 0); __Pyx_INCREF(__pyx_v_obj); - /* "View.MemoryView":428 + /* "View.MemoryView":432 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< @@ -5937,7 +5988,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":429 + /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< @@ -5953,34 +6004,34 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __Pyx_XGOTREF(__pyx_t_5); /*try:*/ { - /* "View.MemoryView":430 + /* "View.MemoryView":434 * 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(1, 430, __pyx_L4_error) + __pyx_t_6 = __Pyx_PyInt_From_int(((__pyx_v_self->flags & (~PyBUF_WRITABLE)) | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 434, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_6); - /* "View.MemoryView":431 + /* "View.MemoryView":435 * 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(1, 431, __pyx_L4_error) + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 435, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_7); - /* "View.MemoryView":430 + /* "View.MemoryView":434 * 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(1, 430, __pyx_L4_error) + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 434, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); @@ -5991,13 +6042,13 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ 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(1, 430, __pyx_L4_error) + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 434, __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":429 + /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< @@ -6014,7 +6065,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - /* "View.MemoryView":432 + /* "View.MemoryView":436 * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) * except TypeError: # <<<<<<<<<<<<<< @@ -6024,12 +6075,12 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __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(1, 432, __pyx_L6_except_error) + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) __PYX_ERR(1, 436, __pyx_L6_except_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_6); - /* "View.MemoryView":433 + /* "View.MemoryView":437 * self.dtype_is_object) * except TypeError: * return None # <<<<<<<<<<<<<< @@ -6046,7 +6097,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ goto __pyx_L6_except_error; __pyx_L6_except_error:; - /* "View.MemoryView":429 + /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< @@ -6067,7 +6118,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __pyx_L9_try_end:; } - /* "View.MemoryView":428 + /* "View.MemoryView":432 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< @@ -6076,7 +6127,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ */ } - /* "View.MemoryView":435 + /* "View.MemoryView":439 * return None * * return obj # <<<<<<<<<<<<<< @@ -6088,7 +6139,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __pyx_r = __pyx_v_obj; goto __pyx_L0; - /* "View.MemoryView":427 + /* "View.MemoryView":431 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< @@ -6110,7 +6161,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ return __pyx_r; } -/* "View.MemoryView":437 +/* "View.MemoryView":441 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< @@ -6129,50 +6180,50 @@ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryvi int __pyx_t_4; __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); - /* "View.MemoryView":441 + /* "View.MemoryView":445 * 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(1, 441, __pyx_L1_error) + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) __PYX_ERR(1, 445, __pyx_L1_error) - /* "View.MemoryView":442 + /* "View.MemoryView":446 * * 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(1, 442, __pyx_L1_error) + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) __PYX_ERR(1, 446, __pyx_L1_error) - /* "View.MemoryView":443 + /* "View.MemoryView":447 * 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_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 443, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 447, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 443, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 443, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 447, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 443, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "View.MemoryView":441 + /* "View.MemoryView":445 * 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_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 441, __pyx_L1_error) + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 445, __pyx_L1_error) - /* "View.MemoryView":437 + /* "View.MemoryView":441 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< @@ -6193,7 +6244,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryvi return __pyx_r; } -/* "View.MemoryView":445 +/* "View.MemoryView":449 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< @@ -6222,7 +6273,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor PyObject *__pyx_t_11 = NULL; __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); - /* "View.MemoryView":447 + /* "View.MemoryView":451 * cdef setitem_slice_assign_scalar(self, memoryview dst, value): * cdef int array[128] * cdef void *tmp = NULL # <<<<<<<<<<<<<< @@ -6231,7 +6282,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ __pyx_v_tmp = NULL; - /* "View.MemoryView":452 + /* "View.MemoryView":456 * cdef __Pyx_memviewslice *dst_slice * cdef __Pyx_memviewslice tmp_slice * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< @@ -6240,7 +6291,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); - /* "View.MemoryView":454 + /* "View.MemoryView":458 * dst_slice = get_slice_from_memview(dst, &tmp_slice) * * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< @@ -6250,7 +6301,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); if (__pyx_t_1) { - /* "View.MemoryView":455 + /* "View.MemoryView":459 * * if self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< @@ -6259,7 +6310,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); - /* "View.MemoryView":456 + /* "View.MemoryView":460 * if self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< @@ -6269,16 +6320,16 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); if (unlikely(__pyx_t_1)) { - /* "View.MemoryView":457 + /* "View.MemoryView":461 * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: * raise MemoryError # <<<<<<<<<<<<<< * item = tmp * else: */ - PyErr_NoMemory(); __PYX_ERR(1, 457, __pyx_L1_error) + PyErr_NoMemory(); __PYX_ERR(1, 461, __pyx_L1_error) - /* "View.MemoryView":456 + /* "View.MemoryView":460 * if self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< @@ -6287,7 +6338,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ } - /* "View.MemoryView":458 + /* "View.MemoryView":462 * if tmp == NULL: * raise MemoryError * item = tmp # <<<<<<<<<<<<<< @@ -6296,7 +6347,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ __pyx_v_item = __pyx_v_tmp; - /* "View.MemoryView":454 + /* "View.MemoryView":458 * dst_slice = get_slice_from_memview(dst, &tmp_slice) * * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< @@ -6306,7 +6357,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor goto __pyx_L3; } - /* "View.MemoryView":460 + /* "View.MemoryView":464 * item = tmp * else: * item = array # <<<<<<<<<<<<<< @@ -6318,7 +6369,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor } __pyx_L3:; - /* "View.MemoryView":462 + /* "View.MemoryView":466 * item = array * * try: # <<<<<<<<<<<<<< @@ -6327,7 +6378,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ /*try:*/ { - /* "View.MemoryView":463 + /* "View.MemoryView":467 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< @@ -6337,7 +6388,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_1) { - /* "View.MemoryView":464 + /* "View.MemoryView":468 * try: * if self.dtype_is_object: * ( item)[0] = value # <<<<<<<<<<<<<< @@ -6346,7 +6397,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); - /* "View.MemoryView":463 + /* "View.MemoryView":467 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< @@ -6356,7 +6407,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor goto __pyx_L8; } - /* "View.MemoryView":466 + /* "View.MemoryView":470 * ( item)[0] = value * else: * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< @@ -6364,13 +6415,13 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor * */ /*else*/ { - __pyx_t_2 = ((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_2)) __PYX_ERR(1, 466, __pyx_L6_error) + __pyx_t_2 = ((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_2)) __PYX_ERR(1, 470, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L8:; - /* "View.MemoryView":470 + /* "View.MemoryView":474 * * * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< @@ -6380,18 +6431,18 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":471 + /* "View.MemoryView":475 * * 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_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 471, __pyx_L6_error) + __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 475, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":470 + /* "View.MemoryView":474 * * * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< @@ -6400,7 +6451,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ } - /* "View.MemoryView":472 + /* "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, # <<<<<<<<<<<<<< @@ -6410,7 +6461,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __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":475 + /* "View.MemoryView":479 * item, self.dtype_is_object) * finally: * PyMem_Free(tmp) # <<<<<<<<<<<<<< @@ -6457,7 +6508,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_L7:; } - /* "View.MemoryView":445 + /* "View.MemoryView":449 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< @@ -6478,7 +6529,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor return __pyx_r; } -/* "View.MemoryView":477 +/* "View.MemoryView":481 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< @@ -6494,28 +6545,28 @@ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *_ PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("setitem_indexed", 0); - /* "View.MemoryView":478 + /* "View.MemoryView":482 * * 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(1, 478, __pyx_L1_error) + __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(1, 482, __pyx_L1_error) __pyx_v_itemp = __pyx_t_1; - /* "View.MemoryView":479 + /* "View.MemoryView":483 * 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(1, 479, __pyx_L1_error) + __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(1, 483, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":477 + /* "View.MemoryView":481 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< @@ -6536,7 +6587,7 @@ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *_ return __pyx_r; } -/* "View.MemoryView":481 +/* "View.MemoryView":485 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< @@ -6563,31 +6614,31 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview int __pyx_t_11; __Pyx_RefNannySetupContext("convert_item_to_object", 0); - /* "View.MemoryView":484 + /* "View.MemoryView":488 * """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(1, 484, __pyx_L1_error) + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 488, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; - /* "View.MemoryView":487 + /* "View.MemoryView":491 * 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(1, 487, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 491, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; - /* "View.MemoryView":488 + /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< @@ -6603,16 +6654,16 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview __Pyx_XGOTREF(__pyx_t_4); /*try:*/ { - /* "View.MemoryView":489 + /* "View.MemoryView":493 * 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(1, 489, __pyx_L3_error) + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 493, __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(1, 489, __pyx_L3_error) + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 493, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = NULL; __pyx_t_8 = 0; @@ -6629,7 +6680,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview #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(1, 489, __pyx_L3_error) + __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(1, 493, __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; @@ -6638,14 +6689,14 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview #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(1, 489, __pyx_L3_error) + __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(1, 493, __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(1, 489, __pyx_L3_error) + __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 493, __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; @@ -6656,7 +6707,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview __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(1, 489, __pyx_L3_error) + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } @@ -6664,7 +6715,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview __pyx_v_result = __pyx_t_1; __pyx_t_1 = 0; - /* "View.MemoryView":488 + /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< @@ -6673,7 +6724,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview */ } - /* "View.MemoryView":493 + /* "View.MemoryView":497 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< @@ -6685,7 +6736,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview __pyx_t_11 = ((__pyx_t_10 == 1) != 0); if (__pyx_t_11) { - /* "View.MemoryView":494 + /* "View.MemoryView":498 * else: * if len(self.view.format) == 1: * return result[0] # <<<<<<<<<<<<<< @@ -6693,13 +6744,13 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview * */ __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(1, 494, __pyx_L5_except_error) + __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(1, 498, __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":493 + /* "View.MemoryView":497 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< @@ -6708,7 +6759,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview */ } - /* "View.MemoryView":495 + /* "View.MemoryView":499 * if len(self.view.format) == 1: * return result[0] * return result # <<<<<<<<<<<<<< @@ -6727,7 +6778,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - /* "View.MemoryView":490 + /* "View.MemoryView":494 * try: * result = struct.unpack(self.view.format, bytesitem) * except struct.error: # <<<<<<<<<<<<<< @@ -6735,7 +6786,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview * 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(1, 490, __pyx_L5_except_error) + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 494, __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; @@ -6743,28 +6794,28 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview __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(1, 490, __pyx_L5_except_error) + if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_5, &__pyx_t_1) < 0) __PYX_ERR(1, 494, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_1); - /* "View.MemoryView":491 + /* "View.MemoryView":495 * 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__9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 491, __pyx_L5_except_error) + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 495, __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(1, 491, __pyx_L5_except_error) + __PYX_ERR(1, 495, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; - /* "View.MemoryView":488 + /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< @@ -6784,7 +6835,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview goto __pyx_L0; } - /* "View.MemoryView":481 + /* "View.MemoryView":485 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< @@ -6810,7 +6861,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview return __pyx_r; } -/* "View.MemoryView":497 +/* "View.MemoryView":501 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< @@ -6841,19 +6892,19 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie char *__pyx_t_14; __Pyx_RefNannySetupContext("assign_item_from_object", 0); - /* "View.MemoryView":500 + /* "View.MemoryView":504 * """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(1, 500, __pyx_L1_error) + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 504, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; - /* "View.MemoryView":505 + /* "View.MemoryView":509 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< @@ -6864,37 +6915,37 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { - /* "View.MemoryView":506 + /* "View.MemoryView":510 * * 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(1, 506, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 510, __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(1, 506, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 506, __pyx_L1_error) + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 510, __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(1, 506, __pyx_L1_error) + __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __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(1, 506, __pyx_L1_error) + __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 510, __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(1, 506, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 506, __pyx_L1_error) + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 510, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; - /* "View.MemoryView":505 + /* "View.MemoryView":509 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< @@ -6904,7 +6955,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie goto __pyx_L3; } - /* "View.MemoryView":508 + /* "View.MemoryView":512 * bytesvalue = struct.pack(self.view.format, *value) * else: * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< @@ -6912,9 +6963,9 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie * 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(1, 508, __pyx_L1_error) + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 512, __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(1, 508, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 512, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_5 = NULL; __pyx_t_7 = 0; @@ -6931,7 +6982,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie #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(1, 508, __pyx_L1_error) + __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(1, 512, __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; @@ -6940,14 +6991,14 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie #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(1, 508, __pyx_L1_error) + __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(1, 512, __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(1, 508, __pyx_L1_error) + __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 512, __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; @@ -6958,18 +7009,18 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie __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(1, 508, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 508, __pyx_L1_error) + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 512, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; } __pyx_L3:; - /* "View.MemoryView":510 + /* "View.MemoryView":514 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< @@ -6979,7 +7030,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie __pyx_t_9 = 0; if (unlikely(__pyx_v_bytesvalue == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); - __PYX_ERR(1, 510, __pyx_L1_error) + __PYX_ERR(1, 514, __pyx_L1_error) } __Pyx_INCREF(__pyx_v_bytesvalue); __pyx_t_10 = __pyx_v_bytesvalue; @@ -6989,7 +7040,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie __pyx_t_11 = __pyx_t_14; __pyx_v_c = (__pyx_t_11[0]); - /* "View.MemoryView":511 + /* "View.MemoryView":515 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< @@ -6998,7 +7049,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie */ __pyx_v_i = __pyx_t_9; - /* "View.MemoryView":510 + /* "View.MemoryView":514 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< @@ -7007,7 +7058,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie */ __pyx_t_9 = (__pyx_t_9 + 1); - /* "View.MemoryView":511 + /* "View.MemoryView":515 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< @@ -7018,7 +7069,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie } __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - /* "View.MemoryView":497 + /* "View.MemoryView":501 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< @@ -7046,7 +7097,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie return __pyx_r; } -/* "View.MemoryView":514 +/* "View.MemoryView":518 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< @@ -7086,7 +7137,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); - /* "View.MemoryView":515 + /* "View.MemoryView":519 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< @@ -7104,20 +7155,20 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_L4_bool_binop_done:; if (unlikely(__pyx_t_1)) { - /* "View.MemoryView":516 + /* "View.MemoryView":520 * 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__10, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 516, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 520, __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(1, 516, __pyx_L1_error) + __PYX_ERR(1, 520, __pyx_L1_error) - /* "View.MemoryView":515 + /* "View.MemoryView":519 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< @@ -7126,7 +7177,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu */ } - /* "View.MemoryView":518 + /* "View.MemoryView":522 * raise ValueError("Cannot create writable memory view from read-only memoryview") * * if flags & PyBUF_ND: # <<<<<<<<<<<<<< @@ -7136,7 +7187,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_1 = ((__pyx_v_flags & PyBUF_ND) != 0); if (__pyx_t_1) { - /* "View.MemoryView":519 + /* "View.MemoryView":523 * * if flags & PyBUF_ND: * info.shape = self.view.shape # <<<<<<<<<<<<<< @@ -7146,7 +7197,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_4 = __pyx_v_self->view.shape; __pyx_v_info->shape = __pyx_t_4; - /* "View.MemoryView":518 + /* "View.MemoryView":522 * raise ValueError("Cannot create writable memory view from read-only memoryview") * * if flags & PyBUF_ND: # <<<<<<<<<<<<<< @@ -7156,7 +7207,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu goto __pyx_L6; } - /* "View.MemoryView":521 + /* "View.MemoryView":525 * info.shape = self.view.shape * else: * info.shape = NULL # <<<<<<<<<<<<<< @@ -7168,7 +7219,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu } __pyx_L6:; - /* "View.MemoryView":523 + /* "View.MemoryView":527 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< @@ -7178,7 +7229,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { - /* "View.MemoryView":524 + /* "View.MemoryView":528 * * if flags & PyBUF_STRIDES: * info.strides = self.view.strides # <<<<<<<<<<<<<< @@ -7188,7 +7239,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_4 = __pyx_v_self->view.strides; __pyx_v_info->strides = __pyx_t_4; - /* "View.MemoryView":523 + /* "View.MemoryView":527 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< @@ -7198,7 +7249,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu goto __pyx_L7; } - /* "View.MemoryView":526 + /* "View.MemoryView":530 * info.strides = self.view.strides * else: * info.strides = NULL # <<<<<<<<<<<<<< @@ -7210,7 +7261,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu } __pyx_L7:; - /* "View.MemoryView":528 + /* "View.MemoryView":532 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< @@ -7220,7 +7271,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); if (__pyx_t_1) { - /* "View.MemoryView":529 + /* "View.MemoryView":533 * * if flags & PyBUF_INDIRECT: * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< @@ -7230,7 +7281,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_4 = __pyx_v_self->view.suboffsets; __pyx_v_info->suboffsets = __pyx_t_4; - /* "View.MemoryView":528 + /* "View.MemoryView":532 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< @@ -7240,7 +7291,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu goto __pyx_L8; } - /* "View.MemoryView":531 + /* "View.MemoryView":535 * info.suboffsets = self.view.suboffsets * else: * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -7252,7 +7303,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu } __pyx_L8:; - /* "View.MemoryView":533 + /* "View.MemoryView":537 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< @@ -7262,7 +7313,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { - /* "View.MemoryView":534 + /* "View.MemoryView":538 * * if flags & PyBUF_FORMAT: * info.format = self.view.format # <<<<<<<<<<<<<< @@ -7272,7 +7323,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_5 = __pyx_v_self->view.format; __pyx_v_info->format = __pyx_t_5; - /* "View.MemoryView":533 + /* "View.MemoryView":537 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< @@ -7282,7 +7333,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu goto __pyx_L9; } - /* "View.MemoryView":536 + /* "View.MemoryView":540 * info.format = self.view.format * else: * info.format = NULL # <<<<<<<<<<<<<< @@ -7294,7 +7345,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu } __pyx_L9:; - /* "View.MemoryView":538 + /* "View.MemoryView":542 * info.format = NULL * * info.buf = self.view.buf # <<<<<<<<<<<<<< @@ -7304,7 +7355,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_6 = __pyx_v_self->view.buf; __pyx_v_info->buf = __pyx_t_6; - /* "View.MemoryView":539 + /* "View.MemoryView":543 * * info.buf = self.view.buf * info.ndim = self.view.ndim # <<<<<<<<<<<<<< @@ -7314,7 +7365,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_7 = __pyx_v_self->view.ndim; __pyx_v_info->ndim = __pyx_t_7; - /* "View.MemoryView":540 + /* "View.MemoryView":544 * info.buf = self.view.buf * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< @@ -7324,7 +7375,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_8 = __pyx_v_self->view.itemsize; __pyx_v_info->itemsize = __pyx_t_8; - /* "View.MemoryView":541 + /* "View.MemoryView":545 * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize * info.len = self.view.len # <<<<<<<<<<<<<< @@ -7334,7 +7385,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_8 = __pyx_v_self->view.len; __pyx_v_info->len = __pyx_t_8; - /* "View.MemoryView":542 + /* "View.MemoryView":546 * info.itemsize = self.view.itemsize * info.len = self.view.len * info.readonly = self.view.readonly # <<<<<<<<<<<<<< @@ -7344,7 +7395,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __pyx_t_1 = __pyx_v_self->view.readonly; __pyx_v_info->readonly = __pyx_t_1; - /* "View.MemoryView":543 + /* "View.MemoryView":547 * info.len = self.view.len * info.readonly = self.view.readonly * info.obj = self # <<<<<<<<<<<<<< @@ -7357,7 +7408,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - /* "View.MemoryView":514 + /* "View.MemoryView":518 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< @@ -7387,7 +7438,7 @@ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbu return __pyx_r; } -/* "View.MemoryView":549 +/* "View.MemoryView":553 * * @property * def T(self): # <<<<<<<<<<<<<< @@ -7416,29 +7467,29 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct _ int __pyx_t_2; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":550 + /* "View.MemoryView":554 * @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(1, 550, __pyx_L1_error) + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 554, __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(1, 550, __pyx_L1_error) + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) __PYX_ERR(1, 554, __pyx_L1_error) __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); __pyx_t_1 = 0; - /* "View.MemoryView":551 + /* "View.MemoryView":555 * 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(1, 551, __pyx_L1_error) + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 555, __pyx_L1_error) - /* "View.MemoryView":552 + /* "View.MemoryView":556 * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) * return result # <<<<<<<<<<<<<< @@ -7450,7 +7501,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct _ __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; - /* "View.MemoryView":549 + /* "View.MemoryView":553 * * @property * def T(self): # <<<<<<<<<<<<<< @@ -7470,7 +7521,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct _ return __pyx_r; } -/* "View.MemoryView":555 +/* "View.MemoryView":559 * * @property * def base(self): # <<<<<<<<<<<<<< @@ -7496,7 +7547,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struc __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":556 + /* "View.MemoryView":560 * @property * def base(self): * return self.obj # <<<<<<<<<<<<<< @@ -7508,7 +7559,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struc __pyx_r = __pyx_v_self->obj; goto __pyx_L0; - /* "View.MemoryView":555 + /* "View.MemoryView":559 * * @property * def base(self): # <<<<<<<<<<<<<< @@ -7523,7 +7574,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struc return __pyx_r; } -/* "View.MemoryView":559 +/* "View.MemoryView":563 * * @property * def shape(self): # <<<<<<<<<<<<<< @@ -7555,7 +7606,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(stru PyObject *__pyx_t_5 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":560 + /* "View.MemoryView":564 * @property * def shape(self): * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< @@ -7563,25 +7614,25 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(stru * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 560, __pyx_L1_error) + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 564, __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(1, 560, __pyx_L1_error) + __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 564, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 560, __pyx_L1_error) + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 564, __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(1, 560, __pyx_L1_error) + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 564, __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":559 + /* "View.MemoryView":563 * * @property * def shape(self): # <<<<<<<<<<<<<< @@ -7601,7 +7652,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(stru return __pyx_r; } -/* "View.MemoryView":563 +/* "View.MemoryView":567 * * @property * def strides(self): # <<<<<<<<<<<<<< @@ -7634,7 +7685,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(st PyObject *__pyx_t_6 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":564 + /* "View.MemoryView":568 * @property * def strides(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< @@ -7644,20 +7695,20 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(st __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); if (unlikely(__pyx_t_1)) { - /* "View.MemoryView":566 + /* "View.MemoryView":570 * 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__11, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 566, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 570, __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(1, 566, __pyx_L1_error) + __PYX_ERR(1, 570, __pyx_L1_error) - /* "View.MemoryView":564 + /* "View.MemoryView":568 * @property * def strides(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< @@ -7666,7 +7717,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(st */ } - /* "View.MemoryView":568 + /* "View.MemoryView":572 * raise ValueError("Buffer view does not expose strides") * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< @@ -7674,25 +7725,25 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(st * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 568, __pyx_L1_error) + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 572, __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(1, 568, __pyx_L1_error) + __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 572, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(1, 568, __pyx_L1_error) + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(1, 572, __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(1, 568, __pyx_L1_error) + __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 572, __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":563 + /* "View.MemoryView":567 * * @property * def strides(self): # <<<<<<<<<<<<<< @@ -7712,7 +7763,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(st return __pyx_r; } -/* "View.MemoryView":571 +/* "View.MemoryView":575 * * @property * def suboffsets(self): # <<<<<<<<<<<<<< @@ -7745,7 +7796,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get_ Py_ssize_t *__pyx_t_6; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":572 + /* "View.MemoryView":576 * @property * def suboffsets(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< @@ -7755,7 +7806,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get_ __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":573 + /* "View.MemoryView":577 * def suboffsets(self): * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< @@ -7763,16 +7814,16 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get_ * 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(1, 573, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 577, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__12, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 573, __pyx_L1_error) + __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__12, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 577, __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":572 + /* "View.MemoryView":576 * @property * def suboffsets(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< @@ -7781,7 +7832,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get_ */ } - /* "View.MemoryView":575 + /* "View.MemoryView":579 * return (-1,) * self.view.ndim * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< @@ -7789,25 +7840,25 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get_ * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 575, __pyx_L1_error) + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 579, __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(1, 575, __pyx_L1_error) + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(1, 575, __pyx_L1_error) + if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(1, 579, __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(1, 575, __pyx_L1_error) + __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __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":571 + /* "View.MemoryView":575 * * @property * def suboffsets(self): # <<<<<<<<<<<<<< @@ -7827,7 +7878,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get_ return __pyx_r; } -/* "View.MemoryView":578 +/* "View.MemoryView":582 * * @property * def ndim(self): # <<<<<<<<<<<<<< @@ -7854,7 +7905,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struc PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":579 + /* "View.MemoryView":583 * @property * def ndim(self): * return self.view.ndim # <<<<<<<<<<<<<< @@ -7862,13 +7913,13 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struc * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 579, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 583, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":578 + /* "View.MemoryView":582 * * @property * def ndim(self): # <<<<<<<<<<<<<< @@ -7887,7 +7938,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struc return __pyx_r; } -/* "View.MemoryView":582 +/* "View.MemoryView":586 * * @property * def itemsize(self): # <<<<<<<<<<<<<< @@ -7914,7 +7965,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(s PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":583 + /* "View.MemoryView":587 * @property * def itemsize(self): * return self.view.itemsize # <<<<<<<<<<<<<< @@ -7922,13 +7973,13 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(s * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 583, __pyx_L1_error) + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 587, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":582 + /* "View.MemoryView":586 * * @property * def itemsize(self): # <<<<<<<<<<<<<< @@ -7947,7 +7998,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(s return __pyx_r; } -/* "View.MemoryView":586 +/* "View.MemoryView":590 * * @property * def nbytes(self): # <<<<<<<<<<<<<< @@ -7976,7 +8027,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(str PyObject *__pyx_t_3 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":587 + /* "View.MemoryView":591 * @property * def nbytes(self): * return self.size * self.view.itemsize # <<<<<<<<<<<<<< @@ -7984,11 +8035,11 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(str * @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(1, 587, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 591, __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(1, 587, __pyx_L1_error) + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 591, __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(1, 587, __pyx_L1_error) + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 591, __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; @@ -7996,7 +8047,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(str __pyx_t_3 = 0; goto __pyx_L0; - /* "View.MemoryView":586 + /* "View.MemoryView":590 * * @property * def nbytes(self): # <<<<<<<<<<<<<< @@ -8017,7 +8068,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(str return __pyx_r; } -/* "View.MemoryView":590 +/* "View.MemoryView":594 * * @property * def size(self): # <<<<<<<<<<<<<< @@ -8051,7 +8102,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struc PyObject *__pyx_t_6 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":591 + /* "View.MemoryView":595 * @property * def size(self): * if self._size is None: # <<<<<<<<<<<<<< @@ -8062,7 +8113,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struc __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":592 + /* "View.MemoryView":596 * def size(self): * if self._size is None: * result = 1 # <<<<<<<<<<<<<< @@ -8072,7 +8123,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struc __Pyx_INCREF(__pyx_int_1); __pyx_v_result = __pyx_int_1; - /* "View.MemoryView":594 + /* "View.MemoryView":598 * result = 1 * * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< @@ -8082,25 +8133,25 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struc __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(1, 594, __pyx_L1_error) + __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 598, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); __pyx_t_6 = 0; - /* "View.MemoryView":595 + /* "View.MemoryView":599 * * 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(1, 595, __pyx_L1_error) + __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 599, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); __pyx_t_6 = 0; } - /* "View.MemoryView":597 + /* "View.MemoryView":601 * result *= length * * self._size = result # <<<<<<<<<<<<<< @@ -8113,7 +8164,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struc __Pyx_DECREF(__pyx_v_self->_size); __pyx_v_self->_size = __pyx_v_result; - /* "View.MemoryView":591 + /* "View.MemoryView":595 * @property * def size(self): * if self._size is None: # <<<<<<<<<<<<<< @@ -8122,7 +8173,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struc */ } - /* "View.MemoryView":599 + /* "View.MemoryView":603 * self._size = result * * return self._size # <<<<<<<<<<<<<< @@ -8134,7 +8185,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struc __pyx_r = __pyx_v_self->_size; goto __pyx_L0; - /* "View.MemoryView":590 + /* "View.MemoryView":594 * * @property * def size(self): # <<<<<<<<<<<<<< @@ -8155,7 +8206,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struc return __pyx_r; } -/* "View.MemoryView":601 +/* "View.MemoryView":605 * return self._size * * def __len__(self): # <<<<<<<<<<<<<< @@ -8182,7 +8233,7 @@ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_1 int __pyx_t_1; __Pyx_RefNannySetupContext("__len__", 0); - /* "View.MemoryView":602 + /* "View.MemoryView":606 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< @@ -8192,7 +8243,7 @@ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_1 __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); if (__pyx_t_1) { - /* "View.MemoryView":603 + /* "View.MemoryView":607 * def __len__(self): * if self.view.ndim >= 1: * return self.view.shape[0] # <<<<<<<<<<<<<< @@ -8202,7 +8253,7 @@ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_1 __pyx_r = (__pyx_v_self->view.shape[0]); goto __pyx_L0; - /* "View.MemoryView":602 + /* "View.MemoryView":606 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< @@ -8211,7 +8262,7 @@ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_1 */ } - /* "View.MemoryView":605 + /* "View.MemoryView":609 * return self.view.shape[0] * * return 0 # <<<<<<<<<<<<<< @@ -8221,7 +8272,7 @@ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_1 __pyx_r = 0; goto __pyx_L0; - /* "View.MemoryView":601 + /* "View.MemoryView":605 * return self._size * * def __len__(self): # <<<<<<<<<<<<<< @@ -8235,7 +8286,7 @@ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_1 return __pyx_r; } -/* "View.MemoryView":607 +/* "View.MemoryView":611 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< @@ -8264,7 +8315,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12 PyObject *__pyx_t_3 = NULL; __Pyx_RefNannySetupContext("__repr__", 0); - /* "View.MemoryView":608 + /* "View.MemoryView":612 * * def __repr__(self): * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< @@ -8272,33 +8323,33 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12 * */ __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(1, 608, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 612, __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(1, 608, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 612, __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(1, 608, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":609 + /* "View.MemoryView":613 * 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(1, 609, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 613, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - /* "View.MemoryView":608 + /* "View.MemoryView":612 * * def __repr__(self): * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 608, __pyx_L1_error) + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); @@ -8306,14 +8357,14 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12 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(1, 608, __pyx_L1_error) + __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(1, 612, __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":607 + /* "View.MemoryView":611 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< @@ -8334,7 +8385,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12 return __pyx_r; } -/* "View.MemoryView":611 +/* "View.MemoryView":615 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< @@ -8362,7 +8413,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14 PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__str__", 0); - /* "View.MemoryView":612 + /* "View.MemoryView":616 * * def __str__(self): * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< @@ -8370,27 +8421,27 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14 * */ __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(1, 612, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __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(1, 612, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 616, __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(1, 612, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __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(1, 612, __pyx_L1_error) + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 616, __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(1, 612, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __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":611 + /* "View.MemoryView":615 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< @@ -8410,7 +8461,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14 return __pyx_r; } -/* "View.MemoryView":615 +/* "View.MemoryView":619 * * * def is_c_contig(self): # <<<<<<<<<<<<<< @@ -8439,7 +8490,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16 PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("is_c_contig", 0); - /* "View.MemoryView":618 + /* "View.MemoryView":622 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< @@ -8448,7 +8499,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16 */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); - /* "View.MemoryView":619 + /* "View.MemoryView":623 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice[0], 'C', self.view.ndim) # <<<<<<<<<<<<<< @@ -8456,13 +8507,13 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16 * def is_f_contig(self): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 619, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 623, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":615 + /* "View.MemoryView":619 * * * def is_c_contig(self): # <<<<<<<<<<<<<< @@ -8481,7 +8532,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16 return __pyx_r; } -/* "View.MemoryView":621 +/* "View.MemoryView":625 * return slice_is_contig(mslice[0], 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< @@ -8510,7 +8561,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18 PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("is_f_contig", 0); - /* "View.MemoryView":624 + /* "View.MemoryView":628 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< @@ -8519,7 +8570,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18 */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); - /* "View.MemoryView":625 + /* "View.MemoryView":629 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< @@ -8527,13 +8578,13 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18 * def copy(self): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 625, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 629, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":621 + /* "View.MemoryView":625 * return slice_is_contig(mslice[0], 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< @@ -8552,7 +8603,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18 return __pyx_r; } -/* "View.MemoryView":627 +/* "View.MemoryView":631 * return slice_is_contig(mslice[0], 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< @@ -8582,7 +8633,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20 PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("copy", 0); - /* "View.MemoryView":629 + /* "View.MemoryView":633 * def copy(self): * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< @@ -8591,7 +8642,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20 */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); - /* "View.MemoryView":631 + /* "View.MemoryView":635 * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS * * slice_copy(self, &mslice) # <<<<<<<<<<<<<< @@ -8600,17 +8651,17 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20 */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); - /* "View.MemoryView":632 + /* "View.MemoryView":636 * * 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(1, 632, __pyx_L1_error) + __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(1, 636, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; - /* "View.MemoryView":637 + /* "View.MemoryView":641 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< @@ -8618,13 +8669,13 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20 * 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(1, 637, __pyx_L1_error) + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 641, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":627 + /* "View.MemoryView":631 * return slice_is_contig(mslice[0], 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< @@ -8643,7 +8694,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20 return __pyx_r; } -/* "View.MemoryView":639 +/* "View.MemoryView":643 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< @@ -8674,7 +8725,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22 PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("copy_fortran", 0); - /* "View.MemoryView":641 + /* "View.MemoryView":645 * def copy_fortran(self): * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< @@ -8683,7 +8734,7 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22 */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); - /* "View.MemoryView":643 + /* "View.MemoryView":647 * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS * * slice_copy(self, &src) # <<<<<<<<<<<<<< @@ -8692,17 +8743,17 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22 */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); - /* "View.MemoryView":644 + /* "View.MemoryView":648 * * 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(1, 644, __pyx_L1_error) + __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(1, 648, __pyx_L1_error) __pyx_v_dst = __pyx_t_1; - /* "View.MemoryView":649 + /* "View.MemoryView":653 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< @@ -8710,13 +8761,13 @@ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22 * */ __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(1, 649, __pyx_L1_error) + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 653, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":639 + /* "View.MemoryView":643 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< @@ -8842,7 +8893,7 @@ static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED st return __pyx_r; } -/* "View.MemoryView":653 +/* "View.MemoryView":657 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< @@ -8859,18 +8910,18 @@ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, in PyObject *__pyx_t_3 = NULL; __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); - /* "View.MemoryView":654 + /* "View.MemoryView":658 * @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(1, 654, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 658, __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(1, 654, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 658, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 654, __pyx_L1_error) + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 658, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_o); __Pyx_GIVEREF(__pyx_v_o); @@ -8881,13 +8932,13 @@ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, in 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(1, 654, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 658, __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":655 + /* "View.MemoryView":659 * 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 # <<<<<<<<<<<<<< @@ -8896,7 +8947,7 @@ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, in */ __pyx_v_result->typeinfo = __pyx_v_typeinfo; - /* "View.MemoryView":656 + /* "View.MemoryView":660 * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo * return result # <<<<<<<<<<<<<< @@ -8908,7 +8959,7 @@ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, in __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; - /* "View.MemoryView":653 + /* "View.MemoryView":657 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< @@ -8930,7 +8981,7 @@ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, in return __pyx_r; } -/* "View.MemoryView":659 +/* "View.MemoryView":663 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< @@ -8944,7 +8995,7 @@ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { int __pyx_t_1; __Pyx_RefNannySetupContext("memoryview_check", 0); - /* "View.MemoryView":660 + /* "View.MemoryView":664 * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): * return isinstance(o, memoryview) # <<<<<<<<<<<<<< @@ -8955,7 +9006,7 @@ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { __pyx_r = __pyx_t_1; goto __pyx_L0; - /* "View.MemoryView":659 + /* "View.MemoryView":663 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< @@ -8969,7 +9020,7 @@ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { return __pyx_r; } -/* "View.MemoryView":662 +/* "View.MemoryView":666 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< @@ -9000,7 +9051,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { PyObject *__pyx_t_11 = NULL; __Pyx_RefNannySetupContext("_unellipsify", 0); - /* "View.MemoryView":667 + /* "View.MemoryView":671 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< @@ -9011,14 +9062,14 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":668 + /* "View.MemoryView":672 * """ * if not isinstance(index, tuple): * tup = (index,) # <<<<<<<<<<<<<< * else: * tup = index */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 668, __pyx_L1_error) + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 672, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_index); __Pyx_GIVEREF(__pyx_v_index); @@ -9026,7 +9077,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_v_tup = __pyx_t_3; __pyx_t_3 = 0; - /* "View.MemoryView":667 + /* "View.MemoryView":671 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< @@ -9036,7 +9087,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { goto __pyx_L3; } - /* "View.MemoryView":670 + /* "View.MemoryView":674 * tup = (index,) * else: * tup = index # <<<<<<<<<<<<<< @@ -9049,19 +9100,19 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { } __pyx_L3:; - /* "View.MemoryView":672 + /* "View.MemoryView":676 * tup = index * * result = [] # <<<<<<<<<<<<<< * have_slices = False * seen_ellipsis = False */ - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 672, __pyx_L1_error) + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 676, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_v_result = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":673 + /* "View.MemoryView":677 * * result = [] * have_slices = False # <<<<<<<<<<<<<< @@ -9070,7 +9121,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { */ __pyx_v_have_slices = 0; - /* "View.MemoryView":674 + /* "View.MemoryView":678 * result = [] * have_slices = False * seen_ellipsis = False # <<<<<<<<<<<<<< @@ -9079,7 +9130,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { */ __pyx_v_seen_ellipsis = 0; - /* "View.MemoryView":675 + /* "View.MemoryView":679 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< @@ -9092,26 +9143,26 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __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(1, 675, __pyx_L1_error) + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 679, __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(1, 675, __pyx_L1_error) + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 679, __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(1, 675, __pyx_L1_error) + __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(1, 679, __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(1, 675, __pyx_L1_error) + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __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(1, 675, __pyx_L1_error) + __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(1, 679, __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(1, 675, __pyx_L1_error) + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #endif } @@ -9121,7 +9172,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 675, __pyx_L1_error) + else __PYX_ERR(1, 679, __pyx_L1_error) } break; } @@ -9131,13 +9182,13 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __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(1, 675, __pyx_L1_error) + __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __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":676 + /* "View.MemoryView":680 * seen_ellipsis = False * for idx, item in enumerate(tup): * if item is Ellipsis: # <<<<<<<<<<<<<< @@ -9148,7 +9199,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { - /* "View.MemoryView":677 + /* "View.MemoryView":681 * for idx, item in enumerate(tup): * if item is Ellipsis: * if not seen_ellipsis: # <<<<<<<<<<<<<< @@ -9158,15 +9209,15 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); if (__pyx_t_1) { - /* "View.MemoryView":678 + /* "View.MemoryView":682 * 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(1, 678, __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(1, 678, __pyx_L1_error) + __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == ((Py_ssize_t)-1))) __PYX_ERR(1, 682, __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(1, 682, __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++) { @@ -9175,10 +9226,10 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__15); } } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 678, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 682, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - /* "View.MemoryView":679 + /* "View.MemoryView":683 * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True # <<<<<<<<<<<<<< @@ -9187,7 +9238,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { */ __pyx_v_seen_ellipsis = 1; - /* "View.MemoryView":677 + /* "View.MemoryView":681 * for idx, item in enumerate(tup): * if item is Ellipsis: * if not seen_ellipsis: # <<<<<<<<<<<<<< @@ -9197,7 +9248,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { goto __pyx_L7; } - /* "View.MemoryView":681 + /* "View.MemoryView":685 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< @@ -9205,11 +9256,11 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { * else: */ /*else*/ { - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__15); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 681, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__15); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 685, __pyx_L1_error) } __pyx_L7:; - /* "View.MemoryView":682 + /* "View.MemoryView":686 * else: * result.append(slice(None)) * have_slices = True # <<<<<<<<<<<<<< @@ -9218,7 +9269,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { */ __pyx_v_have_slices = 1; - /* "View.MemoryView":676 + /* "View.MemoryView":680 * seen_ellipsis = False * for idx, item in enumerate(tup): * if item is Ellipsis: # <<<<<<<<<<<<<< @@ -9228,7 +9279,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { goto __pyx_L6; } - /* "View.MemoryView":684 + /* "View.MemoryView":688 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< @@ -9248,23 +9299,23 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_L9_bool_binop_done:; if (unlikely(__pyx_t_1)) { - /* "View.MemoryView":685 + /* "View.MemoryView":689 * 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(1, 685, __pyx_L1_error) + __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(1, 689, __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(1, 685, __pyx_L1_error) + __pyx_t_11 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 689, __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(1, 685, __pyx_L1_error) + __PYX_ERR(1, 689, __pyx_L1_error) - /* "View.MemoryView":684 + /* "View.MemoryView":688 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< @@ -9273,7 +9324,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { */ } - /* "View.MemoryView":687 + /* "View.MemoryView":691 * raise TypeError("Cannot index with type '%s'" % type(item)) * * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< @@ -9292,18 +9343,18 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_L11_bool_binop_done:; __pyx_v_have_slices = __pyx_t_1; - /* "View.MemoryView":688 + /* "View.MemoryView":692 * * 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(1, 688, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 692, __pyx_L1_error) } __pyx_L6:; - /* "View.MemoryView":675 + /* "View.MemoryView":679 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< @@ -9314,17 +9365,17 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":690 + /* "View.MemoryView":694 * 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(1, 690, __pyx_L1_error) + __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(1, 694, __pyx_L1_error) __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); - /* "View.MemoryView":691 + /* "View.MemoryView":695 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< @@ -9334,14 +9385,14 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_1 = (__pyx_v_nslices != 0); if (__pyx_t_1) { - /* "View.MemoryView":692 + /* "View.MemoryView":696 * 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(1, 692, __pyx_L1_error) + __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 696, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { @@ -9350,10 +9401,10 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__15); } } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 692, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 696, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":691 + /* "View.MemoryView":695 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< @@ -9362,7 +9413,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { */ } - /* "View.MemoryView":694 + /* "View.MemoryView":698 * result.extend([slice(None)] * nslices) * * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< @@ -9372,20 +9423,20 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_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(1, 694, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __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(1, 694, __pyx_L1_error) + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __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(1, 694, __pyx_L1_error) + __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 694, __pyx_L1_error) + __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 698, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_3); @@ -9397,7 +9448,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_11 = 0; goto __pyx_L0; - /* "View.MemoryView":662 + /* "View.MemoryView":666 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< @@ -9423,7 +9474,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { return __pyx_r; } -/* "View.MemoryView":696 +/* "View.MemoryView":700 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< @@ -9442,7 +9493,7 @@ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __ PyObject *__pyx_t_5 = NULL; __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); - /* "View.MemoryView":697 + /* "View.MemoryView":701 * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< @@ -9454,7 +9505,7 @@ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __ __pyx_t_1 = __pyx_t_3; __pyx_v_suboffset = (__pyx_t_1[0]); - /* "View.MemoryView":698 + /* "View.MemoryView":702 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -9464,20 +9515,20 @@ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __ __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); if (unlikely(__pyx_t_4)) { - /* "View.MemoryView":699 + /* "View.MemoryView":703 * 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__16, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 699, __pyx_L1_error) + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 703, __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(1, 699, __pyx_L1_error) + __PYX_ERR(1, 703, __pyx_L1_error) - /* "View.MemoryView":698 + /* "View.MemoryView":702 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -9487,7 +9538,7 @@ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __ } } - /* "View.MemoryView":696 + /* "View.MemoryView":700 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< @@ -9508,7 +9559,7 @@ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __ return __pyx_r; } -/* "View.MemoryView":706 +/* "View.MemoryView":710 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< @@ -9549,7 +9600,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ Py_ssize_t __pyx_t_12; __Pyx_RefNannySetupContext("memview_slice", 0); - /* "View.MemoryView":707 + /* "View.MemoryView":711 * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< @@ -9559,7 +9610,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_v_new_ndim = 0; __pyx_v_suboffset_dim = -1; - /* "View.MemoryView":714 + /* "View.MemoryView":718 * * * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< @@ -9568,7 +9619,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); - /* "View.MemoryView":718 + /* "View.MemoryView":722 * cdef _memoryviewslice memviewsliceobj * * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< @@ -9579,12 +9630,12 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(1, 718, __pyx_L1_error) + __PYX_ERR(1, 722, __pyx_L1_error) } } #endif - /* "View.MemoryView":720 + /* "View.MemoryView":724 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< @@ -9595,20 +9646,20 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":721 + /* "View.MemoryView":725 * * 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(1, 721, __pyx_L1_error) + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 725, __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":722 + /* "View.MemoryView":726 * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< @@ -9617,7 +9668,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); - /* "View.MemoryView":720 + /* "View.MemoryView":724 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< @@ -9627,7 +9678,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ goto __pyx_L3; } - /* "View.MemoryView":724 + /* "View.MemoryView":728 * p_src = &memviewsliceobj.from_slice * else: * slice_copy(memview, &src) # <<<<<<<<<<<<<< @@ -9637,7 +9688,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); - /* "View.MemoryView":725 + /* "View.MemoryView":729 * else: * slice_copy(memview, &src) * p_src = &src # <<<<<<<<<<<<<< @@ -9648,7 +9699,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ } __pyx_L3:; - /* "View.MemoryView":731 + /* "View.MemoryView":735 * * * dst.memview = p_src.memview # <<<<<<<<<<<<<< @@ -9658,7 +9709,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_4 = __pyx_v_p_src->memview; __pyx_v_dst.memview = __pyx_t_4; - /* "View.MemoryView":732 + /* "View.MemoryView":736 * * dst.memview = p_src.memview * dst.data = p_src.data # <<<<<<<<<<<<<< @@ -9668,7 +9719,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_5 = __pyx_v_p_src->data; __pyx_v_dst.data = __pyx_t_5; - /* "View.MemoryView":737 + /* "View.MemoryView":741 * * * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< @@ -9677,7 +9728,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ __pyx_v_p_dst = (&__pyx_v_dst); - /* "View.MemoryView":738 + /* "View.MemoryView":742 * * cdef __Pyx_memviewslice *p_dst = &dst * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< @@ -9686,7 +9737,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); - /* "View.MemoryView":742 + /* "View.MemoryView":746 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< @@ -9698,26 +9749,26 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __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(1, 742, __pyx_L1_error) + __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 746, __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(1, 742, __pyx_L1_error) + __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 746, __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(1, 742, __pyx_L1_error) + __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(1, 746, __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(1, 742, __pyx_L1_error) + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 746, __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(1, 742, __pyx_L1_error) + __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(1, 746, __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(1, 742, __pyx_L1_error) + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 746, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #endif } @@ -9727,7 +9778,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else __PYX_ERR(1, 742, __pyx_L1_error) + else __PYX_ERR(1, 746, __pyx_L1_error) } break; } @@ -9738,7 +9789,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_v_dim = __pyx_t_6; __pyx_t_6 = (__pyx_t_6 + 1); - /* "View.MemoryView":743 + /* "View.MemoryView":747 * * for dim, index in enumerate(indices): * if PyIndex_Check(index): # <<<<<<<<<<<<<< @@ -9748,25 +9799,25 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); if (__pyx_t_2) { - /* "View.MemoryView":747 + /* "View.MemoryView":751 * 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(1, 747, __pyx_L1_error) + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 751, __pyx_L1_error) - /* "View.MemoryView":744 + /* "View.MemoryView":748 * 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(1, 744, __pyx_L1_error) + __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(1, 748, __pyx_L1_error) - /* "View.MemoryView":743 + /* "View.MemoryView":747 * * for dim, index in enumerate(indices): * if PyIndex_Check(index): # <<<<<<<<<<<<<< @@ -9776,7 +9827,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ goto __pyx_L6; } - /* "View.MemoryView":750 + /* "View.MemoryView":754 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< @@ -9787,7 +9838,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { - /* "View.MemoryView":751 + /* "View.MemoryView":755 * False) * elif index is None: * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< @@ -9796,7 +9847,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; - /* "View.MemoryView":752 + /* "View.MemoryView":756 * elif index is None: * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< @@ -9805,7 +9856,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; - /* "View.MemoryView":753 + /* "View.MemoryView":757 * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< @@ -9814,7 +9865,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1L; - /* "View.MemoryView":754 + /* "View.MemoryView":758 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 * new_ndim += 1 # <<<<<<<<<<<<<< @@ -9823,7 +9874,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); - /* "View.MemoryView":750 + /* "View.MemoryView":754 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< @@ -9833,7 +9884,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ goto __pyx_L6; } - /* "View.MemoryView":756 + /* "View.MemoryView":760 * new_ndim += 1 * else: * start = index.start or 0 # <<<<<<<<<<<<<< @@ -9841,13 +9892,13 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ * 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(1, 756, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 760, __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(1, 756, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 760, __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(1, 756, __pyx_L1_error) + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 760, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L7_bool_binop_done; @@ -9856,20 +9907,20 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_L7_bool_binop_done:; __pyx_v_start = __pyx_t_10; - /* "View.MemoryView":757 + /* "View.MemoryView":761 * 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(1, 757, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 761, __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(1, 757, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 761, __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(1, 757, __pyx_L1_error) + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 761, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L9_bool_binop_done; @@ -9878,20 +9929,20 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_L9_bool_binop_done:; __pyx_v_stop = __pyx_t_10; - /* "View.MemoryView":758 + /* "View.MemoryView":762 * 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(1, 758, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 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(1, 758, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 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(1, 758, __pyx_L1_error) + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 762, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L11_bool_binop_done; @@ -9900,55 +9951,55 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_L11_bool_binop_done:; __pyx_v_step = __pyx_t_10; - /* "View.MemoryView":760 + /* "View.MemoryView":764 * 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(1, 760, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 764, __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":761 + /* "View.MemoryView":765 * * 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(1, 761, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 765, __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":762 + /* "View.MemoryView":766 * 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(1, 762, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 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_step = __pyx_t_1; - /* "View.MemoryView":764 + /* "View.MemoryView":768 * 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(1, 764, __pyx_L1_error) + __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(1, 768, __pyx_L1_error) - /* "View.MemoryView":770 + /* "View.MemoryView":774 * have_start, have_stop, have_step, * True) * new_ndim += 1 # <<<<<<<<<<<<<< @@ -9959,7 +10010,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ } __pyx_L6:; - /* "View.MemoryView":742 + /* "View.MemoryView":746 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< @@ -9969,7 +10020,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":772 + /* "View.MemoryView":776 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< @@ -9980,7 +10031,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":773 + /* "View.MemoryView":777 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< @@ -9989,39 +10040,39 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ __Pyx_XDECREF(((PyObject *)__pyx_r)); - /* "View.MemoryView":774 + /* "View.MemoryView":778 * 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(1, 774, __pyx_L1_error) } + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 778, __pyx_L1_error) } - /* "View.MemoryView":775 + /* "View.MemoryView":779 * 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(1, 775, __pyx_L1_error) } + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 779, __pyx_L1_error) } - /* "View.MemoryView":773 + /* "View.MemoryView":777 * * 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(1, 773, __pyx_L1_error) + __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(1, 777, __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(1, 773, __pyx_L1_error) + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 777, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; - /* "View.MemoryView":772 + /* "View.MemoryView":776 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< @@ -10030,7 +10081,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ } - /* "View.MemoryView":778 + /* "View.MemoryView":782 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< @@ -10040,30 +10091,30 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ /*else*/ { __Pyx_XDECREF(((PyObject *)__pyx_r)); - /* "View.MemoryView":779 + /* "View.MemoryView":783 * 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(1, 778, __pyx_L1_error) + __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(1, 782, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - /* "View.MemoryView":778 + /* "View.MemoryView":782 * 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(1, 778, __pyx_L1_error) + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 782, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } - /* "View.MemoryView":706 + /* "View.MemoryView":710 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< @@ -10085,7 +10136,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ return __pyx_r; } -/* "View.MemoryView":803 +/* "View.MemoryView":807 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< @@ -10101,7 +10152,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, int __pyx_t_2; int __pyx_t_3; - /* "View.MemoryView":823 + /* "View.MemoryView":827 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< @@ -10111,7 +10162,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_1) { - /* "View.MemoryView":825 + /* "View.MemoryView":829 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< @@ -10121,7 +10172,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_1 = ((__pyx_v_start < 0) != 0); if (__pyx_t_1) { - /* "View.MemoryView":826 + /* "View.MemoryView":830 * * if start < 0: * start += shape # <<<<<<<<<<<<<< @@ -10130,7 +10181,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - /* "View.MemoryView":825 + /* "View.MemoryView":829 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< @@ -10139,7 +10190,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":827 + /* "View.MemoryView":831 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< @@ -10153,16 +10204,16 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":828 + /* "View.MemoryView":832 * 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(1, 828, __pyx_L1_error) + __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(1, 832, __pyx_L1_error) - /* "View.MemoryView":827 + /* "View.MemoryView":831 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< @@ -10171,7 +10222,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":823 + /* "View.MemoryView":827 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< @@ -10181,7 +10232,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L3; } - /* "View.MemoryView":831 + /* "View.MemoryView":835 * else: * * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< @@ -10200,7 +10251,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_L6_bool_binop_done:; __pyx_v_negative_step = __pyx_t_2; - /* "View.MemoryView":833 + /* "View.MemoryView":837 * negative_step = have_step != 0 and step < 0 * * if have_step and step == 0: # <<<<<<<<<<<<<< @@ -10218,16 +10269,16 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_L9_bool_binop_done:; if (__pyx_t_2) { - /* "View.MemoryView":834 + /* "View.MemoryView":838 * * 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(1, 834, __pyx_L1_error) + __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(1, 838, __pyx_L1_error) - /* "View.MemoryView":833 + /* "View.MemoryView":837 * negative_step = have_step != 0 and step < 0 * * if have_step and step == 0: # <<<<<<<<<<<<<< @@ -10236,7 +10287,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":837 + /* "View.MemoryView":841 * * * if have_start: # <<<<<<<<<<<<<< @@ -10246,7 +10297,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (__pyx_v_have_start != 0); if (__pyx_t_2) { - /* "View.MemoryView":838 + /* "View.MemoryView":842 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< @@ -10256,7 +10307,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":839 + /* "View.MemoryView":843 * if have_start: * if start < 0: * start += shape # <<<<<<<<<<<<<< @@ -10265,7 +10316,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - /* "View.MemoryView":840 + /* "View.MemoryView":844 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< @@ -10275,7 +10326,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":841 + /* "View.MemoryView":845 * start += shape * if start < 0: * start = 0 # <<<<<<<<<<<<<< @@ -10284,7 +10335,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_start = 0; - /* "View.MemoryView":840 + /* "View.MemoryView":844 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< @@ -10293,7 +10344,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":838 + /* "View.MemoryView":842 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< @@ -10303,7 +10354,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L12; } - /* "View.MemoryView":842 + /* "View.MemoryView":846 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< @@ -10313,7 +10364,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); if (__pyx_t_2) { - /* "View.MemoryView":843 + /* "View.MemoryView":847 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< @@ -10323,7 +10374,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { - /* "View.MemoryView":844 + /* "View.MemoryView":848 * elif start >= shape: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< @@ -10332,7 +10383,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_start = (__pyx_v_shape - 1); - /* "View.MemoryView":843 + /* "View.MemoryView":847 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< @@ -10342,7 +10393,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L14; } - /* "View.MemoryView":846 + /* "View.MemoryView":850 * start = shape - 1 * else: * start = shape # <<<<<<<<<<<<<< @@ -10354,7 +10405,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L14:; - /* "View.MemoryView":842 + /* "View.MemoryView":846 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< @@ -10364,7 +10415,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L12:; - /* "View.MemoryView":837 + /* "View.MemoryView":841 * * * if have_start: # <<<<<<<<<<<<<< @@ -10374,7 +10425,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L11; } - /* "View.MemoryView":848 + /* "View.MemoryView":852 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< @@ -10385,7 +10436,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { - /* "View.MemoryView":849 + /* "View.MemoryView":853 * else: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< @@ -10394,7 +10445,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_start = (__pyx_v_shape - 1); - /* "View.MemoryView":848 + /* "View.MemoryView":852 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< @@ -10404,7 +10455,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L15; } - /* "View.MemoryView":851 + /* "View.MemoryView":855 * start = shape - 1 * else: * start = 0 # <<<<<<<<<<<<<< @@ -10418,7 +10469,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L11:; - /* "View.MemoryView":853 + /* "View.MemoryView":857 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< @@ -10428,7 +10479,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (__pyx_v_have_stop != 0); if (__pyx_t_2) { - /* "View.MemoryView":854 + /* "View.MemoryView":858 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< @@ -10438,7 +10489,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":855 + /* "View.MemoryView":859 * if have_stop: * if stop < 0: * stop += shape # <<<<<<<<<<<<<< @@ -10447,7 +10498,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); - /* "View.MemoryView":856 + /* "View.MemoryView":860 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< @@ -10457,7 +10508,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":857 + /* "View.MemoryView":861 * stop += shape * if stop < 0: * stop = 0 # <<<<<<<<<<<<<< @@ -10466,7 +10517,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_stop = 0; - /* "View.MemoryView":856 + /* "View.MemoryView":860 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< @@ -10475,7 +10526,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":854 + /* "View.MemoryView":858 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< @@ -10485,7 +10536,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L17; } - /* "View.MemoryView":858 + /* "View.MemoryView":862 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< @@ -10495,7 +10546,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); if (__pyx_t_2) { - /* "View.MemoryView":859 + /* "View.MemoryView":863 * stop = 0 * elif stop > shape: * stop = shape # <<<<<<<<<<<<<< @@ -10504,7 +10555,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_stop = __pyx_v_shape; - /* "View.MemoryView":858 + /* "View.MemoryView":862 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< @@ -10514,7 +10565,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L17:; - /* "View.MemoryView":853 + /* "View.MemoryView":857 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< @@ -10524,7 +10575,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L16; } - /* "View.MemoryView":861 + /* "View.MemoryView":865 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< @@ -10535,7 +10586,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { - /* "View.MemoryView":862 + /* "View.MemoryView":866 * else: * if negative_step: * stop = -1 # <<<<<<<<<<<<<< @@ -10544,7 +10595,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_stop = -1L; - /* "View.MemoryView":861 + /* "View.MemoryView":865 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< @@ -10554,7 +10605,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L19; } - /* "View.MemoryView":864 + /* "View.MemoryView":868 * stop = -1 * else: * stop = shape # <<<<<<<<<<<<<< @@ -10568,7 +10619,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L16:; - /* "View.MemoryView":866 + /* "View.MemoryView":870 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< @@ -10578,7 +10629,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":867 + /* "View.MemoryView":871 * * if not have_step: * step = 1 # <<<<<<<<<<<<<< @@ -10587,7 +10638,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_step = 1; - /* "View.MemoryView":866 + /* "View.MemoryView":870 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< @@ -10596,7 +10647,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":871 + /* "View.MemoryView":875 * * with cython.cdivision(True): * new_shape = (stop - start) // step # <<<<<<<<<<<<<< @@ -10605,7 +10656,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); - /* "View.MemoryView":873 + /* "View.MemoryView":877 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< @@ -10615,7 +10666,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":874 + /* "View.MemoryView":878 * * if (stop - start) - step * new_shape: * new_shape += 1 # <<<<<<<<<<<<<< @@ -10624,7 +10675,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_new_shape = (__pyx_v_new_shape + 1); - /* "View.MemoryView":873 + /* "View.MemoryView":877 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< @@ -10633,7 +10684,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":876 + /* "View.MemoryView":880 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< @@ -10643,7 +10694,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":877 + /* "View.MemoryView":881 * * if new_shape < 0: * new_shape = 0 # <<<<<<<<<<<<<< @@ -10652,7 +10703,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_new_shape = 0; - /* "View.MemoryView":876 + /* "View.MemoryView":880 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< @@ -10661,7 +10712,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":880 + /* "View.MemoryView":884 * * * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< @@ -10670,7 +10721,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); - /* "View.MemoryView":881 + /* "View.MemoryView":885 * * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< @@ -10679,7 +10730,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; - /* "View.MemoryView":882 + /* "View.MemoryView":886 * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< @@ -10690,7 +10741,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L3:; - /* "View.MemoryView":885 + /* "View.MemoryView":889 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< @@ -10700,7 +10751,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":886 + /* "View.MemoryView":890 * * if suboffset_dim[0] < 0: * dst.data += start * stride # <<<<<<<<<<<<<< @@ -10709,7 +10760,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); - /* "View.MemoryView":885 + /* "View.MemoryView":889 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< @@ -10719,7 +10770,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L23; } - /* "View.MemoryView":888 + /* "View.MemoryView":892 * dst.data += start * stride * else: * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< @@ -10732,7 +10783,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L23:; - /* "View.MemoryView":890 + /* "View.MemoryView":894 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -10742,7 +10793,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":891 + /* "View.MemoryView":895 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< @@ -10752,7 +10803,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":892 + /* "View.MemoryView":896 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< @@ -10762,7 +10813,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":893 + /* "View.MemoryView":897 * if not is_slice: * if new_ndim == 0: * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< @@ -10771,7 +10822,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); - /* "View.MemoryView":892 + /* "View.MemoryView":896 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< @@ -10781,7 +10832,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L26; } - /* "View.MemoryView":895 + /* "View.MemoryView":899 * dst.data = ( dst.data)[0] + suboffset * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< @@ -10790,18 +10841,18 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ /*else*/ { - /* "View.MemoryView":896 + /* "View.MemoryView":900 * 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(1, 895, __pyx_L1_error) + __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(1, 899, __pyx_L1_error) } __pyx_L26:; - /* "View.MemoryView":891 + /* "View.MemoryView":895 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< @@ -10811,7 +10862,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, goto __pyx_L25; } - /* "View.MemoryView":898 + /* "View.MemoryView":902 * "must be indexed and not sliced", dim) * else: * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< @@ -10823,7 +10874,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L25:; - /* "View.MemoryView":890 + /* "View.MemoryView":894 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -10832,7 +10883,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ } - /* "View.MemoryView":900 + /* "View.MemoryView":904 * suboffset_dim[0] = new_ndim * * return 0 # <<<<<<<<<<<<<< @@ -10842,7 +10893,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_r = 0; goto __pyx_L0; - /* "View.MemoryView":803 + /* "View.MemoryView":807 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< @@ -10866,7 +10917,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, return __pyx_r; } -/* "View.MemoryView":906 +/* "View.MemoryView":910 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< @@ -10888,7 +10939,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("pybuffer_index", 0); - /* "View.MemoryView":908 + /* "View.MemoryView":912 * 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 # <<<<<<<<<<<<<< @@ -10897,7 +10948,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_suboffset = -1L; - /* "View.MemoryView":909 + /* "View.MemoryView":913 * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< @@ -10907,7 +10958,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_1 = __pyx_v_view->itemsize; __pyx_v_itemsize = __pyx_t_1; - /* "View.MemoryView":912 + /* "View.MemoryView":916 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< @@ -10917,7 +10968,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":913 + /* "View.MemoryView":917 * * if view.ndim == 0: * shape = view.len / itemsize # <<<<<<<<<<<<<< @@ -10926,15 +10977,15 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ if (unlikely(__pyx_v_itemsize == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - __PYX_ERR(1, 913, __pyx_L1_error) + __PYX_ERR(1, 917, __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(1, 913, __pyx_L1_error) + __PYX_ERR(1, 917, __pyx_L1_error) } __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); - /* "View.MemoryView":914 + /* "View.MemoryView":918 * if view.ndim == 0: * shape = view.len / itemsize * stride = itemsize # <<<<<<<<<<<<<< @@ -10943,7 +10994,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_stride = __pyx_v_itemsize; - /* "View.MemoryView":912 + /* "View.MemoryView":916 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< @@ -10953,7 +11004,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P goto __pyx_L3; } - /* "View.MemoryView":916 + /* "View.MemoryView":920 * stride = itemsize * else: * shape = view.shape[dim] # <<<<<<<<<<<<<< @@ -10963,7 +11014,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P /*else*/ { __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); - /* "View.MemoryView":917 + /* "View.MemoryView":921 * else: * shape = view.shape[dim] * stride = view.strides[dim] # <<<<<<<<<<<<<< @@ -10972,7 +11023,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); - /* "View.MemoryView":918 + /* "View.MemoryView":922 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< @@ -10982,7 +11033,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); if (__pyx_t_2) { - /* "View.MemoryView":919 + /* "View.MemoryView":923 * stride = view.strides[dim] * if view.suboffsets != NULL: * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< @@ -10991,7 +11042,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); - /* "View.MemoryView":918 + /* "View.MemoryView":922 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< @@ -11002,7 +11053,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P } __pyx_L3:; - /* "View.MemoryView":921 + /* "View.MemoryView":925 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< @@ -11012,7 +11063,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":922 + /* "View.MemoryView":926 * * if index < 0: * index += view.shape[dim] # <<<<<<<<<<<<<< @@ -11021,7 +11072,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); - /* "View.MemoryView":923 + /* "View.MemoryView":927 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< @@ -11031,26 +11082,26 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (unlikely(__pyx_t_2)) { - /* "View.MemoryView":924 + /* "View.MemoryView":928 * 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(1, 924, __pyx_L1_error) + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 928, __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(1, 924, __pyx_L1_error) + __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(1, 928, __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(1, 924, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 928, __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(1, 924, __pyx_L1_error) + __PYX_ERR(1, 928, __pyx_L1_error) - /* "View.MemoryView":923 + /* "View.MemoryView":927 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< @@ -11059,7 +11110,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ } - /* "View.MemoryView":921 + /* "View.MemoryView":925 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< @@ -11068,7 +11119,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ } - /* "View.MemoryView":926 + /* "View.MemoryView":930 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< @@ -11078,26 +11129,26 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); if (unlikely(__pyx_t_2)) { - /* "View.MemoryView":927 + /* "View.MemoryView":931 * * 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(1, 927, __pyx_L1_error) + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 931, __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(1, 927, __pyx_L1_error) + __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(1, 931, __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(1, 927, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 931, __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(1, 927, __pyx_L1_error) + __PYX_ERR(1, 931, __pyx_L1_error) - /* "View.MemoryView":926 + /* "View.MemoryView":930 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< @@ -11106,7 +11157,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ } - /* "View.MemoryView":929 + /* "View.MemoryView":933 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * resultp = bufp + index * stride # <<<<<<<<<<<<<< @@ -11115,7 +11166,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); - /* "View.MemoryView":930 + /* "View.MemoryView":934 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -11125,7 +11176,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":931 + /* "View.MemoryView":935 * resultp = bufp + index * stride * if suboffset >= 0: * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< @@ -11134,7 +11185,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); - /* "View.MemoryView":930 + /* "View.MemoryView":934 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -11143,7 +11194,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ } - /* "View.MemoryView":933 + /* "View.MemoryView":937 * resultp = ( resultp)[0] + suboffset * * return resultp # <<<<<<<<<<<<<< @@ -11153,7 +11204,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_r = __pyx_v_resultp; goto __pyx_L0; - /* "View.MemoryView":906 + /* "View.MemoryView":910 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< @@ -11172,7 +11223,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P return __pyx_r; } -/* "View.MemoryView":939 +/* "View.MemoryView":943 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< @@ -11197,7 +11248,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { int __pyx_t_8; int __pyx_t_9; - /* "View.MemoryView":940 + /* "View.MemoryView":944 * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< @@ -11207,7 +11258,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; __pyx_v_ndim = __pyx_t_1; - /* "View.MemoryView":942 + /* "View.MemoryView":946 * cdef int ndim = memslice.memview.view.ndim * * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< @@ -11217,7 +11268,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_t_2 = __pyx_v_memslice->shape; __pyx_v_shape = __pyx_t_2; - /* "View.MemoryView":943 + /* "View.MemoryView":947 * * cdef Py_ssize_t *shape = memslice.shape * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< @@ -11227,7 +11278,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_t_2 = __pyx_v_memslice->strides; __pyx_v_strides = __pyx_t_2; - /* "View.MemoryView":947 + /* "View.MemoryView":951 * * cdef int i, j * for i in range(ndim / 2): # <<<<<<<<<<<<<< @@ -11239,7 +11290,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_4; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; - /* "View.MemoryView":948 + /* "View.MemoryView":952 * cdef int i, j * for i in range(ndim / 2): * j = ndim - 1 - i # <<<<<<<<<<<<<< @@ -11248,7 +11299,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { */ __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); - /* "View.MemoryView":949 + /* "View.MemoryView":953 * for i in range(ndim / 2): * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< @@ -11260,7 +11311,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { (__pyx_v_strides[__pyx_v_i]) = __pyx_t_5; (__pyx_v_strides[__pyx_v_j]) = __pyx_t_6; - /* "View.MemoryView":950 + /* "View.MemoryView":954 * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< @@ -11272,7 +11323,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { (__pyx_v_shape[__pyx_v_i]) = __pyx_t_6; (__pyx_v_shape[__pyx_v_j]) = __pyx_t_5; - /* "View.MemoryView":952 + /* "View.MemoryView":956 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< @@ -11290,16 +11341,16 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_L6_bool_binop_done:; if (__pyx_t_7) { - /* "View.MemoryView":953 + /* "View.MemoryView":957 * * 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(1, 953, __pyx_L1_error) + __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(1, 957, __pyx_L1_error) - /* "View.MemoryView":952 + /* "View.MemoryView":956 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< @@ -11309,7 +11360,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { } } - /* "View.MemoryView":955 + /* "View.MemoryView":959 * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * * return 1 # <<<<<<<<<<<<<< @@ -11319,7 +11370,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_r = 1; goto __pyx_L0; - /* "View.MemoryView":939 + /* "View.MemoryView":943 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< @@ -11343,7 +11394,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { return __pyx_r; } -/* "View.MemoryView":972 +/* "View.MemoryView":976 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< @@ -11366,7 +11417,7 @@ static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewsl __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__", 0); - /* "View.MemoryView":973 + /* "View.MemoryView":977 * * def __dealloc__(self): * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< @@ -11375,7 +11426,7 @@ static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewsl */ __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); - /* "View.MemoryView":972 + /* "View.MemoryView":976 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< @@ -11387,7 +11438,7 @@ static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewsl __Pyx_RefNannyFinishContext(); } -/* "View.MemoryView":975 +/* "View.MemoryView":979 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< @@ -11402,7 +11453,7 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("convert_item_to_object", 0); - /* "View.MemoryView":976 + /* "View.MemoryView":980 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< @@ -11412,7 +11463,7 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":977 + /* "View.MemoryView":981 * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: * return self.to_object_func(itemp) # <<<<<<<<<<<<<< @@ -11420,13 +11471,13 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor * 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(1, 977, __pyx_L1_error) + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 981, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":976 + /* "View.MemoryView":980 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< @@ -11435,7 +11486,7 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor */ } - /* "View.MemoryView":979 + /* "View.MemoryView":983 * return self.to_object_func(itemp) * else: * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< @@ -11444,14 +11495,14 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor */ /*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(1, 979, __pyx_L1_error) + __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(1, 983, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } - /* "View.MemoryView":975 + /* "View.MemoryView":979 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< @@ -11470,7 +11521,7 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor return __pyx_r; } -/* "View.MemoryView":981 +/* "View.MemoryView":985 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< @@ -11486,7 +11537,7 @@ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memo PyObject *__pyx_t_3 = NULL; __Pyx_RefNannySetupContext("assign_item_from_object", 0); - /* "View.MemoryView":982 + /* "View.MemoryView":986 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< @@ -11496,16 +11547,16 @@ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memo __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":983 + /* "View.MemoryView":987 * 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(1, 983, __pyx_L1_error) + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 987, __pyx_L1_error) - /* "View.MemoryView":982 + /* "View.MemoryView":986 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< @@ -11515,7 +11566,7 @@ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memo goto __pyx_L3; } - /* "View.MemoryView":985 + /* "View.MemoryView":989 * self.to_dtype_func(itemp, value) * else: * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< @@ -11523,13 +11574,13 @@ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memo * @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(1, 985, __pyx_L1_error) + __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(1, 989, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L3:; - /* "View.MemoryView":981 + /* "View.MemoryView":985 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< @@ -11550,7 +11601,7 @@ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memo return __pyx_r; } -/* "View.MemoryView":988 +/* "View.MemoryView":992 * * @property * def base(self): # <<<<<<<<<<<<<< @@ -11576,7 +11627,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__ __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":989 + /* "View.MemoryView":993 * @property * def base(self): * return self.from_object # <<<<<<<<<<<<<< @@ -11588,7 +11639,7 @@ static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__ __pyx_r = __pyx_v_self->from_object; goto __pyx_L0; - /* "View.MemoryView":988 + /* "View.MemoryView":992 * * @property * def base(self): # <<<<<<<<<<<<<< @@ -11710,7 +11761,7 @@ static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUS return __pyx_r; } -/* "View.MemoryView":995 +/* "View.MemoryView":999 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< @@ -11735,7 +11786,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("memoryview_fromslice", 0); - /* "View.MemoryView":1003 + /* "View.MemoryView":1007 * cdef _memoryviewslice result * * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< @@ -11745,7 +11796,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1004 + /* "View.MemoryView":1008 * * if memviewslice.memview == Py_None: * return None # <<<<<<<<<<<<<< @@ -11756,7 +11807,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; - /* "View.MemoryView":1003 + /* "View.MemoryView":1007 * cdef _memoryviewslice result * * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< @@ -11765,16 +11816,16 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ } - /* "View.MemoryView":1009 + /* "View.MemoryView":1013 * * * 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(1, 1009, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1013, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1009, __pyx_L1_error) + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1013, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); @@ -11785,13 +11836,13 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __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(1, 1009, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1013, __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":1011 + /* "View.MemoryView":1015 * result = _memoryviewslice(None, 0, dtype_is_object) * * result.from_slice = memviewslice # <<<<<<<<<<<<<< @@ -11800,7 +11851,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->from_slice = __pyx_v_memviewslice; - /* "View.MemoryView":1012 + /* "View.MemoryView":1016 * * result.from_slice = memviewslice * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< @@ -11809,14 +11860,14 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); - /* "View.MemoryView":1014 + /* "View.MemoryView":1018 * __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(1, 1014, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1018, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __Pyx_GOTREF(__pyx_v_result->from_object); @@ -11824,7 +11875,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_v_result->from_object = __pyx_t_2; __pyx_t_2 = 0; - /* "View.MemoryView":1015 + /* "View.MemoryView":1019 * * result.from_object = ( memviewslice.memview).base * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< @@ -11834,7 +11885,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; - /* "View.MemoryView":1017 + /* "View.MemoryView":1021 * result.typeinfo = memviewslice.memview.typeinfo * * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< @@ -11844,7 +11895,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_5 = __pyx_v_memviewslice.memview->view; __pyx_v_result->__pyx_base.view = __pyx_t_5; - /* "View.MemoryView":1018 + /* "View.MemoryView":1022 * * result.view = memviewslice.memview.view * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< @@ -11853,7 +11904,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); - /* "View.MemoryView":1019 + /* "View.MemoryView":1023 * result.view = memviewslice.memview.view * result.view.buf = memviewslice.data * result.view.ndim = ndim # <<<<<<<<<<<<<< @@ -11862,7 +11913,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; - /* "View.MemoryView":1020 + /* "View.MemoryView":1024 * result.view.buf = memviewslice.data * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< @@ -11871,7 +11922,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; - /* "View.MemoryView":1021 + /* "View.MemoryView":1025 * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< @@ -11880,7 +11931,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ Py_INCREF(Py_None); - /* "View.MemoryView":1023 + /* "View.MemoryView":1027 * Py_INCREF(Py_None) * * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< @@ -11890,7 +11941,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_1 = ((((struct __pyx_memoryview_obj *)__pyx_v_memviewslice.memview)->flags & PyBUF_WRITABLE) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1024 + /* "View.MemoryView":1028 * * if (memviewslice.memview).flags & PyBUF_WRITABLE: * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< @@ -11899,7 +11950,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; - /* "View.MemoryView":1023 + /* "View.MemoryView":1027 * Py_INCREF(Py_None) * * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< @@ -11909,7 +11960,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl goto __pyx_L4; } - /* "View.MemoryView":1026 + /* "View.MemoryView":1030 * result.flags = PyBUF_RECORDS * else: * result.flags = PyBUF_RECORDS_RO # <<<<<<<<<<<<<< @@ -11921,7 +11972,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl } __pyx_L4:; - /* "View.MemoryView":1028 + /* "View.MemoryView":1032 * result.flags = PyBUF_RECORDS_RO * * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< @@ -11930,7 +11981,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); - /* "View.MemoryView":1029 + /* "View.MemoryView":1033 * * result.view.shape = result.from_slice.shape * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< @@ -11939,7 +11990,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); - /* "View.MemoryView":1032 + /* "View.MemoryView":1036 * * * result.view.suboffsets = NULL # <<<<<<<<<<<<<< @@ -11948,7 +11999,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.view.suboffsets = NULL; - /* "View.MemoryView":1033 + /* "View.MemoryView":1037 * * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< @@ -11960,7 +12011,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_6 = __pyx_t_8; __pyx_v_suboffset = (__pyx_t_6[0]); - /* "View.MemoryView":1034 + /* "View.MemoryView":1038 * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -11970,7 +12021,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1035 + /* "View.MemoryView":1039 * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< @@ -11979,7 +12030,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); - /* "View.MemoryView":1036 + /* "View.MemoryView":1040 * if suboffset >= 0: * result.view.suboffsets = result.from_slice.suboffsets * break # <<<<<<<<<<<<<< @@ -11988,7 +12039,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ goto __pyx_L6_break; - /* "View.MemoryView":1034 + /* "View.MemoryView":1038 * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -11999,7 +12050,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl } __pyx_L6_break:; - /* "View.MemoryView":1038 + /* "View.MemoryView":1042 * break * * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< @@ -12009,7 +12060,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - /* "View.MemoryView":1039 + /* "View.MemoryView":1043 * * result.view.len = result.view.itemsize * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< @@ -12019,29 +12070,29 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __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(1, 1039, __pyx_L1_error) + __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1043, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":1040 + /* "View.MemoryView":1044 * 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(1, 1040, __pyx_L1_error) + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1044, __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(1, 1040, __pyx_L1_error) + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1044, __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(1, 1040, __pyx_L1_error) + __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 1044, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; } - /* "View.MemoryView":1042 + /* "View.MemoryView":1046 * result.view.len *= length * * result.to_object_func = to_object_func # <<<<<<<<<<<<<< @@ -12050,7 +12101,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->to_object_func = __pyx_v_to_object_func; - /* "View.MemoryView":1043 + /* "View.MemoryView":1047 * * result.to_object_func = to_object_func * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< @@ -12059,7 +12110,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; - /* "View.MemoryView":1045 + /* "View.MemoryView":1049 * result.to_dtype_func = to_dtype_func * * return result # <<<<<<<<<<<<<< @@ -12071,7 +12122,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; - /* "View.MemoryView":995 + /* "View.MemoryView":999 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< @@ -12093,7 +12144,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl return __pyx_r; } -/* "View.MemoryView":1048 +/* "View.MemoryView":1052 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< @@ -12110,7 +12161,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p PyObject *__pyx_t_3 = NULL; __Pyx_RefNannySetupContext("get_slice_from_memview", 0); - /* "View.MemoryView":1051 + /* "View.MemoryView":1055 * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< @@ -12121,20 +12172,20 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":1052 + /* "View.MemoryView":1056 * 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(1, 1052, __pyx_L1_error) + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 1056, __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":1053 + /* "View.MemoryView":1057 * if isinstance(memview, _memoryviewslice): * obj = memview * return &obj.from_slice # <<<<<<<<<<<<<< @@ -12144,7 +12195,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p __pyx_r = (&__pyx_v_obj->from_slice); goto __pyx_L0; - /* "View.MemoryView":1051 + /* "View.MemoryView":1055 * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< @@ -12153,7 +12204,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p */ } - /* "View.MemoryView":1055 + /* "View.MemoryView":1059 * return &obj.from_slice * else: * slice_copy(memview, mslice) # <<<<<<<<<<<<<< @@ -12163,7 +12214,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); - /* "View.MemoryView":1056 + /* "View.MemoryView":1060 * else: * slice_copy(memview, mslice) * return mslice # <<<<<<<<<<<<<< @@ -12174,7 +12225,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p goto __pyx_L0; } - /* "View.MemoryView":1048 + /* "View.MemoryView":1052 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< @@ -12193,7 +12244,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p return __pyx_r; } -/* "View.MemoryView":1059 +/* "View.MemoryView":1063 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< @@ -12214,7 +12265,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem Py_ssize_t __pyx_t_5; __Pyx_RefNannySetupContext("slice_copy", 0); - /* "View.MemoryView":1063 + /* "View.MemoryView":1067 * cdef (Py_ssize_t*) shape, strides, suboffsets * * shape = memview.view.shape # <<<<<<<<<<<<<< @@ -12224,7 +12275,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem __pyx_t_1 = __pyx_v_memview->view.shape; __pyx_v_shape = __pyx_t_1; - /* "View.MemoryView":1064 + /* "View.MemoryView":1068 * * shape = memview.view.shape * strides = memview.view.strides # <<<<<<<<<<<<<< @@ -12234,7 +12285,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem __pyx_t_1 = __pyx_v_memview->view.strides; __pyx_v_strides = __pyx_t_1; - /* "View.MemoryView":1065 + /* "View.MemoryView":1069 * shape = memview.view.shape * strides = memview.view.strides * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< @@ -12244,7 +12295,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem __pyx_t_1 = __pyx_v_memview->view.suboffsets; __pyx_v_suboffsets = __pyx_t_1; - /* "View.MemoryView":1067 + /* "View.MemoryView":1071 * suboffsets = memview.view.suboffsets * * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< @@ -12253,7 +12304,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem */ __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); - /* "View.MemoryView":1068 + /* "View.MemoryView":1072 * * dst.memview = <__pyx_memoryview *> memview * dst.data = memview.view.buf # <<<<<<<<<<<<<< @@ -12262,7 +12313,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem */ __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); - /* "View.MemoryView":1070 + /* "View.MemoryView":1074 * dst.data = memview.view.buf * * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< @@ -12274,7 +12325,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_dim = __pyx_t_4; - /* "View.MemoryView":1071 + /* "View.MemoryView":1075 * * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< @@ -12283,7 +12334,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem */ (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); - /* "View.MemoryView":1072 + /* "View.MemoryView":1076 * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< @@ -12292,7 +12343,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem */ (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); - /* "View.MemoryView":1073 + /* "View.MemoryView":1077 * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< @@ -12307,7 +12358,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_5; } - /* "View.MemoryView":1059 + /* "View.MemoryView":1063 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< @@ -12319,7 +12370,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem __Pyx_RefNannyFinishContext(); } -/* "View.MemoryView":1076 +/* "View.MemoryView":1080 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< @@ -12334,7 +12385,7 @@ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("memoryview_copy", 0); - /* "View.MemoryView":1079 + /* "View.MemoryView":1083 * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< @@ -12343,7 +12394,7 @@ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx */ __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); - /* "View.MemoryView":1080 + /* "View.MemoryView":1084 * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< @@ -12351,13 +12402,13 @@ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx * @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(1, 1080, __pyx_L1_error) + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1084, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":1076 + /* "View.MemoryView":1080 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< @@ -12376,7 +12427,7 @@ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx return __pyx_r; } -/* "View.MemoryView":1083 +/* "View.MemoryView":1087 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< @@ -12396,7 +12447,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview PyObject *__pyx_t_5 = NULL; __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); - /* "View.MemoryView":1090 + /* "View.MemoryView":1094 * cdef int (*to_dtype_func)(char *, object) except 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< @@ -12407,7 +12458,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":1091 + /* "View.MemoryView":1095 * * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< @@ -12417,7 +12468,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; __pyx_v_to_object_func = __pyx_t_3; - /* "View.MemoryView":1092 + /* "View.MemoryView":1096 * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< @@ -12427,7 +12478,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; __pyx_v_to_dtype_func = __pyx_t_4; - /* "View.MemoryView":1090 + /* "View.MemoryView":1094 * cdef int (*to_dtype_func)(char *, object) except 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< @@ -12437,7 +12488,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview goto __pyx_L3; } - /* "View.MemoryView":1094 + /* "View.MemoryView":1098 * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: * to_object_func = NULL # <<<<<<<<<<<<<< @@ -12447,7 +12498,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview /*else*/ { __pyx_v_to_object_func = NULL; - /* "View.MemoryView":1095 + /* "View.MemoryView":1099 * else: * to_object_func = NULL * to_dtype_func = NULL # <<<<<<<<<<<<<< @@ -12458,7 +12509,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview } __pyx_L3:; - /* "View.MemoryView":1097 + /* "View.MemoryView":1101 * to_dtype_func = NULL * * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< @@ -12467,20 +12518,20 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview */ __Pyx_XDECREF(__pyx_r); - /* "View.MemoryView":1099 + /* "View.MemoryView":1103 * 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(1, 1097, __pyx_L1_error) + __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(1, 1101, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; - /* "View.MemoryView":1083 + /* "View.MemoryView":1087 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< @@ -12499,7 +12550,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview return __pyx_r; } -/* "View.MemoryView":1105 +/* "View.MemoryView":1109 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< @@ -12511,7 +12562,7 @@ 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":1106 + /* "View.MemoryView":1110 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< @@ -12521,7 +12572,7 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { __pyx_t_1 = ((__pyx_v_arg < 0) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1107 + /* "View.MemoryView":1111 * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: * return -arg # <<<<<<<<<<<<<< @@ -12531,7 +12582,7 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { __pyx_r = (-__pyx_v_arg); goto __pyx_L0; - /* "View.MemoryView":1106 + /* "View.MemoryView":1110 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< @@ -12540,7 +12591,7 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { */ } - /* "View.MemoryView":1109 + /* "View.MemoryView":1113 * return -arg * else: * return arg # <<<<<<<<<<<<<< @@ -12552,7 +12603,7 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { goto __pyx_L0; } - /* "View.MemoryView":1105 + /* "View.MemoryView":1109 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< @@ -12565,7 +12616,7 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { return __pyx_r; } -/* "View.MemoryView":1112 +/* "View.MemoryView":1116 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< @@ -12583,7 +12634,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ int __pyx_t_3; int __pyx_t_4; - /* "View.MemoryView":1117 + /* "View.MemoryView":1121 * """ * cdef int i * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< @@ -12592,7 +12643,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_v_c_stride = 0; - /* "View.MemoryView":1118 + /* "View.MemoryView":1122 * cdef int i * cdef Py_ssize_t c_stride = 0 * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< @@ -12601,7 +12652,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_v_f_stride = 0; - /* "View.MemoryView":1120 + /* "View.MemoryView":1124 * cdef Py_ssize_t f_stride = 0 * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< @@ -12611,7 +12662,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; - /* "View.MemoryView":1121 + /* "View.MemoryView":1125 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< @@ -12621,7 +12672,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1122 + /* "View.MemoryView":1126 * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< @@ -12630,7 +12681,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - /* "View.MemoryView":1123 + /* "View.MemoryView":1127 * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< @@ -12639,7 +12690,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ goto __pyx_L4_break; - /* "View.MemoryView":1121 + /* "View.MemoryView":1125 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< @@ -12650,7 +12701,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ } __pyx_L4_break:; - /* "View.MemoryView":1125 + /* "View.MemoryView":1129 * break * * for i in range(ndim): # <<<<<<<<<<<<<< @@ -12662,7 +12713,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; - /* "View.MemoryView":1126 + /* "View.MemoryView":1130 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< @@ -12672,7 +12723,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1127 + /* "View.MemoryView":1131 * for i in range(ndim): * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< @@ -12681,7 +12732,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - /* "View.MemoryView":1128 + /* "View.MemoryView":1132 * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< @@ -12690,7 +12741,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ goto __pyx_L7_break; - /* "View.MemoryView":1126 + /* "View.MemoryView":1130 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< @@ -12701,7 +12752,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ } __pyx_L7_break:; - /* "View.MemoryView":1130 + /* "View.MemoryView":1134 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< @@ -12711,7 +12762,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ __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":1131 + /* "View.MemoryView":1135 * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): * return 'C' # <<<<<<<<<<<<<< @@ -12721,7 +12772,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ __pyx_r = 'C'; goto __pyx_L0; - /* "View.MemoryView":1130 + /* "View.MemoryView":1134 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< @@ -12730,7 +12781,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ } - /* "View.MemoryView":1133 + /* "View.MemoryView":1137 * return 'C' * else: * return 'F' # <<<<<<<<<<<<<< @@ -12742,7 +12793,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ goto __pyx_L0; } - /* "View.MemoryView":1112 + /* "View.MemoryView":1116 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< @@ -12755,7 +12806,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ return __pyx_r; } -/* "View.MemoryView":1136 +/* "View.MemoryView":1140 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< @@ -12776,7 +12827,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v Py_ssize_t __pyx_t_5; Py_ssize_t __pyx_t_6; - /* "View.MemoryView":1143 + /* "View.MemoryView":1147 * * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< @@ -12785,7 +12836,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_src_extent = (__pyx_v_src_shape[0]); - /* "View.MemoryView":1144 + /* "View.MemoryView":1148 * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< @@ -12794,7 +12845,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); - /* "View.MemoryView":1145 + /* "View.MemoryView":1149 * 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] # <<<<<<<<<<<<<< @@ -12803,7 +12854,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_src_stride = (__pyx_v_src_strides[0]); - /* "View.MemoryView":1146 + /* "View.MemoryView":1150 * 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] # <<<<<<<<<<<<<< @@ -12812,7 +12863,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); - /* "View.MemoryView":1148 + /* "View.MemoryView":1152 * cdef Py_ssize_t dst_stride = dst_strides[0] * * if ndim == 1: # <<<<<<<<<<<<<< @@ -12822,7 +12873,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1149 + /* "View.MemoryView":1153 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< @@ -12842,7 +12893,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v goto __pyx_L5_bool_binop_done; } - /* "View.MemoryView":1150 + /* "View.MemoryView":1154 * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< @@ -12857,7 +12908,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v __pyx_t_1 = __pyx_t_3; __pyx_L5_bool_binop_done:; - /* "View.MemoryView":1149 + /* "View.MemoryView":1153 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< @@ -12866,7 +12917,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ if (__pyx_t_1) { - /* "View.MemoryView":1151 + /* "View.MemoryView":1155 * if (src_stride > 0 and dst_stride > 0 and * src_stride == itemsize == dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< @@ -12875,7 +12926,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent))); - /* "View.MemoryView":1149 + /* "View.MemoryView":1153 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< @@ -12885,7 +12936,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v goto __pyx_L4; } - /* "View.MemoryView":1153 + /* "View.MemoryView":1157 * memcpy(dst_data, src_data, itemsize * dst_extent) * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< @@ -12898,7 +12949,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "View.MemoryView":1154 + /* "View.MemoryView":1158 * else: * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< @@ -12907,7 +12958,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize)); - /* "View.MemoryView":1155 + /* "View.MemoryView":1159 * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< @@ -12916,7 +12967,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - /* "View.MemoryView":1156 + /* "View.MemoryView":1160 * memcpy(dst_data, src_data, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< @@ -12928,7 +12979,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v } __pyx_L4:; - /* "View.MemoryView":1148 + /* "View.MemoryView":1152 * cdef Py_ssize_t dst_stride = dst_strides[0] * * if ndim == 1: # <<<<<<<<<<<<<< @@ -12938,7 +12989,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v goto __pyx_L3; } - /* "View.MemoryView":1158 + /* "View.MemoryView":1162 * dst_data += dst_stride * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< @@ -12951,7 +13002,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "View.MemoryView":1159 + /* "View.MemoryView":1163 * else: * for i in range(dst_extent): * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< @@ -12960,7 +13011,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ _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":1163 + /* "View.MemoryView":1167 * src_shape + 1, dst_shape + 1, * ndim - 1, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< @@ -12969,7 +13020,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - /* "View.MemoryView":1164 + /* "View.MemoryView":1168 * ndim - 1, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< @@ -12981,7 +13032,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v } __pyx_L3:; - /* "View.MemoryView":1136 + /* "View.MemoryView":1140 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< @@ -12992,7 +13043,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v /* function exit code */ } -/* "View.MemoryView":1166 +/* "View.MemoryView":1170 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< @@ -13002,7 +13053,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v 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":1169 + /* "View.MemoryView":1173 * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< @@ -13011,7 +13062,7 @@ static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memvi */ _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":1166 + /* "View.MemoryView":1170 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< @@ -13022,7 +13073,7 @@ static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memvi /* function exit code */ } -/* "View.MemoryView":1173 +/* "View.MemoryView":1177 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< @@ -13039,7 +13090,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr int __pyx_t_3; int __pyx_t_4; - /* "View.MemoryView":1176 + /* "View.MemoryView":1180 * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< @@ -13049,7 +13100,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_size = __pyx_t_1; - /* "View.MemoryView":1178 + /* "View.MemoryView":1182 * cdef Py_ssize_t size = src.memview.view.itemsize * * for i in range(ndim): # <<<<<<<<<<<<<< @@ -13061,7 +13112,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; - /* "View.MemoryView":1179 + /* "View.MemoryView":1183 * * for i in range(ndim): * size *= src.shape[i] # <<<<<<<<<<<<<< @@ -13071,7 +13122,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); } - /* "View.MemoryView":1181 + /* "View.MemoryView":1185 * size *= src.shape[i] * * return size # <<<<<<<<<<<<<< @@ -13081,7 +13132,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr __pyx_r = __pyx_v_size; goto __pyx_L0; - /* "View.MemoryView":1173 + /* "View.MemoryView":1177 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< @@ -13094,7 +13145,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr return __pyx_r; } -/* "View.MemoryView":1184 +/* "View.MemoryView":1188 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< @@ -13110,7 +13161,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ int __pyx_t_3; int __pyx_t_4; - /* "View.MemoryView":1193 + /* "View.MemoryView":1197 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< @@ -13120,7 +13171,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ __pyx_t_1 = ((__pyx_v_order == 'F') != 0); if (__pyx_t_1) { - /* "View.MemoryView":1194 + /* "View.MemoryView":1198 * * if order == 'F': * for idx in range(ndim): # <<<<<<<<<<<<<< @@ -13132,7 +13183,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_idx = __pyx_t_4; - /* "View.MemoryView":1195 + /* "View.MemoryView":1199 * if order == 'F': * for idx in range(ndim): * strides[idx] = stride # <<<<<<<<<<<<<< @@ -13141,7 +13192,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - /* "View.MemoryView":1196 + /* "View.MemoryView":1200 * for idx in range(ndim): * strides[idx] = stride * stride = stride * shape[idx] # <<<<<<<<<<<<<< @@ -13151,7 +13202,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } - /* "View.MemoryView":1193 + /* "View.MemoryView":1197 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< @@ -13161,7 +13212,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ goto __pyx_L3; } - /* "View.MemoryView":1198 + /* "View.MemoryView":1202 * stride = stride * shape[idx] * else: * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< @@ -13172,7 +13223,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { __pyx_v_idx = __pyx_t_2; - /* "View.MemoryView":1199 + /* "View.MemoryView":1203 * else: * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride # <<<<<<<<<<<<<< @@ -13181,7 +13232,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - /* "View.MemoryView":1200 + /* "View.MemoryView":1204 * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride * stride = stride * shape[idx] # <<<<<<<<<<<<<< @@ -13193,7 +13244,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ } __pyx_L3:; - /* "View.MemoryView":1202 + /* "View.MemoryView":1206 * stride = stride * shape[idx] * * return stride # <<<<<<<<<<<<<< @@ -13203,7 +13254,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ __pyx_r = __pyx_v_stride; goto __pyx_L0; - /* "View.MemoryView":1184 + /* "View.MemoryView":1188 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< @@ -13216,7 +13267,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ return __pyx_r; } -/* "View.MemoryView":1205 +/* "View.MemoryView":1209 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< @@ -13237,7 +13288,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, int __pyx_t_5; int __pyx_t_6; - /* "View.MemoryView":1216 + /* "View.MemoryView":1220 * cdef void *result * * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< @@ -13247,7 +13298,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; - /* "View.MemoryView":1217 + /* "View.MemoryView":1221 * * cdef size_t itemsize = src.memview.view.itemsize * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< @@ -13256,7 +13307,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); - /* "View.MemoryView":1219 + /* "View.MemoryView":1223 * cdef size_t size = slice_get_size(src, ndim) * * result = malloc(size) # <<<<<<<<<<<<<< @@ -13265,7 +13316,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ __pyx_v_result = malloc(__pyx_v_size); - /* "View.MemoryView":1220 + /* "View.MemoryView":1224 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< @@ -13275,16 +13326,16 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1221 + /* "View.MemoryView":1225 * 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(1, 1221, __pyx_L1_error) + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 1225, __pyx_L1_error) - /* "View.MemoryView":1220 + /* "View.MemoryView":1224 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< @@ -13293,7 +13344,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ } - /* "View.MemoryView":1224 + /* "View.MemoryView":1228 * * * tmpslice.data = result # <<<<<<<<<<<<<< @@ -13302,7 +13353,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ __pyx_v_tmpslice->data = ((char *)__pyx_v_result); - /* "View.MemoryView":1225 + /* "View.MemoryView":1229 * * tmpslice.data = result * tmpslice.memview = src.memview # <<<<<<<<<<<<<< @@ -13312,7 +13363,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_4 = __pyx_v_src->memview; __pyx_v_tmpslice->memview = __pyx_t_4; - /* "View.MemoryView":1226 + /* "View.MemoryView":1230 * tmpslice.data = result * tmpslice.memview = src.memview * for i in range(ndim): # <<<<<<<<<<<<<< @@ -13324,7 +13375,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "View.MemoryView":1227 + /* "View.MemoryView":1231 * tmpslice.memview = src.memview * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< @@ -13333,7 +13384,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); - /* "View.MemoryView":1228 + /* "View.MemoryView":1232 * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< @@ -13343,7 +13394,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1L; } - /* "View.MemoryView":1230 + /* "View.MemoryView":1234 * tmpslice.suboffsets[i] = -1 * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< @@ -13352,7 +13403,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ (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":1234 + /* "View.MemoryView":1238 * * * for i in range(ndim): # <<<<<<<<<<<<<< @@ -13364,7 +13415,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; - /* "View.MemoryView":1235 + /* "View.MemoryView":1239 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< @@ -13374,7 +13425,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1236 + /* "View.MemoryView":1240 * for i in range(ndim): * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< @@ -13383,7 +13434,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; - /* "View.MemoryView":1235 + /* "View.MemoryView":1239 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< @@ -13393,7 +13444,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, } } - /* "View.MemoryView":1238 + /* "View.MemoryView":1242 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< @@ -13403,7 +13454,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1239 + /* "View.MemoryView":1243 * * if slice_is_contig(src[0], order, ndim): * memcpy(result, src.data, size) # <<<<<<<<<<<<<< @@ -13412,7 +13463,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ (void)(memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size)); - /* "View.MemoryView":1238 + /* "View.MemoryView":1242 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< @@ -13422,7 +13473,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, goto __pyx_L9; } - /* "View.MemoryView":1241 + /* "View.MemoryView":1245 * memcpy(result, src.data, size) * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< @@ -13434,7 +13485,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, } __pyx_L9:; - /* "View.MemoryView":1243 + /* "View.MemoryView":1247 * copy_strided_to_strided(src, tmpslice, ndim, itemsize) * * return result # <<<<<<<<<<<<<< @@ -13444,7 +13495,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_r = __pyx_v_result; goto __pyx_L0; - /* "View.MemoryView":1205 + /* "View.MemoryView":1209 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< @@ -13468,7 +13519,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, return __pyx_r; } -/* "View.MemoryView":1248 +/* "View.MemoryView":1252 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< @@ -13488,20 +13539,20 @@ static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent #endif __Pyx_RefNannySetupContext("_err_extents", 0); - /* "View.MemoryView":1251 + /* "View.MemoryView":1255 * 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(1, 1251, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1251, __pyx_L1_error) + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1251, __pyx_L1_error) + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1251, __pyx_L1_error) + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); @@ -13513,24 +13564,24 @@ static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent __pyx_t_2 = 0; __pyx_t_3 = 0; - /* "View.MemoryView":1250 + /* "View.MemoryView":1254 * 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(1, 1250, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1254, __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(1, 1250, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1254, __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(1, 1250, __pyx_L1_error) + __PYX_ERR(1, 1254, __pyx_L1_error) - /* "View.MemoryView":1248 + /* "View.MemoryView":1252 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< @@ -13553,7 +13604,7 @@ static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent return __pyx_r; } -/* "View.MemoryView":1254 +/* "View.MemoryView":1258 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< @@ -13574,18 +13625,18 @@ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, __Pyx_RefNannySetupContext("_err_dim", 0); __Pyx_INCREF(__pyx_v_error); - /* "View.MemoryView":1255 + /* "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) # <<<<<<<<<<<<<< * * @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(1, 1255, __pyx_L1_error) + __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(1, 1259, __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(1, 1255, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1259, __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(1, 1255, __pyx_L1_error) + __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1259, __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; @@ -13603,14 +13654,14 @@ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, __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(1, 1255, __pyx_L1_error) + if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1259, __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(1, 1255, __pyx_L1_error) + __PYX_ERR(1, 1259, __pyx_L1_error) - /* "View.MemoryView":1254 + /* "View.MemoryView":1258 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< @@ -13634,7 +13685,7 @@ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, return __pyx_r; } -/* "View.MemoryView":1258 +/* "View.MemoryView":1262 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< @@ -13656,7 +13707,7 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { __Pyx_RefNannySetupContext("_err", 0); __Pyx_INCREF(__pyx_v_error); - /* "View.MemoryView":1259 + /* "View.MemoryView":1263 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< @@ -13666,14 +13717,14 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); if (unlikely(__pyx_t_1)) { - /* "View.MemoryView":1260 + /* "View.MemoryView":1264 * 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(1, 1260, __pyx_L1_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(1, 1264, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_error); __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; @@ -13689,14 +13740,14 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { __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(1, 1260, __pyx_L1_error) + if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1264, __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(1, 1260, __pyx_L1_error) + __PYX_ERR(1, 1264, __pyx_L1_error) - /* "View.MemoryView":1259 + /* "View.MemoryView":1263 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< @@ -13705,7 +13756,7 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { */ } - /* "View.MemoryView":1262 + /* "View.MemoryView":1266 * raise error(msg.decode('ascii')) * else: * raise error # <<<<<<<<<<<<<< @@ -13714,10 +13765,10 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { */ /*else*/ { __Pyx_Raise(__pyx_v_error, 0, 0, 0); - __PYX_ERR(1, 1262, __pyx_L1_error) + __PYX_ERR(1, 1266, __pyx_L1_error) } - /* "View.MemoryView":1258 + /* "View.MemoryView":1262 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< @@ -13741,7 +13792,7 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { return __pyx_r; } -/* "View.MemoryView":1265 +/* "View.MemoryView":1269 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< @@ -13768,7 +13819,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ void *__pyx_t_7; int __pyx_t_8; - /* "View.MemoryView":1273 + /* "View.MemoryView":1277 * Check for overlapping memory and verify the shapes. * """ * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< @@ -13777,7 +13828,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_tmpdata = NULL; - /* "View.MemoryView":1274 + /* "View.MemoryView":1278 * """ * cdef void *tmpdata = NULL * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< @@ -13787,7 +13838,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_1 = __pyx_v_src.memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; - /* "View.MemoryView":1276 + /* "View.MemoryView":1280 * cdef size_t itemsize = src.memview.view.itemsize * cdef int i * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< @@ -13796,7 +13847,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); - /* "View.MemoryView":1277 + /* "View.MemoryView":1281 * cdef int i * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False # <<<<<<<<<<<<<< @@ -13805,7 +13856,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_broadcasting = 0; - /* "View.MemoryView":1278 + /* "View.MemoryView":1282 * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False * cdef bint direct_copy = False # <<<<<<<<<<<<<< @@ -13814,7 +13865,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_direct_copy = 0; - /* "View.MemoryView":1281 + /* "View.MemoryView":1285 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< @@ -13824,7 +13875,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1282 + /* "View.MemoryView":1286 * * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< @@ -13833,7 +13884,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); - /* "View.MemoryView":1281 + /* "View.MemoryView":1285 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< @@ -13843,7 +13894,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ goto __pyx_L3; } - /* "View.MemoryView":1283 + /* "View.MemoryView":1287 * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< @@ -13853,7 +13904,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1284 + /* "View.MemoryView":1288 * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< @@ -13862,7 +13913,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); - /* "View.MemoryView":1283 + /* "View.MemoryView":1287 * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< @@ -13872,7 +13923,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ } __pyx_L3:; - /* "View.MemoryView":1286 + /* "View.MemoryView":1290 * broadcast_leading(&dst, dst_ndim, src_ndim) * * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< @@ -13888,7 +13939,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ } __pyx_v_ndim = __pyx_t_5; - /* "View.MemoryView":1288 + /* "View.MemoryView":1292 * cdef int ndim = max(src_ndim, dst_ndim) * * for i in range(ndim): # <<<<<<<<<<<<<< @@ -13900,7 +13951,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; - /* "View.MemoryView":1289 + /* "View.MemoryView":1293 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< @@ -13910,7 +13961,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1290 + /* "View.MemoryView":1294 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< @@ -13920,7 +13971,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1291 + /* "View.MemoryView":1295 * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: * broadcasting = True # <<<<<<<<<<<<<< @@ -13929,7 +13980,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_broadcasting = 1; - /* "View.MemoryView":1292 + /* "View.MemoryView":1296 * if src.shape[i] == 1: * broadcasting = True * src.strides[i] = 0 # <<<<<<<<<<<<<< @@ -13938,7 +13989,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ (__pyx_v_src.strides[__pyx_v_i]) = 0; - /* "View.MemoryView":1290 + /* "View.MemoryView":1294 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< @@ -13948,7 +13999,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ goto __pyx_L7; } - /* "View.MemoryView":1294 + /* "View.MemoryView":1298 * src.strides[i] = 0 * else: * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< @@ -13956,11 +14007,11 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ * 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(1, 1294, __pyx_L1_error) + __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(1, 1298, __pyx_L1_error) } __pyx_L7:; - /* "View.MemoryView":1289 + /* "View.MemoryView":1293 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< @@ -13969,7 +14020,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ } - /* "View.MemoryView":1296 + /* "View.MemoryView":1300 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< @@ -13979,16 +14030,16 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1297 + /* "View.MemoryView":1301 * * 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(1, 1297, __pyx_L1_error) + __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(1, 1301, __pyx_L1_error) - /* "View.MemoryView":1296 + /* "View.MemoryView":1300 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< @@ -13998,7 +14049,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ } } - /* "View.MemoryView":1299 + /* "View.MemoryView":1303 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< @@ -14008,7 +14059,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __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":1301 + /* "View.MemoryView":1305 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< @@ -14018,7 +14069,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = ((!(__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1302 + /* "View.MemoryView":1306 * * if not slice_is_contig(src, order, ndim): * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< @@ -14027,7 +14078,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); - /* "View.MemoryView":1301 + /* "View.MemoryView":1305 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< @@ -14036,17 +14087,17 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ } - /* "View.MemoryView":1304 + /* "View.MemoryView":1308 * 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(1, 1304, __pyx_L1_error) + __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(1, 1308, __pyx_L1_error) __pyx_v_tmpdata = __pyx_t_7; - /* "View.MemoryView":1305 + /* "View.MemoryView":1309 * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) * src = tmp # <<<<<<<<<<<<<< @@ -14055,7 +14106,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_src = __pyx_v_tmp; - /* "View.MemoryView":1299 + /* "View.MemoryView":1303 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< @@ -14064,7 +14115,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ } - /* "View.MemoryView":1307 + /* "View.MemoryView":1311 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< @@ -14074,7 +14125,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1310 + /* "View.MemoryView":1314 * * * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< @@ -14084,7 +14135,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'C', __pyx_v_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1311 + /* "View.MemoryView":1315 * * if slice_is_contig(src, 'C', ndim): * direct_copy = slice_is_contig(dst, 'C', ndim) # <<<<<<<<<<<<<< @@ -14093,7 +14144,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'C', __pyx_v_ndim); - /* "View.MemoryView":1310 + /* "View.MemoryView":1314 * * * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< @@ -14103,7 +14154,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ goto __pyx_L12; } - /* "View.MemoryView":1312 + /* "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): # <<<<<<<<<<<<<< @@ -14113,7 +14164,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'F', __pyx_v_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1313 + /* "View.MemoryView":1317 * direct_copy = slice_is_contig(dst, 'C', ndim) * elif slice_is_contig(src, 'F', ndim): * direct_copy = slice_is_contig(dst, 'F', ndim) # <<<<<<<<<<<<<< @@ -14122,7 +14173,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'F', __pyx_v_ndim); - /* "View.MemoryView":1312 + /* "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): # <<<<<<<<<<<<<< @@ -14132,7 +14183,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ } __pyx_L12:; - /* "View.MemoryView":1315 + /* "View.MemoryView":1319 * direct_copy = slice_is_contig(dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< @@ -14142,7 +14193,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (__pyx_v_direct_copy != 0); if (__pyx_t_2) { - /* "View.MemoryView":1317 + /* "View.MemoryView":1321 * if direct_copy: * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< @@ -14151,7 +14202,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - /* "View.MemoryView":1318 + /* "View.MemoryView":1322 * * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< @@ -14160,7 +14211,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ (void)(memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim))); - /* "View.MemoryView":1319 + /* "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) # <<<<<<<<<<<<<< @@ -14169,7 +14220,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - /* "View.MemoryView":1320 + /* "View.MemoryView":1324 * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) # <<<<<<<<<<<<<< @@ -14178,7 +14229,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ free(__pyx_v_tmpdata); - /* "View.MemoryView":1321 + /* "View.MemoryView":1325 * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) * return 0 # <<<<<<<<<<<<<< @@ -14188,7 +14239,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_r = 0; goto __pyx_L0; - /* "View.MemoryView":1315 + /* "View.MemoryView":1319 * direct_copy = slice_is_contig(dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< @@ -14197,7 +14248,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ } - /* "View.MemoryView":1307 + /* "View.MemoryView":1311 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< @@ -14206,7 +14257,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ } - /* "View.MemoryView":1323 + /* "View.MemoryView":1327 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< @@ -14220,25 +14271,25 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_8 = (__pyx_t_2 != 0); if (__pyx_t_8) { - /* "View.MemoryView":1326 + /* "View.MemoryView":1330 * * * transpose_memslice(&src) # <<<<<<<<<<<<<< * transpose_memslice(&dst) * */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1326, __pyx_L1_error) + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1330, __pyx_L1_error) - /* "View.MemoryView":1327 + /* "View.MemoryView":1331 * * 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(1, 1327, __pyx_L1_error) + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1331, __pyx_L1_error) - /* "View.MemoryView":1323 + /* "View.MemoryView":1327 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< @@ -14247,7 +14298,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ } - /* "View.MemoryView":1329 + /* "View.MemoryView":1333 * transpose_memslice(&dst) * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< @@ -14256,7 +14307,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - /* "View.MemoryView":1330 + /* "View.MemoryView":1334 * * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< @@ -14265,7 +14316,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); - /* "View.MemoryView":1331 + /* "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) # <<<<<<<<<<<<<< @@ -14274,7 +14325,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - /* "View.MemoryView":1333 + /* "View.MemoryView":1337 * refcount_copying(&dst, dtype_is_object, ndim, True) * * free(tmpdata) # <<<<<<<<<<<<<< @@ -14283,7 +14334,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ free(__pyx_v_tmpdata); - /* "View.MemoryView":1334 + /* "View.MemoryView":1338 * * free(tmpdata) * return 0 # <<<<<<<<<<<<<< @@ -14293,7 +14344,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_r = 0; goto __pyx_L0; - /* "View.MemoryView":1265 + /* "View.MemoryView":1269 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< @@ -14317,7 +14368,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ return __pyx_r; } -/* "View.MemoryView":1337 +/* "View.MemoryView":1341 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< @@ -14332,7 +14383,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic int __pyx_t_2; int __pyx_t_3; - /* "View.MemoryView":1341 + /* "View.MemoryView":1345 * int ndim_other) nogil: * cdef int i * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< @@ -14341,7 +14392,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic */ __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); - /* "View.MemoryView":1343 + /* "View.MemoryView":1347 * cdef int offset = ndim_other - ndim * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< @@ -14351,7 +14402,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; - /* "View.MemoryView":1344 + /* "View.MemoryView":1348 * * for i in range(ndim - 1, -1, -1): * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< @@ -14360,7 +14411,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic */ (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); - /* "View.MemoryView":1345 + /* "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] # <<<<<<<<<<<<<< @@ -14369,7 +14420,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic */ (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); - /* "View.MemoryView":1346 + /* "View.MemoryView":1350 * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< @@ -14379,7 +14430,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); } - /* "View.MemoryView":1348 + /* "View.MemoryView":1352 * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * * for i in range(offset): # <<<<<<<<<<<<<< @@ -14391,7 +14442,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; - /* "View.MemoryView":1349 + /* "View.MemoryView":1353 * * for i in range(offset): * mslice.shape[i] = 1 # <<<<<<<<<<<<<< @@ -14400,7 +14451,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic */ (__pyx_v_mslice->shape[__pyx_v_i]) = 1; - /* "View.MemoryView":1350 + /* "View.MemoryView":1354 * for i in range(offset): * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< @@ -14409,7 +14460,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic */ (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); - /* "View.MemoryView":1351 + /* "View.MemoryView":1355 * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< @@ -14419,7 +14470,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; } - /* "View.MemoryView":1337 + /* "View.MemoryView":1341 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< @@ -14430,7 +14481,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic /* function exit code */ } -/* "View.MemoryView":1359 +/* "View.MemoryView":1363 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< @@ -14441,7 +14492,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslic 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":1363 + /* "View.MemoryView":1367 * * * if dtype_is_object: # <<<<<<<<<<<<<< @@ -14451,7 +14502,7 @@ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, i __pyx_t_1 = (__pyx_v_dtype_is_object != 0); if (__pyx_t_1) { - /* "View.MemoryView":1364 + /* "View.MemoryView":1368 * * if dtype_is_object: * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< @@ -14460,7 +14511,7 @@ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, i */ __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":1363 + /* "View.MemoryView":1367 * * * if dtype_is_object: # <<<<<<<<<<<<<< @@ -14469,7 +14520,7 @@ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, i */ } - /* "View.MemoryView":1359 + /* "View.MemoryView":1363 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< @@ -14480,7 +14531,7 @@ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, i /* function exit code */ } -/* "View.MemoryView":1368 +/* "View.MemoryView":1372 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -14495,7 +14546,7 @@ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_da #endif __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); - /* "View.MemoryView":1371 + /* "View.MemoryView":1375 * Py_ssize_t *strides, int ndim, * bint inc) with gil: * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< @@ -14504,7 +14555,7 @@ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_da */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); - /* "View.MemoryView":1368 + /* "View.MemoryView":1372 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -14519,7 +14570,7 @@ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_da #endif } -/* "View.MemoryView":1374 +/* "View.MemoryView":1378 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -14536,7 +14587,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss int __pyx_t_4; __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); - /* "View.MemoryView":1378 + /* "View.MemoryView":1382 * cdef Py_ssize_t i * * for i in range(shape[0]): # <<<<<<<<<<<<<< @@ -14548,7 +14599,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; - /* "View.MemoryView":1379 + /* "View.MemoryView":1383 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< @@ -14558,7 +14609,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss __pyx_t_4 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_4) { - /* "View.MemoryView":1380 + /* "View.MemoryView":1384 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< @@ -14568,7 +14619,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss __pyx_t_4 = (__pyx_v_inc != 0); if (__pyx_t_4) { - /* "View.MemoryView":1381 + /* "View.MemoryView":1385 * if ndim == 1: * if inc: * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< @@ -14577,7 +14628,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss */ Py_INCREF((((PyObject **)__pyx_v_data)[0])); - /* "View.MemoryView":1380 + /* "View.MemoryView":1384 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< @@ -14587,7 +14638,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss goto __pyx_L6; } - /* "View.MemoryView":1383 + /* "View.MemoryView":1387 * Py_INCREF(( data)[0]) * else: * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< @@ -14599,7 +14650,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss } __pyx_L6:; - /* "View.MemoryView":1379 + /* "View.MemoryView":1383 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< @@ -14609,7 +14660,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss goto __pyx_L5; } - /* "View.MemoryView":1385 + /* "View.MemoryView":1389 * Py_DECREF(( data)[0]) * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< @@ -14618,7 +14669,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss */ /*else*/ { - /* "View.MemoryView":1386 + /* "View.MemoryView":1390 * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, * ndim - 1, inc) # <<<<<<<<<<<<<< @@ -14629,7 +14680,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss } __pyx_L5:; - /* "View.MemoryView":1388 + /* "View.MemoryView":1392 * ndim - 1, inc) * * data += strides[0] # <<<<<<<<<<<<<< @@ -14639,7 +14690,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } - /* "View.MemoryView":1374 + /* "View.MemoryView":1378 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -14651,7 +14702,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss __Pyx_RefNannyFinishContext(); } -/* "View.MemoryView":1394 +/* "View.MemoryView":1398 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< @@ -14661,7 +14712,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss 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":1397 + /* "View.MemoryView":1401 * size_t itemsize, void *item, * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< @@ -14670,7 +14721,7 @@ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - /* "View.MemoryView":1398 + /* "View.MemoryView":1402 * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< @@ -14679,7 +14730,7 @@ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst */ __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":1400 + /* "View.MemoryView":1404 * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, * itemsize, item) * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< @@ -14688,7 +14739,7 @@ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - /* "View.MemoryView":1394 + /* "View.MemoryView":1398 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< @@ -14699,7 +14750,7 @@ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst /* function exit code */ } -/* "View.MemoryView":1404 +/* "View.MemoryView":1408 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -14716,7 +14767,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; - /* "View.MemoryView":1408 + /* "View.MemoryView":1412 * size_t itemsize, void *item) nogil: * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< @@ -14725,7 +14776,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ __pyx_v_stride = (__pyx_v_strides[0]); - /* "View.MemoryView":1409 + /* "View.MemoryView":1413 * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< @@ -14734,7 +14785,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ __pyx_v_extent = (__pyx_v_shape[0]); - /* "View.MemoryView":1411 + /* "View.MemoryView":1415 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< @@ -14744,7 +14795,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1412 + /* "View.MemoryView":1416 * * if ndim == 1: * for i in range(extent): # <<<<<<<<<<<<<< @@ -14756,7 +14807,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; - /* "View.MemoryView":1413 + /* "View.MemoryView":1417 * if ndim == 1: * for i in range(extent): * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< @@ -14765,7 +14816,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ (void)(memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize)); - /* "View.MemoryView":1414 + /* "View.MemoryView":1418 * for i in range(extent): * memcpy(data, item, itemsize) * data += stride # <<<<<<<<<<<<<< @@ -14775,7 +14826,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t __pyx_v_data = (__pyx_v_data + __pyx_v_stride); } - /* "View.MemoryView":1411 + /* "View.MemoryView":1415 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< @@ -14785,7 +14836,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t goto __pyx_L3; } - /* "View.MemoryView":1416 + /* "View.MemoryView":1420 * data += stride * else: * for i in range(extent): # <<<<<<<<<<<<<< @@ -14798,7 +14849,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; - /* "View.MemoryView":1417 + /* "View.MemoryView":1421 * else: * for i in range(extent): * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< @@ -14807,7 +14858,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ __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":1419 + /* "View.MemoryView":1423 * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) * data += stride # <<<<<<<<<<<<<< @@ -14819,7 +14870,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t } __pyx_L3:; - /* "View.MemoryView":1404 + /* "View.MemoryView":1408 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -15394,6 +15445,9 @@ static PyTypeObject __pyx_type___pyx_array = { #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif + #if PY_VERSION_HEX >= 0x030800b1 + 0, /*tp_vectorcall*/ + #endif }; static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { @@ -15502,6 +15556,9 @@ static PyTypeObject __pyx_type___pyx_MemviewEnum = { #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif + #if PY_VERSION_HEX >= 0x030800b1 + 0, /*tp_vectorcall*/ + #endif }; static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; @@ -15752,6 +15809,9 @@ static PyTypeObject __pyx_type___pyx_memoryview = { #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif + #if PY_VERSION_HEX >= 0x030800b1 + 0, /*tp_vectorcall*/ + #endif }; static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; @@ -15887,6 +15947,9 @@ static PyTypeObject __pyx_type___pyx_memoryviewslice = { #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif + #if PY_VERSION_HEX >= 0x030800b1 + 0, /*tp_vectorcall*/ + #endif }; static PyMethodDef __pyx_methods[] = { @@ -16036,9 +16099,9 @@ static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 148, __pyx_L1_error) __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(1, 151, __pyx_L1_error) __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) - __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(1, 400, __pyx_L1_error) - __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(1, 609, __pyx_L1_error) - __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(1, 828, __pyx_L1_error) + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(1, 404, __pyx_L1_error) + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(1, 613, __pyx_L1_error) + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(1, 832, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; @@ -16122,58 +16185,58 @@ static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); - /* "View.MemoryView":414 + /* "View.MemoryView":418 * 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__8 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 414, __pyx_L1_error) + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 418, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); - /* "View.MemoryView":491 + /* "View.MemoryView":495 * 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__9 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 491, __pyx_L1_error) + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 495, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); - /* "View.MemoryView":516 + /* "View.MemoryView":520 * 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__10 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 516, __pyx_L1_error) + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 520, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); - /* "View.MemoryView":566 + /* "View.MemoryView":570 * 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__11 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 566, __pyx_L1_error) + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 570, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__11); __Pyx_GIVEREF(__pyx_tuple__11); - /* "View.MemoryView":573 + /* "View.MemoryView":577 * 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__12 = PyTuple_New(1); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 573, __pyx_L1_error) + __pyx_tuple__12 = PyTuple_New(1); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 577, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__12); __Pyx_INCREF(__pyx_int_neg_1); __Pyx_GIVEREF(__pyx_int_neg_1); @@ -16199,25 +16262,25 @@ static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_GOTREF(__pyx_tuple__14); __Pyx_GIVEREF(__pyx_tuple__14); - /* "View.MemoryView":678 + /* "View.MemoryView":682 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ - __pyx_slice__15 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__15)) __PYX_ERR(1, 678, __pyx_L1_error) + __pyx_slice__15 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__15)) __PYX_ERR(1, 682, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__15); __Pyx_GIVEREF(__pyx_slice__15); - /* "View.MemoryView":699 + /* "View.MemoryView":703 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ - __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(1, 699, __pyx_L1_error) + __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(1, 703, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__16); __Pyx_GIVEREF(__pyx_tuple__16); @@ -16366,12 +16429,16 @@ static int __Pyx_modinit_type_init_code(void) { __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(1, 105, __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(1, 105, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) __pyx_array_type = &__pyx_type___pyx_array; if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __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; } @@ -16386,7 +16453,9 @@ static int __Pyx_modinit_type_init_code(void) { __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(1, 330, __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; } @@ -16398,13 +16467,15 @@ static int __Pyx_modinit_type_init_code(void) { __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(1, 961, __pyx_L1_error) + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __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(1, 961, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 961, __pyx_L1_error) + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; __Pyx_RefNannyFinishContext(); return 0; @@ -16598,10 +16669,9 @@ if (!__Pyx_RefNanny) { __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) - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); - #endif + __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) @@ -16620,9 +16690,9 @@ if (!__Pyx_RefNanny) { } #endif /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_InitCachedBuiltins() < 0) goto __pyx_L1_error; /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_InitCachedConstants() < 0) goto __pyx_L1_error; /*--- Global type/function init code ---*/ (void)__Pyx_modinit_global_init_code(); (void)__Pyx_modinit_variable_export_code(); @@ -16755,29 +16825,29 @@ if (!__Pyx_RefNanny) { __pyx_t_2[7] = PyThread_allocate_lock(); memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_2, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); - /* "View.MemoryView":545 + /* "View.MemoryView":549 * info.obj = self * * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 545, __pyx_L1_error) + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 549, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 545, __pyx_L1_error) + if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 549, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryview_type); - /* "View.MemoryView":991 + /* "View.MemoryView":995 * return self.from_object * * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 991, __pyx_L1_error) + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 995, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 991, __pyx_L1_error) + if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 995, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryviewslice_type); @@ -17027,11 +17097,7 @@ __Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, int i, retval=-1; Py_buffer *buf = &memview->view; __Pyx_RefNannySetupContext("init_memviewslice", 0); - if (!buf) { - PyErr_SetString(PyExc_ValueError, - "buf is NULL."); - goto fail; - } else if (memviewslice->memview || memviewslice->data) { + if (memviewslice->memview || memviewslice->data) { PyErr_SetString(PyExc_ValueError, "memviewslice is already initialized!"); goto fail; @@ -17432,7 +17498,7 @@ static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args return result; } #if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs) { +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); @@ -17503,12 +17569,12 @@ static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, } #if PY_MAJOR_VERSION >= 3 result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, nargs, + args, (int)nargs, k, (int)nk, d, (int)nd, kwdefs, closure); #else result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, nargs, + args, (int)nargs, k, (int)nk, d, (int)nd, closure); #endif @@ -17968,6 +18034,32 @@ static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject return (likely(r)) ? r : __Pyx_GetAttr3Default(d); } +/* 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) @@ -19082,7 +19174,7 @@ static int __Pyx_BufFmt_ParseNumber(const char** ts) { return -1; } else { count = *t++ - '0'; - while (*t >= '0' && *t < '9') { + while (*t >= '0' && *t <= '9') { count *= 10; count += *t++ - '0'; } @@ -19656,7 +19748,7 @@ __pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec } } if (spec & __Pyx_MEMVIEW_PTR) { - if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { + if (!buf->suboffsets || (buf->suboffsets[dim] < 0)) { PyErr_Format(PyExc_ValueError, "Buffer is not indirectly accessible " "in dimension %d.", dim); diff --git a/openmmtools/multistate/multistateanalyzer.py b/openmmtools/multistate/multistateanalyzer.py index fc484bd58..f6ea8ac8f 100644 --- a/openmmtools/multistate/multistateanalyzer.py +++ b/openmmtools/multistate/multistateanalyzer.py @@ -1170,9 +1170,9 @@ class MultiStateSamplerAnalyzer(PhaseAnalyzer): def __init__(self, *args, unbias_restraint=True, restraint_energy_cutoff='auto', restraint_distance_cutoff='auto', **kwargs): + # Warn that API is experimental - import warnings - warnings.warn('Warning: The openmmtools.multistate API is experimental and may change in future releases') + logger.warn('Warning: The openmmtools.multistate API is experimental and may change in future releases') # super() calls clear() that initialize the cached variables. super().__init__(*args, **kwargs) diff --git a/openmmtools/multistate/multistatereporter.py b/openmmtools/multistate/multistatereporter.py index 44aa08705..fb6dc8423 100644 --- a/openmmtools/multistate/multistatereporter.py +++ b/openmmtools/multistate/multistatereporter.py @@ -34,8 +34,8 @@ import time import uuid import yaml -import logging import warnings +import logging import collections import numpy as np @@ -112,9 +112,8 @@ def __init__(self, storage, open_mode=None, analysis_particle_indices=()): # Warn that API is experimental - import warnings - warnings.warn('Warning: The openmmtools.multistate API is experimental and may change in future releases') - + logger.warn('Warning: The openmmtools.multistate API is experimental and may change in future releases') + # Handle checkpointing if type(checkpoint_interval) != int: raise ValueError("checkpoint_interval must be an integer!") diff --git a/openmmtools/multistate/multistatesampler.py b/openmmtools/multistate/multistatesampler.py index c333ac0b6..41fb1859e 100644 --- a/openmmtools/multistate/multistatesampler.py +++ b/openmmtools/multistate/multistatesampler.py @@ -141,8 +141,7 @@ def __init__(self, mcmc_moves=None, number_of_iterations=1, locality=None): # Warn that API is experimental - import warnings - warnings.warn('Warning: The openmmtools.multistate API is experimental and may change in future releases') + logger.warn('Warning: The openmmtools.multistate API is experimental and may change in future releases') # These will be set on initialization. See function # create() for explanation of single variables. From f25f6f6f0f83b59bb7734fb12421844e366c1b97 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Sat, 26 Oct 2019 16:17:29 -0700 Subject: [PATCH 123/152] Rework harmonic oscillator free energy tests with/without unsampled states to run on travis --- openmmtools/tests/test_sampling.py | 405 ++++++++++------------------- 1 file changed, 141 insertions(+), 264 deletions(-) diff --git a/openmmtools/tests/test_sampling.py b/openmmtools/tests/test_sampling.py index d13d0cfb2..ff3eb54c8 100644 --- a/openmmtools/tests/test_sampling.py +++ b/openmmtools/tests/test_sampling.py @@ -32,8 +32,12 @@ from simtk import openmm, unit import mpiplus -from openmmtools.multistate import MultiStateReporter, MultiStateSampler, ReplicaExchangeSampler, ParallelTemperingSampler, SAMSSampler -from openmmtools.multistate import ReplicaExchangeAnalyzer, SAMSAnalyzer +from openmmtools.multistate import MultiStateReporter +from openmmtools.multistate import MultiStateSampler, MultiStateSamplerAnalyzer +from openmmtools.multistate import ReplicaExchangeSampler, ReplicaExchangeAnalyzer +from openmmtools.multistate import ParallelTemperingSampler, ParallelTemperingAnalyzer +from openmmtools.multistate import SAMSSampler, SAMSAnalyzer + from openmmtools.multistate.multistatereporter import _DictYamlLoader # quiet down some citation spam @@ -64,289 +68,162 @@ def check_thermodynamic_states_equality(original_states, restored_states): assert original_state.lambda_sterics == restored_state.lambda_sterics assert original_state.lambda_electrostatics == restored_state.lambda_electrostatics +# ============================================================================== +# Harmonic oscillator free energy test +# ============================================================================== -def compute_harmonic_oscillator_expectations(K, temperature): - """Compute mean and variance of potential and kinetic energies for a 3D harmonic oscillator. - - Notes - ----- - Numerical quadrature is used to compute the mean and standard deviation of the potential energy. - Mean and standard deviation of the kinetic energy, as well as the absolute free energy, is computed analytically. - - Parameters - ---------- - K : simtk.unit.Quantity - Spring constant. - temperature : simtk.unit.Quantity - Temperature. - - Returns - ------- - values : dict - - TODO - - Replace this with built-in analytical expectations - - """ +class TestHarmonicOscillatorsMultiStateSampler(object): + """Test multistate sampler can compute free energies of harmonic oscillator""" - values = dict() + # ------------------------------------ + # VARIABLES TO SET FOR EACH TEST CLASS + # ------------------------------------ - # Compute thermal energy and inverse temperature from specified temperature. - kB = unit.BOLTZMANN_CONSTANT_kB * unit.AVOGADRO_CONSTANT_NA - kT = kB * temperature # thermal energy - beta = 1.0 / kT # inverse temperature + N_SAMPLERS = 3 + N_STATES = 5 # number of thermodynamic states to sample; two additional unsampled states will be added + N_ITERATIONS = 500 # number of iterations + SAMPLER = MultiStateSampler + ANALYZER = MultiStateSamplerAnalyzer - # Compute standard deviation along one dimension. - sigma = 1.0 / unit.sqrt(beta * K) + @classmethod + def setup_class(cls): + # Configure the global context cache to use the Reference platform + from openmmtools import cache + platform = openmm.Platform.getPlatformByName('Reference') + cls.old_global_context_cache = cache.global_context_cache + cache.global_context_cache = cache.ContextCache(platform=platform) - # Define limits of integration along r. - r_min = 0.0 * unit.nanometers # initial value for integration - r_max = 10.0 * sigma # maximum radius to integrate to + # Set oscillators to mass of carbon atom + mass = 12.0 * unit.amu - # Compute mean and std dev of potential energy. - V = lambda r : (K/2.0) * (r*unit.nanometers)**2 / unit.kilojoules_per_mole # potential in kJ/mol, where r in nm - q = lambda r : 4.0 * math.pi * r**2 * math.exp(-beta * (K/2.0) * (r*unit.nanometers)**2) # q(r), where r in nm - (IqV2, dIqV2) = scipy.integrate.quad(lambda r : q(r) * V(r)**2, r_min / unit.nanometers, r_max / unit.nanometers) - (IqV, dIqV) = scipy.integrate.quad(lambda r : q(r) * V(r), r_min / unit.nanometers, r_max / unit.nanometers) - (Iq, dIq) = scipy.integrate.quad(lambda r : q(r), r_min / unit.nanometers, r_max / unit.nanometers) - values['potential'] = dict() - values['potential']['mean'] = (IqV / Iq) * unit.kilojoules_per_mole - values['potential']['stddev'] = (IqV2 / Iq) * unit.kilojoules_per_mole + # Translate the sampler states to be different one from each other. + n_particles = 1 + positions = unit.Quantity(np.zeros([n_particles,3]), unit.angstroms) + cls.sampler_states = [ + mmtools.states.SamplerState(positions=positions) + for sampler_index in range(cls.N_SAMPLERS)] + + # Generate list of thermodynamic states and analytical free energies + # This list includes both sampled and two unsampled states + thermodynamic_states = list() + temperature = 300 * unit.kelvin + f_i = np.zeros([cls.N_STATES+2]) # f_i[state_index] is the dimensionless free energy of state `state_index` + for state_index in range(cls.N_STATES + 2): + sigma = (1.0 + 0.2 * state_index) * unit.angstroms # compute reasonable standard deviation with good overlap + kT = kB * temperature # compute thermal energy + K = kT / sigma**2 # compute spring constant + testsystem = testsystems.HarmonicOscillator(K=K, mass=mass) + thermodynamic_state = mmtools.states.ThermodynamicState(testsystem.system, temperature) + thermodynamic_states.append(thermodynamic_state) + + # Store analytical reduced free energy + f_i[state_index] = - np.log(2 * np.pi * (sigma / unit.angstroms)**2) * (3.0/2.0) + + # delta_f_ij_analytical[i,j] = f_i_analytical[j] - f_i_analytical[i] + cls.f_i_analytical = f_i + cls.delta_f_ij_analytical = f_i - f_i[:,np.newaxis] + + # Define sampled and unsampled states. + cls.nstates = cls.N_STATES + cls.unsampled_states = [thermodynamic_states[0], thermodynamic_states[-1]] # first and last + cls.thermodynamic_states = thermodynamic_states[1:-1] # intermediate states - # Compute mean and std dev of kinetic energy. - values['kinetic'] = dict() - values['kinetic']['mean'] = (3./2.) * kT - values['kinetic']['stddev'] = math.sqrt(3./2.) * kT + @classmethod + def teardown_class(cls): + # Restore global context cache + from openmmtools import cache + cache.global_context_cache = cls.old_global_context_cache + + def run(self, include_unsampled_states=False): + # Create and configure simulation object + move = mmtools.mcmc.MCDisplacementMove(displacement_sigma=1.0*unit.angstroms) + simulation = self.SAMPLER(mcmc_moves=move, number_of_iterations=self.N_ITERATIONS) + + # Define file for temporary storage. + with mmtools.utils.temporary_directory() as tmp_dir: + storage = os.path.join(tmp_dir, 'test_storage.nc') + reporter = MultiStateReporter(storage, checkpoint_interval=self.N_ITERATIONS) + + if include_unsampled_states: + simulation.create(self.thermodynamic_states, self.sampler_states, reporter, + unsampled_thermodynamic_states=self.unsampled_states) + else: + simulation.create(self.thermodynamic_states, self.sampler_states, reporter) - # Compute dimensionless free energy. - # f = - \ln \int_{-\infty}^{+\infty} \exp[-\beta K x^2 / 2] - # = - \ln \int_{-\infty}^{+\infty} \exp[-x^2 / 2 \sigma^2] - # = - \ln [\sqrt{2 \pi} \sigma] - values['f'] = - np.log(2 * np.pi * (sigma / unit.angstroms)**2) * (3.0/2.0) + # Run simulation without debug logging + import logging + logger = logging.getLogger() + logger.setLevel(logging.CRITICAL) + simulation.run() - return values + # Create Analyzer. + analyzer = self.ANALYZER(reporter) + # TODO: Check if deviations exceed tolerance. + delta_f_ij, delta_f_ij_stderr = analyzer.get_free_energy() + nstates, _ = delta_f_ij.shape -# ============================================================================== -# TEST ANALYSIS REPLICA EXCHANGE -# ============================================================================== - -@attr('slow') # Skip on Travis-CI -def test_replica_exchange_harmonic_oscillator(verbose=False, verbose_simulation=False): - """Test harmonic oscillator free energies for replica-exchange.""" - # Define mass of carbon atom. - mass = 12.0 * unit.amu - - sampler_states = list() - thermodynamic_states = list() - analytical_results = list() - f_i_analytical = list() # Dimensionless free energies. - u_i_analytical = list() # Reduced potentials. - - # Define thermodynamic states. - Ks = [500.00, 400.0, 300.0] * unit.kilocalories_per_mole / unit.angstroms**2 # Spring constants. - temperatures = [300.0, 350.0, 400.0] * unit.kelvin # Temperatures. - for (K, temperature) in zip(Ks, temperatures): - # Create harmonic oscillator system. - testsystem = testsystems.HarmonicOscillator(K=K, mass=mass, mm=openmm) - - # Create thermodynamic state and save positions. - system, positions = [testsystem.system, testsystem.positions] - sampler_states.append(mmtools.states.SamplerState(positions)) - thermodynamic_states.append(mmtools.states.ThermodynamicState(system=system, temperature=temperature)) - - # Store analytical results. - results = compute_harmonic_oscillator_expectations(K, temperature) - analytical_results.append(results) - f_i_analytical.append(results['f']) - reduced_potential = results['potential']['mean'] / (kB * temperature) - u_i_analytical.append(reduced_potential) - - # Compute analytical Delta_f_ij - nstates = len(f_i_analytical) - f_i_analytical = np.array(f_i_analytical) - u_i_analytical = np.array(u_i_analytical) - s_i_analytical = u_i_analytical - f_i_analytical - Delta_f_ij_analytical = np.zeros([nstates, nstates], np.float64) - Delta_u_ij_analytical = np.zeros([nstates, nstates], np.float64) - Delta_s_ij_analytical = np.zeros([nstates, nstates], np.float64) - for i in range(nstates): - for j in range(nstates): - Delta_f_ij_analytical[i, j] = f_i_analytical[j] - f_i_analytical[i] - Delta_u_ij_analytical[i, j] = u_i_analytical[j] - u_i_analytical[i] - Delta_s_ij_analytical[i, j] = s_i_analytical[j] - s_i_analytical[i] - - # Create and configure simulation object. - move = mmtools.mcmc.LangevinDynamicsMove(timestep=2.0*unit.femtoseconds, - collision_rate=20.0/unit.picosecond, - n_steps=500, reassign_velocities=True) - simulation = ReplicaExchangeSampler(mcmc_moves=move, number_of_iterations=400) - - # Define file for temporary storage. - with mmtools.utils.temporary_directory() as tmp_dir: - storage = os.path.join(tmp_dir, 'test_storage.nc') - reporter = MultiStateReporter(storage, checkpoint_interval=1) - simulation.create(thermodynamic_states, sampler_states, reporter) - - # Run simulation we keep the debug info off during the simulation - # to not clog the output, and reactivate it for analysis. - simulation.run() - - # Create Analyzer. - analyzer = ReplicaExchangeAnalyzer(reporter) - - # TODO: Check if deviations exceed tolerance. - Delta_f_ij, dDelta_f_ij = analyzer.get_free_energy() - error = np.abs(Delta_f_ij - Delta_f_ij_analytical) - indices = np.where(dDelta_f_ij > 0.0) - nsigma = np.zeros([nstates,nstates], np.float32) - nsigma[indices] = error[indices] / dDelta_f_ij[indices] - MAX_SIGMA = 6.0 # maximum allowed number of standard errors - if np.any(nsigma > MAX_SIGMA): - print("Delta_f_ij") - print(Delta_f_ij) - print("Delta_f_ij_analytical") - print(Delta_f_ij_analytical) - print("error") - print(error) - print("stderr") - print(dDelta_f_ij) - print("nsigma") - print(nsigma) - raise Exception("Dimensionless free energy difference exceeds MAX_SIGMA of %.1f" % MAX_SIGMA) - - Delta_u_ij, dDelta_u_ij = analyzer.get_enthalpy() - error = Delta_u_ij - Delta_u_ij_analytical - nsigma = np.zeros([nstates,nstates], np.float32) - nsigma[indices] = error[indices] / dDelta_f_ij[indices] - if np.any(nsigma > MAX_SIGMA): - print("Delta_u_ij") - print(Delta_u_ij) - print("Delta_u_ij_analytical") - print(Delta_u_ij_analytical) - print("error") - print(error) - print("nsigma") - print(nsigma) - raise Exception("Dimensionless potential energy difference exceeds MAX_SIGMA of %.1f" % MAX_SIGMA) + if include_unsampled_states: + nstates_expected = self.N_STATES+2 + delta_f_ij_analytical = self.delta_f_ij_analytical + else: + nstates_expected = self.N_STATES + delta_f_ij_analytical = self.delta_f_ij_analytical[1:-1,1:-1] + + assert nstates == nstates_expected, \ + f'analyzer.get_free_energy() returned {delta_f_ij.shape} but expected {nstates_expected,nstates_expected}' + + error = np.abs(delta_f_ij - delta_f_ij_analytical) + indices = np.where(delta_f_ij_stderr > 0.0) + nsigma = np.zeros([nstates,nstates], np.float32) + nsigma[indices] = error[indices] / delta_f_ij_stderr[indices] + MAX_SIGMA = 6.0 # maximum allowed number of standard errors + if np.any(nsigma > MAX_SIGMA): + np.set_printoptions(precision=3) + print("delta_f_ij") + print(delta_f_ij) + print("delta_f_ij_analytical") + print(delta_f_ij_analytical) + print("error") + print(error) + print("stderr") + print(delta_f_ij_stderr) + print("nsigma") + print(nsigma) + raise Exception("Dimensionless free energy difference exceeds MAX_SIGMA of %.1f" % MAX_SIGMA) # Clean up. del simulation - if verbose: - print("PASSED.") + def test_with_unsampled_states(self): + self.run(include_unsampled_states=True) + def test_without_unsampled_states(self): + self.run(include_unsampled_states=False) -# ============================================================================== -# TEST ANALYSIS SAMS -# ============================================================================== +class TestHarmonicOscillatorsReplicaExchangeSampler(TestHarmonicOscillatorsMultiStateSampler): + """Test replica-exchange sampler can compute free energies of harmonic oscillator""" -@attr('slow') # Skip on Travis-CI -def test_sams_harmonic_oscillator(verbose=False, verbose_simulation=False): - """Harmonic oscillator free energies for SAMS.""" - # Define mass of carbon atom. - mass = 12.0 * unit.amu - - sampler_states = list() - thermodynamic_states = list() - analytical_results = list() - f_i_analytical = list() # Dimensionless free energies. - u_i_analytical = list() # Reduced potentials. - - # Define thermodynamic states. - Ks = [500.00, 400.0, 300.0] * unit.kilocalories_per_mole / unit.angstroms**2 # Spring constants. - temperatures = [300.0, 350.0, 400.0] * unit.kelvin # Temperatures. - for (K, temperature) in zip(Ks, temperatures): - # Create harmonic oscillator system. - testsystem = testsystems.HarmonicOscillator(K=K, mass=mass, mm=openmm) - - # Create thermodynamic state and save positions. - system, positions = [testsystem.system, testsystem.positions] - sampler_states.append(mmtools.states.SamplerState(positions)) - thermodynamic_states.append(mmtools.states.ThermodynamicState(system=system, temperature=temperature)) - - # Store analytical results. - results = compute_harmonic_oscillator_expectations(K, temperature) - analytical_results.append(results) - f_i_analytical.append(results['f']) - reduced_potential = results['potential']['mean'] / (kB * temperature) - u_i_analytical.append(reduced_potential) - - # Compute analytical Delta_f_ij - nstates = len(f_i_analytical) - f_i_analytical = np.array(f_i_analytical) - u_i_analytical = np.array(u_i_analytical) - s_i_analytical = u_i_analytical - f_i_analytical - Delta_f_ij_analytical = np.zeros([nstates, nstates], np.float64) - Delta_u_ij_analytical = np.zeros([nstates, nstates], np.float64) - Delta_s_ij_analytical = np.zeros([nstates, nstates], np.float64) - for i in range(nstates): - for j in range(nstates): - Delta_f_ij_analytical[i, j] = f_i_analytical[j] - f_i_analytical[i] - Delta_u_ij_analytical[i, j] = u_i_analytical[j] - u_i_analytical[i] - Delta_s_ij_analytical[i, j] = s_i_analytical[j] - s_i_analytical[i] - - # Create and configure simulation object. - move = mmtools.mcmc.LangevinDynamicsMove(timestep=2.0*unit.femtoseconds, - collision_rate=20.0/unit.picosecond, - n_steps=500, reassign_velocities=True) - simulation = SAMSSampler(mcmc_moves=move, number_of_iterations=200) - - # Define file for temporary storage. - with mmtools.utils.temporary_directory() as tmp_dir: - storage = os.path.join(tmp_dir, 'test_storage.nc') - reporter = MultiStateReporter(storage, checkpoint_interval=1) - simulation.create(thermodynamic_states, sampler_states, reporter) - - # Run simulation we keep the debug info off during the simulation - # to not clog the output, and reactivate it for analysis. - simulation.run() - - # Create Analyzer. - analyzer = SAMSAnalyzer(reporter) - - # TODO: Check if deviations exceed tolerance. - Delta_f_ij, dDelta_f_ij = analyzer.get_free_energy() - error = np.abs(Delta_f_ij - Delta_f_ij_analytical) - indices = np.where(dDelta_f_ij > 0.0) - nsigma = np.zeros([nstates,nstates], np.float32) - nsigma[indices] = error[indices] / dDelta_f_ij[indices] - MAX_SIGMA = 6.0 # maximum allowed number of standard errors - if np.any(nsigma > MAX_SIGMA): - print("Delta_f_ij") - print(Delta_f_ij) - print("Delta_f_ij_analytical") - print(Delta_f_ij_analytical) - print("error") - print(error) - print("stderr") - print(dDelta_f_ij) - print("nsigma") - print(nsigma) - raise Exception("Dimensionless free energy difference exceeds MAX_SIGMA of %.1f" % MAX_SIGMA) - - Delta_u_ij, dDelta_u_ij = analyzer.get_enthalpy() - error = Delta_u_ij - Delta_u_ij_analytical - nsigma = np.zeros([nstates,nstates], np.float32) - nsigma[indices] = error[indices] / dDelta_f_ij[indices] - if np.any(nsigma > MAX_SIGMA): - print("Delta_u_ij") - print(Delta_u_ij) - print("Delta_u_ij_analytical") - print(Delta_u_ij_analytical) - print("error") - print(error) - print("nsigma") - print(nsigma) - raise Exception("Dimensionless potential energy difference exceeds MAX_SIGMA of %.1f" % MAX_SIGMA) + # ------------------------------------ + # VARIABLES TO SET FOR EACH TEST CLASS + # ------------------------------------ - # Clean up. - del simulation + N_SAMPLERS = 5 + N_STATES = 5 + SAMPLER = ReplicaExchangeSampler + ANALYZER = ReplicaExchangeAnalyzer - if verbose: - print("PASSED.") +class TestHarmonicOscillatorsSAMSSampler(TestHarmonicOscillatorsMultiStateSampler): + """Test SAMS sampler can compute free energies of harmonic oscillator""" + # ------------------------------------ + # VARIABLES TO SET FOR EACH TEST CLASS + # ------------------------------------ + + N_SAMPLERS = 1 + N_STATES = 5 + SAMPLER = SAMSSampler + ANALYZER = SAMSAnalyzer # ============================================================================== # TEST REPORTER From 6ad1427e761ea5846bbde5de058ce2fcd3567b42 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Sat, 26 Oct 2019 16:22:51 -0700 Subject: [PATCH 124/152] Minor cleanup of comments --- openmmtools/tests/test_sampling.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/openmmtools/tests/test_sampling.py b/openmmtools/tests/test_sampling.py index ff3eb54c8..b690084a2 100644 --- a/openmmtools/tests/test_sampling.py +++ b/openmmtools/tests/test_sampling.py @@ -159,16 +159,16 @@ def run(self, include_unsampled_states=False): # Create Analyzer. analyzer = self.ANALYZER(reporter) - # TODO: Check if deviations exceed tolerance. + # Check if free energies have the right shape and deviations exceed tolerance delta_f_ij, delta_f_ij_stderr = analyzer.get_free_energy() nstates, _ = delta_f_ij.shape if include_unsampled_states: - nstates_expected = self.N_STATES+2 - delta_f_ij_analytical = self.delta_f_ij_analytical + nstates_expected = self.N_STATES+2 # We expect N_STATES plus two additional states + delta_f_ij_analytical = self.delta_f_ij_analytical # Use the whole matrix else: - nstates_expected = self.N_STATES - delta_f_ij_analytical = self.delta_f_ij_analytical[1:-1,1:-1] + nstates_expected = self.N_STATES # We expect only N_STATES + delta_f_ij_analytical = self.delta_f_ij_analytical[1:-1,1:-1] # Use only the intermediate, sampled states assert nstates == nstates_expected, \ f'analyzer.get_free_energy() returned {delta_f_ij.shape} but expected {nstates_expected,nstates_expected}' From 19346937de9fe5a36a4eddcdca255591469b3c70 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Sat, 26 Oct 2019 16:26:14 -0700 Subject: [PATCH 125/152] Update changelog --- docs/releasehistory.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index c580c78ec..96e204d78 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -8,6 +8,10 @@ New features ------------ - Added support in ``AbsoluteAlchemicalFactory`` for handling multiple independent alchemical regions (`#438 `_). +Bugfixes +-------- +- The multistate samplers now issue experimental API warnings via `logger.warn()` rather than `warnings.warn()` (#446) + 0.18.3 - Storage enhancements and bugfixes ========================================== From f89d31842709a63cb8f675cbafb7d3c40c113084 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Mon, 28 Oct 2019 12:41:37 -0700 Subject: [PATCH 126/152] Fix sphinx formatting in changelog --- docs/releasehistory.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 96e204d78..e145ed28a 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -10,7 +10,7 @@ New features Bugfixes -------- -- The multistate samplers now issue experimental API warnings via `logger.warn()` rather than `warnings.warn()` (#446) +- The multistate samplers now issue experimental API warnings via ``logger.warn()`` rather than ```warnings.warn()`` (`#446 `_) 0.18.3 - Storage enhancements and bugfixes ========================================== From 46308b03aa42a816bf229215a39cac141a140b31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Kr=C3=A4mer?= Date: Tue, 29 Oct 2019 07:01:32 -0400 Subject: [PATCH 127/152] attempted fix of surface tension test --- openmmtools/tests/test_states.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index f230aa93c..937fe2001 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -59,7 +59,8 @@ def setup_class(cls): """Create the test systems used in the test suite.""" cls.std_pressure = ThermodynamicState._STANDARD_PRESSURE cls.std_temperature = ThermodynamicState._STANDARD_TEMPERATURE - cls.std_surface_tension = 100.0 * unit.bar * unit.nanometer + cls.std_surface_tension = ThermodynamicState._STANDARD_SURFACE_TENSION + cls.modified_surface_tension = 100.0 * unit.bar * unit.nanometer alanine_explicit = testsystems.AlanineDipeptideExplicit() cls.alanine_positions = alanine_explicit.positions @@ -106,7 +107,7 @@ def setup_class(cls): cls.membrane_barostat_alanine_gamma_nonzero = copy.deepcopy(cls.alanine_explicit) # working around a bug in the unit conversion https://github.com/openmm/openmm/issues/2406 cls.membrane_barostat_gamma_nonzero = openmm.MonteCarloMembraneBarostat( - cls.std_pressure, cls.std_surface_tension.value_in_unit(unit.bar*unit.nanometer), cls.std_temperature, + cls.std_pressure, cls.modified_surface_tension.value_in_unit(unit.bar*unit.nanometer), cls.std_temperature, openmm.MonteCarloMembraneBarostat.XYIsotropic, openmm.MonteCarloMembraneBarostat.ZFree ) cls.membrane_barostat_alanine_gamma_nonzero.addForce(cls.membrane_barostat_gamma_nonzero) @@ -396,15 +397,15 @@ def test_surface_tension(self): # test setting and getting surface tension state = ThermodynamicState(self.membrane_barostat_alanine_gamma_zero, self.std_temperature) - assert utils.is_quantity_close(state.surface_tension, 0.0 * unit.bar * unit.nanometer) - state.surface_tension = self.std_surface_tension - assert utils.is_quantity_close(state.surface_tension, self.std_surface_tension) + assert utils.is_quantity_close(state.surface_tension, 0.0 * unit.bar * unit.nanometer, rtol=0.0, atol=1e-10) + state.surface_tension = self.modified_surface_tension + assert utils.is_quantity_close(state.surface_tension, self.modified_surface_tension) state.surface_tension = 0.0 * unit.bar * unit.nanometer - assert utils.is_quantity_close(state.surface_tension, 0.0 * unit.bar * unit.nanometer) + assert utils.is_quantity_close(state.surface_tension, 0.0 * unit.bar * unit.nanometer, rtol=0.0, atol=1e-10) # test initial surface tension of nonzero-gamma barostat state = ThermodynamicState(self.membrane_barostat_alanine_gamma_nonzero, self.std_temperature) - assert utils.is_quantity_close(state.surface_tension, self.std_surface_tension) + assert utils.is_quantity_close(state.surface_tension, self.modified_surface_tension) def test_property_volume(self): """Check that volume is computed correctly.""" @@ -807,10 +808,10 @@ def test_method_apply_to_context(self): gamma_context = openmm.Context(self.membrane_barostat_alanine_gamma_zero, openmm.VerletIntegrator(0.001)) state3.apply_to_context(gamma_context) assert gamma_context.getParameter(self.membrane_barostat_gamma_nonzero.SurfaceTension()) == 0.0 - state3.surface_tension = self.std_surface_tension + state3.surface_tension = self.modified_surface_tension state3.apply_to_context(gamma_context) assert (gamma_context.getParameter(self.membrane_barostat_gamma_nonzero.SurfaceTension()) - == self.std_surface_tension.value_in_unit(unit.nanometer*unit.bar)) + == self.modified_surface_tension.value_in_unit(unit.nanometer*unit.bar)) state3.surface_tension = 0.0 * unit.nanometer * unit.bar @@ -870,7 +871,7 @@ def test_method_reduced_potential(self): reduced_potential = state.reduced_potential(sampler_state) pressure_volume_work = (self.std_pressure * sampler_state.volume * unit.AVOGADRO_CONSTANT_NA) - surface_work = (self.std_surface_tension * sampler_state.area_xy * + surface_work = (self.modified_surface_tension * sampler_state.area_xy * unit.AVOGADRO_CONSTANT_NA) potential_energy = (reduced_potential / beta - pressure_volume_work + surface_work) / kj_mol From 383a22aaf613e8a6517bc16adde9d4561021653b Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Wed, 6 Nov 2019 00:48:12 +0100 Subject: [PATCH 128/152] Add test reduced_potential_at_states --- openmmtools/tests/test_states.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/openmmtools/tests/test_states.py b/openmmtools/tests/test_states.py index 008a94a7d..8b1004528 100644 --- a/openmmtools/tests/test_states.py +++ b/openmmtools/tests/test_states.py @@ -762,8 +762,17 @@ def test_method_reduced_potential_at_states(self): # Compute with multi-state method. obtained_energies.extend(ThermodynamicState.reduced_potential_at_states(context, compatible_group)) + expected_energies = np.array(expected_energies) assert np.allclose(np.array(expected_energies), np.array(obtained_energies)) + # Check that the utility function does the same. + sampler_state = SamplerState(positions=self.alanine_positions) + thermodynamic_states = [thermodynamic_states[i] for i in [0, 2]] + from openmmtools.cache import ContextCache + obtained_energies = reduced_potential_at_states( + sampler_state, thermodynamic_states, ContextCache()) + assert np.allclose(expected_energies[:2], obtained_energies) + # ============================================================================= # TEST SAMPLER STATE From e5a8f8f132bb79bd83ca7f9dfea85a5a909b983f Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 8 Nov 2019 11:11:28 +0100 Subject: [PATCH 129/152] Fix SEM in test --- openmmtools/tests/test_sampling.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/tests/test_sampling.py b/openmmtools/tests/test_sampling.py index 6cb613035..6a3b8486f 100644 --- a/openmmtools/tests/test_sampling.py +++ b/openmmtools/tests/test_sampling.py @@ -1566,7 +1566,7 @@ def test_uniform_mixing(self): # Find the average number of states visited by # the replicas assigned to this MPI process. mpi_avg_thermo_state_counts[mpi_idx] = np.mean(replica_thermo_state_counts[replica_indices]) - mpi_sem_thermo_state_counts[mpi_idx] = np.std(replica_thermo_state_counts[replica_indices], ddof=1) / len(replica_indices) + mpi_sem_thermo_state_counts[mpi_idx] = np.std(replica_thermo_state_counts[replica_indices], ddof=1) / np.sqrt(len(replica_indices)) # These should be roughly equal. print('MPI process mean number of thermo states visited:') From 7980ea9bdc8fee57fbd0f203ea448fd544b6650b Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 8 Nov 2019 11:13:07 +0100 Subject: [PATCH 130/152] Better comment --- openmmtools/multistate/multistatesampler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/multistate/multistatesampler.py b/openmmtools/multistate/multistatesampler.py index 691eea98e..7228176eb 100644 --- a/openmmtools/multistate/multistatesampler.py +++ b/openmmtools/multistate/multistatesampler.py @@ -1233,7 +1233,7 @@ def _propagate_replica(self, replica_id): logger.critical(message) raise SimulationNaNError(message) - # Return new positions and box vectors. + # Send the new state to the root node. We can ignore velocities as we're not saving them. return sampler_state.__getstate__(ignore_velocities=True) def _get_replica_move_statistics(self, replica_id): From acdcd8c77296b830330a935267d49593963c2ac4 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 8 Nov 2019 11:13:49 +0100 Subject: [PATCH 131/152] Fix release history --- docs/releasehistory.rst | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index e8788ea4d..81a28f973 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -13,11 +13,15 @@ New features Bugfixes -------- - The multistate samplers now issue experimental API warnings via ``logger.warn()`` rather than ```warnings.warn()`` (`#446 `_) - -Bugfixes --------- - Fix return value in ``states.reduced_potential_at_states`` (`#444 `_). +Known issues +------------ +- Using parallel MPI processes causes poor mixing of the odd thermodynamic states while the mixing of the even states is + normal. We're still investigating whether the issue is caused by a change in the MPI library or an internal bug. For + now, we recommend running calculations using only 1 GPU (see also `# `_ + and `yank#1130 `_). + 0.18.3 - Storage enhancements and bugfixes ========================================== From 7de78f806df23b11840d9da2ed79547524004d27 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Fri, 8 Nov 2019 11:21:03 +0100 Subject: [PATCH 132/152] Fix release notes --- docs/releasehistory.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index 81a28f973..ed2556ced 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -19,7 +19,7 @@ Known issues ------------ - Using parallel MPI processes causes poor mixing of the odd thermodynamic states while the mixing of the even states is normal. We're still investigating whether the issue is caused by a change in the MPI library or an internal bug. For - now, we recommend running calculations using only 1 GPU (see also `# `_ + now, we recommend running calculations using only 1 GPU (see also `#449 `_ and `yank#1130 `_). 0.18.3 - Storage enhancements and bugfixes From 9bd05c0bebc0ac5753042a0ca586b080a765216b Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Sat, 21 Mar 2020 15:32:04 +0100 Subject: [PATCH 133/152] Fix restrained atom indices --- openmmtools/multistate/multistateanalyzer.py | 28 +++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/openmmtools/multistate/multistateanalyzer.py b/openmmtools/multistate/multistateanalyzer.py index f6ea8ac8f..7bb7b6c5f 100644 --- a/openmmtools/multistate/multistateanalyzer.py +++ b/openmmtools/multistate/multistateanalyzer.py @@ -1688,11 +1688,19 @@ def extract_decorrelated(cached_dict, dtype, unit): restraint_force = copy.deepcopy(restraint_force) is_periodic = restraint_force.usesPeriodicBoundaryConditions() - # Store the original indices of the restrained atoms. - original_restrained_atom_indices1 = restraint_force.restrained_atom_indices1 - original_restrained_atom_indices2 = restraint_force.restrained_atom_indices2 - original_restrained_atom_indices = (original_restrained_atom_indices1 + - original_restrained_atom_indices2) + # Store the indices of the restrained atoms in the reduced system. + analysis_indices = self._reporter.analysis_particle_indices + + mapped_restrained_indices1 = restraint_force.restrained_atom_indices1 + mapped_restrained_indices2 = restraint_force.restrained_atom_indices2 + + mapped_restrained_indices1 = [analysis_indices.index(index) + for index in mapped_restrained_indices1] + mapped_restrained_indices2 = [analysis_indices.index(index) + for index in mapped_restrained_indices2] + + mapped_restrained_indices = (mapped_restrained_indices1 + + mapped_restrained_indices2) # Create new system with only solute and restraint forces. reduced_system = openmm.System() @@ -1745,7 +1753,7 @@ def extract_decorrelated(cached_dict, dtype, unit): analysis_particles_only=True) for replica_idx, sampler_state in enumerate(sampler_states): - sliced_sampler_state = sampler_state[original_restrained_atom_indices] + sliced_sampler_state = sampler_state[mapped_restrained_indices] sliced_sampler_state.apply_to_context(context) potential_energy = context.getState(getEnergy=True).getPotentialEnergy() self._restraint_energies[iteration][replica_idx] = potential_energy / _OPENMM_ENERGY_UNIT @@ -1762,11 +1770,11 @@ def extract_decorrelated(cached_dict, dtype, unit): dtype=np.float32) trajectory.image_molecules(inplace=True, anchor_molecules=anchor_molecules, other_molecules=imaged_molecules) - positions_group1 = trajectory.xyz[0][original_restrained_atom_indices1] - positions_group2 = trajectory.xyz[0][original_restrained_atom_indices2] + positions_group1 = trajectory.xyz[0][mapped_restrained_indices1] + positions_group2 = trajectory.xyz[0][mapped_restrained_indices2] else: - positions_group1 = sampler_state.positions[original_restrained_atom_indices1] - positions_group2 = sampler_state.positions[original_restrained_atom_indices2] + positions_group1 = sampler_state.positions[mapped_restrained_indices1] + positions_group2 = sampler_state.positions[mapped_restrained_indices2] positions_group1 /= _MDTRAJ_DISTANCE_UNIT positions_group2 /= _MDTRAJ_DISTANCE_UNIT From 9019ae9a8b2df3c19245ae9c6e7e0721931b14d9 Mon Sep 17 00:00:00 2001 From: Andrea Rizzi Date: Sat, 21 Mar 2020 15:39:24 +0100 Subject: [PATCH 134/152] Fix release history --- docs/releasehistory.rst | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index ed2556ced..df29ae2c5 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -1,18 +1,27 @@ Release History *************** + +0.19.1 - Bugfix release +======================= + +Bugfixes +-------- +- Fixed a crash during the restraint unbiasing for systems with an unexpected order of atoms of receptor and ligands (`#462 `_). + + 0.19.0 - Multiple alchemical regions ==================================== New features ------------ - Added support in ``AbsoluteAlchemicalFactory`` for handling multiple independent alchemical regions (`#438 `_). -- Added support for anisotropic and membrane barostats in `ThermodynamicState` (`#437 `_) -- Added support for platform properties in ContextCache (e.g. for mixed and double precision CUDA in multistate sampler) (`#437 `_) +- Added support for anisotropic and membrane barostats in `ThermodynamicState` (`#437 `_). +- Added support for platform properties in ContextCache (e.g. for mixed and double precision CUDA in multistate sampler) (`#437 `_). Bugfixes -------- -- The multistate samplers now issue experimental API warnings via ``logger.warn()`` rather than ```warnings.warn()`` (`#446 `_) +- The multistate samplers now issue experimental API warnings via ``logger.warn()`` rather than ``warnings.warn()`` (`#446 `_). - Fix return value in ``states.reduced_potential_at_states`` (`#444 `_). Known issues From 61f6e00e36abb4cc118a38a96dcc2b0635baa016 Mon Sep 17 00:00:00 2001 From: dominicrufa Date: Fri, 10 Apr 2020 14:30:38 -0400 Subject: [PATCH 135/152] add a loopy customintegrator --- openmmtools/integrators.py | 226 ++++++++++++++++++++++++++ openmmtools/tests/test_integrators.py | 86 +++++++++- 2 files changed, 311 insertions(+), 1 deletion(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 87169d707..1f7a17ba7 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -1895,6 +1895,232 @@ def _add_alchemical_reset_step(self): # Add all dependent parameters self._add_update_alchemical_parameters_step() +class LoopyAlchemicalNonequilibriumLangevinIntegrator(AlchemicalNonequilibriumLangevinIntegrator): + """ + Subclass of `AlchemicalNonequilibriumLangevinIntegrator` that hardcodes the following integration scheme: + + Step 1: lambda_0 equilibrium sampling + run nsteps_eq of BAOAB (V R O R V) integration at the alchemical lambda_0 endstate + Step 2: Forward Annealing + run n_steps_neq of BAOAB (V R O R V H); 'H': Hamiltonian update step + Step 3: lambda_1 equilibrium sampling + run Step 1 at the lambda_1 endstate + Step 3: Reverse Annealing + run Step 2 in the reverse direction + + forward and backward works are saved to `forward_work` and `backward_work`, respectively + """ + def __init__(self, + alchemical_functions = None, + nsteps_eq = 1000, + nsteps_neq = 100, + **kwargs): + """ + arguments + nsteps_eq : int + number of equilibration steps to run at either endstate + nsteps_neq : int + number of nonequilibrium annealing steps to run in either direction + + parameters + _n_steps_eq : int + number of BAOAB loops to run at each endstate in an attempt to generate i.i.d samples from endstates + """ + self._n_steps_eq = nsteps_eq + splitting = 'V R O R V' + super().__init__(alchemical_functions, splitting, nsteps_neq = nsteps_neq, **kwargs) + + def _add_global_variables(self): + """ + modify the super (_add_global_variables) to add a collector for forward and reverse annealing, as well as to specify the number of equilibration + steps at endstates. + """ + super()._add_global_variables() + self.addGlobalVariable('forward_work', 0) + self.addGlobalVariable('backward_work', 0) + self.addGlobalVariable('n_steps_eq', self._n_steps_eq) + self.addGlobalVariable('eq_step', 0) + + #overwrite because this is set to 0 in super() (n_H = 1, but this is omitted in the splitting string); + #see https://github.com/choderalab/openmmtools/blob/c2b61c410b255c4e08927acf8cfcb1cf46f64b70/openmmtools/integrators.py#L1818 + self.setGlobalVariableByName('n_lambda_steps', self._n_steps_neq) + + def _add_integrator_steps(self): + """ + hardcode a custom integration scheme specified at the top of the class + """ + #init/reset + self.addConstrainPositions() #constrain positions + self.addConstrainVelocities() #and velocities + self._add_reset_step() #reset lambda, protocol_works, heat, shadow, ghmc, step (unused), lambda_step, and alchemical_params + + #lambda_0 equilibration + self.beginWhileBlock("eq_step < n_steps_eq") + self._add_canonical_integrator_steps() #add VRORV + self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step + self.endBlock() + + #forward anneal + self.beginWhileBlock("lambda_step < n_lambda_steps") #anneal forward until lambda step is n_lambda_steps (lambda = lambda_step / n_lambda_steps) + self._add_canonical_integrator_steps() #add VRORV + self._substep_function('H') #add the H step... + self.endBlock() + self.addComputeGlobal('forward_work', 'protocol_work') #log the forward protocol work + self.addComputeGlobal('protocol_work', '0') #reset the protocol work for the reverse annealing + + + #lambda_1 equilibration + self.addComputeGlobal('eq_step', '0') #reset eq_step counter + self.beginWhileBlock("eq_step < n_steps_eq") + self._add_canonical_integrator_steps() #add VRORV + self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step + self.endBlock() + + #reverse anneal; don't reset lambda (it is annealing in backward direction) + self.beginWhileBlock("lambda_step > 0") #anneal backward until lambda step is 0 again + self._add_canonical_integrator_steps() #add VRORV + self._substep_function('L') #add the L step (backward H) + self.endBlock() + self.addComputeGlobal('backward_work', 'protocol_work') + + def _add_reset_step(self): + """ + Reset the alchemical lambda to its starting value (lambda = 0) + """ + self.addComputeGlobal("lambda", "0") + self.addComputeGlobal("step", "0") + self.addComputeGlobal("lambda_step", "0") + self.addComputeGlobal('forward_work', "0") + self.addComputeGlobal('backward_work', "0") + self.addComputeGlobal('protocol_work', '0') + self.addComputeGlobal('eq_step', '0') + # Add all dependent parameters + self._add_update_alchemical_parameters_step() + + def _add_canonical_integrator_steps(self): + """ + add the BAOAB integrator + """ + self.addUpdateContextState() + self.addComputeTemperatureDependentConstants({"sigma": "sqrt(kT/m)"}) + + for i, step in enumerate(self._splitting.split()): #splitting is just 'V R O R V' + self._substep_function(step) + + @property + def _step_dispatch_table(self): + """ + add an L step to the dispatch table + """ + dispatch_table = super()._step_dispatch_table + dispatch_table['L'] = (self._add_backward_alchemical_perturbation_step, False) + return dispatch_table + + def _add_backward_alchemical_perturbation_step(self): + """ + _add_alchemical_perturbation_step except the lambda step is decremented + """ + # Store initial potential energy + self.addComputeGlobal("Eold", "energy") + + # Update lambda and increment that tracks updates. + self.addComputeGlobal('lambda', '(lambda_step-1)/n_lambda_steps') + self.addComputeGlobal('lambda_step', 'lambda_step - 1') #decrement instead of increment + + # Update all slaved alchemical parameters + self._add_update_alchemical_parameters_step() + + # Accumulate protocol work + self.addComputeGlobal("Enew", "energy") + self.addComputeGlobal("protocol_work", "protocol_work + (Enew-Eold)") + + def get_forward_work(self, dimensionless=False): + """ + pull the forward work from the integrator global variables + """ + return self._get_energy_with_units('forward_work', dimensionless = dimensionless) + + def get_backward_work(self, dimensionless=False): + """ + pull the backward work from the integrator global variables + """ + return self._get_energy_with_units('backward_work', dimensionless=dimensionless) + +class LoopyIndependentAlchemicalNonequilibriumLangevinIntegrator(LoopyAlchemicalNonequilibriumLangevinIntegrator): + """ + Subclass of LoopyAlchemicalNonequilibriumLangevinIntegrator that runs two independent equilibrium simulations at alchemical + for annealing purposes. + """ + def __init__(self, + zero_endstate_positions, + one_endstate_positions, + alchemical_functions = None, + nsteps_eq = 1000, + nsteps_neq = 100, + **kwargs): + """ + arguments + zero_endstate_positions : np.ndarray() (N, 3) unit.Quantity (in length units) + starting positions of the zero endstate equilibration + one_endstate_positions : np.ndarray() (N,3) unit.Quantity (in length units) + starting positions of the one endstate equilibration + """ + super().__init__(alchemical_functions = alchemical_functions, + nsteps_eq = nsteps_eq, + nsteps_neq = nsteps_neq, + **kwargs) + + self.addPerDofVariable('x_zero_endstate', zero_endstate_positions.value_in_unit_system(unit.md_unit_system)) + self.addPerDofVariable('x_one_endstate', zero_endstate_positions.value_in_unit_system(unit.md_unit_system)) + self.addPerDofVariable('x_annealing', 0.) + + def _add_integrator_steps(self): + """ + hardcode a custom integration scheme specified at the top of the class + """ + #init/reset + self.addConstrainPositions() #constrain positions + self.addConstrainVelocities() #and velocities + self._add_reset_step() #reset lambda, protocol_works, heat, shadow, ghmc, step (unused), lambda_step, and alchemical_params + + #lambda_0 equilibration + self.addComputePerDof('x', 'x_zero_endstate') #replace the x positions with the zero endstate positions + self.beginWhileBlock("eq_step < n_steps_eq") + self._add_canonical_integrator_steps() #add VRORV + self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step + self.endBlock() + self.addComputePerDof('x_zero_endstate', 'x') + self.addComputePerDof('x_annealing', 'x_zero_endstate') + + + #forward anneal + self.addComputePerDof('x', 'x_annealing') + self.beginWhileBlock("lambda_step < n_lambda_steps") #anneal forward until lambda step is n_lambda_steps (lambda = lambda_step / n_lambda_steps) + self._add_canonical_integrator_steps() #add VRORV + self._substep_function('H') #add the H step... + self.endBlock() + self.addComputeGlobal('forward_work', 'protocol_work') #log the forward protocol work + self.addComputeGlobal('protocol_work', '0') #reset the protocol work for the reverse annealing + + + #lambda_1 equilibration + self.addComputePerDof('x', 'x_one_endstate') #replace the x positions with the one endstate positions + self.addComputeGlobal('eq_step', '0') #reset eq_step counter + self.beginWhileBlock("eq_step < n_steps_eq") + self._add_canonical_integrator_steps() #add VRORV + self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step + self.endBlock() + self.addComputePerDof('x_one_endstate', 'x') + self.addComputePerDof('x_annealing', 'x_one_endstate') + + #reverse anneal; don't reset lambda (it is annealing in backward direction) + self.beginWhileBlock("lambda_step > 0") #anneal backward until lambda step is 0 again + self._add_canonical_integrator_steps() #add VRORV + self._substep_function('L') #add the L step (backward H) + self.endBlock() + self.addComputeGlobal('backward_work', 'protocol_work') + + class ExternalPerturbationLangevinIntegrator(NonequilibriumLangevinIntegrator): """ Create a LangevinSplittingIntegrator that accounts for external perturbations and tracks protocol work. diff --git a/openmmtools/tests/test_integrators.py b/openmmtools/tests/test_integrators.py index 01539b327..2057e0cdf 100755 --- a/openmmtools/tests/test_integrators.py +++ b/openmmtools/tests/test_integrators.py @@ -25,7 +25,7 @@ from openmmtools import integrators, testsystems from openmmtools.integrators import (ThermostatedIntegrator, AlchemicalNonequilibriumLangevinIntegrator, - GHMCIntegrator, NoseHooverChainVelocityVerletIntegrator) + GHMCIntegrator, NoseHooverChainVelocityVerletIntegrator, LoopyAlchemicalNonequilibriumLangevinIntegrator) #============================================================================================= @@ -774,10 +774,94 @@ def run_alchemical_langevin_integrator(nsteps=0, splitting="O { V R H R V } O"): if nsigma > NSIGMA_MAX: raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) +def run_loopy_alchemical_langevin_integrator(integrator_flavor = LoopyAlchemicalNonequilibriumLangevinIntegrator, + nsteps=20, + nsteps_neq=10, + nsteps_eq=10): + """ + Test different flavors of the LoopyAlchemicalNonequilibriumLangevinIntegrator (and perhaps subclasses thereof) + + arguments + integrator_flavor : openmmtools.integrator.LoopyAlchemicalNonequilibriumLangevinIntegrator (or subclass) + integrator to run + nsteps : int, default 20 + number of integrator.steps() to run + nsteps_neq : int, default 10 + number of forward/backward annealing steps + nsteps_eq : int, default 10 + number of equilibration steps to run at endstates before annealing + """ + #max deviation from the calculated free energy + NSIGMA_MAX = 6 + n_iterations = 200 # number of forward and reverse protocols + + # These are the alchemical functions that will be used to control the system + temperature = 298.0 * unit.kelvin + sigma = 1.0 * unit.angstrom # stddev of harmonic oscillator + kT = kB * temperature # thermal energy + beta = 1.0 / kT # inverse thermal energy + K = kT / sigma**2 # spring constant corresponding to sigma + mass = 39.948 * unit.amu + period = unit.sqrt(mass/K) # period of harmonic oscillator + timestep = period / 20.0 + collision_rate = 1.0 / period + dF_analytical = 1.0 + parameters = dict() + parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, 2 * sigma) + parameters['testsystems_HarmonicOscillator_U0'] = (0 * kT, 1 * kT) + integrator_kwargs = {'temperature':temperature, + 'collision_rate': collision_rate, + 'timestep': timestep, + 'measure_shadow_work': False, + 'measure_heat': False} + alchemical_functions = { name : '(1-lambda)*%f + lambda*%f' % (value[0].value_in_unit_system(unit.md_unit_system), value[1].value_in_unit_system(unit.md_unit_system)) for (name, value) in parameters.items() } + # Create harmonic oscillator testsystem + testsystem = testsystems.HarmonicOscillator(K=K, mass=mass) + system = testsystem.system + positions = testsystem.positions + + # Create integrator + integrator = LoopyAlchemicalNonequilibriumLangevinIntegrator(alchemical_functions=alchemical_functions, + nsteps_eq=nsteps_eq, + nsteps_neq=nsteps_neq, + **integrator_kwargs) + platform = openmm.Platform.getPlatformByName("Reference") + context = openmm.Context(system, integrator, platform) + context.setPositions(positions) + + forward, backward = [], [] + for _ in range(nsteps): + integrator.step(1) + forward.append(integrator.get_forward_work(dimensionless=True)) + backward.append(integrator.get_backward_work(dimensionless=True)) + + dF, ddF = pymbar.BAR(np.array(forward), np.array(backward)) + nsigma = np.abs(dF - dF_analytical) / ddF + current_lambda = integrator.getGlobalVariableByName('lambda') + assert current_lambda == 0.0, 'final lambda should be 0.0 (was %f)' % current_lambda + print("analytical DeltaF: {:12.4f}, DeltaF: {:12.4f}, dDeltaF: {:12.4f}, nsigma: {:12.1f}".format(dF_analytical, dF, ddF, nsigma)) + if nsigma > NSIGMA_MAX: + raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) + + # Clean up + del context + del integrator + + def test_alchemical_langevin_integrator(): for splitting in ["O { V R H R V } O", "O V R H R V O", "H R V O V R H"]: for nsteps in [0, 1, 10]: run_alchemical_langevin_integrator(nsteps=nsteps) +def test_loopy_alchemical_integrators(): + """ + test loopy alchemical langevin integrators: see run_loopy_alchemical_langevin_integrator + """ + for integrator_flavor in [LoopyAlchemicalNonequilibriumLangevinIntegrator]: + run_loopy_alchemical_langevin_integrator(integrator_flavor = integrator_flavor, + nsteps=20, + nsteps_neq=10, + nsteps_eq=10) + if __name__=="__main__": test_alchemical_langevin_integrator() From 9eed89c67f62833332b690e86505774c7cf6c2fd Mon Sep 17 00:00:00 2001 From: dominicrufa Date: Fri, 10 Apr 2020 14:39:26 -0400 Subject: [PATCH 136/152] help example --- .../troubleshoot_loopy_customintegrator.ipynb | 253 ++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 examples/neq_customintegrator/troubleshoot_loopy_customintegrator.ipynb diff --git a/examples/neq_customintegrator/troubleshoot_loopy_customintegrator.ipynb b/examples/neq_customintegrator/troubleshoot_loopy_customintegrator.ipynb new file mode 100644 index 000000000..8d7bbf7fc --- /dev/null +++ b/examples/neq_customintegrator/troubleshoot_loopy_customintegrator.ipynb @@ -0,0 +1,253 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Attempt to build an `simtk.openmm.CustomIntegrator` for nonequilibrium switching" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "from openmmtools.integrators import AlchemicalNonequilibriumLangevinIntegrator\n", + "from simtk import unit\n", + "import numpy as np\n", + "import simtk.openmm as openmm\n", + "from openmmtools.constants import kB\n", + "from openmmtools import utils\n", + "_OPENMM_ENERGY_UNIT = unit.kilojoules_per_mole\n", + "from pkg_resources import resource_filename\n", + "from openmmtools.integrators import LoopyAlchemicalNonequilibriumLangevinIntegrator" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "from openmmtools.states import SamplerState, ThermodynamicState, CompoundThermodynamicState\n", + "from perses.annihilation.lambda_protocol import RelativeAlchemicalState\n", + "from perses.dispersed.feptasks import minimize\n", + "import pickle\n", + "from openmmtools import cache\n", + "\n", + "\n", + "\n", + "def test_loopy_customintegrator(htf,\n", + " alchemical_functions,\n", + " number_of_applications = 10,\n", + " neq_steps = 100,\n", + " eq_steps = 1000,\n", + " integrator_kwargs = {'temperature': 300.0 * unit.kelvin,\n", + " 'collision_rate': 1.0 / unit.picoseconds,\n", + " 'timestep': 2.0 * unit.femtoseconds,\n", + " 'constraint_tolerance': 1e-6,\n", + " 'measure_shadow_work': False,\n", + " 'measure_heat': False},\n", + " pressure = None\n", + " ):\n", + " \"\"\"\n", + " simple test to see if i can anneal benzene --> fluorobenzene with the loopy integrator\n", + " \"\"\"\n", + " \n", + " thermostate = ThermodynamicState(system = htf.hybrid_system, temperature = integrator_kwargs['temperature'], pressure = pressure)\n", + " alchemical_thermostate = CompoundThermodynamicState(thermostate, [RelativeAlchemicalState.from_system(htf.hybrid_system)])\n", + " sampler_state = SamplerState(positions = htf._hybrid_positions, box_vectors = np.array(htf.hybrid_system.getDefaultPeriodicBoxVectors()))\n", + " minimize(thermostate, sampler_state)\n", + " integrator = LoopyAlchemicalNonequilibriumLangevinIntegrator(alchemical_functions = alchemical_functions,\n", + " nsteps_eq = eq_steps,\n", + " nsteps_neq = neq_steps,\n", + " **integrator_kwargs)\n", + " context, integrator = cache.global_context_cache.get_context(alchemical_thermostate, integrator)\n", + " sampler_state.apply_to_context(context)\n", + " context.setVelocitiesToTemperature(thermostate.temperature)\n", + " return integrator, context" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "x = 'lambda'\n", + "alchemical_functions = {\n", + " 'lambda_sterics_core': x,\n", + " 'lambda_electrostatics_core': x,\n", + " 'lambda_sterics_insert': f\"select(step({x} - 0.5), 1.0, 2.0 * {x})\",\n", + " 'lambda_sterics_delete': f\"select(step({x} - 0.5), 2.0 * ({x} - 0.5), 0.0)\",\n", + " 'lambda_electrostatics_insert': f\"select(step({x} - 0.5), 2.0 * ({x} - 0.5), 0.0)\",\n", + " 'lambda_electrostatics_delete': f\"select(step({x} - 0.5), 1.0, 2.0 * {x})\",\n", + " 'lambda_bonds': x,\n", + " 'lambda_angles': x,\n", + " 'lambda_torsions': x}\n", + "\n", + "htf_filename = resource_filename('coddiwomple', f\"/data/perses_data/benzene_fluorobenzene.solvent.factory.pkl\")\n", + "with open(htf_filename, 'rb') as f:\n", + " htf = pickle.load(f)\n", + "integrator, context = test_loopy_customintegrator(htf = htf,\n", + " alchemical_functions = alchemical_functions, pressure = 1. * unit.atmosphere)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "running 1 trial\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "100%|██████████| 50/50 [08:11<00:00, 9.82s/it]\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "running 50 trial\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "100%|██████████| 50/50 [09:01<00:00, 10.83s/it]\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "running 100 trial\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "100%|██████████| 50/50 [09:47<00:00, 11.75s/it]\n" + ] + } + ], + "source": [ + "import tqdm\n", + "forward_works = {}\n", + "backward_works = {}\n", + "for annealing_steps in [1, 50, 100]:\n", + " print(f\"running {annealing_steps} trial\")\n", + " integrator, context = test_loopy_customintegrator(htf = htf,\n", + " alchemical_functions = alchemical_functions,\n", + " neq_steps = annealing_steps)\n", + " forward, backward = [], []\n", + " for _ in tqdm.trange(50):\n", + " integrator.step(1)\n", + " num_global_vars = integrator.getNumGlobalVariables()\n", + " global_integrator_variables = {integrator.getGlobalVariableName(idx): integrator.getGlobalVariable(idx) for idx in range(num_global_vars)}\n", + " forward.append(global_integrator_variables['forward_work'])\n", + " backward.append(global_integrator_variables['backward_work'])\n", + " forward_works[annealing_steps] = forward\n", + " backward_works[annealing_steps] = backward" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "DEBUG:matplotlib.pyplot:Loaded backend module://ipykernel.pylab.backend_inline version unknown.\n" + ] + } + ], + "source": [ + "%matplotlib inline\n", + "\n", + "import matplotlib\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "Text(0, 0.5, 'frequency')" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYgAAAEWCAYAAAB8LwAVAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjMsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+AADFEAAAgAElEQVR4nOydeVxVZf743x/gAgqIIiIgKjDuCyLiUppDmUtaWk1TmZZmi9k6TYtOM22WLd/p1zSW1WTaMlpZWU2NljalmVZuaRaKYoqKIig7isK9PL8/zrm3C1zgAvcC6vN+vc7rcs6zfc7C+ZzP53mezyNKKTQajUajqYpPcwug0Wg0mpaJVhAajUajcYlWEBqNRqNxiVYQGo1Go3GJVhAajUajcYlWEBqNRqNxiVYQHkBEMkTk4uaW40xDRK4QkUMiUiIiA5vrOorIdBFZ39TttmRE5E0RebK55WipOD+rIvKQiLze3DJ5A7/mFkBzTvMccKdS6j8AItLM4miaEhGJBfYDFqWUtXmlaThKqaeaWwZvoS0ITaMRkY4NLNoVSPWkLK4QEV9vt6HRnI1oBeE5BovIThHJF5E3RCTQniAil4rIdhEpEJHvRCTBKS1DRO4XkR0iUigiy+xlReQz0/1i3ypEZLqZ1ktEvhSRPBHZLSJXO9X5pogsEJEVIlIsIhtF5HdO6TWWbSBrRORrEZkqIq3ryiwiASJSAvgCP4nIry7yVHJxiEiKiGQ67fcWkbXmNU0VkYlVyr4iIitF5ARwoYiEisjbInJMRA6IyN9ExKdyk/KieQ/SRGSUU0KoiCwSkSwROSwiT9qVjt09JSLPmfd+v4hcYqadV+X+nRKRDDPNR0TmiMivIpIrIu+LSJiZFisiSkSmichBETkuIn91kqfGsi6uY7iI/Ne8Tnki8q39vGu7hlXq2CUilzrt+5kyJZn7w8znukBEfhKRFKe8a0XkCRHZYD6Lq0Uk3ExeZ/4WmNfnPBdtDxGR7826s0TkJRHxd0pXInKbiKSb13+BiGGK1nZv3LivvzOf6VzzXJeKSNsars9jIrLEzXvXSkTeMuXZJSIPitNz3eJQSumtkRuQAfwCdAbCgA3Ak2ZaEpADDMV4IU4z8wc4ld0ERJtldwG3uWhjHHDEbCMIOATciOEmTAKOA33NvG8CecAQM30p8J6ZVmvZBp5/a2Aq8CWQD7wGnOdGOQV0q3IdL3Y6hyed0lKATPNvC7AXeAjwBy4CioGeTmULgeEYH0GBwNvAf4AQIBbYA9xk5p8OWIF7zbqvMcuHmemfAP8yr12Eeb9mOpUtB24x7+8s8z5JlXO1AGuBp839PwE/ADFAgFn/u2ZarHltFgKtgAHAaaB3XWVdXOOngVfN9i3ABYC4eQ3tz/AjwFKnOicAaebfnYBcYLx5rUeb+x3M9LXAr0AP81zWAs9UOU+/Wp6RQcAwjGc1FuP/409VnqH/Am2BLsAxYJw796aO+9rNPJcAoAOGMnuhhmf1MWCJm/fuGeAboJ15/3ZgPtctcWt2Ac6GzXxYbnPaHw/8av79CvBElfy7gd87lZ3qlPZ/wKtV8vfAUDIXmPvXAN9WyfMv4FHz7zeB16vIk+ZOWQ9ci84YL53dQBpwdS15G6ogLgCOAj5O6e8CjzmVfdspzdf8J+3jdGwmsNb8ezpVXurmy+J6oKNZtpVT2mRgjVPZvU5prc3ziqxyrq8AK+wyY7zoRjmlR2G8zOwvQgXEVJHn2rrKurjGczEUY7cqx925hnYF0Q1DebQ295cCj5h/zwb+XaXuVcA08++1wN+c0m4HvjD/tp9njQrCxfn8Cfi4yjM0wmn/fWBOXfemrvvqot3LgW01PKuPUV1B1HTv9gFjndJupgUrCN1J7TkOOf19AMMiAMPPPk1E7nJK93dKB+Mf1c5J5zQRCcX4B39YKfWtU51DRaTAqZwf8O9a6gyuR1l72xcAn9vPSSnVV0RSzToALnGSyU4W8JO5XYLxleRpooFDSqkKp2MHML5m7Tjfj3CMa36glvyHlfkf65QejXGuFiBLfutE96lSv+NaK6VOmvns1xsRmYmh4IY5ydwV+FhEnM/BhvHiqlYv1e9hTWUPU5m/Y7zAVptyvaaUegb3rqH9nPaKyC7gMhH5DJgIDHSS5Y8icplTEQuwxo3zqBMR6QE8DyRjvOD9gK1VstVWf033Joxa7quIRADzMRRpiJmW767ctcgUTeVnx/nvFodWEJ6js9PfXTC+SMF4AOYppebVt0LTV/wOxlfNv5ySDgHfKKVGN0BOt8uaL//gKsf61iDrQOAGjK+wfcAbwM1KqaIGyAhwAuOFYCfS6e8jQGcR8XF6wXXBcBs5RHX6+zjGF3ZXYKdTfueXaScREScl0QX4FON6nQbCVQNG2phK9gmMr9xCp6RDwAyl1AYXZWLrqLbGslVRShUD9wH3iUhfjP6izbh3DZ15F+Pe+gA7lVJ7nWT5t1LqlrpkcSWeG3leAbYBk5VSxSLyJ+CqBrRVlbru69OmfAlKqVwRuRx4yQPtZmF8NNmfw8615G12dCe157hDRGLMzsKHgGXm8YXAbSIyVAyCRGSCiIS4Uec8DP/oPVWO/xfoISLXi4jF3AaLSG836mxMWZeIyNfAZ8ApYKRS6nyl1MJGKAeA7cB4EQkTkUgM14KdjRgK5EFT/hTgMuA9VxUppWwYrod5IhIiIl2BPwNLnLJFAHeb9f0R6A2sVEplAauB/ycibcToIP6diPy+rhMQkc4Yz8ENSqmqL95XTXm6mnk7iMikuuqsb1kxBkh0MztuizAsDRv1vIbm8TEYfvx3nI4vwbAsxoqIr4gEijGgwB3L8RhQAcTXkifElLtERHqZ7TcaN+5rCFCC0YHeCXjAE+1iPId/EZF2Zr13eqher6AVhOd4B+OB22duTwIopbZgdJK9hGGi7sXwjbrDZIwOunz5bSTMFPOrcAxwLcaX4FHgWYwOtVppTNla+CvQRSn1Fxcvwobybww3VQbGdbUrXJRSZRhujkswrIOXMV7CabXUdxfGC3EfsB7jfi12St8IdDfrmwdcpZTKNdNuwHBR7cS4hx9i+P3rYhSG5fOh0/2zD+v9J4aFslpEijE6nYe6UWd9y3YH/ofxsvseeFkptba+19B8oX4PnE/le3EImITxUXQM48v8Adx4tyilTmJc6w1ijFIa5iLb/cB1GH0gC53b9gC13dfHMQZwFGL0HX3koTbnApkY8z/+Z7Z52kN1exx7b75Go9FomhgRmYXRgV2nRdocaAtCo9FomggRiRKR4aZLqydG/9DHzS1XTehOao1Go2k6/DGGlccBBRh9Oy83q0S1oF1MGo1Go3GJdjFpNBqNxiVnlYspPDxcxcbGNrcYGo1Gc8awdevW40qpDq7SzioFERsby5YtW5pbDI1GozljEJEDNaVpF5NGo9FoXKIVhEaj0WhcohWERqPRaFxyVvVBaDRnGuXl5WRmZnLq1KnmFkVzlhMYGEhMTAwWi8XtMlpBaDTNSGZmJiEhIcTGxuo1uTVeQylFbm4umZmZxMXFuV1Ou5g0mmbk1KlTtG/fXisHjVcREdq3b19vS1UrCI2mmdHKQdMUNOQ50wriTKDC1twSaDSacxCtIFoyNiu8cy08GQGbFja3NBpNraSlpXHeeecREBDAc88919ziuCQlJcUxmXb8+PEUFBTUUaLhPPXUU16ru6nQCqIls/UN2PM5+AfBF3Og+GjdZTQaD5Kf7/4yzGFhYcyfP5/777/fixJ5jpUrV9K2bVuv1a8VhMZ7KAUb/wWdBsHNX0OFFba/U3c5jcaD3HXXXVx44YUsXbq0zg7OiIgIBg8eXOcwylmzZpGcnEzfvn159NFHHcdjY2N59NFHSUpKon///qSlGYvbPfbYY8yYMYOUlBTi4+OZP3++o8ySJUsYMmQIiYmJzJw5E5vNVmsbzsTGxnL8+HEyMjLo3bs3t9xyC3379mXMmDGUlpYCsHnzZhISEjjvvPN44IEH6NevX7V6srKyGDlyJImJifTr149vv/2WOXPmUFpaSmJiIlOmTKlV1uDgYO677z6SkpIYNWoUx44dA2D+/Pn06dOHhIQErr322lqvqbfQw1xbKtmpkJsOl/0TwrtBdBLs+QIu+HNzS6bxEo9/lsrOI41Zxrs6faLb8OhlfRtcfsmSJWzdupXFixfzyCOPMH78eG6++WYGDBjQ4DrnzZtHWFgYNpuNUaNGsWPHDhISEgAIDw/nxx9/5OWXX+a5557j9ddfBwz31Zo1ayguLqZnz57MmjWLvXv3smzZMjZs2IDFYuH2229n6dKl3HDDDbW24Yr09HTeffddFi5cyNVXX83y5cuZOnUqN954I6+99hrnn38+c+bMcVn2nXfeYezYsfz1r3/FZrNx8uRJLrjgAl566SW2b98OwK5du2qU9cSJEyQlJfH//t//Y+7cuTz++OO89NJLPPPMM+zfv5+AgACvusJqw6sWhIiME5HdIrJXRKpdXTGYb6bvEJEkp7S2IvKhiKSJyC4ROc+bsrY49nxh/PYYZ/zGjYTDW6HsRPPJpDknGTRoEAsWLCA1NZVu3boxZMgQnn/++QbX9/7775OUlMTAgQNJTU1l586djrQrr7zS0WZGRobj+IQJEwgICCA8PJyIiAiys7P56quv2Lp1K4MHDyYxMZGvvvqKffv21dmGK+Li4khMTKzUdkFBAcXFxZx//vkAXHfddS7LDh48mDfeeIPHHnuMn3/+mZCQkGp5apPVx8eHa665BoCpU6eyfv16ABISEpgyZQpLlizBz695vuW91qqI+AILgNEYi3RvFpFPlVLOd+oSjEXVu2Msuv4Kvy2+/k/gC6XUVSLiD7T2lqwtkgMbIKIvhEQa+7EXwIYXIHMzxKc0p2QaL9GYL/2GsmDBAhYuNAZArFy5khtvvJHs7GySk5MdX+9Wq5WVK1fyxhtvkJ6ezty5c5k6dWqD2tu/fz/PPfccmzdvpl27dkyfPr2S6yogIAAAX19frFZrtePOaUoppk2bxtNPP12vNlxRtf7S0lLcXUxt5MiRrFu3jhUrVnD99dfzwAMPcMMNN1TKU5OsrrAPR12xYgXr1q3j008/5YknniA1NbXJFYU3LYghwF6l1D6lVBnG0nqTquSZBLytDH4A2pprtrYBRgKLAJRSZUqp5rGxmgOlDGshJvm3Y9HG1w1Hf24emTRnJXfccQfbt29n+/btREdHs2rVKrZv3+5QDs8//zw9evRg+fLl3Hvvvfzyyy/Mnj2biIiIBrVXVFREUFAQoaGhZGdn8/nnnzdY9lGjRvHhhx+Sk5MDQF5eHgcOHPBYG+3atSMkJIQffvgBgPfee89lvgMHDhAREcEtt9zCTTfdxI8//giAxWKhvLy8VlkBKioq+PDDDwHDXTVixAgqKio4dOgQF154If/3f/9HQUEBJSUlDTqPxuBNddQJOOS0n8lv1kFteToBVuAY8IaIDAC2Avcopar5V0TkVuBWgC5dunhM+GYlbx+cKjQ6qO0EhUNIFBz9pfnk0pxzJCQksH37dtq0aVNn3qNHj5KcnExRURE+Pj688MIL7Ny5s1LZAQMGMHDgQPr27Ut8fDzDhw9vsGx9+vThySefZMyYMVRUVGCxWFiwYAHDhg3zWBuLFi3illtuISgoiJSUFEJDQ6vlWbt2LX//+9+xWCwEBwfz9ttvA3DrrbeSkJBAUlISS5cudSlr165dCQoKIjU1lUGDBhEaGsqyZcuw2WxMnTqVwsJClFLce++9Xh1xVRNeW5NaRP4IjFVK3WzuXw8MUUrd5ZRnBfC0Umq9uf8V8CAgwA/AcKXURhH5J1CklHq4tjaTk5PVWbFg0I734aNb4LYNEOk0amLJVVCcBbM2NJ9sGo+ya9cuevfu3dxiaGqgpKSE4OBgAJ555hmysrL45z//6dE2goODm8w6cPW8ichWpVSyq/zedDFlAp2d9mOAI27myQQylVIbzeMfAkmcKxzeCpbW0KFX5eMRveB4OlRUNI9cGs05xooVKyoNX/3b3/7W3CI1Kd50MW0GuotIHHAYuBaoOgzgU+BOEXkPw/1UqJTKAhCRQyLSUym1GxgF1D4M4Wzi8FaISgTfKrcn7HdgOw1FmdD2LHGnaTQtmGuuucYxwshbNEffgrt4TUEopawiciewCvAFFiulUkXkNjP9VWAlMB7YC5wEbnSq4i5gqTmCaV+VtLMXpSBnFyS6GFLX/nfGb+6vWkFoNBqv49UxU0qplRhKwPnYq05/K+COGspuB1z6xc5qirOgrATCe1RPCzMVRN6v8LsLm1YujUZzzqFDbbQ0ju8xfl0piDbR4BsA+RlNKpJGozk30QqipXE83fh1pSBEDCVReLhpZdJoNOckWkG0NI7vAf8QCIlEWa0cf+UVjj45D5s9FktoDBRpBaFpGaxbt46kpCT8/Pwck71aGvagfIAjbIY3KCgo4OWXX/Za/c2BVhAtjeN7ILw7iJC/dCnH/jmf/CVLODTrdpTNBm06aQtC43XKyso4caLuuF9dunThzTffrDFOUUvju+++81rdWkFovM/xdAjvgaqoIHfRYoLOP4/oZ5+hdNs2Cj76CEI7GR3ZepU5jRfYtWsX9913Hz179mTPnj115o+NjSUhIQEfn9pfJZdffjmDBg2ib9++vPbaa47jwcHB/PWvf2XAgAEMGzaM7OxsAKZPn87dd9/N+eefT3x8fCXr5O9//zuDBw8mISGhUijvmtpwxj7pbe3ataSkpHDVVVfRq1cvpkyZ4oi9tHLlSnr16sWIESO4++67ufTSS6vVk5qa6gjdnZCQQHp6OnPmzOHXX38lMTGRBx54oEZZMzIy6NWrF9OmTSMhIYGrrrqKkydPAjBnzhxHiO+WsK6GDvfdkjhdYriPwrtzKjUVa04OEff9mTYTJ5L/3jKOv/gSoU9NxkfZjMWDQjs1t8QaT/L5HM/H2orsD5c8U2uWEydO8P7777No0SKUUtx4443s2LHDZVTShrJ48WLCwsIoLS1l8ODB/OEPf6B9+/acOHGCYcOGMW/ePB588EEWLlzomIyWlZXF+vXrSUtLY+LEiVx11VWsXr2a9PR0Nm3ahFKKiRMnsm7dOkaOHFljGzWxbds2UlNTiY6OZvjw4WzYsIHk5GRmzpzJunXriIuLY/LkyS7Lvvrqq9xzzz1MmTKFsrIybDYbzzzzDL/88osjxHdNsnbp0oXdu3ezaNEihg8fzowZM3j55ZeZMWMGH3/8MWlpaYhIs4X4dkZbEC2JAiN4F2FxlHz7LYgQNHIkIkLEfX/GmpND3rpfjTy6H0LjIaKioli0aBGvv/46GzZs4Oabb/aocgBj8Ru7lXDo0CHS043BGP7+/o4v9Kohvi+//HJ8fHzo06ePw7JYvXo1q1evZuDAgSQlJZGWluaoq6Y2amLIkCHExMTg4+NDYmIiGRkZpKWlER8fT1xcHECNCuK8887jqaee4tlnn+XAgQO0atWqWp7aZO3cubMjRpQ9xHebNm0IDAzk5ptv5qOPPqJ16+YPYK0tiJZEvqkg2sZy6pev8Y+Lw69dOwBaJycTnJJC7vKvaTdG8C3MhM5DmlFYjcep40vfW3z44YcsWrSIK664gsmTJzNt2jS6du0KwMaNG5k5cyYAc+fOZePGjaxYsQLA8aVcF2vXruV///sf33//Pa1btyYlJcURfttisTjCW9cW4tvu/lFK8Ze//MUhkztt1ERNIcTd4brrrmPo0KGsWLGCsWPH8vrrrxMfH18pT02yZmRkOM7Zjojg5+fHpk2b+Oqrr3jvvfd46aWX+Prrr92Sx1toC6IlUXDQ+G3XlVOpqQT2rbw+QIc/30vFyVKO7wrRFoTGY4wZM4Zly5axfv16QkNDmTRpEhdffDEZGRkMHTrUEQ584sSJzJs3z7HvLoWFhbRr147WrVuTlpbmCJ/dEMaOHcvixYsd4SkOHz5MTk6Ox9ro1asX+/btc1gyy5Ytc5lv3759xMfHc/fddzNx4kSHS664uLhOWQEOHjzI999/D8C7777LiBEjKCkpobCwkPHjx/PCCy/U6xp7C21BtCQKDoClNdZSsGZnE9i3T6XkwB49CL18Enn/+ZjgrT8R5L0Re5pzkPbt23PPPfdwzz33sGnTJnx9fesss3nzZq644gry8/P57LPPePTRR0lNTa2UZ9y4cbz66qskJCTQs2dPhg0b1mAZx4wZw65duzjvPGOByeDgYJYsWeKxNlq1asXLL7/MuHHjCA8PZ8gQ11b6smXLWLJkCRaLhcjISB555BHCwsIYPnw4/fr145JLLuHvf/+7S1l9fX3p3bs3b731FjNnzqR79+7MmjWLwsJCJk2axKlTp1BK8Y9//KNhF8mDeC3cd3Nwxof7fm8K5O7lxOAXOXjDNDovep3gKrHsbYWFZIw9j/ISCJs+g7AZM/ALC2smgTWNRYf7bnnYQ3wrpbjjjjvo3r079957r8fqz8jI4NJLL+WXX5p+bZeWFO5bU18KDkDbrpSZ5q1/19hqWXxDQ+k6PZ6Q7oHkLlrM3lEXU2j6hDUaTeNZuHAhiYmJ9O3bl8LCwmp9COcSWkG0JPIPQtsulB04gPj7Y4mKdJnNr0MUnX5vJX7Ffwns24cjD86m9KefmlhYjebs5N5772X79u3s3LmTpUuXenw0UWxsbLNYDw1BK4iWQmkBnC40FETGASxdOiM1+YCDI6Akh4C4ODq/8gp+4eFkP/Ns08qr0WjOerSCaCnY50C060r5wYP4d+lac97gCLCWQlkJviEhtL/pJkq3baP0Zw9PstJoNOc0WkG0FOxDXEM7U56VhSU6uua8wR2N3xJjyFzoFZcjFgtFK1bWXEaj0WjqiVYQLQUzAJ/Ntx0VJSVYoqJqzhvUwfg1FYRvSAitzz+P4i+/dHuij0aj0dSFVhAtheIj4OtPecFpACzRtSgIhwWR/duh3/+e8sOHKc/M9KaUGk2NpKWlcd555xEQEMBzzz1XKe2LL76gZ8+edOvWjWee+W3GeF5eHqNHj6Z79+6MHj2a/Pz8pha7TuwB/o4cOcJVV13ltXYyMjJ45513vFZ/Q9AKoqVQdATaRFOelQVQuwURHGH8njjmOBQ0eDAAJzdt9pqImnOP+ryww8LCmD9/frUopDabjTvuuIPPP/+cnTt38u6777Jz504AnnnmGUaNGkV6ejqjRo2qpDxaGtHR0V5d80IrCE3NFB2BkN8UhF9ULX0QrduD+DhcTAD+3brh264dJ7du9bakmnOIu+66iwsvvJClS5fWGdsoIiKCwYMHY7FYKh3ftGkT3bp1Iz4+Hn9/f6699lr+85//APCf//yHadOmATBt2jQ++eSTavWWlJQwatQokpKS6N+/v6NsRkYGvXv35pZbbqFv376MGTOG0tJSAFJSUpg9ezZDhgyhR48efPvtt4ChrB544AFHCO5//etftbbhTEZGBv369QPgzTff5Morr2TcuHF0796dBx980JFv0aJF9OjRg5SUFG655RbuvPPOanV98803JCYmkpiYyMCBAykuLmbOnDl8++23JCYm8o9//KNGWdeuXcvIkSO54oor6NOnD7fddhsVFRXYbDamT59Ov3796N+/v0dmYutQGy2FosPQKRnr4WMggl94zWGK8fGF1uGVXEwiQmD/fpyqEuZAc+bw7KZnSctL82idvcJ6MXvI7AaXX7JkCVu3bmXx4sU88sgjjB8/nptvvpkBAwa4Xcfhw4fp3LmzYz8mJoaNGzcCkJ2dTZRpLUdFRTliFTkTGBjIxx9/TJs2bTh+/DjDhg1j4sSJAKSnp/Puu++ycOFCrr76apYvX87UqVMBsFqtbNq0iZUrV/L444/zv//9j0WLFhEaGsrmzZs5ffo0w4cPZ8yYMXTu3NllG1WD6jmzfft2tm3bRkBAAD179uSuu+7C19eXJ554gh9//JGQkBAuuugil9fqueeeY8GCBQwfPpySkhICAwN55plneO655/jvf/8LwGuvveZSVjCU7s6dO+natSvjxo3jo48+Ii4ujsOHDzvmWHgiXLi2IFoCSjlcTLa8fHzbtq15DoSd4I6VXEwAgX36cHrvXirq+NLTaOrDoEGDWLBgAampqXTr1o0hQ4bw/PPPu13e1cCJ2l68rso/9NBDJCQkcPHFF3P48GFH+O+4uDgSExMdcjqHC7/yyiurHV+9ejVvv/02iYmJDB06lNzcXNLT02ttoyZGjRpFaGgogYGB9OnThwMHDrBp0yZ+//vfExYWhsVi4Y9//KPLssOHD+fPf/4z8+fPp6CgAD+/6t/qNckKRqjy+Ph4fH19mTx5MuvXryc+Pp59+/Zx11138cUXX9CmTRu3r3FNaAuiJXAyF2xl0KYTtryd+LoTWym4QyULAjCiv9psnN69m1b1+MLTtAwa86XfUBYsWMDChQsBYyW1G2+8kezsbJKTk3n99dcB40t85cqVvPHGG6SnpzN37lzHV7o7xMTEcOjQIcd+ZmYm0eYw7o4dO5KVlUVUVBRZWVlERERUK7906VKOHTvG1q1bsVgsxMbGOtxdVUN2211MzmnOYcSVUrz44ouMHTu2UhtvvvlmjW3URGPChc+ZM4cJEyawcuVKhg0bxv/+979qeWqSde3atS7Dhbdr146ffvqJVatWsWDBAt5//30WL17sljw1oS2IloA9dHebaKx5ee4F3wvuCCVVLIiePQE4vfdXT0uoOUu54447HOG7o6OjWbVqFdu3b3coh+eff54ePXqwfPly7r33Xn755Rdmz57t8kVeE4MHDyY9PZ39+/dTVlbGe++953ARTZw4kbfeeguAt956i0mTJlUrX1hYSEREBBaLhTVr1nDgwIEGn+/YsWN55ZVXKC8vB2DPnj2cOHHCY20MGTKEb775hvz8fKxWK8uXL3eZ79dff6V///7Mnj2b5ORk0tLSXIYLdyUrGC6m/fv3U1FRwbJlyxgxYgTHjx+noqKCP/zhDw43V2PRFkRLoOiI8dumE7a8PAJ69Ki7TJBpQSgF5teEpVMnxGKhbP8+LwqrOZdISEhg+/btbrkrjh49SnJyMkVFRfj4+PDCCy+wc+dO2rRpw+I6tp4AACAASURBVEsvvcTYsWOx2WzMmDGDvuZaJ3PmzOHqq69m0aJFdOnShQ8++KBavVOmTOGyyy4jOTmZxMREevXq1eDzufnmm8nIyCApKQmlFB06dOCTTz7xWBudOnXioYceYujQoURHR9OnTx9CQ0Or5XvhhRdYs2YNvr6+9OnTh0suuQQfHx/8/PwYMGAA06dP55577nEpKxgr2s2ZM4eff/7Z0WH9888/c+ONN1JRUQHA008/3eDr5EAp5bUNGAfsBvYCc1ykCzDfTN8BJDmlZQA/A9uBLe60N2jQIHVGsmmhUo+2UarwiNo9ZKg68thjdZfZMN8oU1pY6fCvl16qDs663UuCajzNzp07m1sEjYcpLi5WSilVXl6uLr30UvXRRx95tP41a9aoCRMmNKisq+ettver11xMIuILLAAuAfoAk0WkT5VslwDdze1W4JUq6RcqpRJVDbHKzxqKjoD4ogLDsBUW4tfODReTfTZ1lY5q/9g4yvZpC0KjaS4ee+wxEhMT6devH3FxcVx++eXNLVKD8aaLaQiwVym1D0BE3gMmATud8kwC3ja12A8i0lZEopRSWV6Uq+VRlAUhkdiKDP+jW53UrcON35O50P53jsP+8fEUr1mDKi9HqoxH12g03qfqLHJPk5KSQkpKilfbsOPNTupOwCGn/UzzmLt5FLBaRLaKyK01NSIit4rIFhHZcuzYsZqytWxKsiG4I9a8PAD8wtrVXSbIVBBVLIiA+DiwWik7dMhFIY1Go3EfbyoIVwOdq44Bqy3PcKVUEoYb6g4RGemqEaXUa0qpZKVUcocOHRoubXNSkm1YEHlGWAO3LIiaXExxcQDazaTRaBqNNxVEJtDZaT8GOOJuHqWU/TcH+BjDZXV2UnwUgiOw5RsWhK9bfRCuLQi7gji9b79HRdRoNOce3lQQm4HuIhInIv7AtcCnVfJ8CtwgBsOAQqVUlogEiUgIgIgEAWOAM2ONvvpiK4eTxyE4sn4uJr8ACAiFE8crHfYNCcG3Qzhl+7WC0Gg0jcNrCkIpZQXuBFYBu4D3lVKpInKbiNxmZlsJ7MMY5roQuN083hFYLyI/AZuAFUqpL7wla7NitwBCOv7mYmrb1r2yQeHVLAgA/5jOlB8+7CkJNZoaWbduHUlJSfj5+VWLdPrWW2/RvXt3unfv7pgMB7B//36GDh1K9+7dueaaaygrK2tqsWvFOSjfli1buPvuu73W1vbt21m5suUu9OXVmdRKqZVKqR5Kqd8ppeaZx15VSr1q/q2UUneY6f2VUlvM4/uUUgPMra+97FlJ8VHjNzgSW34evqGh7o8+CurgUkFYOnXS60JoGkVZWZlj1m5tdOnShTfffJPrrruu0vG8vDwef/xxNm7cyKZNm3j88ccdocNnz57NvffeS3p6Ou3atWPRokVeOQdPkJyczPz5871W/zmtIDRuYI+nFNwRa16+ex3UdoLCq7mYACwxnSjPzkaZ8Wc0GnfZtWsX9913Hz179mTPnj115o+NjSUhIQEfn8qvklWrVjF69GjCwsJo164do0eP5osvvkApxddff+1YeKemEN8ZGRlccMEFJCUlkZSUxHfffQcYcYhSUlK46qqr6NWrF1OmTHHEP4qNjeXRRx91hOxOSzMi4544cYIZM2YwePBgBg4cWClcuKs2nFm7di2XXnopYMxvmDFjBikpKcTHx1dSHE888QS9evVi9OjRTJ482eVQ1w8++IB+/foxYMAARo4cSVlZGY888gjLli0jMTGRZcuW1Sjrm2++yaRJkxg3bhw9e/bk8ccfd5zbhAkTGDBgAP369WPZsmV13rP6oENtNDd2BRHSEVteXj0VRAc4tLHaYUunTmCzUX70KP4xMR4SVONtjj71FKd3eTbcd0DvXkQ+9FCteU6cOMH777/PokWLUEpx4403smPHDkJCQhrcrqsQ34cPHyY3N5e2bds6opfaj1clIiKCL7/8ksDAQNLT05k8eTJbtmwBYNu2baSmphIdHc3w4cPZsGEDI0aMACA8PJwff/yRl19+meeee47XX3+defPmcdFFF7F48WIKCgoYMmQIF198ca1t1ERaWhpr1qyhuLiYnj17MmvWLH766SeWL1/Otm3bsFqtJCUlMWjQoGpl586dy6pVq+jUqRMFBQX4+/szd+5ctmzZwksvvQTAQw895FJWMOIv/fLLL7Ru3ZrBgwczYcIEDhw4QHR0NCtWrACMuFWeRCuI5qbYVBBBxigm/9hY98sGdTAmylXYjDUiTOxKoTzzsFYQmjqJiooiISGB119/vVFxjpyxf9U7IyJuh/4uLy/nzjvvZPv27fj6+layZoYMGUKM+VwnJiaSkZHhUBDOIb4/+ugjwAib/emnnzq+6k+dOsXBgweJjo6usY2amDBhAgEBAQQEBBAREUF2djbr169n0qRJtGrVCoDLLrvMZdnhw4czffp0rr76aoecValJVoDRo0fTvn17x3muX7+e8ePHc//99zN79mwuvfRSLrjggjrPoT5oBdHclBw1Vojz88eam0ergUnulw0KB1UBpfm/DXvFtCCA8sOZwFAPC6zxFnV96XuLDz/8kEWLFnHFFVcwefJkpk2bRteuXQHYuHEjM2fOBIwv4I0bNzq+Vrdv315jnTExMaxdu9axn5mZSUpKCuHh4RQUFGC1WvHz86sU+tuZf/zjH3Ts2JGffvqJiooKAgMDHWmuwmxXTasa4nv58uX0NKMd23nsscdqbKMmGhPi+9VXX3Vcv8TERJfXryZZN27c6DLEd48ePdi6dSsrV67kL3/5C2PGjOGRRx5xSx530H0QzU2xMYtaVVRgKyjA150hrnYccyEq90NYIiPBx0ePZNK4xZgxY1i2bBnr168nNDSUSZMmcfHFF5ORkcHQoUMd4cAnTpzIvHnzHPu1MXbsWFavXk1+fj75+fmsXr2asWPHIiJceOGFjhFPtYX4joqKwsfHh3//+9/YbLYGn9/YsWN58cUXHS/ybdu2ebSNESNG8Nlnn3Hq1ClKSkocCrQqv/76K0OHDmXu3LmEh4dz6NAhlyG+XckK8OWXX5KXl0dpaSmffPIJw4cP58iRI7Ru3ZqpU6dy//33eyTEtzNaQTQ3ZpgNW2EhVFS4txaEnRpmU4u/P34dO1KmRzJp6kH79u2555572L59O0899RS+da1qCGzevJmYmBg++OADZs6c6QjjHRYWxsMPP8zgwYMZPHgwjzzyCGHms/3ss8/y/PPP061bN3Jzc7npppuq1Xv77bfz1ltvMWzYMPbs2UNQUFCDz+vhhx+mvLychIQE+vXrx8MPP+zRNgYPHszEiRMZMGAAV155JcnJyS5DfD/wwAP079+ffv36MXLkSAYMGMCFF17Izp07HZ3UNckKhiK6/vrrSUxM5A9/+APJycn8/PPPDBkyhMTERObNm8ff/va3hl2kmqgpzOuZuJ2R4b6f76vURzPVqb171c6evVTBp5+5XzZ7pxHy++fl1ZIypkxV+6+b4kFBNd5Ah/s+O7CH+D5x4oQaNGiQ2rp1q0frf+ONN9Qdd9zR6HrqG+5b90E0J0r9ZkGYs6jr52KyWxAuhrp26sSJH37whJQajaYObr31Vnbu3MmpU6eYNm0aSUn16EtswWgF0ZyU5htrUZtzIID6uZhatQPxqWGyXDTWnBwd9lujaQLeeecdr9Y/ffp0pk+f7tU2XKH7IJoT5zkQ9kB9Ye3dL+/ja4yAcqEg/CIjQSmsOTmekFTjRZSbo2A0msbQkOdMK4jmxCnMhiNQXzs34zDZqSncRlQUAOXZ2Y0SUeNdAgMDyc3N1UpC41WUUuTm5ro1lNcZ7WJqThwWRCS2vLX4hIQg/v71q6OGcBt+HTsCUJ51bi3Od6YRExNDZmYmZ+xiV5ozhsDAQMcEQ3fRCqI5cVgQEWaYjXp0UNsJ6gBHqo9Jt1sQ1qNHGyOhxstYLBbizDU8NJqWhnYxNSclOWAJgoAQrPl5+LmzUFBVgjq4tCB8Q0LwCQqiPEsrCI1G0zC0gmhOSo5CiOEKstU3kqud1uFwuhCsp6sl+UVFUn5Uu5g0Gk3D0AqiOSnOhuBIgEa4mMxwGydzqyVZIqOwagtCo9E0EK0gmpMSYy1qpRTW/PyGu5ighpFMkXoUk0ajaTBaQTQnJTkQEklFURFYrQ1zMdWiIPw6RmI7fpyKFrako0ajOTPQCqK5KDsJp4vMWdTmHIjGuJhchduIMtxXVm1FaDSaBqAVRHPhPAfCXKu3XrOo7dRmQUQaCkLPhdBoNA1BK4jmwrEWdUTDAvXZCQgB34BaZ1PruRAajaYhaAXRXDgUhLOLqQF9ECI1zoWwOCwIrSA0Gk390QqiuSgxg+gFR2LLs7uYGqAgwAy3Ud2C8GndGp/QUKzZWkFoNJr6oxVEc1F8FMQXWodhy88zXuZO693WixoC9gFYOnbUFoRGo2kQXlUQIjJORHaLyF4RmeMiXURkvpm+Q0SSqqT7isg2EfmvN+VsFkqyjRe7jy/Whs6itlNDwD6wz6bWCkKj0dQfrykIEfEFFgCXAH2AySLSp0q2S4Du5nYr8EqV9HuAXd6SsVkpyXEKs5HnAQVxzFihrgrGbGo9ikmj0dQfb1oQQ4C9Sql9Sqky4D1gUpU8k4C3zaVRfwDaikgUgIjEABOA170oY/NRchSCDQVhBOprwAgmO0EdwHoKyk5US7JERWIrKKCitLTh9Ws0mnMSbyqITsAhp/1M85i7eV4AHgQqamtERG4VkS0isuWMiqlfkgPBEUAjAvXZMRWNY2SUE465ENrNpNFo6ok3FYS4OFbVB+Iyj4hcCuQopbbW1YhS6jWlVLJSKrlDhw4NkbPpqagwFUQkSqmGB+qzE2IoAYqOVEuyRJpzIfRsao1GU0/qVBAi0tBP20ygs9N+DFD1DVZTnuHARBHJwHBNXSQiSxooR8vjZC4oGwR3pOLESVRZGX4NmUVtJyTa+C2u3tdgD7ehRzJpNJr64o4FsVFEPhCR8SLi6ou/JjYD3UUkTkT8gWuBT6vk+RS4wRzNNAwoVEplKaX+opSKUUrFmuW+VkpNrUfbLZtKs6iNMN2NcjG1MawEVxaEfelRq14XQqPR1BN3FEQP4DXgemCviDwlIj3qKqSUsgJ3AqswRiK9r5RKFZHbROQ2M9tKYB+wF1gI3N6AczjzKDG/5kMiHWE2GhSoz05ACPiHuLQgfAID8W3XTlsQGo2m3tS5JrVSSgFfAl+KyIXAEuB2EfkJmKOU+r6WsisxlIDzsVer1H1HHe2vBdbWJecZhWMWdQTWvQeARloQYFgRLiwI0CvLaTSahlGnghCR9sBUDAsiG7gLwzWUCHwA6BXX64tTHCZb/jYAfBuyWJAzIVEuLQgwOqrLDx1ymabRaDQ14Y6L6XugDXC5UmqCUuojpZRVKbUFeLWOshpXFGcbLiH/oMatBeFMm05QVJOC0LOpNRpN/anTggB6mq6gaiilnvWwPOcGJdmV5kBIYCA+rVs3rs42UUbfRkUF+FTW+35RkVQUF2MrOYFvcFDj2tFoNOcM7lgQq0WkrX1HRNqJyCovynT2U5LjmNzW6DkQdkKioMLqel0I+1wIN/ohKlQFaw+t5T97/0NWie630GjOZdyxIDoopQrsO0qpfBGJ8KJMZz8lRyGyP2APs9HI/geANva5EEccMZ7sOOZCHM0moFu3Gqs4UX6CW7+8lR3HdgDQyq8VT414iou7Xtx4+TQazRmHOxaETUS62HdEpCvVZ0Rr6kMlC6KRYTbshNQyF8INC0Ipxex1s0k9nsrc8+eyfOJyurftzv3f3M9Px35qvHwajeaMwx0F8VdgvYj8W0T+DawD/uJdsc5iyk7C6SKnPoi8xndQA7Q1dXjBwWpJlogOIFLrXIgvD3zJN5nf8MDgB7ii+xX0aNeDV0a/QmRQJLPXzeZk+cnGy6jRaM4o6lQQSqkvgCRgGfA+MEgppfsgGopjiKvh9rHm5+PbmDAbdlq3h4A2kLevWpL4++Mb3r7GuRDWCisvbnuRbm27cW3Pax3H2/i34cnhT3K45DBLdy1tvIwajeaMwt1gfQFAHlAI9BGRkd4T6SzHMUmuIxWlpajSUs90UotAWBzk7XeZbKwL4dqC+Prg12QUZXBn4p34+vhWSkuOTCalcwqLf1lMwakCl+U1Gs3ZiTvB+p4FNmC4mh4wt/u9LNfZi1McJmuufQ6EB/ogANrFubQgoPa5EB+lf0RkUCQpnVNcpt898G5KyktYtnuZZ+TUaDRnBO5YEJdjzIWYoJS6zNwmeluwsxa7ggiJ/C1QX3sPuJgAwuKh4ADYrNWS7EuPVp3ScqTkCN8d+Y4rul1RzXqw071dd0Z0GsG7ae9SZivzjKwajabF446C2AdYvC3IOUNJNogPtG6P9bihIPw8piDijLkQRZnVkiyRUaiTJ6koKqp0/PP9n6NQTOpWdbG/ytzQ5wZyT+XyRcYXnpFVo9G0eNxRECeB7SLyLxGZb9+8LdhZS0m2sUSojy/W3OOAJxVEvPHrws3021yIym6mrw9+TZ/2fegUXHWxv8oMixpG1zZd+Sj9I8/IqtFoWjzuKIhPgSeA74CtTpumIRRn/zYHItcLLiZw2VHtWHo067eRTDknc9hxfAejuoyqs2oR4fJul7M1eysHig54Rl6NRtOicWeY61sYw1t/UEq9Zd+8L9pZSslvCsJ6PBefkBB8AgI8U3dwJPi1qsGCsE+W+23p0bWH1gK4pSAAJv5uIj7iwyd7P2m8rBqNpsXjziimy4DtwBfmfqKIVF0ZTuMuJTmOUBi2vFzPuZfACNIX3h1ydlVL8uvQAXx9K82F2HB4A52COxEfGu9W9RGtI7ig0wV8uvdTrBXVO8I1Gs3ZhTsupseAIUABgFJqO3oNiIZRUQEncipZEB5zL9np2A+yf6l2WHx98evQwTEXwlphZdPRTQyLGkZ9VpK9otsV5JTm8N2R7zwmskajaZm4oyCsSqnCKsd0LKaGUJpnjDKyK4hcD1sQAJH9DDdWiauorr/Nhfjl+C+UlJcwLHpYvaofGTOSsMAwPk7/2CPiajSalos7CuIXEbkO8BWR7iLyIkaHtaa+FJsjiOxxmI4fxy/c0wrCiBJLVvUAe85Lj/6Q9QOCMCyyfgrC4mvh0vhLWZu5lvxT+Y0WV6PRtFzcURB3AX2B08C7QBHwJ28KddZiVxAhUajycmyFhZ53MUUnGfMsMjdVS7JERmE9mo1Siq3ZW+nRrgdtA9u6qKR2JnWbhLXCyop9KzwhsUajaaG4M4rppFLqr0qpwUqpZPPvU00h3FmHfc3okCisecbXt8ddTAHBENEXDrlQEFGRqNOnKcs9zo5jO0iMSGxQEz3a9aBP+z56NJNGc5bjziimNSLyddWtKYQ763AoiEhs5iQ5j1sQAF3Ph4M/QHlppcP2uRD70zdz0nqywQoC4PJul7M7fzdpeWmNElWj0bRc3HEx3c9vQfoexhjyusWbQp21FGcZYbn9ArDm2sNshHu+nR5jwVoK+76pdNg+F2L/ns0AJHZouIIYHzcei49FWxEazVmMOy6mrU7bBqXUn4GhTSDb2UdRlmPlN0ccJk93UgPEjgD/YNjzeaXDFtOCyMnYSfvA9nWG16iN0IBQLupyESv2raDcVt4ocTUaTcvEHRdTmNMWLiJjgUh3KheRcSKyW0T2isgcF+lixnbaKyI7RCTJPB4oIptE5CcRSRWRx+t9Zi2RYmcFYQxD9XgfBIBfAPzuItizyph7YeLbvj1YLJQcPkBiRGK95j+44vJul1NwuoC1mWsbKbBGo2mJuONi2orhUtoKfA/cB9xUVyER8QUWAJcAfYDJItKnSrZLgO7mdivwinn8NHCRUmoAkAiME5H6jcdsiRRnQYi5klx2Dj7BwfgEBXmnrd4TjfYy1jkOiY8PPhHhWI4XNcq9ZOe8qPOIaBWh3UwazVmKOy6mOKVUvPnbXSk1Rim13o26hwB7lVL7lFJlwHtA1ZjSk4C3lcEPQFsRiTL3S8w8FnM7syfn2axGmI020QBYs7Px69jRe+31vszo79i0sNLh0nataV+sGtVBbcfXx5eJ3Say4fAGjp6oeb1rjUZzZuKOi+nK2rZainYCDjntZ5rH3MojIr4ish3IAb5USm1054RaLCXZgHJYEOU52Vi8qSAsgTDweti9Egp/Wx8itw2EFwm92/f2SDNX9bgKhdKrzWk0ZyHuuJhuAhYBU8ztdWAqcBlwaS3lXDm4q1oBNeZRStmUUolADDBERPq5bETkVhHZIiJbjh2rHl6ixeCYJGe3IHK8a0EAJM8wfjcvchw6EHiS9iXgL55ZA6pTcCcu7HwhH+75kFJrad0FNBrNGYM7CkIBfZRSf1BK/QFjVjVKqRuVUjNqKZcJdHbajwGO1DePUqoAWAuMcymcUq+ZE/iSO3To4MbpNBPF5mmFRKJsNqzHjuHXMcK7bbbrCr0mwNY3oOwktgobe/xz8bUprMePe6yZ6/tcT8HpAr2YkEZzluGOgohVSmU57WcDPdwotxnoLiJxIuIPXIux+JAznwI3mKOZhgGFSqksEekgIm0BRKQVcDFwZs/IslsQbaKNIa42m3ddTHaGzoLSfNixjANFBzgabITpth71XJ/BoI6DSIpIYvEvi/Wa1RrNWYQ7CmKtiKwSkekiMg1YAaypq5BSygrcCawCdgHvK6VSReQ2EbnNzLYSY83rvcBC4HbzeBSwRkR2YCiaL5VS/63PibU4io6A+ELrcKw5xqI9XncxgTGrOjIBNr7Krtyd5IYYXr3yLM92Kt824DZyTuawLG0ZOcWnKDltRakze1yBRnOu41dXBqXUnSJyBTDSPPSaUsqtWM9KqZUYSsD52KtOfyvgDhfldgAD3WnjjKH4qNFB7eODNbsJFYQIDJsFn8wiLeNritr6A6VYj2bVWbQ+hKjedPDrz/9teomHlwZCRWv8fX24uE8E1w+LZVh8WKPnXWg0mqbFHQsC4EdghVLqXmCViIR4Uaazk+Ijjkly5aaCaBIXE0CfSWBpza7srURGd0MCAjxmQZRZK3j+yz1MWvAdR/ePAZ9ShiVv4KHxvZg8pDPf/ZrL5IU/cMPiTRwvOe2RNjUaTdPgzjDXW4APgX+ZhzoBemZUfbFbEJjrQlss+IaFNU3b/kGo7mNJO51L77BelRYOagyFJ8v547++Z/5X6UxKjOb7+6ZwS/+bSS3+im6xB3h8Uj9++MsoHrusD5v25zH+n9+ycV+uB05Io9E0Be5YEHcAwzHWgUAplQ54efjNWUhR1m+T5HKy8esQjvi4a8A1nuweoyj0EXpV+OIXFYU1q3EupuJT5dzwxiZ2HSliwXVJPH91IqGtLMwaMIveYb15aP1D7M3fS6DFl+nD4/jkjuEEB/hx/eJNfPer50ZQaTQa7+HOG+q0ORMaABHx40yf1dzUlJ2A04W/TZLLzsES0UTuJZNdoYZO75WXiaVjR4ebqyGcKrdx05tbSD1cyIIpSUxIiHKkWXwtzL9oPq38WjHzy5nsK9gHQO+oNiyfdT6x7Vtzy1tb2HZQr0an0bR03FEQ34jIQ0ArERkNfAB85l2xzjKKzDkQbWIAKD98GEt0dJOKkFa4DwF6HNqOX1Qk1pwclNXaoLqeXrmLTRl5/OOaREb3qa7oIoMiWTh6ITZlY+rKqXyR8QUA7YL8WXLTUNoHBzD9jc0czD3ZmFPSaDRexh0FMQc4BvwMzMQYlfQ3bwp11lFoRhMJ7YSy2SjPysISE9OkIuzK20VXSyitj+/BEtoKKiqwNmDm+erUo7z1/QFuHhHHZQNqVnLd2nVjyfglxIXG8cA3D/DwhocpLismok0gS24ailKKO975kdNWW2NOS6PReJFaFYQZkfVtpdRCpdQflVJXmX9rF1N9KDxs/IbGGBPUrFYsMQ1fi6Eh7M7bTe/2RjBdizI6qMvr2Q+RVVjKg8t30L9TKA+O61Vn/piQGN685E1u6X8Ln/76KZd/cjlfHfiKLu1b8/c/DuDnw4U8vfLMnv+o0ZzN1KoglFI2oIM5E1rTUIoOAwIh0ZRlGsrCvwktiMLThRw5cYRe0UMhKAK/U7uB+iuIxz5N5XR5BfMnD8Tfz70OdouPhbuT7mbp+KW0C2zHn9b+iYe+fYgLerRhxvA43vwugy93Nrw/RKPReI86J8oBGcAGEfkUOGE/qJR63ltCnXUUHoLgjuDnT3mmEVm1KV1M9nWje4X1hi7DsBz8CaBeI5m+2XOMVanZPDiuJ3Hh9V/Dol94P9699F0W7ljIqz+9yt6CvfwzZQHf/Xqchz/5hWHxYYQEeiaAoEaj8Qw1fgaKyL/NP68B/mvmDXHaNO5SeBhCDZdS+eFM8PFxrA/dFDgURPteEJOM74kD+IQEU36kauxE15RZK3j801TiwoO4aURcg+Ww+Fi4PfF2Xhr1EhlFGcz66hb+NjGW7OJT/N8Xuxtcr0aj8Q61+QkGiUhX4CDwootN4y6FmdDGUBBlmZn4RXZELE33tbwrbxcRrSMICwyDmMEAWNq3ofyIexbE4g372Xf8BI9e1ocAP99GyzMyZiQLRi3gYPFBFu5+mBvOi2HJxgNsychrdN0ajcZz1KYgXgW+wIjcusVpsy9BqnEHpYw+iFAjqnl55mH8OzXtCKbdebvpHWYuEBSVCOKLJUTc6oMoLC3n5TV7GdUrgpSenpsfOThyME8Of5Ifc34kMGIV0aGteOQ/qdgq9PgHjaalUKOCUErNV0r1Bt4wlxy1b3FKqfgmlPHMpjQfyk/+5mLKzGzS/odT1lPsL9xPrzBz1JF/a+jYB4v/CbdcTIu+3UfRKSv3jenpcdnGx4/n6h5X887uf3PNBeXszCpi+dbMugtqNJomwZ01qWc1hSBnLfblPkNjqDh9GmtOTpMOcU3PT8embL8pCIBOyVjIoaK4hgLXFAAAIABJREFUGFtxcY1l80+UsXhDBuP7R9Inuo1X5Lsv+T6ig6L5MuclErsE8ffVuzlxumET+DQajWdpumBA5ypF5hyINjGUHzImzPl36dJkze/K2wVQWUFEJWAJKAFqH+r6r3X7OFFm5U8Xu7M+VMNobWnNX4f9lYyiDIYkpHGs+DSvfvOr19rTaDTuoxWEt3GyIE7v3w+Af2zDRwLVl7S8NEL8Q+gU7GS1dOyHX2tjBnNNbqb8E2W89V0GEwdE06OjdwetjYwZyfDo4fz30NuMS2jDwm/3kVN8yqttajSautEKwtsUZoKPBYI6ULY/AwD/uNgma3533m56hfWqvFhPRG8spoKoaS7Ekh8OUFpu4/aUbk0hJvcOupfismK6xP5IuU3x8hptRWg0zY1WEN6m6LAR5tvHh7L9+/Hr0AHf4OAmadpWYWNP/h56tqvSwRwQgl90Z/AVl0NdT5XbeOv7DC7s2YGekU0z5aVnWE9SYlJYefADLh8YzjsbD3KkoLRJ2tZoNK7RCsLbFGY6hriW7d+Pf1zTuZcyijI4ZTtF7/a9q6VJZH8sQa77IJb/mMnxkjJuHfm7phDTwU39b6LwdCGx8T8D8OLXe5u0fY1GUxmtILyN0yzqplYQLjuo7XTshyXwNOWHD1U6bKtQvP7tfhJiQhkW30Qr3pkkRiSS3DGZT/a9w9WDI/lgyyEO5emQ4BpNc6EVhDexlTsmyVnz87EVFjZ5/4O/jz9xoS6UUsc+WFpbjdAfTqxJy2H/8RPcOjK+cr9FE3Fz/5vJOZlDt/h0RGDht/uaXAaNRmOgFYQ3KcwEZYOwOMr2GS+6gCa2ILq3647Fx0VYj/Ce+LW2YT2WV2nhoLe+zyAqNJBxfSObTE5nzo8+n25tu/HFwY+4cmAMyzYf4ljx6WaRRaM519EKwpvkZxi/bbtSZh/i2kQKQilFWl6aa/cSQFg8liAFSmE1lx/99VgJ36YfZ8rQ/9/eeYfHVV17+10ajXrvlqxqy93GxsbYYGO6jQ2YEpL4hoSACUmAEFJuICTky73JvQnJzb3pQOgQIJRQTAk2GHAB915k2VavVu/S1P39cY5lWZZklSkS7Pd55pmZvfc5+zcjzVlnl7VWBoEW//xriAg3TbqJQ/WHuHS2HbvLzdOfFvlFi0bzeUcbCG9y0kDEZmErKkKsVqxpvvGirm6vptnW3L+BCAzCmpIInFqofm5LCUGWAL4833eOfH1xzYRrCA0MZUvN21w1I4Vnt5TQ2uXwqyaN5vOINhDepKnE8IGISsVeVIw1MwOxjDwa6mAYcIHaxJphjGYcVVW02Zy8uqucFbPGkRAR7BON/REZFMmyrGW8W/Qut1w4jtYuJ3/fWupXTRrN5xGvGggRWSYi+SJyXETu76NeROSPZv1+ETnXLE8XkY9EJE9EDonId72p02s0FkNMBgRYsBcV+XT9Ib8hH0GYFNt/mAxrtpGC1FFezut7KmizOfnawkxfSRyQL07+Ip3OToq7NrE4N4EnNhfR5dD5qzUaX+I1A2Hms/4LcBUwDVglItN6NbsKyDUfdwAPm+VO4AdmNNkFwF19HDv6aSyG2CyUw4G9rIygbN8Fwc1ryCMzKpMwa1i/bQLSpmEJduEoPsoL20qZNi6K2ekxPtM4ENPjpzM1biqvHnuVby+ZQF2bjVd1pFeNxqd4cwQxHziulCpUStmBfwAre7VZCTyrDLYCMSIyTilVpZTaDaCUagXyAN+FQPUUjcUQm4m9vBycTp/6QBxpOHIqB0R/JEzCGuaipbCAvKoWVp2f4ZetrX0hIqycuJIjDUdIiGvgnPQY/raxEKfL7W9pGs3nBm8aiDSgpxdWOWde5M/aRkSygDnAtr46EZE7RGSniOysra0doWQP0tVs5IKIzeqOwRScneWTrpu6mqhqrzJSjA5EQi6BYS66KqoJtVpYOTvVJ/oGy1XZVxEogbxd9DbfXjKB0oYO3jkw+DzaGo1mZHjTQPR1K9o7XdiAbUQkAvgncK9SqqWvTpRSf1NKzVNKzUtMTBy2WI/TWGI8x2b5fIvrkUYzB/UAC9QAhMZgjbZiaWnnmlkpRIX4Lg3qYIgLiWNR2iLeKXiHy6YkMCExnMc2FaKUzjqn0fgCbxqIciC9x/vxQO/Y0v22ERErhnF4Xin1mhd1eoceW1ztxUVY4uKwREf7pOv8hnxgEAYCsEdHY3G6+fK0WG/LGhbXTLiGms4adtRsZ/WiHA5WtLCtSOeu1mh8gTcNxA4gV0SyRSQI+DKwplebNcDXzN1MC4BmpVSVGBPhTwB5Sqn/9aJG79HLByIoK8tnXec15JEUlkRcyNljKVUGGZnipgaMzphHS9KXEGmN5K2Ct7jh3DRiw6w8vkk7zmk0vsBrBkIp5QTuBtZiLDK/rJQ6JCLfEpFvmc3eBQqB48BjwJ1m+YXAV4FLRWSv+VjuLa1eobEYQmMhJBp7cYlPYzDl1ecxLe7sm76OnmglzxIPgLO87Cyt/UOwJZil2UtZX7oeNza+uiCT9UdOUFjb5m9pGs1nHq/6QSil3lVKTVJKTVBK/ZdZ9ohS6hHztVJK3WXWz1RK7TTLNyulRCk1Syk123y8602tHqexGGIycbW24qqr89kIosPRQVFzEdPiz24g/rmrnIIwY0+Ao/Cwt6UNm2tyrqHT2ckHpR9w88JMrAEBPPVJsb9laTSfebQntbdoKDSC9BUbi9W+MhD5jfkoVJ85IHridLl5bU8FEbmzkQCFo/iYT/QNhzlJc0iLSGNNwRqSIkNYOTuVV3aV0dRh97c0jeYzjTYQ3sBpM8JsJEzCXlwMQLCPDMThemMkcDYfiI3HaqlttXH+vPOwhjtxlI3eUBYiwjUTrmF71Xaq26tZvTibLoeb57eNXs0azWcBbSC8QUMhKDfE5xoGQgRrhm8C4OXV5xEfEk9SWNKA7V7dVU58eBCLzpmCNQrsVTU+0Tdcrs65GoXivaL3mJISxeLcBJ75tBi7UzvOaTTeQhsIb1B31HhOMAyENTWVgGDfBMA73HCYqfFTB/SIbmy388HhGlbOTsMaaCEoIQJH/ehe9M2MymRG/AzeKXoHgNWLsqlptfH2/t47pzUajafQBsIb1Jnz+fETsZeU+Gz9ocvZRWFT4Vmnl9bsq8TucvOFueMBsKYk4e5y42pu9oXMYbMiZwVHGo5Q0FTAkkmJ5CZF8PimIu04p9F4CW0gvEHdMYhMRQWFYy8u9pmBONp4FJdyMT1++oDtXtlVxvTUKKalGj4Q1nTDV9FeUuxtiSNiWfYyAiSAdwrfQURYvSibw1UtbCms97c0jeYziTYQ3qD+GCTk4qqvx93W5jMDkVdv5IAYaAdTXlULBytaukcPAEE5kwFwHNvvXYEjJCE0gfNTzufdondRSnHdnDTiwoN4crN2nNNovIE2EJ5GKag73r3+AL7b4prXkEdMcAzjwsf12+afu8qxWoSVs0/FRLROOgcAx/HR6wtxkuU5y6loq2B/3X5CrBZuXpDJB3k12nFOo/EC2kB4mtZqsDWftsXVV17Uh+sPMzWu/wVqh8vNG3sruGxKMnHhQd3llvHTsAS5sJeM/jvxyzMuJyggiHcKjcXqry7IJMgSwJOfjH7tGs1YQxsIT1NzyHhOmoa9uNjIQz2u/zt6T2Fz2TjWdGzA6aWP82upa7OfNr0EQFQq1kg3jspqL6scORFBESxJX8La4rU43U4SI4O5bk4qr+4qp7FdO85pNJ5EGwhPc8Kcpkmejq3Yd3mo8+rzcLqdzEqY1W+bV3eVkRARxJLJvcKiB1gIig3BXtPkZZWeYUXOChq6GthatRWA1Yty6HK4eWG7dpzTaDyJNhCepuYwRKRAWJxPdzAdqDsAwMzEmX3W17fZWJ9Xw/Vz0rBazvyzW5NicTTZUK7Rn/d5cdpiIoMiebfQCM81OSWSxbkJPP1pMTbn6Nev0YwVtIHwNCcOQfI0lMuFo6TUZyE2DtQeICU8pV8P6jf3VuJ0K27sPb1kYk0bB25wVo/+aaYgSxBXZl7J+tL1dDo7Abh9cQ61rTbe3qczzmk0nkIbCE/ickJtPiRNw1FVhXI4fDaC2F+3n5kJfY8ewAitMTMtmikpUX3WB2VNAMA+BnYyASzPXk6Hs4MNZRsAuCg3wXCc26wd5zQaT6ENhCdpKASXzVigNvNQ+8JA1HfWU9FW0e/6w6HKZg5XtXDTvL5HDwDWiYZznePo6PaFOMnc5LkkhSV172YSEW5fnE1eVQtbCrTjnEbjCbSB8CQnjHUAkqef2uKamen1bs+2/vDKznKCLAFcMyu133NYc2eDKOxFR72i0dNYAixclXUVmys209RlLK6vnJ1GfHgQj2vHOY3GI2gD4Ukq94IlCJKmYi8uJiA8HEtCgte73V+7H4tY+kwSZHO6eGNvBVdMTya2h+9DbyRxAtZwF/aSsbMTaEXOCpzKybqSdQCEWC18dWEmHx6p4XiNdpzTaEaKNhCepGovJE2DwODuHUwDRVX1FPvr9jMpdhKhgaFn1L1/+ARNHQ6+NC994JNYQwmKtWCvqPWSSs8zJW4K2dHZvFt0KtngzQsyCQrUjnMajSfQBsJTKAVV+yB1NoDPtri63C4O1h3sd4H6pR1lpMWEcuHEs49kgpOjsdd1oNxjI8eCiLAiewW7Tuyiqs3YvZQQEcwNc9J4bXc5DdpxTqMZEdpAeIrGIuhqhnGzcdtsOCorfbL+UNRcRLujnVmJZy5Qlzd2sPl4HTfOHY8l4OwjmaDxKSinGhNbXU+yPHs5AP8q/ld32W2LjIxzL2wr8ZcsjeYzgTYQnqJyr/GcOhtHaSkoRVB2tte73V2zG4DZSbPPqPvnrgqUgpv68X3oTVBODgC2Y/meE+hl0qPSmZU4q3s3E8Ck5EiWTErk6U+L6XJoxzmNZrhoA+EpKveYC9TTsPkwiuvOEztJDE0kI/L0lKZut+KVXWVcODGe9LiwQZ0raLIxTWU/vMfjOr3J8uzlHG08yrHGY91ld148gbo2Oy/ovNUazbDRBsJTlG2HcbO7F6jB+1FclVLsqt7FvOR5ZyyGbymsp7yxky+ebXG6B4E5MwkIdGM/nudpqV5ladZSLGI5bbH6/Jx4zs+O45ENBXoUodEME20gPIHTZowg0ucDxgK1JTEBS0SEV7stay2jprOGuclzz6h7aUcZUSGBLJ2eMujzSVw2QZFO7MVja+4+ITSBBeMW8G7hu6d5UX/3slxqWm28vLPMj+o0mrGLVw2EiCwTkXwROS4i9/dRLyLyR7N+v4ic26PuSRGpEZGD3tToEar2GR7UGQsAsBeXEJyZ5fVud57YCcC8lHmnlTd3OHjvUDXXzUkjxDqESLJh8QTFCLYxtNX1JCtyVlDZXsne2r3dZQsnxDMvM5aHPy7QQfw0mmHgNQMhIhbgL8BVwDRglYj09uS6Csg1H3cAD/eoexpY5i19HqVsm/E8/tQIwhdJgnad2EVcSBw50Tmnlb+5rwK70z2k6SUARAhOjcbZ1IWrpcWDSr3PpRmXEmIJOW2xWkT47uW5VDV38fxWvRah0QwVb44g5gPHlVKFSik78A9gZa82K4FnlcFWIEZExgEopTYCDV7U5znKtkFsFkQm42ppwVVf75sF6uqdzE2ee8b6w0s7ypieGsWMtOghnzMk20hFassfOzuZAMKt4VycfjHritfhcDu6yxdNTOCCCfH8+aPjtHY5BjiDRqPpjTcNRBrQc/K33CwbapsBEZE7RGSniOysrfXD1IhSULoN0s3ppRJj/t7bBqKyrZLK9soz1h/2ljVxqLKFL503xNGDSfCkSQB0HTkyYo2+Znn2chptjXxS8Ul3mYhw37IpNLTbeWyT9q7WaIaCNw1EX55ZveMwD6bNgCil/qaUmqeUmpeYmHj2AzxNYzG015y2QA3eNxDd6w/Jp68/PLelhPAgC9fPGZKd7SYweyqWIDe2g3vP3niUsWj8IuJD4nnt2GunlZ+THsOKmeN4fFMhta02P6nTaMYe3jQQ5UDP29jxQOUw2oxuTq4/pJ8PYIT5DgjAmj68O/jBsrVyKzHBMeTG5naXNbbbeWt/Jdefm0ZkiHVY55W4HIJjHHQdGRt5IXpiDbBy7YRr2Vi+kbrOutPqfrh0Mnanm9+uHXsjI43GX3jTQOwAckUkW0SCgC8Da3q1WQN8zdzNtABoVkqNrZRgRZsgJMYI0ocxgrCmpREQ1H/k1JHiVm42V2zmwrQLCZBTf8JXdpVhd7q5ecEIQnzEZRMc48BWXDEm0o/25rrc63ApF2sKTv9Xy04IZ/WibF7eWc7u0kY/qdNoxhZeMxBKKSdwN7AWyANeVkodEpFvici3zGbvAoXAceAx4M6Tx4vIi8AWYLKIlIvIam9pHRFFGyF7MQQYX6WtuMjr00uH6g7RaGtkcdri7jK3W/H3raXMz4rrN2vcoIhOJyROoWwO7KVjb+dPTnQOc5Lm8Pqx18/ILPedy3JJiQrhwTcO4nLrrHMazdnwqh+EUupdpdQkpdQEpdR/mWWPKKUeMV8rpdRdZv1MpdTOHseuUkqNU0pZlVLjlVJPeFPrsGgshuZSyF4CGJ7N9uISrxuITRWbEIQLUy/sLttwtJbShg6+siBjgCMHQYCFkBwjsVDX/rGRXa43N+TeQHFLcXecqpNEBAfy06uncqiyhb9vHVvOgBqNP9Ce1COhaKPxnH0RAM4TJ1AdHV73gdhUvolZibOICYnpLntsUyEpUSEsnzluxOcPnjSZgCDo2D22YjKd5MrMK4mwRvBy/stn1K2YOY7FuQk89N4RSurb/aBOoxk7aAMxEoo2QkQyJBhbQ23HjGBxIbm5Ax01Iuo66zhYf/C06aVDlc18WlDP1y/MwmoZ+Z9UkiYTGmejc/euEZ/LH4RZw7hu4nWsK1lHbcfpW59FhIdunIUlQPjeS3txusZG7guNxh9oAzFclDIMRNZiMB3VbMeOAxA0caLXuv208lMAFo8/ZSCe2FREWJCFVfNHOL10koRJhCbYsB0vGHMe1SdZNWUVLreLV46+ckZdakwov7xuBrtLm3hkQ4Ef1Gk0YwNtIIZL3TFoO9E9vQTGCMKSmEBgbKzXut1Uvon4kHimxE0BoLq5izX7KvnivHSiQ4e3tfUMEnIJS7CDUnTu2+eZc/qYjKgMFo9fzMv5L2N3nZlZ7tpzUrl61jj+74NjbD5W18cZNBqNNhDDpWiD8dzLQAR7cfRgc9nYVLGJJelLure3PvlJEW6luO1CDyYnis8lJN4BInTs2Hn29qOUr0z5CvVd9awtXntGnYjw6xtnMTExgrte2E1RnV6P0Gh6ow3EcCnaCNEZRgwmQLnd2AoKCPbi+sMnFZ/Q7mjnyswrAahrs/HclhKuPSeVjPjBJQUaFMERWOJTCcuMpO2jjzx3Xh+zMHUh2dHZPHf4uTO2vIKxq+nxW+YRIHD7Mzt0DmuNphfaQAwHtwuKNxn+D+b6g6OiAtXZ6dURxLqSdUQHRzN/nBHW4/FNRXQ5Xdx9qReMUvJ0ItId2I4dG5P+EGCMElbPWE1eQx4flfVt6NLjwnj45rmUN3byb49tpb5Nh+LQaE6iDcRwqNgFnY0w8fLuopML1N4aQXQ4Ovio9CMuy7gMa4CVhnY7z24p5ppZqUxM8kJiouQZRMYacRRb13/o+fP7iBU5K8iIzODhfQ/3OYoAWJATzxO3nEdRXTv/9tg2alq6fKxSoxmdaAMxHI6tAwmACZd0F3UdPmzkU8id5JUu15eup8PZwdU5VwOG30Onw8V3LvXSiCVlJkFhdoJzMmj94APv9OEDAgMC+eY53+RIwxE+LO3f0C3KTeCpr59HaUMHV/9pMzuKx0akeY3Gm2gDMRyOrTOC84We2q3UdeAAQRNysESEe6XLNwveJC0ijbnJc6ls6uSpT4q4elYqucmRXumPlFkARJ2XQ+euXdgKxu520OXZy8mMyuSv+/6KW/Xv93DBxAReu/MCY8vw37byl4+OY3dqPwnN5xdtIIZK6wkjxWiP6SWlFJ0HDxI6Y6ZXuixvLWd71XaunXAtARLA/6zNx63gR0sne6U/AOKywRpOzPRgxGql4elnvNeXlwkMCOTOc+7kaONR3jj+xoBtp46L4s27F7F0egq/XZvPsj9s5KMjNf1OT2k0n2W0gRgqx83pltwru4ucVVW46usJmTnDK12+fPRlAiSAG3JvYF9ZE6/tqWD1omzS4zy4c6k3ARZInk5g+1FibvoCTa+/jq1w7CbcuSr7KuYkzeEPu/9As615wLbRoVb+8pVzefrW83C7Fbc+vYPlf9zMa7vL6bSPvQi3Gs1w0QZiqBxbBxEpkHJqtNB54CAAoTM9P4KwuWy8fux1Lkm/hOSwZH75zmESIoK48+IJHu/rDMbNgqp9JNxxBwGhoVQ98ABu+9jcCioiPHD+AzTbmvnNjt8M6piLJyex9nsX8ZsbZ+Fwufn+y/uY98v3+f7Le1mfd4IuhzYWms822kAMBUenMYKYtLR7eytA18EDYLUSPGWKx7t88/ibNNmaWDVlFS9sL2VHcSM/vHLysBMCDYmMhWBvI9Bdzbj//A869+6l8r77UE6n9/v2AlPipvCNWd9gTcEa3i95f1DHBAda+OJ56ay79yJeuP18Vswax/uHTrD6mZ2c+4v3ufP5Xbyxp4LmDp3vWvPZI9DfAsYUBR+CvQ2mrTytuGPPHkImT/Z4kiCn28mTB59kZsJMUkNmcNu7m7hgQvyw800PmYyFxnPpFqKu+jaOyipqfvtbShsaSfvd/xCYkOAbHR7kjpl38GnFpzz4yYNMiJlATnTOoI4LCBAumJjABRMT+MV1M9hSUM+6wyd4//AJ3j1QTWCAsCAnniunJ3PFtGTGRYd6+ZNoNN5HjyCGwuE3jexxPcJruNra6dy7j/CFCz3e3TuF71DRVsHqGat54PWDuJXioRtnIdJXKm8vEJ0GMRlQYgQIjF99G6kP/ZrOffsouuFGOvaMvXDgVouV3138O4Itwdz5wZ3UdNQM+RzBgRYunpzEf18/k20/vozX7ryA2xfnUNnUyc/ePMTCX33ItX/ezHNbS2i3jc3RlkYD2kAMHkcn5P8LpqwAy6npnY7t28HpJPzCCwc4eOjYXDb+vPfPTI+fTnFpFhuP1vKjpZO9uzDdFxkXQOkWI3otEL1yJVn/eBEJDqbka7fQ9PrAu4JGIynhKfz1sr/S2NXIre/dSkVbxbDPFRAgnJsRy/1XTeHDH17MB99fwo+WTcblVjz4xkEW/Go9v3z7MGUNHR78BBqNb9BTTIMl7y2wtcCsL51W3P7JJ0hoKKHnzvFod88eepbq9mq+knMfv3g1nyumJfO1hVke7WNQZF4A+/8BNXmQbOTdDpkyhexXX6H83nup+vGPUV2dxK5a5XttI2B6wnQeveJR7lx/J6veXsV/L/5vFqUtGvF5JyZFMDFpIt9eMoHdpU089UkRT31azBOfFHHltGTuviSXmeOjPfAJRgcOl5uKxk5OtHRR326ny+HC4XITFBhARLCVhIggMuPDiQ2z+m7kq/EY8lna3z1v3jy1c6eXoo8+fTU0lcI9e7vzTwMULLsKa2YGGY8+6rGuylrKuH7N9cxLuoCd268hKtTKm3dd6JuF6d60VsPvpsAlD8CSH51W5bbZqLj3e7R9/DFpv/89UUuv7Ocko5fC5kJ+8PEPON50nMszLuf7875PeqRn13iqmjv5+9YSnttSQkuXk0unJPGdSycyJ8N7YeG9QWuXg92lTRyubCG/uoUj1a0U1LbhcJ39GhITZmVOegxzM2NZMimJGWlR2mCMEkRkl1JqXp912kAMgvoC+NO5cOlP4aJ/7y62FRZSuHwFyT/5CXFfvdkjXTndTlavXc2RhnxCau6nvimUN+66gIlJXvKYHgxPLAV7O3x78xlV7q4uSr9+K115eWQ8/RRhczw7kvIFXc4unj38LI8feByH28HlGZfzxclfZF7yPI9exFq7HDy7pYTHNxXS2OFgcW4C91yWy3lZcR7rw5O0dDnYVtjAtsJ6thU1cKiyGbd5uUiNDmFySiSTU6KYmBRBclQwCRHBhFotWAMDsDvdtHU5qWntori+g/zqFnaXNnG8pg2A5Khgls8cx01z05mWGuXHT6nRBmKkrLkH9v0D7t0PkSndxbV//CN1jzzKxI8/wpqU5JGu/rj7jzx24DGiW2+hoWYGz9w23/8XkC1/gbUPwD17IO7MXT/OhgaKV63C3dpG1ssvETR+vB9EjpwT7Sd4+tDTvFnwJq32VlLDU1matZSl2UuZFjfNY8ai3ebk71tL+NvGQurb7SzMieeey3JZkBPn17tqpRRHqlv5KL+Gj/Nr2V3SiNOtCAoMYHZ6DAuy45ifHc/M8dHDTk5V32bjo/xa3j9czUdHarG73ExPjeILc8ezcnYaceGe3QmoOTvaQIyE5nL4w2yYewus+F13sXI4OH75FQRPnEjGE497pKu3Ct7igc0PENy5kLaK63n61vksyIn3yLlHRFMZ/H4mLLoXLv95n01sRUUUf3kVgYkJZL34IpZIP454Rkins5P3S97nX0X/YmvlVpzKSUZkhmEsspYyKXaSRy7knXYXz28r4dGNhdS22pifFcd3LpvIookJPjMULV0OPjlWx8f5tWw4Wku1Gcl26rgoLp6cyEW5iczJiCHEavF4343tdtbsq+SVXWUcrGghyBLAldOTWTU/g4U58QQE6CkoX6ANxEh47Ztw8FVj7SHm1Nx085o1VP7oPsY//FciL7lkgBMMjncK3+GBTQ/g6sghuP6bPHrzfOb5e+TQk5dvMfxAvncQQvpeZG3fuo3S228n/PzzSX/0ESRw7O+BaOpqYn3petYWr2V79XZcykV2dDZLs5ayLGsZE2JG7tHe5XDx0o4yHtlQQFVzF3MyYvjOpRO5eFKSxy+oCs3NAAARoElEQVSSbrficFULG47WsiG/ll2ljbjcisiQQBbnJnDxpCSWTE4kOSrEo/2ejbyqFl7aUcbreypo7nSQGR/Gl85L5wtzx5MU6Vst/dHlcNFpd+FwuwkQISzIQkigZcwbMm0ghsux9+H5LxjrDpf+tLvY3dVF4TXXEhAeTvZr/0QChr9b2OV28Zttf+aFo4/jbM8hV93D326+kJTo0fGj6KZqHzx6EVzykzMWq3vS+MorVD/4M6KuuYbUX/33Z8JInKShq4EPSj7gveL32Fm9E4ViYsxElmUtY1n2MjKjMkd0fpvTxau7yvnrRwVUNHWSGh3CdXPSWDYjhRmp0cO6ECmlKG3oYE9pE5uO1bHhaC11ZlKkGWlRLJmUyJJJSczJiMFq8f+u9y6Hi/cOVvPi9lK2FTUQGCBcNjWJm+amsyg3wSsjmZ502l0cr2kj/0Qrx060kn+ileM1bdS12ehynBnZNzBAGBcTwviYMNJiQxkfG8rEpAhmpkWTERc2JhbitYEYDjVH4KllEJEM39wIgcHdVdX/+QsaX3iBjKeeHJGD3Jr8TfzPjv+l0XUcd8tcvjnjR3xr8RSCAv3/Q+2Tl242jOZtayF1dr/N6h55hNrf/4HIKy5n3K9+7bUQ6P6ktqOWdSXrWFu8lj01hsPg1LipXJl1JcuyljE+cvjrMA6Xm38drOa13eVsPFqLW0FCRBDn58QzMy2aKSmRpMaEkhQZTIjVgiVA6HS4aO1ycqKli/LGTo7XtLGvrIl95U00mWFAYsKsXJSbyJJJiSyelDBq7sz7o6C2jZd2lPHqrnIa2u1EBAeyZHIiF+UmcMGEBMbHhg77Amx3uimqayf/RCtHq1s5esJ4lDR0nHT5ISgwgAmJEeSai/AxYUGEBVkItASglKLD7qK500FlUyfljZ3Gdt/Wru7jI0MCmZ4axYzUaGakRTMjLYrshAgso2zE4TcDISLLgD8AFuBxpdSve9WLWb8c6AC+rpTaPZhj+8JjBuL4B/D6t414S7e9170w67bbqfvTn6h/7HHivv51ku+/b0indbkVu8srePHgWjZXv02n5TjKGcE5YV/joWW3MD7Wx05wQ6X1BDx+GTg64N9egfFz+23a8MwznHjoNwSlp5P04/uJWLJkTNxNDYfq9mrWFRvGYn/dfgBmxM9gWfYy5qXMIzcmlyDL8BZf69tsbDhay8f5tewqaaSiqXNQxwUITEqOZHZ6DLPGx3BOejRTUqJG3cVpMNidbj4tqOO9g9WsP1JDbasxAooPD2JGWjQTEiMYHxtKSnQIUSFWwoKNUYbbrWizOWnpclLV1ElpQwelDR2UNXRQ3tiJ09ySZQkQsuLDmJwSyaTkSCYnRzIpJZLMuDAChziqsjldHDvRxsGKZg5WNnOwooW8qhZsZl6REGsAk5MjmTouimmpUUxKjiQzPozkyBC/TVX5xUCIiAU4ClwBlAM7gFVKqcM92iwHvoNhIM4H/qCUOn8wx/bFsA1E4cdga4WGQsh/D0o/hcQpcNMzkDSFjj17aNuwgZa338FRXk7MTTeR8vP/h1hOH+4W1NVR0dJMQ3sb9R1t1He0Ut1+grLWaqo7iml0lkBwBSJuLO5YFsTdwE+X3Mr4mDHkOFVfAM9cAy2VMO1amHgFpM3tdqLrSfv27VQ9+CCOklKCsrOJuPQSI2ZVVBS4XERcdBFi9YNvhxepaKtgbfFa3it6j7yGPMDIR5Ebk0tubC7JYcmkhKeQEp5ChDWCcGs44dZwgixBWMRCYEAg0cH9/z80tNspqG2jurmLmlYbdqcbp8tNiNVCZEggCRHBpMeFkREXRmiQd6dj/IFSiuM1bWwprOdAeTMHK1sormuncxCRdWPDrGTEhXV/PycNQk5iOMGB3vuunC43BbXtHKhoJq+qhcOVLeRVt3SP7ACCAwNIjwsjMy6MpKhg4sKDiAsPJiEiiKhQK2FWC6FBFkKtlu5RowgIxrMlQEiICB5ARf/4y0AsBH6ulFpqvv8xgFLqVz3aPAp8rJR60XyfD1wMZJ3t2L4YtoH4r3HGXTFAfC6c+zWY/w2wGgHXKr7/fVrWriN0zmwSvv1tIvoJq3Hek9fTZTneZ51FhRNnzWJq7ExumHIll2TPJUBG6VTS2ehqho2/hX0vQXuN8X1d+6c+myq7nea33qL5jTfp2LsXHKd+FLlbPiUwdmw5iw2FyrZKDtQd4HD9YQ7XH6a4pZjajlpcqv+LWVxIHBu+tMGHKsc+Sinq2+3Uttpo7XLSbnciQIAIESGBRIUEkhRljC5GC0opqpq7OF7TRklDB6X17ZTUGyOcujY7jR12XO7BX5sTIoLZ+dPLz96wD/xlIL4ALFNK3W6+/ypwvlLq7h5t3gZ+rZTabL5fD9yHYSAGPLbHOe4A7jDfTgbyRyg9Aagb4Tm8gdY1NEarLhi92rSuoTFadcHQtGUqpRL7qvDmFpO+JtR6W6P+2gzmWKNQqb8BfxuatP4RkZ39WVN/onUNjdGqC0avNq1raIxWXeA5bd40EOVAz6A244HKQbYJGsSxGo1Go/Ei3pwE3wHkiki2iAQBXwbW9GqzBviaGCwAmpVSVYM8VqPRaDRexGsjCKWUU0TuBtZibFV9Uil1SES+ZdY/AryLsYPpOMY211sHOtZbWnvhsekqD6N1DY3RqgtGrzata2iMVl3gIW2fKUc5jUaj0XiOMbrPUqPRaDTeRhsIjUaj0fSJNhCAiPxWRI6IyH4ReV1EYnrU/VhEjotIvogs9ZO+ZWb/x0Xkfn9oMHWki8hHIpInIodE5LtmeZyIvC8ix8xnv3i/iYhFRPaY/jWjQpeIxIjIq+b/V56ILBwlur5n/g0PisiLIhLiL10i8qSI1IjIwR5l/Wrx1W+yH11+v1b0patH3Q9FRIlIgkd0KaU+9w/gSiDQfP0Q8JD5ehqwDwgGsoECwOJjbRaz3xyM7b/7gGl++p7GAeearyMxwqFMA34D3G+W33/y+/ODvu8DLwBvm+/9rgt4BrjdfB0ExPhbF5AGFAGh5vuXga/7SxdwEXAucLBHWZ9afPmb7EeX368Vfekyy9MxNvaUAAme0KVHEIBSap1Symm+3YrhdwGwEviHUsqmlCrC2G0138fy5gPHlVKFSik78A9Tl89RSlUpM5iiUqoVyMO42KzEuBBiPl/na20iMh5YAfTM3uRXXSIShfFjfgJAKWVXSjX5W5dJIBAqIoFAGIafkV90KaU2Ag29ivvT4rPfZF+6RsO1op/vC+D/gB9xulPxiHRpA3EmtwH/Ml+nAWU96srNMl8yGjScgYhkAXOAbUCyMvxXMJ89k391aPwe48fRM2i/v3XlALXAU+bU1+MiEu5vXUqpCuB/gFKgCsP/aJ2/dfWiPy2j6fcwaq4VInItUKGU2terakS6PjcGQkQ+MOdbez9W9mjzE8AJPH+yqI9T+Xpf8GjQcBoiEgH8E7hXKdXiTy2mnquBGqXULn9r6UUgxlTAw0qpOUA7xnSJXzHn81diTDmkAuEicrN/VQ2aUfF7GE3XChEJA34C/Kyv6j7KBq3rs5Pu6ywopQYMdSgitwBXA5cpc/KOwYUL8TajQUM3ImLFMA7PK6VeM4tPiMg4pVSViIwDanws60LgWjHCx4cAUSLy91GgqxwoV0ptM9+/imEg/K3rcqBIKVULICKvAReMAl096U+L338Po/BaMQHD2O8TI+fKeGC3iMwfqa7PzQhiIMRITnQfcK1SqqNH1RrgyyISLCLZQC6w3cfyRk3YETH++54A8pRS/9ujag1wi/n6FuBNX+pSSv1YKTVeKZWF8f18qJS6eRToqgbKRGSyWXQZcNjfujCmlhaISJj5N70MYz3J37p60p8Wv/4mR+O1Qil1QCmVpJTKMn8D5RibSapHrMsbq+xj7YGxcFMG7DUfj/So+wnGyn8+cJWf9C3H2DFUAPzEj9/TIozh6f4e39VyIB5YDxwzn+P8qPFiTu1i8rsuYDaw0/zO3gBiR4mu/wCOAAeB5zB2ufhFF/AixlqIw7y4rR5Ii69+k/3o8vu1oi9dveqLMXcxjVSXDrWh0Wg0mj7RU0wajUaj6RNtIDQajUbTJ9pAaDQajaZPtIHQaDQaTZ9oA6HRaDSaPtEGQvOZQkR+LiI/PEub60Rk2jDO3TZ8ZYM6f3HPKJxDOO5jM1LntT3en5GwfrjnP0vfF4sZPbdH2TQz2ui/zFhP/R07RUS2iIit599MREJFZK+I2D2tVzM0tIHQfB65DiPK5ahBRCwjPMVXlFJ+z9suIqkY0WFvwHAKHCj1ZQNwD0ZcqG6UUp1Kqdn4MWKAxkAbCM2QEZE3RGSXGPkE7uhRvkxEdovIPhFZb5ZFiMhTInLAjKF/o1ne1uO4L4jI0+brp0XkYTHyThSKyBIz/n3eyTYDHd9L5zdEZIep55+m5/AFwLXAb8271Anm4z3zM20SkSnm8dnmHe4OEflFP9/Fj0TkHvP1/4nIh+bry8xwH4jIKvPzHxSRh3p+BhH5TxHZBizsUR5q6vmGiISLyDvmZzgoIl8awt8pQESeEZFfnqVdm4g8ZH7+D0RkvjkKKewxKgnp8XfcIyKX9HGeKOAl4A6l1Gal1A+AWhH5z776VUrVKKV2YDh8aUYh2kBohsNtSqm5wDzgHhGJF5FE4DHgRqXUOcBNZtsHMaKFzlRKzQI+HMT5Y4FLge8Bb2GEMZ4OzBSR2UPQ+ZpS6jxTTx6Gx+mnGOEH/l0pNVspVYBxl/sd8zP9EPirefwfMALtnQdU99PHRmCx+XoeECFGvKpFwCbzjvoh8/PMBs4TkZOhq8MxYvqfr5TabJZFmJ/5BaXUY8AyoFIpdY5Sagbw3iA/eyBGILmjSqmfnqVtOPCx+flbgV8CVwDXAycv7ncBKKVmAquAZ0QkpOdJlFItSqnF5nd8suw+pVRfQeQ0YwBtIDTD4R4R2YcRDz8dI77LAmCjMmLOo5Q6Ga/+cuAvJw9USjUO4vxvKcPF/wBwQhmxZtzAISBrCDpnmCOCA8BXMIzMaYgRmfYC4BUR2Qs8ipEYCYwggC+ar5/rp49dwFwRiQRswBYMQ7EY2ASch3HxrVVGHoHnMXJEALgwAh/25E3gKaXUs+b7A8Dl5h3+YqVU8yA/+6MYxue/BtHWzinDcwDYoJRymK+zzPJFmN+BUuoIRlKaSYPUohmjaAOhGRIicjHGRX+heWe+ByOCqtB3GOH+ynuWhfSqs5nP7h6vT74/ueg50PEneRq427zr/Y9+2gUATeZo4uRjaj86z8C8kBYDtwKfYhiFSzAibObRd7jlk3QppVy9yj4BrhIxwnIqpY4CczEu1r8SkcHejX8KXNL7Lr8fHOpUzJ3u79w0yie/74E+x6AQkbvMab295shKM8rRBkIzVKKBRqVUhzlXv8As3wIsESNiJCISZ5avA+4+ebCcyi18QkSmikgAxlTGUBnM8ZFAlTnl85Ue5a1mHcrIZ1EkIjeZ+kREzjHbfYIRHZZex/dmI8bU1EYMA/EtYK950d2G8b0kiLEQvQrYMMC5fgbUY05zmRfSDqXU3zEWc88d4NiePAG8izEy8kRY/42Y34GITAIyMIK/DRql1F96GGG9AD0G0AZCM1TeAwJFZD/wC4xpJpSRW+AO4DVz+ukls/0vgVhzgXUfxt01GHkR3sZYk6gaho7BHP8gxgX6fYzIpSf5B/Dv5mLrBIwL32pT3yFOpXT9LnCXiOzAMIz9sQljWmqLUuoE0GWWoYxsaD8GPsLIDbxbKXW2MNr3AiEi8htgJrDdnP76Ccb3OSiUEZJ9N/CcaUgDOX1ENhT+CljM6bqXgK8rpYZ7LgBEJEVEyjFyif9URMrNhW7NKEFHc9Voxjgi8jHwQ6XUzgHaJGKMavyernawiEgxME8pVedvLZ9X9AhCoxn7NABPn9yS2huzfBPGSGbUY27z3QtYOT3HuMbH6BGERqPRaPpEjyA0Go1G0yfaQGg0Go2mT7SB0Gg0Gk2faAOh0Wg0mj7RBkKj0Wg0ffL/AfDfg8IalflHAAAAAElFTkSuQmCC\n", + "text/plain": [ + "
" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "for time in [1, 100]:\n", + " seaborn.distplot(np.array(forward_works[time]), hist=False, label = f\"--> {time} annealing steps\")\n", + " seaborn.distplot(-np.array(backward_works[time]), hist=False, label = f\"<--{time} annealing steps\")\n", + "plt.title(f\"benzene --> fluorobenzene solvent annealing\")\n", + "plt.xlabel(f\"accumulated works [kJ mol^-1]\")\n", + "plt.ylabel(f\"frequency\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.7" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} From bc216064ba3f6594f210fa86ce1fce0d21614065 Mon Sep 17 00:00:00 2001 From: dominicrufa <46943710+dominicrufa@users.noreply.github.com> Date: Mon, 13 Apr 2020 17:02:07 -0400 Subject: [PATCH 137/152] Update openmmtools/integrators.py Co-Authored-By: Josh Fass --- openmmtools/integrators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 1f7a17ba7..8353aaa96 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -1952,7 +1952,7 @@ def _add_integrator_steps(self): #init/reset self.addConstrainPositions() #constrain positions self.addConstrainVelocities() #and velocities - self._add_reset_step() #reset lambda, protocol_works, heat, shadow, ghmc, step (unused), lambda_step, and alchemical_params + self._add_reset_step() #reset lambda, protocol_works, heat, shadow, ghmc, step (unused), lambda_step, eq_step, and alchemical_params #lambda_0 equilibration self.beginWhileBlock("eq_step < n_steps_eq") From 8f1a26f746018bc1697681d5dc532b60cd09ec94 Mon Sep 17 00:00:00 2001 From: dominicrufa Date: Mon, 13 Apr 2020 17:06:06 -0400 Subject: [PATCH 138/152] deleting `x_annealing` as it is a redundant placeholder variable --- openmmtools/integrators.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 1f7a17ba7..0d7d1360b 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -2072,7 +2072,6 @@ def __init__(self, self.addPerDofVariable('x_zero_endstate', zero_endstate_positions.value_in_unit_system(unit.md_unit_system)) self.addPerDofVariable('x_one_endstate', zero_endstate_positions.value_in_unit_system(unit.md_unit_system)) - self.addPerDofVariable('x_annealing', 0.) def _add_integrator_steps(self): """ @@ -2090,11 +2089,9 @@ def _add_integrator_steps(self): self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step self.endBlock() self.addComputePerDof('x_zero_endstate', 'x') - self.addComputePerDof('x_annealing', 'x_zero_endstate') #forward anneal - self.addComputePerDof('x', 'x_annealing') self.beginWhileBlock("lambda_step < n_lambda_steps") #anneal forward until lambda step is n_lambda_steps (lambda = lambda_step / n_lambda_steps) self._add_canonical_integrator_steps() #add VRORV self._substep_function('H') #add the H step... @@ -2111,7 +2108,6 @@ def _add_integrator_steps(self): self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step self.endBlock() self.addComputePerDof('x_one_endstate', 'x') - self.addComputePerDof('x_annealing', 'x_one_endstate') #reverse anneal; don't reset lambda (it is annealing in backward direction) self.beginWhileBlock("lambda_step > 0") #anneal backward until lambda step is 0 again From b3bd3c32bb43b23f6808a11cb97b09e0e7b002fd Mon Sep 17 00:00:00 2001 From: John Chodera Date: Mon, 13 Apr 2020 21:42:10 -0700 Subject: [PATCH 139/152] Fix travis since miniconda changed location cc https://github.com/MolSSI/cookiecutter-cms/pull/104 --- devtools/travis-ci/before_install.sh | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/devtools/travis-ci/before_install.sh b/devtools/travis-ci/before_install.sh index cfaa07398..08f99b808 100755 --- a/devtools/travis-ci/before_install.sh +++ b/devtools/travis-ci/before_install.sh @@ -3,7 +3,7 @@ pushd . cd $HOME # Make sure some level of pip is installed python -m ensurepip - +{% if (cookiecutter.dependency_source == 'Prefer conda-forge over the default anaconda channel with pip fallback' or cookiecutter.dependency_source == 'Prefer default anaconda channel with pip fallback') %} # Install Miniconda if [ "$TRAVIS_OS_NAME" == "osx" ]; then # Make OSX md5 mimic md5sum from linux, alias does not work @@ -15,8 +15,8 @@ else MINICONDA=Miniconda3-latest-Linux-x86_64.sh fi MINICONDA_HOME=$HOME/miniconda -MINICONDA_MD5=$(curl -s https://repo.continuum.io/miniconda/ | grep -A3 $MINICONDA | sed -n '4p' | sed -n 's/ *\(.*\)<\/td> */\1/p') -wget -q https://repo.continuum.io/miniconda/$MINICONDA +MINICONDA_MD5=$(wget -qO- https://repo.anaconda.com/miniconda/ | grep -A3 $MINICONDA | sed -n '4p' | sed -n 's/ *\(.*\)<\/td> */\1/p') +wget -q https://repo.anaconda.com/miniconda/$MINICONDA if [[ $MINICONDA_MD5 != $(md5sum $MINICONDA | cut -d ' ' -f 1) ]]; then echo "Miniconda MD5 mismatch" exit 1 @@ -30,12 +30,25 @@ echo ". $MINICONDA_HOME/etc/profile.d/conda.sh" >> ~/.bashrc # Source the profi echo "conda activate" >> ~/.bashrc # Activate conda source ~/.bashrc # source file to get new commands #export PATH=$MINICONDA_HOME/bin:$PATH # Old way, should not be needed anymore - + {% if cookiecutter.dependency_source == "Prefer conda-forge over the default anaconda channel with pip fallback" %} conda config --add channels conda-forge - + {% endif %} conda config --set always_yes yes conda install conda conda-build jinja2 anaconda-client conda update --quiet --all - +{% elif cookiecutter.dependency_source == 'Dependencies from pip only (no conda)' %} +if [ "$TRAVIS_OS_NAME" == "osx" ]; then + HOMEBREW_NO_AUTO_UPDATE=1 brew upgrade pyenv + # Pyenv requires minor revision, get the latest + PYENV_VERSION=$(pyenv install --list |grep $PYTHON_VER | sed -n "s/^[ \t]*\(${PYTHON_VER}\.*[0-9]*\).*/\1/p" | tail -n 1) + # Install version + pyenv install $PYENV_VERSION + # Use version for this + pyenv global $PYENV_VERSION + # Setup up path shims + eval "$(pyenv init -)" +fi +pip install --upgrade pip setuptools +{% endif %} # Restore original directory popd From a515540a3ddbcc634992ddab11890fce1cad29f7 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Mon, 13 Apr 2020 21:47:52 -0700 Subject: [PATCH 140/152] Fix the fix --- devtools/travis-ci/before_install.sh | 21 ++++----------------- 1 file changed, 4 insertions(+), 17 deletions(-) diff --git a/devtools/travis-ci/before_install.sh b/devtools/travis-ci/before_install.sh index 08f99b808..6d2fef577 100755 --- a/devtools/travis-ci/before_install.sh +++ b/devtools/travis-ci/before_install.sh @@ -3,7 +3,7 @@ pushd . cd $HOME # Make sure some level of pip is installed python -m ensurepip -{% if (cookiecutter.dependency_source == 'Prefer conda-forge over the default anaconda channel with pip fallback' or cookiecutter.dependency_source == 'Prefer default anaconda channel with pip fallback') %} + # Install Miniconda if [ "$TRAVIS_OS_NAME" == "osx" ]; then # Make OSX md5 mimic md5sum from linux, alias does not work @@ -30,25 +30,12 @@ echo ". $MINICONDA_HOME/etc/profile.d/conda.sh" >> ~/.bashrc # Source the profi echo "conda activate" >> ~/.bashrc # Activate conda source ~/.bashrc # source file to get new commands #export PATH=$MINICONDA_HOME/bin:$PATH # Old way, should not be needed anymore - {% if cookiecutter.dependency_source == "Prefer conda-forge over the default anaconda channel with pip fallback" %} + conda config --add channels conda-forge - {% endif %} + conda config --set always_yes yes conda install conda conda-build jinja2 anaconda-client conda update --quiet --all -{% elif cookiecutter.dependency_source == 'Dependencies from pip only (no conda)' %} -if [ "$TRAVIS_OS_NAME" == "osx" ]; then - HOMEBREW_NO_AUTO_UPDATE=1 brew upgrade pyenv - # Pyenv requires minor revision, get the latest - PYENV_VERSION=$(pyenv install --list |grep $PYTHON_VER | sed -n "s/^[ \t]*\(${PYTHON_VER}\.*[0-9]*\).*/\1/p" | tail -n 1) - # Install version - pyenv install $PYENV_VERSION - # Use version for this - pyenv global $PYENV_VERSION - # Setup up path shims - eval "$(pyenv init -)" -fi -pip install --upgrade pip setuptools -{% endif %} + # Restore original directory popd From 115d1fb83fef074b2b298a77f0c2b1512fc4fb52 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Tue, 14 Apr 2020 20:34:47 -0700 Subject: [PATCH 141/152] Remove accidentally committed C vile --- openmmtools/multistate/mixing/_mix_replicas.c | 20904 ---------------- 1 file changed, 20904 deletions(-) delete mode 100644 openmmtools/multistate/mixing/_mix_replicas.c diff --git a/openmmtools/multistate/mixing/_mix_replicas.c b/openmmtools/multistate/mixing/_mix_replicas.c deleted file mode 100644 index ffd0c3578..000000000 --- a/openmmtools/multistate/mixing/_mix_replicas.c +++ /dev/null @@ -1,20904 +0,0 @@ -/* Generated by Cython 0.29.13 */ - -/* BEGIN: Cython Metadata -{ - "distutils": { - "depends": [], - "name": "openmmtools.multistate.mixing._mix_replicas", - "sources": [ - "./openmmtools/multistate/mixing/_mix_replicas.pyx" - ] - }, - "module_name": "openmmtools.multistate.mixing._mix_replicas" -} -END: Cython Metadata */ - -#define 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_13" -#define CYTHON_HEX_VERSION 0x001D0DF0 -#define CYTHON_FUTURE_DIVISION 0 -#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 - #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 - #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 -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 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 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #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 1 - #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 - #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 - #ifndef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 1 - #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) - #endif - #ifndef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #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" -#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#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 - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #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) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) -#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 - #define PyObject_Unicode PyObject_Str -#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 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 PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : (Py_INCREF(func), 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(MS_WINDOWS) - #define _USE_MATH_DEFINES -#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_ERR(f_index, lineno, Ln_error) \ -{ \ - __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; 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__openmmtools__multistate__mixing___mix_replicas -#define __PYX_HAVE_API__openmmtools__multistate__mixing___mix_replicas -/* Early includes */ -#include -#include -#include -#include "stdlib.h" -#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); -#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; - - -static const char *__pyx_f[] = { - "openmmtools/multistate/mixing/_mix_replicas.pyx", - "stringsource", -}; -/* 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_atomic_int_type int -#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 ||\ - (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) &&\ - !defined(__i386__) - #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) - #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using GNU atomics" - #endif -#elif CYTHON_ATOMICS && defined(_MSC_VER) && 0 - #include - #undef __pyx_atomic_int_type - #define __pyx_atomic_int_type LONG - #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) - #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) - #ifdef __PYX_DEBUG_ATOMICS - #pragma message ("Using MSVC atomics") - #endif -#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 - #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) - #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) - #ifdef __PYX_DEBUG_ATOMICS - #warning "Using Intel 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), memview->lock) - #define __pyx_sub_acquisition_count(memview)\ - __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) -#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; - - -/*--- Type declarations ---*/ -struct __pyx_array_obj; -struct __pyx_MemviewEnum_obj; -struct __pyx_memoryview_obj; -struct __pyx_memoryviewslice_obj; - -/* "View.MemoryView":105 - * - * @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":279 - * - * @cname('__pyx_MemviewEnum') - * cdef class Enum(object): # <<<<<<<<<<<<<< - * cdef object name - * def __init__(self, name): - */ -struct __pyx_MemviewEnum_obj { - PyObject_HEAD - PyObject *name; -}; - - -/* "View.MemoryView":330 - * - * @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":965 - * - * @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":105 - * - * @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":330 - * - * @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":965 - * - * @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); - -/* 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); - -/* None.proto */ -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); - -/* 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); - -/* 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); - -/* 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 - -/* 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 - -/* 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); - -/* 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 - -/* 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 - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" - #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 - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* 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 - -/* None.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 *); - -/* 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 - -/* 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)); - -/* 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 - -/* GetAttr3.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); - -/* 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) {\ - 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);\ -} -#define __Pyx_GetModuleGlobalNameUncached(var, name) {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -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 - -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/* RaiseNoneIterError.proto */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); - -/* ExtTypeTest.proto */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); - -/* GetTopmostException.proto */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); -#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 - -/* 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 - -/* 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); - Py_SIZE(list) = len+1; - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) -#endif - -/* 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 - -/* 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); - Py_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 long __Pyx_div_long(long, long); - -/* WriteUnraisableException.proto */ -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename, - int full_traceback, int nogil); - -/* 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); - -/* SetupReduce.proto */ -static int __Pyx_setup_reduce(PyObject* type_obj); - -/* 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); - -#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_ds_long(PyObject *, int writable_flag); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *, int writable_flag); - -/* ObjectToMemviewSlice.proto */ -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_long(PyObject *, int writable_flag); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* 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); - -/* 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 'cython.view' */ - -/* Module declarations from 'cython' */ - -/* Module declarations from 'libc.math' */ - -/* Module declarations from 'libc.string' */ - -/* Module declarations from 'libc.stdio' */ - -/* Module declarations from 'openmmtools.multistate.mixing._mix_replicas' */ -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 long __pyx_f_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(long, long, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ -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_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 "openmmtools.multistate.mixing._mix_replicas" -extern int __pyx_module_is_main_openmmtools__multistate__mixing___mix_replicas; -int __pyx_module_is_main_openmmtools__multistate__mixing___mix_replicas = 0; - -/* Implementation of 'openmmtools.multistate.mixing._mix_replicas' */ -static PyObject *__pyx_builtin_range; -static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_MemoryError; -static PyObject *__pyx_builtin_enumerate; -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_O[] = "O"; -static const char __pyx_k_c[] = "c"; -static const char __pyx_k_id[] = "id"; -static const char __pyx_k_new[] = "__new__"; -static const char __pyx_k_obj[] = "obj"; -static const char __pyx_k_base[] = "base"; -static const char __pyx_k_dict[] = "__dict__"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_mode[] = "mode"; -static const char __pyx_k_name[] = "name"; -static const char __pyx_k_ndim[] = "ndim"; -static const char __pyx_k_pack[] = "pack"; -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_u_kl[] = "u_kl"; -static const char __pyx_k_ASCII[] = "ASCII"; -static const char __pyx_k_class[] = "__class__"; -static const char __pyx_k_error[] = "error"; -static const char __pyx_k_flags[] = "flags"; -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_encode[] = "encode"; -static const char __pyx_k_format[] = "format"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_name_2[] = "__name__"; -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_fortran[] = "fortran"; -static const char __pyx_k_memview[] = "memview"; -static const char __pyx_k_nstates[] = "nstates"; -static const char __pyx_k_Ellipsis[] = "Ellipsis"; -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_TypeError[] = "TypeError"; -static const char __pyx_k_enumerate[] = "enumerate"; -static const char __pyx_k_pyx_state[] = "__pyx_state"; -static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; -static const char __pyx_k_IndexError[] = "IndexError"; -static const char __pyx_k_ValueError[] = "ValueError"; -static const char __pyx_k_pyx_result[] = "__pyx_result"; -static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; -static const char __pyx_k_MemoryError[] = "MemoryError"; -static const char __pyx_k_PickleError[] = "PickleError"; -static const char __pyx_k_Nij_accepted[] = "Nij_accepted"; -static const char __pyx_k_Nij_proposed[] = "Nij_proposed"; -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_nswap_attempts[] = "nswap_attempts"; -static const char __pyx_k_replica_states[] = "replica_states"; -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_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_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_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_s_vs_0xb0[] = "Incompatible checksums (%s vs 0xb068931 = (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_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_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_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_Ellipsis; -static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; -static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0xb0; -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_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_s_Nij_accepted; -static PyObject *__pyx_n_s_Nij_proposed; -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_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_base; -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_kp_s_contiguous_and_direct; -static PyObject *__pyx_kp_s_contiguous_and_indirect; -static PyObject *__pyx_n_s_dict; -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_flags; -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_kp_s_got_differing_extents_in_dimensi; -static PyObject *__pyx_n_s_id; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_itemsize; -static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_memview; -static PyObject *__pyx_n_s_mode; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_name_2; -static PyObject *__pyx_n_s_ndim; -static PyObject *__pyx_n_s_new; -static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; -static PyObject *__pyx_n_s_nstates; -static PyObject *__pyx_n_s_nswap_attempts; -static PyObject *__pyx_n_s_obj; -static PyObject *__pyx_n_s_pack; -static PyObject *__pyx_n_s_pickle; -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_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_replica_states; -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_u_kl; -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_pf_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nswap_attempts, long __pyx_v_nstates, __Pyx_memviewslice __pyx_v_replica_states, __Pyx_memviewslice __pyx_v_u_kl, __Pyx_memviewslice __pyx_v_Nij_proposed, __Pyx_memviewslice __pyx_v_Nij_accepted); /* 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_int_0; -static PyObject *__pyx_int_1; -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__15; -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__16; -static PyObject *__pyx_tuple__17; -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__23; -static PyObject *__pyx_tuple__24; -static PyObject *__pyx_codeobj__25; -/* Late includes */ - -/* "openmmtools/multistate/mixing/_mix_replicas.pyx":10 - * @cython.cdivision(True) - * @cython.boundscheck(False) - * cpdef long _mix_replicas_cython(long nswap_attempts, long nstates, long[:] replica_states, double[:,:] u_kl, long[:,:] Nij_proposed, long[:,:] Nij_accepted) nogil: # <<<<<<<<<<<<<< - * cdef long swap_attempt - * cdef long i, j, istate, jstate, tmp_state - */ - -static PyObject *__pyx_pw_11openmmtools_10multistate_6mixing_13_mix_replicas_1_mix_replicas_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static long __pyx_f_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(long __pyx_v_nswap_attempts, long __pyx_v_nstates, __Pyx_memviewslice __pyx_v_replica_states, __Pyx_memviewslice __pyx_v_u_kl, __Pyx_memviewslice __pyx_v_Nij_proposed, __Pyx_memviewslice __pyx_v_Nij_accepted, CYTHON_UNUSED int __pyx_skip_dispatch) { - CYTHON_UNUSED long __pyx_v_swap_attempt; - long __pyx_v_i; - long __pyx_v_j; - long __pyx_v_istate; - long __pyx_v_jstate; - long __pyx_v_tmp_state; - double __pyx_v_log_P_accept; - long __pyx_r; - long __pyx_t_1; - long __pyx_t_2; - long __pyx_t_3; - Py_ssize_t __pyx_t_4; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - Py_ssize_t __pyx_t_7; - Py_ssize_t __pyx_t_8; - int __pyx_t_9; - Py_ssize_t __pyx_t_10; - Py_ssize_t __pyx_t_11; - Py_ssize_t __pyx_t_12; - Py_ssize_t __pyx_t_13; - Py_ssize_t __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; - Py_ssize_t __pyx_t_20; - Py_ssize_t __pyx_t_21; - Py_ssize_t __pyx_t_22; - Py_ssize_t __pyx_t_23; - Py_ssize_t __pyx_t_24; - Py_ssize_t __pyx_t_25; - Py_ssize_t __pyx_t_26; - Py_ssize_t __pyx_t_27; - Py_ssize_t __pyx_t_28; - Py_ssize_t __pyx_t_29; - Py_ssize_t __pyx_t_30; - Py_ssize_t __pyx_t_31; - Py_ssize_t __pyx_t_32; - Py_ssize_t __pyx_t_33; - Py_ssize_t __pyx_t_34; - Py_ssize_t __pyx_t_35; - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":14 - * cdef long i, j, istate, jstate, tmp_state - * cdef double log_P_accept - * for swap_attempt in range(nswap_attempts): # <<<<<<<<<<<<<< - * i = (drand48()*nstates) - * j = (drand48()*nstates) - */ - __pyx_t_1 = __pyx_v_nswap_attempts; - __pyx_t_2 = __pyx_t_1; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_swap_attempt = __pyx_t_3; - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":15 - * cdef double log_P_accept - * for swap_attempt in range(nswap_attempts): - * i = (drand48()*nstates) # <<<<<<<<<<<<<< - * j = (drand48()*nstates) - * istate = replica_states[i] - */ - __pyx_v_i = ((long)(drand48() * __pyx_v_nstates)); - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":16 - * for swap_attempt in range(nswap_attempts): - * i = (drand48()*nstates) - * j = (drand48()*nstates) # <<<<<<<<<<<<<< - * istate = replica_states[i] - * jstate = replica_states[j] - */ - __pyx_v_j = ((long)(drand48() * __pyx_v_nstates)); - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":17 - * i = (drand48()*nstates) - * j = (drand48()*nstates) - * istate = replica_states[i] # <<<<<<<<<<<<<< - * jstate = replica_states[j] - * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): - */ - __pyx_t_4 = __pyx_v_i; - __pyx_v_istate = (*((long *) ( /* dim=0 */ (__pyx_v_replica_states.data + __pyx_t_4 * __pyx_v_replica_states.strides[0]) ))); - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":18 - * j = (drand48()*nstates) - * istate = replica_states[i] - * jstate = replica_states[j] # <<<<<<<<<<<<<< - * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): - * continue - */ - __pyx_t_5 = __pyx_v_j; - __pyx_v_jstate = (*((long *) ( /* dim=0 */ (__pyx_v_replica_states.data + __pyx_t_5 * __pyx_v_replica_states.strides[0]) ))); - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":19 - * istate = replica_states[i] - * jstate = replica_states[j] - * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): # <<<<<<<<<<<<<< - * continue - * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) - */ - __pyx_t_7 = __pyx_v_i; - __pyx_t_8 = __pyx_v_istate; - __pyx_t_9 = (isnan((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_7 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_8 * __pyx_v_u_kl.strides[1]) )))) != 0); - if (!__pyx_t_9) { - } else { - __pyx_t_6 = __pyx_t_9; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_10 = __pyx_v_i; - __pyx_t_11 = __pyx_v_jstate; - __pyx_t_9 = (isnan((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_10 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_11 * __pyx_v_u_kl.strides[1]) )))) != 0); - if (!__pyx_t_9) { - } else { - __pyx_t_6 = __pyx_t_9; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_12 = __pyx_v_j; - __pyx_t_13 = __pyx_v_istate; - __pyx_t_9 = (isnan((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_12 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_13 * __pyx_v_u_kl.strides[1]) )))) != 0); - if (!__pyx_t_9) { - } else { - __pyx_t_6 = __pyx_t_9; - goto __pyx_L6_bool_binop_done; - } - __pyx_t_14 = __pyx_v_j; - __pyx_t_15 = __pyx_v_jstate; - __pyx_t_9 = (isnan((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_14 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_15 * __pyx_v_u_kl.strides[1]) )))) != 0); - __pyx_t_6 = __pyx_t_9; - __pyx_L6_bool_binop_done:; - if (__pyx_t_6) { - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":20 - * jstate = replica_states[j] - * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): - * continue # <<<<<<<<<<<<<< - * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) - * Nij_proposed[istate, jstate] +=1 - */ - goto __pyx_L3_continue; - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":19 - * istate = replica_states[i] - * jstate = replica_states[j] - * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): # <<<<<<<<<<<<<< - * continue - * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) - */ - } - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":21 - * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): - * continue - * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) # <<<<<<<<<<<<<< - * Nij_proposed[istate, jstate] +=1 - * Nij_proposed[jstate, istate] +=1 - */ - __pyx_t_16 = __pyx_v_i; - __pyx_t_17 = __pyx_v_jstate; - __pyx_t_18 = __pyx_v_j; - __pyx_t_19 = __pyx_v_istate; - __pyx_t_20 = __pyx_v_j; - __pyx_t_21 = __pyx_v_jstate; - __pyx_t_22 = __pyx_v_i; - __pyx_t_23 = __pyx_v_istate; - __pyx_v_log_P_accept = ((-((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_16 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_17 * __pyx_v_u_kl.strides[1]) ))) + (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_18 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_19 * __pyx_v_u_kl.strides[1]) ))))) + ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_20 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_21 * __pyx_v_u_kl.strides[1]) ))) + (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_22 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_23 * __pyx_v_u_kl.strides[1]) ))))); - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":22 - * continue - * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) - * Nij_proposed[istate, jstate] +=1 # <<<<<<<<<<<<<< - * Nij_proposed[jstate, istate] +=1 - * if(log_P_accept>=0 or drand48()=0 or drand48()=0 or drand48()= 0.0) != 0); - if (!__pyx_t_9) { - } else { - __pyx_t_6 = __pyx_t_9; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_9 = ((drand48() < exp(__pyx_v_log_P_accept)) != 0); - __pyx_t_6 = __pyx_t_9; - __pyx_L11_bool_binop_done:; - if (__pyx_t_6) { - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":25 - * Nij_proposed[jstate, istate] +=1 - * if(log_P_accept>=0 or drand48()=0 or drand48()=0 or drand48() 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_mix_replicas_cython") < 0)) __PYX_ERR(0, 10, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 6) { - 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); - } - __pyx_v_nswap_attempts = __Pyx_PyInt_As_long(values[0]); if (unlikely((__pyx_v_nswap_attempts == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 10, __pyx_L3_error) - __pyx_v_nstates = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v_nstates == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 10, __pyx_L3_error) - __pyx_v_replica_states = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_replica_states.memview)) __PYX_ERR(0, 10, __pyx_L3_error) - __pyx_v_u_kl = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_u_kl.memview)) __PYX_ERR(0, 10, __pyx_L3_error) - __pyx_v_Nij_proposed = __Pyx_PyObject_to_MemoryviewSlice_dsds_long(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Nij_proposed.memview)) __PYX_ERR(0, 10, __pyx_L3_error) - __pyx_v_Nij_accepted = __Pyx_PyObject_to_MemoryviewSlice_dsds_long(values[5], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Nij_accepted.memview)) __PYX_ERR(0, 10, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_mix_replicas_cython", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 10, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("openmmtools.multistate.mixing._mix_replicas._mix_replicas_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(__pyx_self, __pyx_v_nswap_attempts, __pyx_v_nstates, __pyx_v_replica_states, __pyx_v_u_kl, __pyx_v_Nij_proposed, __pyx_v_Nij_accepted); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nswap_attempts, long __pyx_v_nstates, __Pyx_memviewslice __pyx_v_replica_states, __Pyx_memviewslice __pyx_v_u_kl, __Pyx_memviewslice __pyx_v_Nij_proposed, __Pyx_memviewslice __pyx_v_Nij_accepted) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("_mix_replicas_cython", 0); - __Pyx_XDECREF(__pyx_r); - if (unlikely(!__pyx_v_replica_states.memview)) { __Pyx_RaiseUnboundLocalError("replica_states"); __PYX_ERR(0, 10, __pyx_L1_error) } - if (unlikely(!__pyx_v_u_kl.memview)) { __Pyx_RaiseUnboundLocalError("u_kl"); __PYX_ERR(0, 10, __pyx_L1_error) } - if (unlikely(!__pyx_v_Nij_proposed.memview)) { __Pyx_RaiseUnboundLocalError("Nij_proposed"); __PYX_ERR(0, 10, __pyx_L1_error) } - if (unlikely(!__pyx_v_Nij_accepted.memview)) { __Pyx_RaiseUnboundLocalError("Nij_accepted"); __PYX_ERR(0, 10, __pyx_L1_error) } - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_f_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(__pyx_v_nswap_attempts, __pyx_v_nstates, __pyx_v_replica_states, __pyx_v_u_kl, __pyx_v_Nij_proposed, __pyx_v_Nij_accepted, 0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("openmmtools.multistate.mixing._mix_replicas._mix_replicas_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __PYX_XDEC_MEMVIEW(&__pyx_v_replica_states, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_u_kl, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_Nij_proposed, 1); - __PYX_XDEC_MEMVIEW(&__pyx_v_Nij_accepted, 1); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":122 - * 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_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(1, 122, __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(1, 122, __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(1, 122, __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(1, 122, __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(1, 123, __pyx_L3_error) - } else { - - /* "View.MemoryView":123 - * - * 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(1, 122, __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(1, 122, __pyx_L1_error) - if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { - PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(1, 122, __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":122 - * 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; - __Pyx_RefNannySetupContext("__cinit__", 0); - __Pyx_INCREF(__pyx_v_format); - - /* "View.MemoryView":129 - * 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(1, 129, __pyx_L1_error) - } - __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(1, 129, __pyx_L1_error) - __pyx_v_self->ndim = ((int)__pyx_t_1); - - /* "View.MemoryView":130 - * - * self.ndim = len(shape) - * self.itemsize = itemsize # <<<<<<<<<<<<<< - * - * if not self.ndim: - */ - __pyx_v_self->itemsize = __pyx_v_itemsize; - - /* "View.MemoryView":132 - * 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":133 - * - * 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_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 133, __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(1, 133, __pyx_L1_error) - - /* "View.MemoryView":132 - * self.itemsize = itemsize - * - * if not self.ndim: # <<<<<<<<<<<<<< - * raise ValueError("Empty shape tuple for cython.array") - * - */ - } - - /* "View.MemoryView":135 - * 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":136 - * - * 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__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 136, __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(1, 136, __pyx_L1_error) - - /* "View.MemoryView":135 - * raise ValueError("Empty shape tuple for cython.array") - * - * if itemsize <= 0: # <<<<<<<<<<<<<< - * raise ValueError("itemsize <= 0 for cython.array") - * - */ - } - - /* "View.MemoryView":138 - * 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":139 - * - * 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(1, 139, __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(1, 139, __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":138 - * 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":140 - * 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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) __PYX_ERR(1, 140, __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":141 - * 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(1, 141, __pyx_L1_error) - } - __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(1, 141, __pyx_L1_error) - __pyx_v_self->format = __pyx_t_7; - - /* "View.MemoryView":144 - * - * - * 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":145 - * - * 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":147 - * 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":148 - * - * if not self._shape: - * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 148, __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(1, 148, __pyx_L1_error) - - /* "View.MemoryView":147 - * self._strides = self._shape + self.ndim - * - * if not self._shape: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate shape and strides.") - * - */ - } - - /* "View.MemoryView":151 - * - * - * 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(1, 151, __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(1, 151, __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(1, 151, __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":152 - * - * 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":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_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 153, __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(1, 153, __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(1, 153, __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(1, 153, __pyx_L1_error) - - /* "View.MemoryView":152 - * - * 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":154 - * 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":151 - * - * - * 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":157 - * - * 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(1, 157, __pyx_L1_error) - if (__pyx_t_4) { - - /* "View.MemoryView":158 - * cdef char order - * if mode == 'fortran': - * order = b'F' # <<<<<<<<<<<<<< - * self.mode = u'fortran' - * elif mode == 'c': - */ - __pyx_v_order = 'F'; - - /* "View.MemoryView":159 - * 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":157 - * - * cdef char order - * if mode == 'fortran': # <<<<<<<<<<<<<< - * order = b'F' - * self.mode = u'fortran' - */ - goto __pyx_L10; - } - - /* "View.MemoryView":160 - * 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(1, 160, __pyx_L1_error) - if (likely(__pyx_t_4)) { - - /* "View.MemoryView":161 - * self.mode = u'fortran' - * elif mode == 'c': - * order = b'C' # <<<<<<<<<<<<<< - * self.mode = u'c' - * else: - */ - __pyx_v_order = 'C'; - - /* "View.MemoryView":162 - * 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":160 - * order = b'F' - * self.mode = u'fortran' - * elif mode == 'c': # <<<<<<<<<<<<<< - * order = b'C' - * self.mode = u'c' - */ - goto __pyx_L10; - } - - /* "View.MemoryView":164 - * 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(1, 164, __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(1, 164, __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(1, 164, __pyx_L1_error) - } - __pyx_L10:; - - /* "View.MemoryView":166 - * 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":169 - * 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":170 - * - * 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(1, 170, __pyx_L1_error) - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 170, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_v_self->dtype_is_object = __pyx_t_4; - - /* "View.MemoryView":171 - * 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":174 - * - * - * 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":175 - * - * 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":176 - * 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__4, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 176, __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(1, 176, __pyx_L1_error) - - /* "View.MemoryView":175 - * - * self.data = malloc(self.len) - * if not self.data: # <<<<<<<<<<<<<< - * raise MemoryError("unable to allocate array data.") - * - */ - } - - /* "View.MemoryView":178 - * 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":179 - * - * 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":180 - * 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(1, 180, __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(1, 180, __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":181 - * 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":182 - * for i in range(self.len / itemsize): - * p[i] = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - Py_INCREF(Py_None); - } - - /* "View.MemoryView":178 - * raise MemoryError("unable to allocate array data.") - * - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * p = self.data - * for i in range(self.len / itemsize): - */ - } - - /* "View.MemoryView":171 - * self.free_data = allocate_buffer - * self.dtype_is_object = format == b'O' - * if allocate_buffer: # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":122 - * 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":185 - * - * @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; - 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":186 - * @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":187 - * 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(1, 187, __pyx_L1_error) - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":188 - * 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":187 - * 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":189 - * 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(1, 189, __pyx_L1_error) - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":190 - * 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":189 - * 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":191 - * 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":192 - * 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__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 192, __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(1, 192, __pyx_L1_error) - - /* "View.MemoryView":191 - * 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":193 - * 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":194 - * 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":195 - * 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":196 - * 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":197 - * 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":198 - * 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":199 - * 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":200 - * info.suboffsets = NULL - * info.itemsize = self.itemsize - * info.readonly = 0 # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - __pyx_v_info->readonly = 0; - - /* "View.MemoryView":202 - * 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":203 - * - * 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":202 - * info.readonly = 0 - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.format - * else: - */ - goto __pyx_L5; - } - - /* "View.MemoryView":205 - * info.format = self.format - * else: - * info.format = NULL # <<<<<<<<<<<<<< - * - * info.obj = self - */ - /*else*/ { - __pyx_v_info->format = NULL; - } - __pyx_L5:; - - /* "View.MemoryView":207 - * 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":185 - * - * @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":211 - * __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":212 - * - * 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":213 - * 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":212 - * - * 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":214 - * 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":215 - * 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":216 - * 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":215 - * 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":218 - * 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":214 - * 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":219 - * self._strides, self.ndim, False) - * free(self.data) - * PyObject_Free(self._shape) # <<<<<<<<<<<<<< - * - * @property - */ - PyObject_Free(__pyx_v_self->_shape); - - /* "View.MemoryView":211 - * __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":222 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":223 - * @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(1, 223, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":222 - * - * @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":226 - * - * @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; - __Pyx_RefNannySetupContext("get_memview", 0); - - /* "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) - * - */ - __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); - - /* "View.MemoryView":228 - * 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(1, 228, __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(1, 228, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 228, __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(1, 228, __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":226 - * - * @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":230 - * 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":231 - * - * def __len__(self): - * return self._shape[0] # <<<<<<<<<<<<<< - * - * def __getattr__(self, attr): - */ - __pyx_r = (__pyx_v_self->_shape[0]); - goto __pyx_L0; - - /* "View.MemoryView":230 - * 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":233 - * 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; - __Pyx_RefNannySetupContext("__getattr__", 0); - - /* "View.MemoryView":234 - * - * 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(1, 234, __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(1, 234, __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":233 - * 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":236 - * 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; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "View.MemoryView":237 - * - * 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(1, 237, __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(1, 237, __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":236 - * 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":239 - * 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; - __Pyx_RefNannySetupContext("__setitem__", 0); - - /* "View.MemoryView":240 - * - * 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(1, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(1, 240, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "View.MemoryView":239 - * 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; - __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__6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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; - __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__7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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":244 - * - * @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; - __Pyx_RefNannySetupContext("array_cwrapper", 0); - - /* "View.MemoryView":248 - * 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":249 - * - * 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(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 249, __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(1, 249, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 249, __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(1, 249, __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":248 - * cdef array result - * - * if buf == NULL: # <<<<<<<<<<<<<< - * result = array(shape, itemsize, format, mode.decode('ASCII')) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":251 - * 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(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 251, __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(1, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 251, __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":252 - * 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(1, 252, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(1, 252, __pyx_L1_error) - - /* "View.MemoryView":251 - * 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(1, 251, __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":253 - * 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":255 - * 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":244 - * - * @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":281 - * 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_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(1, 281, __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(1, 281, __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":282 - * 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":281 - * 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":283 - * 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":284 - * 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":283 - * 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; - __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(1, 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(1, 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(1, 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(1, 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(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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; - __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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 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(1, 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":298 - * - * @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":300 - * 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":304 - * - * with cython.cdivision(True): - * offset = aligned_p % alignment # <<<<<<<<<<<<<< - * - * if offset > 0: - */ - __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); - - /* "View.MemoryView":306 - * 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":307 - * - * 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":306 - * offset = aligned_p % alignment - * - * if offset > 0: # <<<<<<<<<<<<<< - * aligned_p += alignment - offset - * - */ - } - - /* "View.MemoryView":309 - * aligned_p += alignment - offset - * - * return aligned_p # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = ((void *)__pyx_v_aligned_p); - goto __pyx_L0; - - /* "View.MemoryView":298 - * - * @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":345 - * 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_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(1, 345, __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(1, 345, __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(1, 345, __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(1, 345, __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(1, 345, __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; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "View.MemoryView":346 - * - * 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":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_GetBuffer(obj, &self.view, flags) - */ - __pyx_v_self->flags = __pyx_v_flags; - - /* "View.MemoryView":348 - * 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":349 - * 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(1, 349, __pyx_L1_error) - - /* "View.MemoryView":350 - * 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":351 - * __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":352 - * if self.view.obj == NULL: - * (<__pyx_buffer *> &self.view).obj = Py_None - * Py_INCREF(Py_None) # <<<<<<<<<<<<<< - * - * global __pyx_memoryview_thread_locks_used - */ - Py_INCREF(Py_None); - - /* "View.MemoryView":350 - * 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":348 - * 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 - * - * 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":356 - * 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":357 - * 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":355 - * - * 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":358 - * 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":359 - * __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":360 - * 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":361 - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: - * raise MemoryError # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - PyErr_NoMemory(); __PYX_ERR(1, 361, __pyx_L1_error) - - /* "View.MemoryView":360 - * if self.lock is NULL: - * self.lock = PyThread_allocate_lock() - * if self.lock is NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * - */ - } - - /* "View.MemoryView":358 - * 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":363 - * 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":364 - * - * 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_L11_bool_binop_done; - } - __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L11_bool_binop_done:; - __pyx_v_self->dtype_is_object = __pyx_t_1; - - /* "View.MemoryView":363 - * 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_L10; - } - - /* "View.MemoryView":366 - * 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_L10:; - - /* "View.MemoryView":368 - * 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":370 - * 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":345 - * 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":372 - * 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":373 - * - * 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":374 - * 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":373 - * - * 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":375 - * 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":377 - * 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":378 - * - * (<__pyx_buffer *> &self.view).obj = NULL - * Py_DECREF(Py_None) # <<<<<<<<<<<<<< - * - * cdef int i - */ - Py_DECREF(Py_None); - - /* "View.MemoryView":375 - * 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":382 - * 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":383 - * 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":384 - * 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":385 - * 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":386 - * 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":388 - * 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":387 - * __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":386 - * 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":389 - * __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":384 - * 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":391 - * 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":382 - * 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":372 - * self.typeinfo = NULL - * - * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "View.MemoryView":393 - * 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; - __Pyx_RefNannySetupContext("get_item_pointer", 0); - - /* "View.MemoryView":395 - * 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":397 - * 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(1, 397, __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(1, 397, __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(1, 397, __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(1, 397, __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(1, 397, __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(1, 397, __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(1, 397, __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":398 - * - * 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(1, 398, __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(1, 398, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_7; - - /* "View.MemoryView":397 - * 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":400 - * itemp = pybuffer_index(&self.view, itemp, idx, dim) - * - * return itemp # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_itemp; - goto __pyx_L0; - - /* "View.MemoryView":393 - * 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":403 - * - * - * 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; - __Pyx_RefNannySetupContext("__getitem__", 0); - - /* "View.MemoryView":404 - * - * 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":405 - * 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":404 - * - * def __getitem__(memoryview self, object index): - * if index is Ellipsis: # <<<<<<<<<<<<<< - * return self - * - */ - } - - /* "View.MemoryView":407 - * 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(1, 407, __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(1, 407, __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(1, 407, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 407, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 407, __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":410 - * - * 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(1, 410, __pyx_L1_error) - if (__pyx_t_2) { - - /* "View.MemoryView":411 - * 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(1, 411, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":410 - * - * cdef char *itemp - * if have_slices: # <<<<<<<<<<<<<< - * return memview_slice(self, indices) - * else: - */ - } - - /* "View.MemoryView":413 - * 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(1, 413, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_6; - - /* "View.MemoryView":414 - * 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(1, 414, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":403 - * - * - * 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":416 - * 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; - __Pyx_RefNannySetupContext("__setitem__", 0); - __Pyx_INCREF(__pyx_v_index); - - /* "View.MemoryView":417 - * - * 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":418 - * 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__8, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 418, __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(1, 418, __pyx_L1_error) - - /* "View.MemoryView":417 - * - * def __setitem__(memoryview self, object index, object value): - * if self.view.readonly: # <<<<<<<<<<<<<< - * raise TypeError("Cannot assign to read-only memoryview") - * - */ - } - - /* "View.MemoryView":420 - * 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(1, 420, __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(1, 420, __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(1, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 420, __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":422 - * 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(1, 422, __pyx_L1_error) - if (__pyx_t_1) { - - /* "View.MemoryView":423 - * - * 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(1, 423, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_obj = __pyx_t_2; - __pyx_t_2 = 0; - - /* "View.MemoryView":424 - * 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(1, 424, __pyx_L1_error) - if (__pyx_t_1) { - - /* "View.MemoryView":425 - * 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(1, 425, __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(1, 425, __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":424 - * if have_slices: - * obj = self.is_slice(value) - * if obj: # <<<<<<<<<<<<<< - * self.setitem_slice_assignment(self[index], obj) - * else: - */ - goto __pyx_L5; - } - - /* "View.MemoryView":427 - * 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(1, 427, __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(1, 427, __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(1, 427, __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":422 - * have_slices, index = _unellipsify(index, self.view.ndim) - * - * if have_slices: # <<<<<<<<<<<<<< - * obj = self.is_slice(value) - * if obj: - */ - goto __pyx_L4; - } - - /* "View.MemoryView":429 - * 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(1, 429, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L4:; - - /* "View.MemoryView":416 - * 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":431 - * 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; - __Pyx_RefNannySetupContext("is_slice", 0); - __Pyx_INCREF(__pyx_v_obj); - - /* "View.MemoryView":432 - * - * 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":433 - * 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":434 - * 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(1, 434, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "View.MemoryView":435 - * 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(1, 435, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "View.MemoryView":434 - * 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(1, 434, __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(1, 434, __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":433 - * 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":436 - * 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(1, 436, __pyx_L6_except_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_6); - - /* "View.MemoryView":437 - * 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":433 - * 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":432 - * - * cdef is_slice(self, obj): - * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< - * try: - * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, - */ - } - - /* "View.MemoryView":439 - * 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":431 - * 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":441 - * 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 - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); - - /* "View.MemoryView":445 - * 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(1, 445, __pyx_L1_error) - - /* "View.MemoryView":446 - * - * 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(1, 446, __pyx_L1_error) - - /* "View.MemoryView":447 - * 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_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "View.MemoryView":445 - * 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_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 445, __pyx_L1_error) - - /* "View.MemoryView":441 - * 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_1); - __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":449 - * 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 - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_t_4; - char const *__pyx_t_5; - PyObject *__pyx_t_6 = NULL; - 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; - __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); - - /* "View.MemoryView":451 - * 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":456 - * 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_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); - - /* "View.MemoryView":458 - * 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_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":459 - * - * 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":460 - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * item = tmp - */ - __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":461 - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: - * raise MemoryError # <<<<<<<<<<<<<< - * item = tmp - * else: - */ - PyErr_NoMemory(); __PYX_ERR(1, 461, __pyx_L1_error) - - /* "View.MemoryView":460 - * if self.view.itemsize > sizeof(array): - * tmp = PyMem_Malloc(self.view.itemsize) - * if tmp == NULL: # <<<<<<<<<<<<<< - * raise MemoryError - * item = tmp - */ - } - - /* "View.MemoryView":462 - * if tmp == NULL: - * raise MemoryError - * item = tmp # <<<<<<<<<<<<<< - * else: - * item = array - */ - __pyx_v_item = __pyx_v_tmp; - - /* "View.MemoryView":458 - * 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":464 - * item = tmp - * else: - * item = array # <<<<<<<<<<<<<< - * - * try: - */ - /*else*/ { - __pyx_v_item = ((void *)__pyx_v_array); - } - __pyx_L3:; - - /* "View.MemoryView":466 - * item = array - * - * try: # <<<<<<<<<<<<<< - * if self.dtype_is_object: - * ( item)[0] = value - */ - /*try:*/ { - - /* "View.MemoryView":467 - * - * try: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * ( item)[0] = value - * else: - */ - __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":468 - * 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":467 - * - * try: - * if self.dtype_is_object: # <<<<<<<<<<<<<< - * ( item)[0] = value - * else: - */ - goto __pyx_L8; - } - - /* "View.MemoryView":470 - * ( item)[0] = value - * else: - * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __pyx_t_2 = ((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_2)) __PYX_ERR(1, 470, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } - __pyx_L8:; - - /* "View.MemoryView":474 - * - * - * 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_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":475 - * - * 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_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 475, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":474 - * - * - * 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":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, # <<<<<<<<<<<<<< - * 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":479 - * 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_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); - __Pyx_XGOTREF(__pyx_t_6); - __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_t_3 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; - { - PyMem_Free(__pyx_v_tmp); - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_9); - __Pyx_XGIVEREF(__pyx_t_10); - __Pyx_XGIVEREF(__pyx_t_11); - __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); - } - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_XGIVEREF(__pyx_t_7); - __Pyx_XGIVEREF(__pyx_t_8); - __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); - __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; - __pyx_lineno = __pyx_t_3; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; - goto __pyx_L1_error; - } - __pyx_L7:; - } - - /* "View.MemoryView":449 - * 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_2); - __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":481 - * 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; - __Pyx_RefNannySetupContext("setitem_indexed", 0); - - /* "View.MemoryView":482 - * - * 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(1, 482, __pyx_L1_error) - __pyx_v_itemp = __pyx_t_1; - - /* "View.MemoryView":483 - * 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(1, 483, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":481 - * 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":485 - * 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; - __Pyx_RefNannySetupContext("convert_item_to_object", 0); - - /* "View.MemoryView":488 - * """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(1, 488, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_struct = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":491 - * 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(1, 491, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":492 - * - * 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":493 - * 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(1, 493, __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(1, 493, __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(1, 493, __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(1, 493, __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(1, 493, __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(1, 493, __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":492 - * - * bytesitem = itemp[:self.view.itemsize] - * try: # <<<<<<<<<<<<<< - * result = struct.unpack(self.view.format, bytesitem) - * except struct.error: - */ - } - - /* "View.MemoryView":497 - * 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":498 - * 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(1, 498, __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":497 - * raise ValueError("Unable to convert item to object") - * else: - * if len(self.view.format) == 1: # <<<<<<<<<<<<<< - * return result[0] - * return result - */ - } - - /* "View.MemoryView":499 - * 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":494 - * 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(1, 494, __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(1, 494, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_1); - - /* "View.MemoryView":495 - * 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__9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 495, __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(1, 495, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "View.MemoryView":492 - * - * 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":485 - * 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":501 - * 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; - __Pyx_RefNannySetupContext("assign_item_from_object", 0); - - /* "View.MemoryView":504 - * """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(1, 504, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_struct = __pyx_t_1; - __pyx_t_1 = 0; - - /* "View.MemoryView":509 - * 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":510 - * - * 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(1, 510, __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(1, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 510, __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(1, 510, __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(1, 510, __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(1, 510, __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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 510, __pyx_L1_error) - __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - - /* "View.MemoryView":509 - * cdef Py_ssize_t i - * - * if isinstance(value, tuple): # <<<<<<<<<<<<<< - * bytesvalue = struct.pack(self.view.format, *value) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":512 - * 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(1, 512, __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(1, 512, __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(1, 512, __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(1, 512, __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(1, 512, __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(1, 512, __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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 512, __pyx_L1_error) - __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - } - __pyx_L3:; - - /* "View.MemoryView":514 - * 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(1, 514, __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":515 - * - * for i, c in enumerate(bytesvalue): - * itemp[i] = c # <<<<<<<<<<<<<< - * - * @cname('getbuffer') - */ - __pyx_v_i = __pyx_t_9; - - /* "View.MemoryView":514 - * 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":515 - * - * 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":501 - * 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":518 - * - * @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; - 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":519 - * @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":520 - * 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__10, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 520, __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(1, 520, __pyx_L1_error) - - /* "View.MemoryView":519 - * @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":522 - * 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":523 - * - * 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":522 - * 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":525 - * info.shape = self.view.shape - * else: - * info.shape = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_STRIDES: - */ - /*else*/ { - __pyx_v_info->shape = NULL; - } - __pyx_L6:; - - /* "View.MemoryView":527 - * 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":528 - * - * 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":527 - * info.shape = NULL - * - * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< - * info.strides = self.view.strides - * else: - */ - goto __pyx_L7; - } - - /* "View.MemoryView":530 - * info.strides = self.view.strides - * else: - * info.strides = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_INDIRECT: - */ - /*else*/ { - __pyx_v_info->strides = NULL; - } - __pyx_L7:; - - /* "View.MemoryView":532 - * 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":533 - * - * 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":532 - * info.strides = NULL - * - * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< - * info.suboffsets = self.view.suboffsets - * else: - */ - goto __pyx_L8; - } - - /* "View.MemoryView":535 - * info.suboffsets = self.view.suboffsets - * else: - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * - * if flags & PyBUF_FORMAT: - */ - /*else*/ { - __pyx_v_info->suboffsets = NULL; - } - __pyx_L8:; - - /* "View.MemoryView":537 - * 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":538 - * - * 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":537 - * info.suboffsets = NULL - * - * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * info.format = self.view.format - * else: - */ - goto __pyx_L9; - } - - /* "View.MemoryView":540 - * info.format = self.view.format - * else: - * info.format = NULL # <<<<<<<<<<<<<< - * - * info.buf = self.view.buf - */ - /*else*/ { - __pyx_v_info->format = NULL; - } - __pyx_L9:; - - /* "View.MemoryView":542 - * 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":543 - * - * 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":544 - * 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":545 - * 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":546 - * 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":547 - * 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":518 - * - * @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":553 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":554 - * @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(1, 554, __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(1, 554, __pyx_L1_error) - __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":555 - * 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(1, 555, __pyx_L1_error) - - /* "View.MemoryView":556 - * 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":553 - * - * @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":559 - * - * @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":560 - * @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":559 - * - * @property - * def base(self): # <<<<<<<<<<<<<< - * return self.obj - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":563 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":564 - * @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(1, 564, __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(1, 564, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 564, __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(1, 564, __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":563 - * - * @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":567 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":568 - * @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":570 - * 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__11, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 570, __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(1, 570, __pyx_L1_error) - - /* "View.MemoryView":568 - * @property - * def strides(self): - * if self.view.strides == NULL: # <<<<<<<<<<<<<< - * - * raise ValueError("Buffer view does not expose strides") - */ - } - - /* "View.MemoryView":572 - * 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(1, 572, __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(1, 572, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(1, 572, __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(1, 572, __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":567 - * - * @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":575 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":576 - * @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":577 - * 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(1, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__12, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 577, __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":576 - * @property - * def suboffsets(self): - * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< - * return (-1,) * self.view.ndim - * - */ - } - - /* "View.MemoryView":579 - * 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(1, 579, __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(1, 579, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(1, 579, __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(1, 579, __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":575 - * - * @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":582 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":583 - * @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(1, 583, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":582 - * - * @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":586 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":587 - * @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(1, 587, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":586 - * - * @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":590 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":591 - * @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(1, 591, __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(1, 591, __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(1, 591, __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":590 - * - * @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":594 - * - * @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; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "View.MemoryView":595 - * @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":596 - * 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":598 - * 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(1, 598, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); - __pyx_t_6 = 0; - - /* "View.MemoryView":599 - * - * 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(1, 599, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); - __pyx_t_6 = 0; - } - - /* "View.MemoryView":601 - * 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":595 - * @property - * def size(self): - * if self._size is None: # <<<<<<<<<<<<<< - * result = 1 - * - */ - } - - /* "View.MemoryView":603 - * 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":594 - * - * @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":605 - * 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":606 - * - * 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":607 - * 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":606 - * - * def __len__(self): - * if self.view.ndim >= 1: # <<<<<<<<<<<<<< - * return self.view.shape[0] - * - */ - } - - /* "View.MemoryView":609 - * return self.view.shape[0] - * - * return 0 # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":605 - * 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":611 - * 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; - __Pyx_RefNannySetupContext("__repr__", 0); - - /* "View.MemoryView":612 - * - * 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(1, 612, __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(1, 612, __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(1, 612, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "View.MemoryView":613 - * 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(1, 613, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - - /* "View.MemoryView":612 - * - * def __repr__(self): - * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< - * id(self)) - * - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 612, __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(1, 612, __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":611 - * 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":615 - * 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; - __Pyx_RefNannySetupContext("__str__", 0); - - /* "View.MemoryView":616 - * - * 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(1, 616, __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(1, 616, __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(1, 616, __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(1, 616, __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(1, 616, __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":615 - * 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":619 - * - * - * 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 - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("is_c_contig", 0); - - /* "View.MemoryView":622 - * 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_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); - - /* "View.MemoryView":623 - * 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_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 623, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":619 - * - * - * def is_c_contig(self): # <<<<<<<<<<<<<< - * cdef __Pyx_memviewslice *mslice - * cdef __Pyx_memviewslice tmp - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __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":625 - * 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 - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("is_f_contig", 0); - - /* "View.MemoryView":628 - * 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_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); - - /* "View.MemoryView":629 - * 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_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 629, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":625 - * 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_1); - __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":631 - * 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; - __Pyx_RefNannySetupContext("copy", 0); - - /* "View.MemoryView":633 - * 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":635 - * 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":636 - * - * 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(1, 636, __pyx_L1_error) - __pyx_v_mslice = __pyx_t_1; - - /* "View.MemoryView":641 - * 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(1, 641, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":631 - * 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":643 - * 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; - __Pyx_RefNannySetupContext("copy_fortran", 0); - - /* "View.MemoryView":645 - * 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":647 - * 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":648 - * - * 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(1, 648, __pyx_L1_error) - __pyx_v_dst = __pyx_t_1; - - /* "View.MemoryView":653 - * 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(1, 653, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":643 - * 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; - __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__13, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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; - __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__14, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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":657 - * - * @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; - __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); - - /* "View.MemoryView":658 - * @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(1, 658, __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(1, 658, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 658, __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(1, 658, __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":659 - * 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":660 - * 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":657 - * - * @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":663 - * - * @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":664 - * @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":663 - * - * @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":666 - * 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; - __Pyx_RefNannySetupContext("_unellipsify", 0); - - /* "View.MemoryView":671 - * 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":672 - * """ - * if not isinstance(index, tuple): - * tup = (index,) # <<<<<<<<<<<<<< - * else: - * tup = index - */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 672, __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":671 - * full slices. - * """ - * if not isinstance(index, tuple): # <<<<<<<<<<<<<< - * tup = (index,) - * else: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":674 - * tup = (index,) - * else: - * tup = index # <<<<<<<<<<<<<< - * - * result = [] - */ - /*else*/ { - __Pyx_INCREF(__pyx_v_index); - __pyx_v_tup = __pyx_v_index; - } - __pyx_L3:; - - /* "View.MemoryView":676 - * tup = index - * - * result = [] # <<<<<<<<<<<<<< - * have_slices = False - * seen_ellipsis = False - */ - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 676, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_result = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":677 - * - * result = [] - * have_slices = False # <<<<<<<<<<<<<< - * seen_ellipsis = False - * for idx, item in enumerate(tup): - */ - __pyx_v_have_slices = 0; - - /* "View.MemoryView":678 - * result = [] - * have_slices = False - * seen_ellipsis = False # <<<<<<<<<<<<<< - * for idx, item in enumerate(tup): - * if item is Ellipsis: - */ - __pyx_v_seen_ellipsis = 0; - - /* "View.MemoryView":679 - * 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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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":680 - * 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":681 - * 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":682 - * 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(1, 682, __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(1, 682, __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__15); - __Pyx_GIVEREF(__pyx_slice__15); - PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__15); - } - } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 682, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "View.MemoryView":683 - * 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":681 - * 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":685 - * seen_ellipsis = True - * else: - * result.append(slice(None)) # <<<<<<<<<<<<<< - * have_slices = True - * else: - */ - /*else*/ { - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__15); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 685, __pyx_L1_error) - } - __pyx_L7:; - - /* "View.MemoryView":686 - * 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":680 - * 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":688 - * 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":689 - * 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(1, 689, __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(1, 689, __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(1, 689, __pyx_L1_error) - - /* "View.MemoryView":688 - * 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":691 - * 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":692 - * - * 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(1, 692, __pyx_L1_error) - } - __pyx_L6:; - - /* "View.MemoryView":679 - * 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":694 - * 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(1, 694, __pyx_L1_error) - __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); - - /* "View.MemoryView":695 - * - * nslices = ndim - len(result) - * if nslices: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * nslices) - * - */ - __pyx_t_1 = (__pyx_v_nslices != 0); - if (__pyx_t_1) { - - /* "View.MemoryView":696 - * 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(1, 696, __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__15); - __Pyx_GIVEREF(__pyx_slice__15); - PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__15); - } - } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 696, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "View.MemoryView":695 - * - * nslices = ndim - len(result) - * if nslices: # <<<<<<<<<<<<<< - * result.extend([slice(None)] * nslices) - * - */ - } - - /* "View.MemoryView":698 - * 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(1, 698, __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(1, 698, __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(1, 698, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 698, __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":666 - * 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":700 - * 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; - __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); - - /* "View.MemoryView":701 - * - * 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":702 - * 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":703 - * 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__16, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 703, __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(1, 703, __pyx_L1_error) - - /* "View.MemoryView":702 - * 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":700 - * 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":710 - * - * @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; - __Pyx_RefNannySetupContext("memview_slice", 0); - - /* "View.MemoryView":711 - * @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":718 - * - * - * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< - * - * cdef _memoryviewslice memviewsliceobj - */ - (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); - - /* "View.MemoryView":722 - * 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(1, 722, __pyx_L1_error) - } - } - #endif - - /* "View.MemoryView":724 - * 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":725 - * - * 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(1, 725, __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":726 - * 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":724 - * assert memview.view.ndim > 0 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * memviewsliceobj = memview - * p_src = &memviewsliceobj.from_slice - */ - goto __pyx_L3; - } - - /* "View.MemoryView":728 - * 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":729 - * else: - * slice_copy(memview, &src) - * p_src = &src # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_p_src = (&__pyx_v_src); - } - __pyx_L3:; - - /* "View.MemoryView":735 - * - * - * 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":736 - * - * 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":741 - * - * - * 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":742 - * - * 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":746 - * 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(1, 746, __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(1, 746, __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(1, 746, __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(1, 746, __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(1, 746, __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(1, 746, __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(1, 746, __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":747 - * - * 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":751 - * 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(1, 751, __pyx_L1_error) - - /* "View.MemoryView":748 - * 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(1, 748, __pyx_L1_error) - - /* "View.MemoryView":747 - * - * 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":754 - * 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":755 - * 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":756 - * 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":757 - * 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":758 - * 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":754 - * 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":760 - * 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(1, 760, __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(1, 760, __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(1, 760, __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":761 - * 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(1, 761, __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(1, 761, __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(1, 761, __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":762 - * 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(1, 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(1, 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(1, 762, __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":764 - * 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(1, 764, __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":765 - * - * 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(1, 765, __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":766 - * 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(1, 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_step = __pyx_t_1; - - /* "View.MemoryView":768 - * 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(1, 768, __pyx_L1_error) - - /* "View.MemoryView":774 - * 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":746 - * 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":776 - * 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":777 - * - * 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":778 - * 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(1, 778, __pyx_L1_error) } - - /* "View.MemoryView":779 - * 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(1, 779, __pyx_L1_error) } - - /* "View.MemoryView":777 - * - * 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(1, 777, __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(1, 777, __pyx_L1_error) - __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "View.MemoryView":776 - * new_ndim += 1 - * - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * return memoryview_fromslice(dst, new_ndim, - * memviewsliceobj.to_object_func, - */ - } - - /* "View.MemoryView":782 - * 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":783 - * 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(1, 782, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "View.MemoryView":782 - * 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(1, 782, __pyx_L1_error) - __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":710 - * - * @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":807 - * - * @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; - - /* "View.MemoryView":827 - * 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":829 - * 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":830 - * - * 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":829 - * if not is_slice: - * - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if not 0 <= start < shape: - */ - } - - /* "View.MemoryView":831 - * 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":832 - * 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(1, 832, __pyx_L1_error) - - /* "View.MemoryView":831 - * if start < 0: - * start += shape - * if not 0 <= start < shape: # <<<<<<<<<<<<<< - * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) - * else: - */ - } - - /* "View.MemoryView":827 - * cdef bint negative_step - * - * if not is_slice: # <<<<<<<<<<<<<< - * - * if start < 0: - */ - goto __pyx_L3; - } - - /* "View.MemoryView":835 - * 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":837 - * 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":838 - * - * 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(1, 838, __pyx_L1_error) - - /* "View.MemoryView":837 - * 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":841 - * - * - * if have_start: # <<<<<<<<<<<<<< - * if start < 0: - * start += shape - */ - __pyx_t_2 = (__pyx_v_have_start != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":842 - * - * 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":843 - * if have_start: - * if start < 0: - * start += shape # <<<<<<<<<<<<<< - * if start < 0: - * start = 0 - */ - __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - - /* "View.MemoryView":844 - * 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":845 - * start += shape - * if start < 0: - * start = 0 # <<<<<<<<<<<<<< - * elif start >= shape: - * if negative_step: - */ - __pyx_v_start = 0; - - /* "View.MemoryView":844 - * if start < 0: - * start += shape - * if start < 0: # <<<<<<<<<<<<<< - * start = 0 - * elif start >= shape: - */ - } - - /* "View.MemoryView":842 - * - * if have_start: - * if start < 0: # <<<<<<<<<<<<<< - * start += shape - * if start < 0: - */ - goto __pyx_L12; - } - - /* "View.MemoryView":846 - * 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":847 - * 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":848 - * elif start >= shape: - * if negative_step: - * start = shape - 1 # <<<<<<<<<<<<<< - * else: - * start = shape - */ - __pyx_v_start = (__pyx_v_shape - 1); - - /* "View.MemoryView":847 - * start = 0 - * elif start >= shape: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - goto __pyx_L14; - } - - /* "View.MemoryView":850 - * start = shape - 1 - * else: - * start = shape # <<<<<<<<<<<<<< - * else: - * if negative_step: - */ - /*else*/ { - __pyx_v_start = __pyx_v_shape; - } - __pyx_L14:; - - /* "View.MemoryView":846 - * if start < 0: - * start = 0 - * elif start >= shape: # <<<<<<<<<<<<<< - * if negative_step: - * start = shape - 1 - */ - } - __pyx_L12:; - - /* "View.MemoryView":841 - * - * - * if have_start: # <<<<<<<<<<<<<< - * if start < 0: - * start += shape - */ - goto __pyx_L11; - } - - /* "View.MemoryView":852 - * 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":853 - * else: - * if negative_step: - * start = shape - 1 # <<<<<<<<<<<<<< - * else: - * start = 0 - */ - __pyx_v_start = (__pyx_v_shape - 1); - - /* "View.MemoryView":852 - * start = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * start = shape - 1 - * else: - */ - goto __pyx_L15; - } - - /* "View.MemoryView":855 - * start = shape - 1 - * else: - * start = 0 # <<<<<<<<<<<<<< - * - * if have_stop: - */ - /*else*/ { - __pyx_v_start = 0; - } - __pyx_L15:; - } - __pyx_L11:; - - /* "View.MemoryView":857 - * start = 0 - * - * if have_stop: # <<<<<<<<<<<<<< - * if stop < 0: - * stop += shape - */ - __pyx_t_2 = (__pyx_v_have_stop != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":858 - * - * 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":859 - * if have_stop: - * if stop < 0: - * stop += shape # <<<<<<<<<<<<<< - * if stop < 0: - * stop = 0 - */ - __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); - - /* "View.MemoryView":860 - * 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":861 - * stop += shape - * if stop < 0: - * stop = 0 # <<<<<<<<<<<<<< - * elif stop > shape: - * stop = shape - */ - __pyx_v_stop = 0; - - /* "View.MemoryView":860 - * if stop < 0: - * stop += shape - * if stop < 0: # <<<<<<<<<<<<<< - * stop = 0 - * elif stop > shape: - */ - } - - /* "View.MemoryView":858 - * - * if have_stop: - * if stop < 0: # <<<<<<<<<<<<<< - * stop += shape - * if stop < 0: - */ - goto __pyx_L17; - } - - /* "View.MemoryView":862 - * 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":863 - * stop = 0 - * elif stop > shape: - * stop = shape # <<<<<<<<<<<<<< - * else: - * if negative_step: - */ - __pyx_v_stop = __pyx_v_shape; - - /* "View.MemoryView":862 - * if stop < 0: - * stop = 0 - * elif stop > shape: # <<<<<<<<<<<<<< - * stop = shape - * else: - */ - } - __pyx_L17:; - - /* "View.MemoryView":857 - * start = 0 - * - * if have_stop: # <<<<<<<<<<<<<< - * if stop < 0: - * stop += shape - */ - goto __pyx_L16; - } - - /* "View.MemoryView":865 - * stop = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * stop = -1 - * else: - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_negative_step != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":866 - * else: - * if negative_step: - * stop = -1 # <<<<<<<<<<<<<< - * else: - * stop = shape - */ - __pyx_v_stop = -1L; - - /* "View.MemoryView":865 - * stop = shape - * else: - * if negative_step: # <<<<<<<<<<<<<< - * stop = -1 - * else: - */ - goto __pyx_L19; - } - - /* "View.MemoryView":868 - * stop = -1 - * else: - * stop = shape # <<<<<<<<<<<<<< - * - * if not have_step: - */ - /*else*/ { - __pyx_v_stop = __pyx_v_shape; - } - __pyx_L19:; - } - __pyx_L16:; - - /* "View.MemoryView":870 - * stop = shape - * - * if not have_step: # <<<<<<<<<<<<<< - * step = 1 - * - */ - __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":871 - * - * if not have_step: - * step = 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_step = 1; - - /* "View.MemoryView":870 - * stop = shape - * - * if not have_step: # <<<<<<<<<<<<<< - * step = 1 - * - */ - } - - /* "View.MemoryView":875 - * - * 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":877 - * 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":878 - * - * if (stop - start) - step * new_shape: - * new_shape += 1 # <<<<<<<<<<<<<< - * - * if new_shape < 0: - */ - __pyx_v_new_shape = (__pyx_v_new_shape + 1); - - /* "View.MemoryView":877 - * new_shape = (stop - start) // step - * - * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< - * new_shape += 1 - * - */ - } - - /* "View.MemoryView":880 - * 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":881 - * - * if new_shape < 0: - * new_shape = 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_new_shape = 0; - - /* "View.MemoryView":880 - * new_shape += 1 - * - * if new_shape < 0: # <<<<<<<<<<<<<< - * new_shape = 0 - * - */ - } - - /* "View.MemoryView":884 - * - * - * 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":885 - * - * 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":886 - * 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":889 - * - * - * 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":890 - * - * 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":889 - * - * - * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< - * dst.data += start * stride - * else: - */ - goto __pyx_L23; - } - - /* "View.MemoryView":892 - * 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":894 - * 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":895 - * - * 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":896 - * 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":897 - * 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":896 - * if suboffset >= 0: - * if not is_slice: - * if new_ndim == 0: # <<<<<<<<<<<<<< - * dst.data = ( dst.data)[0] + suboffset - * else: - */ - goto __pyx_L26; - } - - /* "View.MemoryView":899 - * 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":900 - * 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(1, 899, __pyx_L1_error) - } - __pyx_L26:; - - /* "View.MemoryView":895 - * - * if suboffset >= 0: - * if not is_slice: # <<<<<<<<<<<<<< - * if new_ndim == 0: - * dst.data = ( dst.data)[0] + suboffset - */ - goto __pyx_L25; - } - - /* "View.MemoryView":902 - * "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":894 - * dst.suboffsets[suboffset_dim[0]] += start * stride - * - * if suboffset >= 0: # <<<<<<<<<<<<<< - * if not is_slice: - * if new_ndim == 0: - */ - } - - /* "View.MemoryView":904 - * suboffset_dim[0] = new_ndim - * - * return 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":807 - * - * @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":910 - * - * @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; - __Pyx_RefNannySetupContext("pybuffer_index", 0); - - /* "View.MemoryView":912 - * 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":913 - * 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":916 - * 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":917 - * - * 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(1, 917, __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(1, 917, __pyx_L1_error) - } - __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); - - /* "View.MemoryView":918 - * if view.ndim == 0: - * shape = view.len / itemsize - * stride = itemsize # <<<<<<<<<<<<<< - * else: - * shape = view.shape[dim] - */ - __pyx_v_stride = __pyx_v_itemsize; - - /* "View.MemoryView":916 - * cdef char *resultp - * - * if view.ndim == 0: # <<<<<<<<<<<<<< - * shape = view.len / itemsize - * stride = itemsize - */ - goto __pyx_L3; - } - - /* "View.MemoryView":920 - * 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":921 - * 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":922 - * 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":923 - * 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":922 - * shape = view.shape[dim] - * stride = view.strides[dim] - * if view.suboffsets != NULL: # <<<<<<<<<<<<<< - * suboffset = view.suboffsets[dim] - * - */ - } - } - __pyx_L3:; - - /* "View.MemoryView":925 - * 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":926 - * - * 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":927 - * 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":928 - * 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(1, 928, __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(1, 928, __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(1, 928, __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(1, 928, __pyx_L1_error) - - /* "View.MemoryView":927 - * if index < 0: - * index += view.shape[dim] - * if index < 0: # <<<<<<<<<<<<<< - * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) - * - */ - } - - /* "View.MemoryView":925 - * suboffset = view.suboffsets[dim] - * - * if index < 0: # <<<<<<<<<<<<<< - * index += view.shape[dim] - * if index < 0: - */ - } - - /* "View.MemoryView":930 - * 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":931 - * - * 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(1, 931, __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(1, 931, __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(1, 931, __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(1, 931, __pyx_L1_error) - - /* "View.MemoryView":930 - * 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":933 - * 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":934 - * - * 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":935 - * 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":934 - * - * resultp = bufp + index * stride - * if suboffset >= 0: # <<<<<<<<<<<<<< - * resultp = ( resultp)[0] + suboffset - * - */ - } - - /* "View.MemoryView":937 - * resultp = ( resultp)[0] + suboffset - * - * return resultp # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_resultp; - goto __pyx_L0; - - /* "View.MemoryView":910 - * - * @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":943 - * - * @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; - - /* "View.MemoryView":944 - * @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":946 - * 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":947 - * - * 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":951 - * - * 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":952 - * 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":953 - * 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":954 - * 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":956 - * 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":957 - * - * 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(1, 957, __pyx_L1_error) - - /* "View.MemoryView":956 - * 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":959 - * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") - * - * return 1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 1; - goto __pyx_L0; - - /* "View.MemoryView":943 - * - * @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":976 - * 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":977 - * - * 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":976 - * 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":979 - * __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; - __Pyx_RefNannySetupContext("convert_item_to_object", 0); - - /* "View.MemoryView":980 - * - * 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":981 - * 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(1, 981, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "View.MemoryView":980 - * - * cdef convert_item_to_object(self, char *itemp): - * if self.to_object_func != NULL: # <<<<<<<<<<<<<< - * return self.to_object_func(itemp) - * else: - */ - } - - /* "View.MemoryView":983 - * 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(1, 983, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - } - - /* "View.MemoryView":979 - * __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":985 - * 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; - __Pyx_RefNannySetupContext("assign_item_from_object", 0); - - /* "View.MemoryView":986 - * - * 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":987 - * 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(1, 987, __pyx_L1_error) - - /* "View.MemoryView":986 - * - * 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":989 - * 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(1, 989, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - __pyx_L3:; - - /* "View.MemoryView":985 - * 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":992 - * - * @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":993 - * @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":992 - * - * @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; - __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__17, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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; - __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__18, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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":999 - * - * @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; - __Pyx_RefNannySetupContext("memoryview_fromslice", 0); - - /* "View.MemoryView":1007 - * 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":1008 - * - * if memviewslice.memview == Py_None: - * return None # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - - /* "View.MemoryView":1007 - * cdef _memoryviewslice result - * - * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< - * return None - * - */ - } - - /* "View.MemoryView":1013 - * - * - * 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(1, 1013, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1013, __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(1, 1013, __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":1015 - * 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":1016 - * - * result.from_slice = memviewslice - * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< - * - * result.from_object = ( memviewslice.memview).base - */ - __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); - - /* "View.MemoryView":1018 - * __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(1, 1018, __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":1019 - * - * 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":1021 - * 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":1022 - * - * 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":1023 - * 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":1024 - * 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":1025 - * 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":1027 - * 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":1028 - * - * 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":1027 - * Py_INCREF(Py_None) - * - * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< - * result.flags = PyBUF_RECORDS - * else: - */ - goto __pyx_L4; - } - - /* "View.MemoryView":1030 - * 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":1032 - * 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":1033 - * - * 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":1036 - * - * - * 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":1037 - * - * 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":1038 - * 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":1039 - * 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":1040 - * if suboffset >= 0: - * result.view.suboffsets = result.from_slice.suboffsets - * break # <<<<<<<<<<<<<< - * - * result.view.len = result.view.itemsize - */ - goto __pyx_L6_break; - - /* "View.MemoryView":1038 - * 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":1042 - * 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":1043 - * - * 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(1, 1043, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); - __pyx_t_2 = 0; - - /* "View.MemoryView":1044 - * 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(1, 1044, __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(1, 1044, __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(1, 1044, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - } - - /* "View.MemoryView":1046 - * 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":1047 - * - * 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":1049 - * 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":999 - * - * @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":1052 - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *mslice): - * 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; - __Pyx_RefNannySetupContext("get_slice_from_memview", 0); - - /* "View.MemoryView":1055 - * __Pyx_memviewslice *mslice): - * 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":1056 - * 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(1, 1056, __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":1057 - * 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":1055 - * __Pyx_memviewslice *mslice): - * cdef _memoryviewslice obj - * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< - * obj = memview - * return &obj.from_slice - */ - } - - /* "View.MemoryView":1059 - * return &obj.from_slice - * else: - * slice_copy(memview, mslice) # <<<<<<<<<<<<<< - * return mslice - * - */ - /*else*/ { - __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); - - /* "View.MemoryView":1060 - * else: - * slice_copy(memview, mslice) - * return mslice # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_slice_copy') - */ - __pyx_r = __pyx_v_mslice; - goto __pyx_L0; - } - - /* "View.MemoryView":1052 - * - * @cname('__pyx_memoryview_get_slice_from_memoryview') - * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< - * __Pyx_memviewslice *mslice): - * cdef _memoryviewslice obj - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_obj); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "View.MemoryView":1063 - * - * @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":1067 - * 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":1068 - * - * 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":1069 - * 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":1071 - * 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":1072 - * - * 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":1074 - * 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":1075 - * - * 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":1076 - * 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":1077 - * 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":1063 - * - * @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":1080 - * - * @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; - __Pyx_RefNannySetupContext("memoryview_copy", 0); - - /* "View.MemoryView":1083 - * "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":1084 - * 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(1, 1084, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "View.MemoryView":1080 - * - * @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":1087 - * - * @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; - __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); - - /* "View.MemoryView":1094 - * 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":1095 - * - * 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":1096 - * 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":1094 - * 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":1098 - * 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":1099 - * 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":1101 - * 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":1103 - * 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(1, 1101, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "View.MemoryView":1087 - * - * @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":1109 - * - * - * 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":1110 - * - * 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":1111 - * 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":1110 - * - * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: - * if arg < 0: # <<<<<<<<<<<<<< - * return -arg - * else: - */ - } - - /* "View.MemoryView":1113 - * return -arg - * else: - * return arg # <<<<<<<<<<<<<< - * - * @cname('__pyx_get_best_slice_order') - */ - /*else*/ { - __pyx_r = __pyx_v_arg; - goto __pyx_L0; - } - - /* "View.MemoryView":1109 - * - * - * 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":1116 - * - * @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":1121 - * """ - * cdef int i - * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< - * cdef Py_ssize_t f_stride = 0 - * - */ - __pyx_v_c_stride = 0; - - /* "View.MemoryView":1122 - * 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":1124 - * 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":1125 - * - * 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":1126 - * 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":1127 - * if mslice.shape[i] > 1: - * c_stride = mslice.strides[i] - * break # <<<<<<<<<<<<<< - * - * for i in range(ndim): - */ - goto __pyx_L4_break; - - /* "View.MemoryView":1125 - * - * for i in range(ndim - 1, -1, -1): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * c_stride = mslice.strides[i] - * break - */ - } - } - __pyx_L4_break:; - - /* "View.MemoryView":1129 - * 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":1130 - * - * 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":1131 - * 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":1132 - * 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":1130 - * - * for i in range(ndim): - * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< - * f_stride = mslice.strides[i] - * break - */ - } - } - __pyx_L7_break:; - - /* "View.MemoryView":1134 - * 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":1135 - * - * 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":1134 - * break - * - * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< - * return 'C' - * else: - */ - } - - /* "View.MemoryView":1137 - * return 'C' - * else: - * return 'F' # <<<<<<<<<<<<<< - * - * @cython.cdivision(True) - */ - /*else*/ { - __pyx_r = 'F'; - goto __pyx_L0; - } - - /* "View.MemoryView":1116 - * - * @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":1140 - * - * @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":1147 - * - * 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":1148 - * 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":1149 - * 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":1150 - * 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":1152 - * 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":1153 - * - * 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":1154 - * 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":1153 - * - * 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":1155 - * 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":1153 - * - * 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":1157 - * 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":1158 - * 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":1159 - * 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":1160 - * 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":1152 - * 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":1162 - * 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":1163 - * 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":1167 - * 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":1168 - * 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":1140 - * - * @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":1170 - * 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":1173 - * __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":1170 - * 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":1177 - * - * @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 int i - */ - -static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { - int __pyx_v_i; - Py_ssize_t __pyx_v_size; - Py_ssize_t __pyx_r; - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - int __pyx_t_4; - - /* "View.MemoryView":1180 - * "Return the size of the memory occupied by the slice in number of bytes" - * cdef int i - * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< - * - * for i in range(ndim): - */ - __pyx_t_1 = __pyx_v_src->memview->view.itemsize; - __pyx_v_size = __pyx_t_1; - - /* "View.MemoryView":1182 - * cdef Py_ssize_t size = src.memview.view.itemsize - * - * for i in range(ndim): # <<<<<<<<<<<<<< - * size *= src.shape[i] - * - */ - __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_i = __pyx_t_4; - - /* "View.MemoryView":1183 - * - * for i in range(ndim): - * size *= src.shape[i] # <<<<<<<<<<<<<< - * - * return size - */ - __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); - } - - /* "View.MemoryView":1185 - * size *= src.shape[i] - * - * return size # <<<<<<<<<<<<<< - * - * @cname('__pyx_fill_contig_strides_array') - */ - __pyx_r = __pyx_v_size; - goto __pyx_L0; - - /* "View.MemoryView":1177 - * - * @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 int i - */ - - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} - -/* "View.MemoryView":1188 - * - * @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":1197 - * 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":1198 - * - * if order == 'F': - * for idx in range(ndim): # <<<<<<<<<<<<<< - * strides[idx] = stride - * 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":1199 - * if order == 'F': - * for idx in range(ndim): - * strides[idx] = stride # <<<<<<<<<<<<<< - * stride = stride * shape[idx] - * else: - */ - (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - - /* "View.MemoryView":1200 - * for idx in range(ndim): - * strides[idx] = stride - * 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":1197 - * cdef int idx - * - * if order == 'F': # <<<<<<<<<<<<<< - * for idx in range(ndim): - * strides[idx] = stride - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1202 - * stride = stride * shape[idx] - * else: - * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * strides[idx] = stride - * 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":1203 - * else: - * for idx in range(ndim - 1, -1, -1): - * strides[idx] = stride # <<<<<<<<<<<<<< - * stride = stride * shape[idx] - * - */ - (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - - /* "View.MemoryView":1204 - * for idx in range(ndim - 1, -1, -1): - * strides[idx] = stride - * stride = stride * shape[idx] # <<<<<<<<<<<<<< - * - * return stride - */ - __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); - } - } - __pyx_L3:; - - /* "View.MemoryView":1206 - * stride = stride * shape[idx] - * - * return stride # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_data_to_temp') - */ - __pyx_r = __pyx_v_stride; - goto __pyx_L0; - - /* "View.MemoryView":1188 - * - * @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":1209 - * - * @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; - - /* "View.MemoryView":1220 - * 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":1221 - * - * 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":1223 - * 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":1224 - * - * result = malloc(size) - * if not result: # <<<<<<<<<<<<<< - * _err(MemoryError, NULL) - * - */ - __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1225 - * 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(1, 1225, __pyx_L1_error) - - /* "View.MemoryView":1224 - * - * result = malloc(size) - * if not result: # <<<<<<<<<<<<<< - * _err(MemoryError, NULL) - * - */ - } - - /* "View.MemoryView":1228 - * - * - * tmpslice.data = result # <<<<<<<<<<<<<< - * tmpslice.memview = src.memview - * for i in range(ndim): - */ - __pyx_v_tmpslice->data = ((char *)__pyx_v_result); - - /* "View.MemoryView":1229 - * - * 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":1230 - * 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":1231 - * 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":1232 - * 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":1234 - * 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":1238 - * - * - * 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":1239 - * - * 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":1240 - * 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":1239 - * - * for i in range(ndim): - * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< - * tmpslice.strides[i] = 0 - * - */ - } - } - - /* "View.MemoryView":1242 - * 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":1243 - * - * 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":1242 - * tmpslice.strides[i] = 0 - * - * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< - * memcpy(result, src.data, size) - * else: - */ - goto __pyx_L9; - } - - /* "View.MemoryView":1245 - * 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":1247 - * copy_strided_to_strided(src, tmpslice, ndim, itemsize) - * - * return result # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_result; - goto __pyx_L0; - - /* "View.MemoryView":1209 - * - * @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":1252 - * - * @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; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err_extents", 0); - - /* "View.MemoryView":1255 - * 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(1, 1255, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1255, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1255, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1255, __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":1254 - * 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(1, 1254, __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(1, 1254, __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(1, 1254, __pyx_L1_error) - - /* "View.MemoryView":1252 - * - * @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":1258 - * - * @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; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err_dim", 0); - __Pyx_INCREF(__pyx_v_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) # <<<<<<<<<<<<<< - * - * @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(1, 1259, __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(1, 1259, __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(1, 1259, __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(1, 1259, __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(1, 1259, __pyx_L1_error) - - /* "View.MemoryView":1258 - * - * @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":1262 - * - * @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; - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); - #endif - __Pyx_RefNannySetupContext("_err", 0); - __Pyx_INCREF(__pyx_v_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')) - * else: - */ - __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "View.MemoryView":1264 - * 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(1, 1264, __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(1, 1264, __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(1, 1264, __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')) - * else: - */ - } - - /* "View.MemoryView":1266 - * raise error(msg.decode('ascii')) - * else: - * raise error # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_copy_contents') - */ - /*else*/ { - __Pyx_Raise(__pyx_v_error, 0, 0, 0); - __PYX_ERR(1, 1266, __pyx_L1_error) - } - - /* "View.MemoryView":1262 - * - * @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":1269 - * - * @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; - - /* "View.MemoryView":1277 - * 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":1278 - * """ - * 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":1280 - * 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":1281 - * 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":1282 - * 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":1285 - * 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":1286 - * - * 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":1285 - * 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":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_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1288 - * 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":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_L3:; - - /* "View.MemoryView":1290 - * 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":1292 - * 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":1293 - * - * 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":1294 - * 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":1295 - * 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":1296 - * 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":1294 - * 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":1298 - * 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(1, 1298, __pyx_L1_error) - } - __pyx_L7:; - - /* "View.MemoryView":1293 - * - * for i in range(ndim): - * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< - * if src.shape[i] == 1: - * broadcasting = True - */ - } - - /* "View.MemoryView":1300 - * _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":1301 - * - * 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(1, 1301, __pyx_L1_error) - - /* "View.MemoryView":1300 - * _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":1303 - * _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":1305 - * 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":1306 - * - * 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":1305 - * if slices_overlap(&src, &dst, ndim, itemsize): - * - * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< - * order = get_best_order(&dst, ndim) - * - */ - } - - /* "View.MemoryView":1308 - * 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(1, 1308, __pyx_L1_error) - __pyx_v_tmpdata = __pyx_t_7; - - /* "View.MemoryView":1309 - * - * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) - * src = tmp # <<<<<<<<<<<<<< - * - * if not broadcasting: - */ - __pyx_v_src = __pyx_v_tmp; - - /* "View.MemoryView":1303 - * _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":1311 - * src = tmp - * - * if not broadcasting: # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1314 - * - * - * 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":1315 - * - * 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":1314 - * - * - * 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":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_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'F', __pyx_v_ndim) != 0); - if (__pyx_t_2) { - - /* "View.MemoryView":1317 - * 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":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_L12:; - - /* "View.MemoryView":1319 - * 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":1321 - * 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":1322 - * - * 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":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) - * return 0 - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1324 - * 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":1325 - * 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":1319 - * direct_copy = slice_is_contig(dst, 'F', ndim) - * - * if direct_copy: # <<<<<<<<<<<<<< - * - * refcount_copying(&dst, dtype_is_object, ndim, False) - */ - } - - /* "View.MemoryView":1311 - * src = tmp - * - * if not broadcasting: # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":1327 - * 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":1330 - * - * - * transpose_memslice(&src) # <<<<<<<<<<<<<< - * transpose_memslice(&dst) - * - */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1330, __pyx_L1_error) - - /* "View.MemoryView":1331 - * - * 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(1, 1331, __pyx_L1_error) - - /* "View.MemoryView":1327 - * return 0 - * - * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< - * - * - */ - } - - /* "View.MemoryView":1333 - * 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":1334 - * - * 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":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) # <<<<<<<<<<<<<< - * - * free(tmpdata) - */ - __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - - /* "View.MemoryView":1337 - * refcount_copying(&dst, dtype_is_object, ndim, True) - * - * free(tmpdata) # <<<<<<<<<<<<<< - * return 0 - * - */ - free(__pyx_v_tmpdata); - - /* "View.MemoryView":1338 - * - * free(tmpdata) - * return 0 # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview_broadcast_leading') - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "View.MemoryView":1269 - * - * @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":1341 - * - * @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":1345 - * 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":1347 - * 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":1348 - * - * 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":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->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); - - /* "View.MemoryView":1350 - * 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":1352 - * 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":1353 - * - * 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":1354 - * 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":1355 - * mslice.shape[i] = 1 - * mslice.strides[i] = mslice.strides[0] - * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< - * - * - */ - (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; - } - - /* "View.MemoryView":1341 - * - * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< - * int ndim, - * int ndim_other) nogil: - */ - - /* function exit code */ -} - -/* "View.MemoryView":1363 - * - * @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":1367 - * - * - * 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":1368 - * - * 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":1367 - * - * - * if dtype_is_object: # <<<<<<<<<<<<<< - * refcount_objects_in_slice_with_gil(dst.data, dst.shape, - * dst.strides, ndim, inc) - */ - } - - /* "View.MemoryView":1363 - * - * @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":1372 - * - * @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":1375 - * 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":1372 - * - * @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":1378 - * - * @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":1382 - * 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":1383 - * - * 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":1384 - * 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":1385 - * if ndim == 1: - * if inc: - * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< - * else: - * Py_DECREF(( data)[0]) - */ - Py_INCREF((((PyObject **)__pyx_v_data)[0])); - - /* "View.MemoryView":1384 - * for i in range(shape[0]): - * if ndim == 1: - * if inc: # <<<<<<<<<<<<<< - * Py_INCREF(( data)[0]) - * else: - */ - goto __pyx_L6; - } - - /* "View.MemoryView":1387 - * 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":1383 - * - * for i in range(shape[0]): - * if ndim == 1: # <<<<<<<<<<<<<< - * if inc: - * Py_INCREF(( data)[0]) - */ - goto __pyx_L5; - } - - /* "View.MemoryView":1389 - * Py_DECREF(( data)[0]) - * else: - * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< - * ndim - 1, inc) - * - */ - /*else*/ { - - /* "View.MemoryView":1390 - * 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":1392 - * ndim - 1, inc) - * - * data += strides[0] # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); - } - - /* "View.MemoryView":1378 - * - * @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":1398 - * - * @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":1401 - * 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":1402 - * 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":1404 - * _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":1398 - * - * @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":1408 - * - * @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":1412 - * 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":1413 - * 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":1415 - * 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":1416 - * - * 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":1417 - * 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":1418 - * 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":1415 - * cdef Py_ssize_t extent = shape[0] - * - * if ndim == 1: # <<<<<<<<<<<<<< - * for i in range(extent): - * memcpy(data, item, itemsize) - */ - goto __pyx_L3; - } - - /* "View.MemoryView":1420 - * 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":1421 - * 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":1423 - * _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":1408 - * - * @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; - 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(1, 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(1, 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(1, 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(1, 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(1, 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 - 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_t_6; - __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - */ - __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xb068931) != 0); - if (__pyx_t_1) { - - /* "(tree fragment)":5 - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: - * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - * __pyx_result = Enum.__new__(__pyx_type) - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_PickleError); - __Pyx_GIVEREF(__pyx_n_s_PickleError); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); - __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_2); - __pyx_v___pyx_PickleError = __pyx_t_2; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":6 - * if __pyx_checksum != 0xb068931: - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< - * __pyx_result = Enum.__new__(__pyx_type) - * if __pyx_state is not None: - */ - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_INCREF(__pyx_v___pyx_PickleError); - __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 6, __pyx_L1_error) - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) - */ - } - - /* "(tree fragment)":7 - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (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_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(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_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v___pyx_result = __pyx_t_3; - __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (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_1 = (__pyx_v___pyx_state != Py_None); - __pyx_t_6 = (__pyx_t_1 != 0); - if (__pyx_t_6) { - - /* "(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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 9, __pyx_L1_error) - __pyx_t_3 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (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_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __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; - __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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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); - ++Py_REFCNT(o); - __pyx_array___dealloc__(o); - --Py_REFCNT(o); - 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) - "openmmtools.multistate.mixing._mix_replicas.array", /*tp_name*/ - sizeof(struct __pyx_array_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_array, /*tp_dealloc*/ - 0, /*tp_print*/ - 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 - 0, /*tp_vectorcall*/ - #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) - "openmmtools.multistate.mixing._mix_replicas.Enum", /*tp_name*/ - sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_Enum, /*tp_dealloc*/ - 0, /*tp_print*/ - 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 - 0, /*tp_vectorcall*/ - #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); - ++Py_REFCNT(o); - __pyx_memoryview___dealloc__(o); - --Py_REFCNT(o); - 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) - "openmmtools.multistate.mixing._mix_replicas.memoryview", /*tp_name*/ - sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ - 0, /*tp_print*/ - 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 - 0, /*tp_vectorcall*/ - #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); - ++Py_REFCNT(o); - __pyx_memoryviewslice___dealloc__(o); - --Py_REFCNT(o); - 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) - "openmmtools.multistate.mixing._mix_replicas._memoryviewslice", /*tp_name*/ - sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ - 0, /*tp_print*/ - 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 - 0, /*tp_vectorcall*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {"_mix_replicas_cython", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11openmmtools_10multistate_6mixing_13_mix_replicas_1_mix_replicas_cython, METH_VARARGS|METH_KEYWORDS, 0}, - {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__mix_replicas(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec__mix_replicas}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "_mix_replicas", - 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_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_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_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_k_Incompatible_checksums_s_vs_0xb0, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xb0), 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_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_s_Nij_accepted, __pyx_k_Nij_accepted, sizeof(__pyx_k_Nij_accepted), 0, 0, 1, 1}, - {&__pyx_n_s_Nij_proposed, __pyx_k_Nij_proposed, sizeof(__pyx_k_Nij_proposed), 0, 0, 1, 1}, - {&__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_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_base, __pyx_k_base, sizeof(__pyx_k_base), 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_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_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 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_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 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_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_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 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_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 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_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_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_nstates, __pyx_k_nstates, sizeof(__pyx_k_nstates), 0, 0, 1, 1}, - {&__pyx_n_s_nswap_attempts, __pyx_k_nswap_attempts, sizeof(__pyx_k_nswap_attempts), 0, 0, 1, 1}, - {&__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_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 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_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_replica_states, __pyx_k_replica_states, sizeof(__pyx_k_replica_states), 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_u_kl, __pyx_k_u_kl, sizeof(__pyx_k_u_kl), 0, 0, 1, 1}, - {&__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}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 14, __pyx_L1_error) - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 133, __pyx_L1_error) - __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 148, __pyx_L1_error) - __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(1, 151, __pyx_L1_error) - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) - __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(1, 404, __pyx_L1_error) - __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(1, 613, __pyx_L1_error) - __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(1, 832, __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); - - /* "View.MemoryView":133 - * - * if not self.ndim: - * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< - * - * if itemsize <= 0: - */ - __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 133, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple_); - __Pyx_GIVEREF(__pyx_tuple_); - - /* "View.MemoryView":136 - * - * if itemsize <= 0: - * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< - * - * if not isinstance(format, bytes): - */ - __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__2); - __Pyx_GIVEREF(__pyx_tuple__2); - - /* "View.MemoryView":148 - * - * if not self._shape: - * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__3); - __Pyx_GIVEREF(__pyx_tuple__3); - - /* "View.MemoryView":176 - * self.data = malloc(self.len) - * if not self.data: - * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< - * - * if self.dtype_is_object: - */ - __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 176, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__4); - __Pyx_GIVEREF(__pyx_tuple__4); - - /* "View.MemoryView":192 - * 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__5 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 192, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); - - /* "(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__6 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__6); - __Pyx_GIVEREF(__pyx_tuple__6); - - /* "(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__7 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__7); - __Pyx_GIVEREF(__pyx_tuple__7); - - /* "View.MemoryView":418 - * 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__8 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 418, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__8); - __Pyx_GIVEREF(__pyx_tuple__8); - - /* "View.MemoryView":495 - * 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__9 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 495, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__9); - __Pyx_GIVEREF(__pyx_tuple__9); - - /* "View.MemoryView":520 - * 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__10 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 520, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__10); - __Pyx_GIVEREF(__pyx_tuple__10); - - /* "View.MemoryView":570 - * 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__11 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 570, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__11); - __Pyx_GIVEREF(__pyx_tuple__11); - - /* "View.MemoryView":577 - * 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__12 = PyTuple_New(1); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__12); - __Pyx_INCREF(__pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_int_neg_1); - PyTuple_SET_ITEM(__pyx_tuple__12, 0, __pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_tuple__12); - - /* "(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__13 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__13); - __Pyx_GIVEREF(__pyx_tuple__13); - - /* "(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__14 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__14); - __Pyx_GIVEREF(__pyx_tuple__14); - - /* "View.MemoryView":682 - * if item is Ellipsis: - * if not seen_ellipsis: - * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< - * seen_ellipsis = True - * else: - */ - __pyx_slice__15 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__15)) __PYX_ERR(1, 682, __pyx_L1_error) - __Pyx_GOTREF(__pyx_slice__15); - __Pyx_GIVEREF(__pyx_slice__15); - - /* "View.MemoryView":703 - * for suboffset in suboffsets[:ndim]: - * if suboffset >= 0: - * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(1, 703, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__16); - __Pyx_GIVEREF(__pyx_tuple__16); - - /* "(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__17 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__17); - __Pyx_GIVEREF(__pyx_tuple__17); - - /* "(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__18 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__18); - __Pyx_GIVEREF(__pyx_tuple__18); - - /* "View.MemoryView":286 - * return self.name - * - * cdef generic = Enum("") # <<<<<<<<<<<<<< - * cdef strided = Enum("") # default - * cdef indirect = Enum("") - */ - __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(1, 286, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__19); - __Pyx_GIVEREF(__pyx_tuple__19); - - /* "View.MemoryView":287 - * - * cdef generic = Enum("") - * cdef strided = Enum("") # default # <<<<<<<<<<<<<< - * cdef indirect = Enum("") - * - */ - __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(1, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__20); - __Pyx_GIVEREF(__pyx_tuple__20); - - /* "View.MemoryView":288 - * cdef generic = Enum("") - * cdef strided = Enum("") # default - * cdef indirect = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(1, 288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__21); - __Pyx_GIVEREF(__pyx_tuple__21); - - /* "View.MemoryView":291 - * - * - * cdef contiguous = Enum("") # <<<<<<<<<<<<<< - * cdef indirect_contiguous = Enum("") - * - */ - __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(1, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__22); - __Pyx_GIVEREF(__pyx_tuple__22); - - /* "View.MemoryView":292 - * - * cdef contiguous = Enum("") - * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_tuple__23 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(1, 292, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__23); - __Pyx_GIVEREF(__pyx_tuple__23); - - /* "(tree fragment)":1 - * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_tuple__24 = 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__24)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__24); - __Pyx_GIVEREF(__pyx_tuple__24); - __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 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_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) __PYX_ERR(1, 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_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_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 - __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(1, 105, __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(1, 105, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) - __pyx_array_type = &__pyx_type___pyx_array; - if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __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(1, 279, __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(1, 330, __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(1, 330, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 330, __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(1, 965, __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(1, 965, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __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 - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -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; -} - - -#if PY_MAJOR_VERSION < 3 -#ifdef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC void -#else -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#endif -#else -#ifdef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC init_mix_replicas(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC init_mix_replicas(void) -#else -__Pyx_PyMODINIT_FUNC PyInit__mix_replicas(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit__mix_replicas(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__mix_replicas(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - static PyThread_type_lock __pyx_t_2[8]; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module '_mix_replicas' 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__mix_replicas(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(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #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("_mix_replicas", __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_openmmtools__multistate__mixing___mix_replicas) { - 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, "openmmtools.multistate.mixing._mix_replicas")) { - if (unlikely(PyDict_SetItemString(modules, "openmmtools.multistate.mixing._mix_replicas", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) goto __pyx_L1_error; - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) goto __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)) goto __pyx_L1_error; - (void)__Pyx_modinit_type_import_code(); - (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 - - /* "openmmtools/multistate/mixing/_mix_replicas.pyx":1 - * cimport cython # <<<<<<<<<<<<<< - * from libc.math cimport exp, isnan - * from libc.stdio cimport printf - */ - __pyx_t_1 = __Pyx_PyDict_NewPresized(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_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "View.MemoryView":209 - * info.obj = self - * - * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * def __dealloc__(array self): - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 209, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 209, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_array_type); - - /* "View.MemoryView":286 - * return self.name - * - * cdef generic = Enum("") # <<<<<<<<<<<<<< - * cdef strided = Enum("") # default - * cdef indirect = Enum("") - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 286, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(generic); - __Pyx_DECREF_SET(generic, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":287 - * - * cdef generic = Enum("") - * cdef strided = Enum("") # default # <<<<<<<<<<<<<< - * cdef indirect = Enum("") - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 287, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(strided); - __Pyx_DECREF_SET(strided, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":288 - * cdef generic = Enum("") - * cdef strided = Enum("") # default - * cdef indirect = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 288, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(indirect); - __Pyx_DECREF_SET(indirect, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":291 - * - * - * cdef contiguous = Enum("") # <<<<<<<<<<<<<< - * cdef indirect_contiguous = Enum("") - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 291, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(contiguous); - __Pyx_DECREF_SET(contiguous, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":292 - * - * cdef contiguous = Enum("") - * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 292, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(indirect_contiguous); - __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "View.MemoryView":316 - * - * 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":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(), - * PyThread_allocate_lock(), - */ - __pyx_t_2[0] = PyThread_allocate_lock(); - __pyx_t_2[1] = PyThread_allocate_lock(); - __pyx_t_2[2] = PyThread_allocate_lock(); - __pyx_t_2[3] = PyThread_allocate_lock(); - __pyx_t_2[4] = PyThread_allocate_lock(); - __pyx_t_2[5] = PyThread_allocate_lock(); - __pyx_t_2[6] = PyThread_allocate_lock(); - __pyx_t_2[7] = PyThread_allocate_lock(); - memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_2, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); - - /* "View.MemoryView":549 - * info.obj = self - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 549, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - PyType_Modified(__pyx_memoryview_type); - - /* "View.MemoryView":995 - * return self.from_object - * - * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 995, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 995, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 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_1 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_1) < 0) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 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); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init openmmtools.multistate.mixing._mix_replicas", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init openmmtools.multistate.mixing._mix_replicas"); - } - __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; -} - -/* 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_CheckExact(key)) || 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 - (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(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 - (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(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; -} - -/* None */ -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { - PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); -} - -/* 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 (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]; -#ifdef 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 (!memview || (PyObject *) memview == Py_None) - return; - if (__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 (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 (!memview ) { - return; - } else if ((PyObject *) memview == Py_None) { - memslice->memview = NULL; - return; - } - if (__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 (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; - } -} - -/* 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; -} - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = func->ob_type->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 - -/* 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_COMPILING_IN_PYPY - 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); -#else - 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); - } -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#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 - -/* 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 - -/* 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; -} - -/* 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 - -/* 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 (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { - 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 - -/* 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_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 -} - -/* None */ -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); -} - -/* 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; - 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 - -/* 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; - } - length = stop - start; - if (unlikely(length <= 0)) - return PyUnicode_FromUnicode(NULL, 0); - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -/* 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 - -/* 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); -} - -/* 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); -} - -/* 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"); -} - -/* RaiseNoneIterError */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); -} - -/* 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; -} - -/* 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 - -/* 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; -} - -/* 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 (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= 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 - -/* None */ -static CYTHON_INLINE long __Pyx_div_long(long a, long b) { - long q = a / b; - long r = a - q*b; - q -= ((r != 0) & ((r ^ b) < 0)); - return q; -} - -/* WriteUnraisableException */ -static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, - CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, - int full_traceback, CYTHON_UNUSED int nogil) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_PyThreadState_declare -#ifdef WITH_THREAD - PyGILState_STATE state; - if (nogil) - state = PyGILState_Ensure(); -#ifdef _MSC_VER - else state = (PyGILState_STATE)-1; -#endif -#endif - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - if (full_traceback) { - Py_XINCREF(old_exc); - Py_XINCREF(old_val); - Py_XINCREF(old_tb); - __Pyx_ErrRestore(old_exc, old_val, old_tb); - PyErr_PrintEx(1); - } - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } -#ifdef WITH_THREAD - if (nogil) - PyGILState_Release(state); -#endif -} - -/* ImportFrom */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -/* HasAttr */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { - PyObject *r; - if (unlikely(!__Pyx_PyBaseString_Check(n))) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return -1; - } - r = __Pyx_GetAttr(o, n); - if (unlikely(!r)) { - PyErr_Clear(); - return 0; - } else { - Py_DECREF(r); - return 1; - } -} - -/* PyObject_GenericGetAttrNoDict */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { - PyErr_Format(PyExc_AttributeError, -#if PY_MAJOR_VERSION >= 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; -} - -/* 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_reduce_ex = NULL; - PyObject *reduce = NULL; - PyObject *reduce_ex = NULL; - PyObject *reduce_cython = NULL; - PyObject *setstate = NULL; - PyObject *setstate_cython = NULL; -#if CYTHON_USE_PYTYPE_LOOKUP - if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto GOOD; -#else - if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto GOOD; -#endif -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto BAD; -#else - object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto BAD; -#endif - reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto 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 BAD; -#else - object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto BAD; -#endif - reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto BAD; - if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { - reduce_cython = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_cython); if (unlikely(!reduce_cython)) goto BAD; - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto 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_GetAttrStr(type_obj, __pyx_n_s_setstate_cython); if (unlikely(!setstate_cython)) goto BAD; - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto BAD; - } - PyType_Modified((PyTypeObject*)type_obj); - } - } - goto GOOD; -BAD: - if (!PyErr_Occurred()) - PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); - ret = -1; -GOOD: -#if !CYTHON_USE_PYTYPE_LOOKUP - Py_XDECREF(object_reduce); - Py_XDECREF(object_reduce_ex); -#endif - Py_XDECREF(reduce); - Py_XDECREF(reduce_ex); - Py_XDECREF(reduce_cython); - Py_XDECREF(setstate); - Py_XDECREF(setstate_cython); - return ret; -} - -/* CLineInTraceback */ -#ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(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; - 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" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - 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); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - 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; - 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) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __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); -} - -#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; -} - -/* 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;\ - } - -/* 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 '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 '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 '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; - int ndim = ctx->head->field->type->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; - 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 '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->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 (buf->strides[dim] != sizeof(void *)) { - PyErr_Format(PyExc_ValueError, - "Buffer is not indirectly contiguous " - "in dimension %d.", dim); - goto fail; - } - } else if (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 (stride < buf->itemsize) { - PyErr_SetString(PyExc_ValueError, - "Buffer and memoryview are not contiguous " - "in the same dimension."); - goto fail; - } - } - } else { - if (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 (spec & (__Pyx_MEMVIEW_PTR)) { - PyErr_Format(PyExc_ValueError, - "C-contiguous buffer is not indirect in " - "dimension %d", dim); - goto fail; - } else if (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 (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 (!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 (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 (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 (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 (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; - } - if ((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; - } - for (i = 0; i < ndim; i++) { - spec = axes_specs[i]; - if (!__pyx_check_strides(buf, i, ndim, spec)) - goto fail; - if (!__pyx_check_suboffsets(buf, i, ndim, spec)) - goto fail; - } - if (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_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; -} - -/* ObjectToMemviewSlice */ - static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_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), (__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_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_dsds_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), (__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_long, stack, - &result, obj); - if (unlikely(retcode == -1)) - goto __pyx_fail; - return result; -__pyx_fail: - result.memview = NULL; - result.data = NULL; - return result; -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; - 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); - } -} - -/* 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 (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) { - const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; - 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 - 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) { - const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; - 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 - 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) { - const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; - 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); - } -} - -/* CIntFromPy */ - static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { - const char neg_one = (char) ((char) 0 - (char) 1), const_zero = (char) 0; - 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 - 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[4], rtversion[4]; - PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); - if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { - char message[200]; - 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 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 */ From fa871d1b3fd4e7ea0786173874f755d60a5242e1 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Tue, 14 Apr 2020 22:03:37 -0700 Subject: [PATCH 142/152] Add PeriodicNonequilibriumIntegrator to docs --- docs/integrators.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/integrators.rst b/docs/integrators.rst index d3ed14234..4edcc20a6 100644 --- a/docs/integrators.rst +++ b/docs/integrators.rst @@ -46,6 +46,7 @@ These integrators are available for nonequilibrium switching simulations, and pr NonequilibriumLangevinIntegrator AlchemicalNonequilibriumLangevinIntegrator + PeriodicNonequilibriumIntegrator ExternalPerturbationLangevinIntegrator | From fe6042fde08e5b757fc214694aa02a088df05519 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Tue, 14 Apr 2020 22:49:19 -0700 Subject: [PATCH 143/152] Add PeriodicNonequilibriumIntegrator (heavily based on loopy integrators from @domrufa) --- openmmtools/integrators.py | 301 ++++++++++---------------- openmmtools/tests/test_integrators.py | 128 +++++++---- 2 files changed, 197 insertions(+), 232 deletions(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index e328bc97e..3c3db05c6 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -1081,7 +1081,7 @@ def __init__(self, Forces are only used in V-step. Handle multiple force groups by appending the force group index to V-steps, e.g. "V0" will only use forces from force group 0. "V" will perform a step using all forces. - "{" will cause metropolization, and must be followed later by a "}". + "{" will cause Metropolization, and must be followed later by a "}". temperature : np.unit.Quantity compatible with kelvin, default: 298.0*unit.kelvin @@ -1734,12 +1734,12 @@ def __init__(self, If not specified, no alchemical functions will be used. splitting : string, default: "O { V R H R V } O" - Sequence of R, V, O (and optionally V{i}), and { }substeps to be executed each timestep. There is also an H option, - which increments the global parameter `lambda` by 1/nsteps_neq for each step. + Sequence of "R", "V", "O" (and optionally "{", "}", "V0", "V1", ...) substeps to be executed each timestep. + "H" increments the global parameter `lambda` by 1/nsteps_neq for each step and accumulates protocol work. Forces are only used in V-step. Handle multiple force groups by appending the force group index to V-steps, e.g. "V0" will only use forces from force group 0. "V" will perform a step using all forces. - ( will cause metropolization, and must be followed later by a ). + { will cause Metropolization, and must be followed later by a }. temperature : np.unit.Quantity compatible with kelvin, default: 298.0*unit.kelvin Fictitious "bath" temperature @@ -1772,6 +1772,8 @@ def __init__(self, self._alchemical_functions = alchemical_functions self._n_steps_neq = nsteps_neq # number of integrator steps + if not hasattr(self, '_n_steps_per_cycle'): # for subclasses + self._n_steps_per_cycle = nsteps_neq # number of integrator steps per complete cycle # collect the system parameters. self._system_parameters = {system_parameter for system_parameter in alchemical_functions.keys()} @@ -1780,6 +1782,9 @@ def __init__(self, kwargs['splitting'] = splitting super(AlchemicalNonequilibriumLangevinIntegrator, self).__init__(*args, **kwargs) + if self._ORV_counts['H'] == 0: + raise ValueError('Integrator splitting string must contain at least one "H"') + @property def _step_dispatch_table(self): """dict: The dispatch table step_name -> add_step_function.""" @@ -1810,14 +1815,16 @@ def _add_global_variables(self): self.addGlobalVariable('Eold', 0) #old energy value before perturbation self.addGlobalVariable('Enew', 0) #new energy value after perturbation self.addGlobalVariable('lambda', 0.0) # parameter switched from 0 <--> 1 during course of integrating internal 'nsteps' of dynamics - self.addGlobalVariable('nsteps', self._n_steps_neq) # total number of NCMC steps to perform; this SHOULD NOT BE CHANGED during the protocol + self.addGlobalVariable('n_steps_neq', self._n_steps_neq) + self.addGlobalVariable('n_steps_per_cycle', self._n_steps_per_cycle) # total number of NCMC steps to perform; this SHOULD NOT BE CHANGED during the protocol + # TODO: Change 'step' to something that oesn't collide with the built-in lepton 'step()' function self.addGlobalVariable('step', 0) # step counter for handling initialization and terminating integration # Keep track of number of Hamiltonian updates per nonequilibrium switch n_H = self._ORV_counts['H'] # number of H updates per integrator step self._n_lambda_steps = self._n_steps_neq * n_H # number of Hamiltonian increments per switching step if self._n_steps_neq == 0: - self._n_lambda_steps = 1 # instantaneous switching + self._n_lambda_steps = n_H # instantaneous switching self.addGlobalVariable('n_lambda_steps', self._n_lambda_steps) # total number of NCMC steps to perform; this SHOULD NOT BE CHANGED during the protocol self.addGlobalVariable('lambda_step', 0) @@ -1833,7 +1840,10 @@ def _add_alchemical_perturbation_step(self): """ Add alchemical perturbation step, accumulating protocol work. - TODO: Extend this to be able to handle force groups? + .. todo :: + + This could be extended to only evaluate energies for force groups with global context parameters + to speed up work evaluations. """ # Store initial potential energy @@ -1872,7 +1882,7 @@ def _add_integrator_steps(self): else: #call the superclass function to insert the appropriate steps, provided the step number is less than n_steps self.beginIfBlock("step >= 0") - self.beginIfBlock("step < nsteps") + self.beginIfBlock("step < n_steps_per_cycle") super(AlchemicalNonequilibriumLangevinIntegrator, self)._add_integrator_steps() self.addComputeGlobal("step", "step + 1") self.endBlock() @@ -1895,40 +1905,79 @@ def _add_alchemical_reset_step(self): # Add all dependent parameters self._add_update_alchemical_parameters_step() -class LoopyAlchemicalNonequilibriumLangevinIntegrator(AlchemicalNonequilibriumLangevinIntegrator): +class PeriodicNonequilibriumIntegrator(AlchemicalNonequilibriumLangevinIntegrator): """ - Subclass of `AlchemicalNonequilibriumLangevinIntegrator` that hardcodes the following integration scheme: - - Step 1: lambda_0 equilibrium sampling - run nsteps_eq of BAOAB (V R O R V) integration at the alchemical lambda_0 endstate - Step 2: Forward Annealing - run n_steps_neq of BAOAB (V R O R V H); 'H': Hamiltonian update step - Step 3: lambda_1 equilibrium sampling - run Step 1 at the lambda_1 endstate - Step 3: Reverse Annealing - run Step 2 in the reverse direction - - forward and backward works are saved to `forward_work` and `backward_work`, respectively + Periodic nonequilibrium integrator where master alchemical parameter ``lambda`` + is driven through a periodic protocol: + + eq 0 for nsteps_eq | neq 0->1 over nsteps_neq | eq 1 for nsteps_eq | neq 1->0 for nsteps_neq + + Arbitrary Langevin splitting strings can be provided. + + .. warning :: This API is experimental, and subject to change. + + Examples + -------- + + Create a nonequilibrium integrator to switch the center of a harmonic oscillator between two locations, dwelling in either state to allow equilibration. + This example uses BAOAB (V R O R V) for integration. + + >>> # Create harmonic oscillator testsystem + >>> from openmmtools import testsystems + >>> from simtk import openmm, unit + >>> testsystem = testsystems.HarmonicOscillator() + >>> # Create a nonequilibrium alchemical integrator + >>> alchemical_functions = { 'testsystems_HarmonicOscillator_x0' : 'lambda' } + >>> nsteps_eq = 100 # number of steps to dwell in equilibrium at lambda = 0 or 1 + >>> nsteps_neq = 50 # number of steps in the switching trajectory where lambda is switched from 0 to 1 + >>> integrator = PeriodicAlchemicalNonequilibriumLangevinIntegrator( + ... temperature=300*unit.kelvin, collision_rate=1.0/unit.picoseconds, timestep=1.0*unit.femtoseconds, + ... alchemical_functions=alchemical_functions, splitting="V R H O R V", + ... nsteps_eq=nsteps_eq, nsteps_neq=nsteps_neq) + >>> # Create a Context + >>> context = openmm.Context(testsystem.system, integrator) + >>> # Run one periodic cycle: (eq 0) > (neq 0->1) > (eq 1) > (neq 1->0) + >>> context.setPositions(testsystem.positions) + >>> nsteps_per_period = 2*nsteps_eq + 2*nsteps_neq + >>> integrator.step(nsteps_per_period) + >>> protocol_work = integrator.protocol_work # retrieve protocol work (excludes shadow work) + >>> total_work = integrator.total_work # retrieve total work (includes shadow work, if requested) + >>> # Run another cycle + >>> integrator.step(nsteps_per_period) + >>> # Reset and run again + >>> context.setPositions(testsystem.positions) + >>> integrator.reset() + >>> integrator.step(nsteps_per_period) """ def __init__(self, - alchemical_functions = None, - nsteps_eq = 1000, - nsteps_neq = 100, + alchemical_functions=None, + nsteps_eq=1000, + nsteps_neq=100, + splitting="V R H O R V", **kwargs): """ - arguments - nsteps_eq : int - number of equilibration steps to run at either endstate - nsteps_neq : int - number of nonequilibrium annealing steps to run in either direction + Parameters + ---------- + nsteps_eq : int, optional, default=1000 + Number of equilibration steps to dwell within lambda = 0 or 1 when reached + nsteps_neq : int, optional, default=100 + Number of nonequilibrium switching steps for 0->1 and 1->0 switches + splitting : string, default: "V R H O R V" + Sequence of "R", "V", "O" (and optionally "{", "}", "V0", "V1", ...) substeps to be executed each timestep. + "H" increments the global parameter `lambda` by 1/nsteps_neq for each step and accumulates protocol work. - parameters - _n_steps_eq : int - number of BAOAB loops to run at each endstate in an attempt to generate i.i.d samples from endstates + Forces are only used in V-step. Handle multiple force groups by appending the force group index + to V-steps, e.g. "V0" will only use forces from force group 0. "V" will perform a step using all forces. + { will cause Metropolization, and must be followed later by a }. """ - self._n_steps_eq = nsteps_eq - splitting = 'V R O R V' - super().__init__(alchemical_functions, splitting, nsteps_neq = nsteps_neq, **kwargs) + # Check that a valid set of steps has been specified + nsteps_per_period = nsteps_eq + nsteps_neq + nsteps_eq + nsteps_neq + if nsteps_per_period <= 0: + raise ValueError(f'nsteps_per_period = {nsteps_per_period} must be > 0') + + self._n_steps_eq = nsteps_eq # store number of equilibration steps to dwell within lambda = 0 or 1 when reached + self._n_steps_per_cycle = nsteps_eq + nsteps_neq + nsteps_eq + nsteps_neq + super().__init__(alchemical_functions, splitting, nsteps_neq=nsteps_neq, **kwargs) def _add_global_variables(self): """ @@ -1936,96 +1985,57 @@ def _add_global_variables(self): steps at endstates. """ super()._add_global_variables() - self.addGlobalVariable('forward_work', 0) - self.addGlobalVariable('backward_work', 0) self.addGlobalVariable('n_steps_eq', self._n_steps_eq) - self.addGlobalVariable('eq_step', 0) - - #overwrite because this is set to 0 in super() (n_H = 1, but this is omitted in the splitting string); - #see https://github.com/choderalab/openmmtools/blob/c2b61c410b255c4e08927acf8cfcb1cf46f64b70/openmmtools/integrators.py#L1818 - self.setGlobalVariableByName('n_lambda_steps', self._n_steps_neq) def _add_integrator_steps(self): """ - hardcode a custom integration scheme specified at the top of the class + Override the base class to insert reset steps around the integrator. """ - #init/reset - self.addConstrainPositions() #constrain positions - self.addConstrainVelocities() #and velocities - self._add_reset_step() #reset lambda, protocol_works, heat, shadow, ghmc, step (unused), lambda_step, eq_step, and alchemical_params - - #lambda_0 equilibration - self.beginWhileBlock("eq_step < n_steps_eq") - self._add_canonical_integrator_steps() #add VRORV - self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step - self.endBlock() - - #forward anneal - self.beginWhileBlock("lambda_step < n_lambda_steps") #anneal forward until lambda step is n_lambda_steps (lambda = lambda_step / n_lambda_steps) - self._add_canonical_integrator_steps() #add VRORV - self._substep_function('H') #add the H step... - self.endBlock() - self.addComputeGlobal('forward_work', 'protocol_work') #log the forward protocol work - self.addComputeGlobal('protocol_work', '0') #reset the protocol work for the reverse annealing - - - #lambda_1 equilibration - self.addComputeGlobal('eq_step', '0') #reset eq_step counter - self.beginWhileBlock("eq_step < n_steps_eq") - self._add_canonical_integrator_steps() #add VRORV - self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step + # First step: Constrain positions and velocities and reset work accumulators and alchemical integrators + self.beginIfBlock('step = 0') + self.addConstrainPositions() + self.addConstrainVelocities() + self._add_reset_protocol_work_step() + self._add_alchemical_reset_step() self.endBlock() - #reverse anneal; don't reset lambda (it is annealing in backward direction) - self.beginWhileBlock("lambda_step > 0") #anneal backward until lambda step is 0 again - self._add_canonical_integrator_steps() #add VRORV - self._substep_function('L') #add the L step (backward H) + # Main body + self.beginIfBlock("step >= 0") + super(AlchemicalNonequilibriumLangevinIntegrator, self)._add_integrator_steps() + self.addComputeGlobal("step", "step + 1") self.endBlock() - self.addComputeGlobal('backward_work', 'protocol_work') - def _add_reset_step(self): - """ - Reset the alchemical lambda to its starting value (lambda = 0) - """ - self.addComputeGlobal("lambda", "0") + # Reset step counter + self.beginIfBlock("step >= n_steps_per_cycle") self.addComputeGlobal("step", "0") self.addComputeGlobal("lambda_step", "0") - self.addComputeGlobal('forward_work', "0") - self.addComputeGlobal('backward_work', "0") - self.addComputeGlobal('protocol_work', '0') - self.addComputeGlobal('eq_step', '0') - # Add all dependent parameters - self._add_update_alchemical_parameters_step() + self.endBlock() - def _add_canonical_integrator_steps(self): - """ - add the BAOAB integrator + # Reset step + self.beginIfBlock('step = -1') + self._add_reset_protocol_work_step() + self._add_alchemical_reset_step() # sets step to 0 + self.endBlock() + def _add_alchemical_perturbation_step(self): """ - self.addUpdateContextState() - self.addComputeTemperatureDependentConstants({"sigma": "sqrt(kT/m)"}) + Add alchemical perturbation step, accumulating protocol work. - for i, step in enumerate(self._splitting.split()): #splitting is just 'V R O R V' - self._substep_function(step) + .. todo :: - @property - def _step_dispatch_table(self): - """ - add an L step to the dispatch table - """ - dispatch_table = super()._step_dispatch_table - dispatch_table['L'] = (self._add_backward_alchemical_perturbation_step, False) - return dispatch_table + This could be extended to only evaluate energies for force groups with global context parameters + to speed up work evaluations. - def _add_backward_alchemical_perturbation_step(self): - """ - _add_alchemical_perturbation_step except the lambda step is decremented """ # Store initial potential energy self.addComputeGlobal("Eold", "energy") # Update lambda and increment that tracks updates. - self.addComputeGlobal('lambda', '(lambda_step-1)/n_lambda_steps') - self.addComputeGlobal('lambda_step', 'lambda_step - 1') #decrement instead of increment + lambda_control_expression = "lambda"\ + " + delta_lambda*step((step+0.5)-n_steps_eq)*step((n_steps_eq+n_steps_neq) - (step+0.5))"\ + " - delta_lambda*step((step+0.5)-(n_steps_eq+n_steps_neq+n_steps_eq))*step(n_steps_per_cycle - (step+0.5));"\ + "delta_lambda = 1/n_lambda_steps;" # Note that there may be multiple H per integrator string, so we correct for this here + self.addComputeGlobal('lambda', lambda_control_expression) + self.addComputeGlobal('lambda_step', 'lambda_step + 1') # Update all slaved alchemical parameters self._add_update_alchemical_parameters_step() @@ -2034,89 +2044,6 @@ def _add_backward_alchemical_perturbation_step(self): self.addComputeGlobal("Enew", "energy") self.addComputeGlobal("protocol_work", "protocol_work + (Enew-Eold)") - def get_forward_work(self, dimensionless=False): - """ - pull the forward work from the integrator global variables - """ - return self._get_energy_with_units('forward_work', dimensionless = dimensionless) - - def get_backward_work(self, dimensionless=False): - """ - pull the backward work from the integrator global variables - """ - return self._get_energy_with_units('backward_work', dimensionless=dimensionless) - -class LoopyIndependentAlchemicalNonequilibriumLangevinIntegrator(LoopyAlchemicalNonequilibriumLangevinIntegrator): - """ - Subclass of LoopyAlchemicalNonequilibriumLangevinIntegrator that runs two independent equilibrium simulations at alchemical - for annealing purposes. - """ - def __init__(self, - zero_endstate_positions, - one_endstate_positions, - alchemical_functions = None, - nsteps_eq = 1000, - nsteps_neq = 100, - **kwargs): - """ - arguments - zero_endstate_positions : np.ndarray() (N, 3) unit.Quantity (in length units) - starting positions of the zero endstate equilibration - one_endstate_positions : np.ndarray() (N,3) unit.Quantity (in length units) - starting positions of the one endstate equilibration - """ - super().__init__(alchemical_functions = alchemical_functions, - nsteps_eq = nsteps_eq, - nsteps_neq = nsteps_neq, - **kwargs) - - self.addPerDofVariable('x_zero_endstate', zero_endstate_positions.value_in_unit_system(unit.md_unit_system)) - self.addPerDofVariable('x_one_endstate', zero_endstate_positions.value_in_unit_system(unit.md_unit_system)) - - def _add_integrator_steps(self): - """ - hardcode a custom integration scheme specified at the top of the class - """ - #init/reset - self.addConstrainPositions() #constrain positions - self.addConstrainVelocities() #and velocities - self._add_reset_step() #reset lambda, protocol_works, heat, shadow, ghmc, step (unused), lambda_step, and alchemical_params - - #lambda_0 equilibration - self.addComputePerDof('x', 'x_zero_endstate') #replace the x positions with the zero endstate positions - self.beginWhileBlock("eq_step < n_steps_eq") - self._add_canonical_integrator_steps() #add VRORV - self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step - self.endBlock() - self.addComputePerDof('x_zero_endstate', 'x') - - - #forward anneal - self.beginWhileBlock("lambda_step < n_lambda_steps") #anneal forward until lambda step is n_lambda_steps (lambda = lambda_step / n_lambda_steps) - self._add_canonical_integrator_steps() #add VRORV - self._substep_function('H') #add the H step... - self.endBlock() - self.addComputeGlobal('forward_work', 'protocol_work') #log the forward protocol work - self.addComputeGlobal('protocol_work', '0') #reset the protocol work for the reverse annealing - - - #lambda_1 equilibration - self.addComputePerDof('x', 'x_one_endstate') #replace the x positions with the one endstate positions - self.addComputeGlobal('eq_step', '0') #reset eq_step counter - self.beginWhileBlock("eq_step < n_steps_eq") - self._add_canonical_integrator_steps() #add VRORV - self.addComputeGlobal('eq_step', "eq_step + 1") #increment eq_step - self.endBlock() - self.addComputePerDof('x_one_endstate', 'x') - - #reverse anneal; don't reset lambda (it is annealing in backward direction) - self.beginWhileBlock("lambda_step > 0") #anneal backward until lambda step is 0 again - self._add_canonical_integrator_steps() #add VRORV - self._substep_function('L') #add the L step (backward H) - self.endBlock() - self.addComputeGlobal('backward_work', 'protocol_work') - - class ExternalPerturbationLangevinIntegrator(NonequilibriumLangevinIntegrator): """ Create a LangevinSplittingIntegrator that accounts for external perturbations and tracks protocol work. diff --git a/openmmtools/tests/test_integrators.py b/openmmtools/tests/test_integrators.py index 2057e0cdf..49121c434 100755 --- a/openmmtools/tests/test_integrators.py +++ b/openmmtools/tests/test_integrators.py @@ -25,7 +25,7 @@ from openmmtools import integrators, testsystems from openmmtools.integrators import (ThermostatedIntegrator, AlchemicalNonequilibriumLangevinIntegrator, - GHMCIntegrator, NoseHooverChainVelocityVerletIntegrator, LoopyAlchemicalNonequilibriumLangevinIntegrator) + GHMCIntegrator, NoseHooverChainVelocityVerletIntegrator) #============================================================================================= @@ -759,9 +759,9 @@ def run_alchemical_langevin_integrator(nsteps=0, splitting="O { V R H R V } O"): # Check final conditions before reset current_lambda = nonequilibrium_integrator.getGlobalVariableByName('lambda') - assert current_lambda == 1.0, 'final lambda should be 1.0 (was %f)' % current_lambda + assert current_lambda == 1.0, 'final lambda should be 1.0 (was %f) for splitting %s' % (current_lambda, splitting) current_step = nonequilibrium_integrator.getGlobalVariableByName('step') - assert int(current_step) == max(1,nsteps), 'final step should be %d (was %f)' % (max(1,nsteps), current_step) + assert int(current_step) == max(1,nsteps), 'final step should be %d (was %f) for splitting %s' % (max(1,nsteps), current_step, splitting) nonequilibrium_integrator.reset() # Clean up @@ -774,26 +774,23 @@ def run_alchemical_langevin_integrator(nsteps=0, splitting="O { V R H R V } O"): if nsigma > NSIGMA_MAX: raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) -def run_loopy_alchemical_langevin_integrator(integrator_flavor = LoopyAlchemicalNonequilibriumLangevinIntegrator, - nsteps=20, - nsteps_neq=10, - nsteps_eq=10): +def test_periodic_langevin_integrator(splitting="V R H O R V", ncycles=40, nsteps_neq=1000, nsteps_eq=1000): """ - Test different flavors of the LoopyAlchemicalNonequilibriumLangevinIntegrator (and perhaps subclasses thereof) - - arguments - integrator_flavor : openmmtools.integrator.LoopyAlchemicalNonequilibriumLangevinIntegrator (or subclass) - integrator to run - nsteps : int, default 20 - number of integrator.steps() to run - nsteps_neq : int, default 10 - number of forward/backward annealing steps - nsteps_eq : int, default 10 - number of equilibration steps to run at endstates before annealing + Test PeriodicNonequilibriumIntegrator + + Parameters + ---------- + integrator_flavor : openmmtools.integrator.PeriodicNonequilibriumIntegrator (or subclass) + integrator to run + ncycles : int, optional, default=20 + number of cycles + nsteps_neq : int, optional, default=10 + number of forward/backward annealing steps + nsteps_eq : int, optional, default=10 + number of equilibration steps to run at endstates before annealing """ #max deviation from the calculated free energy NSIGMA_MAX = 6 - n_iterations = 200 # number of forward and reverse protocols # These are the alchemical functions that will be used to control the system temperature = 298.0 * unit.kelvin @@ -807,7 +804,7 @@ def run_loopy_alchemical_langevin_integrator(integrator_flavor = LoopyAlchemical collision_rate = 1.0 / period dF_analytical = 1.0 parameters = dict() - parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, 2 * sigma) + parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, 1 * sigma) parameters['testsystems_HarmonicOscillator_U0'] = (0 * kT, 1 * kT) integrator_kwargs = {'temperature':temperature, 'collision_rate': collision_rate, @@ -821,24 +818,76 @@ def run_loopy_alchemical_langevin_integrator(integrator_flavor = LoopyAlchemical positions = testsystem.positions # Create integrator - integrator = LoopyAlchemicalNonequilibriumLangevinIntegrator(alchemical_functions=alchemical_functions, - nsteps_eq=nsteps_eq, - nsteps_neq=nsteps_neq, - **integrator_kwargs) + from openmmtools.integrators import PeriodicNonequilibriumIntegrator + integrator = PeriodicNonequilibriumIntegrator(alchemical_functions=alchemical_functions, + splitting=splitting, + nsteps_eq=nsteps_eq, + nsteps_neq=nsteps_neq, + **integrator_kwargs) platform = openmm.Platform.getPlatformByName("Reference") context = openmm.Context(system, integrator, platform) context.setPositions(positions) - forward, backward = [], [] - for _ in range(nsteps): - integrator.step(1) - forward.append(integrator.get_forward_work(dimensionless=True)) - backward.append(integrator.get_backward_work(dimensionless=True)) + nsteps_per_cycle = nsteps_eq + nsteps_neq + nsteps_eq + nsteps_neq + assert integrator.getGlobalVariableByName("n_steps_per_cycle") == nsteps_per_cycle - dF, ddF = pymbar.BAR(np.array(forward), np.array(backward)) + step = 0 + for cycle in range(2): + # eq (0) + for i in range(nsteps_eq): + integrator.step(1) + step += 1 + assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) + assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) + # neq (0 -> 1) + for i in range(nsteps_neq): + integrator.step(1) + step += 1 + assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) + assert np.isclose(integrator.getGlobalVariableByName("lambda"), (i+1)/nsteps_neq), f'{step} {integrator.getGlobalVariableByName("lambda")}' + # eq (1) + for i in range(nsteps_eq): + integrator.step(1) + step += 1 + assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) + assert np.isclose(integrator.getGlobalVariableByName("lambda"), 1.0) + # neq (1 -> 0) + for i in range(nsteps_neq): + integrator.step(1) + step += 1 + assert integrator.getGlobalVariableByName("step") == (step % nsteps_per_cycle) + assert np.isclose(integrator.getGlobalVariableByName("lambda"), 1 - (i+1)/nsteps_neq) + + assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) + + # Reset the integrator + integrator.reset() + + forward_works, reverse_works = list(), list() + for _ in range(ncycles): + # Equilibrium (lambda = 0) + integrator.step(nsteps_eq) + # Forward (0 -> 1) + initial_work = integrator.get_protocol_work(dimensionless=True) + integrator.step(nsteps_neq) + final_work = integrator.get_protocol_work(dimensionless=True) + forward_work = final_work - initial_work + forward_works.append(forward_work) + # Equilibrium (lambda = 1) + integrator.step(nsteps_eq) + # Reverse work (1 -> 0) + initial_work = integrator.get_protocol_work(dimensionless=True) + integrator.step(nsteps_neq) + final_work = integrator.get_protocol_work(dimensionless=True) + reverse_work = final_work - initial_work + reverse_works.append(reverse_work) + + print(np.array(forward_works).std()) + print(np.array(reverse_works).std()) + + dF, ddF = pymbar.BAR(np.array(forward_works), np.array(reverse_works)) nsigma = np.abs(dF - dF_analytical) / ddF - current_lambda = integrator.getGlobalVariableByName('lambda') - assert current_lambda == 0.0, 'final lambda should be 0.0 (was %f)' % current_lambda + assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) print("analytical DeltaF: {:12.4f}, DeltaF: {:12.4f}, dDeltaF: {:12.4f}, nsigma: {:12.1f}".format(dF_analytical, dF, ddF, nsigma)) if nsigma > NSIGMA_MAX: raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) @@ -847,21 +896,10 @@ def run_loopy_alchemical_langevin_integrator(integrator_flavor = LoopyAlchemical del context del integrator - def test_alchemical_langevin_integrator(): - for splitting in ["O { V R H R V } O", "O V R H R V O", "H R V O V R H"]: + for splitting in ["O V R H R V O", "H R V O V R H", "O { V R H R V } O"]: for nsteps in [0, 1, 10]: - run_alchemical_langevin_integrator(nsteps=nsteps) - -def test_loopy_alchemical_integrators(): - """ - test loopy alchemical langevin integrators: see run_loopy_alchemical_langevin_integrator - """ - for integrator_flavor in [LoopyAlchemicalNonequilibriumLangevinIntegrator]: - run_loopy_alchemical_langevin_integrator(integrator_flavor = integrator_flavor, - nsteps=20, - nsteps_neq=10, - nsteps_eq=10) + run_alchemical_langevin_integrator(splitting=splitting, nsteps=nsteps) if __name__=="__main__": test_alchemical_langevin_integrator() From 88baad87a77fa25bfb1e3b655128f301061c002f Mon Sep 17 00:00:00 2001 From: John Chodera Date: Tue, 14 Apr 2020 22:55:02 -0700 Subject: [PATCH 144/152] Update changelog --- docs/releasehistory.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/releasehistory.rst b/docs/releasehistory.rst index df29ae2c5..4b1682144 100644 --- a/docs/releasehistory.rst +++ b/docs/releasehistory.rst @@ -2,6 +2,13 @@ Release History *************** +0.20.0 - Periodic alchemical integrators +======================================== + +Enhancements +------------ +- Add `PeriodicNonequilibriumIntegrator`, a simple extension of `AlchemicalNonequilibriumLangevinIntegrator` that supports periodic alchemical protocols + 0.19.1 - Bugfix release ======================= From 1585fddfbf8e107927a3aaf3be1a73378032c408 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Tue, 14 Apr 2020 23:30:35 -0700 Subject: [PATCH 145/152] Add back C file --- openmmtools/multistate/mixing/_mix_replicas.c | 20902 ++++++++++++++++ 1 file changed, 20902 insertions(+) create mode 100644 openmmtools/multistate/mixing/_mix_replicas.c diff --git a/openmmtools/multistate/mixing/_mix_replicas.c b/openmmtools/multistate/mixing/_mix_replicas.c new file mode 100644 index 000000000..29df1ad68 --- /dev/null +++ b/openmmtools/multistate/mixing/_mix_replicas.c @@ -0,0 +1,20902 @@ +/* Generated by Cython 0.29.16 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [], + "name": "openmmtools.multistate.mixing._mix_replicas", + "sources": [ + "./openmmtools/multistate/mixing/_mix_replicas.pyx" + ] + }, + "module_name": "openmmtools.multistate.mixing._mix_replicas" +} +END: Cython Metadata */ + +#define 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_16" +#define CYTHON_HEX_VERSION 0x001D10F0 +#define CYTHON_FUTURE_DIVISION 0 +#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 + #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 + #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 +#elif defined(PYSTON_VERSION) + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_PYSTON 1 + #define CYTHON_COMPILING_IN_CPYTHON 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 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_PYSTON 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #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 1 + #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 + #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 + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #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) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) + #endif +#endif +#if !defined(CYTHON_FAST_PYCCALL) +#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #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" +#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#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 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #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) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) +#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 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 PyInt_AsLong +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : (Py_INCREF(func), 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(MS_WINDOWS) + #define _USE_MATH_DEFINES +#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_ERR(f_index, lineno, Ln_error) \ +{ \ + __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; 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__openmmtools__multistate__mixing___mix_replicas +#define __PYX_HAVE_API__openmmtools__multistate__mixing___mix_replicas +/* Early includes */ +#include +#include +#include +#include "stdlib.h" +#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); +#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; + + +static const char *__pyx_f[] = { + "openmmtools/multistate/mixing/_mix_replicas.pyx", + "stringsource", +}; +/* 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_atomic_int_type int +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) &&\ + !defined(__i386__) + #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) && 0 + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type LONG + #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 + #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) + #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using Intel 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), memview->lock) + #define __pyx_sub_acquisition_count(memview)\ + __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) +#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; + + +/*--- Type declarations ---*/ +struct __pyx_array_obj; +struct __pyx_MemviewEnum_obj; +struct __pyx_memoryview_obj; +struct __pyx_memoryviewslice_obj; + +/* "View.MemoryView":105 + * + * @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":279 + * + * @cname('__pyx_MemviewEnum') + * cdef class Enum(object): # <<<<<<<<<<<<<< + * cdef object name + * def __init__(self, name): + */ +struct __pyx_MemviewEnum_obj { + PyObject_HEAD + PyObject *name; +}; + + +/* "View.MemoryView":330 + * + * @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":965 + * + * @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":105 + * + * @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":330 + * + * @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":965 + * + * @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); + +/* 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); + +/* None.proto */ +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +/* 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); + +/* 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); + +/* 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 + +/* 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 + +/* 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); + +/* 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 + +/* 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 + static size_t __pyx_pyframe_localsplus_offset = 0; + #include "frameobject.h" + #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 + +/* PyObjectCall2Args.proto */ +static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectCallMethO.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectCallOneArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* 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 + +/* None.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 *); + +/* 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 + +/* 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)); + +/* 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 + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* 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) {\ + 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);\ +} +#define __Pyx_GetModuleGlobalNameUncached(var, name) {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} +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 + +/* RaiseTooManyValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/* RaiseNeedMoreValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* RaiseNoneIterError.proto */ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +/* GetTopmostException.proto */ +#if CYTHON_USE_EXC_INFO_STACK +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#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 + +/* 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 + +/* 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); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +/* 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 + +/* 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); + Py_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 long __Pyx_div_long(long, long); + +/* 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); + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* 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); + +#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_ds_long(PyObject *, int writable_flag); + +/* ObjectToMemviewSlice.proto */ +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *, int writable_flag); + +/* ObjectToMemviewSlice.proto */ +static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_long(PyObject *, int writable_flag); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +/* 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); + +/* 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 'cython.view' */ + +/* Module declarations from 'cython' */ + +/* Module declarations from 'libc.math' */ + +/* Module declarations from 'libc.string' */ + +/* Module declarations from 'libc.stdio' */ + +/* Module declarations from 'openmmtools.multistate.mixing._mix_replicas' */ +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 long __pyx_f_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(long, long, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ +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_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 "openmmtools.multistate.mixing._mix_replicas" +extern int __pyx_module_is_main_openmmtools__multistate__mixing___mix_replicas; +int __pyx_module_is_main_openmmtools__multistate__mixing___mix_replicas = 0; + +/* Implementation of 'openmmtools.multistate.mixing._mix_replicas' */ +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_enumerate; +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_O[] = "O"; +static const char __pyx_k_c[] = "c"; +static const char __pyx_k_id[] = "id"; +static const char __pyx_k_new[] = "__new__"; +static const char __pyx_k_obj[] = "obj"; +static const char __pyx_k_base[] = "base"; +static const char __pyx_k_dict[] = "__dict__"; +static const char __pyx_k_main[] = "__main__"; +static const char __pyx_k_mode[] = "mode"; +static const char __pyx_k_name[] = "name"; +static const char __pyx_k_ndim[] = "ndim"; +static const char __pyx_k_pack[] = "pack"; +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_u_kl[] = "u_kl"; +static const char __pyx_k_ASCII[] = "ASCII"; +static const char __pyx_k_class[] = "__class__"; +static const char __pyx_k_error[] = "error"; +static const char __pyx_k_flags[] = "flags"; +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_encode[] = "encode"; +static const char __pyx_k_format[] = "format"; +static const char __pyx_k_import[] = "__import__"; +static const char __pyx_k_name_2[] = "__name__"; +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_fortran[] = "fortran"; +static const char __pyx_k_memview[] = "memview"; +static const char __pyx_k_nstates[] = "nstates"; +static const char __pyx_k_Ellipsis[] = "Ellipsis"; +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_TypeError[] = "TypeError"; +static const char __pyx_k_enumerate[] = "enumerate"; +static const char __pyx_k_pyx_state[] = "__pyx_state"; +static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; +static const char __pyx_k_IndexError[] = "IndexError"; +static const char __pyx_k_ValueError[] = "ValueError"; +static const char __pyx_k_pyx_result[] = "__pyx_result"; +static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static const char __pyx_k_MemoryError[] = "MemoryError"; +static const char __pyx_k_PickleError[] = "PickleError"; +static const char __pyx_k_Nij_accepted[] = "Nij_accepted"; +static const char __pyx_k_Nij_proposed[] = "Nij_proposed"; +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_nswap_attempts[] = "nswap_attempts"; +static const char __pyx_k_replica_states[] = "replica_states"; +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_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_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_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_s_vs_0xb0[] = "Incompatible checksums (%s vs 0xb068931 = (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_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_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_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_Ellipsis; +static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; +static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0xb0; +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_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_s_Nij_accepted; +static PyObject *__pyx_n_s_Nij_proposed; +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_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_base; +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_kp_s_contiguous_and_direct; +static PyObject *__pyx_kp_s_contiguous_and_indirect; +static PyObject *__pyx_n_s_dict; +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_flags; +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_kp_s_got_differing_extents_in_dimensi; +static PyObject *__pyx_n_s_id; +static PyObject *__pyx_n_s_import; +static PyObject *__pyx_n_s_itemsize; +static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; +static PyObject *__pyx_n_s_main; +static PyObject *__pyx_n_s_memview; +static PyObject *__pyx_n_s_mode; +static PyObject *__pyx_n_s_name; +static PyObject *__pyx_n_s_name_2; +static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_new; +static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; +static PyObject *__pyx_n_s_nstates; +static PyObject *__pyx_n_s_nswap_attempts; +static PyObject *__pyx_n_s_obj; +static PyObject *__pyx_n_s_pack; +static PyObject *__pyx_n_s_pickle; +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_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_replica_states; +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_u_kl; +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_pf_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nswap_attempts, long __pyx_v_nstates, __Pyx_memviewslice __pyx_v_replica_states, __Pyx_memviewslice __pyx_v_u_kl, __Pyx_memviewslice __pyx_v_Nij_proposed, __Pyx_memviewslice __pyx_v_Nij_accepted); /* 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_int_0; +static PyObject *__pyx_int_1; +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__15; +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__16; +static PyObject *__pyx_tuple__17; +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__23; +static PyObject *__pyx_tuple__24; +static PyObject *__pyx_codeobj__25; +/* Late includes */ + +/* "openmmtools/multistate/mixing/_mix_replicas.pyx":10 + * @cython.cdivision(True) + * @cython.boundscheck(False) + * cpdef long _mix_replicas_cython(long nswap_attempts, long nstates, long[:] replica_states, double[:,:] u_kl, long[:,:] Nij_proposed, long[:,:] Nij_accepted) nogil: # <<<<<<<<<<<<<< + * cdef long swap_attempt + * cdef long i, j, istate, jstate, tmp_state + */ + +static PyObject *__pyx_pw_11openmmtools_10multistate_6mixing_13_mix_replicas_1_mix_replicas_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static long __pyx_f_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(long __pyx_v_nswap_attempts, long __pyx_v_nstates, __Pyx_memviewslice __pyx_v_replica_states, __Pyx_memviewslice __pyx_v_u_kl, __Pyx_memviewslice __pyx_v_Nij_proposed, __Pyx_memviewslice __pyx_v_Nij_accepted, CYTHON_UNUSED int __pyx_skip_dispatch) { + CYTHON_UNUSED long __pyx_v_swap_attempt; + long __pyx_v_i; + long __pyx_v_j; + long __pyx_v_istate; + long __pyx_v_jstate; + long __pyx_v_tmp_state; + double __pyx_v_log_P_accept; + long __pyx_r; + long __pyx_t_1; + long __pyx_t_2; + long __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + int __pyx_t_9; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + Py_ssize_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + Py_ssize_t __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; + Py_ssize_t __pyx_t_20; + Py_ssize_t __pyx_t_21; + Py_ssize_t __pyx_t_22; + Py_ssize_t __pyx_t_23; + Py_ssize_t __pyx_t_24; + Py_ssize_t __pyx_t_25; + Py_ssize_t __pyx_t_26; + Py_ssize_t __pyx_t_27; + Py_ssize_t __pyx_t_28; + Py_ssize_t __pyx_t_29; + Py_ssize_t __pyx_t_30; + Py_ssize_t __pyx_t_31; + Py_ssize_t __pyx_t_32; + Py_ssize_t __pyx_t_33; + Py_ssize_t __pyx_t_34; + Py_ssize_t __pyx_t_35; + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":14 + * cdef long i, j, istate, jstate, tmp_state + * cdef double log_P_accept + * for swap_attempt in range(nswap_attempts): # <<<<<<<<<<<<<< + * i = (drand48()*nstates) + * j = (drand48()*nstates) + */ + __pyx_t_1 = __pyx_v_nswap_attempts; + __pyx_t_2 = __pyx_t_1; + for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { + __pyx_v_swap_attempt = __pyx_t_3; + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":15 + * cdef double log_P_accept + * for swap_attempt in range(nswap_attempts): + * i = (drand48()*nstates) # <<<<<<<<<<<<<< + * j = (drand48()*nstates) + * istate = replica_states[i] + */ + __pyx_v_i = ((long)(drand48() * __pyx_v_nstates)); + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":16 + * for swap_attempt in range(nswap_attempts): + * i = (drand48()*nstates) + * j = (drand48()*nstates) # <<<<<<<<<<<<<< + * istate = replica_states[i] + * jstate = replica_states[j] + */ + __pyx_v_j = ((long)(drand48() * __pyx_v_nstates)); + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":17 + * i = (drand48()*nstates) + * j = (drand48()*nstates) + * istate = replica_states[i] # <<<<<<<<<<<<<< + * jstate = replica_states[j] + * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): + */ + __pyx_t_4 = __pyx_v_i; + __pyx_v_istate = (*((long *) ( /* dim=0 */ (__pyx_v_replica_states.data + __pyx_t_4 * __pyx_v_replica_states.strides[0]) ))); + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":18 + * j = (drand48()*nstates) + * istate = replica_states[i] + * jstate = replica_states[j] # <<<<<<<<<<<<<< + * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): + * continue + */ + __pyx_t_5 = __pyx_v_j; + __pyx_v_jstate = (*((long *) ( /* dim=0 */ (__pyx_v_replica_states.data + __pyx_t_5 * __pyx_v_replica_states.strides[0]) ))); + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":19 + * istate = replica_states[i] + * jstate = replica_states[j] + * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): # <<<<<<<<<<<<<< + * continue + * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) + */ + __pyx_t_7 = __pyx_v_i; + __pyx_t_8 = __pyx_v_istate; + __pyx_t_9 = (isnan((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_7 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_8 * __pyx_v_u_kl.strides[1]) )))) != 0); + if (!__pyx_t_9) { + } else { + __pyx_t_6 = __pyx_t_9; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_10 = __pyx_v_i; + __pyx_t_11 = __pyx_v_jstate; + __pyx_t_9 = (isnan((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_10 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_11 * __pyx_v_u_kl.strides[1]) )))) != 0); + if (!__pyx_t_9) { + } else { + __pyx_t_6 = __pyx_t_9; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_12 = __pyx_v_j; + __pyx_t_13 = __pyx_v_istate; + __pyx_t_9 = (isnan((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_12 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_13 * __pyx_v_u_kl.strides[1]) )))) != 0); + if (!__pyx_t_9) { + } else { + __pyx_t_6 = __pyx_t_9; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_14 = __pyx_v_j; + __pyx_t_15 = __pyx_v_jstate; + __pyx_t_9 = (isnan((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_14 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_15 * __pyx_v_u_kl.strides[1]) )))) != 0); + __pyx_t_6 = __pyx_t_9; + __pyx_L6_bool_binop_done:; + if (__pyx_t_6) { + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":20 + * jstate = replica_states[j] + * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): + * continue # <<<<<<<<<<<<<< + * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) + * Nij_proposed[istate, jstate] +=1 + */ + goto __pyx_L3_continue; + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":19 + * istate = replica_states[i] + * jstate = replica_states[j] + * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): # <<<<<<<<<<<<<< + * continue + * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) + */ + } + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":21 + * if (isnan(u_kl[i, istate]) or isnan(u_kl[i, jstate]) or isnan(u_kl[j, istate]) or isnan(u_kl[j, jstate])): + * continue + * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) # <<<<<<<<<<<<<< + * Nij_proposed[istate, jstate] +=1 + * Nij_proposed[jstate, istate] +=1 + */ + __pyx_t_16 = __pyx_v_i; + __pyx_t_17 = __pyx_v_jstate; + __pyx_t_18 = __pyx_v_j; + __pyx_t_19 = __pyx_v_istate; + __pyx_t_20 = __pyx_v_j; + __pyx_t_21 = __pyx_v_jstate; + __pyx_t_22 = __pyx_v_i; + __pyx_t_23 = __pyx_v_istate; + __pyx_v_log_P_accept = ((-((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_16 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_17 * __pyx_v_u_kl.strides[1]) ))) + (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_18 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_19 * __pyx_v_u_kl.strides[1]) ))))) + ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_20 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_21 * __pyx_v_u_kl.strides[1]) ))) + (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_u_kl.data + __pyx_t_22 * __pyx_v_u_kl.strides[0]) ) + __pyx_t_23 * __pyx_v_u_kl.strides[1]) ))))); + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":22 + * continue + * log_P_accept = - (u_kl[i, jstate] + u_kl[j, istate]) + (u_kl[j, jstate] + u_kl[i, istate]) + * Nij_proposed[istate, jstate] +=1 # <<<<<<<<<<<<<< + * Nij_proposed[jstate, istate] +=1 + * if(log_P_accept>=0 or drand48()=0 or drand48()=0 or drand48()= 0.0) != 0); + if (!__pyx_t_9) { + } else { + __pyx_t_6 = __pyx_t_9; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_9 = ((drand48() < exp(__pyx_v_log_P_accept)) != 0); + __pyx_t_6 = __pyx_t_9; + __pyx_L11_bool_binop_done:; + if (__pyx_t_6) { + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":25 + * Nij_proposed[jstate, istate] +=1 + * if(log_P_accept>=0 or drand48()=0 or drand48()=0 or drand48() 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_mix_replicas_cython") < 0)) __PYX_ERR(0, 10, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 6) { + 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); + } + __pyx_v_nswap_attempts = __Pyx_PyInt_As_long(values[0]); if (unlikely((__pyx_v_nswap_attempts == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 10, __pyx_L3_error) + __pyx_v_nstates = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v_nstates == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 10, __pyx_L3_error) + __pyx_v_replica_states = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_replica_states.memview)) __PYX_ERR(0, 10, __pyx_L3_error) + __pyx_v_u_kl = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_u_kl.memview)) __PYX_ERR(0, 10, __pyx_L3_error) + __pyx_v_Nij_proposed = __Pyx_PyObject_to_MemoryviewSlice_dsds_long(values[4], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Nij_proposed.memview)) __PYX_ERR(0, 10, __pyx_L3_error) + __pyx_v_Nij_accepted = __Pyx_PyObject_to_MemoryviewSlice_dsds_long(values[5], PyBUF_WRITABLE); if (unlikely(!__pyx_v_Nij_accepted.memview)) __PYX_ERR(0, 10, __pyx_L3_error) + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_mix_replicas_cython", 1, 6, 6, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 10, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("openmmtools.multistate.mixing._mix_replicas._mix_replicas_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(__pyx_self, __pyx_v_nswap_attempts, __pyx_v_nstates, __pyx_v_replica_states, __pyx_v_u_kl, __pyx_v_Nij_proposed, __pyx_v_Nij_accepted); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(CYTHON_UNUSED PyObject *__pyx_self, long __pyx_v_nswap_attempts, long __pyx_v_nstates, __Pyx_memviewslice __pyx_v_replica_states, __Pyx_memviewslice __pyx_v_u_kl, __Pyx_memviewslice __pyx_v_Nij_proposed, __Pyx_memviewslice __pyx_v_Nij_accepted) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("_mix_replicas_cython", 0); + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_replica_states.memview)) { __Pyx_RaiseUnboundLocalError("replica_states"); __PYX_ERR(0, 10, __pyx_L1_error) } + if (unlikely(!__pyx_v_u_kl.memview)) { __Pyx_RaiseUnboundLocalError("u_kl"); __PYX_ERR(0, 10, __pyx_L1_error) } + if (unlikely(!__pyx_v_Nij_proposed.memview)) { __Pyx_RaiseUnboundLocalError("Nij_proposed"); __PYX_ERR(0, 10, __pyx_L1_error) } + if (unlikely(!__pyx_v_Nij_accepted.memview)) { __Pyx_RaiseUnboundLocalError("Nij_accepted"); __PYX_ERR(0, 10, __pyx_L1_error) } + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_f_11openmmtools_10multistate_6mixing_13_mix_replicas__mix_replicas_cython(__pyx_v_nswap_attempts, __pyx_v_nstates, __pyx_v_replica_states, __pyx_v_u_kl, __pyx_v_Nij_proposed, __pyx_v_Nij_accepted, 0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("openmmtools.multistate.mixing._mix_replicas._mix_replicas_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __PYX_XDEC_MEMVIEW(&__pyx_v_replica_states, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_u_kl, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Nij_proposed, 1); + __PYX_XDEC_MEMVIEW(&__pyx_v_Nij_accepted, 1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":122 + * 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_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(1, 122, __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(1, 122, __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(1, 122, __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(1, 122, __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(1, 123, __pyx_L3_error) + } else { + + /* "View.MemoryView":123 + * + * 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(1, 122, __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(1, 122, __pyx_L1_error) + if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { + PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(1, 122, __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":122 + * 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; + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_INCREF(__pyx_v_format); + + /* "View.MemoryView":129 + * 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(1, 129, __pyx_L1_error) + } + __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(1, 129, __pyx_L1_error) + __pyx_v_self->ndim = ((int)__pyx_t_1); + + /* "View.MemoryView":130 + * + * self.ndim = len(shape) + * self.itemsize = itemsize # <<<<<<<<<<<<<< + * + * if not self.ndim: + */ + __pyx_v_self->itemsize = __pyx_v_itemsize; + + /* "View.MemoryView":132 + * 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":133 + * + * 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_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 133, __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(1, 133, __pyx_L1_error) + + /* "View.MemoryView":132 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ + } + + /* "View.MemoryView":135 + * 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":136 + * + * 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__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 136, __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(1, 136, __pyx_L1_error) + + /* "View.MemoryView":135 + * raise ValueError("Empty shape tuple for cython.array") + * + * if itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ + } + + /* "View.MemoryView":138 + * 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":139 + * + * 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(1, 139, __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(1, 139, __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":138 + * 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":140 + * 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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) __PYX_ERR(1, 140, __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":141 + * 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(1, 141, __pyx_L1_error) + } + __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(1, 141, __pyx_L1_error) + __pyx_v_self->format = __pyx_t_7; + + /* "View.MemoryView":144 + * + * + * 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":145 + * + * 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":147 + * 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":148 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 148, __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(1, 148, __pyx_L1_error) + + /* "View.MemoryView":147 + * self._strides = self._shape + self.ndim + * + * if not self._shape: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape and strides.") + * + */ + } + + /* "View.MemoryView":151 + * + * + * 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(1, 151, __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(1, 151, __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(1, 151, __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":152 + * + * 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":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_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 153, __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(1, 153, __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(1, 153, __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(1, 153, __pyx_L1_error) + + /* "View.MemoryView":152 + * + * 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":154 + * 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":151 + * + * + * 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":157 + * + * 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(1, 157, __pyx_L1_error) + if (__pyx_t_4) { + + /* "View.MemoryView":158 + * cdef char order + * if mode == 'fortran': + * order = b'F' # <<<<<<<<<<<<<< + * self.mode = u'fortran' + * elif mode == 'c': + */ + __pyx_v_order = 'F'; + + /* "View.MemoryView":159 + * 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":157 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = b'F' + * self.mode = u'fortran' + */ + goto __pyx_L10; + } + + /* "View.MemoryView":160 + * 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(1, 160, __pyx_L1_error) + if (likely(__pyx_t_4)) { + + /* "View.MemoryView":161 + * self.mode = u'fortran' + * elif mode == 'c': + * order = b'C' # <<<<<<<<<<<<<< + * self.mode = u'c' + * else: + */ + __pyx_v_order = 'C'; + + /* "View.MemoryView":162 + * 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":160 + * order = b'F' + * self.mode = u'fortran' + * elif mode == 'c': # <<<<<<<<<<<<<< + * order = b'C' + * self.mode = u'c' + */ + goto __pyx_L10; + } + + /* "View.MemoryView":164 + * 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(1, 164, __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(1, 164, __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(1, 164, __pyx_L1_error) + } + __pyx_L10:; + + /* "View.MemoryView":166 + * 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":169 + * 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":170 + * + * 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(1, 170, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 170, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_v_self->dtype_is_object = __pyx_t_4; + + /* "View.MemoryView":171 + * 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":174 + * + * + * 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":175 + * + * 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":176 + * 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__4, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 176, __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(1, 176, __pyx_L1_error) + + /* "View.MemoryView":175 + * + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ + } + + /* "View.MemoryView":178 + * 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":179 + * + * 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":180 + * 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(1, 180, __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(1, 180, __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":181 + * 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":182 + * for i in range(self.len / itemsize): + * p[i] = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + Py_INCREF(Py_None); + } + + /* "View.MemoryView":178 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ + } + + /* "View.MemoryView":171 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * + * + */ + } + + /* "View.MemoryView":122 + * 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":185 + * + * @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; + 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":186 + * @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":187 + * 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(1, 187, __pyx_L1_error) + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":188 + * 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":187 + * 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":189 + * 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(1, 189, __pyx_L1_error) + __pyx_t_1 = (__pyx_t_2 != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":190 + * 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":189 + * 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":191 + * 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":192 + * 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__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 192, __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(1, 192, __pyx_L1_error) + + /* "View.MemoryView":191 + * 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":193 + * 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":194 + * 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":195 + * 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":196 + * 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":197 + * 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":198 + * 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":199 + * 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":200 + * info.suboffsets = NULL + * info.itemsize = self.itemsize + * info.readonly = 0 # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + __pyx_v_info->readonly = 0; + + /* "View.MemoryView":202 + * 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":203 + * + * 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":202 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ + goto __pyx_L5; + } + + /* "View.MemoryView":205 + * info.format = self.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.obj = self + */ + /*else*/ { + __pyx_v_info->format = NULL; + } + __pyx_L5:; + + /* "View.MemoryView":207 + * 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":185 + * + * @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":211 + * __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":212 + * + * 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":213 + * 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":212 + * + * 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":214 + * 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":215 + * 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":216 + * 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":215 + * 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":218 + * 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":214 + * 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":219 + * self._strides, self.ndim, False) + * free(self.data) + * PyObject_Free(self._shape) # <<<<<<<<<<<<<< + * + * @property + */ + PyObject_Free(__pyx_v_self->_shape); + + /* "View.MemoryView":211 + * __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":222 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":223 + * @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(1, 223, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":222 + * + * @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":226 + * + * @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; + __Pyx_RefNannySetupContext("get_memview", 0); + + /* "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) + * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":228 + * 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(1, 228, __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(1, 228, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 228, __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(1, 228, __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":226 + * + * @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":230 + * 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":231 + * + * def __len__(self): + * return self._shape[0] # <<<<<<<<<<<<<< + * + * def __getattr__(self, attr): + */ + __pyx_r = (__pyx_v_self->_shape[0]); + goto __pyx_L0; + + /* "View.MemoryView":230 + * 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":233 + * 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; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":234 + * + * 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(1, 234, __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(1, 234, __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":233 + * 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":236 + * 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; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":237 + * + * 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(1, 237, __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(1, 237, __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":236 + * 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":239 + * 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; + __Pyx_RefNannySetupContext("__setitem__", 0); + + /* "View.MemoryView":240 + * + * 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(1, 240, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(1, 240, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":239 + * 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; + __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__6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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; + __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__7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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":244 + * + * @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; + __Pyx_RefNannySetupContext("array_cwrapper", 0); + + /* "View.MemoryView":248 + * 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":249 + * + * 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(1, 249, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 249, __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(1, 249, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 249, __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(1, 249, __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":248 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":251 + * 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(1, 251, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 251, __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(1, 251, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 251, __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":252 + * 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(1, 252, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(1, 252, __pyx_L1_error) + + /* "View.MemoryView":251 + * 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(1, 251, __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":253 + * 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":255 + * 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":244 + * + * @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":281 + * 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_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(1, 281, __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(1, 281, __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":282 + * 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":281 + * 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":283 + * 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":284 + * 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":283 + * 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; + __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(1, 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(1, 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(1, 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(1, 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(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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; + __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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 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(1, 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":298 + * + * @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":300 + * 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":304 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":306 + * 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":307 + * + * 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":306 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + } + + /* "View.MemoryView":309 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + /* "View.MemoryView":298 + * + * @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":345 + * 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_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(1, 345, __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(1, 345, __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(1, 345, __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(1, 345, __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(1, 345, __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; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "View.MemoryView":346 + * + * 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":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_GetBuffer(obj, &self.view, flags) + */ + __pyx_v_self->flags = __pyx_v_flags; + + /* "View.MemoryView":348 + * 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":349 + * 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(1, 349, __pyx_L1_error) + + /* "View.MemoryView":350 + * 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":351 + * __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":352 + * if self.view.obj == NULL: + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) # <<<<<<<<<<<<<< + * + * global __pyx_memoryview_thread_locks_used + */ + Py_INCREF(Py_None); + + /* "View.MemoryView":350 + * 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":348 + * 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 + * + * 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":356 + * 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":357 + * 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":355 + * + * 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":358 + * 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":359 + * __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":360 + * 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":361 + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + PyErr_NoMemory(); __PYX_ERR(1, 361, __pyx_L1_error) + + /* "View.MemoryView":360 + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + } + + /* "View.MemoryView":358 + * 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":363 + * 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":364 + * + * 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_L11_bool_binop_done; + } + __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L11_bool_binop_done:; + __pyx_v_self->dtype_is_object = __pyx_t_1; + + /* "View.MemoryView":363 + * 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_L10; + } + + /* "View.MemoryView":366 + * 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_L10:; + + /* "View.MemoryView":368 + * 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":370 + * 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":345 + * 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":372 + * 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":373 + * + * 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":374 + * 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":373 + * + * 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":375 + * 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":377 + * 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":378 + * + * (<__pyx_buffer *> &self.view).obj = NULL + * Py_DECREF(Py_None) # <<<<<<<<<<<<<< + * + * cdef int i + */ + Py_DECREF(Py_None); + + /* "View.MemoryView":375 + * 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":382 + * 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":383 + * 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":384 + * 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":385 + * 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":386 + * 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":388 + * 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":387 + * __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":386 + * 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":389 + * __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":384 + * 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":391 + * 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":382 + * 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":372 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":393 + * 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; + __Pyx_RefNannySetupContext("get_item_pointer", 0); + + /* "View.MemoryView":395 + * 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":397 + * 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(1, 397, __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(1, 397, __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(1, 397, __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(1, 397, __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(1, 397, __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(1, 397, __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(1, 397, __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":398 + * + * 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(1, 398, __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(1, 398, __pyx_L1_error) + __pyx_v_itemp = __pyx_t_7; + + /* "View.MemoryView":397 + * 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":400 + * itemp = pybuffer_index(&self.view, itemp, idx, dim) + * + * return itemp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_itemp; + goto __pyx_L0; + + /* "View.MemoryView":393 + * 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":403 + * + * + * 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; + __Pyx_RefNannySetupContext("__getitem__", 0); + + /* "View.MemoryView":404 + * + * 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":405 + * 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":404 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ + } + + /* "View.MemoryView":407 + * 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(1, 407, __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(1, 407, __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(1, 407, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 407, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 407, __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":410 + * + * 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(1, 410, __pyx_L1_error) + if (__pyx_t_2) { + + /* "View.MemoryView":411 + * 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(1, 411, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":410 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ + } + + /* "View.MemoryView":413 + * 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(1, 413, __pyx_L1_error) + __pyx_v_itemp = __pyx_t_6; + + /* "View.MemoryView":414 + * 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(1, 414, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":403 + * + * + * 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":416 + * 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; + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_INCREF(__pyx_v_index); + + /* "View.MemoryView":417 + * + * 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":418 + * 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__8, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 418, __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(1, 418, __pyx_L1_error) + + /* "View.MemoryView":417 + * + * def __setitem__(memoryview self, object index, object value): + * if self.view.readonly: # <<<<<<<<<<<<<< + * raise TypeError("Cannot assign to read-only memoryview") + * + */ + } + + /* "View.MemoryView":420 + * 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(1, 420, __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(1, 420, __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(1, 420, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 420, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 420, __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":422 + * 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(1, 422, __pyx_L1_error) + if (__pyx_t_1) { + + /* "View.MemoryView":423 + * + * 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(1, 423, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_obj = __pyx_t_2; + __pyx_t_2 = 0; + + /* "View.MemoryView":424 + * 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(1, 424, __pyx_L1_error) + if (__pyx_t_1) { + + /* "View.MemoryView":425 + * 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(1, 425, __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(1, 425, __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":424 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ + goto __pyx_L5; + } + + /* "View.MemoryView":427 + * 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(1, 427, __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(1, 427, __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(1, 427, __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":422 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ + goto __pyx_L4; + } + + /* "View.MemoryView":429 + * 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(1, 429, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_L4:; + + /* "View.MemoryView":416 + * 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":431 + * 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; + __Pyx_RefNannySetupContext("is_slice", 0); + __Pyx_INCREF(__pyx_v_obj); + + /* "View.MemoryView":432 + * + * 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":433 + * 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":434 + * 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(1, 434, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":435 + * 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(1, 435, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_7); + + /* "View.MemoryView":434 + * 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(1, 434, __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(1, 434, __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":433 + * 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":436 + * 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(1, 436, __pyx_L6_except_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GOTREF(__pyx_t_6); + + /* "View.MemoryView":437 + * 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":433 + * 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":432 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, + */ + } + + /* "View.MemoryView":439 + * 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":431 + * 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":441 + * 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; + __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); + + /* "View.MemoryView":445 + * 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(1, 445, __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(1, 445, __pyx_L1_error) + + /* "View.MemoryView":446 + * + * 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(1, 446, __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(1, 446, __pyx_L1_error) + + /* "View.MemoryView":447 + * 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(1, 447, __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(1, 447, __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(1, 447, __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(1, 447, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":445 + * 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(1, 445, __pyx_L1_error) + + /* "View.MemoryView":441 + * 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":449 + * 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; + __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); + + /* "View.MemoryView":451 + * 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":456 + * 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(1, 456, __pyx_L1_error) + __pyx_v_dst_slice = __pyx_t_1; + + /* "View.MemoryView":458 + * 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":459 + * + * 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":460 + * 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":461 + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + * raise MemoryError # <<<<<<<<<<<<<< + * item = tmp + * else: + */ + PyErr_NoMemory(); __PYX_ERR(1, 461, __pyx_L1_error) + + /* "View.MemoryView":460 + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ + } + + /* "View.MemoryView":462 + * if tmp == NULL: + * raise MemoryError + * item = tmp # <<<<<<<<<<<<<< + * else: + * item = array + */ + __pyx_v_item = __pyx_v_tmp; + + /* "View.MemoryView":458 + * 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":464 + * item = tmp + * else: + * item = array # <<<<<<<<<<<<<< + * + * try: + */ + /*else*/ { + __pyx_v_item = ((void *)__pyx_v_array); + } + __pyx_L3:; + + /* "View.MemoryView":466 + * item = array + * + * try: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * ( item)[0] = value + */ + /*try:*/ { + + /* "View.MemoryView":467 + * + * 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":468 + * 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":467 + * + * try: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ + goto __pyx_L8; + } + + /* "View.MemoryView":470 + * ( 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(1, 470, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L8:; + + /* "View.MemoryView":474 + * + * + * 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":475 + * + * 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(1, 475, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":474 + * + * + * 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":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, # <<<<<<<<<<<<<< + * 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":479 + * 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":449 + * 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":481 + * 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; + __Pyx_RefNannySetupContext("setitem_indexed", 0); + + /* "View.MemoryView":482 + * + * 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(1, 482, __pyx_L1_error) + __pyx_v_itemp = __pyx_t_1; + + /* "View.MemoryView":483 + * 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(1, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":481 + * 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":485 + * 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; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":488 + * """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(1, 488, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":491 + * 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(1, 491, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":492 + * + * 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":493 + * 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(1, 493, __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(1, 493, __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(1, 493, __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(1, 493, __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(1, 493, __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(1, 493, __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":492 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ + } + + /* "View.MemoryView":497 + * 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":498 + * 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(1, 498, __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":497 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ + } + + /* "View.MemoryView":499 + * 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":494 + * 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(1, 494, __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(1, 494, __pyx_L5_except_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GOTREF(__pyx_t_1); + + /* "View.MemoryView":495 + * 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__9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 495, __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(1, 495, __pyx_L5_except_error) + } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; + + /* "View.MemoryView":492 + * + * 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":485 + * 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":501 + * 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; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":504 + * """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(1, 504, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_struct = __pyx_t_1; + __pyx_t_1 = 0; + + /* "View.MemoryView":509 + * 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":510 + * + * 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(1, 510, __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(1, 510, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 510, __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(1, 510, __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(1, 510, __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(1, 510, __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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 510, __pyx_L1_error) + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "View.MemoryView":509 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":512 + * 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(1, 512, __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(1, 512, __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(1, 512, __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(1, 512, __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(1, 512, __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(1, 512, __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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 512, __pyx_L1_error) + __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":514 + * 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(1, 514, __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":515 + * + * for i, c in enumerate(bytesvalue): + * itemp[i] = c # <<<<<<<<<<<<<< + * + * @cname('getbuffer') + */ + __pyx_v_i = __pyx_t_9; + + /* "View.MemoryView":514 + * 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":515 + * + * 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":501 + * 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":518 + * + * @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; + 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":519 + * @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":520 + * 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__10, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 520, __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(1, 520, __pyx_L1_error) + + /* "View.MemoryView":519 + * @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":522 + * 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":523 + * + * 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":522 + * 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":525 + * info.shape = self.view.shape + * else: + * info.shape = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_STRIDES: + */ + /*else*/ { + __pyx_v_info->shape = NULL; + } + __pyx_L6:; + + /* "View.MemoryView":527 + * 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":528 + * + * 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":527 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ + goto __pyx_L7; + } + + /* "View.MemoryView":530 + * info.strides = self.view.strides + * else: + * info.strides = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_INDIRECT: + */ + /*else*/ { + __pyx_v_info->strides = NULL; + } + __pyx_L7:; + + /* "View.MemoryView":532 + * 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":533 + * + * 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":532 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ + goto __pyx_L8; + } + + /* "View.MemoryView":535 + * info.suboffsets = self.view.suboffsets + * else: + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * + * if flags & PyBUF_FORMAT: + */ + /*else*/ { + __pyx_v_info->suboffsets = NULL; + } + __pyx_L8:; + + /* "View.MemoryView":537 + * 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":538 + * + * 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":537 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ + goto __pyx_L9; + } + + /* "View.MemoryView":540 + * info.format = self.view.format + * else: + * info.format = NULL # <<<<<<<<<<<<<< + * + * info.buf = self.view.buf + */ + /*else*/ { + __pyx_v_info->format = NULL; + } + __pyx_L9:; + + /* "View.MemoryView":542 + * 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":543 + * + * 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":544 + * 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":545 + * 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":546 + * 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":547 + * 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":518 + * + * @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":553 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":554 + * @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(1, 554, __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(1, 554, __pyx_L1_error) + __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":555 + * 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(1, 555, __pyx_L1_error) + + /* "View.MemoryView":556 + * 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":553 + * + * @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":559 + * + * @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":560 + * @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":559 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.obj + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":563 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":564 + * @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(1, 564, __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(1, 564, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 564, __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(1, 564, __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":563 + * + * @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":567 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":568 + * @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":570 + * 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__11, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 570, __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(1, 570, __pyx_L1_error) + + /* "View.MemoryView":568 + * @property + * def strides(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ + } + + /* "View.MemoryView":572 + * 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(1, 572, __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(1, 572, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(1, 572, __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(1, 572, __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":567 + * + * @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":575 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":576 + * @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":577 + * 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(1, 577, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__12, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 577, __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":576 + * @property + * def suboffsets(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return (-1,) * self.view.ndim + * + */ + } + + /* "View.MemoryView":579 + * 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(1, 579, __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(1, 579, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(1, 579, __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(1, 579, __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":575 + * + * @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":582 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":583 + * @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(1, 583, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":582 + * + * @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":586 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":587 + * @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(1, 587, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":586 + * + * @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":590 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":591 + * @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(1, 591, __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(1, 591, __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(1, 591, __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":590 + * + * @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":594 + * + * @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; + __Pyx_RefNannySetupContext("__get__", 0); + + /* "View.MemoryView":595 + * @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":596 + * 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":598 + * 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(1, 598, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); + __pyx_t_6 = 0; + + /* "View.MemoryView":599 + * + * 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(1, 599, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); + __pyx_t_6 = 0; + } + + /* "View.MemoryView":601 + * 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":595 + * @property + * def size(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ + } + + /* "View.MemoryView":603 + * 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":594 + * + * @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":605 + * 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":606 + * + * 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":607 + * 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":606 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ + } + + /* "View.MemoryView":609 + * return self.view.shape[0] + * + * return 0 # <<<<<<<<<<<<<< + * + * def __repr__(self): + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":605 + * 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":611 + * 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; + __Pyx_RefNannySetupContext("__repr__", 0); + + /* "View.MemoryView":612 + * + * 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(1, 612, __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(1, 612, __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(1, 612, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "View.MemoryView":613 + * 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(1, 613, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + /* "View.MemoryView":612 + * + * def __repr__(self): + * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< + * id(self)) + * + */ + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 612, __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(1, 612, __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":611 + * 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":615 + * 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; + __Pyx_RefNannySetupContext("__str__", 0); + + /* "View.MemoryView":616 + * + * 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(1, 616, __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(1, 616, __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(1, 616, __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(1, 616, __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(1, 616, __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":615 + * 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":619 + * + * + * 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; + __Pyx_RefNannySetupContext("is_c_contig", 0); + + /* "View.MemoryView":622 + * 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(1, 622, __pyx_L1_error) + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":623 + * 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(1, 623, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":619 + * + * + * 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":625 + * 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; + __Pyx_RefNannySetupContext("is_f_contig", 0); + + /* "View.MemoryView":628 + * 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(1, 628, __pyx_L1_error) + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":629 + * 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(1, 629, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":625 + * 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":631 + * 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; + __Pyx_RefNannySetupContext("copy", 0); + + /* "View.MemoryView":633 + * 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":635 + * 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":636 + * + * 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(1, 636, __pyx_L1_error) + __pyx_v_mslice = __pyx_t_1; + + /* "View.MemoryView":641 + * 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(1, 641, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":631 + * 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":643 + * 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; + __Pyx_RefNannySetupContext("copy_fortran", 0); + + /* "View.MemoryView":645 + * 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":647 + * 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":648 + * + * 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(1, 648, __pyx_L1_error) + __pyx_v_dst = __pyx_t_1; + + /* "View.MemoryView":653 + * 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(1, 653, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":643 + * 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; + __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__13, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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; + __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__14, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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":657 + * + * @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; + __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); + + /* "View.MemoryView":658 + * @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(1, 658, __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(1, 658, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 658, __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(1, 658, __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":659 + * 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":660 + * 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":657 + * + * @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":663 + * + * @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":664 + * @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":663 + * + * @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":666 + * 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; + __Pyx_RefNannySetupContext("_unellipsify", 0); + + /* "View.MemoryView":671 + * 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":672 + * """ + * if not isinstance(index, tuple): + * tup = (index,) # <<<<<<<<<<<<<< + * else: + * tup = index + */ + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 672, __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":671 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":674 + * tup = (index,) + * else: + * tup = index # <<<<<<<<<<<<<< + * + * result = [] + */ + /*else*/ { + __Pyx_INCREF(__pyx_v_index); + __pyx_v_tup = __pyx_v_index; + } + __pyx_L3:; + + /* "View.MemoryView":676 + * tup = index + * + * result = [] # <<<<<<<<<<<<<< + * have_slices = False + * seen_ellipsis = False + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 676, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_result = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "View.MemoryView":677 + * + * result = [] + * have_slices = False # <<<<<<<<<<<<<< + * seen_ellipsis = False + * for idx, item in enumerate(tup): + */ + __pyx_v_have_slices = 0; + + /* "View.MemoryView":678 + * result = [] + * have_slices = False + * seen_ellipsis = False # <<<<<<<<<<<<<< + * for idx, item in enumerate(tup): + * if item is Ellipsis: + */ + __pyx_v_seen_ellipsis = 0; + + /* "View.MemoryView":679 + * 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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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(1, 679, __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":680 + * 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":681 + * 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":682 + * 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(1, 682, __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(1, 682, __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__15); + __Pyx_GIVEREF(__pyx_slice__15); + PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__15); + } + } + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 682, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":683 + * 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":681 + * 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":685 + * seen_ellipsis = True + * else: + * result.append(slice(None)) # <<<<<<<<<<<<<< + * have_slices = True + * else: + */ + /*else*/ { + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__15); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 685, __pyx_L1_error) + } + __pyx_L7:; + + /* "View.MemoryView":686 + * 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":680 + * 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":688 + * 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":689 + * 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(1, 689, __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(1, 689, __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(1, 689, __pyx_L1_error) + + /* "View.MemoryView":688 + * 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":691 + * 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":692 + * + * 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(1, 692, __pyx_L1_error) + } + __pyx_L6:; + + /* "View.MemoryView":679 + * 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":694 + * 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(1, 694, __pyx_L1_error) + __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); + + /* "View.MemoryView":695 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + __pyx_t_1 = (__pyx_v_nslices != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":696 + * 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(1, 696, __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__15); + __Pyx_GIVEREF(__pyx_slice__15); + PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__15); + } + } + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 696, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":695 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ + } + + /* "View.MemoryView":698 + * 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(1, 698, __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(1, 698, __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(1, 698, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 698, __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":666 + * 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":700 + * 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; + __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); + + /* "View.MemoryView":701 + * + * 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":702 + * 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":703 + * 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__16, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 703, __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(1, 703, __pyx_L1_error) + + /* "View.MemoryView":702 + * 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":700 + * 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":710 + * + * @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; + __Pyx_RefNannySetupContext("memview_slice", 0); + + /* "View.MemoryView":711 + * @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":718 + * + * + * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< + * + * cdef _memoryviewslice memviewsliceobj + */ + (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); + + /* "View.MemoryView":722 + * 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(1, 722, __pyx_L1_error) + } + } + #endif + + /* "View.MemoryView":724 + * 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":725 + * + * 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(1, 725, __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":726 + * 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":724 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ + goto __pyx_L3; + } + + /* "View.MemoryView":728 + * 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":729 + * else: + * slice_copy(memview, &src) + * p_src = &src # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_p_src = (&__pyx_v_src); + } + __pyx_L3:; + + /* "View.MemoryView":735 + * + * + * 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":736 + * + * 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":741 + * + * + * 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":742 + * + * 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":746 + * 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(1, 746, __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(1, 746, __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(1, 746, __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(1, 746, __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(1, 746, __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(1, 746, __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(1, 746, __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":747 + * + * 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":751 + * 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(1, 751, __pyx_L1_error) + + /* "View.MemoryView":748 + * 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(1, 748, __pyx_L1_error) + + /* "View.MemoryView":747 + * + * 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":754 + * 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":755 + * 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":756 + * 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":757 + * 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":758 + * 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":754 + * 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":760 + * 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(1, 760, __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(1, 760, __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(1, 760, __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":761 + * 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(1, 761, __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(1, 761, __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(1, 761, __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":762 + * 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(1, 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(1, 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(1, 762, __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":764 + * 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(1, 764, __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":765 + * + * 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(1, 765, __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":766 + * 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(1, 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_step = __pyx_t_1; + + /* "View.MemoryView":768 + * 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(1, 768, __pyx_L1_error) + + /* "View.MemoryView":774 + * 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":746 + * 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":776 + * 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":777 + * + * 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":778 + * 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(1, 778, __pyx_L1_error) } + + /* "View.MemoryView":779 + * 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(1, 779, __pyx_L1_error) } + + /* "View.MemoryView":777 + * + * 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(1, 777, __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(1, 777, __pyx_L1_error) + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "View.MemoryView":776 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ + } + + /* "View.MemoryView":782 + * 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":783 + * 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(1, 782, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + + /* "View.MemoryView":782 + * 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(1, 782, __pyx_L1_error) + __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":710 + * + * @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":807 + * + * @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; + + /* "View.MemoryView":827 + * 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":829 + * 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":830 + * + * 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":829 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ + } + + /* "View.MemoryView":831 + * 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":832 + * 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(1, 832, __pyx_L1_error) + + /* "View.MemoryView":831 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ + } + + /* "View.MemoryView":827 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ + goto __pyx_L3; + } + + /* "View.MemoryView":835 + * 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":837 + * 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":838 + * + * 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(1, 838, __pyx_L1_error) + + /* "View.MemoryView":837 + * 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":841 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + __pyx_t_2 = (__pyx_v_have_start != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":842 + * + * 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":843 + * if have_start: + * if start < 0: + * start += shape # <<<<<<<<<<<<<< + * if start < 0: + * start = 0 + */ + __pyx_v_start = (__pyx_v_start + __pyx_v_shape); + + /* "View.MemoryView":844 + * 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":845 + * start += shape + * if start < 0: + * start = 0 # <<<<<<<<<<<<<< + * elif start >= shape: + * if negative_step: + */ + __pyx_v_start = 0; + + /* "View.MemoryView":844 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ + } + + /* "View.MemoryView":842 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ + goto __pyx_L12; + } + + /* "View.MemoryView":846 + * 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":847 + * 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":848 + * elif start >= shape: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = shape + */ + __pyx_v_start = (__pyx_v_shape - 1); + + /* "View.MemoryView":847 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + goto __pyx_L14; + } + + /* "View.MemoryView":850 + * start = shape - 1 + * else: + * start = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + /*else*/ { + __pyx_v_start = __pyx_v_shape; + } + __pyx_L14:; + + /* "View.MemoryView":846 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ + } + __pyx_L12:; + + /* "View.MemoryView":841 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ + goto __pyx_L11; + } + + /* "View.MemoryView":852 + * 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":853 + * else: + * if negative_step: + * start = shape - 1 # <<<<<<<<<<<<<< + * else: + * start = 0 + */ + __pyx_v_start = (__pyx_v_shape - 1); + + /* "View.MemoryView":852 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ + goto __pyx_L15; + } + + /* "View.MemoryView":855 + * start = shape - 1 + * else: + * start = 0 # <<<<<<<<<<<<<< + * + * if have_stop: + */ + /*else*/ { + __pyx_v_start = 0; + } + __pyx_L15:; + } + __pyx_L11:; + + /* "View.MemoryView":857 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + __pyx_t_2 = (__pyx_v_have_stop != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":858 + * + * 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":859 + * if have_stop: + * if stop < 0: + * stop += shape # <<<<<<<<<<<<<< + * if stop < 0: + * stop = 0 + */ + __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); + + /* "View.MemoryView":860 + * 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":861 + * stop += shape + * if stop < 0: + * stop = 0 # <<<<<<<<<<<<<< + * elif stop > shape: + * stop = shape + */ + __pyx_v_stop = 0; + + /* "View.MemoryView":860 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ + } + + /* "View.MemoryView":858 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ + goto __pyx_L17; + } + + /* "View.MemoryView":862 + * 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":863 + * stop = 0 + * elif stop > shape: + * stop = shape # <<<<<<<<<<<<<< + * else: + * if negative_step: + */ + __pyx_v_stop = __pyx_v_shape; + + /* "View.MemoryView":862 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ + } + __pyx_L17:; + + /* "View.MemoryView":857 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ + goto __pyx_L16; + } + + /* "View.MemoryView":865 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + /*else*/ { + __pyx_t_2 = (__pyx_v_negative_step != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":866 + * else: + * if negative_step: + * stop = -1 # <<<<<<<<<<<<<< + * else: + * stop = shape + */ + __pyx_v_stop = -1L; + + /* "View.MemoryView":865 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ + goto __pyx_L19; + } + + /* "View.MemoryView":868 + * stop = -1 + * else: + * stop = shape # <<<<<<<<<<<<<< + * + * if not have_step: + */ + /*else*/ { + __pyx_v_stop = __pyx_v_shape; + } + __pyx_L19:; + } + __pyx_L16:; + + /* "View.MemoryView":870 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":871 + * + * if not have_step: + * step = 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_step = 1; + + /* "View.MemoryView":870 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ + } + + /* "View.MemoryView":875 + * + * 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":877 + * 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":878 + * + * if (stop - start) - step * new_shape: + * new_shape += 1 # <<<<<<<<<<<<<< + * + * if new_shape < 0: + */ + __pyx_v_new_shape = (__pyx_v_new_shape + 1); + + /* "View.MemoryView":877 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ + } + + /* "View.MemoryView":880 + * 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":881 + * + * if new_shape < 0: + * new_shape = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_new_shape = 0; + + /* "View.MemoryView":880 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ + } + + /* "View.MemoryView":884 + * + * + * 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":885 + * + * 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":886 + * 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":889 + * + * + * 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":890 + * + * 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":889 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ + goto __pyx_L23; + } + + /* "View.MemoryView":892 + * 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":894 + * 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":895 + * + * 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":896 + * 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":897 + * 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":896 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ + goto __pyx_L26; + } + + /* "View.MemoryView":899 + * 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":900 + * 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(1, 899, __pyx_L1_error) + } + __pyx_L26:; + + /* "View.MemoryView":895 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ + goto __pyx_L25; + } + + /* "View.MemoryView":902 + * "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":894 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ + } + + /* "View.MemoryView":904 + * suboffset_dim[0] = new_ndim + * + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":807 + * + * @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":910 + * + * @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; + __Pyx_RefNannySetupContext("pybuffer_index", 0); + + /* "View.MemoryView":912 + * 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":913 + * 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":916 + * 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":917 + * + * 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(1, 917, __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(1, 917, __pyx_L1_error) + } + __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); + + /* "View.MemoryView":918 + * if view.ndim == 0: + * shape = view.len / itemsize + * stride = itemsize # <<<<<<<<<<<<<< + * else: + * shape = view.shape[dim] + */ + __pyx_v_stride = __pyx_v_itemsize; + + /* "View.MemoryView":916 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ + goto __pyx_L3; + } + + /* "View.MemoryView":920 + * 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":921 + * 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":922 + * 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":923 + * 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":922 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ + } + } + __pyx_L3:; + + /* "View.MemoryView":925 + * 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":926 + * + * 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":927 + * 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":928 + * 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(1, 928, __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(1, 928, __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(1, 928, __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(1, 928, __pyx_L1_error) + + /* "View.MemoryView":927 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ + } + + /* "View.MemoryView":925 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ + } + + /* "View.MemoryView":930 + * 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":931 + * + * 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(1, 931, __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(1, 931, __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(1, 931, __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(1, 931, __pyx_L1_error) + + /* "View.MemoryView":930 + * 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":933 + * 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":934 + * + * 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":935 + * 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":934 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ + } + + /* "View.MemoryView":937 + * resultp = ( resultp)[0] + suboffset + * + * return resultp # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_resultp; + goto __pyx_L0; + + /* "View.MemoryView":910 + * + * @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":943 + * + * @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; + + /* "View.MemoryView":944 + * @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":946 + * 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":947 + * + * 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":951 + * + * 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":952 + * 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":953 + * 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":954 + * 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":956 + * 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":957 + * + * 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(1, 957, __pyx_L1_error) + + /* "View.MemoryView":956 + * 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":959 + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + * return 1 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 1; + goto __pyx_L0; + + /* "View.MemoryView":943 + * + * @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":976 + * 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":977 + * + * 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":976 + * 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":979 + * __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; + __Pyx_RefNannySetupContext("convert_item_to_object", 0); + + /* "View.MemoryView":980 + * + * 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":981 + * 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(1, 981, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "View.MemoryView":980 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ + } + + /* "View.MemoryView":983 + * 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(1, 983, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + } + + /* "View.MemoryView":979 + * __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":985 + * 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; + __Pyx_RefNannySetupContext("assign_item_from_object", 0); + + /* "View.MemoryView":986 + * + * 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":987 + * 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(1, 987, __pyx_L1_error) + + /* "View.MemoryView":986 + * + * 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":989 + * 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(1, 989, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_L3:; + + /* "View.MemoryView":985 + * 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":992 + * + * @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":993 + * @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":992 + * + * @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; + __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__17, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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; + __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__18, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 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(1, 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":999 + * + * @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; + __Pyx_RefNannySetupContext("memoryview_fromslice", 0); + + /* "View.MemoryView":1007 + * 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":1008 + * + * if memviewslice.memview == Py_None: + * return None # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + + /* "View.MemoryView":1007 + * cdef _memoryviewslice result + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ + } + + /* "View.MemoryView":1013 + * + * + * 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(1, 1013, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1013, __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(1, 1013, __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":1015 + * 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":1016 + * + * result.from_slice = memviewslice + * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< + * + * result.from_object = ( memviewslice.memview).base + */ + __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); + + /* "View.MemoryView":1018 + * __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(1, 1018, __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":1019 + * + * 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":1021 + * 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":1022 + * + * 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":1023 + * 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":1024 + * 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":1025 + * 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":1027 + * 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":1028 + * + * 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":1027 + * Py_INCREF(Py_None) + * + * if (memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< + * result.flags = PyBUF_RECORDS + * else: + */ + goto __pyx_L4; + } + + /* "View.MemoryView":1030 + * 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":1032 + * 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":1033 + * + * 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":1036 + * + * + * 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":1037 + * + * 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":1038 + * 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":1039 + * 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":1040 + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets + * break # <<<<<<<<<<<<<< + * + * result.view.len = result.view.itemsize + */ + goto __pyx_L6_break; + + /* "View.MemoryView":1038 + * 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":1042 + * 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":1043 + * + * 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(1, 1043, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); + __pyx_t_2 = 0; + + /* "View.MemoryView":1044 + * 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(1, 1044, __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(1, 1044, __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(1, 1044, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result->__pyx_base.view.len = __pyx_t_9; + } + + /* "View.MemoryView":1046 + * 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":1047 + * + * 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":1049 + * 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":999 + * + * @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":1052 + * + * @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; + __Pyx_RefNannySetupContext("get_slice_from_memview", 0); + + /* "View.MemoryView":1055 + * __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":1056 + * 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(1, 1056, __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":1057 + * 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":1055 + * __Pyx_memviewslice *mslice) except NULL: + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ + } + + /* "View.MemoryView":1059 + * return &obj.from_slice + * else: + * slice_copy(memview, mslice) # <<<<<<<<<<<<<< + * return mslice + * + */ + /*else*/ { + __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); + + /* "View.MemoryView":1060 + * else: + * slice_copy(memview, mslice) + * return mslice # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_slice_copy') + */ + __pyx_r = __pyx_v_mslice; + goto __pyx_L0; + } + + /* "View.MemoryView":1052 + * + * @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":1063 + * + * @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":1067 + * 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":1068 + * + * 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":1069 + * 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":1071 + * 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":1072 + * + * 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":1074 + * 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":1075 + * + * 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":1076 + * 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":1077 + * 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":1063 + * + * @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":1080 + * + * @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; + __Pyx_RefNannySetupContext("memoryview_copy", 0); + + /* "View.MemoryView":1083 + * "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":1084 + * 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(1, 1084, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1080 + * + * @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":1087 + * + * @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; + __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); + + /* "View.MemoryView":1094 + * 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":1095 + * + * 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":1096 + * 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":1094 + * 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":1098 + * 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":1099 + * 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":1101 + * 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":1103 + * 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(1, 1101, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "View.MemoryView":1087 + * + * @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":1109 + * + * + * 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":1110 + * + * 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":1111 + * 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":1110 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ + } + + /* "View.MemoryView":1113 + * return -arg + * else: + * return arg # <<<<<<<<<<<<<< + * + * @cname('__pyx_get_best_slice_order') + */ + /*else*/ { + __pyx_r = __pyx_v_arg; + goto __pyx_L0; + } + + /* "View.MemoryView":1109 + * + * + * 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":1116 + * + * @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":1121 + * """ + * cdef int i + * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< + * cdef Py_ssize_t f_stride = 0 + * + */ + __pyx_v_c_stride = 0; + + /* "View.MemoryView":1122 + * 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":1124 + * 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":1125 + * + * 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":1126 + * 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":1127 + * if mslice.shape[i] > 1: + * c_stride = mslice.strides[i] + * break # <<<<<<<<<<<<<< + * + * for i in range(ndim): + */ + goto __pyx_L4_break; + + /* "View.MemoryView":1125 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ + } + } + __pyx_L4_break:; + + /* "View.MemoryView":1129 + * 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":1130 + * + * 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":1131 + * 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":1132 + * 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":1130 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ + } + } + __pyx_L7_break:; + + /* "View.MemoryView":1134 + * 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":1135 + * + * 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":1134 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ + } + + /* "View.MemoryView":1137 + * return 'C' + * else: + * return 'F' # <<<<<<<<<<<<<< + * + * @cython.cdivision(True) + */ + /*else*/ { + __pyx_r = 'F'; + goto __pyx_L0; + } + + /* "View.MemoryView":1116 + * + * @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":1140 + * + * @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":1147 + * + * 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":1148 + * 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":1149 + * 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":1150 + * 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":1152 + * 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":1153 + * + * 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":1154 + * 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":1153 + * + * 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":1155 + * 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":1153 + * + * 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":1157 + * 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":1158 + * 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":1159 + * 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":1160 + * 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":1152 + * 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":1162 + * 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":1163 + * 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":1167 + * 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":1168 + * 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":1140 + * + * @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":1170 + * 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":1173 + * __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":1170 + * 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":1177 + * + * @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":1179 + * 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":1181 + * 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":1182 + * + * for shape in src.shape[:ndim]: + * size *= shape # <<<<<<<<<<<<<< + * + * return size + */ + __pyx_v_size = (__pyx_v_size * __pyx_v_shape); + } + + /* "View.MemoryView":1184 + * size *= shape + * + * return size # <<<<<<<<<<<<<< + * + * @cname('__pyx_fill_contig_strides_array') + */ + __pyx_r = __pyx_v_size; + goto __pyx_L0; + + /* "View.MemoryView":1177 + * + * @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":1187 + * + * @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":1196 + * 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":1197 + * + * 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":1198 + * 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":1199 + * 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":1196 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ + goto __pyx_L3; + } + + /* "View.MemoryView":1201 + * 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":1202 + * 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":1203 + * 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":1205 + * stride *= shape[idx] + * + * return stride # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_data_to_temp') + */ + __pyx_r = __pyx_v_stride; + goto __pyx_L0; + + /* "View.MemoryView":1187 + * + * @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":1208 + * + * @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; + + /* "View.MemoryView":1219 + * 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":1220 + * + * 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":1222 + * 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":1223 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1224 + * 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(1, 1224, __pyx_L1_error) + + /* "View.MemoryView":1223 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ + } + + /* "View.MemoryView":1227 + * + * + * tmpslice.data = result # <<<<<<<<<<<<<< + * tmpslice.memview = src.memview + * for i in range(ndim): + */ + __pyx_v_tmpslice->data = ((char *)__pyx_v_result); + + /* "View.MemoryView":1228 + * + * 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":1229 + * 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":1230 + * 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":1231 + * 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":1233 + * 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":1237 + * + * + * 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":1238 + * + * 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":1239 + * 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":1238 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ + } + } + + /* "View.MemoryView":1241 + * 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":1242 + * + * 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":1241 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ + goto __pyx_L9; + } + + /* "View.MemoryView":1244 + * 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":1246 + * copy_strided_to_strided(src, tmpslice, ndim, itemsize) + * + * return result # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "View.MemoryView":1208 + * + * @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":1251 + * + * @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; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_extents", 0); + + /* "View.MemoryView":1254 + * 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(1, 1254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1254, __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":1253 + * 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(1, 1253, __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(1, 1253, __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(1, 1253, __pyx_L1_error) + + /* "View.MemoryView":1251 + * + * @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":1257 + * + * @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; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err_dim", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1258 + * @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(1, 1258, __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(1, 1258, __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(1, 1258, __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(1, 1258, __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(1, 1258, __pyx_L1_error) + + /* "View.MemoryView":1257 + * + * @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":1261 + * + * @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; + #ifdef WITH_THREAD + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); + #endif + __Pyx_RefNannySetupContext("_err", 0); + __Pyx_INCREF(__pyx_v_error); + + /* "View.MemoryView":1262 + * @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":1263 + * 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(1, 1263, __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(1, 1263, __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(1, 1263, __pyx_L1_error) + + /* "View.MemoryView":1262 + * @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":1265 + * raise error(msg.decode('ascii')) + * else: + * raise error # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_copy_contents') + */ + /*else*/ { + __Pyx_Raise(__pyx_v_error, 0, 0, 0); + __PYX_ERR(1, 1265, __pyx_L1_error) + } + + /* "View.MemoryView":1261 + * + * @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":1268 + * + * @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; + + /* "View.MemoryView":1276 + * 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":1277 + * """ + * 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":1279 + * 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":1280 + * 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":1281 + * 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":1284 + * 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":1285 + * + * 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":1284 + * 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":1286 + * 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":1287 + * 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":1286 + * 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":1289 + * 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":1291 + * 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":1292 + * + * 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":1293 + * 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":1294 + * 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":1295 + * 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":1293 + * 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":1297 + * 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(1, 1297, __pyx_L1_error) + } + __pyx_L7:; + + /* "View.MemoryView":1292 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ + } + + /* "View.MemoryView":1299 + * _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":1300 + * + * 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(1, 1300, __pyx_L1_error) + + /* "View.MemoryView":1299 + * _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":1302 + * _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":1304 + * 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":1305 + * + * 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":1304 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ + } + + /* "View.MemoryView":1307 + * 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(1, 1307, __pyx_L1_error) + __pyx_v_tmpdata = __pyx_t_7; + + /* "View.MemoryView":1308 + * + * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) + * src = tmp # <<<<<<<<<<<<<< + * + * if not broadcasting: + */ + __pyx_v_src = __pyx_v_tmp; + + /* "View.MemoryView":1302 + * _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":1310 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); + if (__pyx_t_2) { + + /* "View.MemoryView":1313 + * + * + * 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":1314 + * + * 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":1313 + * + * + * 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":1315 + * 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":1316 + * 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":1315 + * 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":1318 + * 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":1320 + * 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":1321 + * + * 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":1322 + * 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":1323 + * 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":1324 + * 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":1318 + * direct_copy = slice_is_contig(dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ + } + + /* "View.MemoryView":1310 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ + } + + /* "View.MemoryView":1326 + * 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":1329 + * + * + * transpose_memslice(&src) # <<<<<<<<<<<<<< + * transpose_memslice(&dst) + * + */ + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1329, __pyx_L1_error) + + /* "View.MemoryView":1330 + * + * 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(1, 1330, __pyx_L1_error) + + /* "View.MemoryView":1326 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ + } + + /* "View.MemoryView":1332 + * 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":1333 + * + * 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":1334 + * 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":1336 + * refcount_copying(&dst, dtype_is_object, ndim, True) + * + * free(tmpdata) # <<<<<<<<<<<<<< + * return 0 + * + */ + free(__pyx_v_tmpdata); + + /* "View.MemoryView":1337 + * + * free(tmpdata) + * return 0 # <<<<<<<<<<<<<< + * + * @cname('__pyx_memoryview_broadcast_leading') + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "View.MemoryView":1268 + * + * @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":1340 + * + * @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":1344 + * 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":1346 + * 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":1347 + * + * 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":1348 + * 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":1349 + * 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":1351 + * 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":1352 + * + * 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":1353 + * 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":1354 + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] + * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + * + * + */ + (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; + } + + /* "View.MemoryView":1340 + * + * @cname('__pyx_memoryview_broadcast_leading') + * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< + * int ndim, + * int ndim_other) nogil: + */ + + /* function exit code */ +} + +/* "View.MemoryView":1362 + * + * @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":1366 + * + * + * 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":1367 + * + * 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":1366 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ + } + + /* "View.MemoryView":1362 + * + * @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":1371 + * + * @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":1374 + * 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":1371 + * + * @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":1377 + * + * @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":1381 + * 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":1382 + * + * 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":1383 + * 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":1384 + * if ndim == 1: + * if inc: + * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< + * else: + * Py_DECREF(( data)[0]) + */ + Py_INCREF((((PyObject **)__pyx_v_data)[0])); + + /* "View.MemoryView":1383 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< + * Py_INCREF(( data)[0]) + * else: + */ + goto __pyx_L6; + } + + /* "View.MemoryView":1386 + * 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":1382 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ + goto __pyx_L5; + } + + /* "View.MemoryView":1388 + * Py_DECREF(( data)[0]) + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< + * ndim - 1, inc) + * + */ + /*else*/ { + + /* "View.MemoryView":1389 + * 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":1391 + * ndim - 1, inc) + * + * data += strides[0] # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); + } + + /* "View.MemoryView":1377 + * + * @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":1397 + * + * @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":1400 + * 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":1401 + * 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":1403 + * _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":1397 + * + * @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":1407 + * + * @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":1411 + * 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":1412 + * 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":1414 + * 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":1415 + * + * 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":1416 + * 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":1417 + * 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":1414 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ + goto __pyx_L3; + } + + /* "View.MemoryView":1419 + * 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":1420 + * 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":1422 + * _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":1407 + * + * @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; + 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(1, 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(1, 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(1, 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(1, 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(1, 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 + 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_t_6; + __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); + + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result + * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + */ + __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xb068931) != 0); + if (__pyx_t_1) { + + /* "(tree fragment)":5 + * cdef object __pyx_result + * if __pyx_checksum != 0xb068931: + * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_PickleError); + __Pyx_GIVEREF(__pyx_n_s_PickleError); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_2); + __pyx_v___pyx_PickleError = __pyx_t_2; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "(tree fragment)":6 + * if __pyx_checksum != 0xb068931: + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: + */ + __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_INCREF(__pyx_v___pyx_PickleError); + __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(1, 6, __pyx_L1_error) + + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result + * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + */ + } + + /* "(tree fragment)":7 + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (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_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = NULL; + if (CYTHON_UNPACK_METHODS && likely(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_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v___pyx_result = __pyx_t_3; + __pyx_t_3 = 0; + + /* "(tree fragment)":8 + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (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_1 = (__pyx_v___pyx_state != Py_None); + __pyx_t_6 = (__pyx_t_1 != 0); + if (__pyx_t_6) { + + /* "(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)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 9, __pyx_L1_error) + __pyx_t_3 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "(tree fragment)":8 + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (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_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __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; + __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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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(1, 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); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + --Py_REFCNT(o); + 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) + "openmmtools.multistate.mixing._mix_replicas.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 + 0, /*tp_vectorcall*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 + 0, /*tp_print*/ + #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) + "openmmtools.multistate.mixing._mix_replicas.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 + 0, /*tp_vectorcall*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 + 0, /*tp_print*/ + #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); + ++Py_REFCNT(o); + __pyx_memoryview___dealloc__(o); + --Py_REFCNT(o); + 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) + "openmmtools.multistate.mixing._mix_replicas.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 + 0, /*tp_vectorcall*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 + 0, /*tp_print*/ + #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); + ++Py_REFCNT(o); + __pyx_memoryviewslice___dealloc__(o); + --Py_REFCNT(o); + 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) + "openmmtools.multistate.mixing._mix_replicas._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 + 0, /*tp_vectorcall*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 + 0, /*tp_print*/ + #endif +}; + +static PyMethodDef __pyx_methods[] = { + {"_mix_replicas_cython", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_11openmmtools_10multistate_6mixing_13_mix_replicas_1_mix_replicas_cython, METH_VARARGS|METH_KEYWORDS, 0}, + {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__mix_replicas(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec__mix_replicas}, + {0, NULL} +}; +#endif + +static struct PyModuleDef __pyx_moduledef = { + PyModuleDef_HEAD_INIT, + "_mix_replicas", + 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_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_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_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_k_Incompatible_checksums_s_vs_0xb0, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xb0), 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_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_s_Nij_accepted, __pyx_k_Nij_accepted, sizeof(__pyx_k_Nij_accepted), 0, 0, 1, 1}, + {&__pyx_n_s_Nij_proposed, __pyx_k_Nij_proposed, sizeof(__pyx_k_Nij_proposed), 0, 0, 1, 1}, + {&__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_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_base, __pyx_k_base, sizeof(__pyx_k_base), 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_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_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 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_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 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_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_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 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_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 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_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_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_nstates, __pyx_k_nstates, sizeof(__pyx_k_nstates), 0, 0, 1, 1}, + {&__pyx_n_s_nswap_attempts, __pyx_k_nswap_attempts, sizeof(__pyx_k_nswap_attempts), 0, 0, 1, 1}, + {&__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_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 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_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_replica_states, __pyx_k_replica_states, sizeof(__pyx_k_replica_states), 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_u_kl, __pyx_k_u_kl, sizeof(__pyx_k_u_kl), 0, 0, 1, 1}, + {&__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}, + {0, 0, 0, 0, 0, 0, 0} +}; +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 133, __pyx_L1_error) + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 148, __pyx_L1_error) + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(1, 151, __pyx_L1_error) + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(1, 404, __pyx_L1_error) + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(1, 613, __pyx_L1_error) + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(1, 832, __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); + + /* "View.MemoryView":133 + * + * if not self.ndim: + * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< + * + * if itemsize <= 0: + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "View.MemoryView":136 + * + * if itemsize <= 0: + * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< + * + * if not isinstance(format, bytes): + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 136, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "View.MemoryView":148 + * + * if not self._shape: + * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__3); + __Pyx_GIVEREF(__pyx_tuple__3); + + /* "View.MemoryView":176 + * self.data = malloc(self.len) + * if not self.data: + * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< + * + * if self.dtype_is_object: + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 176, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "View.MemoryView":192 + * 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__5 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 192, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__5); + __Pyx_GIVEREF(__pyx_tuple__5); + + /* "(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__6 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + + /* "(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__7 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "View.MemoryView":418 + * 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__8 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 418, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + + /* "View.MemoryView":495 + * 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__9 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 495, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__9); + __Pyx_GIVEREF(__pyx_tuple__9); + + /* "View.MemoryView":520 + * 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__10 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 520, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + + /* "View.MemoryView":570 + * 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__11 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 570, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + + /* "View.MemoryView":577 + * 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__12 = PyTuple_New(1); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 577, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_INCREF(__pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_tuple__12, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_tuple__12); + + /* "(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__13 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + + /* "(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__14 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + + /* "View.MemoryView":682 + * if item is Ellipsis: + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< + * seen_ellipsis = True + * else: + */ + __pyx_slice__15 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__15)) __PYX_ERR(1, 682, __pyx_L1_error) + __Pyx_GOTREF(__pyx_slice__15); + __Pyx_GIVEREF(__pyx_slice__15); + + /* "View.MemoryView":703 + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: + * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(1, 703, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + + /* "(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__17 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__17); + __Pyx_GIVEREF(__pyx_tuple__17); + + /* "(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__18 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__18); + __Pyx_GIVEREF(__pyx_tuple__18); + + /* "View.MemoryView":286 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(1, 286, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + + /* "View.MemoryView":287 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(1, 287, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__20); + __Pyx_GIVEREF(__pyx_tuple__20); + + /* "View.MemoryView":288 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(1, 288, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); + + /* "View.MemoryView":291 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(1, 291, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__22); + __Pyx_GIVEREF(__pyx_tuple__22); + + /* "View.MemoryView":292 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_tuple__23 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(1, 292, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__23); + __Pyx_GIVEREF(__pyx_tuple__23); + + /* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result + */ + __pyx_tuple__24 = 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__24)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 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_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) __PYX_ERR(1, 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_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_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 + __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(1, 105, __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(1, 105, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) + __pyx_array_type = &__pyx_type___pyx_array; + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __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(1, 279, __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(1, 330, __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(1, 330, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 330, __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(1, 965, __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(1, 965, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __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 + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +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; +} + + +#if PY_MAJOR_VERSION < 3 +#ifdef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC void +#else +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#endif +#else +#ifdef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC PyObject * +#else +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#endif +#endif + + +#if PY_MAJOR_VERSION < 3 +__Pyx_PyMODINIT_FUNC init_mix_replicas(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC init_mix_replicas(void) +#else +__Pyx_PyMODINIT_FUNC PyInit__mix_replicas(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit__mix_replicas(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__mix_replicas(PyObject *__pyx_pyinit_module) +#endif +#endif +{ + PyObject *__pyx_t_1 = NULL; + static PyThread_type_lock __pyx_t_2[8]; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module '_mix_replicas' 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__mix_replicas(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(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #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("_mix_replicas", __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_openmmtools__multistate__mixing___mix_replicas) { + 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, "openmmtools.multistate.mixing._mix_replicas")) { + if (unlikely(PyDict_SetItemString(modules, "openmmtools.multistate.mixing._mix_replicas", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #endif + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins() < 0) goto __pyx_L1_error; + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants() < 0) goto __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)) goto __pyx_L1_error; + (void)__Pyx_modinit_type_import_code(); + (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 + + /* "openmmtools/multistate/mixing/_mix_replicas.pyx":1 + * cimport cython # <<<<<<<<<<<<<< + * from libc.math cimport exp, isnan + * from libc.stdio cimport printf + */ + __pyx_t_1 = __Pyx_PyDict_NewPresized(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_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "View.MemoryView":209 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * def __dealloc__(array self): + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 209, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 209, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_array_type); + + /* "View.MemoryView":286 + * return self.name + * + * cdef generic = Enum("") # <<<<<<<<<<<<<< + * cdef strided = Enum("") # default + * cdef indirect = Enum("") + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 286, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(generic); + __Pyx_DECREF_SET(generic, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":287 + * + * cdef generic = Enum("") + * cdef strided = Enum("") # default # <<<<<<<<<<<<<< + * cdef indirect = Enum("") + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 287, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(strided); + __Pyx_DECREF_SET(strided, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":288 + * cdef generic = Enum("") + * cdef strided = Enum("") # default + * cdef indirect = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 288, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect); + __Pyx_DECREF_SET(indirect, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":291 + * + * + * cdef contiguous = Enum("") # <<<<<<<<<<<<<< + * cdef indirect_contiguous = Enum("") + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 291, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(contiguous); + __Pyx_DECREF_SET(contiguous, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":292 + * + * cdef contiguous = Enum("") + * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 292, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XGOTREF(indirect_contiguous); + __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __pyx_t_1 = 0; + + /* "View.MemoryView":316 + * + * 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":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(), + * PyThread_allocate_lock(), + */ + __pyx_t_2[0] = PyThread_allocate_lock(); + __pyx_t_2[1] = PyThread_allocate_lock(); + __pyx_t_2[2] = PyThread_allocate_lock(); + __pyx_t_2[3] = PyThread_allocate_lock(); + __pyx_t_2[4] = PyThread_allocate_lock(); + __pyx_t_2[5] = PyThread_allocate_lock(); + __pyx_t_2[6] = PyThread_allocate_lock(); + __pyx_t_2[7] = PyThread_allocate_lock(); + memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_2, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); + + /* "View.MemoryView":549 + * info.obj = self + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 549, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 549, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + PyType_Modified(__pyx_memoryview_type); + + /* "View.MemoryView":995 + * return self.from_object + * + * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 995, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 995, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 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_1 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_1) < 0) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 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); + if (__pyx_m) { + if (__pyx_d) { + __Pyx_AddTraceback("init openmmtools.multistate.mixing._mix_replicas", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + Py_CLEAR(__pyx_m); + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init openmmtools.multistate.mixing._mix_replicas"); + } + __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; +} + +/* 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_CheckExact(key)) || 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 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(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 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(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; +} + +/* None */ +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +/* 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 (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]; +#ifdef 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 (!memview || (PyObject *) memview == Py_None) + return; + if (__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 (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 (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; + } + if (__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 (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; + } +} + +/* 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; +} + +/* PyObjectCall */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = func->ob_type->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 + +/* 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_COMPILING_IN_PYPY + 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); +#else + 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); + } +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} +#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 + +/* 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 + +/* 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; +} + +/* 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 + +/* 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 (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { + 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 + +/* 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_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 +} + +/* None */ +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); +} + +/* 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; + 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 + +/* 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; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/* 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 + +/* 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); +} + +/* 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); +} + +/* 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"); +} + +/* RaiseNoneIterError */ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +/* 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; +} + +/* 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 + +/* 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; +} + +/* 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 (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= 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 + +/* None */ +static CYTHON_INLINE long __Pyx_div_long(long a, long b) { + long q = a / b; + long r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +/* HasAttr */ +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!__Pyx_PyBaseString_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_GetAttr(o, n); + if (unlikely(!r)) { + PyErr_Clear(); + return 0; + } else { + Py_DECREF(r); + return 1; + } +} + +/* PyObject_GenericGetAttrNoDict */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { + PyErr_Format(PyExc_AttributeError, +#if PY_MAJOR_VERSION >= 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; +} + +/* 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_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; +#else + if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; +#endif +#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_GetAttrStr(type_obj, __pyx_n_s_reduce_cython); if (unlikely(!reduce_cython)) goto __PYX_BAD; + 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; + 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_GetAttrStr(type_obj, __pyx_n_s_setstate_cython); if (unlikely(!setstate_cython)) goto __PYX_BAD; + 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; + } + 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); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* CLineInTraceback */ +#ifndef CYTHON_CLINE_IN_TRACEBACK +static int __Pyx_CLineForTraceback(CYTHON_NCP_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; + 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" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + 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); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + 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; + 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) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __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); +} + +#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; +} + +/* 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;\ + } + +/* 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; + int ndim = ctx->head->field->type->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; + 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->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 (buf->strides[dim] != sizeof(void *)) { + PyErr_Format(PyExc_ValueError, + "Buffer is not indirectly contiguous " + "in dimension %d.", dim); + goto fail; + } + } else if (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 (stride < buf->itemsize) { + PyErr_SetString(PyExc_ValueError, + "Buffer and memoryview are not contiguous " + "in the same dimension."); + goto fail; + } + } + } else { + if (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 (spec & (__Pyx_MEMVIEW_PTR)) { + PyErr_Format(PyExc_ValueError, + "C-contiguous buffer is not indirect in " + "dimension %d", dim); + goto fail; + } else if (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 (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 (!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 (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 (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 (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 (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; + } + if ((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; + } + for (i = 0; i < ndim; i++) { + spec = axes_specs[i]; + if (!__pyx_check_strides(buf, i, ndim, spec)) + goto fail; + if (!__pyx_check_suboffsets(buf, i, ndim, spec)) + goto fail; + } + if (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_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; +} + +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_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), (__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_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_dsds_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), (__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_long, stack, + &result, obj); + if (unlikely(retcode == -1)) + goto __pyx_fail; + return result; +__pyx_fail: + result.memview = NULL; + result.data = NULL; + return result; +} + +/* CIntToPy */ + static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; + 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); + } +} + +/* 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 (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) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; + 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 + 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) { + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; + 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 + 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) { + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; + 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); + } +} + +/* CIntFromPy */ + static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { + const char neg_one = (char) ((char) 0 - (char) 1), const_zero = (char) 0; + 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 + 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[4], rtversion[4]; + PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); + PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); + if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { + char message[200]; + 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 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 */ From 442fab25b3b1cd3cfca65ace778d024f83218fa4 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Tue, 14 Apr 2020 23:52:40 -0700 Subject: [PATCH 146/152] Remove unused Jupyter --- .../troubleshoot_loopy_customintegrator.ipynb | 253 ------------------ 1 file changed, 253 deletions(-) delete mode 100644 examples/neq_customintegrator/troubleshoot_loopy_customintegrator.ipynb diff --git a/examples/neq_customintegrator/troubleshoot_loopy_customintegrator.ipynb b/examples/neq_customintegrator/troubleshoot_loopy_customintegrator.ipynb deleted file mode 100644 index 8d7bbf7fc..000000000 --- a/examples/neq_customintegrator/troubleshoot_loopy_customintegrator.ipynb +++ /dev/null @@ -1,253 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Attempt to build an `simtk.openmm.CustomIntegrator` for nonequilibrium switching" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "from openmmtools.integrators import AlchemicalNonequilibriumLangevinIntegrator\n", - "from simtk import unit\n", - "import numpy as np\n", - "import simtk.openmm as openmm\n", - "from openmmtools.constants import kB\n", - "from openmmtools import utils\n", - "_OPENMM_ENERGY_UNIT = unit.kilojoules_per_mole\n", - "from pkg_resources import resource_filename\n", - "from openmmtools.integrators import LoopyAlchemicalNonequilibriumLangevinIntegrator" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "from openmmtools.states import SamplerState, ThermodynamicState, CompoundThermodynamicState\n", - "from perses.annihilation.lambda_protocol import RelativeAlchemicalState\n", - "from perses.dispersed.feptasks import minimize\n", - "import pickle\n", - "from openmmtools import cache\n", - "\n", - "\n", - "\n", - "def test_loopy_customintegrator(htf,\n", - " alchemical_functions,\n", - " number_of_applications = 10,\n", - " neq_steps = 100,\n", - " eq_steps = 1000,\n", - " integrator_kwargs = {'temperature': 300.0 * unit.kelvin,\n", - " 'collision_rate': 1.0 / unit.picoseconds,\n", - " 'timestep': 2.0 * unit.femtoseconds,\n", - " 'constraint_tolerance': 1e-6,\n", - " 'measure_shadow_work': False,\n", - " 'measure_heat': False},\n", - " pressure = None\n", - " ):\n", - " \"\"\"\n", - " simple test to see if i can anneal benzene --> fluorobenzene with the loopy integrator\n", - " \"\"\"\n", - " \n", - " thermostate = ThermodynamicState(system = htf.hybrid_system, temperature = integrator_kwargs['temperature'], pressure = pressure)\n", - " alchemical_thermostate = CompoundThermodynamicState(thermostate, [RelativeAlchemicalState.from_system(htf.hybrid_system)])\n", - " sampler_state = SamplerState(positions = htf._hybrid_positions, box_vectors = np.array(htf.hybrid_system.getDefaultPeriodicBoxVectors()))\n", - " minimize(thermostate, sampler_state)\n", - " integrator = LoopyAlchemicalNonequilibriumLangevinIntegrator(alchemical_functions = alchemical_functions,\n", - " nsteps_eq = eq_steps,\n", - " nsteps_neq = neq_steps,\n", - " **integrator_kwargs)\n", - " context, integrator = cache.global_context_cache.get_context(alchemical_thermostate, integrator)\n", - " sampler_state.apply_to_context(context)\n", - " context.setVelocitiesToTemperature(thermostate.temperature)\n", - " return integrator, context" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "x = 'lambda'\n", - "alchemical_functions = {\n", - " 'lambda_sterics_core': x,\n", - " 'lambda_electrostatics_core': x,\n", - " 'lambda_sterics_insert': f\"select(step({x} - 0.5), 1.0, 2.0 * {x})\",\n", - " 'lambda_sterics_delete': f\"select(step({x} - 0.5), 2.0 * ({x} - 0.5), 0.0)\",\n", - " 'lambda_electrostatics_insert': f\"select(step({x} - 0.5), 2.0 * ({x} - 0.5), 0.0)\",\n", - " 'lambda_electrostatics_delete': f\"select(step({x} - 0.5), 1.0, 2.0 * {x})\",\n", - " 'lambda_bonds': x,\n", - " 'lambda_angles': x,\n", - " 'lambda_torsions': x}\n", - "\n", - "htf_filename = resource_filename('coddiwomple', f\"/data/perses_data/benzene_fluorobenzene.solvent.factory.pkl\")\n", - "with open(htf_filename, 'rb') as f:\n", - " htf = pickle.load(f)\n", - "integrator, context = test_loopy_customintegrator(htf = htf,\n", - " alchemical_functions = alchemical_functions, pressure = 1. * unit.atmosphere)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "running 1 trial\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "100%|██████████| 50/50 [08:11<00:00, 9.82s/it]\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "running 50 trial\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "100%|██████████| 50/50 [09:01<00:00, 10.83s/it]\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "running 100 trial\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "100%|██████████| 50/50 [09:47<00:00, 11.75s/it]\n" - ] - } - ], - "source": [ - "import tqdm\n", - "forward_works = {}\n", - "backward_works = {}\n", - "for annealing_steps in [1, 50, 100]:\n", - " print(f\"running {annealing_steps} trial\")\n", - " integrator, context = test_loopy_customintegrator(htf = htf,\n", - " alchemical_functions = alchemical_functions,\n", - " neq_steps = annealing_steps)\n", - " forward, backward = [], []\n", - " for _ in tqdm.trange(50):\n", - " integrator.step(1)\n", - " num_global_vars = integrator.getNumGlobalVariables()\n", - " global_integrator_variables = {integrator.getGlobalVariableName(idx): integrator.getGlobalVariable(idx) for idx in range(num_global_vars)}\n", - " forward.append(global_integrator_variables['forward_work'])\n", - " backward.append(global_integrator_variables['backward_work'])\n", - " forward_works[annealing_steps] = forward\n", - " backward_works[annealing_steps] = backward" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "DEBUG:matplotlib.pyplot:Loaded backend module://ipykernel.pylab.backend_inline version unknown.\n" - ] - } - ], - "source": [ - "%matplotlib inline\n", - "\n", - "import matplotlib\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import seaborn" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Text(0, 0.5, 'frequency')" - ] - }, - "execution_count": 17, - "metadata": {}, - "output_type": "execute_result" - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYgAAAEWCAYAAAB8LwAVAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjMsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+AADFEAAAgAElEQVR4nOydeVxVZf743x/gAgqIIiIgKjDuCyLiUppDmUtaWk1TmZZmi9k6TYtOM22WLd/p1zSW1WTaMlpZWU2NljalmVZuaRaKYoqKIig7isK9PL8/zrm3C1zgAvcC6vN+vc7rcs6zfc7C+ZzP53mezyNKKTQajUajqYpPcwug0Wg0mpaJVhAajUajcYlWEBqNRqNxiVYQGo1Go3GJVhAajUajcYlWEBqNRqNxiVYQHkBEMkTk4uaW40xDRK4QkUMiUiIiA5vrOorIdBFZ39TttmRE5E0RebK55WipOD+rIvKQiLze3DJ5A7/mFkBzTvMccKdS6j8AItLM4miaEhGJBfYDFqWUtXmlaThKqaeaWwZvoS0ITaMRkY4NLNoVSPWkLK4QEV9vt6HRnI1oBeE5BovIThHJF5E3RCTQniAil4rIdhEpEJHvRCTBKS1DRO4XkR0iUigiy+xlReQz0/1i3ypEZLqZ1ktEvhSRPBHZLSJXO9X5pogsEJEVIlIsIhtF5HdO6TWWbSBrRORrEZkqIq3ryiwiASJSAvgCP4nIry7yVHJxiEiKiGQ67fcWkbXmNU0VkYlVyr4iIitF5ARwoYiEisjbInJMRA6IyN9ExKdyk/KieQ/SRGSUU0KoiCwSkSwROSwiT9qVjt09JSLPmfd+v4hcYqadV+X+nRKRDDPNR0TmiMivIpIrIu+LSJiZFisiSkSmichBETkuIn91kqfGsi6uY7iI/Ne8Tnki8q39vGu7hlXq2CUilzrt+5kyJZn7w8znukBEfhKRFKe8a0XkCRHZYD6Lq0Uk3ExeZ/4WmNfnPBdtDxGR7826s0TkJRHxd0pXInKbiKSb13+BiGGK1nZv3LivvzOf6VzzXJeKSNsars9jIrLEzXvXSkTeMuXZJSIPitNz3eJQSumtkRuQAfwCdAbCgA3Ak2ZaEpADDMV4IU4z8wc4ld0ERJtldwG3uWhjHHDEbCMIOATciOEmTAKOA33NvG8CecAQM30p8J6ZVmvZBp5/a2Aq8CWQD7wGnOdGOQV0q3IdL3Y6hyed0lKATPNvC7AXeAjwBy4CioGeTmULgeEYH0GBwNvAf4AQIBbYA9xk5p8OWIF7zbqvMcuHmemfAP8yr12Eeb9mOpUtB24x7+8s8z5JlXO1AGuBp839PwE/ADFAgFn/u2ZarHltFgKtgAHAaaB3XWVdXOOngVfN9i3ABYC4eQ3tz/AjwFKnOicAaebfnYBcYLx5rUeb+x3M9LXAr0AP81zWAs9UOU+/Wp6RQcAwjGc1FuP/409VnqH/Am2BLsAxYJw796aO+9rNPJcAoAOGMnuhhmf1MWCJm/fuGeAboJ15/3ZgPtctcWt2Ac6GzXxYbnPaHw/8av79CvBElfy7gd87lZ3qlPZ/wKtV8vfAUDIXmPvXAN9WyfMv4FHz7zeB16vIk+ZOWQ9ci84YL53dQBpwdS15G6ogLgCOAj5O6e8CjzmVfdspzdf8J+3jdGwmsNb8ezpVXurmy+J6oKNZtpVT2mRgjVPZvU5prc3ziqxyrq8AK+wyY7zoRjmlR2G8zOwvQgXEVJHn2rrKurjGczEUY7cqx925hnYF0Q1DebQ295cCj5h/zwb+XaXuVcA08++1wN+c0m4HvjD/tp9njQrCxfn8Cfi4yjM0wmn/fWBOXfemrvvqot3LgW01PKuPUV1B1HTv9gFjndJupgUrCN1J7TkOOf19AMMiAMPPPk1E7nJK93dKB+Mf1c5J5zQRCcX4B39YKfWtU51DRaTAqZwf8O9a6gyuR1l72xcAn9vPSSnVV0RSzToALnGSyU4W8JO5XYLxleRpooFDSqkKp2MHML5m7Tjfj3CMa36glvyHlfkf65QejXGuFiBLfutE96lSv+NaK6VOmvns1xsRmYmh4IY5ydwV+FhEnM/BhvHiqlYv1e9hTWUPU5m/Y7zAVptyvaaUegb3rqH9nPaKyC7gMhH5DJgIDHSS5Y8icplTEQuwxo3zqBMR6QE8DyRjvOD9gK1VstVWf033Joxa7quIRADzMRRpiJmW767ctcgUTeVnx/nvFodWEJ6js9PfXTC+SMF4AOYppebVt0LTV/wOxlfNv5ySDgHfKKVGN0BOt8uaL//gKsf61iDrQOAGjK+wfcAbwM1KqaIGyAhwAuOFYCfS6e8jQGcR8XF6wXXBcBs5RHX6+zjGF3ZXYKdTfueXaScREScl0QX4FON6nQbCVQNG2phK9gmMr9xCp6RDwAyl1AYXZWLrqLbGslVRShUD9wH3iUhfjP6izbh3DZ15F+Pe+gA7lVJ7nWT5t1LqlrpkcSWeG3leAbYBk5VSxSLyJ+CqBrRVlbru69OmfAlKqVwRuRx4yQPtZmF8NNmfw8615G12dCe157hDRGLMzsKHgGXm8YXAbSIyVAyCRGSCiIS4Uec8DP/oPVWO/xfoISLXi4jF3AaLSG836mxMWZeIyNfAZ8ApYKRS6nyl1MJGKAeA7cB4EQkTkUgM14KdjRgK5EFT/hTgMuA9VxUppWwYrod5IhIiIl2BPwNLnLJFAHeb9f0R6A2sVEplAauB/ycibcToIP6diPy+rhMQkc4Yz8ENSqmqL95XTXm6mnk7iMikuuqsb1kxBkh0MztuizAsDRv1vIbm8TEYfvx3nI4vwbAsxoqIr4gEijGgwB3L8RhQAcTXkifElLtERHqZ7TcaN+5rCFCC0YHeCXjAE+1iPId/EZF2Zr13eqher6AVhOd4B+OB22duTwIopbZgdJK9hGGi7sXwjbrDZIwOunz5bSTMFPOrcAxwLcaX4FHgWYwOtVppTNla+CvQRSn1Fxcvwobybww3VQbGdbUrXJRSZRhujkswrIOXMV7CabXUdxfGC3EfsB7jfi12St8IdDfrmwdcpZTKNdNuwHBR7cS4hx9i+P3rYhSG5fOh0/2zD+v9J4aFslpEijE6nYe6UWd9y3YH/ofxsvseeFkptba+19B8oX4PnE/le3EImITxUXQM48v8Adx4tyilTmJc6w1ijFIa5iLb/cB1GH0gC53b9gC13dfHMQZwFGL0HX3koTbnApkY8z/+Z7Z52kN1exx7b75Go9FomhgRmYXRgV2nRdocaAtCo9FomggRiRKR4aZLqydG/9DHzS1XTehOao1Go2k6/DGGlccBBRh9Oy83q0S1oF1MGo1Go3GJdjFpNBqNxiVnlYspPDxcxcbGNrcYGo1Gc8awdevW40qpDq7SzioFERsby5YtW5pbDI1GozljEJEDNaVpF5NGo9FoXKIVhEaj0WhcohWERqPRaFxyVvVBaDRnGuXl5WRmZnLq1KnmFkVzlhMYGEhMTAwWi8XtMlpBaDTNSGZmJiEhIcTGxuo1uTVeQylFbm4umZmZxMXFuV1Ou5g0mmbk1KlTtG/fXisHjVcREdq3b19vS1UrCI2mmdHKQdMUNOQ50wriTKDC1twSaDSacxCtIFoyNiu8cy08GQGbFja3NBpNraSlpXHeeecREBDAc88919ziuCQlJcUxmXb8+PEUFBTUUaLhPPXUU16ru6nQCqIls/UN2PM5+AfBF3Og+GjdZTQaD5Kf7/4yzGFhYcyfP5/777/fixJ5jpUrV9K2bVuv1a8VhMZ7KAUb/wWdBsHNX0OFFba/U3c5jcaD3HXXXVx44YUsXbq0zg7OiIgIBg8eXOcwylmzZpGcnEzfvn159NFHHcdjY2N59NFHSUpKon///qSlGYvbPfbYY8yYMYOUlBTi4+OZP3++o8ySJUsYMmQIiYmJzJw5E5vNVmsbzsTGxnL8+HEyMjLo3bs3t9xyC3379mXMmDGUlpYCsHnzZhISEjjvvPN44IEH6NevX7V6srKyGDlyJImJifTr149vv/2WOXPmUFpaSmJiIlOmTKlV1uDgYO677z6SkpIYNWoUx44dA2D+/Pn06dOHhIQErr322lqvqbfQw1xbKtmpkJsOl/0TwrtBdBLs+QIu+HNzS6bxEo9/lsrOI41Zxrs6faLb8OhlfRtcfsmSJWzdupXFixfzyCOPMH78eG6++WYGDBjQ4DrnzZtHWFgYNpuNUaNGsWPHDhISEgAIDw/nxx9/5OWXX+a5557j9ddfBwz31Zo1ayguLqZnz57MmjWLvXv3smzZMjZs2IDFYuH2229n6dKl3HDDDbW24Yr09HTeffddFi5cyNVXX83y5cuZOnUqN954I6+99hrnn38+c+bMcVn2nXfeYezYsfz1r3/FZrNx8uRJLrjgAl566SW2b98OwK5du2qU9cSJEyQlJfH//t//Y+7cuTz++OO89NJLPPPMM+zfv5+AgACvusJqw6sWhIiME5HdIrJXRKpdXTGYb6bvEJEkp7S2IvKhiKSJyC4ROc+bsrY49nxh/PYYZ/zGjYTDW6HsRPPJpDknGTRoEAsWLCA1NZVu3boxZMgQnn/++QbX9/7775OUlMTAgQNJTU1l586djrQrr7zS0WZGRobj+IQJEwgICCA8PJyIiAiys7P56quv2Lp1K4MHDyYxMZGvvvqKffv21dmGK+Li4khMTKzUdkFBAcXFxZx//vkAXHfddS7LDh48mDfeeIPHHnuMn3/+mZCQkGp5apPVx8eHa665BoCpU6eyfv16ABISEpgyZQpLlizBz695vuW91qqI+AILgNEYi3RvFpFPlVLOd+oSjEXVu2Msuv4Kvy2+/k/gC6XUVSLiD7T2lqwtkgMbIKIvhEQa+7EXwIYXIHMzxKc0p2QaL9GYL/2GsmDBAhYuNAZArFy5khtvvJHs7GySk5MdX+9Wq5WVK1fyxhtvkJ6ezty5c5k6dWqD2tu/fz/PPfccmzdvpl27dkyfPr2S6yogIAAAX19frFZrtePOaUoppk2bxtNPP12vNlxRtf7S0lLcXUxt5MiRrFu3jhUrVnD99dfzwAMPcMMNN1TKU5OsrrAPR12xYgXr1q3j008/5YknniA1NbXJFYU3LYghwF6l1D6lVBnG0nqTquSZBLytDH4A2pprtrYBRgKLAJRSZUqp5rGxmgOlDGshJvm3Y9HG1w1Hf24emTRnJXfccQfbt29n+/btREdHs2rVKrZv3+5QDs8//zw9evRg+fLl3Hvvvfzyyy/Mnj2biIiIBrVXVFREUFAQoaGhZGdn8/nnnzdY9lGjRvHhhx+Sk5MDQF5eHgcOHPBYG+3atSMkJIQffvgBgPfee89lvgMHDhAREcEtt9zCTTfdxI8//giAxWKhvLy8VlkBKioq+PDDDwHDXTVixAgqKio4dOgQF154If/3f/9HQUEBJSUlDTqPxuBNddQJOOS0n8lv1kFteToBVuAY8IaIDAC2Avcopar5V0TkVuBWgC5dunhM+GYlbx+cKjQ6qO0EhUNIFBz9pfnk0pxzJCQksH37dtq0aVNn3qNHj5KcnExRURE+Pj688MIL7Ny5s1LZAQMGMHDgQPr27Ut8fDzDhw9vsGx9+vThySefZMyYMVRUVGCxWFiwYAHDhg3zWBuLFi3illtuISgoiJSUFEJDQ6vlWbt2LX//+9+xWCwEBwfz9ttvA3DrrbeSkJBAUlISS5cudSlr165dCQoKIjU1lUGDBhEaGsqyZcuw2WxMnTqVwsJClFLce++9Xh1xVRNeW5NaRP4IjFVK3WzuXw8MUUrd5ZRnBfC0Umq9uf8V8CAgwA/AcKXURhH5J1CklHq4tjaTk5PVWbFg0I734aNb4LYNEOk0amLJVVCcBbM2NJ9sGo+ya9cuevfu3dxiaGqgpKSE4OBgAJ555hmysrL45z//6dE2goODm8w6cPW8ichWpVSyq/zedDFlAp2d9mOAI27myQQylVIbzeMfAkmcKxzeCpbW0KFX5eMRveB4OlRUNI9cGs05xooVKyoNX/3b3/7W3CI1Kd50MW0GuotIHHAYuBaoOgzgU+BOEXkPw/1UqJTKAhCRQyLSUym1GxgF1D4M4Wzi8FaISgTfKrcn7HdgOw1FmdD2LHGnaTQtmGuuucYxwshbNEffgrt4TUEopawiciewCvAFFiulUkXkNjP9VWAlMB7YC5wEbnSq4i5gqTmCaV+VtLMXpSBnFyS6GFLX/nfGb+6vWkFoNBqv49UxU0qplRhKwPnYq05/K+COGspuB1z6xc5qirOgrATCe1RPCzMVRN6v8LsLm1YujUZzzqFDbbQ0ju8xfl0piDbR4BsA+RlNKpJGozk30QqipXE83fh1pSBEDCVReLhpZdJoNOckWkG0NI7vAf8QCIlEWa0cf+UVjj45D5s9FktoDBRpBaFpGaxbt46kpCT8/Pwck71aGvagfIAjbIY3KCgo4OWXX/Za/c2BVhAtjeN7ILw7iJC/dCnH/jmf/CVLODTrdpTNBm06aQtC43XKyso4caLuuF9dunThzTffrDFOUUvju+++81rdWkFovM/xdAjvgaqoIHfRYoLOP4/oZ5+hdNs2Cj76CEI7GR3ZepU5jRfYtWsX9913Hz179mTPnj115o+NjSUhIQEfn9pfJZdffjmDBg2ib9++vPbaa47jwcHB/PWvf2XAgAEMGzaM7OxsAKZPn87dd9/N+eefT3x8fCXr5O9//zuDBw8mISGhUijvmtpwxj7pbe3ataSkpHDVVVfRq1cvpkyZ4oi9tHLlSnr16sWIESO4++67ufTSS6vVk5qa6gjdnZCQQHp6OnPmzOHXX38lMTGRBx54oEZZMzIy6NWrF9OmTSMhIYGrrrqKkydPAjBnzhxHiO+WsK6GDvfdkjhdYriPwrtzKjUVa04OEff9mTYTJ5L/3jKOv/gSoU9NxkfZjMWDQjs1t8QaT/L5HM/H2orsD5c8U2uWEydO8P7777No0SKUUtx4443s2LHDZVTShrJ48WLCwsIoLS1l8ODB/OEPf6B9+/acOHGCYcOGMW/ePB588EEWLlzomIyWlZXF+vXrSUtLY+LEiVx11VWsXr2a9PR0Nm3ahFKKiRMnsm7dOkaOHFljGzWxbds2UlNTiY6OZvjw4WzYsIHk5GRmzpzJunXriIuLY/LkyS7Lvvrqq9xzzz1MmTKFsrIybDYbzzzzDL/88osjxHdNsnbp0oXdu3ezaNEihg8fzowZM3j55ZeZMWMGH3/8MWlpaYhIs4X4dkZbEC2JAiN4F2FxlHz7LYgQNHIkIkLEfX/GmpND3rpfjTy6H0LjIaKioli0aBGvv/46GzZs4Oabb/aocgBj8Ru7lXDo0CHS043BGP7+/o4v9Kohvi+//HJ8fHzo06ePw7JYvXo1q1evZuDAgSQlJZGWluaoq6Y2amLIkCHExMTg4+NDYmIiGRkZpKWlER8fT1xcHECNCuK8887jqaee4tlnn+XAgQO0atWqWp7aZO3cubMjRpQ9xHebNm0IDAzk5ptv5qOPPqJ16+YPYK0tiJZEvqkg2sZy6pev8Y+Lw69dOwBaJycTnJJC7vKvaTdG8C3MhM5DmlFYjcep40vfW3z44YcsWrSIK664gsmTJzNt2jS6du0KwMaNG5k5cyYAc+fOZePGjaxYsQLA8aVcF2vXruV///sf33//Pa1btyYlJcURfttisTjCW9cW4tvu/lFK8Ze//MUhkztt1ERNIcTd4brrrmPo0KGsWLGCsWPH8vrrrxMfH18pT02yZmRkOM7Zjojg5+fHpk2b+Oqrr3jvvfd46aWX+Prrr92Sx1toC6IlUXDQ+G3XlVOpqQT2rbw+QIc/30vFyVKO7wrRFoTGY4wZM4Zly5axfv16QkNDmTRpEhdffDEZGRkMHTrUEQ584sSJzJs3z7HvLoWFhbRr147WrVuTlpbmCJ/dEMaOHcvixYsd4SkOHz5MTk6Ox9ro1asX+/btc1gyy5Ytc5lv3759xMfHc/fddzNx4kSHS664uLhOWQEOHjzI999/D8C7777LiBEjKCkpobCwkPHjx/PCCy/U6xp7C21BtCQKDoClNdZSsGZnE9i3T6XkwB49CL18Enn/+ZjgrT8R5L0Re5pzkPbt23PPPfdwzz33sGnTJnx9fesss3nzZq644gry8/P57LPPePTRR0lNTa2UZ9y4cbz66qskJCTQs2dPhg0b1mAZx4wZw65duzjvPGOByeDgYJYsWeKxNlq1asXLL7/MuHHjCA8PZ8gQ11b6smXLWLJkCRaLhcjISB555BHCwsIYPnw4/fr145JLLuHvf/+7S1l9fX3p3bs3b731FjNnzqR79+7MmjWLwsJCJk2axKlTp1BK8Y9//KNhF8mDeC3cd3Nwxof7fm8K5O7lxOAXOXjDNDovep3gKrHsbYWFZIw9j/ISCJs+g7AZM/ALC2smgTWNRYf7bnnYQ3wrpbjjjjvo3r079957r8fqz8jI4NJLL+WXX5p+bZeWFO5bU18KDkDbrpSZ5q1/19hqWXxDQ+k6PZ6Q7oHkLlrM3lEXU2j6hDUaTeNZuHAhiYmJ9O3bl8LCwmp9COcSWkG0JPIPQtsulB04gPj7Y4mKdJnNr0MUnX5vJX7Ffwns24cjD86m9KefmlhYjebs5N5772X79u3s3LmTpUuXenw0UWxsbLNYDw1BK4iWQmkBnC40FETGASxdOiM1+YCDI6Akh4C4ODq/8gp+4eFkP/Ns08qr0WjOerSCaCnY50C060r5wYP4d+lac97gCLCWQlkJviEhtL/pJkq3baP0Zw9PstJoNOc0WkG0FOxDXEM7U56VhSU6uua8wR2N3xJjyFzoFZcjFgtFK1bWXEaj0WjqiVYQLQUzAJ/Ntx0VJSVYoqJqzhvUwfg1FYRvSAitzz+P4i+/dHuij0aj0dSFVhAtheIj4OtPecFpACzRtSgIhwWR/duh3/+e8sOHKc/M9KaUGk2NpKWlcd555xEQEMBzzz1XKe2LL76gZ8+edOvWjWee+W3GeF5eHqNHj6Z79+6MHj2a/Pz8pha7TuwB/o4cOcJVV13ltXYyMjJ45513vFZ/Q9AKoqVQdATaRFOelQVQuwURHGH8njjmOBQ0eDAAJzdt9pqImnOP+ryww8LCmD9/frUopDabjTvuuIPPP/+cnTt38u6777Jz504AnnnmGUaNGkV6ejqjRo2qpDxaGtHR0V5d80IrCE3NFB2BkN8UhF9ULX0QrduD+DhcTAD+3brh264dJ7du9bakmnOIu+66iwsvvJClS5fWGdsoIiKCwYMHY7FYKh3ftGkT3bp1Iz4+Hn9/f6699lr+85//APCf//yHadOmATBt2jQ++eSTavWWlJQwatQokpKS6N+/v6NsRkYGvXv35pZbbqFv376MGTOG0tJSAFJSUpg9ezZDhgyhR48efPvtt4ChrB544AFHCO5//etftbbhTEZGBv369QPgzTff5Morr2TcuHF0796dBx980JFv0aJF9OjRg5SUFG655RbuvPPOanV98803JCYmkpiYyMCBAykuLmbOnDl8++23JCYm8o9//KNGWdeuXcvIkSO54oor6NOnD7fddhsVFRXYbDamT59Ov3796N+/v0dmYutQGy2FosPQKRnr4WMggl94zWGK8fGF1uGVXEwiQmD/fpyqEuZAc+bw7KZnSctL82idvcJ6MXvI7AaXX7JkCVu3bmXx4sU88sgjjB8/nptvvpkBAwa4Xcfhw4fp3LmzYz8mJoaNGzcCkJ2dTZRpLUdFRTliFTkTGBjIxx9/TJs2bTh+/DjDhg1j4sSJAKSnp/Puu++ycOFCrr76apYvX87UqVMBsFqtbNq0iZUrV/L444/zv//9j0WLFhEaGsrmzZs5ffo0w4cPZ8yYMXTu3NllG1WD6jmzfft2tm3bRkBAAD179uSuu+7C19eXJ554gh9//JGQkBAuuugil9fqueeeY8GCBQwfPpySkhICAwN55plneO655/jvf/8LwGuvveZSVjCU7s6dO+natSvjxo3jo48+Ii4ujsOHDzvmWHgiXLi2IFoCSjlcTLa8fHzbtq15DoSd4I6VXEwAgX36cHrvXirq+NLTaOrDoEGDWLBgAampqXTr1o0hQ4bw/PPPu13e1cCJ2l68rso/9NBDJCQkcPHFF3P48GFH+O+4uDgSExMdcjqHC7/yyiurHV+9ejVvv/02iYmJDB06lNzcXNLT02ttoyZGjRpFaGgogYGB9OnThwMHDrBp0yZ+//vfExYWhsVi4Y9//KPLssOHD+fPf/4z8+fPp6CgAD+/6t/qNckKRqjy+Ph4fH19mTx5MuvXryc+Pp59+/Zx11138cUXX9CmTRu3r3FNaAuiJXAyF2xl0KYTtryd+LoTWym4QyULAjCiv9psnN69m1b1+MLTtAwa86XfUBYsWMDChQsBYyW1G2+8kezsbJKTk3n99dcB40t85cqVvPHGG6SnpzN37lzHV7o7xMTEcOjQIcd+ZmYm0eYw7o4dO5KVlUVUVBRZWVlERERUK7906VKOHTvG1q1bsVgsxMbGOtxdVUN2211MzmnOYcSVUrz44ouMHTu2UhtvvvlmjW3URGPChc+ZM4cJEyawcuVKhg0bxv/+979qeWqSde3atS7Dhbdr146ffvqJVatWsWDBAt5//30WL17sljw1oS2IloA9dHebaKx5ee4F3wvuCCVVLIiePQE4vfdXT0uoOUu54447HOG7o6OjWbVqFdu3b3coh+eff54ePXqwfPly7r33Xn755Rdmz57t8kVeE4MHDyY9PZ39+/dTVlbGe++953ARTZw4kbfeeguAt956i0mTJlUrX1hYSEREBBaLhTVr1nDgwIEGn+/YsWN55ZVXKC8vB2DPnj2cOHHCY20MGTKEb775hvz8fKxWK8uXL3eZ79dff6V///7Mnj2b5ORk0tLSXIYLdyUrGC6m/fv3U1FRwbJlyxgxYgTHjx+noqKCP/zhDw43V2PRFkRLoOiI8dumE7a8PAJ69Ki7TJBpQSgF5teEpVMnxGKhbP8+LwqrOZdISEhg+/btbrkrjh49SnJyMkVFRfj4+PDCCy+wc+dO2rRpw+I6tp4AACAASURBVEsvvcTYsWOx2WzMmDGDvuZaJ3PmzOHqq69m0aJFdOnShQ8++KBavVOmTOGyyy4jOTmZxMREevXq1eDzufnmm8nIyCApKQmlFB06dOCTTz7xWBudOnXioYceYujQoURHR9OnTx9CQ0Or5XvhhRdYs2YNvr6+9OnTh0suuQQfHx/8/PwYMGAA06dP55577nEpKxgr2s2ZM4eff/7Z0WH9888/c+ONN1JRUQHA008/3eDr5EAp5bUNGAfsBvYCc1ykCzDfTN8BJDmlZQA/A9uBLe60N2jQIHVGsmmhUo+2UarwiNo9ZKg68thjdZfZMN8oU1pY6fCvl16qDs663UuCajzNzp07m1sEjYcpLi5WSilVXl6uLr30UvXRRx95tP41a9aoCRMmNKisq+ettver11xMIuILLAAuAfoAk0WkT5VslwDdze1W4JUq6RcqpRJVDbHKzxqKjoD4ogLDsBUW4tfODReTfTZ1lY5q/9g4yvZpC0KjaS4ee+wxEhMT6devH3FxcVx++eXNLVKD8aaLaQiwVym1D0BE3gMmATud8kwC3ja12A8i0lZEopRSWV6Uq+VRlAUhkdiKDP+jW53UrcON35O50P53jsP+8fEUr1mDKi9HqoxH12g03qfqLHJPk5KSQkpKilfbsOPNTupOwCGn/UzzmLt5FLBaRLaKyK01NSIit4rIFhHZcuzYsZqytWxKsiG4I9a8PAD8wtrVXSbIVBBVLIiA+DiwWik7dMhFIY1Go3EfbyoIVwOdq44Bqy3PcKVUEoYb6g4RGemqEaXUa0qpZKVUcocOHRoubXNSkm1YEHlGWAO3LIiaXExxcQDazaTRaBqNNxVEJtDZaT8GOOJuHqWU/TcH+BjDZXV2UnwUgiOw5RsWhK9bfRCuLQi7gji9b79HRdRoNOce3lQQm4HuIhInIv7AtcCnVfJ8CtwgBsOAQqVUlogEiUgIgIgEAWOAM2ONvvpiK4eTxyE4sn4uJr8ACAiFE8crHfYNCcG3Qzhl+7WC0Gg0jcNrCkIpZQXuBFYBu4D3lVKpInKbiNxmZlsJ7MMY5roQuN083hFYLyI/AZuAFUqpL7wla7NitwBCOv7mYmrb1r2yQeHVLAgA/5jOlB8+7CkJNZoaWbduHUlJSfj5+VWLdPrWW2/RvXt3unfv7pgMB7B//36GDh1K9+7dueaaaygrK2tqsWvFOSjfli1buPvuu73W1vbt21m5suUu9OXVmdRKqZVKqR5Kqd8ppeaZx15VSr1q/q2UUneY6f2VUlvM4/uUUgPMra+97FlJ8VHjNzgSW34evqGh7o8+CurgUkFYOnXS60JoGkVZWZlj1m5tdOnShTfffJPrrruu0vG8vDwef/xxNm7cyKZNm3j88ccdocNnz57NvffeS3p6Ou3atWPRokVeOQdPkJyczPz5871W/zmtIDRuYI+nFNwRa16+ex3UdoLCq7mYACwxnSjPzkaZ8Wc0GnfZtWsX9913Hz179mTPnj115o+NjSUhIQEfn8qvklWrVjF69GjCwsJo164do0eP5osvvkApxddff+1YeKemEN8ZGRlccMEFJCUlkZSUxHfffQcYcYhSUlK46qqr6NWrF1OmTHHEP4qNjeXRRx91hOxOSzMi4544cYIZM2YwePBgBg4cWClcuKs2nFm7di2XXnopYMxvmDFjBikpKcTHx1dSHE888QS9evVi9OjRTJ482eVQ1w8++IB+/foxYMAARo4cSVlZGY888gjLli0jMTGRZcuW1Sjrm2++yaRJkxg3bhw9e/bk8ccfd5zbhAkTGDBgAP369WPZsmV13rP6oENtNDd2BRHSEVteXj0VRAc4tLHaYUunTmCzUX70KP4xMR4SVONtjj71FKd3eTbcd0DvXkQ+9FCteU6cOMH777/PokWLUEpx4403smPHDkJCQhrcrqsQ34cPHyY3N5e2bds6opfaj1clIiKCL7/8ksDAQNLT05k8eTJbtmwBYNu2baSmphIdHc3w4cPZsGEDI0aMACA8PJwff/yRl19+meeee47XX3+defPmcdFFF7F48WIKCgoYMmQIF198ca1t1ERaWhpr1qyhuLiYnj17MmvWLH766SeWL1/Otm3bsFqtJCUlMWjQoGpl586dy6pVq+jUqRMFBQX4+/szd+5ctmzZwksvvQTAQw895FJWMOIv/fLLL7Ru3ZrBgwczYcIEDhw4QHR0NCtWrACMuFWeRCuI5qbYVBBBxigm/9hY98sGdTAmylXYjDUiTOxKoTzzsFYQmjqJiooiISGB119/vVFxjpyxf9U7IyJuh/4uLy/nzjvvZPv27fj6+layZoYMGUKM+VwnJiaSkZHhUBDOIb4/+ugjwAib/emnnzq+6k+dOsXBgweJjo6usY2amDBhAgEBAQQEBBAREUF2djbr169n0qRJtGrVCoDLLrvMZdnhw4czffp0rr76aoecValJVoDRo0fTvn17x3muX7+e8ePHc//99zN79mwuvfRSLrjggjrPoT5oBdHclBw1Vojz88eam0ergUnulw0KB1UBpfm/DXvFtCCA8sOZwFAPC6zxFnV96XuLDz/8kEWLFnHFFVcwefJkpk2bRteuXQHYuHEjM2fOBIwv4I0bNzq+Vrdv315jnTExMaxdu9axn5mZSUpKCuHh4RQUFGC1WvHz86sU+tuZf/zjH3Ts2JGffvqJiooKAgMDHWmuwmxXTasa4nv58uX0NKMd23nsscdqbKMmGhPi+9VXX3Vcv8TERJfXryZZN27c6DLEd48ePdi6dSsrV67kL3/5C2PGjOGRRx5xSx530H0QzU2xMYtaVVRgKyjA150hrnYccyEq90NYIiPBx0ePZNK4xZgxY1i2bBnr168nNDSUSZMmcfHFF5ORkcHQoUMd4cAnTpzIvHnzHPu1MXbsWFavXk1+fj75+fmsXr2asWPHIiJceOGFjhFPtYX4joqKwsfHh3//+9/YbLYGn9/YsWN58cUXHS/ybdu2ebSNESNG8Nlnn3Hq1ClKSkocCrQqv/76K0OHDmXu3LmEh4dz6NAhlyG+XckK8OWXX5KXl0dpaSmffPIJw4cP58iRI7Ru3ZqpU6dy//33eyTEtzNaQTQ3ZpgNW2EhVFS4txaEnRpmU4u/P34dO1KmRzJp6kH79u2555572L59O0899RS+da1qCGzevJmYmBg++OADZs6c6QjjHRYWxsMPP8zgwYMZPHgwjzzyCGHms/3ss8/y/PPP061bN3Jzc7npppuq1Xv77bfz1ltvMWzYMPbs2UNQUFCDz+vhhx+mvLychIQE+vXrx8MPP+zRNgYPHszEiRMZMGAAV155JcnJyS5DfD/wwAP079+ffv36MXLkSAYMGMCFF17Izp07HZ3UNckKhiK6/vrrSUxM5A9/+APJycn8/PPPDBkyhMTERObNm8ff/va3hl2kmqgpzOuZuJ2R4b6f76vURzPVqb171c6evVTBp5+5XzZ7pxHy++fl1ZIypkxV+6+b4kFBNd5Ah/s+O7CH+D5x4oQaNGiQ2rp1q0frf+ONN9Qdd9zR6HrqG+5b90E0J0r9ZkGYs6jr52KyWxAuhrp26sSJH37whJQajaYObr31Vnbu3MmpU6eYNm0aSUn16EtswWgF0ZyU5htrUZtzIID6uZhatQPxqWGyXDTWnBwd9lujaQLeeecdr9Y/ffp0pk+f7tU2XKH7IJoT5zkQ9kB9Ye3dL+/ja4yAcqEg/CIjQSmsOTmekFTjRZSbo2A0msbQkOdMK4jmxCnMhiNQXzs34zDZqSncRlQUAOXZ2Y0SUeNdAgMDyc3N1UpC41WUUuTm5ro1lNcZ7WJqThwWRCS2vLX4hIQg/v71q6OGcBt+HTsCUJ51bi3Od6YRExNDZmYmZ+xiV5ozhsDAQMcEQ3fRCqI5cVgQEWaYjXp0UNsJ6gBHqo9Jt1sQ1qNHGyOhxstYLBbizDU8NJqWhnYxNSclOWAJgoAQrPl5+LmzUFBVgjq4tCB8Q0LwCQqiPEsrCI1G0zC0gmhOSo5CiOEKstU3kqud1uFwuhCsp6sl+UVFUn5Uu5g0Gk3D0AqiOSnOhuBIgEa4mMxwGydzqyVZIqOwagtCo9E0EK0gmpMSYy1qpRTW/PyGu5ighpFMkXoUk0ajaTBaQTQnJTkQEklFURFYrQ1zMdWiIPw6RmI7fpyKFrako0ajOTPQCqK5KDsJp4vMWdTmHIjGuJhchduIMtxXVm1FaDSaBqAVRHPhPAfCXKu3XrOo7dRmQUQaCkLPhdBoNA1BK4jmwrEWdUTDAvXZCQgB34BaZ1PruRAajaYhaAXRXDgUhLOLqQF9ECI1zoWwOCwIrSA0Gk390QqiuSgxg+gFR2LLs7uYGqAgwAy3Ud2C8GndGp/QUKzZWkFoNJr6oxVEc1F8FMQXWodhy88zXuZO693WixoC9gFYOnbUFoRGo2kQXlUQIjJORHaLyF4RmeMiXURkvpm+Q0SSqqT7isg2EfmvN+VsFkqyjRe7jy/Whs6itlNDwD6wz6bWCkKj0dQfrykIEfEFFgCXAH2AySLSp0q2S4Du5nYr8EqV9HuAXd6SsVkpyXEKs5HnAQVxzFihrgrGbGo9ikmj0dQfb1oQQ4C9Sql9Sqky4D1gUpU8k4C3zaVRfwDaikgUgIjEABOA170oY/NRchSCDQVhBOprwAgmO0EdwHoKyk5US7JERWIrKKCitLTh9Ws0mnMSbyqITsAhp/1M85i7eV4AHgQqamtERG4VkS0isuWMiqlfkgPBEUAjAvXZMRWNY2SUE465ENrNpNFo6ok3FYS4OFbVB+Iyj4hcCuQopbbW1YhS6jWlVLJSKrlDhw4NkbPpqagwFUQkSqmGB+qzE2IoAYqOVEuyRJpzIfRsao1GU0/qVBAi0tBP20ygs9N+DFD1DVZTnuHARBHJwHBNXSQiSxooR8vjZC4oGwR3pOLESVRZGX4NmUVtJyTa+C2u3tdgD7ehRzJpNJr64o4FsVFEPhCR8SLi6ou/JjYD3UUkTkT8gWuBT6vk+RS4wRzNNAwoVEplKaX+opSKUUrFmuW+VkpNrUfbLZtKs6iNMN2NcjG1MawEVxaEfelRq14XQqPR1BN3FEQP4DXgemCviDwlIj3qKqSUsgJ3AqswRiK9r5RKFZHbROQ2M9tKYB+wF1gI3N6AczjzKDG/5kMiHWE2GhSoz05ACPiHuLQgfAID8W3XTlsQGo2m3tS5JrVSSgFfAl+KyIXAEuB2EfkJmKOU+r6WsisxlIDzsVer1H1HHe2vBdbWJecZhWMWdQTWvQeARloQYFgRLiwI0CvLaTSahlGnghCR9sBUDAsiG7gLwzWUCHwA6BXX64tTHCZb/jYAfBuyWJAzIVEuLQgwOqrLDx1ymabRaDQ14Y6L6XugDXC5UmqCUuojpZRVKbUFeLWOshpXFGcbLiH/oMatBeFMm05QVJOC0LOpNRpN/anTggB6mq6gaiilnvWwPOcGJdmV5kBIYCA+rVs3rs42UUbfRkUF+FTW+35RkVQUF2MrOYFvcFDj2tFoNOcM7lgQq0WkrX1HRNqJyCovynT2U5LjmNzW6DkQdkKioMLqel0I+1wIN/ohKlQFaw+t5T97/0NWie630GjOZdyxIDoopQrsO0qpfBGJ8KJMZz8lRyGyP2APs9HI/geANva5EEccMZ7sOOZCHM0moFu3Gqs4UX6CW7+8lR3HdgDQyq8VT414iou7Xtx4+TQazRmHOxaETUS62HdEpCvVZ0Rr6kMlC6KRYTbshNQyF8INC0Ipxex1s0k9nsrc8+eyfOJyurftzv3f3M9Px35qvHwajeaMwx0F8VdgvYj8W0T+DawD/uJdsc5iyk7C6SKnPoi8xndQA7Q1dXjBwWpJlogOIFLrXIgvD3zJN5nf8MDgB7ii+xX0aNeDV0a/QmRQJLPXzeZk+cnGy6jRaM4o6lQQSqkvgCRgGfA+MEgppfsgGopjiKvh9rHm5+PbmDAbdlq3h4A2kLevWpL4++Mb3r7GuRDWCisvbnuRbm27cW3Pax3H2/i34cnhT3K45DBLdy1tvIwajeaMwt1gfQFAHlAI9BGRkd4T6SzHMUmuIxWlpajSUs90UotAWBzk7XeZbKwL4dqC+Prg12QUZXBn4p34+vhWSkuOTCalcwqLf1lMwakCl+U1Gs3ZiTvB+p4FNmC4mh4wt/u9LNfZi1McJmuufQ6EB/ogANrFubQgoPa5EB+lf0RkUCQpnVNcpt898G5KyktYtnuZZ+TUaDRnBO5YEJdjzIWYoJS6zNwmeluwsxa7ggiJ/C1QX3sPuJgAwuKh4ADYrNWS7EuPVp3ScqTkCN8d+Y4rul1RzXqw071dd0Z0GsG7ae9SZivzjKwajabF446C2AdYvC3IOUNJNogPtG6P9bihIPw8piDijLkQRZnVkiyRUaiTJ6koKqp0/PP9n6NQTOpWdbG/ytzQ5wZyT+XyRcYXnpFVo9G0eNxRECeB7SLyLxGZb9+8LdhZS0m2sUSojy/W3OOAJxVEvPHrws3021yIym6mrw9+TZ/2fegUXHWxv8oMixpG1zZd+Sj9I8/IqtFoWjzuKIhPgSeA74CtTpumIRRn/zYHItcLLiZw2VHtWHo067eRTDknc9hxfAejuoyqs2oR4fJul7M1eysHig54Rl6NRtOicWeY61sYw1t/UEq9Zd+8L9pZSslvCsJ6PBefkBB8AgI8U3dwJPi1qsGCsE+W+23p0bWH1gK4pSAAJv5uIj7iwyd7P2m8rBqNpsXjziimy4DtwBfmfqKIVF0ZTuMuJTmOUBi2vFzPuZfACNIX3h1ydlVL8uvQAXx9K82F2HB4A52COxEfGu9W9RGtI7ig0wV8uvdTrBXVO8I1Gs3ZhTsupseAIUABgFJqO3oNiIZRUQEncipZEB5zL9np2A+yf6l2WHx98evQwTEXwlphZdPRTQyLGkZ9VpK9otsV5JTm8N2R7zwmskajaZm4oyCsSqnCKsd0LKaGUJpnjDKyK4hcD1sQAJH9DDdWiauorr/Nhfjl+C+UlJcwLHpYvaofGTOSsMAwPk7/2CPiajSalos7CuIXEbkO8BWR7iLyIkaHtaa+FJsjiOxxmI4fxy/c0wrCiBJLVvUAe85Lj/6Q9QOCMCyyfgrC4mvh0vhLWZu5lvxT+Y0WV6PRtFzcURB3AX2B08C7QBHwJ28KddZiVxAhUajycmyFhZ53MUUnGfMsMjdVS7JERmE9mo1Siq3ZW+nRrgdtA9u6qKR2JnWbhLXCyop9KzwhsUajaaG4M4rppFLqr0qpwUqpZPPvU00h3FmHfc3okCisecbXt8ddTAHBENEXDrlQEFGRqNOnKcs9zo5jO0iMSGxQEz3a9aBP+z56NJNGc5bjziimNSLyddWtKYQ763AoiEhs5iQ5j1sQAF3Ph4M/QHlppcP2uRD70zdz0nqywQoC4PJul7M7fzdpeWmNElWj0bRc3HEx3c9vQfoexhjyusWbQp21FGcZYbn9ArDm2sNshHu+nR5jwVoK+76pdNg+F2L/ns0AJHZouIIYHzcei49FWxEazVmMOy6mrU7bBqXUn4GhTSDb2UdRlmPlN0ccJk93UgPEjgD/YNjzeaXDFtOCyMnYSfvA9nWG16iN0IBQLupyESv2raDcVt4ocTUaTcvEHRdTmNMWLiJjgUh3KheRcSKyW0T2isgcF+lixnbaKyI7RCTJPB4oIptE5CcRSRWRx+t9Zi2RYmcFYQxD9XgfBIBfAPzuItizyph7YeLbvj1YLJQcPkBiRGK95j+44vJul1NwuoC1mWsbKbBGo2mJuONi2orhUtoKfA/cB9xUVyER8QUWAJcAfYDJItKnSrZLgO7mdivwinn8NHCRUmoAkAiME5H6jcdsiRRnQYi5klx2Dj7BwfgEBXmnrd4TjfYy1jkOiY8PPhHhWI4XNcq9ZOe8qPOIaBWh3UwazVmKOy6mOKVUvPnbXSk1Rim13o26hwB7lVL7lFJlwHtA1ZjSk4C3lcEPQFsRiTL3S8w8FnM7syfn2axGmI020QBYs7Px69jRe+31vszo79i0sNLh0nataV+sGtVBbcfXx5eJ3Say4fAGjp6oeb1rjUZzZuKOi+nK2rZainYCDjntZ5rH3MojIr4ish3IAb5USm1054RaLCXZgHJYEOU52Vi8qSAsgTDweti9Egp/Wx8itw2EFwm92/f2SDNX9bgKhdKrzWk0ZyHuuJhuAhYBU8ztdWAqcBlwaS3lXDm4q1oBNeZRStmUUolADDBERPq5bETkVhHZIiJbjh2rHl6ixeCYJGe3IHK8a0EAJM8wfjcvchw6EHiS9iXgL55ZA6pTcCcu7HwhH+75kFJrad0FNBrNGYM7CkIBfZRSf1BK/QFjVjVKqRuVUjNqKZcJdHbajwGO1DePUqoAWAuMcymcUq+ZE/iSO3To4MbpNBPF5mmFRKJsNqzHjuHXMcK7bbbrCr0mwNY3oOwktgobe/xz8bUprMePe6yZ6/tcT8HpAr2YkEZzluGOgohVSmU57WcDPdwotxnoLiJxIuIPXIux+JAznwI3mKOZhgGFSqksEekgIm0BRKQVcDFwZs/IslsQbaKNIa42m3ddTHaGzoLSfNixjANFBzgabITpth71XJ/BoI6DSIpIYvEvi/Wa1RrNWYQ7CmKtiKwSkekiMg1YAaypq5BSygrcCawCdgHvK6VSReQ2EbnNzLYSY83rvcBC4HbzeBSwRkR2YCiaL5VS/63PibU4io6A+ELrcKw5xqI9XncxgTGrOjIBNr7Krtyd5IYYXr3yLM92Kt824DZyTuawLG0ZOcWnKDltRakze1yBRnOu41dXBqXUnSJyBTDSPPSaUsqtWM9KqZUYSsD52KtOfyvgDhfldgAD3WnjjKH4qNFB7eODNbsJFYQIDJsFn8wiLeNritr6A6VYj2bVWbQ+hKjedPDrz/9teomHlwZCRWv8fX24uE8E1w+LZVh8WKPnXWg0mqbFHQsC4EdghVLqXmCViIR4Uaazk+Ijjkly5aaCaBIXE0CfSWBpza7srURGd0MCAjxmQZRZK3j+yz1MWvAdR/ePAZ9ShiVv4KHxvZg8pDPf/ZrL5IU/cMPiTRwvOe2RNjUaTdPgzjDXW4APgX+ZhzoBemZUfbFbEJjrQlss+IaFNU3b/kGo7mNJO51L77BelRYOagyFJ8v547++Z/5X6UxKjOb7+6ZwS/+bSS3+im6xB3h8Uj9++MsoHrusD5v25zH+n9+ycV+uB05Io9E0Be5YEHcAwzHWgUAplQ54efjNWUhR1m+T5HKy8esQjvi4a8A1nuweoyj0EXpV+OIXFYU1q3EupuJT5dzwxiZ2HSliwXVJPH91IqGtLMwaMIveYb15aP1D7M3fS6DFl+nD4/jkjuEEB/hx/eJNfPer50ZQaTQa7+HOG+q0ORMaABHx40yf1dzUlJ2A04W/TZLLzsES0UTuJZNdoYZO75WXiaVjR4ebqyGcKrdx05tbSD1cyIIpSUxIiHKkWXwtzL9oPq38WjHzy5nsK9gHQO+oNiyfdT6x7Vtzy1tb2HZQr0an0bR03FEQ34jIQ0ArERkNfAB85l2xzjKKzDkQbWIAKD98GEt0dJOKkFa4DwF6HNqOX1Qk1pwclNXaoLqeXrmLTRl5/OOaREb3qa7oIoMiWTh6ITZlY+rKqXyR8QUA7YL8WXLTUNoHBzD9jc0czD3ZmFPSaDRexh0FMQc4BvwMzMQYlfQ3bwp11lFoRhMJ7YSy2SjPysISE9OkIuzK20VXSyitj+/BEtoKKiqwNmDm+erUo7z1/QFuHhHHZQNqVnLd2nVjyfglxIXG8cA3D/DwhocpLismok0gS24ailKKO975kdNWW2NOS6PReJFaFYQZkfVtpdRCpdQflVJXmX9rF1N9KDxs/IbGGBPUrFYsMQ1fi6Eh7M7bTe/2RjBdizI6qMvr2Q+RVVjKg8t30L9TKA+O61Vn/piQGN685E1u6X8Ln/76KZd/cjlfHfiKLu1b8/c/DuDnw4U8vfLMnv+o0ZzN1KoglFI2oIM5E1rTUIoOAwIh0ZRlGsrCvwktiMLThRw5cYRe0UMhKAK/U7uB+iuIxz5N5XR5BfMnD8Tfz70OdouPhbuT7mbp+KW0C2zHn9b+iYe+fYgLerRhxvA43vwugy93Nrw/RKPReI86J8oBGcAGEfkUOGE/qJR63ltCnXUUHoLgjuDnT3mmEVm1KV1M9nWje4X1hi7DsBz8CaBeI5m+2XOMVanZPDiuJ3Hh9V/Dol94P9699F0W7ljIqz+9yt6CvfwzZQHf/Xqchz/5hWHxYYQEeiaAoEaj8Qw1fgaKyL/NP68B/mvmDXHaNO5SeBhCDZdS+eFM8PFxrA/dFDgURPteEJOM74kD+IQEU36kauxE15RZK3j801TiwoO4aURcg+Ww+Fi4PfF2Xhr1EhlFGcz66hb+NjGW7OJT/N8Xuxtcr0aj8Q61+QkGiUhX4CDwootN4y6FmdDGUBBlmZn4RXZELE33tbwrbxcRrSMICwyDmMEAWNq3ofyIexbE4g372Xf8BI9e1ocAP99GyzMyZiQLRi3gYPFBFu5+mBvOi2HJxgNsychrdN0ajcZz1KYgXgW+wIjcusVpsy9BqnEHpYw+iFAjqnl55mH8OzXtCKbdebvpHWYuEBSVCOKLJUTc6oMoLC3n5TV7GdUrgpSenpsfOThyME8Of5Ifc34kMGIV0aGteOQ/qdgq9PgHjaalUKOCUErNV0r1Bt4wlxy1b3FKqfgmlPHMpjQfyk/+5mLKzGzS/odT1lPsL9xPrzBz1JF/a+jYB4v/CbdcTIu+3UfRKSv3jenpcdnGx4/n6h5X887uf3PNBeXszCpi+dbMugtqNJomwZ01qWc1hSBnLfblPkNjqDh9GmtOTpMOcU3PT8embL8pCIBOyVjIoaK4hgLXFAAAIABJREFUGFtxcY1l80+UsXhDBuP7R9Inuo1X5Lsv+T6ig6L5MuclErsE8ffVuzlxumET+DQajWdpumBA5ypF5hyINjGUHzImzPl36dJkze/K2wVQWUFEJWAJKAFqH+r6r3X7OFFm5U8Xu7M+VMNobWnNX4f9lYyiDIYkpHGs+DSvfvOr19rTaDTuoxWEt3GyIE7v3w+Af2zDRwLVl7S8NEL8Q+gU7GS1dOyHX2tjBnNNbqb8E2W89V0GEwdE06OjdwetjYwZyfDo4fz30NuMS2jDwm/3kVN8yqttajSautEKwtsUZoKPBYI6ULY/AwD/uNgma3533m56hfWqvFhPRG8spoKoaS7Ekh8OUFpu4/aUbk0hJvcOupfismK6xP5IuU3x8hptRWg0zY1WEN6m6LAR5tvHh7L9+/Hr0AHf4OAmadpWYWNP/h56tqvSwRwQgl90Z/AVl0NdT5XbeOv7DC7s2YGekU0z5aVnWE9SYlJYefADLh8YzjsbD3KkoLRJ2tZoNK7RCsLbFGY6hriW7d+Pf1zTuZcyijI4ZTtF7/a9q6VJZH8sQa77IJb/mMnxkjJuHfm7phDTwU39b6LwdCGx8T8D8OLXe5u0fY1GUxmtILyN0yzqplYQLjuo7XTshyXwNOWHD1U6bKtQvP7tfhJiQhkW30Qr3pkkRiSS3DGZT/a9w9WDI/lgyyEO5emQ4BpNc6EVhDexlTsmyVnz87EVFjZ5/4O/jz9xoS6UUsc+WFpbjdAfTqxJy2H/8RPcOjK+cr9FE3Fz/5vJOZlDt/h0RGDht/uaXAaNRmOgFYQ3KcwEZYOwOMr2GS+6gCa2ILq3647Fx0VYj/Ce+LW2YT2WV2nhoLe+zyAqNJBxfSObTE5nzo8+n25tu/HFwY+4cmAMyzYf4ljx6WaRRaM519EKwpvkZxi/bbtSZh/i2kQKQilFWl6aa/cSQFg8liAFSmE1lx/99VgJ36YfZ8rQ/9/eeYfHVV17+10ajXrvlqxqy93GxsbYYGO6jQ2YEpL4hoSACUmAEFJuICTky73JvQnJzb3pQOgQIJRQTAk2GHAB915k2VavVu/S1P39cY5lWZZklSkS7Pd55pmZvfc5+zcjzVlnl7VWBoEW//xriAg3TbqJQ/WHuHS2HbvLzdOfFvlFi0bzeUcbCG9y0kDEZmErKkKsVqxpvvGirm6vptnW3L+BCAzCmpIInFqofm5LCUGWAL4833eOfH1xzYRrCA0MZUvN21w1I4Vnt5TQ2uXwqyaN5vOINhDepKnE8IGISsVeVIw1MwOxjDwa6mAYcIHaxJphjGYcVVW02Zy8uqucFbPGkRAR7BON/REZFMmyrGW8W/Qut1w4jtYuJ3/fWupXTRrN5xGvGggRWSYi+SJyXETu76NeROSPZv1+ETnXLE8XkY9EJE9EDonId72p02s0FkNMBgRYsBcV+XT9Ib8hH0GYFNt/mAxrtpGC1FFezut7KmizOfnawkxfSRyQL07+Ip3OToq7NrE4N4EnNhfR5dD5qzUaX+I1A2Hms/4LcBUwDVglItN6NbsKyDUfdwAPm+VO4AdmNNkFwF19HDv6aSyG2CyUw4G9rIygbN8Fwc1ryCMzKpMwa1i/bQLSpmEJduEoPsoL20qZNi6K2ekxPtM4ENPjpzM1biqvHnuVby+ZQF2bjVd1pFeNxqd4cwQxHziulCpUStmBfwAre7VZCTyrDLYCMSIyTilVpZTaDaCUagXyAN+FQPUUjcUQm4m9vBycTp/6QBxpOHIqB0R/JEzCGuaipbCAvKoWVp2f4ZetrX0hIqycuJIjDUdIiGvgnPQY/raxEKfL7W9pGs3nBm8aiDSgpxdWOWde5M/aRkSygDnAtr46EZE7RGSniOysra0doWQP0tVs5IKIzeqOwRScneWTrpu6mqhqrzJSjA5EQi6BYS66KqoJtVpYOTvVJ/oGy1XZVxEogbxd9DbfXjKB0oYO3jkw+DzaGo1mZHjTQPR1K9o7XdiAbUQkAvgncK9SqqWvTpRSf1NKzVNKzUtMTBy2WI/TWGI8x2b5fIvrkUYzB/UAC9QAhMZgjbZiaWnnmlkpRIX4Lg3qYIgLiWNR2iLeKXiHy6YkMCExnMc2FaKUzjqn0fgCbxqIciC9x/vxQO/Y0v22ERErhnF4Xin1mhd1eoceW1ztxUVY4uKwREf7pOv8hnxgEAYCsEdHY3G6+fK0WG/LGhbXTLiGms4adtRsZ/WiHA5WtLCtSOeu1mh8gTcNxA4gV0SyRSQI+DKwplebNcDXzN1MC4BmpVSVGBPhTwB5Sqn/9aJG79HLByIoK8tnXec15JEUlkRcyNljKVUGGZnipgaMzphHS9KXEGmN5K2Ct7jh3DRiw6w8vkk7zmk0vsBrBkIp5QTuBtZiLDK/rJQ6JCLfEpFvmc3eBQqB48BjwJ1m+YXAV4FLRWSv+VjuLa1eobEYQmMhJBp7cYlPYzDl1ecxLe7sm76OnmglzxIPgLO87Cyt/UOwJZil2UtZX7oeNza+uiCT9UdOUFjb5m9pGs1nHq/6QSil3lVKTVJKTVBK/ZdZ9ohS6hHztVJK3WXWz1RK7TTLNyulRCk1Syk123y8602tHqexGGIycbW24qqr89kIosPRQVFzEdPiz24g/rmrnIIwY0+Ao/Cwt6UNm2tyrqHT2ckHpR9w88JMrAEBPPVJsb9laTSfebQntbdoKDSC9BUbi9W+MhD5jfkoVJ85IHridLl5bU8FEbmzkQCFo/iYT/QNhzlJc0iLSGNNwRqSIkNYOTuVV3aV0dRh97c0jeYzjTYQ3sBpM8JsJEzCXlwMQLCPDMThemMkcDYfiI3HaqlttXH+vPOwhjtxlI3eUBYiwjUTrmF71Xaq26tZvTibLoeb57eNXs0azWcBbSC8QUMhKDfE5xoGQgRrhm8C4OXV5xEfEk9SWNKA7V7dVU58eBCLzpmCNQrsVTU+0Tdcrs65GoXivaL3mJISxeLcBJ75tBi7UzvOaTTeQhsIb1B31HhOMAyENTWVgGDfBMA73HCYqfFTB/SIbmy388HhGlbOTsMaaCEoIQJH/ehe9M2MymRG/AzeKXoHgNWLsqlptfH2/t47pzUajafQBsIb1Jnz+fETsZeU+Gz9ocvZRWFT4Vmnl9bsq8TucvOFueMBsKYk4e5y42pu9oXMYbMiZwVHGo5Q0FTAkkmJ5CZF8PimIu04p9F4CW0gvEHdMYhMRQWFYy8u9pmBONp4FJdyMT1++oDtXtlVxvTUKKalGj4Q1nTDV9FeUuxtiSNiWfYyAiSAdwrfQURYvSibw1UtbCms97c0jeYziTYQ3qD+GCTk4qqvx93W5jMDkVdv5IAYaAdTXlULBytaukcPAEE5kwFwHNvvXYEjJCE0gfNTzufdondRSnHdnDTiwoN4crN2nNNovIE2EJ5GKag73r3+AL7b4prXkEdMcAzjwsf12+afu8qxWoSVs0/FRLROOgcAx/HR6wtxkuU5y6loq2B/3X5CrBZuXpDJB3k12nFOo/EC2kB4mtZqsDWftsXVV17Uh+sPMzWu/wVqh8vNG3sruGxKMnHhQd3llvHTsAS5sJeM/jvxyzMuJyggiHcKjcXqry7IJMgSwJOfjH7tGs1YQxsIT1NzyHhOmoa9uNjIQz2u/zt6T2Fz2TjWdGzA6aWP82upa7OfNr0EQFQq1kg3jspqL6scORFBESxJX8La4rU43U4SI4O5bk4qr+4qp7FdO85pNJ5EGwhPc8Kcpkmejq3Yd3mo8+rzcLqdzEqY1W+bV3eVkRARxJLJvcKiB1gIig3BXtPkZZWeYUXOChq6GthatRWA1Yty6HK4eWG7dpzTaDyJNhCepuYwRKRAWJxPdzAdqDsAwMzEmX3W17fZWJ9Xw/Vz0rBazvyzW5NicTTZUK7Rn/d5cdpiIoMiebfQCM81OSWSxbkJPP1pMTbn6Nev0YwVtIHwNCcOQfI0lMuFo6TUZyE2DtQeICU8pV8P6jf3VuJ0K27sPb1kYk0bB25wVo/+aaYgSxBXZl7J+tL1dDo7Abh9cQ61rTbe3qczzmk0nkIbCE/ickJtPiRNw1FVhXI4fDaC2F+3n5kJfY8ewAitMTMtmikpUX3WB2VNAMA+BnYyASzPXk6Hs4MNZRsAuCg3wXCc26wd5zQaT6ENhCdpKASXzVigNvNQ+8JA1HfWU9FW0e/6w6HKZg5XtXDTvL5HDwDWiYZznePo6PaFOMnc5LkkhSV172YSEW5fnE1eVQtbCrTjnEbjCbSB8CQnjHUAkqef2uKamen1bs+2/vDKznKCLAFcMyu133NYc2eDKOxFR72i0dNYAixclXUVmys209RlLK6vnJ1GfHgQj2vHOY3GI2gD4Ukq94IlCJKmYi8uJiA8HEtCgte73V+7H4tY+kwSZHO6eGNvBVdMTya2h+9DbyRxAtZwF/aSsbMTaEXOCpzKybqSdQCEWC18dWEmHx6p4XiNdpzTaEaKNhCepGovJE2DwODuHUwDRVX1FPvr9jMpdhKhgaFn1L1/+ARNHQ6+NC994JNYQwmKtWCvqPWSSs8zJW4K2dHZvFt0KtngzQsyCQrUjnMajSfQBsJTKAVV+yB1NoDPtri63C4O1h3sd4H6pR1lpMWEcuHEs49kgpOjsdd1oNxjI8eCiLAiewW7Tuyiqs3YvZQQEcwNc9J4bXc5DdpxTqMZEdpAeIrGIuhqhnGzcdtsOCorfbL+UNRcRLujnVmJZy5Qlzd2sPl4HTfOHY8l4OwjmaDxKSinGhNbXU+yPHs5AP8q/ld32W2LjIxzL2wr8ZcsjeYzgTYQnqJyr/GcOhtHaSkoRVB2tte73V2zG4DZSbPPqPvnrgqUgpv68X3oTVBODgC2Y/meE+hl0qPSmZU4q3s3E8Ck5EiWTErk6U+L6XJoxzmNZrhoA+EpKveYC9TTsPkwiuvOEztJDE0kI/L0lKZut+KVXWVcODGe9LiwQZ0raLIxTWU/vMfjOr3J8uzlHG08yrHGY91ld148gbo2Oy/ovNUazbDRBsJTlG2HcbO7F6jB+1FclVLsqt7FvOR5ZyyGbymsp7yxky+ebXG6B4E5MwkIdGM/nudpqV5ladZSLGI5bbH6/Jx4zs+O45ENBXoUodEME20gPIHTZowg0ucDxgK1JTEBS0SEV7stay2jprOGuclzz6h7aUcZUSGBLJ2eMujzSVw2QZFO7MVja+4+ITSBBeMW8G7hu6d5UX/3slxqWm28vLPMj+o0mrGLVw2EiCwTkXwROS4i9/dRLyLyR7N+v4ic26PuSRGpEZGD3tToEar2GR7UGQsAsBeXEJyZ5fVud57YCcC8lHmnlTd3OHjvUDXXzUkjxDqESLJh8QTFCLYxtNX1JCtyVlDZXsne2r3dZQsnxDMvM5aHPy7QQfw0mmHgNQMhIhbgL8BVwDRglYj09uS6Csg1H3cAD/eoexpY5i19HqVsm/E8/tQIwhdJgnad2EVcSBw50Tmnlb+5rwK70z2k6SUARAhOjcbZ1IWrpcWDSr3PpRmXEmIJOW2xWkT47uW5VDV38fxWvRah0QwVb44g5gPHlVKFSik78A9gZa82K4FnlcFWIEZExgEopTYCDV7U5znKtkFsFkQm42ppwVVf75sF6uqdzE2ee8b6w0s7ypieGsWMtOghnzMk20hFassfOzuZAMKt4VycfjHritfhcDu6yxdNTOCCCfH8+aPjtHY5BjiDRqPpjTcNRBrQc/K33CwbapsBEZE7RGSniOysrfXD1IhSULoN0s3ppRJj/t7bBqKyrZLK9soz1h/2ljVxqLKFL503xNGDSfCkSQB0HTkyYo2+Znn2chptjXxS8Ul3mYhw37IpNLTbeWyT9q7WaIaCNw1EX55ZveMwD6bNgCil/qaUmqeUmpeYmHj2AzxNYzG015y2QA3eNxDd6w/Jp68/PLelhPAgC9fPGZKd7SYweyqWIDe2g3vP3niUsWj8IuJD4nnt2GunlZ+THsOKmeN4fFMhta02P6nTaMYe3jQQ5UDP29jxQOUw2oxuTq4/pJ8PYIT5DgjAmj68O/jBsrVyKzHBMeTG5naXNbbbeWt/Jdefm0ZkiHVY55W4HIJjHHQdGRt5IXpiDbBy7YRr2Vi+kbrOutPqfrh0Mnanm9+uHXsjI43GX3jTQOwAckUkW0SCgC8Da3q1WQN8zdzNtABoVkqNrZRgRZsgJMYI0ocxgrCmpREQ1H/k1JHiVm42V2zmwrQLCZBTf8JXdpVhd7q5ecEIQnzEZRMc48BWXDEm0o/25rrc63ApF2sKTv9Xy04IZ/WibF7eWc7u0kY/qdNoxhZeMxBKKSdwN7AWyANeVkodEpFvici3zGbvAoXAceAx4M6Tx4vIi8AWYLKIlIvIam9pHRFFGyF7MQQYX6WtuMjr00uH6g7RaGtkcdri7jK3W/H3raXMz4rrN2vcoIhOJyROoWwO7KVjb+dPTnQOc5Lm8Pqx18/ILPedy3JJiQrhwTcO4nLrrHMazdnwqh+EUupdpdQkpdQEpdR/mWWPKKUeMV8rpdRdZv1MpdTOHseuUkqNU0pZlVLjlVJPeFPrsGgshuZSyF4CGJ7N9uISrxuITRWbEIQLUy/sLttwtJbShg6+siBjgCMHQYCFkBwjsVDX/rGRXa43N+TeQHFLcXecqpNEBAfy06uncqiyhb9vHVvOgBqNP9Ce1COhaKPxnH0RAM4TJ1AdHV73gdhUvolZibOICYnpLntsUyEpUSEsnzluxOcPnjSZgCDo2D22YjKd5MrMK4mwRvBy/stn1K2YOY7FuQk89N4RSurb/aBOoxk7aAMxEoo2QkQyJBhbQ23HjGBxIbm5Ax01Iuo66zhYf/C06aVDlc18WlDP1y/MwmoZ+Z9UkiYTGmejc/euEZ/LH4RZw7hu4nWsK1lHbcfpW59FhIdunIUlQPjeS3txusZG7guNxh9oAzFclDIMRNZiMB3VbMeOAxA0caLXuv208lMAFo8/ZSCe2FREWJCFVfNHOL10koRJhCbYsB0vGHMe1SdZNWUVLreLV46+ckZdakwov7xuBrtLm3hkQ4Ef1Gk0YwNtIIZL3TFoO9E9vQTGCMKSmEBgbKzXut1Uvon4kHimxE0BoLq5izX7KvnivHSiQ4e3tfUMEnIJS7CDUnTu2+eZc/qYjKgMFo9fzMv5L2N3nZlZ7tpzUrl61jj+74NjbD5W18cZNBqNNhDDpWiD8dzLQAR7cfRgc9nYVLGJJelLure3PvlJEW6luO1CDyYnis8lJN4BInTs2Hn29qOUr0z5CvVd9awtXntGnYjw6xtnMTExgrte2E1RnV6P0Gh6ow3EcCnaCNEZRgwmQLnd2AoKCPbi+sMnFZ/Q7mjnyswrAahrs/HclhKuPSeVjPjBJQUaFMERWOJTCcuMpO2jjzx3Xh+zMHUh2dHZPHf4uTO2vIKxq+nxW+YRIHD7Mzt0DmuNphfaQAwHtwuKNxn+D+b6g6OiAtXZ6dURxLqSdUQHRzN/nBHW4/FNRXQ5Xdx9qReMUvJ0ItId2I4dG5P+EGCMElbPWE1eQx4flfVt6NLjwnj45rmUN3byb49tpb5Nh+LQaE6iDcRwqNgFnY0w8fLuopML1N4aQXQ4Ovio9CMuy7gMa4CVhnY7z24p5ppZqUxM8kJiouQZRMYacRRb13/o+fP7iBU5K8iIzODhfQ/3OYoAWJATzxO3nEdRXTv/9tg2alq6fKxSoxmdaAMxHI6tAwmACZd0F3UdPmzkU8id5JUu15eup8PZwdU5VwOG30Onw8V3LvXSiCVlJkFhdoJzMmj94APv9OEDAgMC+eY53+RIwxE+LO3f0C3KTeCpr59HaUMHV/9pMzuKx0akeY3Gm2gDMRyOrTOC84We2q3UdeAAQRNysESEe6XLNwveJC0ijbnJc6ls6uSpT4q4elYqucmRXumPlFkARJ2XQ+euXdgKxu520OXZy8mMyuSv+/6KW/Xv93DBxAReu/MCY8vw37byl4+OY3dqPwnN5xdtIIZK6wkjxWiP6SWlFJ0HDxI6Y6ZXuixvLWd71XaunXAtARLA/6zNx63gR0sne6U/AOKywRpOzPRgxGql4elnvNeXlwkMCOTOc+7kaONR3jj+xoBtp46L4s27F7F0egq/XZvPsj9s5KMjNf1OT2k0n2W0gRgqx83pltwru4ucVVW46usJmTnDK12+fPRlAiSAG3JvYF9ZE6/tqWD1omzS4zy4c6k3ARZInk5g+1FibvoCTa+/jq1w7CbcuSr7KuYkzeEPu/9As615wLbRoVb+8pVzefrW83C7Fbc+vYPlf9zMa7vL6bSPvQi3Gs1w0QZiqBxbBxEpkHJqtNB54CAAoTM9P4KwuWy8fux1Lkm/hOSwZH75zmESIoK48+IJHu/rDMbNgqp9JNxxBwGhoVQ98ABu+9jcCioiPHD+AzTbmvnNjt8M6piLJyex9nsX8ZsbZ+Fwufn+y/uY98v3+f7Le1mfd4IuhzYWms822kAMBUenMYKYtLR7eytA18EDYLUSPGWKx7t88/ibNNmaWDVlFS9sL2VHcSM/vHLysBMCDYmMhWBvI9Bdzbj//A869+6l8r77UE6n9/v2AlPipvCNWd9gTcEa3i95f1DHBAda+OJ56ay79yJeuP18Vswax/uHTrD6mZ2c+4v3ufP5Xbyxp4LmDp3vWvPZI9DfAsYUBR+CvQ2mrTytuGPPHkImT/Z4kiCn28mTB59kZsJMUkNmcNu7m7hgQvyw800PmYyFxnPpFqKu+jaOyipqfvtbShsaSfvd/xCYkOAbHR7kjpl38GnFpzz4yYNMiJlATnTOoI4LCBAumJjABRMT+MV1M9hSUM+6wyd4//AJ3j1QTWCAsCAnniunJ3PFtGTGRYd6+ZNoNN5HjyCGwuE3jexxPcJruNra6dy7j/CFCz3e3TuF71DRVsHqGat54PWDuJXioRtnIdJXKm8vEJ0GMRlQYgQIjF99G6kP/ZrOffsouuFGOvaMvXDgVouV3138O4Itwdz5wZ3UdNQM+RzBgRYunpzEf18/k20/vozX7ryA2xfnUNnUyc/ePMTCX33ItX/ezHNbS2i3jc3RlkYD2kAMHkcn5P8LpqwAy6npnY7t28HpJPzCCwc4eOjYXDb+vPfPTI+fTnFpFhuP1vKjpZO9uzDdFxkXQOkWI3otEL1yJVn/eBEJDqbka7fQ9PrAu4JGIynhKfz1sr/S2NXIre/dSkVbxbDPFRAgnJsRy/1XTeHDH17MB99fwo+WTcblVjz4xkEW/Go9v3z7MGUNHR78BBqNb9BTTIMl7y2wtcCsL51W3P7JJ0hoKKHnzvFod88eepbq9mq+knMfv3g1nyumJfO1hVke7WNQZF4A+/8BNXmQbOTdDpkyhexXX6H83nup+vGPUV2dxK5a5XttI2B6wnQeveJR7lx/J6veXsV/L/5vFqUtGvF5JyZFMDFpIt9eMoHdpU089UkRT31azBOfFHHltGTuviSXmeOjPfAJRgcOl5uKxk5OtHRR326ny+HC4XITFBhARLCVhIggMuPDiQ2z+m7kq/EY8lna3z1v3jy1c6eXoo8+fTU0lcI9e7vzTwMULLsKa2YGGY8+6rGuylrKuH7N9cxLuoCd268hKtTKm3dd6JuF6d60VsPvpsAlD8CSH51W5bbZqLj3e7R9/DFpv/89UUuv7Ocko5fC5kJ+8PEPON50nMszLuf7875PeqRn13iqmjv5+9YSnttSQkuXk0unJPGdSycyJ8N7YeG9QWuXg92lTRyubCG/uoUj1a0U1LbhcJ39GhITZmVOegxzM2NZMimJGWlR2mCMEkRkl1JqXp912kAMgvoC+NO5cOlP4aJ/7y62FRZSuHwFyT/5CXFfvdkjXTndTlavXc2RhnxCau6nvimUN+66gIlJXvKYHgxPLAV7O3x78xlV7q4uSr9+K115eWQ8/RRhczw7kvIFXc4unj38LI8feByH28HlGZfzxclfZF7yPI9exFq7HDy7pYTHNxXS2OFgcW4C91yWy3lZcR7rw5O0dDnYVtjAtsJ6thU1cKiyGbd5uUiNDmFySiSTU6KYmBRBclQwCRHBhFotWAMDsDvdtHU5qWntori+g/zqFnaXNnG8pg2A5Khgls8cx01z05mWGuXHT6nRBmKkrLkH9v0D7t0PkSndxbV//CN1jzzKxI8/wpqU5JGu/rj7jzx24DGiW2+hoWYGz9w23/8XkC1/gbUPwD17IO7MXT/OhgaKV63C3dpG1ssvETR+vB9EjpwT7Sd4+tDTvFnwJq32VlLDU1matZSl2UuZFjfNY8ai3ebk71tL+NvGQurb7SzMieeey3JZkBPn17tqpRRHqlv5KL+Gj/Nr2V3SiNOtCAoMYHZ6DAuy45ifHc/M8dHDTk5V32bjo/xa3j9czUdHarG73ExPjeILc8ezcnYaceGe3QmoOTvaQIyE5nL4w2yYewus+F13sXI4OH75FQRPnEjGE497pKu3Ct7igc0PENy5kLaK63n61vksyIn3yLlHRFMZ/H4mLLoXLv95n01sRUUUf3kVgYkJZL34IpZIP454Rkins5P3S97nX0X/YmvlVpzKSUZkhmEsspYyKXaSRy7knXYXz28r4dGNhdS22pifFcd3LpvIookJPjMULV0OPjlWx8f5tWw4Wku1Gcl26rgoLp6cyEW5iczJiCHEavF4343tdtbsq+SVXWUcrGghyBLAldOTWTU/g4U58QQE6CkoX6ANxEh47Ztw8FVj7SHm1Nx085o1VP7oPsY//FciL7lkgBMMjncK3+GBTQ/g6sghuP6bPHrzfOb5e+TQk5dvMfxAvncQQvpeZG3fuo3S228n/PzzSX/0ESRw7O+BaOpqYn3petYWr2V79XZcykV2dDZLs5ayLGsZE2JG7tHe5XDx0o4yHtlQQFVzF3MyYvjOpRO5eFKSxy+oCs3NAAARoElEQVSSbrficFULG47WsiG/ll2ljbjcisiQQBbnJnDxpCSWTE4kOSrEo/2ejbyqFl7aUcbreypo7nSQGR/Gl85L5wtzx5MU6Vst/dHlcNFpd+FwuwkQISzIQkigZcwbMm0ghsux9+H5LxjrDpf+tLvY3dVF4TXXEhAeTvZr/0QChr9b2OV28Zttf+aFo4/jbM8hV93D326+kJTo0fGj6KZqHzx6EVzykzMWq3vS+MorVD/4M6KuuYbUX/33Z8JInKShq4EPSj7gveL32Fm9E4ViYsxElmUtY1n2MjKjMkd0fpvTxau7yvnrRwVUNHWSGh3CdXPSWDYjhRmp0cO6ECmlKG3oYE9pE5uO1bHhaC11ZlKkGWlRLJmUyJJJSczJiMFq8f+u9y6Hi/cOVvPi9lK2FTUQGCBcNjWJm+amsyg3wSsjmZ502l0cr2kj/0Qrx060kn+ileM1bdS12ehynBnZNzBAGBcTwviYMNJiQxkfG8rEpAhmpkWTERc2JhbitYEYDjVH4KllEJEM39wIgcHdVdX/+QsaX3iBjKeeHJGD3Jr8TfzPjv+l0XUcd8tcvjnjR3xr8RSCAv3/Q+2Tl242jOZtayF1dr/N6h55hNrf/4HIKy5n3K9+7bUQ6P6ktqOWdSXrWFu8lj01hsPg1LipXJl1JcuyljE+cvjrMA6Xm38drOa13eVsPFqLW0FCRBDn58QzMy2aKSmRpMaEkhQZTIjVgiVA6HS4aO1ycqKli/LGTo7XtLGvrIl95U00mWFAYsKsXJSbyJJJiSyelDBq7sz7o6C2jZd2lPHqrnIa2u1EBAeyZHIiF+UmcMGEBMbHhg77Amx3uimqayf/RCtHq1s5esJ4lDR0nHT5ISgwgAmJEeSai/AxYUGEBVkItASglKLD7qK500FlUyfljZ3Gdt/Wru7jI0MCmZ4axYzUaGakRTMjLYrshAgso2zE4TcDISLLgD8AFuBxpdSve9WLWb8c6AC+rpTaPZhj+8JjBuL4B/D6t414S7e9170w67bbqfvTn6h/7HHivv51ku+/b0indbkVu8srePHgWjZXv02n5TjKGcE5YV/joWW3MD7Wx05wQ6X1BDx+GTg64N9egfFz+23a8MwznHjoNwSlp5P04/uJWLJkTNxNDYfq9mrWFRvGYn/dfgBmxM9gWfYy5qXMIzcmlyDL8BZf69tsbDhay8f5tewqaaSiqXNQxwUITEqOZHZ6DLPGx3BOejRTUqJG3cVpMNidbj4tqOO9g9WsP1JDbasxAooPD2JGWjQTEiMYHxtKSnQIUSFWwoKNUYbbrWizOWnpclLV1ElpQwelDR2UNXRQ3tiJ09ySZQkQsuLDmJwSyaTkSCYnRzIpJZLMuDAChziqsjldHDvRxsGKZg5WNnOwooW8qhZsZl6REGsAk5MjmTouimmpUUxKjiQzPozkyBC/TVX5xUCIiAU4ClwBlAM7gFVKqcM92iwHvoNhIM4H/qCUOn8wx/bFsA1E4cdga4WGQsh/D0o/hcQpcNMzkDSFjj17aNuwgZa338FRXk7MTTeR8vP/h1hOH+4W1NVR0dJMQ3sb9R1t1He0Ut1+grLWaqo7iml0lkBwBSJuLO5YFsTdwE+X3Mr4mDHkOFVfAM9cAy2VMO1amHgFpM3tdqLrSfv27VQ9+CCOklKCsrOJuPQSI2ZVVBS4XERcdBFi9YNvhxepaKtgbfFa3it6j7yGPMDIR5Ebk0tubC7JYcmkhKeQEp5ChDWCcGs44dZwgixBWMRCYEAg0cH9/z80tNspqG2jurmLmlYbdqcbp8tNiNVCZEggCRHBpMeFkREXRmiQd6dj/IFSiuM1bWwprOdAeTMHK1sormuncxCRdWPDrGTEhXV/PycNQk5iOMGB3vuunC43BbXtHKhoJq+qhcOVLeRVt3SP7ACCAwNIjwsjMy6MpKhg4sKDiAsPJiEiiKhQK2FWC6FBFkKtlu5RowgIxrMlQEiICB5ARf/4y0AsBH6ulFpqvv8xgFLqVz3aPAp8rJR60XyfD1wMZJ3t2L4YtoH4r3HGXTFAfC6c+zWY/w2wGgHXKr7/fVrWriN0zmwSvv1tIvoJq3Hek9fTZTneZ51FhRNnzWJq7ExumHIll2TPJUBG6VTS2ehqho2/hX0vQXuN8X1d+6c+myq7nea33qL5jTfp2LsXHKd+FLlbPiUwdmw5iw2FyrZKDtQd4HD9YQ7XH6a4pZjajlpcqv+LWVxIHBu+tMGHKsc+Sinq2+3Uttpo7XLSbnciQIAIESGBRIUEkhRljC5GC0opqpq7OF7TRklDB6X17ZTUGyOcujY7jR12XO7BX5sTIoLZ+dPLz96wD/xlIL4ALFNK3W6+/ypwvlLq7h5t3gZ+rZTabL5fD9yHYSAGPLbHOe4A7jDfTgbyRyg9Aagb4Tm8gdY1NEarLhi92rSuoTFadcHQtGUqpRL7qvDmFpO+JtR6W6P+2gzmWKNQqb8BfxuatP4RkZ39WVN/onUNjdGqC0avNq1raIxWXeA5bd40EOVAz6A244HKQbYJGsSxGo1Go/Ei3pwE3wHkiki2iAQBXwbW9GqzBviaGCwAmpVSVYM8VqPRaDRexGsjCKWUU0TuBtZibFV9Uil1SES+ZdY/AryLsYPpOMY211sHOtZbWnvhsekqD6N1DY3RqgtGrzata2iMVl3gIW2fKUc5jUaj0XiOMbrPUqPRaDTeRhsIjUaj0fSJNhCAiPxWRI6IyH4ReV1EYnrU/VhEjotIvogs9ZO+ZWb/x0Xkfn9oMHWki8hHIpInIodE5LtmeZyIvC8ix8xnv3i/iYhFRPaY/jWjQpeIxIjIq+b/V56ILBwlur5n/g0PisiLIhLiL10i8qSI1IjIwR5l/Wrx1W+yH11+v1b0patH3Q9FRIlIgkd0KaU+9w/gSiDQfP0Q8JD5ehqwDwgGsoECwOJjbRaz3xyM7b/7gGl++p7GAeearyMxwqFMA34D3G+W33/y+/ODvu8DLwBvm+/9rgt4BrjdfB0ExPhbF5AGFAGh5vuXga/7SxdwEXAucLBHWZ9afPmb7EeX368Vfekyy9MxNvaUAAme0KVHEIBSap1Symm+3YrhdwGwEviHUsqmlCrC2G0138fy5gPHlVKFSik78A9Tl89RSlUpM5iiUqoVyMO42KzEuBBiPl/na20iMh5YAfTM3uRXXSIShfFjfgJAKWVXSjX5W5dJIBAqIoFAGIafkV90KaU2Ag29ivvT4rPfZF+6RsO1op/vC+D/gB9xulPxiHRpA3EmtwH/Ml+nAWU96srNMl8yGjScgYhkAXOAbUCyMvxXMJ89k391aPwe48fRM2i/v3XlALXAU+bU1+MiEu5vXUqpCuB/gFKgCsP/aJ2/dfWiPy2j6fcwaq4VInItUKGU2terakS6PjcGQkQ+MOdbez9W9mjzE8AJPH+yqI9T+Xpf8GjQcBoiEgH8E7hXKdXiTy2mnquBGqXULn9r6UUgxlTAw0qpOUA7xnSJXzHn81diTDmkAuEicrN/VQ2aUfF7GE3XChEJA34C/Kyv6j7KBq3rs5Pu6ywopQYMdSgitwBXA5cpc/KOwYUL8TajQUM3ImLFMA7PK6VeM4tPiMg4pVSViIwDanws60LgWjHCx4cAUSLy91GgqxwoV0ptM9+/imEg/K3rcqBIKVULICKvAReMAl096U+L338Po/BaMQHD2O8TI+fKeGC3iMwfqa7PzQhiIMRITnQfcK1SqqNH1RrgyyISLCLZQC6w3cfyRk3YETH++54A8pRS/9ujag1wi/n6FuBNX+pSSv1YKTVeKZWF8f18qJS6eRToqgbKRGSyWXQZcNjfujCmlhaISJj5N70MYz3J37p60p8Wv/4mR+O1Qil1QCmVpJTKMn8D5RibSapHrMsbq+xj7YGxcFMG7DUfj/So+wnGyn8+cJWf9C3H2DFUAPzEj9/TIozh6f4e39VyIB5YDxwzn+P8qPFiTu1i8rsuYDaw0/zO3gBiR4mu/wCOAAeB5zB2ufhFF/AixlqIw7y4rR5Ii69+k/3o8vu1oi9dveqLMXcxjVSXDrWh0Wg0mj7RU0wajUaj6RNtIDQajUbTJ9pAaDQajaZPtIHQaDQaTZ9oA6HRaDSaPtEGQvOZQkR+LiI/PEub60Rk2jDO3TZ8ZYM6f3HPKJxDOO5jM1LntT3en5GwfrjnP0vfF4sZPbdH2TQz2ui/zFhP/R07RUS2iIit599MREJFZK+I2D2tVzM0tIHQfB65DiPK5ahBRCwjPMVXlFJ+z9suIqkY0WFvwHAKHCj1ZQNwD0ZcqG6UUp1Kqdn4MWKAxkAbCM2QEZE3RGSXGPkE7uhRvkxEdovIPhFZb5ZFiMhTInLAjKF/o1ne1uO4L4jI0+brp0XkYTHyThSKyBIz/n3eyTYDHd9L5zdEZIep55+m5/AFwLXAb8271Anm4z3zM20SkSnm8dnmHe4OEflFP9/Fj0TkHvP1/4nIh+bry8xwH4jIKvPzHxSRh3p+BhH5TxHZBizsUR5q6vmGiISLyDvmZzgoIl8awt8pQESeEZFfnqVdm4g8ZH7+D0RkvjkKKewxKgnp8XfcIyKX9HGeKOAl4A6l1Gal1A+AWhH5z776VUrVKKV2YDh8aUYh2kBohsNtSqm5wDzgHhGJF5FE4DHgRqXUOcBNZtsHMaKFzlRKzQI+HMT5Y4FLge8Bb2GEMZ4OzBSR2UPQ+ZpS6jxTTx6Gx+mnGOEH/l0pNVspVYBxl/sd8zP9EPirefwfMALtnQdU99PHRmCx+XoeECFGvKpFwCbzjvoh8/PMBs4TkZOhq8MxYvqfr5TabJZFmJ/5BaXUY8AyoFIpdY5Sagbw3iA/eyBGILmjSqmfnqVtOPCx+flbgV8CVwDXAycv7ncBKKVmAquAZ0QkpOdJlFItSqnF5nd8suw+pVRfQeQ0YwBtIDTD4R4R2YcRDz8dI77LAmCjMmLOo5Q6Ga/+cuAvJw9USjUO4vxvKcPF/wBwQhmxZtzAISBrCDpnmCOCA8BXMIzMaYgRmfYC4BUR2Qs8ipEYCYwggC+ar5/rp49dwFwRiQRswBYMQ7EY2ASch3HxrVVGHoHnMXJEALgwAh/25E3gKaXUs+b7A8Dl5h3+YqVU8yA/+6MYxue/BtHWzinDcwDYoJRymK+zzPJFmN+BUuoIRlKaSYPUohmjaAOhGRIicjHGRX+heWe+ByOCqtB3GOH+ynuWhfSqs5nP7h6vT74/ueg50PEneRq427zr/Y9+2gUATeZo4uRjaj86z8C8kBYDtwKfYhiFSzAibObRd7jlk3QppVy9yj4BrhIxwnIqpY4CczEu1r8SkcHejX8KXNL7Lr8fHOpUzJ3u79w0yie/74E+x6AQkbvMab295shKM8rRBkIzVKKBRqVUhzlXv8As3wIsESNiJCISZ5avA+4+ebCcyi18QkSmikgAxlTGUBnM8ZFAlTnl85Ue5a1mHcrIZ1EkIjeZ+kREzjHbfYIRHZZex/dmI8bU1EYMA/EtYK950d2G8b0kiLEQvQrYMMC5fgbUY05zmRfSDqXU3zEWc88d4NiePAG8izEy8kRY/42Y34GITAIyMIK/DRql1F96GGG9AD0G0AZCM1TeAwJFZD/wC4xpJpSRW+AO4DVz+ukls/0vgVhzgXUfxt01GHkR3sZYk6gaho7BHP8gxgX6fYzIpSf5B/Dv5mLrBIwL32pT3yFOpXT9LnCXiOzAMIz9sQljWmqLUuoE0GWWoYxsaD8GPsLIDbxbKXW2MNr3AiEi8htgJrDdnP76Ccb3OSiUEZJ9N/CcaUgDOX1ENhT+CljM6bqXgK8rpYZ7LgBEJEVEyjFyif9URMrNhW7NKEFHc9Voxjgi8jHwQ6XUzgHaJGKMavyernawiEgxME8pVedvLZ9X9AhCoxn7NABPn9yS2huzfBPGSGbUY27z3QtYOT3HuMbH6BGERqPRaPpEjyA0Go1G0yfaQGg0Go2mT7SB0Gg0Gk2faAOh0Wg0mj7RBkKj0Wg0ffL/AfDfg8IalflHAAAAAElFTkSuQmCC\n", - "text/plain": [ - "
" - ] - }, - "metadata": { - "needs_background": "light" - }, - "output_type": "display_data" - } - ], - "source": [ - "for time in [1, 100]:\n", - " seaborn.distplot(np.array(forward_works[time]), hist=False, label = f\"--> {time} annealing steps\")\n", - " seaborn.distplot(-np.array(backward_works[time]), hist=False, label = f\"<--{time} annealing steps\")\n", - "plt.title(f\"benzene --> fluorobenzene solvent annealing\")\n", - "plt.xlabel(f\"accumulated works [kJ mol^-1]\")\n", - "plt.ylabel(f\"frequency\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.7" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} From 9924e5bb9c4a317a8cec045207a4339437b85e8b Mon Sep 17 00:00:00 2001 From: John Chodera Date: Wed, 15 Apr 2020 08:22:22 -0700 Subject: [PATCH 147/152] Address helpful comments from @dominicrufa --- openmmtools/integrators.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 3c3db05c6..06b377906 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -1985,7 +1985,7 @@ def _add_global_variables(self): steps at endstates. """ super()._add_global_variables() - self.addGlobalVariable('n_steps_eq', self._n_steps_eq) + self.addGlobalVariable('n_steps_eq', self._n_steps_eq) # number of steps per nonequilibrium switching phase (forward or backward) def _add_integrator_steps(self): """ @@ -2029,12 +2029,12 @@ def _add_alchemical_perturbation_step(self): # Store initial potential energy self.addComputeGlobal("Eold", "energy") - # Update lambda and increment that tracks updates. - lambda_control_expression = "lambda"\ - " + delta_lambda*step((step+0.5)-n_steps_eq)*step((n_steps_eq+n_steps_neq) - (step+0.5))"\ - " - delta_lambda*step((step+0.5)-(n_steps_eq+n_steps_neq+n_steps_eq))*step(n_steps_per_cycle - (step+0.5));"\ - "delta_lambda = 1/n_lambda_steps;" # Note that there may be multiple H per integrator string, so we correct for this here - self.addComputeGlobal('lambda', lambda_control_expression) + # Compute lambda increment (only nonzero in forward or backward switching phases) + lambda_increment_expression = "lambda + delta_lambda*is_forward_switch - delta_lambda*is_backward_switch;"\ + "is_forward_switch = step((step+0.5)-n_steps_eq)*step((n_steps_eq+n_steps_neq) - (step+0.5));"\ # logic to identify forward switching steps + "is_backward_switch = step((step+0.5)-(n_steps_eq+n_steps_neq+n_steps_eq))*step(n_steps_per_cycle - (step+0.5));"\ # logic to identify backward switching steps + "delta_lambda = 1/n_lambda_steps;" # there may be multiple H per integrator string, so we need to use n_lambda_steps instead of n_steps_neq + self.addComputeGlobal('lambda', lambda_increment_expression) # increment lambda self.addComputeGlobal('lambda_step', 'lambda_step + 1') # Update all slaved alchemical parameters From fa3fd8098ac345bc46fd6d14d7f5c0730f19a698 Mon Sep 17 00:00:00 2001 From: dominicrufa Date: Fri, 17 Apr 2020 12:35:20 -0400 Subject: [PATCH 148/152] fixing string syntax error and make 'cycle' variable consistent --- openmmtools/integrators.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 06b377906..996b2bd60 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -1971,12 +1971,12 @@ def __init__(self, { will cause Metropolization, and must be followed later by a }. """ # Check that a valid set of steps has been specified - nsteps_per_period = nsteps_eq + nsteps_neq + nsteps_eq + nsteps_neq - if nsteps_per_period <= 0: - raise ValueError(f'nsteps_per_period = {nsteps_per_period} must be > 0') + n_steps_per_cycle = 2*nsteps_eq + 2*nsteps_neq + if n_steps_per_cycle <= 0: + raise ValueError(f'nsteps_per_period = {n_steps_per_cycle} must be > 0') self._n_steps_eq = nsteps_eq # store number of equilibration steps to dwell within lambda = 0 or 1 when reached - self._n_steps_per_cycle = nsteps_eq + nsteps_neq + nsteps_eq + nsteps_neq + self._n_steps_per_cycle = n_steps_per_cycle super().__init__(alchemical_functions, splitting, nsteps_neq=nsteps_neq, **kwargs) def _add_global_variables(self): @@ -2030,10 +2030,13 @@ def _add_alchemical_perturbation_step(self): self.addComputeGlobal("Eold", "energy") # Compute lambda increment (only nonzero in forward or backward switching phases) - lambda_increment_expression = "lambda + delta_lambda*is_forward_switch - delta_lambda*is_backward_switch;"\ - "is_forward_switch = step((step+0.5)-n_steps_eq)*step((n_steps_eq+n_steps_neq) - (step+0.5));"\ # logic to identify forward switching steps - "is_backward_switch = step((step+0.5)-(n_steps_eq+n_steps_neq+n_steps_eq))*step(n_steps_per_cycle - (step+0.5));"\ # logic to identify backward switching steps - "delta_lambda = 1/n_lambda_steps;" # there may be multiple H per integrator string, so we need to use n_lambda_steps instead of n_steps_neq + is_forward_switch = "step((step+0.5)-n_steps_eq)*step((n_steps_eq+n_steps_neq) - (step+0.5))" #logic: define bool forward switch + is_backward_switch = "step((step+0.5)-(n_steps_eq+n_steps_neq+n_steps_eq))*step(n_steps_per_cycle - (step+0.5))" #logic: define bool backward switch + lambda_increment_expression = f"lambda + delta_lambda*is_forward_switch - delta_lambda*is_backward_switch;" + lambda_increment_expression += f"is_forward_switch = {is_forward_switch};" + lambda_increment_expression += f"is_backward_switch = {is_backward_switch};" + lambda_increment_expression += "delta_lambda = 1/n_lambda_steps;" + self.addComputeGlobal('lambda', lambda_increment_expression) # increment lambda self.addComputeGlobal('lambda_step', 'lambda_step + 1') From 3cab2654d2e5bdee671018ebb79c717cc6d00d70 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Mon, 20 Apr 2020 20:58:11 -0700 Subject: [PATCH 149/152] Fix an issue with accidentally resetting PeriodicNonequilibriumIntegrator --- openmmtools/integrators.py | 2 -- openmmtools/tests/test_integrators.py | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 996b2bd60..4934c3262 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -1995,8 +1995,6 @@ def _add_integrator_steps(self): self.beginIfBlock('step = 0') self.addConstrainPositions() self.addConstrainVelocities() - self._add_reset_protocol_work_step() - self._add_alchemical_reset_step() self.endBlock() # Main body diff --git a/openmmtools/tests/test_integrators.py b/openmmtools/tests/test_integrators.py index 49121c434..c4cdfef59 100755 --- a/openmmtools/tests/test_integrators.py +++ b/openmmtools/tests/test_integrators.py @@ -774,7 +774,7 @@ def run_alchemical_langevin_integrator(nsteps=0, splitting="O { V R H R V } O"): if nsigma > NSIGMA_MAX: raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) -def test_periodic_langevin_integrator(splitting="V R H O R V", ncycles=40, nsteps_neq=1000, nsteps_eq=1000): +def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nsteps_neq=1000, nsteps_eq=1000): """ Test PeriodicNonequilibriumIntegrator From 141ac5fd5b3936eed2edbe3942b28d95a9fddf1a Mon Sep 17 00:00:00 2001 From: John Chodera Date: Tue, 21 Apr 2020 10:36:33 -0700 Subject: [PATCH 150/152] Ensure alchemical parameters are correctly set at beginning of nonequilibrium periodic integration cycle --- openmmtools/integrators.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 4934c3262..39120aee6 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -1644,7 +1644,7 @@ def reset(self): Manually reset protocol work and other statistics. """ self.reset_protocol_work() - super(NonequilibriumLangevinIntegrator, self).reset() + super().reset() class AlchemicalNonequilibriumLangevinIntegrator(NonequilibriumLangevinIntegrator): """Allows nonequilibrium switching based on force parameters specified in alchemical_functions. @@ -1876,14 +1876,14 @@ def _add_integrator_steps(self): if self._n_steps_neq == 0: # If nsteps = 0, we need to force execution on the first step only. self.beginIfBlock('step = 0') - super(AlchemicalNonequilibriumLangevinIntegrator, self)._add_integrator_steps() + super()._add_integrator_steps() self.addComputeGlobal("step", "step + 1") self.endBlock() else: #call the superclass function to insert the appropriate steps, provided the step number is less than n_steps self.beginIfBlock("step >= 0") self.beginIfBlock("step < n_steps_per_cycle") - super(AlchemicalNonequilibriumLangevinIntegrator, self)._add_integrator_steps() + super()._add_integrator_steps() self.addComputeGlobal("step", "step + 1") self.endBlock() self.endBlock() @@ -1993,13 +1993,14 @@ def _add_integrator_steps(self): """ # First step: Constrain positions and velocities and reset work accumulators and alchemical integrators self.beginIfBlock('step = 0') + self._add_update_alchemical_parameters_step() # sets alchemical parameters based on master lambda self.addConstrainPositions() self.addConstrainVelocities() self.endBlock() # Main body self.beginIfBlock("step >= 0") - super(AlchemicalNonequilibriumLangevinIntegrator, self)._add_integrator_steps() + NonequilibriumLangevinIntegrator._add_integrator_steps(self) # includes H step which updates alchemical state and accumulates work self.addComputeGlobal("step", "step + 1") self.endBlock() @@ -2014,6 +2015,7 @@ def _add_integrator_steps(self): self._add_reset_protocol_work_step() self._add_alchemical_reset_step() # sets step to 0 self.endBlock() + def _add_alchemical_perturbation_step(self): """ Add alchemical perturbation step, accumulating protocol work. From fb672f3acea0fb21dfe15056d93ace6e0a80f9cd Mon Sep 17 00:00:00 2001 From: John Chodera Date: Tue, 21 Apr 2020 10:40:29 -0700 Subject: [PATCH 151/152] Use more robust scheme to initialize PeriodicNonequilibriumIntegrator --- openmmtools/integrators.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/openmmtools/integrators.py b/openmmtools/integrators.py index 39120aee6..be419ecde 100644 --- a/openmmtools/integrators.py +++ b/openmmtools/integrators.py @@ -1993,9 +1993,10 @@ def _add_integrator_steps(self): """ # First step: Constrain positions and velocities and reset work accumulators and alchemical integrators self.beginIfBlock('step = 0') - self._add_update_alchemical_parameters_step() # sets alchemical parameters based on master lambda self.addConstrainPositions() self.addConstrainVelocities() + self._add_reset_protocol_work_step() + self._add_alchemical_reset_step() # set alchemical parameters too self.endBlock() # Main body @@ -2004,7 +2005,7 @@ def _add_integrator_steps(self): self.addComputeGlobal("step", "step + 1") self.endBlock() - # Reset step counter + # We allow this integrator to cycle instead of halting at the final step self.beginIfBlock("step >= n_steps_per_cycle") self.addComputeGlobal("step", "0") self.addComputeGlobal("lambda_step", "0") From 6f865a2ccf18b0a01a95ba853d995ece66ceb0d8 Mon Sep 17 00:00:00 2001 From: John Chodera Date: Mon, 4 May 2020 09:46:19 -0700 Subject: [PATCH 152/152] Update neq integrator tests to generate trajectory. --- openmmtools/tests/test_integrators.py | 46 ++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/openmmtools/tests/test_integrators.py b/openmmtools/tests/test_integrators.py index c4cdfef59..c1da9b249 100755 --- a/openmmtools/tests/test_integrators.py +++ b/openmmtools/tests/test_integrators.py @@ -774,7 +774,7 @@ def run_alchemical_langevin_integrator(nsteps=0, splitting="O { V R H R V } O"): if nsigma > NSIGMA_MAX: raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) -def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nsteps_neq=1000, nsteps_eq=1000): +def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nsteps_neq=1000, nsteps_eq=1000, write_trajectory=False): """ Test PeriodicNonequilibriumIntegrator @@ -782,12 +782,14 @@ def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nst ---------- integrator_flavor : openmmtools.integrator.PeriodicNonequilibriumIntegrator (or subclass) integrator to run - ncycles : int, optional, default=20 + ncycles : int, optional, default=40 number of cycles - nsteps_neq : int, optional, default=10 + nsteps_neq : int, optional, default=1000 number of forward/backward annealing steps - nsteps_eq : int, optional, default=10 + nsteps_eq : int, optional, default=1000 number of equilibration steps to run at endstates before annealing + write_trajectory : bool, optional, default=True + If True, will generate a PDB file that contains the harmonic oscillator trajectory """ #max deviation from the calculated free energy NSIGMA_MAX = 6 @@ -802,10 +804,11 @@ def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nst period = unit.sqrt(mass/K) # period of harmonic oscillator timestep = period / 20.0 collision_rate = 1.0 / period - dF_analytical = 1.0 + dF_analytical = 5.0 parameters = dict() - parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, 1 * sigma) - parameters['testsystems_HarmonicOscillator_U0'] = (0 * kT, 1 * kT) + displacement = 10 * sigma + parameters['testsystems_HarmonicOscillator_x0'] = (0 * sigma, displacement) + parameters['testsystems_HarmonicOscillator_U0'] = (0 * kT, 5 * kT) integrator_kwargs = {'temperature':temperature, 'collision_rate': collision_rate, 'timestep': timestep, @@ -816,6 +819,7 @@ def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nst testsystem = testsystems.HarmonicOscillator(K=K, mass=mass) system = testsystem.system positions = testsystem.positions + topology = testsystem.topology # Create integrator from openmmtools.integrators import PeriodicNonequilibriumIntegrator @@ -831,6 +835,32 @@ def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nst nsteps_per_cycle = nsteps_eq + nsteps_neq + nsteps_eq + nsteps_neq assert integrator.getGlobalVariableByName("n_steps_per_cycle") == nsteps_per_cycle + if write_trajectory: + from simtk.openmm.app import PDBFile + filename = 'neq-trajectory.pdb' + print(f'Writing trajectory to {filename}') + with open(filename, 'wt') as outfile: + # Write reference + import copy + pos1 = copy.deepcopy(positions) + pos2 = copy.deepcopy(positions) + pos2[0,0] += displacement + PDBFile.writeModel(topology, pos1, outfile) + PDBFile.writeModel(topology, pos2, outfile) + + interval = 10 + PDBFile.writeModel(topology, positions, outfile, modelIndex=0) + for step in range(0,2*nsteps_per_cycle,interval): + integrator.step(interval) + positions = context.getState(getPositions=True).getPositions(asNumpy=True) + PDBFile.writeModel(topology, positions, outfile, modelIndex=step) + + PDBFile.writeModel(topology, pos1, outfile) + PDBFile.writeModel(topology, pos2, outfile) + + # Reset the integrator + integrator.reset() + step = 0 for cycle in range(2): # eq (0) @@ -890,7 +920,7 @@ def test_periodic_langevin_integrator(splitting="H V R O R V H", ncycles=40, nst assert np.isclose(integrator.getGlobalVariableByName("lambda"), 0.0) print("analytical DeltaF: {:12.4f}, DeltaF: {:12.4f}, dDeltaF: {:12.4f}, nsigma: {:12.1f}".format(dF_analytical, dF, ddF, nsigma)) if nsigma > NSIGMA_MAX: - raise Exception("The free energy difference for the nonequilibrium switching for splitting '%s' and %d steps is not zero within statistical error." % (splitting, nsteps)) + raise Exception(f"The free energy difference for the nonequilibrium switching for splitting {splitting} is not zero within statistical error.") # Clean up del context