本文整理匯總了Python中qutip.solver.Result.times方法的典型用法代碼示例。如果您正苦於以下問題:Python Result.times方法的具體用法?Python Result.times怎麽用?Python Result.times使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類qutip.solver.Result
的用法示例。
在下文中一共展示了Result.times方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _smepdpsolve_generic
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def _smepdpsolve_generic(sso, options, progress_bar):
"""
For internal use. See smepdpsolve.
"""
if debug:
logger.debug(inspect.stack()[0][3])
N_store = len(sso.times)
N_substeps = sso.nsubsteps
dt = (sso.times[1] - sso.times[0]) / N_substeps
nt = sso.ntraj
data = Result()
data.solver = "smepdpsolve"
data.times = sso.times
data.expect = np.zeros((len(sso.e_ops), N_store), dtype=complex)
data.jump_times = []
data.jump_op_idx = []
# Liouvillian for the deterministic part.
# needs to be modified for TD systems
L = liouvillian(sso.H, sso.c_ops)
progress_bar.start(sso.ntraj)
for n in range(sso.ntraj):
progress_bar.update(n)
rho_t = mat2vec(sso.rho0.full()).ravel()
states_list, jump_times, jump_op_idx = \
_smepdpsolve_single_trajectory(data, L, dt, sso.times,
N_store, N_substeps,
rho_t, sso.rho0.dims,
sso.c_ops, sso.e_ops)
data.states.append(states_list)
data.jump_times.append(jump_times)
data.jump_op_idx.append(jump_op_idx)
progress_bar.finished()
# average density matrices
if options.average_states and np.any(data.states):
data.states = [sum([data.states[m][n] for m in range(nt)]).unit()
for n in range(len(data.times))]
# average
data.expect = data.expect / sso.ntraj
# standard error
if nt > 1:
data.se = (data.ss - nt * (data.expect ** 2)) / (nt * (nt - 1))
else:
data.se = None
return data
示例2: solve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def solve(self, rho0, tlist, options=None):
"""
Solve the ODE for the evolution of diagonal states and Hamiltonians.
"""
if options is None:
options = Options()
output = Result()
output.solver = "pisolve"
output.times = tlist
output.states = []
output.states.append(Qobj(rho0))
rhs_generate = lambda y, tt, M: M.dot(y)
rho0_flat = np.diag(np.real(rho0.full()))
L = self.coefficient_matrix()
rho_t = odeint(rhs_generate, rho0_flat, tlist, args=(L,))
for r in rho_t[1:]:
diag = np.diag(r)
output.states.append(Qobj(diag))
return output
示例3: fsesolve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def fsesolve(H, psi0, tlist, e_ops=[], T=None, args={}, Tsteps=100):
"""
Solve the Schrodinger equation using the Floquet formalism.
Parameters
----------
H : :class:`qutip.qobj.Qobj`
System Hamiltonian, time-dependent with period `T`.
psi0 : :class:`qutip.qobj`
Initial state vector (ket).
tlist : *list* / *array*
list of times for :math:`t`.
e_ops : list of :class:`qutip.qobj` / callback function
list of operators for which to evaluate expectation values. If this
list is empty, the state vectors for each time in `tlist` will be
returned instead of expectation values.
T : float
The period of the time-dependence of the hamiltonian.
args : dictionary
Dictionary with variables required to evaluate H.
Tsteps : integer
The number of time steps in one driving period for which to
precalculate the Floquet modes. `Tsteps` should be an even number.
Returns
-------
output : :class:`qutip.solver.Result`
An instance of the class :class:`qutip.solver.Result`, which
contains either an *array* of expectation values or an array of
state vectors, for the times specified by `tlist`.
"""
if not T:
# assume that tlist span exactly one period of the driving
T = tlist[-1]
# find the floquet modes for the time-dependent hamiltonian
f_modes_0, f_energies = floquet_modes(H, T, args)
# calculate the wavefunctions using the from the floquet modes
f_modes_table_t = floquet_modes_table(f_modes_0, f_energies,
np.linspace(0, T, Tsteps + 1),
H, T, args)
# setup Result for storing the results
output = Result()
output.times = tlist
output.solver = "fsesolve"
if isinstance(e_ops, FunctionType):
output.num_expect = 0
expt_callback = True
elif isinstance(e_ops, list):
output.num_expect = len(e_ops)
expt_callback = False
if output.num_expect == 0:
output.states = []
else:
output.expect = []
for op in e_ops:
if op.isherm:
output.expect.append(np.zeros(len(tlist)))
else:
output.expect.append(np.zeros(len(tlist), dtype=complex))
else:
raise TypeError("e_ops must be a list Qobj or a callback function")
psi0_fb = psi0.transform(f_modes_0)
for t_idx, t in enumerate(tlist):
f_modes_t = floquet_modes_t_lookup(f_modes_table_t, t, T)
f_states_t = floquet_states(f_modes_t, f_energies, t)
psi_t = psi0_fb.transform(f_states_t, True)
if expt_callback:
# use callback method
e_ops(t, psi_t)
else:
# calculate all the expectation values, or output psi if
# no expectation value operators where defined
if output.num_expect == 0:
output.states.append(Qobj(psi_t))
else:
for e_idx, e in enumerate(e_ops):
output.expect[e_idx][t_idx] = expect(e, psi_t)
return output
示例4: _generic_ode_solve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def _generic_ode_solve(r, rho0, tlist, e_ops, opt, progress_bar):
"""
Internal function for solving ME. Solve an ODE which solver parameters
already setup (r). Calculate the required expectation values or invoke
callback function at each time step.
"""
#
# prepare output array
#
n_tsteps = len(tlist)
e_sops_data = []
output = Result()
output.solver = "mesolve"
output.times = tlist
if opt.store_states:
output.states = []
if isinstance(e_ops, types.FunctionType):
n_expt_op = 0
expt_callback = True
elif isinstance(e_ops, list):
n_expt_op = len(e_ops)
expt_callback = False
if n_expt_op == 0:
# fall back on storing states
output.states = []
opt.store_states = True
else:
output.expect = []
output.num_expect = n_expt_op
for op in e_ops:
e_sops_data.append(spre(op).data)
if op.isherm and rho0.isherm:
output.expect.append(np.zeros(n_tsteps))
else:
output.expect.append(np.zeros(n_tsteps, dtype=complex))
else:
raise TypeError("Expectation parameter must be a list or a function")
#
# start evolution
#
progress_bar.start(n_tsteps)
rho = Qobj(rho0)
dt = np.diff(tlist)
for t_idx, t in enumerate(tlist):
progress_bar.update(t_idx)
if not r.successful():
break
if opt.store_states or expt_callback:
rho.data = vec2mat(r.y)
if opt.store_states:
output.states.append(Qobj(rho))
if expt_callback:
# use callback method
e_ops(t, rho)
for m in range(n_expt_op):
if output.expect[m].dtype == complex:
output.expect[m][t_idx] = expect_rho_vec(e_sops_data[m], r.y, 0)
else:
output.expect[m][t_idx] = expect_rho_vec(e_sops_data[m], r.y, 1)
if t_idx < n_tsteps - 1:
r.integrate(r.t + dt[t_idx])
progress_bar.finished()
if not opt.rhs_reuse and config.tdname is not None:
try:
os.remove(config.tdname + ".pyx")
except:
pass
if opt.store_final_state:
rho.data = vec2mat(r.y)
output.final_state = Qobj(rho)
return output
示例5: brmesolve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def brmesolve(H, psi0, tlist, a_ops, e_ops=[], spectra_cb=[], c_ops=[],
args={}, options=Options()):
"""
Solve the dynamics for a system using the Bloch-Redfield master equation.
.. note::
This solver does not currently support time-dependent Hamiltonians.
Parameters
----------
H : :class:`qutip.Qobj`
System Hamiltonian.
rho0 / psi0: :class:`qutip.Qobj`
Initial density matrix or state vector (ket).
tlist : *list* / *array*
List of times for :math:`t`.
a_ops : list of :class:`qutip.qobj`
List of system operators that couple to bath degrees of freedom.
e_ops : list of :class:`qutip.qobj` / callback function
List of operators for which to evaluate expectation values.
c_ops : list of :class:`qutip.qobj`
List of system collapse operators.
args : *dictionary*
Placeholder for future implementation, kept for API consistency.
options : :class:`qutip.solver.Options`
Options for the solver.
Returns
-------
result: :class:`qutip.solver.Result`
An instance of the class :class:`qutip.solver.Result`, which contains
either an array of expectation values, for operators given in e_ops,
or a list of states for the times specified by `tlist`.
"""
if not spectra_cb:
# default to infinite temperature white noise
spectra_cb = [lambda w: 1.0 for _ in a_ops]
R, ekets = bloch_redfield_tensor(H, a_ops, spectra_cb, c_ops)
output = Result()
output.solver = "brmesolve"
output.times = tlist
results = bloch_redfield_solve(R, ekets, psi0, tlist, e_ops, options)
if e_ops:
output.expect = results
else:
output.states = results
return output
示例6: mcsolve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
#.........這裏部分代碼省略.........
# check for type of time-dependence (if any)
time_type, h_stuff, c_stuff = _td_format_check(H, c_ops, 'mc')
c_terms = len(c_stuff[0]) + len(c_stuff[1]) + len(c_stuff[2])
# set time_type for use in multiprocessing
config.tflag = time_type
# check for collapse operators
if c_terms > 0:
config.cflag = 1
else:
config.cflag = 0
# Configure data
_mc_data_config(H, psi0, h_stuff, c_ops, c_stuff, args, e_ops,
options, config)
# compile and load cython functions if necessary
_mc_func_load(config)
else:
# setup args for new parameters when rhs_reuse=True and tdfunc is given
# string based
if config.tflag in [1, 10, 11]:
if any(args):
config.c_args = []
arg_items = list(args.items())
for k in range(len(arg_items)):
config.c_args.append(arg_items[k][1])
# function based
elif config.tflag in [2, 3, 20, 22]:
config.h_func_args = args
# load monte carlo class
mc = _MC(config)
# Run the simulation
mc.run()
# Remove RHS cython file if necessary
if not options.rhs_reuse and config.tdname:
_cython_build_cleanup(config.tdname)
# AFTER MCSOLVER IS DONE
# ----------------------
# Store results in the Result object
output = Result()
output.solver = 'mcsolve'
output.seeds = config.options.seeds
# state vectors
if (mc.psi_out is not None and config.options.average_states
and config.cflag and ntraj != 1):
output.states = parfor(_mc_dm_avg, mc.psi_out.T)
elif mc.psi_out is not None:
output.states = mc.psi_out
# expectation values
if (mc.expect_out is not None and config.cflag
and config.options.average_expect):
# averaging if multiple trajectories
if isinstance(ntraj, int):
output.expect = [np.mean(np.array([mc.expect_out[nt][op]
for nt in range(ntraj)],
dtype=object),
axis=0)
for op in range(config.e_num)]
elif isinstance(ntraj, (list, np.ndarray)):
output.expect = []
for num in ntraj:
expt_data = np.mean(mc.expect_out[:num], axis=0)
data_list = []
if any([not op.isherm for op in e_ops]):
for k in range(len(e_ops)):
if e_ops[k].isherm:
data_list.append(np.real(expt_data[k]))
else:
data_list.append(expt_data[k])
else:
data_list = [data for data in expt_data]
output.expect.append(data_list)
else:
# no averaging for single trajectory or if average_expect flag
# (Options) is off
if mc.expect_out is not None:
output.expect = mc.expect_out
# simulation parameters
output.times = config.tlist
output.num_expect = config.e_num
output.num_collapse = config.c_num
output.ntraj = config.ntraj
output.col_times = mc.collapse_times_out
output.col_which = mc.which_op_out
if e_ops_dict:
output.expect = {e: output.expect[n]
for n, e in enumerate(e_ops_dict.keys())}
return output
示例7: _generic_ode_solve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def _generic_ode_solve(r, rho0, tlist, e_ops, opt, progress_bar):
"""
Internal function for solving ME. Solve an ODE which solver parameters
already setup (r). Calculate the required expectation values or invoke
callback function at each time step.
"""
#
# prepare output array
#
n_tsteps = len(tlist)
e_sops_data = []
output = Result()
output.solver = "mesolve"
output.times = tlist
if opt.store_states:
output.states = []
if isinstance(e_ops, types.FunctionType):
n_expt_op = 0
expt_callback = True
elif isinstance(e_ops, list):
n_expt_op = len(e_ops)
expt_callback = False
if n_expt_op == 0:
# fall back on storing states
output.states = []
opt.store_states = True
else:
output.expect = []
output.num_expect = n_expt_op
for op in e_ops:
e_sops_data.append(spre(op).data)
if op.isherm and rho0.isherm:
output.expect.append(np.zeros(n_tsteps))
else:
output.expect.append(np.zeros(n_tsteps, dtype=complex))
else:
raise TypeError("Expectation parameter must be a list or a function")
#
# start evolution
#
progress_bar.start(n_tsteps)
rho = Qobj(rho0)
dt = np.diff(tlist)
for t_idx, t in enumerate(tlist):
progress_bar.update(t_idx)
if not r.successful():
raise Exception("ODE integration error: Try to increase "
"the allowed number of substeps by increasing "
"the nsteps parameter in the Options class.")
if opt.store_states or expt_callback:
rho.data = dense2D_to_fastcsr_fmode(vec2mat(r.y), rho.shape[0], rho.shape[1])
if opt.store_states:
output.states.append(Qobj(rho, isherm=True))
if expt_callback:
# use callback method
e_ops(t, rho)
for m in range(n_expt_op):
if output.expect[m].dtype == complex:
output.expect[m][t_idx] = expect_rho_vec(e_sops_data[m],
r.y, 0)
else:
output.expect[m][t_idx] = expect_rho_vec(e_sops_data[m],
r.y, 1)
if t_idx < n_tsteps - 1:
r.integrate(r.t + dt[t_idx])
progress_bar.finished()
if (not opt.rhs_reuse) and (config.tdname is not None):
_cython_build_cleanup(config.tdname)
if opt.store_final_state:
rho.data = dense2D_to_fastcsr_fmode(vec2mat(r.y), rho.shape[0], rho.shape[1])
output.final_state = Qobj(rho, dims=rho0.dims, isherm=True)
return output
示例8: brmesolve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def brmesolve(H, psi0, tlist, a_ops=[], e_ops=[], c_ops=[],
args={}, use_secular=True, sec_cutoff = 0.1,
tol=qset.atol,
spectra_cb=None, options=None,
progress_bar=None, _safe_mode=True, verbose=False):
"""
Solves for the dynamics of a system using the Bloch-Redfield master equation,
given an input Hamiltonian, Hermitian bath-coupling terms and their associated
spectrum functions, as well as possible Lindblad collapse operators.
For time-independent systems, the Hamiltonian must be given as a Qobj,
whereas the bath-coupling terms (a_ops), must be written as a nested list
of operator - spectrum function pairs, where the frequency is specified by
the `w` variable.
*Example*
a_ops = [[a+a.dag(),lambda w: 0.2*(w>=0)]]
For time-dependent systems, the Hamiltonian, a_ops, and Lindblad collapse
operators (c_ops), can be specified in the QuTiP string-based time-dependent
format. For the a_op spectra, the frequency variable must be `w`, and the
string cannot contain any other variables other than the possibility of having
a time-dependence through the time variable `t`:
*Example*
a_ops = [[a+a.dag(), '0.2*exp(-t)*(w>=0)']]
It is also possible to use Cubic_Spline objects for time-dependence. In
the case of a_ops, Cubic_Splines must be passed as a tuple:
*Example*
a_ops = [ [a+a.dag(), ( f(w), g(t)] ]
where f(w) and g(t) are strings or Cubic_spline objects for the bath
spectrum and time-dependence, respectively.
Finally, if one has bath-couplimg terms of the form
H = f(t)*a + conj[f(t)]*a.dag(), then the correct input format is
*Example*
a_ops = [ [(a,a.dag()), (f(w), g1(t), g2(t))],... ]
where f(w) is the spectrum of the operators while g1(t) and g2(t)
are the time-dependence of the operators `a` and `a.dag()`, respectively
Parameters
----------
H : Qobj / list
System Hamiltonian given as a Qobj or
nested list in string-based format.
psi0: Qobj
Initial density matrix or state vector (ket).
tlist : array_like
List of times for evaluating evolution
a_ops : list
Nested list of Hermitian system operators that couple to
the bath degrees of freedom, along with their associated
spectra.
e_ops : list
List of operators for which to evaluate expectation values.
c_ops : list
List of system collapse operators, or nested list in
string-based format.
args : dict
Placeholder for future implementation, kept for API consistency.
use_secular : bool {True}
Use secular approximation when evaluating bath-coupling terms.
sec_cutoff : float {0.1}
Cutoff for secular approximation.
tol : float {qutip.setttings.atol}
Tolerance used for removing small values after
basis transformation.
spectra_cb : list
DEPRECIATED. Do not use.
options : :class:`qutip.solver.Options`
Options for the solver.
progress_bar : BaseProgressBar
Optional instance of BaseProgressBar, or a subclass thereof, for
showing the progress of the simulation.
Returns
-------
result: :class:`qutip.solver.Result`
#.........這裏部分代碼省略.........
示例9: _ssepdpsolve_generic
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def _ssepdpsolve_generic(sso, options, progress_bar):
"""
For internal use. See ssepdpsolve.
"""
if debug:
logger.debug(inspect.stack()[0][3])
N_store = len(sso.times)
N_substeps = sso.nsubsteps
dt = (sso.times[1] - sso.times[0]) / N_substeps
nt = sso.ntraj
data = Result()
data.solver = "sepdpsolve"
data.times = sso.tlist
data.expect = np.zeros((len(sso.e_ops), N_store), dtype=complex)
data.ss = np.zeros((len(sso.e_ops), N_store), dtype=complex)
data.jump_times = []
data.jump_op_idx = []
# effective hamiltonian for deterministic part
Heff = sso.H
for c in sso.c_ops:
Heff += -0.5j * c.dag() * c
progress_bar.start(sso.ntraj)
for n in range(sso.ntraj):
progress_bar.update(n)
psi_t = sso.state0.full().ravel()
states_list, jump_times, jump_op_idx = \
_ssepdpsolve_single_trajectory(data, Heff, dt, sso.times,
N_store, N_substeps,
psi_t, sso.state0.dims,
sso.c_ops, sso.e_ops)
data.states.append(states_list)
data.jump_times.append(jump_times)
data.jump_op_idx.append(jump_op_idx)
progress_bar.finished()
# average density matrices
if options.average_states and np.any(data.states):
data.states = [sum([data.states[m][n] for m in range(nt)]).unit()
for n in range(len(data.times))]
# average
data.expect = data.expect / nt
# standard error
if nt > 1:
data.se = (data.ss - nt * (data.expect ** 2)) / (nt * (nt - 1))
else:
data.se = None
# convert complex data to real if hermitian
data.expect = [np.real(data.expect[n, :])
if e.isherm else data.expect[n, :]
for n, e in enumerate(sso.e_ops)]
return data
示例10: essolve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def essolve(H, rho0, tlist, c_op_list, e_ops):
"""
Evolution of a state vector or density matrix (`rho0`) for a given
Hamiltonian (`H`) and set of collapse operators (`c_op_list`), by
expressing the ODE as an exponential series. The output is either
the state vector at arbitrary points in time (`tlist`), or the
expectation values of the supplied operators (`e_ops`).
Parameters
----------
H : qobj/function_type
System Hamiltonian.
rho0 : :class:`qutip.qobj`
Initial state density matrix.
tlist : list/array
``list`` of times for :math:`t`.
c_op_list : list of :class:`qutip.qobj`
``list`` of :class:`qutip.qobj` collapse operators.
e_ops : list of :class:`qutip.qobj`
``list`` of :class:`qutip.qobj` operators for which to evaluate
expectation values.
Returns
-------
expt_array : array
Expectation values of wavefunctions/density matrices for the
times specified in ``tlist``.
.. note:: This solver does not support time-dependent Hamiltonians.
"""
n_expt_op = len(e_ops)
n_tsteps = len(tlist)
# Calculate the Liouvillian
if (c_op_list is None or len(c_op_list) == 0) and isket(rho0):
L = H
else:
L = liouvillian(H, c_op_list)
es = ode2es(L, rho0)
# evaluate the expectation values
if n_expt_op == 0:
results = [Qobj()] * n_tsteps
else:
results = np.zeros([n_expt_op, n_tsteps], dtype=complex)
for n, e in enumerate(e_ops):
results[n, :] = expect(e, esval(es, tlist))
data = Result()
data.solver = "essolve"
data.times = tlist
data.expect = [np.real(results[n, :]) if e.isherm else results[n, :]
for n, e in enumerate(e_ops)]
return data
示例11: run
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def run(self, rho0, tlist):
"""
Function to solve for an open quantum system using the
HEOM model.
Parameters
----------
rho0 : Qobj
Initial state (density matrix) of the system.
tlist : list
Time over which system evolves.
Returns
-------
results : :class:`qutip.solver.Result`
Object storing all results from the simulation.
"""
start_run = timeit.default_timer()
sup_dim = self._sup_dim
stats = self.stats
r = self._ode
if not self._configured:
raise RuntimeError("Solver must be configured before it is run")
if stats:
ss_conf = stats.sections.get('config')
if ss_conf is None:
raise RuntimeError("No config section for solver stats")
ss_run = stats.sections.get('run')
if ss_run is None:
ss_run = stats.add_section('run')
# Set up terms of the matsubara and tanimura boundaries
output = Result()
output.solver = "hsolve"
output.times = tlist
output.states = []
if stats: start_init = timeit.default_timer()
output.states.append(Qobj(rho0))
rho0_flat = rho0.full().ravel('F') # Using 'F' effectively transposes
rho0_he = np.zeros([sup_dim*self._N_he], dtype=complex)
rho0_he[:sup_dim] = rho0_flat
r.set_initial_value(rho0_he, tlist[0])
if stats:
stats.add_timing('initialize',
timeit.default_timer() - start_init, ss_run)
start_integ = timeit.default_timer()
dt = np.diff(tlist)
n_tsteps = len(tlist)
for t_idx, t in enumerate(tlist):
if t_idx < n_tsteps - 1:
r.integrate(r.t + dt[t_idx])
rho = Qobj(r.y[:sup_dim].reshape(rho0.shape), dims=rho0.dims)
output.states.append(rho)
if stats:
time_now = timeit.default_timer()
stats.add_timing('integrate',
time_now - start_integ, ss_run)
if ss_run.total_time is None:
ss_run.total_time = time_now - start_run
else:
ss_run.total_time += time_now - start_run
stats.total_time = ss_conf.total_time + ss_run.total_time
return output
示例12: _generic_ode_solve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def _generic_ode_solve(r, psi0, tlist, e_ops, opt, progress_bar, dims=None):
"""
Internal function for solving ODEs.
"""
#
# prepare output array
#
n_tsteps = len(tlist)
output = Result()
output.solver = "sesolve"
output.times = tlist
if psi0.isunitary:
oper_evo = True
oper_n = dims[0][0]
norm_dim_factor = np.sqrt(oper_n)
else:
oper_evo = False
norm_dim_factor = 1.0
if opt.store_states:
output.states = []
if isinstance(e_ops, types.FunctionType):
n_expt_op = 0
expt_callback = True
elif isinstance(e_ops, list):
n_expt_op = len(e_ops)
expt_callback = False
if n_expt_op == 0:
# fallback on storing states
output.states = []
opt.store_states = True
else:
output.expect = []
output.num_expect = n_expt_op
for op in e_ops:
if op.isherm:
output.expect.append(np.zeros(n_tsteps))
else:
output.expect.append(np.zeros(n_tsteps, dtype=complex))
else:
raise TypeError("Expectation parameter must be a list or a function")
def get_curr_state_data():
if oper_evo:
return vec2mat(r.y)
else:
return r.y
#
# start evolution
#
progress_bar.start(n_tsteps)
dt = np.diff(tlist)
for t_idx, t in enumerate(tlist):
progress_bar.update(t_idx)
if not r.successful():
raise Exception("ODE integration error: Try to increase "
"the allowed number of substeps by increasing "
"the nsteps parameter in the Options class.")
# get the current state / oper data if needed
cdata = None
if opt.store_states or opt.normalize_output or n_expt_op > 0:
cdata = get_curr_state_data()
if opt.normalize_output:
# cdata *= _get_norm_factor(cdata, oper_evo)
cdata *= norm_dim_factor / la_norm(cdata)
if oper_evo:
r.set_initial_value(cdata.ravel('F'), r.t)
else:
r.set_initial_value(cdata, r.t)
if opt.store_states:
output.states.append(Qobj(cdata, dims=dims))
if expt_callback:
# use callback method
e_ops(t, Qobj(cdata, dims=dims))
for m in range(n_expt_op):
output.expect[m][t_idx] = cy_expect_psi(e_ops[m].data,
cdata, e_ops[m].isherm)
if t_idx < n_tsteps - 1:
r.integrate(r.t + dt[t_idx])
progress_bar.finished()
if not opt.rhs_reuse and config.tdname is not None:
try:
os.remove(config.tdname + ".pyx")
except:
#.........這裏部分代碼省略.........
示例13: _generic_ode_solve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def _generic_ode_solve(r, psi0, tlist, e_ops, opt, progress_bar,
state_norm_func=None, dims=None):
"""
Internal function for solving ODEs.
"""
#
# prepare output array
#
n_tsteps = len(tlist)
output = Result()
output.solver = "sesolve"
output.times = tlist
if opt.store_states:
output.states = []
if isinstance(e_ops, types.FunctionType):
n_expt_op = 0
expt_callback = True
elif isinstance(e_ops, list):
n_expt_op = len(e_ops)
expt_callback = False
if n_expt_op == 0:
# fallback on storing states
output.states = []
opt.store_states = True
else:
output.expect = []
output.num_expect = n_expt_op
for op in e_ops:
if op.isherm:
output.expect.append(np.zeros(n_tsteps))
else:
output.expect.append(np.zeros(n_tsteps, dtype=complex))
else:
raise TypeError("Expectation parameter must be a list or a function")
#
# start evolution
#
progress_bar.start(n_tsteps)
dt = np.diff(tlist)
for t_idx, t in enumerate(tlist):
progress_bar.update(t_idx)
if not r.successful():
break
if state_norm_func:
data = r.y / state_norm_func(r.y)
r.set_initial_value(data, r.t)
if opt.store_states:
output.states.append(Qobj(r.y, dims=dims))
if expt_callback:
# use callback method
e_ops(t, Qobj(r.y, dims=psi0.dims))
for m in range(n_expt_op):
output.expect[m][t_idx] = cy_expect_psi(e_ops[m].data,
r.y, e_ops[m].isherm)
if t_idx < n_tsteps - 1:
r.integrate(r.t + dt[t_idx])
progress_bar.finished()
if not opt.rhs_reuse and config.tdname is not None:
try:
os.remove(config.tdname + ".pyx")
except:
pass
if opt.store_final_state:
output.final_state = Qobj(r.y)
return output
示例14: mcsolve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
#.........這裏部分代碼省略.........
H, c_ops, args = _td_wrap_array_str(H, c_ops, args, tlist)
# ----------------------------------------------
# SETUP ODE DATA IF NONE EXISTS OR NOT REUSING
# ----------------------------------------------
if (not options.rhs_reuse) or (not config.tdfunc):
# reset config collapse and time-dependence flags to default values
config.soft_reset()
# check for type of time-dependence (if any)
time_type, h_stuff, c_stuff = _td_format_check(H, c_ops, "mc")
h_terms = len(h_stuff[0]) + len(h_stuff[1]) + len(h_stuff[2])
c_terms = len(c_stuff[0]) + len(c_stuff[1]) + len(c_stuff[2])
# set time_type for use in multiprocessing
config.tflag = time_type
# check for collapse operators
if c_terms > 0:
config.cflag = 1
else:
config.cflag = 0
# Configure data
_mc_data_config(H, psi0, h_stuff, c_ops, c_stuff, args, e_ops, options, config)
# compile and load cython functions if necessary
_mc_func_load(config)
else:
# setup args for new parameters when rhs_reuse=True and tdfunc is given
# string based
if config.tflag in array([1, 10, 11]):
if any(args):
config.c_args = []
arg_items = args.items()
for k in range(len(args)):
config.c_args.append(arg_items[k][1])
# function based
elif config.tflag in array([2, 3, 20, 22]):
config.h_func_args = args
# load monte-carlo class
mc = _MC_class(config)
# RUN THE SIMULATION
mc.run()
# remove RHS cython file if necessary
if not options.rhs_reuse and config.tdname:
try:
os.remove(config.tdname + ".pyx")
except:
pass
# AFTER MCSOLVER IS DONE --------------------------------------
# ------- COLLECT AND RETURN OUTPUT DATA IN ODEDATA OBJECT --------------
output = Result()
output.solver = "mcsolve"
# state vectors
if mc.psi_out is not None and config.options.average_states and config.cflag and ntraj != 1:
output.states = parfor(_mc_dm_avg, mc.psi_out.T)
elif mc.psi_out is not None:
output.states = mc.psi_out
# expectation values
elif mc.expect_out is not None and config.cflag and config.options.average_expect:
# averaging if multiple trajectories
if isinstance(ntraj, int):
output.expect = [mean([mc.expect_out[nt][op] for nt in range(ntraj)], axis=0) for op in range(config.e_num)]
elif isinstance(ntraj, (list, ndarray)):
output.expect = []
for num in ntraj:
expt_data = mean(mc.expect_out[:num], axis=0)
data_list = []
if any([not op.isherm for op in e_ops]):
for k in range(len(e_ops)):
if e_ops[k].isherm:
data_list.append(np.real(expt_data[k]))
else:
data_list.append(expt_data[k])
else:
data_list = [data for data in expt_data]
output.expect.append(data_list)
else:
# no averaging for single trajectory or if average_states flag
# (Options) is off
if mc.expect_out is not None:
output.expect = mc.expect_out
# simulation parameters
output.times = config.tlist
output.num_expect = config.e_num
output.num_collapse = config.c_num
output.ntraj = config.ntraj
output.col_times = mc.collapse_times_out
output.col_which = mc.which_op_out
if e_ops_dict:
output.expect = {e: output.expect[n] for n, e in enumerate(e_ops_dict.keys())}
return output
示例15: floquet_markov_mesolve
# 需要導入模塊: from qutip.solver import Result [as 別名]
# 或者: from qutip.solver.Result import times [as 別名]
def floquet_markov_mesolve(R, ekets, rho0, tlist, e_ops, f_modes_table=None,
options=None, floquet_basis=True):
"""
Solve the dynamics for the system using the Floquet-Markov master equation.
"""
if options is None:
opt = Options()
else:
opt = options
if opt.tidy:
R.tidyup()
#
# check initial state
#
if isket(rho0):
# Got a wave function as initial state: convert to density matrix.
rho0 = ket2dm(rho0)
#
# prepare output array
#
n_tsteps = len(tlist)
dt = tlist[1] - tlist[0]
output = Result()
output.solver = "fmmesolve"
output.times = tlist
if isinstance(e_ops, FunctionType):
n_expt_op = 0
expt_callback = True
elif isinstance(e_ops, list):
n_expt_op = len(e_ops)
expt_callback = False
if n_expt_op == 0:
output.states = []
else:
if not f_modes_table:
raise TypeError("The Floquet mode table has to be provided " +
"when requesting expectation values.")
output.expect = []
output.num_expect = n_expt_op
for op in e_ops:
if op.isherm:
output.expect.append(np.zeros(n_tsteps))
else:
output.expect.append(np.zeros(n_tsteps, dtype=complex))
else:
raise TypeError("Expectation parameter must be a list or a function")
#
# transform the initial density matrix to the eigenbasis: from
# computational basis to the floquet basis
#
if ekets is not None:
rho0 = rho0.transform(ekets)
#
# setup integrator
#
initial_vector = mat2vec(rho0.full())
r = scipy.integrate.ode(cy_ode_rhs)
r.set_f_params(R.data.data, R.data.indices, R.data.indptr)
r.set_integrator('zvode', method=opt.method, order=opt.order,
atol=opt.atol, rtol=opt.rtol, max_step=opt.max_step)
r.set_initial_value(initial_vector, tlist[0])
#
# start evolution
#
rho = Qobj(rho0)
t_idx = 0
for t in tlist:
if not r.successful():
break
rho.data = vec2mat(r.y)
if expt_callback:
# use callback method
if floquet_basis:
e_ops(t, Qobj(rho))
else:
f_modes_table_t, T = f_modes_table
f_modes_t = floquet_modes_t_lookup(f_modes_table_t, t, T)
e_ops(t, Qobj(rho).transform(f_modes_t, True))
else:
# calculate all the expectation values, or output rho if
# no operators
if n_expt_op == 0:
if floquet_basis:
#.........這裏部分代碼省略.........