### Verify Installation Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/install.rst.txt Import OQuPy in an interactive session to check the installed version. ```python >>> import oqupy >>> oqupy.__version__ ``` ```none '0.5.0' ``` -------------------------------- ### Install OQuPy Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/install.rst.txt Install the OQuPy package using pip. ```bash $ python3 -m pip install oqupy ``` -------------------------------- ### Import OQuPy and dependencies Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tebd.rst.txt Initial setup for the OQuPy environment and plotting tools. ```python import sys sys.path.insert(0,'..') import oqupy import numpy as np import matplotlib.pyplot as plt ``` -------------------------------- ### Importing Required Packages Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_gradient/pt_gradient.rst.txt Initial setup for the OQuPy environment, including path configuration and necessary library imports. ```python import sys sys.path.insert(0,'..') import numpy as np import oqupy from oqupy import operators as op import matplotlib.pyplot as plt ``` -------------------------------- ### Initialize Process Tensor and Backend Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/pt_tempo.html Handles the setup of process tensors and backend configuration based on provided parameters and bath properties. ```python self._process_tensor = None if process_tensor_file or isinstance(process_tensor_file, Text): if isinstance(process_tensor_file, Text): filename = process_tensor_file else: filename = None self._init_file_process_tensor(filename, overwrite) else: self._init_simple_process_tensor() if backend_config is None: self._backend_config = PT_TEMPO_BACKEND_CONFIG else: self._backend_config = backend_config self._coupling_comm = self._bath._coupling_comm self._coupling_acomm = self._bath._coupling_acomm tmp_num_steps = int((end_time - self._start_time)/self._parameters.dt) assert tmp_num_steps >= 2, \ "Parameter `end_time` must be more than two times steps " \ + "larger than the parameter `start_time`!" self._num_steps = tmp_num_steps self._backend_instance = None self._init_pt_tempo_backend() ``` -------------------------------- ### Define Spin-Boson Model Source: https://oqupy.readthedocs.io/en/latest/pages/tutorials/parameters.html Setup the system, bath, and environment parameters for a spin-boson model. ```python sigma_x = oqupy.operators.sigma('x') sigma_y = oqupy.operators.sigma('y') sigma_z = oqupy.operators.sigma('z') sigma_m = oqupy.operators.sigma('-') omega_cutoff = 2.5 alpha = 0.8 T = 0.2 correlations = oqupy.PowerLawSD(alpha=alpha, zeta=1, cutoff=omega_cutoff, cutoff_type='exponential', temperature=T) bath = oqupy.Bath(0.5 * sigma_z, correlations) Omega = 2.0 Gamma = 0.02 system = oqupy.System(0.5 * Omega * sigma_x, gammas=[Gamma], lindblad_operators=[sigma_m], # incoherent dissipation ) t_start = 0.0 t_end = 5.0 ``` -------------------------------- ### Spin-boson model simulation script Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/quickstart.rst.txt A complete example script demonstrating the definition of system parameters, bath correlations, and the execution of a TEMPO computation. ```python Omega = 1.0 omega_cutoff = 5.0 alpha = 0.3 system = oqupy.System(0.5 * Omega * sigma_x) correlations = oqupy.PowerLawSD(alpha=alpha, zeta=1, cutoff=omega_cutoff, cutoff_type='exponential') bath = oqupy.Bath(0.5 * sigma_z, correlations) tempo_parameters = oqupy.TempoParameters(dt=0.1, tcut=3.0, epsrel=10**(-4)) dynamics = oqupy.tempo_compute(system=system, bath=bath, initial_state=up_density_matrix, start_time=0.0, end_time=15.0, parameters=tempo_parameters, unique=False) t, s_z = dynamics.expectations(0.5*sigma_z, real=True) plt.plot(t, s_z, label=r'$\alpha=0.3$') plt.xlabel(r'$t\,\Omega$') plt.ylabel(r'$\langle\sigma_z\rangle$') plt.legend() ``` -------------------------------- ### Define Bath and Parameters for PT-TEMPO Source: https://oqupy.readthedocs.io/en/latest/pages/tutorials/parameters.html Setup the environment and bath parameters required for a PT-TEMPO computation. ```python alpha = 0.25 # Doesn't affect PT computation nu_c = 227.9 T = 39.3 start_time = 0.0 dt = 1e-3 epsrel = 1e-8 end_time = 250 * dt # 251 steps starting from t=0.0 correlations = oqupy.PowerLawSD(alpha=alpha, zeta=1, cutoff=nu_c, cutoff_type='gaussian') bath = oqupy.Bath(oqupy.operators.sigma("z")/2.0, correlations) ``` -------------------------------- ### Check Python Version Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/install.rst.txt Verify that Python 3.10 or higher is installed on the system. ```bash $ python3 --version Python 3.10.14 ``` -------------------------------- ### Initialize open system state Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tebd.rst.txt Create an AugmentedMPS for the open spin chain starting in a fully mixed state. ```python initial_augmented_mps_B = oqupy.AugmentedMPS([mixed_dm, mixed_dm, mixed_dm, mixed_dm, mixed_dm]) ``` -------------------------------- ### Get Unitary Propagators Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/system.html Prepares propagator functions for the system based on the Hamiltonian. ```python def get_unitary_propagators(self, dt, start_time, subdiv_limit, epsrel): """Prepare propagator functions for the system. """ first_step = expm(-1j*self._hamiltonian*dt/2.0) second_step = expm(-1j*self._hamiltonian*dt/2.0) def propagators(step: int): """Create the system propagators (first and second half) for the time step `step` """ return first_step, second_step return propagators ``` -------------------------------- ### Compute System Dynamics Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/system_dynamics.html Example of calculating system dynamics using a process tensor and system operators. ```python dynamics = compute_dynamics( system=system, process_tensor=process_tensor, control=control, start_time=start_time, initial_state=initial_state, dt=dt, num_steps=max_step, progress_type='silent') _, corr = dynamics.expectations(operators[-1]) ret_correlations = corr[last_times] return ret_correlations ``` -------------------------------- ### Prepare TEMPO Backend Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/tempo.html Internal method to initialize the backend instance with system propagators and correlation coefficients. ```python def _prepare_backend(self): """Create and initialize the TEMPO backend. """ dim = self._dimension def coeffs(k): shape = "upper-triangle" if k==0 else "square" return self._correlations.correlation_2d_integral( self._dt, k * self._dt, shape=shape, matsubara=True) operators = (-self._bath.coupling_operator.diagonal(), self._bath.coupling_operator.diagonal(), np.zeros((dim,))) unitary_transform = self._bath.unitary_transform # ToDo: Unitary transform is not used. Check that GibbsTempo also works # with non-diagonal coupling operators!!! if not np.allclose(unitary_transform,np.identity(self.dimension)): raise NotImplementedError( "GibbsTempo is currently implemented only for diagonal "\ + "bath coupling operators. See GitHub Issue #???.") epsrel = self._parameters.epsrel max_step = self._parameters.n_steps propagators = self._system.get_unitary_propagators( - 1j * self._dt, 0, 0, 0) self._backend_instance = TIBaseBackend( dim, epsrel, propagators(1)[0], coeffs, operators, max_step=max_step, config=self._backend_config) ``` -------------------------------- ### Fidelity output Source: https://oqupy.readthedocs.io/en/latest/pages/tutorials/pt_gradient/pt_gradient.html Example output of the fidelity calculation. ```text The fidelity is 0.9012528539245532. ``` -------------------------------- ### Check OQuPy version Source: https://oqupy.readthedocs.io/en/latest/pages/tutorials/pt_tempo.html Verify the currently installed version of the OQuPy package. ```python oqupy.__version__ ``` -------------------------------- ### Import OQuPy and dependencies Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/mf_tempo.rst.txt Initializes the environment by importing necessary libraries and setting the path. ```python import sys sys.path.insert(0,'..') import oqupy import numpy as np import matplotlib.pyplot as plt ``` -------------------------------- ### Check Pip Version Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/install.rst.txt Verify that pip version 23.0 or higher is installed. ```bash $ python3 -m pip --version pip 23.3.1 from /home/gefux/anaconda3/envs/oqupy-ci/lib/python3.10/site-packages/pip (python 3.10) ``` -------------------------------- ### Plot Label Output Source: https://oqupy.readthedocs.io/en/latest/pages/tutorials/bath_dynamics.html Example of the return value from a matplotlib label command. ```text Text(0, 0.5, '$\Delta Q ( \Omega, t)$') ``` -------------------------------- ### Initialize PT-TEMPO Backend Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/pt_tempo.html Configures the PtTempoBackend instance with degeneracy maps and influence parameters. ```python def _init_pt_tempo_backend(self): """Create and initialize the pt-tempo backend. """ if self._unique: sum_north = np.ones(np.max(self._bath.north_degeneracy_map)+1, dtype=float) sum_west = np.ones(np.max(self._bath.west_degeneracy_map)+1, dtype=float) degeneracy_maps = [self._bath.north_degeneracy_map, self._bath.west_degeneracy_map] else: sum_north = np.ones(self._dimension**2, dtype=float) sum_west = np.ones(self._dimension**2, dtype=float) degeneracy_maps = None dkmax = self._parameters.dkmax if dkmax is None: dkmax = self._num_steps self._backend_instance = PtTempoBackend( dimension=self._dimension, influence=self._influence, process_tensor=self._process_tensor, sum_north=sum_north, sum_west=sum_west, num_steps=self._num_steps, dkmax=dkmax, epsrel=self._parameters.epsrel, config=self._backend_config, degeneracy_maps=degeneracy_maps) ``` -------------------------------- ### oqupy.pt_tebd.PtTebd.initialize Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/pt_tebd.html Prepares the propagator, backend, and results structure for the PT-TEBD computation. ```APIDOC ## oqupy.pt_tebd.PtTebd.initialize ### Description Initializes the propagator, the PT-TEBD backend, and the results dictionary to prepare for the simulation steps. ``` -------------------------------- ### Get Initial Tensor Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/process_tensor.html Retrieves the initial system state, which may be correlated. ```python def get_initial_tensor(self) -> ndarray: """ Get the (possibly correlated) initial system state. """ return _get_data_and_shape(step=0, data=self._initial_tensor_data, shape=self._initial_tensor_shape) ``` -------------------------------- ### Parse system parameters and initialize backend Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/tempo.html Parses input system tuples and prepares the MeanFieldTempo backend instance. ```python # List of tuples, one for each system: (system, initial_state, # bath, hs_dim) parsed_system_tuple_list = [_tempo_physical_input_parse( True, system, initial_state, bath) for system, initial_state, bath in zip( mean_field_system.system_list, initial_state_list, bath_list)] parsed_parameter_names = ["system", "initial_state", "bath", "hs_dim"] # Dictionary of keys from parsed_parameter_names. The items are # a lists of systems (Key = "system") and corresponding lists of # values (Key = "initial_state", "bath", "hs_dim"). Considered to be # 'parameters' for the overall (mean-field system dynamics) computation. self._parsed_parameters_dict = {} for i, parsed_parameter_name in enumerate(parsed_parameter_names): self._parsed_parameters_dict[parsed_parameter_name] = [] for parsed_parameter_tuple in parsed_system_tuple_list: self._parsed_parameters_dict[parsed_parameter_name].append( parsed_parameter_tuple[i]) # Check initial field can be cast to complex, and start time float self._initial_field = check_convert(initial_field, complex, "initial_field") self._start_time = check_convert(start_time, float, "start_time") # Prepare the MeanFieldTempo backend self._prepare_backend() ``` ```python def _prepare_backend(self): """Create and initialize the MeanFieldTempo backend. """ initial_state_list = \ self._parsed_parameters_dict["initial_state"] hs_dim_list = \ self._parsed_parameters_dict["hs_dim"] initial_field = self._initial_field influence_list = [self._get_influence(bath) for bath in self._parsed_parameters_dict["bath"]] unitary_transform_list = [bath.unitary_transform for bath in self._parsed_parameters_dict["bath"]] propagators_list = [system.get_propagators( self._parameters.dt, self._start_time, self._parameters.subdiv_limit, self._parameters.liouvillian_epsrel) for system in self._parsed_parameters_dict["system"]] compute_field = self._compute_field compute_field_derivative = self._compute_field_derivative if self._unique: sum_north_list = [np.ones(np.max(bath.north_degeneracy_map)+1, dtype=float) for bath in self._parsed_parameters_dict["bath"]] sum_west_list = [np.ones(np.max(bath.west_degeneracy_map)+1, dtype=float) for bath in self._parsed_parameters_dict["bath"]] degeneracy_maps_list = [[bath.north_degeneracy_map, bath.west_degeneracy_map] for bath in self._parsed_parameters_dict["bath"]] else: sum_north_list = [np.ones(dim**2, dtype=float) for dim in self._parsed_parameters_dict["hs_dim"]] sum_west_list = [np.ones(dim**2, dtype=float) for dim in self._parsed_parameters_dict["hs_dim"]] degeneracy_maps_list = [None for bath in self._parsed_parameters_dict["bath"]] # N.B. For now all baths constrained to have same memory length dkmax = self._parameters.dkmax epsrel = self._parameters.epsrel self._backend_instance = MeanFieldTempoBackend( initial_state_list, initial_field, influence_list, unitary_transform_list, propagators_list, compute_field, compute_field_derivative, sum_north_list, sum_west_list, dkmax, epsrel, config=self._backend_config, degeneracy_maps_list=degeneracy_maps_list, dim_list=hs_dim_list, ) ``` -------------------------------- ### Get Cap Tensor Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/process_tensor.html Retrieves the cap tensor for a specific time step. ```python def get_cap_tensor(self, step: int) -> ndarray: """ Get the cap tensor (vector) to terminate the PT-MPO at time step `step`. """ length = len(self._cap_tensors) if step >= length or step < 0: return None return self._cap_tensors[step] ``` -------------------------------- ### Initialize TEMPO backend Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/tempo.html Configures and initializes the backend instance required for tensor network propagation. ```python def _prepare_backend(self): """Create and initialize the TEMPO backend. """ dim = self._dimension initial_state = self._initial_state.reshape(dim**2) influence = self._influence unitary_transform = self._bath.unitary_transform propagators = self._system.get_propagators( self._parameters.dt, self._start_time, self._parameters.subdiv_limit, self._parameters.liouvillian_epsrel) if self._unique: sum_north = np.ones(np.max(self._bath.north_degeneracy_map)+1, dtype=float) sum_west = np.ones(np.max(self._bath.west_degeneracy_map)+1, dtype=float) degeneracy_maps = [self._bath.north_degeneracy_map, self._bath.west_degeneracy_map] else: sum_north = np.ones(dim**2, dtype=float) sum_west = np.ones(dim**2, dtype=float) degeneracy_maps = None dkmax = self._parameters.dkmax epsrel = self._parameters.epsrel self._backend_instance = TempoBackend( initial_state, influence, unitary_transform, propagators, sum_north, sum_west, dkmax, epsrel, config=self._backend_config, degeneracy_maps=degeneracy_maps, dim=dim) ``` -------------------------------- ### Get Initial Tensor Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/process_tensor.html Retrieves the initial system state, which may be correlated. ```python def get_initial_tensor(self) -> ndarray: """ Get the (possibly correlated) initial system state. """ return self._initial_tensor ``` -------------------------------- ### Computation Progress Output Source: https://oqupy.readthedocs.io/en/latest/pages/tutorials/bath_dynamics.html Example of the console output generated during the correlation computation process. ```text --> Compute correlations: 100.0% 100 of 100 [########################################] 00:00:07 Elapsed time: 7.7s ``` -------------------------------- ### Prepare the PT-TEBD simulation Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tebd.rst.txt Initialize the PtTebd object with the system chain and parameters. ```python pt_tebd_closed = oqupy.PtTebd( initial_augmented_mps=initial_augmented_mps_A, system_chain=system_chain, process_tensors=[None, None, None, None, None], parameters=pt_tebd_params, dynamics_sites=[0, 1, 2, 3, 4]) ``` -------------------------------- ### Initialize SystemChain Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/system.html Constructor for a 1D chain of systems, initializing site Liouvillians and nearest-neighbor Liouvillians based on Hilbert space dimensions. ```python def __init__( self, hilbert_space_dimensions: List[int], name: Optional[Text] = None, description: Optional[Text] = None) -> None: """Create a SystemChain object. """ tmp_hs_dims = np.array(hilbert_space_dimensions, int) assert len(tmp_hs_dims.shape) == 1 assert len(hilbert_space_dimensions) >= 1 assert np.all(tmp_hs_dims > 0) self._hs_dims = tmp_hs_dims self._site_liouvillians = [] for hs_dim in self._hs_dims: self._site_liouvillians.append( np.zeros((hs_dim**2, hs_dim**2), dtype=NpDtype)) self._nn_liouvillians = [] for hs_dim_l, hs_dim_r in zip(self._hs_dims[:-1], self._hs_dims[1:]): self._nn_liouvillians.append( np.zeros((hs_dim_l**2 * hs_dim_r**2, hs_dim_l**2 * hs_dim_r**2), dtype=NpDtype)) super().__init__(name, description) ``` -------------------------------- ### Define system matrices Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/n_time_correlations.rst.txt Setup of the matrices representing the three-level chromophore system operators. ```python P_1 = np.array([[0., 0., 0.], [0., 1., 0.], [0., 0., 0.]], dtype=complex) P_2 = np.array([[0., 0., 0.], [0., 0., 0.], [0., 0., 1.]], dtype=complex) sigma_min = np.array([[0., 0., 0.], [0., 0., 1.], [0., 0., 0.]], dtype=complex) sigma_plus = np.array([[0., 0., 0.], [0., 0., 0.], [0., 1., 0.]], dtype=complex) dip_02 = np.array([[0., 0., 1.], [0., 0., 0.], [1., 0., 0.]], dtype=complex) ``` -------------------------------- ### Tempo.__init__ Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/tempo.html Initializes a new Tempo object with the specified system, bath, and computation parameters. ```APIDOC ## Tempo.__init__(system, bath, parameters, backend_config=None, name=None, description=None) ### Description Creates a Tempo object to manage the simulation of an open quantum system. ### Parameters - **system** (System) - Required - The quantum system to simulate. - **bath** (Bath) - Required - The bath object, initiated with a CustomSD or derived correlations object. - **parameters** (GibbsParameters) - Required - The parameters for the GibbsTEMPO computation. - **backend_config** (dict) - Optional - The configuration of the backend. Defaults to None. - **name** (str) - Optional - An optional name for the tempo object. - **description** (str) - Optional - An optional description of the tempo object. ``` -------------------------------- ### Get Bond Dimensions Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/process_tensor.html Returns the bond dimensions of the MPS form of the process tensor. ```python def get_bond_dimensions(self) -> ndarray: """ Return the bond dimensions of the MPS form of the process tensor. """ bond_dims = [] for mpo in self._mpo_tensors: if mpo is None: bond_dims.append(0) else: bond_dims.append(mpo.shape[0]) bond_dims.append(self._mpo_tensors[-1].shape[1]) return np.array(bond_dims) ``` -------------------------------- ### Define Bath and Simulation Parameters Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/parameters.rst.txt Sets up the harmonic environment and simulation parameters for a PT-TEMPO computation. ```python alpha = 0.25 # Doesn't affect PT computation nu_c = 227.9 T = 39.3 start_time = 0.0 dt = 1e-3 epsrel = 1e-8 end_time = 250 * dt # 251 steps starting from t=0.0 correlations = oqupy.PowerLawSD(alpha=alpha, zeta=1, cutoff=nu_c, cutoff_type='gaussian') bath = oqupy.Bath(oqupy.operators.sigma("z")/2.0, correlations) ``` -------------------------------- ### Configure Bath and TEMPO Parameters Source: https://oqupy.readthedocs.io/en/latest/pages/tutorials/pt_gradient/pt_gradient.html Sets up the spectral density, bath coupling, and numerical TEMPO parameters for the process tensor computation. ```python # spectral density parameters alpha = 0.126 omega_cutoff = 3.04 temperature = 5 * 0.1309 # 1K = 0.1309/ps in natural units # numerical tempo parameters tcut = 2.0 esprel = 10**(-4) correlations = oqupy.PowerLawSD( alpha=alpha, zeta=3, cutoff=omega_cutoff, cutoff_type='gaussian', temperature=temperature) bath = oqupy.Bath(op.sigma("z")/2, correlations) tempo_params = oqupy.TempoParameters(dt=dt, tcut=tcut, epsrel=esprel) ``` -------------------------------- ### Initialize GibbsTempo Object Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/tempo.html Constructor for the GibbsTempo class, requiring a system, bath, and Gibbs parameters. ```python def __init__( self, system: System, bath: Bath, parameters: GibbsParameters, backend_config: Optional[Dict] = None, name: Optional[Text] = None, description: Optional[Text] = None) -> None: """Create a Tempo object. """ super().__init__(name, description) check_isinstance(system, System, name='system') if len(system.gammas) > 0: raise Warning('Markovian decay ignored for GibbsTempo') check_isinstance(bath, Bath, name='bath') check_isinstance(bath.correlations, CustomSD, name='bath.correlations') check_isinstance(parameters, GibbsParameters, name='parameters') self._system, self._initial_state, self._bath, self._dimension = \ _tempo_physical_input_parse(False, system, None, bath) self._parameters = parameters self._correlations = self._bath.correlations self._temperature = self._correlations.temperature self._dt = self._parameters.time_step_length(self._temperature) if backend_config is None: self._backend_config = TEMPO_BACKEND_CONFIG else: self._backend_config = backend_config self._dynamics = None self._backend_instance = None self._prepare_backend() ``` -------------------------------- ### Get Bond Dimensions Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/process_tensor.html Calculates and returns the bond dimensions of the MPS form of the process tensor. ```python def get_bond_dimensions(self) -> ndarray: """Return the bond dimensions of the MPS form of the process tensor.""" bond_dims = [] for tensor_shape in self._mpo_tensors_shape: bond_dims.append(tensor_shape[0]) bond_dims.append(self._mpo_tensors_shape[-1][1]) return np.array(bond_dims) ``` -------------------------------- ### Get MPO Tensor Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/process_tensor.html Retrieves the MPO tensor for a given time step, optionally applying transformations. ```python def get_mpo_tensor( self, step: int, transformed: Optional[bool] = True) -> ndarray: """ Get the MPO tensor for time step `step`. The axes correspond to the following legs: [0] ... past bond leg, [1] ... future bond leg, [2] ... input (from system) leg, [3] ... output (to system) leg. Applies the transformation (stored in `.transform_in` and `.transform_out`) when `transformed` is true. """ tensor = _get_data_and_shape(step, data=self._mpo_tensors_data, shape=self._mpo_tensors_shape) if transformed: if len(tensor.shape) == 3: tensor = util.create_delta(tensor, [0, 1, 2, 2]) if self._transform_in is not None: tensor = np.dot(np.moveaxis(tensor, -2, -1), self._transform_in.T) tensor = np.moveaxis(tensor, -1, -2) if self._transform_out is not None: tensor = np.dot(tensor, self._transform_out) return tensor ``` -------------------------------- ### Define multiple system configurations Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tempo.rst.txt Create a list of system objects with varying detuning parameters for batch processing. ```python deltas = [-10.0, -5.0, 0.0, 5.0, 10.0] systems = [] for delta in deltas: # NOTE: omitting "delta=delta" in the parameter definition below # would lead to all systems having the same detuning. # This is a common python pitfall. Check out # https://docs.python-guide.org/writing/gotchas/#late-binding-closures # for more information on this. def hamiltonian_t(t, delta=delta): return delta/2.0 * sigma_z \ + gaussian_shape(t, area = np.pi/2.0, tau = 0.245)/2.0 * sigma_x system = oqupy.TimeDependentSystem(hamiltonian_t) systems.append(system) ``` -------------------------------- ### Get Cap Tensor Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/process_tensor.html Retrieves the cap tensor for a specific time step, returning None if the index is out of bounds. ```python def get_cap_tensor(self, step: int) -> ndarray: """ Get the cap tensor (vector) to terminate the PT-MPO at time step `step`. """ try: tensor = _get_data_and_shape(step, data=self._cap_tensors_data, shape=self._cap_tensors_shape) except IndexError: tensor = None return tensor ``` -------------------------------- ### Initialize results dictionary Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/pt_tebd.html Internal method to set up the results storage dictionary, including bond dimensions and dynamics tracking. ```python def _init_results(self) -> None: """Initialise the results dictionary. """ pt_bond_dimensions = {} for site, pt in enumerate(self._process_tensors): if pt is not None: pt_bond_dimensions[site] = pt.get_bond_dimensions() self._results = { 'time':[], 'norm': [], 'bond_dimensions': [], 'dynamics': {}, 'pt_bond_dimensions': pt_bond_dimensions, } for sites in self._dynamics_sites: self._results['dynamics'][sites] = Dynamics(name=f"site{sites}") ``` -------------------------------- ### Get MPO Tensor Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/process_tensor.html Retrieves the MPO tensor for a given time step, optionally applying input/output transformations. ```python def get_mpo_tensor( self, step: int, transformed: Optional[bool] = True) -> ndarray: """ Get the MPO tensor for time step `step`. The axes correspond to the following legs: [0] ... past bond leg, [1] ... future bond leg, [2] ... input (from system) leg, [3] ... output (to system) leg. Applies the transformation (stored in `.transform_in` and `.transform_out`) when `transformed` is true. """ length = len(self._mpo_tensors) if step >= length or step < 0: raise IndexError("Process tensor index out of bound. ") tensor = self._mpo_tensors[step] if len(tensor.shape) == 3: tensor = util.create_delta(tensor, [0, 1, 2, 2]) if transformed is False: return tensor if self._transform_in is not None: tensor = np.dot(np.moveaxis(tensor, -2, -1), self._transform_in.T) tensor = np.moveaxis(tensor, -1, -2) if self._transform_out is not None: tensor = np.dot(tensor, self._transform_out) return tensor ``` -------------------------------- ### Initialize Tempo Object Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/quickstart.rst.txt Create a Tempo object to manage the computation of system dynamics. ```python tempo = oqupy.Tempo(system=system, bath=bath, parameters=tempo_parameters, initial_state=up_density_matrix, start_time=0.0, unique=False) ``` -------------------------------- ### Calculate number of steps Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/tempo.html Determines the required number of steps to reach a target end time from a starting step. ```python def _get_num_step(self, start_step: int, end_time: float) -> Tuple[int, int]: """Return the number of steps required from start_step to reach end_time""" end_step = int((end_time - self._start_time)/self._parameters.dt) num_step = max(0, end_step - start_step) return num_step ``` -------------------------------- ### Compute dynamics with TEMPO Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tempo.rst.txt Initialize TEMPO parameters and compute the system dynamics over a specified time interval. ```python tempo_parameters = oqupy.TempoParameters(dt=0.1, tcut=2.0, epsrel=10**(-4)) tempo_sys = oqupy.Tempo(system=system, bath=bath, initial_state=initial_state, start_time=-2.0, parameters=tempo_parameters) dynamics = tempo_sys.compute(end_time=3.0) ``` -------------------------------- ### Initialize PT-TEBD backend Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/pt_tebd.html Method to initialize the propagator, backend, and results structure for the simulation. ```python def initialize(self) -> None: """Initialize propagator, the PT-TEBD backend and results. """ self._step = self._start_step self._tebd_propagator = compute_tebd_propagator( system_chain=self._system_chain, time_step=self._parameters.dt/2.0, epsrel=self._parameters.epsrel, order=self._parameters.order) self._results = {} self._t_mps = PtTebdBackend( gammas=self._initial_augmented_mps.gammas, lambdas=self._initial_augmented_mps.lambdas, epsrel=self._parameters.epsrel, config=self._backend_config) self._init_results() self._apply_controls(step=self.step, post=False) self._append_results() ``` -------------------------------- ### Configure bosonic environment Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tebd.rst.txt Define a PowerLawSD spectral density and create a Bath object coupled to the first spin site. ```python alpha = 0.32 omega_cutoff = 4.0 temperature = 1.6 correlations = oqupy.PowerLawSD( alpha=alpha, zeta=1, cutoff=omega_cutoff, cutoff_type='exponential', temperature=temperature) bath = oqupy.Bath(sy, correlations) ``` -------------------------------- ### PowerLawSD.__init__ Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/bath_correlations.html Initializes a new PowerLawSD object representing a spectral density with a power-law form. ```APIDOC ## PowerLawSD(alpha, zeta, cutoff, cutoff_type='exponential', temperature=0.0, name=None, description=None) ### Description Creates a PowerLawSD object to model spectral density correlations of the form J(omega) = 2 * alpha * (omega^zeta / omega_c^(zeta-1)) * X(omega, omega_c). ### Parameters - **alpha** (float) - Required - The coupling strength. - **zeta** (float) - Required - The exponent (dimensionality of the environment). - **cutoff** (float) - Required - The cutoff frequency. - **cutoff_type** (str) - Optional - The cutoff type: 'hard', 'exponential', or 'gaussian'. Defaults to 'exponential'. - **temperature** (float) - Optional - The environment's temperature. Defaults to 0.0. - **name** (str) - Optional - An optional name for the correlations. - **description** (str) - Optional - An optional description of the correlations. ``` -------------------------------- ### SystemChain Constructor Source: https://oqupy.readthedocs.io/en/latest/pages/modules.html Initializes a new 1D chain of systems with specified Hilbert space dimensions. ```APIDOC ## SystemChain(hilbert_space_dimensions, name=None, description=None) ### Description Represents a 1D chain of systems with nearest neighbor interactions. ### Parameters - **hilbert_space_dimensions** (List[int]) - Required - Hilbert space dimension for each chain site. - **name** (str) - Optional - An optional name for the system chain. - **description** (str) - Optional - An optional description of the system chain. ``` -------------------------------- ### Initialize MeanFieldSystem Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/mf_tempo.rst.txt Wraps a list of TimeDependentSystemWithField objects into a MeanFieldSystem for collective dynamics. ```python system_list = [system] # a list of TimeDependentiSystemWithField objects mean_field_system = oqupy.MeanFieldSystem( system_list=system_list, field_eom=field_eom) ``` -------------------------------- ### TimeDependentSystem.__init__ Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/system.html Initializes a new TimeDependentSystem object representing a system with time-dependent Hamiltonian, gammas, and Lindblad operators. ```APIDOC ## TimeDependentSystem(hamiltonian, gammas=None, lindblad_operators=None, name=None, description=None) ### Description Creates a TimeDependentSystem object for systems without coupling to a non-Markovian bath, allowing for time-dependent Hamiltonian and Lindblad terms. ### Parameters - **hamiltonian** (Callable[[float], ndarray]) - Required - System-only Hamiltonian H(t). - **gammas** (List[Callable[[float], float]]) - Optional - The rates gamma_n(t). - **lindblad_operators** (List[Callable[[float], ndarray]]) - Optional - The Lindblad operators A_n(t). - **name** (str) - Optional - An optional name for the system. - **description** (str) - Optional - An optional description of the system. ``` -------------------------------- ### Import OQuPy and dependencies Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/n_time_correlations.rst.txt Initial imports required for OQuPy functionality, Fourier transforms, and plotting. ```python import sys sys.path.insert(0,'..') import oqupy from oqupy.system_dynamics import compute_correlations_nt import numpy as np import matplotlib.pyplot as plt from scipy.fft import fftfreq, fftshift, fft2 ``` -------------------------------- ### Define spin operators and density matrices Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tempo.rst.txt Initialize common Pauli operators and standard spin density matrices for quantum dot simulations. ```python sigma_x = oqupy.operators.sigma("x") sigma_y = oqupy.operators.sigma("y") sigma_z = oqupy.operators.sigma("z") up_density_matrix = oqupy.operators.spin_dm("z+") down_density_matrix = oqupy.operators.spin_dm("z-") mixed_density_matrix = oqupy.operators.spin_dm("mixed") ``` -------------------------------- ### oqupy.pt_tebd.PtTebd.__init__ Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/pt_tebd.html Initializes the PT-TEBD computation object with the necessary system parameters and configuration. ```APIDOC ## oqupy.pt_tebd.PtTebd.__init__ ### Description Initializes a new PtTebd instance to manage the time-evolution of an augmented Matrix Product State (MPS) using process tensors. ### Parameters - **initial_augmented_mps** (AugmentedMPS) - Required - The initial augmented MPS state. - **system_chain** (SystemChain) - Required - The system chain Liouvillians. - **process_tensors** (List[BaseProcessTensor]) - Required - List of process tensors for each site. - **parameters** (PtTebdParameters) - Required - Computation parameters. - **chain_control** (ChainControl) - Optional - Control operations. - **start_time** (float) - Optional - Starting time stamp. - **start_step** (int) - Optional - Starting time step. - **dynamics_sites** (List[Union[int, tuple]]) - Optional - Sites to record dynamics for. - **backend_config** (dict) - Optional - Backend configuration (e.g., 'parallel': 'multiprocess' or 'multithread'). ``` -------------------------------- ### PtTempo.__init__ Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/pt_tempo.html Initializes a new PtTempo object to facilitate a PT-TEMPO computation. ```APIDOC ## PtTempo(bath, start_time, end_time, parameters, unique=False, process_tensor_file=None, overwrite=False, backend_config=None, name=None, description=None) ### Description Creates a PtTempo object to manage the computation of a process tensor using the PT-TEMPO algorithm. ### Parameters - **bath** (Bath) - Required - The Bath object including the coupling operator to the system. - **start_time** (float) - Required - The start time of the computation. - **end_time** (float) - Required - The end time of the computation. - **parameters** (TempoParameters) - Required - The parameters for the PT-TEMPO computation. - **unique** (bool) - Optional - Whether to use degeneracy checking to reduce the dimension of bath tensors. - **process_tensor_file** (Union[Text, bool]) - Optional - File path or boolean for process tensor storage. - **overwrite** (bool) - Optional - Whether to overwrite existing process tensor files. - **backend_config** (Dict) - Optional - Configuration for the backend; defaults to PT_TEMPO_BACKEND_CONFIG if None. - **name** (Text) - Optional - An optional name for the object. - **description** (Text) - Optional - An optional description of the object. ``` -------------------------------- ### Configure PT-TEMPO Parameters Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/n_time_correlations.rst.txt Sets the physical bath parameters and numerical convergence settings for the PT-TEMPO computation. ```python omega_cutoff = 3.04 alpha =0.1 temperature = 13.09 dt=0.2 dkmax=200 epsrel=10**(-2) tempo_parameters = oqupy.TempoParameters(dt=dt, dkmax=dkmax, epsrel=epsrel) ``` -------------------------------- ### Configure Time Parameters Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_gradient/pt_gradient.rst.txt Set the simulation duration and discretization steps. ```python max_time = 5.0 N = 50 # number of time steps dt = max_time/N ``` -------------------------------- ### Iterate and Plot TEMPO Convergence for Varying Timesteps Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/parameters.rst.txt Compares simulation results across different timesteps by adjusting epsrel to maintain convergence. Requires pre-defined system, bath, and initial state objects. ```python for dt, epsrel in zip([0.0625,0.125, 0.25],[6.9e-06,6.9e-05,6.9e-05]): params = oqupy.TempoParameters(dt=dt, epsrel=epsrel, tcut=2.5) dynamics = oqupy.tempo_compute(system=system, bath=bath, initial_state=initial_state, start_time=t_start, end_time=t_end, parameters=params) t, s_z = dynamics.expectations(sigma_z, real=True) plt.plot(t, s_z, label=r'${}$, ${:.2g}$'.format(dt,epsrel)) plt.xlabel(r'$t$') plt.ylabel(r'$\langle\sigma_z\rangle$') plt.legend(title=r'$dt, \epsilon_{rel}$') ``` -------------------------------- ### Define System and Dipole Operators Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/n_time_correlations.rst.txt Sets up the system Hamiltonian, dipole operators, and the initial density matrix for the correlation calculation. ```python eps = 5. omeg= 2. reorg = 2.0*alpha*omega_cutoff system = oqupy.System((eps+reorg)*(P_1 + P_2) + omeg * (sigma_plus + sigma_min)) dip_v = np.array([[0., 0., 1.], [0., 0., 0.],[1., 0., 0.]], dtype=complex) dipole_ops = [dip_v, dip_v, dip_v, dip_v] initial_state = np.array([[1., 0., 0.], [0., 0., 0.],[0., 0., 0.]], dtype=complex) ``` -------------------------------- ### Initialize MeanFieldSystem Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/system.html Constructor for a system interacting with a common field, requiring a list of systems and a field equation of motion. ```python def __init__(self, system_list: List[TimeDependentSystemWithField], field_eom: Callable[[float, List[ndarray], complex], complex], name: Optional[Text] = None, description: Optional[Text] = None) -> None: super().__init__(name, description) tmp_system_list = _check_mean_field_system_list(system_list) self._system_list = tmp_system_list # input check for field equation of motion tmp_dimension_list = [system.hamiltonian(1.0, 1.0+1.0j).shape[0] for system in self.system_list] tmp_field_eom = _check_mean_field_system_eom(tmp_dimension_list, field_eom) self._field_eom = tmp_field_eom ``` -------------------------------- ### Visualize Custom Parameters Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/quickstart.rst.txt Verify the manually defined parameters against the bath correlations. ```python fig, ax = plt.subplots(1,1) oqupy.helpers.plot_correlations_with_parameters(bath.correlations, tempo_parameters, ax=ax) ``` -------------------------------- ### Initialize dynamics metadata Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/tempo.html Creates a MeanFieldDynamics object using metadata from the current MeanFieldTempo instance. ```python def _init_dynamics(self): """Create a MeanFieldDynamics object with metadata from the MeanFieldTempo object. """ name = None description = "computed from '{}' MeanFieldTempo".format(self.name) self._dynamics = MeanFieldDynamics(name=name, description=description) ``` -------------------------------- ### preparation(density_matrix) Source: https://oqupy.readthedocs.io/en/latest/_modules/oqupy/operators.html Constructs a state preparation superoperator. ```APIDOC ## preparation(density_matrix) ### Description Constructs the superoperator that prepares the given density matrix state. ### Parameters - **density_matrix** (ndarray) - Required - The density matrix to prepare. ``` -------------------------------- ### Set physical parameters for the quantum dot Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tempo.rst.txt Define the cutoff frequency, coupling strength, temperature, and initial state for the spin-boson model. ```python omega_cutoff = 3.04 alpha = 0.126 temperature = 0.1309 initial_state=down_density_matrix ``` -------------------------------- ### Configure and run open PT-TEBD Source: https://oqupy.readthedocs.io/en/latest/_sources/pages/tutorials/pt_tebd.rst.txt Initialize the PtTebd object with the computed process tensor and run the computation for the open spin chain. ```python pt_tebd_open = oqupy.PtTebd( initial_augmented_mps=initial_augmented_mps_B, system_chain=system_chain, process_tensors=[pt, None, None, None, None], parameters=pt_tebd_params, dynamics_sites=[0, 1, 2, 3, 4], chain_control=None) print("PT-TEBD computation (open spin chain):") results_open = pt_tebd_open.compute(num_steps, progress_type="bar") ```