licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.3.12
bdaf4f73bfd2bcf32b773f96141016735f55b533
docs
1573
```@meta CurrentModule = EulerLagrange ``` # Euler-Lagrange This package generates code for the Euler-Lagrange equations as well as Hamilton's equations for [GeometricIntegrators.jl](https://github.com/JuliaGNI/GeometricIntegrators.jl) and related packages. ## Installation *EulerLagrange.jl* and all of its dependencies can be installed via the Julia REPL by typing ``` ]add EulerLagrange ``` ## Usage Using EulerLagrange.jl is very simple and typically consists of four to five steps: 1) Obtain symbolic variables for a Lagrangian or Hamiltonian system of a given dimension. 2) Obtain a symbolic representation of the parameters of the system if it has any. 3) Build the Lagrangian or Hamiltonian using those symbolic variables and parameters. 4) Construct a `LagrangianSystem` or `HamiltonianSystem`, which is where the actual code generation happens. 5) Generate a `LODEProblem` or `HODEProblem` that can then be solved with [GeometricIntegrators.jl](https://github.com/JuliaGNI/GeometricIntegrators.jl). Details for the specific system types can be found on the following pages: ```@contents Pages = [ "hamiltonian.md", "lagrangian.md", "degenerate_lagrangian.md", "caveats.md", ] ``` ## References If you use EulerLagrange.jl in your work, please consider citing it by ``` @misc{Kraus:2023:EulerLagrange, title={EulerLagrange.jl: Code generation for Euler-Lagrange equations in Julia}, author={Kraus, Michael}, year={2023}, howpublished={\url{https://github.com/JuliaGNI/EulerLagrange.jl}}, doi={10.5281/zenodo.8241048} } ```
EulerLagrange
https://github.com/JuliaGNI/EulerLagrange.jl.git
[ "MIT" ]
0.3.12
bdaf4f73bfd2bcf32b773f96141016735f55b533
docs
3562
# Lagrangian Systems The Euler-Lagrange equations, that is the dynamical equations of a Lagrangian system, are given in terms of the Lagrangian ``L(x,v)`` by ```math \frac{d}{dt} \frac{\partial L}{\partial v} - \frac{\partial L}{\partial x} = 0 . ``` For regular (i.e. non-degenerate) Lagrangians, this is a set of second-order ordinary differential equations. In many numerical applications, it is advantageous to solve the implicit form of these equations, given by ```math \begin{align*} \frac{d \vartheta}{dt} &= f , & \vartheta &= \frac{\partial L}{\partial v} , & f = \frac{\partial L}{\partial x} . \end{align*} ``` In the following, we show how these equations can be obtained for the example of a particle in a square potential. ## Particle in a potential Before any use, we need to load `EulerLagrange`: ```@example lag using EulerLagrange ``` Next, we generate symbolic variables for a two-dimensional system: ```@example lag t, x, v = lagrangian_variables(2) ``` With those variables, we can construct a Lagrangian ```@example lag using LinearAlgebra L = v ⋅ v / 2 - x ⋅ x / 2 ``` This Lagrangian together with the symbolic variables is then used to construct a `LagrangianSystem`: ```@example lag lag_sys = LagrangianSystem(L, t, x, v) ``` The constructor computes the Euler-Lagrange equations and generates the corresponding Julia code. In the last step, we can now construct a `LODEProblem` from the `LagrangianSystem` and some appropriate initial conditions, a time span to integrate over and a time step: ```@example lag tspan = (0.0, 10.0) tstep = 0.01 q₀ = [1.0, 1.0] p₀ = [0.5, 2.0] lprob = LODEProblem(lag_sys, tspan, tstep, q₀, p₀) ``` We can integrate this system using GeometricIntegrators: ```@example lag using GeometricIntegrators sol = integrate(lprob, Gauss(1)) using CairoMakie fig = lines(parent(sol.q[:,1]), parent(sol.q[:,2]); axis = (; xlabel = "x₁", ylabel = "x₂", title = "Particle moving in a square potential"), figure = (; size = (800,600), fontsize = 22)) save("particle_vi.svg", fig); nothing # hide ``` ![](particle_vi.svg) ## Parameters We can also include parametric dependencies in the Lagrangian. Consider, for example, a parameter `α` that determines the strength of the potential. The easiest way, to account for parameters, is to create a named tuple with typical values for each parameter, e.g., ```@example lag params = (α = 5.0,) ``` In the next step, we use the function `symbolize` to generate a symbolic version of the parameters: ```@example lag sparams = symbolize(params) ``` Now we modify the Lagrangian to account for the parameter: ```@example lag L = v ⋅ v / 2 - sparams.α * (x ⋅ x) / 2 ``` From here on, everything follows along the same lines as before, the only difference being that we also need to pass the symbolic parameters `sparams` to the `LagrangianSystem` constructor: ```@example lag lag_sys = LagrangianSystem(L, t, x, v, sparams) ``` Analogously, we need to pass actual parameter values `params` to the `LODEProblem` constructor via the `parameters` keyword argument: ```@example lag lprob = LODEProblem(lag_sys, tspan, tstep, q₀, p₀; parameters = params) ``` This problem can again be integrated using GeometricIntegrators: ```@example lag sol = integrate(lprob, Gauss(1)) fig = lines(parent(sol.q[:,1]), parent(sol.q[:,2]); axis = (; xlabel = "x₁", ylabel = "x₂", title = "Particle moving in a square potential"), figure = (; size = (800,600), fontsize = 22)) save("particle_vi_param.svg", fig); nothing # hide ``` ![](particle_vi_param.svg)
EulerLagrange
https://github.com/JuliaGNI/EulerLagrange.jl.git
[ "MIT" ]
0.3.12
bdaf4f73bfd2bcf32b773f96141016735f55b533
docs
123
```@meta CurrentModule = EulerLagrange ``` # Euler-Lagrange Library Functions ```@autodocs Modules = [EulerLagrange] ```
EulerLagrange
https://github.com/JuliaGNI/EulerLagrange.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
3800
## run the following command under HierarchicalEOM.jl root directory # julia --project=docs/ -e 'using Pkg; Pkg.develop(PackageSpec(path=pwd()));Pkg.instantiate()' # julia --project=docs/ docs/make.jl import Literate using Documenter, HierarchicalEOM DocMeta.setdocmeta!(HierarchicalEOM, :DocTestSetup, :(using HierarchicalEOM); recursive = true) const DRAFT = false # set `true` to disable cell evaluation ENV["GKSwstype"] = "100" # enable headless mode for GR to suppress warnings when plotting const MathEngine = MathJax3( Dict( :loader => Dict("load" => ["[tex]/physics"]), :tex => Dict( "inlineMath" => [["\$", "\$"], ["\\(", "\\)"]], "tags" => "ams", "packages" => ["base", "ams", "autoload", "physics"], ), ), ) # clean and rebuild the output markdown directory for examples doc_output_path = abspath(joinpath(@__DIR__, "src", "examples")) if isdir(doc_output_path) rm(doc_output_path, recursive = true) end mkdir(doc_output_path) # Generate page: Quick Start QS_source_file = abspath(joinpath(@__DIR__, "..", "examples", "quick_start.jl")) Literate.markdown(QS_source_file, doc_output_path) # Generate example pages EXAMPLES = ["cavityQED", "dynamical_decoupling", "SIAM", "electronic_current"] EX_source_files = [abspath(joinpath(@__DIR__, "..", "examples", "$(ex_name).jl")) for ex_name in EXAMPLES] EX_output_files = ["examples/$(ex_name).md" for ex_name in EXAMPLES] for file in EX_source_files Literate.markdown(file, doc_output_path) end const PAGES = Any[ "Home"=>Any[ "Introduction"=>"index.md", "Installation"=>"install.md", "Quick Start"=>"examples/quick_start.md", "Cite HierarchicalEOM.jl"=>"cite.md", ], "Manual"=>Any[ "Bosonic Bath"=>Any[ "Introduction"=>"bath_boson/bosonic_bath_intro.md", "Drude-Lorentz Spectral Density"=>"bath_boson/Boson_Drude_Lorentz.md", ], "Bosonic Bath (RWA)"=>Any["Introduction"=>"bath_boson_RWA/bosonic_bath_RWA_intro.md"], "Fermionic Bath"=>Any[ "Introduction"=>"bath_fermion/fermionic_bath_intro.md", "Lorentz Spectral Density"=>"bath_fermion/Fermion_Lorentz.md", ], "Auxiliary Density Operators"=>"ADOs.md", "HEOMLS Matrices"=>Any[ "Introduction"=>"heom_matrix/HEOMLS_intro.md", "HEOMLS for Schrödinger Equation"=>"heom_matrix/schrodinger_eq.md", "HEOMLS for Bosonic Bath"=>"heom_matrix/M_Boson.md", "HEOMLS for Fermionic Bath"=>"heom_matrix/M_Fermion.md", "HEOMLS for Bosonic and Fermionic Bath"=>"heom_matrix/M_Boson_Fermion.md", "HEOMLS for Master Equation"=>"heom_matrix/master_eq.md", ], "Parity Support"=>"Parity.md", "Hierarchy Dictionary"=>"hierarchy_dictionary.md", "Time Evolution"=>"time_evolution.md", "Stationary State"=>"stationary_state.md", "Spectrum"=>"spectrum.md", "Examples"=>EX_output_files, "Solvers Lists"=>Any["ODE_solvers.md", "LS_solvers.md"], "Extensions"=>Any["CUDA.jl"=>"extensions/CUDA.md"], ], "Library API"=>"libraryAPI.md", ] makedocs(; modules = [HierarchicalEOM], authors = "Yi-Te Huang", repo = Remotes.GitHub("qutip", "HierarchicalEOM.jl"), sitename = "Documentation | HierarchicalEOM.jl", pages = PAGES, format = Documenter.HTML(; prettyurls = get(ENV, "CI", "false") == "true", canonical = "https://qutip.github.io/HierarchicalEOM.jl", edit_link = "main", mathengine = MathEngine, ansicolor = true, size_threshold_ignore = ["libraryAPI.md"], ), draft = DRAFT, ) deploydocs(; repo = "github.com/qutip/HierarchicalEOM.jl", devbranch = "main")
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
3272
# # [The single-impurity Anderson model](@id exp-SIAM) # The investigation of the Kondo effect in single-impurity Anderson model is crucial as it serves both as a valuable testing ground for the theories of the Kondo effect and has the potential to lead to a better understanding of this intrinsic many-body phenomena. import QuantumToolbox using HierarchicalEOM import Plots # ## Hamiltonian # We consider a single-level electronic system [which can be populated by a spin-up ($\uparrow$) or spin-down ($\downarrow$) electron] coupled to a fermionic reservoir ($\textrm{f}$). The total Hamiltonian is given by $H_{\textrm{T}}=H_\textrm{s}+H_\textrm{f}+H_\textrm{sf}$, where each terms takes the form # ```math # \begin{aligned} # H_{\textrm{s}} &= \epsilon \left(d^\dagger_\uparrow d_\uparrow + d^\dagger_\downarrow d_\downarrow \right) + U\left(d^\dagger_\uparrow d_\uparrow d^\dagger_\downarrow d_\downarrow\right),\\ # H_{\textrm{f}} &=\sum_{\sigma=\uparrow,\downarrow}\sum_{k}\epsilon_{\sigma,k}c_{\sigma,k}^{\dagger}c_{\sigma,k},\\ # H_{\textrm{sf}} &=\sum_{\sigma=\uparrow,\downarrow}\sum_{k}g_{k}c_{\sigma,k}^{\dagger}d_{\sigma} + g_{k}^*d_{\sigma}^{\dagger}c_{\sigma,k}. # \end{aligned} # ``` # Here, $d_\uparrow$ $(d_\downarrow)$ annihilates a spin-up (spin-down) electron in the system, $\epsilon$ is the energy of the electron, and $U$ is the Coulomb repulsion energy for double occupation. Furthermore, $c_{\sigma,k}$ $(c_{\sigma,k}^{\dagger})$ annihilates (creates) an electron in the state $k$ (with energy $\epsilon_{\sigma,k}$) of the reservoir. # # Now, we need to build the system Hamiltonian and initial state with the package [`QuantumToolbox.jl`](https://github.com/qutip/QuantumToolbox.jl) to construct the operators. ϵ = -5 U = 10 σm = sigmam() ## σ- σz = sigmaz() ## σz II = qeye(2) ## identity matrix ## construct the annihilation operator for both spin-up and spin-down ## (utilize Jordan–Wigner transformation) d_up = tensor(σm, II) d_dn = tensor(-1 * σz, σm) Hsys = ϵ * (d_up' * d_up + d_dn' * d_dn) + U * (d_up' * d_up * d_dn' * d_dn) # ## Construct bath objects # We assume the fermionic reservoir to have a [Lorentzian-shaped spectral density](@ref doc-Fermion-Lorentz), and we utilize the Padé decomposition. Furthermore, the spectral densities depend on the following physical parameters: # - the coupling strength $\Gamma$ between system and reservoirs # - the band-width $W$ # - the product of the Boltzmann constant $k$ and the absolute temperature $T$ : $kT$ # - the chemical potential $\mu$ # - the total number of exponentials for the reservoir $2(N + 1)$ Γ = 2 μ = 0 W = 10 kT = 0.5 N = 5 bath_up = Fermion_Lorentz_Pade(d_up, Γ, μ, W, kT, N) bath_dn = Fermion_Lorentz_Pade(d_dn, Γ, μ, W, kT, N) bath_list = [bath_up, bath_dn] # ## Construct HEOMLS matrix # (see also [HEOMLS Matrix for Fermionic Baths](@ref doc-M_Fermion)) tier = 3 M_even = M_Fermion(Hsys, tier, bath_list) M_odd = M_Fermion(Hsys, tier, bath_list, ODD) # ## Solve stationary state of ADOs # (see also [Stationary State](@ref doc-Stationary-State)) ados_s = steadystate(M_even) # ## Calculate density of states (DOS) # (see also [Spectrum](@ref doc-Spectrum)) ωlist = -10:1:10 dos = DensityOfStates(M_odd, ados_s, d_up, ωlist) Plots.plot(ωlist, dos)
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
3316
# # [LinearSolve solvers](@id benchmark-LS-solvers) # # In this page, we will benchmark several solvers provided by [LinearSolve.jl](https://docs.sciml.ai/LinearSolve/stable/) for solving steadystate and spectrum in hierarchical equations of motion approach. using LinearSolve using BenchmarkTools using HierarchicalEOM HierarchicalEOM.versioninfo() # Here, we use the example of [the single-impurity Anderson model](@ref exp-SIAM): ϵ = -5 U = 10 Γ = 2 μ = 0 W = 10 kT = 0.5 N = 5 tier = 2 ωlist = -10:1:10 σm = sigmam() σz = sigmaz() II = qeye(2) d_up = kron(σm, II) d_dn = kron(-1 * σz, σm) Hsys = ϵ * (d_up' * d_up + d_dn' * d_dn) + U * (d_up' * d_up * d_dn' * d_dn) bath_up = Fermion_Lorentz_Pade(d_up, Γ, μ, W, kT, N) bath_dn = Fermion_Lorentz_Pade(d_dn, Γ, μ, W, kT, N) bath_list = [bath_up, bath_dn] M_even = M_Fermion(Hsys, tier, bath_list) M_odd = M_Fermion(Hsys, tier, bath_list, ODD) ados_s = steadystate(M_even); # ## LinearSolve Solver List # (click [here](https://docs.sciml.ai/LinearSolve/stable/solvers/solvers/) to see the full solver list provided by `LinearSolve.jl`) # ### UMFPACKFactorization (Default solver) # This solver performs better when there is more structure to the sparsity pattern (depends on the complexity of your system and baths). UMFPACKFactorization(); # ### KLUFactorization # This solver performs better when there is less structure to the sparsity pattern (depends on the complexity of your system and baths). KLUFactorization(); # ### A generic BICGSTAB implementation from Krylov KrylovJL_BICGSTAB(); # ### Pardiso # This solver is based on Intel openAPI Math Kernel Library (MKL) Pardiso # !!! note "Note" # Using this solver requires adding the package [Pardiso.jl](https://github.com/JuliaSparse/Pardiso.jl), i.e. `using Pardiso` using Pardiso using LinearSolve MKLPardisoFactorize() MKLPardisoIterate(); # ## Solving Stationary State # Since we are using [`BenchmarkTools`](https://juliaci.github.io/BenchmarkTools.jl/stable/) (`@benchmark`) in the following, we set `verbose = false` to disable the output message. # ### UMFPACKFactorization (Default solver) @benchmark steadystate(M_even; verbose = false) # ### KLUFactorization @benchmark steadystate(M_even; solver = KLUFactorization(), verbose = false) # ### KrylovJL_BICGSTAB @benchmark steadystate(M_even; solver = KrylovJL_BICGSTAB(rtol = 1e-10, atol = 1e-12), verbose = false) # ### MKLPardisoFactorize @benchmark steadystate(M_even; solver = MKLPardisoFactorize(), verbose = false) # ### MKLPardisoIterate @benchmark steadystate(M_even; solver = MKLPardisoIterate(), verbose = false) # ## Calculate Spectrum # ### UMFPACKFactorization (Default solver) @benchmark DensityOfStates(M_odd, ados_s, d_up, ωlist; verbose = false) # ### KLUFactorization @benchmark DensityOfStates(M_odd, ados_s, d_up, ωlist; solver = KLUFactorization(), verbose = false) # ### KrylovJL_BICGSTAB @benchmark DensityOfStates( M_odd, ados_s, d_up, ωlist; solver = KrylovJL_BICGSTAB(rtol = 1e-10, atol = 1e-12), verbose = false, ) # ### MKLPardisoFactorize @benchmark DensityOfStates(M_odd, ados_s, d_up, ωlist; solver = MKLPardisoFactorize(), verbose = false) # ### MKLPardisoIterate @benchmark DensityOfStates(M_odd, ados_s, d_up, ωlist; solver = MKLPardisoIterate(), verbose = false)
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
2996
# # [DifferentialEquations solvers](@id benchmark-ODE-solvers) # # In this page, we will benchmark several solvers provided by [DifferentialEquations.jl](https://docs.sciml.ai/DiffEqDocs/stable/) for solving time evolution in hierarchical equations of motion approach. using OrdinaryDiffEq ## or "using DifferentialEquations" using BenchmarkTools using HierarchicalEOM HierarchicalEOM.versioninfo() # Here, we use the example of [driven systems and dynamical decoupling](@ref exp-dynamical-decoupling): Γ = 0.0005 W = 0.005 kT = 0.05 N = 3 tier = 6 amp = 0.50 delay = 20 tlist = 0:0.4:400 σz = sigmaz() σx = sigmax() H0 = 0.0 * σz ψ0 = (basis(2, 0) + basis(2, 1)) / √2 params = (V = amp, Δ = delay, σx = σx) function pulse(V, Δ, t) τ = 0.5 * π / V period = τ + Δ if (t % period) < τ return V else return 0 end end H_D(t, p::NamedTuple) = pulse(p.V, p.Δ, t) * p.σx bath = Boson_DrudeLorentz_Pade(σz, Γ, W, kT, N) M = M_Boson(H0, tier, bath); # ## ODE Solver List # (click [here](https://docs.sciml.ai/DiffEqDocs/stable/solvers/ode_solve/) to see the full solver list provided by `DifferentialEquations.jl`) # # For any extra solver options, we can add it in the function [`HEOMsolve`](@ref) with keyword arguments. These keyword arguments will be directly pass to the solvers in `DifferentialEquations` # (click [here](https://docs.sciml.ai/DiffEqDocs/stable/basics/common_solver_opts/) to see the documentation for the common solver options) # # Furthermore, since we are using [`BenchmarkTools`](https://juliaci.github.io/BenchmarkTools.jl/stable/) (`@benchmark`) in the following, we set `verbose = false` to disable the output message. # # ### DP5 (Default solver) # Dormand-Prince's 5/4 Runge-Kutta method. (free 4th order interpolant) @benchmark HEOMsolve(M, ψ0, tlist; H_t = H_D, params = params, abstol = 1e-12, reltol = 1e-12, verbose = false) # ### RK4 # The canonical Runge-Kutta Order 4 method. Uses a defect control for adaptive stepping using maximum error over the whole interval. @benchmark HEOMsolve( M, ψ0, tlist; H_t = H_D, params = params, solver = RK4(), abstol = 1e-12, reltol = 1e-12, verbose = false, ) # ### Tsit5 # Tsitouras 5/4 Runge-Kutta method. (free 4th order interpolant). @benchmark HEOMsolve( M, ψ0, tlist; H_t = H_D, params = params, solver = Tsit5(), abstol = 1e-12, reltol = 1e-12, verbose = false, ) # ### Vern7 # Verner's “Most Efficient” 7/6 Runge-Kutta method. (lazy 7th order interpolant). @benchmark HEOMsolve( M, ψ0, tlist; H_t = H_D, params = params, solver = Vern7(), abstol = 1e-12, reltol = 1e-12, verbose = false, ) # ### Vern9 # Verner's “Most Efficient” 9/8 Runge-Kutta method. (lazy 9th order interpolant) @benchmark HEOMsolve( M, ψ0, tlist; H_t = H_D, params = params, solver = Vern9(), abstol = 1e-12, reltol = 1e-12, verbose = false, )
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
7408
# # Cavity QED system # Cavity quantum electrodynamics (cavity QED) is an important topic for studying the interaction between atoms (or other particles) and light confined in a reflective cavity, under conditions where the quantum nature of photons is significant. import QuantumToolbox using HierarchicalEOM using LaTeXStrings import Plots # ## Hamiltonian # The Jaynes-Cummings model is a standard model in the realm of cavity QED. It illustrates the interaction between a two-level atom ($\textrm{A}$) and a quantized single-mode within a cavity ($\textrm{c}$). # ```math # \begin{aligned} # H_{\textrm{s}}&=H_{\textrm{A}}+H_{\textrm{c}}+H_{\textrm{int}},\\ # H_{\textrm{A}}&=\frac{\omega_A}{2}\sigma_z,\\ # H_{\textrm{c}}&=\omega_{\textrm{c}} a^\dagger a,\\ # H_{\textrm{int}}&=g (a^\dagger\sigma^-+a\sigma^+), # \end{aligned} # ``` # where $\sigma^-$ ($\sigma^+$) is the annihilation (creation) operator of the atom, and $a$ ($a^\dagger$) is the annihilation (creation) operator of the cavity. # # Furthermore, we consider the system is coupled to a bosonic reservoir ($\textrm{b}$). The total Hamiltonian is given by $H_{\textrm{Total}}=H_\textrm{s}+H_\textrm{b}+H_\textrm{sb}$, where $H_\textrm{b}$ and $H_\textrm{sb}$ takes the form # ```math # \begin{aligned} # H_{\textrm{b}} &=\sum_{k}\omega_{k}b_{k}^{\dagger}b_{k},\\ # H_{\textrm{sb}} &=(a+a^\dagger)\sum_{k}g_{k}(b_k + b_k^{\dagger}). # \end{aligned} # ``` # Here, $H_{\textrm{b}}$ describes a bosonic reservoir where $b_{k}$ $(b_{k}^{\dagger})$ is the bosonic annihilation (creation) operator associated to the $k$th mode (with frequency $\omega_{k}$). Also, $H_{\textrm{sb}}$ illustrates the interaction between the cavity and the bosonic reservoir. # Now, we need to build the system Hamiltonian and initial state with the package [`QuantumToolbox.jl`](https://github.com/qutip/QuantumToolbox.jl) to construct the operators. N = 3 ## system cavity Hilbert space cutoff ωA = 2 ωc = 2 g = 0.1 ## operators a_c = destroy(N) I_c = qeye(N) σz_A = sigmaz() σm_A = sigmam() I_A = qeye(2) ## operators in tensor-space a = tensor(a_c, I_A) σz = tensor(I_c, σz_A) σm = tensor(I_c, σm_A) ## Hamiltonian H_A = 0.5 * ωA * σz H_c = ωc * a' * a H_int = g * (a' * σm + a * σm') H_s = H_A + H_c + H_int ## initial state ψ0 = tensor(basis(N, 0), basis(2, 0)) # ## Construct bath objects # We assume the bosonic reservoir to have a [Drude-Lorentz Spectral Density](@ref Boson-Drude-Lorentz), and we utilize the Padé decomposition. Furthermore, the spectral densities depend on the following physical parameters: # - the coupling strength $\Gamma$ between system and reservoir # - the band-width $W$ # - the product of the Boltzmann constant $k$ and the absolute temperature $T$ : $kT$ # - the total number of exponentials for the reservoir $(N + 1)$ Γ = 0.01 W = 1 kT = 0.025 N = 20 Bath = Boson_DrudeLorentz_Pade(a + a', Γ, W, kT, N) # Before incorporating the correlation function into the HEOMLS matrix, it is essential to verify if the total number of exponentials for the reservoir sufficiently describes the practical situation. tlist_test = 0:0.1:10; Bath_test = Boson_DrudeLorentz_Pade(a + a', Γ, W, kT, 1000); Ct = C(Bath, tlist_test); Ct2 = C(Bath_test, tlist_test); Plots.plot(tlist_test, real(Ct), label = "N=20 (real part )", linestyle = :dash, linewidth = 3) Plots.plot!(tlist_test, real(Ct2), label = "N=1000 (real part)", linestyle = :solid, linewidth = 3) Plots.plot!(tlist_test, imag(Ct), label = "N=20 (imag part)", linestyle = :dash, linewidth = 3) Plots.plot!(tlist_test, imag(Ct2), label = "N=1000 (imag part)", linestyle = :solid, linewidth = 3) Plots.xaxis!("t") Plots.yaxis!("C(t)") # ## Construct HEOMLS matrix # (see also [HEOMLS Matrix for Bosonic Baths](@ref doc-M_Boson)) # Here, we consider an incoherent pumping to the atom, which can be described by an Lindblad dissipator (see [here](@ref doc-Master-Equation) for more details). # # Furthermore, we set the [important threshold](@ref doc-Importance-Value-and-Threshold) to be `1e-6`. pump = 0.01 J_pump = sqrt(pump) * σm' tier = 2 M_Heom = M_Boson(H_s, tier, threshold = 1e-6, Bath) M_Heom = addBosonDissipator(M_Heom, J_pump) # ## Solve time evolution of ADOs # (see also [Time Evolution](@ref doc-Time-Evolution)) t_list = 0:1:500 sol_H = HEOMsolve(M_Heom, ψ0, t_list; e_ops = [σz, a' * a]) # ## Solve stationary state of ADOs # (see also [Stationary State](@ref doc-Stationary-State)) steady_H = steadystate(M_Heom); # ## Expectation values # observable of atom: $\sigma_z$ σz_evo_H = real(sol_H.expect[1, :]) σz_steady_H = expect(σz, steady_H) # observable of cavity: $a^\dagger a$ (average photon number) np_evo_H = real(sol_H.expect[2, :]) np_steady_H = expect(a' * a, steady_H) p1 = Plots.plot( t_list, [σz_evo_H, ones(length(t_list)) .* σz_steady_H], label = [L"\langle \sigma_z \rangle" L"\langle \sigma_z \rangle ~~(\textrm{steady})"], linewidth = 3, linestyle = [:solid :dash], ) p2 = Plots.plot( t_list, [np_evo_H, ones(length(t_list)) .* np_steady_H], label = [L"\langle a^\dagger a \rangle" L"\langle a^\dagger a \rangle ~~(\textrm{steady})"], linewidth = 3, linestyle = [:solid :dash], ) Plots.plot(p1, p2, layout = [1, 1]) Plots.xaxis!("t") # ## Power spectrum # (see also [Spectrum](@ref doc-Spectrum)) ω_list = 1:0.01:3 psd_H = PowerSpectrum(M_Heom, steady_H, a, ω_list) Plots.plot(ω_list, psd_H, linewidth = 3) Plots.xaxis!(L"\omega") # ## Compare with Master Eq. approach # (see also [HEOMLS for Master Equations](@ref doc-Master-Equation)) # # The Lindblad master equations which describs the cavity couples to an extra bosonic reservoir with [Drude-Lorentzian spectral density](@ref Boson-Drude-Lorentz) is given by ## Drude_Lorentzian spectral density Drude_Lorentz(ω, Γ, W) = 4 * Γ * W * ω / ((ω)^2 + (W)^2) ## Bose-Einstein distribution n_b(ω, kT) = 1 / (exp(ω / kT) - 1) ## build the jump operators jump_op = [sqrt(Drude_Lorentz(ωc, Γ, W) * (n_b(ωc, kT) + 1)) * a, sqrt(Drude_Lorentz(ωc, Γ, W) * (n_b(ωc, kT))) * a', J_pump]; ## construct the HEOMLS matrix for master equation M_master = M_S(H_s) M_master = addBosonDissipator(M_master, jump_op) ## time evolution sol_M = HEOMsolve(M_master, ψ0, t_list; e_ops = [σz, a' * a]); ## steady state steady_M = steadystate(M_master); ## expectation value of σz σz_evo_M = real(sol_M.expect[1, :]) σz_steady_M = expect(σz, steady_M) ## average photon number np_evo_M = real(sol_M.expect[2, :]) np_steady_M = expect(a' * a, steady_M) p1 = Plots.plot( t_list, [σz_evo_M, ones(length(t_list)) .* σz_steady_M], label = [L"\langle \sigma_z \rangle" L"\langle \sigma_z \rangle ~~(\textrm{steady})"], linewidth = 3, linestyle = [:solid :dash], ) p2 = Plots.plot( t_list, [np_evo_M, ones(length(t_list)) .* np_steady_M], label = [L"\langle a^\dagger a \rangle" L"\langle a^\dagger a \rangle ~~(\textrm{steady})"], linewidth = 3, linestyle = [:solid :dash], ) Plots.plot(p1, p2, layout = [1, 1]) Plots.xaxis!("t") # We can also calculate the power spectrum ω_list = 1:0.01:3 psd_M = PowerSpectrum(M_master, steady_M, a, ω_list) Plots.plot(ω_list, psd_M, linewidth = 3) Plots.xaxis!(L"\omega") # Due to the weak coupling between the system and an extra bosonic environment, the Master equation's outcome is expected to be similar to the results obtained from the HEOM method.
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
5219
# # [Driven Systems and Dynamical Decoupling](@id exp-dynamical-decoupling) # In this page, we show how to solve the time evolution with time-dependent Hamiltonian problems in hierarchical equations of motion approach. using QuantumToolbox using HierarchicalEOM using LaTeXStrings import Plots # Here, we study dynamical decoupling which is a common tool used to undo the dephasing effect from the environment even for finite pulse duration. # # ## Hamiltonian # We consider a two-level system coupled to a bosonic reservoir ($\textrm{b}$). The total Hamiltonian is given by $H_{\textrm{T}}=H_\textrm{s}+H_\textrm{b}+H_\textrm{sb}$, where each terms takes the form # ```math # \begin{aligned} # H_{\textrm{s}}(t) &= H_0 + H_{\textrm{D}}(t),\\ # H_0 &= \frac{\omega_0}{2} \sigma_z,\\ # H_{\textrm{b}} &=\sum_{k}\omega_{k}b_{k}^{\dagger}b_{k},\\ # H_{\textrm{sb}} &=\sigma_z\sum_{k}g_{\alpha,k}(b_k + b_k^{\dagger}). # \end{aligned} # ``` # Here, $H_{\textrm{b}}$ describes a bosonic reservoir where $b_{k}$ $(b_{k}^{\dagger})$ is the bosonic annihilation (creation) operator associated to the $k$th mode (with frequency $\omega_{k}$). # # Furthermore, to observe the time evolution of the coherence, we consider the initial state to be # ```math # ψ(t=0)=\frac{1}{\sqrt{2}}\left(|0\rangle+|1\rangle\right) # ``` # Now, we need to build the system Hamiltonian and initial state with the package [`QuantumToolbox.jl`](https://github.com/qutip/QuantumToolbox.jl) to construct the operators. ω0 = 0.0 σz = sigmaz() σx = sigmax() H0 = 0.5 * ω0 * σz ## Define the operator that measures the 0, 1 element of density matrix ρ01 = Qobj([0 1; 0 0]) ψ0 = (basis(2, 0) + basis(2, 1)) / √2; # The time-dependent driving term $H_{\textrm{D}}(t)$ has the form # ```math # H_{\textrm{D}}(t) = \sum_{n=1}^N f_n(t) \sigma_x # ``` # where the pulse is chosen to have duration $\tau$ together with a delay $\Delta$ between each pulses, namely # ```math # f_n(t) # = \begin{cases} # V & \textrm{if}~~(n-1)\tau + n\Delta \leq t \leq n (\tau + \Delta),\\ # 0 & \textrm{otherwise}. # \end{cases} # ``` # Here, we set the period of the pulses to be $\tau V = \pi/2$. Therefore, we consider two scenarios with fast and slow pulses: ## a function which returns the amplitude of the pulse at time t function pulse(V, Δ, t) τ = 0.5 * π / V period = τ + Δ if (t % period) < τ return V else return 0 end end tlist = 0:0.4:400 amp_fast = 0.50 amp_slow = 0.01 delay = 20 Plots.plot( tlist, [[pulse(amp_fast, delay, t) for t in tlist], [pulse(amp_slow, delay, t) for t in tlist]], label = ["Fast Pulse" "Slow Pulse"], linestyle = [:solid :dash], ) # ## Construct bath objects # We assume the bosonic reservoir to have a [Drude-Lorentz Spectral Density](@ref Boson-Drude-Lorentz), and we utilize the Padé decomposition. Furthermore, the spectral densities depend on the following physical parameters: # - the coupling strength $\Gamma$ between system and reservoir # - the band-width $W$ # - the product of the Boltzmann constant $k$ and the absolute temperature $T$ : $kT$ # - the total number of exponentials for the reservoir $(N + 1)$ Γ = 0.0005 W = 0.005 kT = 0.05 N = 3 bath = Boson_DrudeLorentz_Pade(σz, Γ, W, kT, N) # ## Construct HEOMLS matrix # (see also [HEOMLS Matrix for Bosonic Baths](@ref doc-M_Boson)) # !!! note "Note" # Only provide the **time-independent** part of system Hamiltonian when constructing HEOMLS matrices (the time-dependent part `H_t` should be given when solving the time evolution). tier = 6 M = M_Boson(H0, tier, bath) # ## time evolution with time-independent Hamiltonian # (see also [Time Evolution](@ref doc-Time-Evolution)) noPulseSol = HEOMsolve(M, ψ0, tlist; e_ops = [ρ01]); # ## Solve time evolution with time-dependent Hamiltonian # (see also [Time Evolution](@ref doc-Time-Evolution)) # # We need to provide a user-defined function (named as `H_D` in this case), which must be in the form `H_D(t, p::NamedTuple)` and returns the time-dependent part of system Hamiltonian (in `QuantumObject` type) at any given time point `t`. The parameter `p` should be a `NamedTuple` which contains all the extra parameters [`V` (amplitude), `Δ` (delay), and `σx` (operator) in this case] for the function `H_D`: H_D(t, p::NamedTuple) = pulse(p.V, p.Δ, t) * p.σx; # The parameter `p` will be passed to your function `H_D` directly from the **last required** parameter in `HEOMsolve`: fastTuple = (V = amp_fast, Δ = delay, σx = σx) slowTuple = (V = amp_slow, Δ = delay, σx = σx) fastPulseSol = HEOMsolve(M, ψ0, tlist; e_ops = [ρ01], H_t = H_D, params = fastTuple) slowPulseSol = HEOMsolve(M, ψ0, tlist; e_ops = [ρ01], H_t = H_D, params = slowTuple) # ## Plot the coherence Plots.plot( tlist, [real(fastPulseSol.expect[1, :]), real(slowPulseSol.expect[1, :]), real(noPulseSol.expect[1, :])], label = ["Fast Pulse" "Slow Pulse" "no Pulse"], linestyle = [:solid :dot :dash], linewidth = 3, xlabel = L"t", ylabel = L"\rho_{01}", grid = false, ) # This example is from QuTiP-BoFiN paper : [Phys. Rev. Research 5, 013181 (2023)](https://link.aps.org/doi/10.1103/PhysRevResearch.5.013181).
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
5285
# # Electronic Current # # In this example, we demonstrate how to compute an environmental observable: the electronic current. import QuantumToolbox using HierarchicalEOM using LaTeXStrings import Plots # ## Hamiltonian # We consider a single-level charge system coupled to two [left (L) and right (R)] fermionic reservoirs ($\textrm{f}$). The total Hamiltonian is given by $H_{\textrm{T}}=H_\textrm{s}+H_\textrm{f}+H_\textrm{sf}$, where each terms takes the form # ```math # \begin{aligned} # H_{\textrm{s}} &= \epsilon d^\dagger d,\\ # H_{\textrm{f}} &=\sum_{\alpha=\textrm{L},\textrm{R}}\sum_{k}\epsilon_{\alpha,k}c_{\alpha,k}^{\dagger}c_{\alpha,k},\\ # H_{\textrm{sf}} &=\sum_{\alpha=\textrm{L},\textrm{R}}\sum_{k}g_{\alpha,k}c_{\alpha,k}^{\dagger}d + g_{\alpha,k}^* d^{\dagger}c_{\alpha,k}. # \end{aligned} # ``` # Here, $d$ $(d^\dagger)$ annihilates (creates) an electron in the system and $\epsilon$ is the energy of the electron. Furthermore, $c_{\alpha,k}$ $(c_{\alpha,k}^{\dagger})$ annihilates (creates) an electron in the state $k$ (with energy $\epsilon_{\alpha,k}$) of the $\alpha$-th reservoir. # # Now, we need to build the system Hamiltonian and initial state with the package [`QuantumToolbox.jl`](https://github.com/qutip/QuantumToolbox.jl) to construct the operators. d = destroy(2) ## annihilation operator of the system electron ## The system Hamiltonian ϵ = 1.0 # site energy Hsys = ϵ * d' * d ## System initial state ψ0 = basis(2, 0); # ## Construct bath objects # We assume the fermionic reservoir to have a [Lorentzian-shaped spectral density](@ref doc-Fermion-Lorentz), and we utilize the Padé decomposition. Furthermore, the spectral densities depend on the following physical parameters: # - the coupling strength $\Gamma$ between system and reservoirs # - the band-width $W$ # - the product of the Boltzmann constant $k$ and the absolute temperature $T$ : $kT$ # - the chemical potential $\mu$ # - the total number of exponentials for the reservoir $2(N + 1)$ Γ = 0.01 W = 1 kT = 0.025851991 μL = 1.0 # Left bath μR = -1.0 # Right bath N = 2 bath_L = Fermion_Lorentz_Pade(d, Γ, μL, W, kT, N) bath_R = Fermion_Lorentz_Pade(d, Γ, μR, W, kT, N) baths = [bath_L, bath_R] # ## Construct HEOMLS matrix # (see also [HEOMLS Matrix for Fermionic Baths](@ref doc-M_Fermion)) tier = 5 M = M_Fermion(Hsys, tier, baths) # ## Solve time evolution of ADOs # (see also [Time Evolution](@ref doc-Time-Evolution)) tlist = 0:0.5:100 ados_evolution = HEOMsolve(M, ψ0, tlist).ados; # ## Solve stationary state of ADOs # (see also [Stationary State](@ref doc-Stationary-State)) ados_steady = steadystate(M); # ## Calculate current # Within the influence functional approach, the expectation value of the electronic current from the $\alpha$-fermionic bath into the system can be written in terms of the first-level-fermionic ($n=1$) auxiliary density operators, namely # ```math # \langle I_\alpha(t) \rangle =(-e) \frac{d\langle \mathcal{N}_\alpha\rangle}{dt}=i e \sum_{q\in\textbf{q}}(-1)^{\delta_{\nu,-}} ~\textrm{Tr}\left[d^{\bar{\nu}}\rho^{(0,1,+)}_{\vert \textbf{q}}(t)\right], # ``` # where $e$ represents the value of the elementary charge, and $\mathcal{N}_\alpha=\sum_k c^\dagger_{\alpha,k}c_{\alpha,k}$ is the occupation number operator for the $\alpha$-fermionic bath. # # Given an ADOs, we provide a function which calculates the current from the $\alpha$-fermionic bath into the system with the help of [Hierarchy Dictionary](@ref doc-Hierarchy-Dictionary). # # `bathIdx`: # - 1 means 1st bath (bath_L) # - 2 means 2nd bath (bath_R) function Ic(ados, M::M_Fermion, bathIdx::Int) ## the hierarchy dictionary HDict = M.hierarchy ## we need all the indices of ADOs for the first level idx_list = HDict.lvl2idx[1] I = 0.0im for idx in idx_list ρ1 = ados[idx] ## 1st-level ADO ## find the corresponding bath index (α) and exponent term index (k) nvec = HDict.idx2nvec[idx] for (α, k, _) in getIndexEnsemble(nvec, HDict.bathPtr) if α == bathIdx exponent = M.bath[α][k] if exponent.types == "fA" ## fermion-absorption I += tr(exponent.op' * ρ1) elseif exponent.types == "fE" ## fermion-emission I -= tr(exponent.op' * ρ1) end break end end end eV_to_Joule = 1.60218E-19 # unit conversion ## (e / ħ) * I [change unit to μA] return 1.519270639695384E15 * real(1im * I) * eV_to_Joule * 1E6 end ## steady current Is_L = ones(length(tlist)) .* Ic(ados_steady, M, 1) Is_R = ones(length(tlist)) .* Ic(ados_steady, M, 2) ## time evolution current Ie_L = [] Ie_R = [] for ados in ados_evolution push!(Ie_L, Ic(ados, M, 1)) push!(Ie_R, Ic(ados, M, 2)) end Plots.plot( tlist, [Ie_L, Ie_R, Is_L, Is_R], label = ["Bath L" "Bath R" "Bath L (Steady State)" "Bath R (Steady State)"], linecolor = [:blue :red :blue :red], linestyle = [:solid :solid :dash :dash], linewidth = 3, xlabel = "time", ylabel = "Current", grid = false, ) # Note that this example can also be found in [qutip documentation](https://qutip.org/docs/latest/guide/heom/fermionic.html#steady-state-currents)
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
6997
# # Quick Start # # ### Content # - [Import HierarchicalEOM.jl](#Import-HierarchicalEOM.jl) # - [System and Bath](#System-and-Bath) # - [HEOM Liouvillian superoperator](#HEOM-Liouvillian-superoperator) # - [Time Evolution](#Time-Evolution) # - [Stationary State](#Stationary-State) # - [Reduced Density Operator](#Reduced-Density-Operator) # - [Expectation Value](#Expectation-Value) # - [Multiple Baths](#Multiple-Baths) # ### Import HierarchicalEOM.jl # Here are the functions in `HierarchicalEOM.jl` that we will use in this tutorial (Quick Start): import HierarchicalEOM import HierarchicalEOM: Boson_DrudeLorentz_Pade, M_Boson, HEOMsolve, getRho, BosonBath # Note that you can also type `using HierarchicalEOM` to import everything you need in `HierarchicalEOM.jl`. # To check the versions of dependencies of `HierarchicalEOM.jl`, run the following function HierarchicalEOM.versioninfo() # ### System and Bath # Let us consider a simple two-level system coupled to a Drude-Lorentz bosonic bath. The system Hamiltonian, ``H_{sys}``, and the bath spectral density, ``J_D``, are # ```math # H_{sys}=\frac{\epsilon \sigma_z}{2} + \frac{\Delta \sigma_x}{2} ~~\text{and} # ``` # ```math # J_{D}(\omega)=\frac{2\lambda W\omega}{W^2+\omega^2}, # ``` # #### System Hamiltonian and initial state # You must construct system hamiltonian, initial state, and coupling operators by [`QuantumToolbox`](https://github.com/qutip/QuantumToolbox.jl) framework. It provides many useful functions to create arbitrary quantum states and operators which can be combined in all the expected ways. import QuantumToolbox: Qobj, sigmaz, sigmax, basis, ket2dm, expect, steadystate ## The system Hamiltonian ϵ = 0.5 # energy of 2-level system Δ = 1.0 # tunneling term Hsys = 0.5 * ϵ * sigmaz() + 0.5 * Δ * sigmax() ## System initial state ρ0 = ket2dm(basis(2, 0)); ## Define the operators that measure the populations of the two system states: P00 = ket2dm(basis(2, 0)) P11 = ket2dm(basis(2, 1)) ## Define the operator that measures the 0, 1 element of density matrix ## (corresponding to coherence): P01 = basis(2, 0) * basis(2, 1)' # #### Bath Properties # Now, we demonstrate how to describe the bath using the built-in implementation of ``J_D(\omega)`` under Pade expansion by calling [`Boson_DrudeLorentz_Pade`](@ref) λ = 0.1 # coupling strength W = 0.5 # band-width (cut-off frequency) kT = 0.5 # the product of the Boltzmann constant k and the absolute temperature T Q = sigmaz() # system-bath coupling operator N = 2 # Number of expansion terms to retain: ## Padé expansion: bath = Boson_DrudeLorentz_Pade(Q, λ, W, kT, N) # For other different expansions of the different spectral density correlation functions, please refer to [Bosonic Bath](@ref doc-Bosonic-Bath) and [Fermionic Bath](@ref doc-Fermionic-Bath). # ### HEOM Liouvillian superoperator # For bosonic bath, we can construct the HEOM Liouvillian superoperator matrix by calling [`M_Boson`](@ref) tier = 5 # maximum tier of hierarchy L = M_Boson(Hsys, tier, bath) # To learn more about the HEOM Liouvillian superoperator matrix (including other types: `M_Fermion`, `M_Boson_Fermion`), please refer to [HEOMLS Matrices](@ref doc-HEOMLS-Matrix). # ### Time Evolution # Next, we can calculate the time evolution for the entire auxiliary density operators (ADOs) by calling [`HEOMsolve`](@ref) tlist = 0:0.2:50 sol = HEOMsolve(L, ρ0, tlist; e_ops = [P00, P11, P01]) # To learn more about `HEOMsolve`, please refer to [Time Evolution](@ref doc-Time-Evolution). # ### Stationary State # We can also solve the stationary state of the auxiliary density operators (ADOs) by calling [`steadystate`](@ref). ados_steady = steadystate(L) # To learn more about `steadystate`, please refer to [Stationary State](@ref doc-Stationary-State). # ### Reduced Density Operator # To obtain the reduced density operator, one can either access the first element of auxiliary density operator (`ADOs`) or call [`getRho`](@ref): ## reduce density operator in the final time (`end`) of the evolution ados_list = sol.ados ρ = ados_list[end][1] # index `1` represents the reduced density operator ρ = getRho(ados_list[end]) ## reduce density operator in stationary state ρ = ados_steady[1] ρ = getRho(ados_steady) # One of the great features of `HierarchicalEOM.jl` is that we allow users to not only considering the density operator of the reduced # state but also easily take high-order terms into account without struggling in finding the indices (see [Auxiliary Density Operators](@ref doc-ADOs) and [Hierarchy Dictionary](@ref doc-Hierarchy-Dictionary) for more details). # ### Expectation Value # We can now compare the results obtained from `HEOMsolve` and `steadystate`: ## for time evolution p00_e = real(sol.expect[1, :]) # P00 is the 1st element in e_ops p01_e = real(sol.expect[3, :]); # P01 is the 3rd element in e_ops ## for steady state p00_s = expect(P00, ados_steady) p01_s = expect(P01, ados_steady); # ### Plot the results using Plots, LaTeXStrings plot(tlist, p00_e, label = L"\textrm{P}_{00}", linecolor = :blue, linestyle = :solid, linewidth = 3, grid = false) plot!(tlist, p01_e, label = L"\textrm{P}_{01}", linecolor = :red, linestyle = :solid, linewidth = 3) plot!( tlist, ones(length(tlist)) .* p00_s, label = L"\textrm{P}_{00} \textrm{(Steady State)}", linecolor = :blue, linestyle = :dash, linewidth = 3, ) plot!( tlist, ones(length(tlist)) .* p01_s, label = L"\textrm{P}_{01} \textrm{(Steady State)}", linecolor = :red, linestyle = :dash, linewidth = 3, ) xlabel!("time") ylabel!("Population") # ### Multiple Baths # `HierarchicalEOM.jl` also supports for system to interact with multiple baths. # All you need to do is to provide a list of baths instead of a single bath ## The system Hamiltonian Hsys = Qobj([ 0.25 1.50 2.50 1.50 0.75 3.50 2.50 3.50 1.25 ]) ## System initial state ρ0 = ket2dm(basis(3, 0)); ## Projector for each system state: P00 = ket2dm(basis(3, 0)) P11 = ket2dm(basis(3, 1)) P22 = ket2dm(basis(3, 2)); ## Construct one bath for each system state: ## note that `BosonBath[]` make the list created in type: Vector{BosonBath} baths = BosonBath[] for i in 0:2 ## system-bath coupling operator: |i><i| Q = ket2dm(basis(3, i)) push!(baths, Boson_DrudeLorentz_Pade(Q, λ, W, kT, N)) end L = M_Boson(Hsys, tier, baths) tlist = 0:0.025:5 sol = HEOMsolve(L, ρ0, tlist; e_ops = [P00, P11, P22]) ## calculate population for each system state: p0 = real(sol.expect[1, :]) p1 = real(sol.expect[2, :]) p2 = real(sol.expect[3, :]) plot(tlist, p0, linewidth = 3, linecolor = "blue", label = L"P_0", grid = false) plot!(tlist, p1, linewidth = 3, linecolor = "orange", label = L"P_1") plot!(tlist, p2, linewidth = 3, linecolor = :green, label = L"P_2") xlabel!("time") ylabel!("Population") # Note that this example can also be found in [qutip documentation](https://qutip.org/docs/latest/guide/heom/bosonic.html).
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
4082
module HierarchicalEOM_CUDAExt using HierarchicalEOM import HierarchicalEOM.HeomBase: AbstractHEOMLSMatrix, _Tr, _HandleVectorType, _HandleIdentityType import CUDA import CUDA: cu, CuArray import CUDA.CUSPARSE: CuSparseVector, CuSparseMatrixCSC import SparseArrays: sparse, SparseVector, SparseMatrixCSC @doc raw""" cu(M::AbstractHEOMLSMatrix) Return a new HEOMLS-matrix-type object with `M.data` is in the type of `CuSparseMatrixCSC{ComplexF32, Int32}` for gpu calculations. """ cu(M::AbstractHEOMLSMatrix) = CuSparseMatrixCSC(M) @doc raw""" CuSparseMatrixCSC(M::AbstractHEOMLSMatrix) Return a new HEOMLS-matrix-type object with `M.data` is in the type of `CuSparseMatrixCSC{ComplexF32, Int32}` for gpu calculations. """ function CuSparseMatrixCSC(M::T) where {T<:AbstractHEOMLSMatrix} A = M.data if typeof(A) <: CuSparseMatrixCSC return M else colptr = CuArray{Int32}(A.colptr) rowval = CuArray{Int32}(A.rowval) nzval = CuArray{ComplexF32}(A.nzval) A_gpu = CuSparseMatrixCSC{ComplexF32,Int32}(colptr, rowval, nzval, size(A)) if T <: M_S return M_S(A_gpu, M.tier, M.dims, M.N, M.sup_dim, M.parity) elseif T <: M_Boson return M_Boson(A_gpu, M.tier, M.dims, M.N, M.sup_dim, M.parity, M.bath, M.hierarchy) elseif T <: M_Fermion return M_Fermion(A_gpu, M.tier, M.dims, M.N, M.sup_dim, M.parity, M.bath, M.hierarchy) else return M_Boson_Fermion( A_gpu, M.Btier, M.Ftier, M.dims, M.N, M.sup_dim, M.parity, M.Bbath, M.Fbath, M.hierarchy, ) end end end function CuSparseMatrixCSC{ComplexF32}(M::HEOMSuperOp) A = M.data AType = typeof(A) if AType == CuSparseMatrixCSC{ComplexF32,Int32} return M elseif AType <: CuSparseMatrixCSC colptr = CuArray{Int32}(A.colPtr) rowval = CuArray{Int32}(A.rowVal) nzval = CuArray{ComplexF32}(A.nzVal) A_gpu = CuSparseMatrixCSC{ComplexF32,Int32}(colptr, rowval, nzval, size(A)) return HEOMSuperOp(A_gpu, M.dims, M.N, M.parity) else colptr = CuArray{Int32}(A.colptr) rowval = CuArray{Int32}(A.rowval) nzval = CuArray{ComplexF32}(A.nzval) A_gpu = CuSparseMatrixCSC{ComplexF32,Int32}(colptr, rowval, nzval, size(A)) return HEOMSuperOp(A_gpu, M.dims, M.N, M.parity) end end function _Tr(M::AbstractHEOMLSMatrix{T}) where {T<:CuSparseMatrixCSC} D = prod(M.dims) return CuSparseVector(SparseVector(M.N * D^2, [1 + n * (D + 1) for n in 0:(D-1)], ones(eltype(M), D))) end # for changing a `CuArray` back to `ADOs` _HandleVectorType(V::T, cp::Bool = false) where {T<:CuArray} = Vector{ComplexF64}(V) # for changing the type of `ADOs` to match the type of HEOMLS matrix function _HandleVectorType(MatrixType::Type{TM}, V::SparseVector) where {TM<:CuSparseMatrixCSC} TE = eltype(MatrixType) return CuArray{TE}(V) end ##### We first remove this part because there are errors when solveing steady states using GPU # function _HandleSteadyStateMatrix(MatrixType::Type{TM}, M::AbstractHEOMLSMatrix, S::Int) where TM <: CuSparseMatrixCSC # colptr = Vector{Int32}(M.data.colPtr) # rowval = Vector{Int32}(M.data.rowVal) # nzval = Vector{ComplexF32}(M.data.nzVal) # A = SparseMatrixCSC{ComplexF32, Int32}(S, S, colptr, rowval, nzval) # A[1,1:S] .= 0f0 # # # sparse(row_idx, col_idx, values, row_dims, col_dims) # A += sparse(ones(Int32, M.dim), [Int32((n - 1) * (M.dim + 1) + 1) for n in 1:(M.dim)], ones(ComplexF32, M.dim), S, S) # return CuSparseMatrixCSC(A) # end function _HandleIdentityType(MatrixType::Type{TM}, S::Int) where {TM<:CuSparseMatrixCSC} colptr = CuArray{Int32}(Int32(1):Int32(S + 1)) rowval = CuArray{Int32}(Int32(1):Int32(S)) nzval = CUDA.ones(ComplexF32, S) return CuSparseMatrixCSC{ComplexF32,Int32}(colptr, rowval, nzval, (S, S)) end end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
7091
@doc raw""" struct ADOs The Auxiliary Density Operators for HEOM model. # Fields - `data` : the vectorized auxiliary density operators - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of auxiliary density operators - `parity`: the parity label (`EVEN` or `ODD`). # Methods One can obtain the density matrix for specific index (`idx`) by calling : `ados[idx]`. `HierarchicalEOM.jl` also supports the following calls (methods) : ```julia length(ados); # returns the total number of `ADOs` ados[1:idx]; # returns a vector which contains the `ADO` (in matrix form) from index `1` to `idx` ados[1:end]; # returns a vector which contains all the `ADO` (in matrix form) ados[:]; # returns a vector which contains all the `ADO` (in matrix form) for rho in ados # iteration # do something end ``` """ struct ADOs data::SparseVector{ComplexF64,Int64} dims::SVector N::Int parity::AbstractParity end # these functions are for forward compatibility ADOs(data::SparseVector{ComplexF64,Int64}, dim::Int, N::Int, parity::AbstractParity) = ADOs(data, [dim], N, parity) ADOs(data::SparseVector{ComplexF64,Int64}, dims::AbstractVector, N::Int, parity::AbstractParity) = ADOs(data, SVector{length(dims),Int}(dims), N, parity) @doc raw""" ADOs(V, N, parity) Gernerate the object of auxiliary density operators for HEOM model. # Parameters - `V::AbstractVector` : the vectorized auxiliary density operators - `N::Int` : the number of auxiliary density operators. - `parity::AbstractParity` : the parity label (`EVEN` or `ODD`). Default to `EVEN`. """ function ADOs(V::AbstractVector, N::Int, parity::AbstractParity = EVEN) # check the dimension of V d = size(V, 1) dim = √(d / N) if isinteger(dim) return ADOs(sparsevec(V), SVector{1,Int}(Int(dim)), N, parity) else error("The dimension of vector is not consistent with the ADOs number \"N\".") end end @doc raw""" ADOs(ρ, N, parity) Gernerate the object of auxiliary density operators for HEOM model. # Parameters - `ρ` : the reduced density operator - `N::Int` : the number of auxiliary density operators. - `parity::AbstractParity` : the parity label (`EVEN` or `ODD`). Default to `EVEN`. """ function ADOs(ρ::QuantumObject, N::Int = 1, parity::AbstractParity = EVEN) _ρ = sparsevec(ket2dm(ρ).data) return ADOs(sparsevec(_ρ.nzind, _ρ.nzval, N * length(_ρ)), ρ.dims, N, parity) end ADOs(ρ, N::Int = 1, parity::AbstractParity = EVEN) = error("HierarchicalEOM doesn't support input `ρ` with type : $(typeof(ρ))") checkbounds(A::ADOs, i::Int) = ((i > A.N) || (i < 1)) ? error("Attempt to access $(A.N)-element ADOs at index [$(i)]") : nothing @doc raw""" length(A::ADOs) Returns the total number of the Auxiliary Density Operators (ADOs) """ length(A::ADOs) = A.N @doc raw""" eltype(A::ADOs) Returns the elements' type of the Auxiliary Density Operators (ADOs) """ eltype(A::ADOs) = eltype(A.data) lastindex(A::ADOs) = length(A) function getindex(A::ADOs, i::Int) checkbounds(A, i) D = prod(A.dims) sup_dim = D^2 back = sup_dim * i return QuantumObject(reshape(A.data[(back-sup_dim+1):back], D, D), Operator, A.dims) end function getindex(A::ADOs, r::UnitRange{Int}) checkbounds(A, r[1]) checkbounds(A, r[end]) result = [] D = prod(A.dims) sup_dim = D^2 for i in r back = sup_dim * i push!(result, QuantumObject(reshape(A.data[(back-sup_dim+1):back], D, D), Operator, A.dims)) end return result end getindex(A::ADOs, ::Colon) = getindex(A, 1:lastindex(A)) iterate(A::ADOs, state::Int = 1) = state > length(A) ? nothing : (A[state], state + 1) show(io::IO, A::ADOs) = print(io, "$(A.N) Auxiliary Density Operators with $(A.parity) and (system) dims = $(A.dims)\n") show(io::IO, m::MIME"text/plain", A::ADOs) = show(io, A) @doc raw""" getRho(ados) Return the density matrix of the reduced state (system) from a given auxiliary density operators # Parameters - `ados::ADOs` : the auxiliary density operators for HEOM model # Returns - `ρ::QuantumObject` : The density matrix of the reduced state """ function getRho(ados::ADOs) D = prod(ados.dims) return QuantumObject(reshape(ados.data[1:(D^2)], D, D), Operator, ados.dims) end @doc raw""" getADO(ados, idx) Return the auxiliary density operator with a specific index from auxiliary density operators This function equals to calling : `ados[idx]`. # Parameters - `ados::ADOs` : the auxiliary density operators for HEOM model - `idx::Int` : the index of the auxiliary density operator # Returns - `ρ_idx::QuantumObject` : The auxiliary density operator """ getADO(ados::ADOs, idx::Int) = ados[idx] @doc raw""" expect(op, ados; take_real=true) Return the expectation value of the operator `op` for the reduced density operator in the given `ados`, namely ```math \textrm{Tr}\left[ O \rho \right], ``` where ``O`` is the operator and ``\rho`` is the reduced density operator in the given ADOs. # Parameters - `op` : the operator ``O`` to take the expectation value - `ados::ADOs` : the auxiliary density operators for HEOM model - `take_real::Bool` : whether to automatically take the real part of the trace or not. Default to `true` # Returns - `exp_val` : The expectation value """ function expect(op, ados::ADOs; take_real::Bool = true) if typeof(op) <: HEOMSuperOp _check_sys_dim_and_ADOs_num(op, ados) exp_val = dot(transpose(_Tr(ados.dims, ados.N)), (SparseMatrixCSC(op) * ados).data) else _op = HandleMatrixType(op, ados.dims, "op (observable)"; type = Operator) exp_val = tr(_op.data * getRho(ados).data) end if take_real return real(exp_val) else return exp_val end end @doc raw""" expect(op, ados_list; take_real=true) Return a list of expectation values of the operator `op` corresponds to the reduced density operators in the given `ados_list`, namely ```math \textrm{Tr}\left[ O \rho \right], ``` where ``O`` is the operator and ``\rho`` is the reduced density operator in one of the `ADOs` from `ados_list`. # Parameters - `op` : the operator ``O`` to take the expectation value - `ados_list::Vector{ADOs}` : the list of auxiliary density operators for HEOM model - `take_real::Bool` : whether to automatically take the real part of the trace or not. Default to `true` # Returns - `exp_val` : The expectation value """ function expect(op, ados_list::Vector{ADOs}; take_real::Bool = true) dims = ados_list[1].dims N = ados_list[1].N for i in 2:length(ados_list) _check_sys_dim_and_ADOs_num(ados_list[1], ados_list[i]) end if typeof(op) <: HEOMSuperOp _check_sys_dim_and_ADOs_num(op, ados_list[1]) _op = op else _op = HEOMSuperOp(op, EVEN, dims, N, "L") end tr_op = transpose(_Tr(dims, N)) * SparseMatrixCSC(_op).data exp_val = [dot(tr_op, ados.data) for ados in ados_list] if take_real return real.(exp_val) else return exp_val end end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
38895
abstract type AbstractBath end abstract type AbstractBosonBath end abstract type AbstractFermionBath end @doc raw""" struct Exponent An object which describes a single exponential-expansion term (naively, an excitation mode) within the decomposition of the bath correlation functions. The expansion of a bath correlation function can be expressed as : ``C(t) = \sum_i \eta_i \exp(-\gamma_i t)``. # Fields - `op::QuantumObject` : The system coupling operator according to system-bath interaction. - `η::Number` : the coefficient ``\eta_i`` in bath correlation function. - `γ::Number` : the coefficient ``\gamma_i`` in bath correlation function. - `types::String` : The type-tag of the exponent. The different types of the Exponent: - `\"bR\"` : from real part of bosonic correlation function ``C^{u=\textrm{R}}(t)`` - `\"bI\"` : from imaginary part of bosonic correlation function ``C^{u=\textrm{I}}(t)`` - `\"bRI\"` : from combined (real and imaginary part) bosonic bath correlation function ``C(t)`` - `\"bA\"` : from absorption bosonic correlation function ``C^{\nu=+}(t)`` - `\"bE\"` : from emission bosonic correlation function ``C^{\nu=-}(t)`` - `\"fA\"` : from absorption fermionic correlation function ``C^{\nu=+}(t)`` - `\"fE\"` : from emission fermionic correlation function ``C^{\nu=-}(t)`` """ struct Exponent op::QuantumObject η::Number γ::Number types::String end show(io::IO, E::Exponent) = print(io, "Bath Exponent with types = \"$(E.types)\", η = $(E.η), γ = $(E.γ).\n") show(io::IO, m::MIME"text/plain", E::Exponent) = show(io, E) show(io::IO, B::AbstractBath) = print(io, "$(typeof(B)) object with $(B.Nterm) exponential-expansion terms\n") show(io::IO, m::MIME"text/plain", B::AbstractBath) = show(io, B) show(io::IO, B::AbstractBosonBath) = print(io, "$(typeof(B))-type bath with $(B.Nterm) exponential-expansion terms\n") show(io::IO, m::MIME"text/plain", B::AbstractBosonBath) = show(io, B) show(io::IO, B::AbstractFermionBath) = print(io, "$(typeof(B))-type bath with $(B.Nterm) exponential-expansion terms\n") show(io::IO, m::MIME"text/plain", B::AbstractFermionBath) = show(io, B) checkbounds(B::AbstractBath, i::Int) = ((i < 1) || (i > B.Nterm)) ? error("Attempt to access $(B.Nterm)-exponent term Bath at index [$(i)]") : nothing length(B::AbstractBath) = B.Nterm lastindex(B::AbstractBath) = B.Nterm function getindex(B::AbstractBath, i::Int) checkbounds(B, i) count = 0 for b in B.bath if i <= (count + b.Nterm) k = i - count b_type = typeof(b) if b_type == bosonRealImag η = b.η_real[k] + 1.0im * b.η_imag[k] types = "bRI" op = B.op else η = b.η[k] if b_type == bosonReal types = "bR" op = B.op elseif b_type == bosonImag types = "bI" op = B.op elseif b_type == bosonAbsorb types = "bA" op = B.op' elseif b_type == bosonEmit types = "bE" op = B.op elseif b_type == fermionAbsorb types = "fA" op = B.op' elseif b_type == fermionEmit types = "fE" op = B.op end end return Exponent(op, η, b.γ[k], types) else count += b.Nterm end end end function getindex(B::AbstractBath, r::UnitRange{Int}) checkbounds(B, r[1]) checkbounds(B, r[end]) count = 0 exp_list = Exponent[] for b in B.bath for k in 1:b.Nterm count += 1 if (r[1] <= count) && (count <= r[end]) b_type = typeof(b) if b_type == bosonRealImag η = b.η_real[k] + 1.0im * b.η_imag[k] types = "bRI" op = B.op else η = b.η[k] if b_type == bosonReal types = "bR" op = B.op elseif b_type == bosonImag types = "bI" op = B.op elseif b_type == bosonAbsorb types = "bA" op = B.op' elseif b_type == bosonEmit types = "bE" op = B.op elseif b_type == fermionAbsorb types = "fA" op = B.op' elseif b_type == fermionEmit types = "fE" op = B.op end end push!(exp_list, Exponent(op, η, b.γ[k], types)) end if count == r[end] return exp_list end end end end getindex(B::AbstractBath, ::Colon) = getindex(B, 1:B.Nterm) iterate(B::AbstractBath, state::Int = 1) = state > length(B) ? nothing : (B[state], state + 1) isclose(a::Number, b::Number, rtol = 1e-05, atol = 1e-08) = abs(a - b) <= (atol + rtol * abs(b)) function _check_bosonic_coupling_operator(op) _op = HandleMatrixType(op, "op (coupling operator)") if !ishermitian(_op) @warn "The system-bosonic-bath coupling operator \"op\" should be Hermitian Operator." end return _op end _check_bosonic_RWA_coupling_operator(op) = HandleMatrixType(op, "op (coupling operator)") function _check_gamma_absorb_and_emit(γ_absorb, γ_emit) len = length(γ_absorb) if length(γ_emit) == len for k in 1:len if !(γ_absorb[k] ≈ conj(γ_emit[k])) @warn "The elements in \'γ_absorb\' should be complex conjugate of the corresponding elements in \'γ_emit\'." end end else error("The length of \'γ_absorb\' and \'γ_emit\' should be the same.") end end _check_fermionic_coupling_operator(op) = HandleMatrixType(op, "op (coupling operator)") function _combine_same_gamma(η::Vector{Ti}, γ::Vector{Tj}) where {Ti,Tj<:Number} if length(η) != length(γ) error("The length of \'η\' and \'γ\' should be the same.") end ηnew = ComplexF64[η[1]] γnew = ComplexF64[γ[1]] for j in 2:length(γ) valueDontExist = true for k in 1:length(γnew) if isclose(γnew[k], γ[j]) ηnew[k] += η[j] valueDontExist = false end end if valueDontExist push!(ηnew, η[j]) push!(γnew, γ[j]) end end return ηnew, γnew end @doc raw""" struct BosonBath <: AbstractBath An object which describes the interaction between system and bosonic bath # Fields - `bath` : the different boson-bath-type objects which describes the interaction between system and bosonic bath - `op` : The system coupling operator, must be Hermitian and, for fermionic systems, even-parity to be compatible with charge conservation. - `Nterm` : the number of exponential-expansion term of correlation functions - `δ` : The approximation discrepancy which is used for adding the terminator to HEOM matrix (see function: addTerminator) # Methods One can obtain the ``k``-th exponent (exponential-expansion term) from `bath::BosonBath` by calling : `bath[k]`. `HierarchicalEOM.jl` also supports the following calls (methods) : ```julia bath[1:k]; # returns a vector which contains the exponents from the `1`-st to the `k`-th term. bath[1:end]; # returns a vector which contains all the exponential-expansion terms bath[:]; # returns a vector which contains all the exponential-expansion terms from b in bath # do something end ``` """ struct BosonBath <: AbstractBath bath::Vector{AbstractBosonBath} op::QuantumObject Nterm::Int δ::Number end @doc raw""" BosonBath(op, η, γ, δ=0.0; combine=true) Generate BosonBath object for the case where real part and imaginary part of the correlation function are combined. ```math \begin{aligned} C(\tau) &=\frac{1}{2\pi}\int_{0}^{\infty} d\omega J(\omega)\left[n(\omega)e^{i\omega \tau}+(n(\omega)+1)e^{-i\omega \tau}\right]\\ &=\sum_i \eta_i \exp(-\gamma_i \tau), \end{aligned} ``` where ``J(\omega)`` is the spectral density of the bath and ``n(\omega)`` represents the Bose-Einstein distribution. # Parameters - `op::QuantumObject` : The system coupling operator, must be Hermitian and, for fermionic systems, even-parity to be compatible with charge conservation. - `η::Vector{Ti<:Number}` : the coefficients ``\eta_i`` in bath correlation function ``C(\tau)``. - `γ::Vector{Tj<:Number}` : the coefficients ``\gamma_i`` in bath correlation function ``C(\tau)``. - `δ::Number` : The approximation discrepancy (Default to `0.0`) which is used for adding the terminator to HEOM matrix (see function: addTerminator) - `combine::Bool` : Whether to combine the exponential-expansion terms with the same frequency. Defaults to `true`. """ function BosonBath( op::QuantumObject, η::Vector{Ti}, γ::Vector{Tj}, δ::Number = 0.0; combine::Bool = true, ) where {Ti,Tj<:Number} _op = HandleMatrixType(op, "op (coupling operator)") if combine ηnew, γnew = _combine_same_gamma(η, γ) bRI = bosonRealImag(_op, real.(ηnew), imag.(ηnew), γnew) else bRI = bosonRealImag(_op, real.(η), imag.(η), γ) end return BosonBath(AbstractBosonBath[bRI], _op, bRI.Nterm, δ) end @doc raw""" BosonBath(op, η_real, γ_real, η_imag, γ_imag, δ=0.0; combine=true) Generate BosonBath object for the case where the correlation function splits into real part and imaginary part. ```math \begin{aligned} C(\tau) &=\frac{1}{2\pi}\int_{0}^{\infty} d\omega J(\omega)\left[n(\omega)e^{i\omega \tau}+(n(\omega)+1)e^{-i\omega \tau}\right]\\ &=\sum_i \eta_i \exp(-\gamma_i \tau), \end{aligned} ``` where ``J(\omega)`` is the spectral density of the bath and ``n(\omega)`` represents the Bose-Einstein distribution. When ``\gamma_i \neq \gamma_i^*``, a closed form for the HEOM can be obtained by further decomposing ``C(\tau)`` into its real (R) and imaginary (I) parts as ```math C(\tau)=\sum_{u=\textrm{R},\textrm{I}}(\delta_{u, \textrm{R}} + i\delta_{u, \textrm{I}})C^{u}(\tau) ``` where ``\delta`` is the Kronecker delta function and ``C^{u}(\tau)=\sum_i \eta_i^u \exp(-\gamma_i^u \tau)`` # Parameters - `op::QuantumObject` : The system coupling operator, must be Hermitian and, for fermionic systems, even-parity to be compatible with charge conservation. - `η_real::Vector{Ti<:Number}` : the coefficients ``\eta_i`` in real part of bath correlation function ``C^{u=\textrm{R}}``. - `γ_real::Vector{Tj<:Number}` : the coefficients ``\gamma_i`` in real part of bath correlation function ``C^{u=\textrm{R}}``. - `η_imag::Vector{Tk<:Number}` : the coefficients ``\eta_i`` in imaginary part of bath correlation function ``C^{u=\textrm{I}}``. - `γ_imag::Vector{Tl<:Number}` : the coefficients ``\gamma_i`` in imaginary part of bath correlation function ``C^{u=\textrm{I}}``. - `δ::Number` : The approximation discrepancy (Default to `0.0`) which is used for adding the terminator to HEOM matrix (see function: addTerminator) - `combine::Bool` : Whether to combine the exponential-expansion terms with the same frequency. Defaults to `true`. """ function BosonBath( op::QuantumObject, η_real::Vector{Ti}, γ_real::Vector{Tj}, η_imag::Vector{Tk}, γ_imag::Vector{Tl}, δ::Tm = 0.0; combine::Bool = true, ) where {Ti,Tj,Tk,Tl,Tm<:Number} _op = HandleMatrixType(op, "op (coupling operator)") if combine ηR, γR = _combine_same_gamma(η_real, γ_real) ηI, γI = _combine_same_gamma(η_imag, γ_imag) NR = length(γR) NI = length(γI) Nterm = NR + NI ηRI_real = ComplexF64[] ηRI_imag = ComplexF64[] γRI = ComplexF64[] real_idx = Int64[] imag_idx = Int64[] for j in 1:NR for k in 1:NI if isclose(γR[j], γI[k]) # record index push!(real_idx, j) push!(imag_idx, k) # append combined coefficient vectors push!(ηRI_real, ηR[j]) push!(ηRI_imag, ηI[k]) push!(γRI, γR[j]) end end end sort!(real_idx) sort!(imag_idx) deleteat!(ηR, real_idx) deleteat!(γR, real_idx) deleteat!(ηI, imag_idx) deleteat!(γI, imag_idx) bR = bosonReal(_op, ηR, γR) bI = bosonImag(_op, ηI, γI) bRI = bosonRealImag(_op, ηRI_real, ηRI_imag, γRI) Nterm_new = bR.Nterm + bI.Nterm + bRI.Nterm if Nterm != (Nterm_new + bRI.Nterm) error("Conflicts occur in combining real and imaginary parts of bath correlation function.") end return BosonBath(AbstractBosonBath[bR, bI, bRI], _op, Nterm_new, δ) else bR = bosonReal(_op, η_real, γ_real) bI = bosonImag(_op, η_imag, γ_imag) return BosonBath(AbstractBosonBath[bR, bI], _op, bR.Nterm + bI.Nterm, δ) end end @doc raw""" struct bosonReal <: AbstractBosonBath A bosonic bath for the real part of bath correlation function ``C^{u=\textrm{R}}`` # Fields - `Comm` : the super-operator (commutator) for the coupling operator. - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `η` : the coefficients ``\eta_i`` in real part of bath correlation function ``C^{u=\textrm{R}}``. - `γ` : the coefficients ``\gamma_i`` in real part of bath correlation function ``C^{u=\textrm{R}}``. - `Nterm` : the number of exponential-expansion term of correlation function """ struct bosonReal <: AbstractBosonBath Comm::SparseMatrixCSC{ComplexF64,Int64} dims::SVector η::AbstractVector γ::AbstractVector Nterm::Int end @doc raw""" bosonReal(op, η_real, γ_real) Generate bosonic bath for the real part of bath correlation function ``C^{u=\textrm{R}}`` # Parameters - `op::QuantumObject` : The system coupling operator, must be Hermitian and, for fermionic systems, even-parity to be compatible with charge conservation. - `η_real::Vector{Ti<:Number}` : the coefficients ``\eta_i`` in real part of bath correlation function ``C^{u=\textrm{R}}``. - `γ_real::Vector{Tj<:Number}` : the coefficients ``\gamma_i`` in real part of bath correlation function ``C^{u=\textrm{R}}``. """ function bosonReal(op::QuantumObject, η_real::Vector{Ti}, γ_real::Vector{Tj}) where {Ti,Tj<:Number} _op = _check_bosonic_coupling_operator(op) # check if the length of coefficients are valid N_exp_term = length(η_real) if N_exp_term != length(γ_real) error("The length of \'η_real\' and \'γ_real\' should be the same.") end Id_cache = I(size(_op, 1)) return bosonReal(_spre(_op.data, Id_cache) - _spost(_op.data, Id_cache), _op.dims, η_real, γ_real, N_exp_term) end @doc raw""" struct bosonImag <: AbstractBosonBath A bosonic bath for the imaginary part of bath correlation function ``C^{u=\textrm{I}}`` # Fields - `Comm` : the super-operator (commutator) for the coupling operator. - `anComm` : the super-operator (anti-commutator) for the coupling operator. - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `η` : the coefficients ``\eta_i`` in imaginary part of bath correlation function ``C^{u=\textrm{I}}``. - `γ` : the coefficients ``\gamma_i`` in imaginary part of bath correlation function ``C^{u=\textrm{I}}``. - `Nterm` : the number of exponential-expansion term of correlation function """ struct bosonImag <: AbstractBosonBath Comm::SparseMatrixCSC{ComplexF64,Int64} anComm::SparseMatrixCSC{ComplexF64,Int64} dims::SVector η::AbstractVector γ::AbstractVector Nterm::Int end @doc raw""" bosonImag(op, η_imag, γ_imag) Generate bosonic bath for the imaginary part of correlation function ``C^{u=\textrm{I}}`` # Parameters - `op::QuantumObject` : The system coupling operator, must be Hermitian and, for fermionic systems, even-parity to be compatible with charge conservation. - `η_imag::Vector{Ti<:Number}` : the coefficients ``\eta_i`` in imaginary part of bath correlation functions ``C^{u=\textrm{I}}``. - `γ_imag::Vector{Tj<:Number}` : the coefficients ``\gamma_i`` in imaginary part of bath correlation functions ``C^{u=\textrm{I}}``. """ function bosonImag(op::QuantumObject, η_imag::Vector{Ti}, γ_imag::Vector{Tj}) where {Ti,Tj<:Number} _op = _check_bosonic_coupling_operator(op) # check if the length of coefficients are valid N_exp_term = length(η_imag) if N_exp_term != length(γ_imag) error("The length of \'η_imag\' and \'γ_imag\' should be the same.") end Id_cache = I(size(_op, 1)) spreQ = _spre(_op.data, Id_cache) spostQ = _spost(_op.data, Id_cache) return bosonImag(spreQ - spostQ, spreQ + spostQ, _op.dims, η_imag, γ_imag, N_exp_term) end @doc raw""" sturct bosonRealImag <: AbstractBosonBath A bosonic bath which the real part and imaginary part of the bath correlation function are combined # Fields - `Comm` : the super-operator (commutator) for the coupling operator. - `anComm` : the super-operator (anti-commutator) for the coupling operator. - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `η_real` : the real part of coefficients ``\eta_i`` in bath correlation function ``\sum_i \eta_i \exp(-\gamma_i t)``. - `η_imag` : the imaginary part of coefficients ``\eta_i`` in bath correlation function ``\sum_i \eta_i \exp(-\gamma_i t)``. - `γ` : the coefficients ``\gamma_i`` in bath correlation function ``\sum_i \eta_i \exp(-\gamma_i t)``. - `Nterm` : the number of exponential-expansion term of correlation function """ struct bosonRealImag <: AbstractBosonBath Comm::SparseMatrixCSC{ComplexF64,Int64} anComm::SparseMatrixCSC{ComplexF64,Int64} dims::SVector η_real::AbstractVector η_imag::AbstractVector γ::AbstractVector Nterm::Int end @doc raw""" bosonRealImag(op, η_real, η_imag, γ) Generate bosonic bath which the real part and imaginary part of the bath correlation function are combined # Parameters - `op::QuantumObject` : The system coupling operator, must be Hermitian and, for fermionic systems, even-parity to be compatible with charge conservation. - `η_real::Vector{Ti<:Number}` : the real part of coefficients ``\eta_i`` in bath correlation function ``\sum_i \eta_i \exp(-\gamma_i t)``. - `η_imag::Vector{Tj<:Number}` : the imaginary part of coefficients ``\eta_i`` in bath correlation function ``\sum_i \eta_i \exp(-\gamma_i t)``. - `γ::Vector{Tk<:Number}` : the coefficients ``\gamma_i`` in bath correlation function ``\sum_i \eta_i \exp(-\gamma_i t)``. """ function bosonRealImag( op::QuantumObject, η_real::Vector{Ti}, η_imag::Vector{Tj}, γ::Vector{Tk}, ) where {Ti,Tj,Tk<:Number} _op = _check_bosonic_coupling_operator(op) # check if the length of coefficients are valid N_exp_term = length(η_real) if (N_exp_term != length(η_imag)) || (N_exp_term != length(γ)) error("The length of \'η_real\', \'η_imag\' and \'γ\' should be the same.") end Id_cache = I(size(_op, 1)) spreQ = _spre(_op.data, Id_cache) spostQ = _spost(_op.data, Id_cache) return bosonRealImag(spreQ - spostQ, spreQ + spostQ, _op.dims, η_real, η_imag, γ, N_exp_term) end @doc raw""" BosonBathRWA(op, η_absorb, γ_absorb, η_emit, γ_emit, δ=0.0) A function for generating BosonBath object where the interaction between system and bosonic bath applies the rotating wave approximation (RWA). ```math \begin{aligned} C^{\nu=+}(\tau) &=\frac{1}{2\pi}\int_{0}^{\infty} d\omega J(\omega) n(\omega) e^{i\omega \tau}\\ &=\sum_i \eta_i^{\nu=+} \exp(-\gamma_i^{\nu=+} \tau),\\ C^{\nu=-}(\tau) &=\frac{1}{2\pi}\int_{0}^{\infty} d\omega J(\omega) (1+n(\omega)) e^{-i\omega \tau}\\ &=\sum_i \eta_i^{\nu=-} \exp(-\gamma_i^{\nu=-} \tau), \end{aligned} ``` where ``\nu=+`` (``\nu=-``) represents absorption (emission) process, ``J(\omega)`` is the spectral density of the bath and ``n(\omega)`` is the Bose-Einstein distribution. # Parameters - `op::QuantumObject` : The system annihilation operator according to the system-bosonic-bath interaction. - `η_absorb::Vector{Ti<:Number}` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}(\tau)``. - `γ_absorb::Vector{Tj<:Number}` : the coefficients ``\gamma_i`` of absorption bath correlation function ``C^{\nu=+}(\tau)``. - `η_emit::Vector{Tk<:Number}` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}(\tau)``. - `γ_emit::Vector{Tl<:Number}` : the coefficients ``\gamma_i`` of emission bath correlation function ``C^{\nu=-}(\tau)``. - `δ::Number` : The approximation discrepancy (Defaults to `0.0`) which is used for adding the terminator to HEOMLS matrix (see function: addTerminator) """ function BosonBathRWA( op::QuantumObject, η_absorb::Vector{Ti}, γ_absorb::Vector{Tj}, η_emit::Vector{Tk}, γ_emit::Vector{Tl}, δ::Tm = 0.0, ) where {Ti,Tj,Tk,Tl,Tm<:Number} _check_gamma_absorb_and_emit(γ_absorb, γ_emit) _op = HandleMatrixType(op, "op (coupling operator)") bA = bosonAbsorb(adjoint(_op), η_absorb, γ_absorb, η_emit) bE = bosonEmit(_op, η_emit, γ_emit, η_absorb) return BosonBath(AbstractBosonBath[bA, bE], _op, bA.Nterm + bE.Nterm, δ) end @doc raw""" struct bosonAbsorb <: AbstractBosonBath An bath object which describes the absorption process of the bosonic system by a correlation function ``C^{\nu=+}`` # Fields - `spre` : the super-operator (left side operator multiplication) for the coupling operator. - `spost` : the super-operator (right side operator multiplication) for the coupling operator. - `CommD` : the super-operator (commutator) for the adjoint of the coupling operator. - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `η` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}``. - `γ` : the coefficients ``\gamma_i`` of absorption bath correlation function ``C^{\nu=+}``. - `η_emit` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}``. - `Nterm` : the number of exponential-expansion term of correlation function """ struct bosonAbsorb <: AbstractBosonBath spre::SparseMatrixCSC{ComplexF64,Int64} spost::SparseMatrixCSC{ComplexF64,Int64} CommD::SparseMatrixCSC{ComplexF64,Int64} dims::SVector η::AbstractVector γ::AbstractVector η_emit::AbstractVector Nterm::Int end @doc raw""" bosonAbsorb(op, η_absorb, γ_absorb, η_emit) Generate bosonic bath which describes the absorption process of the bosonic system by a correlation function ``C^{\nu=+}`` # Parameters - `op::QuantumObject` : The system creation operator according to the system-fermionic-bath interaction. - `η_absorb::Vector{Ti<:Number}` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}``. - `γ_absorb::Vector{Tj<:Number}` : the coefficients ``\gamma_i`` of absorption bath correlation function ``C^{\nu=+}``. - `η_emit::Vector{Tk<:Number}` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}``. """ function bosonAbsorb( op::QuantumObject, η_absorb::Vector{Ti}, γ_absorb::Vector{Tj}, η_emit::Vector{Tk}, ) where {Ti,Tj,Tk<:Number} _op = _check_bosonic_RWA_coupling_operator(op) # check if the length of coefficients are valid N_exp_term = length(η_absorb) if (N_exp_term != length(γ_absorb)) || (N_exp_term != length(η_emit)) error("The length of \'η_absorb\', \'γ_absorb\' and \'η_emit\' should all be the same.") end Id_cache = I(size(_op, 1)) return bosonAbsorb( _spre(_op.data, Id_cache), _spost(_op.data, Id_cache), _spre(adjoint(_op).data, Id_cache) - _spost(adjoint(_op).data, Id_cache), _op.dims, η_absorb, γ_absorb, η_emit, N_exp_term, ) end @doc raw""" struct bosonEmit <: AbstractBosonBath An bath object which describes the emission process of the bosonic system by a correlation function ``C^{\nu=-}`` # Fields - `spre` : the super-operator (left side operator multiplication) for the coupling operator. - `spost` : the super-operator (right side operator multiplication) for the coupling operator. - `CommD` : the super-operator (commutator) for the adjoint of the coupling operator. - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `η` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}``. - `γ` : the coefficients ``\gamma_i`` of emission bath correlation function ``C^{\nu=-}``. - `η_absorb` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}``. - `Nterm` : the number of exponential-expansion term of correlation function """ struct bosonEmit <: AbstractBosonBath spre::SparseMatrixCSC{ComplexF64,Int64} spost::SparseMatrixCSC{ComplexF64,Int64} CommD::SparseMatrixCSC{ComplexF64,Int64} dims::SVector η::AbstractVector γ::AbstractVector η_absorb::AbstractVector Nterm::Int end @doc raw""" bosonEmit(op, η_emit, γ_emit, η_absorb) Generate bosonic bath which describes the emission process of the bosonic system by a correlation function ``C^{\nu=-}`` # Parameters - `op::QuantumObject` : The system annihilation operator according to the system-bosonic-bath interaction. - `η_emit::Vector{Ti<:Number}` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}``. - `γ_emit::Vector{Ti<:Number}` : the coefficients ``\gamma_i`` of emission bath correlation function ``C^{\nu=-}``. - `η_absorb::Vector{Ti<:Number}` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}``. """ function bosonEmit( op::QuantumObject, η_emit::Vector{Ti}, γ_emit::Vector{Tj}, η_absorb::Vector{Tk}, ) where {Ti,Tj,Tk<:Number} _op = _check_bosonic_RWA_coupling_operator(op) # check if the length of coefficients are valid N_exp_term = length(η_emit) if (N_exp_term != length(γ_emit)) || (N_exp_term != length(η_absorb)) error("The length of \'η_emit\', \'γ_emit\' and \'η_absorb\' should all be the same.") end Id_cache = I(size(_op, 1)) return bosonEmit( _spre(_op.data, Id_cache), _spost(_op.data, Id_cache), _spre(adjoint(_op).data, Id_cache) - _spost(adjoint(_op).data, Id_cache), _op.dims, η_emit, γ_emit, η_absorb, N_exp_term, ) end @doc raw""" struct FermionBath <: AbstractBath An object which describes the interaction between system and fermionic bath # Fields - `bath` : the different fermion-bath-type objects which describes the interaction - `op` : The system \"emission\" operator according to the system-fermionic-bath interaction. - `Nterm` : the number of exponential-expansion term of correlation functions - `δ` : The approximation discrepancy which is used for adding the terminator to HEOM matrix (see function: addTerminator) # Methods One can obtain the ``k``-th exponent (exponential-expansion term) from `bath::FermionBath` by calling : `bath[k]`. `HierarchicalEOM.jl` also supports the following calls (methods) : ```julia bath[1:k]; # returns a vector which contains the exponents from the `1`-st to the `k`-th term. bath[1:end]; # returns a vector which contains all the exponential-expansion terms bath[:]; # returns a vector which contains all the exponential-expansion terms from b in bath # do something end ``` """ struct FermionBath <: AbstractBath bath::Vector{AbstractFermionBath} op::QuantumObject Nterm::Int δ::Number end @doc raw""" FermionBath(op, η_absorb, γ_absorb, η_emit, γ_emit, δ=0.0) Generate FermionBath object ```math \begin{aligned} C^{\nu=+}(\tau) &=\frac{1}{2\pi}\int_{-\infty}^{\infty} d\omega J(\omega) n(\omega) e^{i\omega \tau}\\ &=\sum_i \eta_i^{\nu=+} \exp(-\gamma_i^{\nu=+} \tau),\\ C^{\nu=-}(\tau) &=\frac{1}{2\pi}\int_{-\infty}^{\infty} d\omega J(\omega) (1-n(\omega)) e^{-i\omega \tau}\\ &=\sum_i \eta_i^{\nu=-} \exp(-\gamma_i^{\nu=-} \tau), \end{aligned} ``` where ``\nu=+`` (``\nu=-``) represents absorption (emission) process, ``J(\omega)`` is the spectral density of the bath and ``n(\omega)`` is the Fermi-Dirac distribution. # Parameters - `op::QuantumObject` : The system annihilation operator according to the system-fermionic-bath interaction. - `η_absorb::Vector{Ti<:Number}` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}(\tau)``. - `γ_absorb::Vector{Tj<:Number}` : the coefficients ``\gamma_i`` of absorption bath correlation function ``C^{\nu=+}(\tau)``. - `η_emit::Vector{Tk<:Number}` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}(\tau)``. - `γ_emit::Vector{Tl<:Number}` : the coefficients ``\gamma_i`` of emission bath correlation function ``C^{\nu=-}(\tau)``. - `δ::Number` : The approximation discrepancy (Defaults to `0.0`) which is used for adding the terminator to HEOMLS matrix (see function: addTerminator) """ function FermionBath( op::QuantumObject, η_absorb::Vector{Ti}, γ_absorb::Vector{Tj}, η_emit::Vector{Tk}, γ_emit::Vector{Tl}, δ::Tm = 0.0, ) where {Ti,Tj,Tk,Tl,Tm<:Number} _check_gamma_absorb_and_emit(γ_absorb, γ_emit) _op = HandleMatrixType(op, "op (coupling operator)") fA = fermionAbsorb(adjoint(_op), η_absorb, γ_absorb, η_emit) fE = fermionEmit(_op, η_emit, γ_emit, η_absorb) return FermionBath(AbstractFermionBath[fA, fE], _op, fA.Nterm + fE.Nterm, δ) end @doc raw""" struct fermionAbsorb <: AbstractFermionBath An bath object which describes the absorption process of the fermionic system by a correlation function ``C^{\nu=+}`` # Fields - `spre` : the super-operator (left side operator multiplication) for the coupling operator. - `spost` : the super-operator (right side operator multiplication) for the coupling operator. - `spreD` : the super-operator (left side operator multiplication) for the adjoint of the coupling operator. - `spostD` : the super-operator (right side operator multiplication) for the adjoint of the coupling operator. - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `η` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}``. - `γ` : the coefficients ``\gamma_i`` of absorption bath correlation function ``C^{\nu=+}``. - `η_emit` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}``. - `Nterm` : the number of exponential-expansion term of correlation function """ struct fermionAbsorb <: AbstractFermionBath spre::SparseMatrixCSC{ComplexF64,Int64} spost::SparseMatrixCSC{ComplexF64,Int64} spreD::SparseMatrixCSC{ComplexF64,Int64} spostD::SparseMatrixCSC{ComplexF64,Int64} dims::SVector η::AbstractVector γ::AbstractVector η_emit::AbstractVector Nterm::Int end @doc raw""" fermionAbsorb(op, η_absorb, γ_absorb, η_emit) Generate fermionic bath which describes the absorption process of the fermionic system by a correlation function ``C^{\nu=+}`` # Parameters - `op::QuantumObject` : The system creation operator according to the system-fermionic-bath interaction. - `η_absorb::Vector{Ti<:Number}` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}``. - `γ_absorb::Vector{Tj<:Number}` : the coefficients ``\gamma_i`` of absorption bath correlation function ``C^{\nu=+}``. - `η_emit::Vector{Tk<:Number}` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}``. """ function fermionAbsorb( op::QuantumObject, η_absorb::Vector{Ti}, γ_absorb::Vector{Tj}, η_emit::Vector{Tk}, ) where {Ti,Tj,Tk<:Number} _op = _check_fermionic_coupling_operator(op) # check if the length of coefficients are valid N_exp_term = length(η_absorb) if (N_exp_term != length(γ_absorb)) || (N_exp_term != length(η_emit)) error("The length of \'η_absorb\', \'γ_absorb\' and \'η_emit\' should all be the same.") end Id_cache = I(size(_op, 1)) return fermionAbsorb( _spre(_op.data, Id_cache), _spost(_op.data, Id_cache), _spre(adjoint(_op).data, Id_cache), _spost(adjoint(_op).data, Id_cache), _op.dims, η_absorb, γ_absorb, η_emit, N_exp_term, ) end @doc raw""" struct fermionEmit <: AbstractFermionBath An bath object which describes the emission process of the fermionic system by a correlation function ``C^{\nu=-}`` # Fields - `spre` : the super-operator (left side operator multiplication) for the coupling operator. - `spost` : the super-operator (right side operator multiplication) for the coupling operator. - `spreD` : the super-operator (left side operator multiplication) for the adjoint of the coupling operator. - `spostD` : the super-operator (right side operator multiplication) for the adjoint of the coupling operator. - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `η` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}``. - `γ` : the coefficients ``\gamma_i`` of emission bath correlation function ``C^{\nu=-}``. - `η_absorb` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}``. - `Nterm` : the number of exponential-expansion term of correlation function """ struct fermionEmit <: AbstractFermionBath spre::SparseMatrixCSC{ComplexF64,Int64} spost::SparseMatrixCSC{ComplexF64,Int64} spreD::SparseMatrixCSC{ComplexF64,Int64} spostD::SparseMatrixCSC{ComplexF64,Int64} dims::SVector η::AbstractVector γ::AbstractVector η_absorb::AbstractVector Nterm::Int end @doc raw""" fermionEmit(op, η_emit, γ_emit, η_absorb) Generate fermionic bath which describes the emission process of the fermionic system by a correlation function ``C^{\nu=-}`` # Parameters - `op::QuantumObject` : The system annihilation operator according to the system-fermionic-bath interaction. - `η_emit::Vector{Ti<:Number}` : the coefficients ``\eta_i`` of emission bath correlation function ``C^{\nu=-}``. - `γ_emit::Vector{Ti<:Number}` : the coefficients ``\gamma_i`` of emission bath correlation function ``C^{\nu=-}``. - `η_absorb::Vector{Ti<:Number}` : the coefficients ``\eta_i`` of absorption bath correlation function ``C^{\nu=+}``. """ function fermionEmit( op::QuantumObject, η_emit::Vector{Ti}, γ_emit::Vector{Tj}, η_absorb::Vector{Tk}, ) where {Ti,Tj,Tk<:Number} _op = _check_fermionic_coupling_operator(op) # check if the length of coefficients are valid N_exp_term = length(η_emit) if (N_exp_term != length(γ_emit)) || (N_exp_term != length(η_absorb)) error("The length of \'η_emit\', \'γ_emit\' and \'η_absorb\' should all be the same.") end Id_cache = I(size(_op, 1)) return fermionEmit( _spre(_op.data, Id_cache), _spost(_op.data, Id_cache), _spre(adjoint(_op).data, Id_cache), _spost(adjoint(_op).data, Id_cache), _op.dims, η_emit, γ_emit, η_absorb, N_exp_term, ) end @doc raw""" C(bath, tlist) Calculate the correlation function ``C(t)`` for a given bosonic bath and time list. ## if the input bosonic bath did not apply rotating wave approximation (RWA) ```math C(t)=\sum_{u=\textrm{R},\textrm{I}}(\delta_{u, \textrm{R}} + i\delta_{u, \textrm{I}})C^{u}(t) ``` where ```math C^{u}(t)=\sum_i \eta_i^u e^{-\gamma_i^u t} ``` ## if the input bosonic bath applies rotating wave approximation (RWA) ```math C^{\nu=\pm}(t)=\sum_i \eta_i^\nu e^{-\gamma_i^\nu t} ``` # Parameters - `bath::BosonBath` : The bath object which describes a certain bosonic bath. - `tlist::AbstractVector`: The specific time. # Returns (without RWA) - `clist::Vector{ComplexF64}` : a list of the value of correlation function according to the given time list. # Returns (with RWA) - `cplist::Vector{ComplexF64}` : a list of the value of the absorption (``\nu=+``) correlation function according to the given time list. - `cmlist::Vector{ComplexF64}` : a list of the value of the emission (``\nu=-``) correlation function according to the given time list. """ function C(bath::BosonBath, tlist::AbstractVector) T = (bath[1]).types # without RWA if (T == "bR") || (T == "bI") || (T == "bRI") clist = zeros(ComplexF64, length(tlist)) for (i, t) in enumerate(tlist) for e in bath if (e.types == "bR") || (e.types == "bRI") clist[i] += e.η * exp(-e.γ * t) elseif e.types == "bI" clist[i] += 1.0im * e.η * exp(-e.γ * t) else error("Invalid bath") end end end return clist # with RWA else cplist = zeros(ComplexF64, length(tlist)) cmlist = zeros(ComplexF64, length(tlist)) for (i, t) in enumerate(tlist) for e in bath if e.types == "bA" cplist[i] += e.η * exp(-e.γ * t) elseif e.types == "bE" cmlist[i] += e.η * exp(-e.γ * t) else error("Invalid bath") end end end return cplist, cmlist end end @doc raw""" C(bath, tlist) Calculate the correlation function ``C^{\nu=+}(t)`` and ``C^{\nu=-}(t)`` for a given fermionic bath and time list. Here, ``\nu=+`` represents the absorption process and ``\nu=-`` represents the emmision process. ```math C^{\nu=\pm}(t)=\sum_i \eta_i^\nu e^{-\gamma_i^\nu t} ``` # Parameters - `bath::FermionBath` : The bath object which describes a certain fermionic bath. - `tlist::AbstractVector`: The specific time. # Returns - `cplist::Vector{ComplexF64}` : a list of the value of the absorption (``\nu=+``) correlation function according to the given time list. - `cmlist::Vector{ComplexF64}` : a list of the value of the emission (``\nu=-``) correlation function according to the given time list. """ function C(bath::FermionBath, tlist::AbstractVector) cplist = zeros(ComplexF64, length(tlist)) cmlist = zeros(ComplexF64, length(tlist)) for (i, t) in enumerate(tlist) for e in bath if e.types == "fA" cplist[i] += e.η * exp(-e.γ * t) else cmlist[i] += e.η * exp(-e.γ * t) end end end return cplist, cmlist end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
7396
abstract type AbstractHEOMLSMatrix{T} end # equal to : sparse(vec(system_identity_matrix)) function _Tr(dims::SVector, N::Int) D = prod(dims) return SparseVector(N * D^2, [1 + n * (D + 1) for n in 0:(D-1)], ones(ComplexF64, D)) end function _Tr(M::AbstractHEOMLSMatrix{T}) where {T<:SparseMatrixCSC} D = prod(M.dims) return SparseVector(M.N * D^2, [1 + n * (D + 1) for n in 0:(D-1)], ones(eltype(M), D)) end function HandleMatrixType(M::QuantumObject, MatrixName::String = ""; type::QuantumObjectType = Operator) if M.type == type return M else error("The matrix $(MatrixName) should be an $(type).") end end function HandleMatrixType(M::QuantumObject, dims::SVector, MatrixName::String = ""; type::QuantumObjectType = Operator) if M.dims == dims return HandleMatrixType(M, MatrixName; type = type) else error("The dims of $(MatrixName) should be: $(dims)") end end HandleMatrixType(M, dims::SVector, MatrixName::String = ""; type::QuantumObjectType = Operator) = HandleMatrixType(M, MatrixName; type = type) HandleMatrixType(M, MatrixName::String = ""; type::QuantumObjectType = Operator) = error("HierarchicalEOM doesn't support matrix $(MatrixName) with type : $(typeof(M))") function _HandleFloatType(ElType::Type{T}, V::StepRangeLen) where {T<:Number} if real(ElType) == Float32 return StepRangeLen(Float32(V.ref), Float32(V.step), Int32(V.len), Int64(V.offset)) else return StepRangeLen(Float64(V.ref), Float64(V.step), Int64(V.len), Int64(V.offset)) end end function _HandleFloatType(ElType::Type{T}, V::Any) where {T<:Number} FType = real(ElType) if eltype(V) == FType return V else convert.(FType, V) end end # for changing a `Vector` back to `ADOs` _HandleVectorType(V::T, cp::Bool = true) where {T<:Vector} = cp ? Vector{ComplexF64}(V) : V # for changing the type of `ADOs` to match the type of HEOMLS matrix function _HandleVectorType(MatrixType::Type{TM}, V::SparseVector) where {TM<:AbstractMatrix} TE = eltype(MatrixType) return Vector{TE}(V) end function _HandleSteadyStateMatrix(M::AbstractHEOMLSMatrix, S::Int) ElType = eltype(M) D = prod(M.dims) A = copy(M.data) A[1, 1:S] .= 0 # sparse(row_idx, col_idx, values, row_dims, col_dims) A += sparse(ones(ElType, D), [(n - 1) * (D + 1) + 1 for n in 1:D], ones(ElType, D), S, S) return A end function _HandleIdentityType(MatrixType::Type{TM}, S::Int) where {TM<:AbstractMatrix} ElType = eltype(MatrixType) return sparse(one(ElType) * I, S, S) end function _check_sys_dim_and_ADOs_num(A, B) if (A.dims != B.dims) error("Inconsistent system dimension (\"dims\").") end if (A.N != B.N) error("Inconsistent number of ADOs (\"N\").") end end _check_parity(A, B) = (typeof(A.parity) != typeof(B.parity)) ? error("Inconsistent parity.") : nothing function _get_pkg_version(pkg_name::String) D = Pkg.dependencies() for uuid in keys(D) if D[uuid].name == pkg_name return D[uuid].version end end end """ HierarchicalEOM.print_logo(io::IO=stdout) Print the Logo of HierarchicalEOM package """ function print_logo(io::IO = stdout) default = :default green = 28 blue = 63 purple = 133 red = 124 printstyled(io, " __", color = green, bold = true) printstyled(io, "\n") printstyled(io, " / \\", color = green, bold = true) printstyled(io, "\n") printstyled(io, " __ __ ", color = default) printstyled(io, "__", color = red, bold = true) printstyled(io, " \\__/ ", color = green, bold = true) printstyled(io, "__", color = purple, bold = true) printstyled(io, "\n") printstyled(io, "| | | | ", color = default) printstyled(io, "/ \\", color = red, bold = true) printstyled(io, " ", color = default) printstyled(io, "/ \\", color = purple, bold = true) printstyled(io, "\n") printstyled(io, "| | | | ______ ______ ", color = default) printstyled(io, "\\__/", color = red, bold = true) printstyled(io, "_ _", color = default) printstyled(io, "\\__/", color = purple, bold = true) printstyled(io, "\n") printstyled(io, "| |___| |/ __ \\ / ", color = default) printstyled(io, "__", color = blue, bold = true) printstyled(io, " \\ / ' \\/ \\", color = default) printstyled(io, "\n") printstyled(io, "| ___ | |__) | ", color = default) printstyled(io, "/ \\", color = blue, bold = true) printstyled(io, " | _ _ |", color = default) printstyled(io, "\n") printstyled(io, "| | | | ____/| ", color = default) printstyled(io, "( )", color = blue, bold = true) printstyled(io, " | / \\ / \\ |", color = default) printstyled(io, "\n") printstyled(io, "| | | | |____ | ", color = default) printstyled(io, "\\__/", color = blue, bold = true) printstyled(io, " | | | | | |", color = default) printstyled(io, "\n") printstyled(io, "|__| |__|\\______) \\______/|__| |_| |_|", color = default) return printstyled(io, "\n") end """ HierarchicalEOM.versioninfo(io::IO=stdout) Command line output of information on HierarchicalEOM, dependencies, and system informations. """ function versioninfo(io::IO = stdout) cpu = Sys.cpu_info() BLAS_info = BLAS.get_config().loaded_libs[1] Sys.iswindows() ? OS_name = "Windows" : Sys.isapple() ? OS_name = "macOS" : OS_name = Sys.KERNEL # print the logo of HEOM package print("\n") print_logo(io) # print introduction println( io, "\n", "Julia framework for Hierarchical Equations of Motion\n", "≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡\n", "Copyright © QuTiP team 2023 and later.\n", "Lead developer : Yi-Te Huang\n", "Other developers:\n", " Simon Cross, Neill Lambert, Po-Chen Kuo and Shen-Liang Yang\n", ) # print package information println( io, "Package information:\n", "====================================\n", "Julia Ver. $(VERSION)\n", "HierarchicalEOM Ver. $(_get_pkg_version("HierarchicalEOM"))\n", "QuantumToolbox Ver. $(_get_pkg_version("QuantumToolbox"))\n", "LinearSolve Ver. $(_get_pkg_version("LinearSolve"))\n", "OrdinaryDiffEqCore Ver. $(_get_pkg_version("OrdinaryDiffEqCore"))\n", ) # print System information println(io, "System information:") println(io, "====================================") println(io, """OS : $(OS_name) ($(Sys.MACHINE))""") println(io, """CPU : $(length(cpu)) × $(cpu[1].model)""") println(io, """Memory : $(round(Sys.total_memory() / 2 ^ 30, digits=3)) GB""") println(io, """WORD_SIZE: $(Sys.WORD_SIZE)""") println(io, """LIBM : $(Base.libm_name)""") println(io, """LLVM : libLLVM-$(Base.libllvm_version) ($(Sys.JIT), $(Sys.CPU_NAME))""") println(io, """BLAS : $(basename(BLAS_info.libname)) ($(BLAS_info.interface))""") println(io, """Threads : $(Threads.nthreads()) (on $(Sys.CPU_THREADS) virtual cores)""") return print(io, "\n") end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
4352
module HierarchicalEOM import Reexport: @reexport @reexport using QuantumToolbox # sub-module HeomBase for HierarchicalEOM module HeomBase import Pkg import LinearAlgebra: BLAS, kron, I import SparseArrays: sparse, SparseVector, SparseMatrixCSC import StaticArraysCore: SVector import QuantumToolbox: QuantumObject, QuantumObjectType, Operator, SuperOperator export _Tr, AbstractHEOMLSMatrix, _check_sys_dim_and_ADOs_num, _check_parity, HandleMatrixType, _HandleFloatType, _HandleVectorType, _HandleSteadyStateMatrix, _HandleIdentityType include("HeomBase.jl") end import .HeomBase.versioninfo as versioninfo import .HeomBase.print_logo as print_logo @reexport import .HeomBase: AbstractHEOMLSMatrix # sub-module Bath for HierarchicalEOM module Bath using ..HeomBase import Base: show, length, getindex, lastindex, iterate, checkbounds import LinearAlgebra: ishermitian, eigvals, I import SparseArrays: SparseMatrixCSC import StaticArraysCore: SVector import QuantumToolbox: QuantumObject, _spre, _spost export AbstractBath, BosonBath, BosonBathRWA, FermionBath, Exponent, C, AbstractBosonBath, bosonReal, bosonImag, bosonRealImag, bosonAbsorb, bosonEmit, AbstractFermionBath, fermionAbsorb, fermionEmit, Boson_DrudeLorentz_Matsubara, Boson_DrudeLorentz_Pade, Fermion_Lorentz_Matsubara, Fermion_Lorentz_Pade include("Bath.jl") include("bath_correlation_functions/bath_correlation_func.jl") end @reexport using .Bath # sub-module HeomAPI for HierarchicalEOM module HeomAPI import Reexport: @reexport using ..HeomBase using ..Bath import Base: ==, !, +, -, *, show, length, size, getindex, keys, setindex!, lastindex, iterate, checkbounds, hash, copy, eltype import Base.Threads: @threads, threadid, nthreads, lock, unlock, SpinLock import LinearAlgebra: I, kron, tr, norm, dot, mul! import SparseArrays: sparse, sparsevec, spzeros, SparseVector, SparseMatrixCSC, AbstractSparseMatrix import StaticArraysCore: SVector import QuantumToolbox: QuantumObject, Operator, SuperOperator, TimeDependentOperatorSum, _spre, _spost, spre, spost, sprepost, expect, ket2dm, liouvillian, lindblad_dissipator, steadystate, ProgressBar, next! import FastExpm: fastExpm import SciMLBase: init, solve, solve!, u_modified!, ODEProblem, FullSpecialize, CallbackSet import SciMLOperators: MatrixOperator import OrdinaryDiffEqCore: OrdinaryDiffEqAlgorithm import OrdinaryDiffEqLowOrderRK: DP5 import DiffEqCallbacks: PresetTimeCallback, TerminateSteadyState import LinearSolve: LinearProblem, SciMLLinearSolveAlgorithm, UMFPACKFactorization import JLD2: jldopen export AbstractParity, OddParity, EvenParity, value, ODD, EVEN, ADOs, getRho, getADO, Nvec, AbstractHierarchyDict, HierarchyDict, MixHierarchyDict, getIndexEnsemble, HEOMSuperOp, M_S, M_Boson, M_Fermion, M_Boson_Fermion, Propagator, addBosonDissipator, addFermionDissipator, addTerminator, TimeEvolutionHEOMSol, HEOMsolve, evolution, # has been deprecated, throws error only SteadyState, # has been deprecated, throws error only PowerSpectrum, DensityOfStates include("Parity.jl") include("ADOs.jl") include("heom_matrices/heom_matrix_base.jl") include("heom_matrices/Nvec.jl") include("heom_matrices/HierarchyDict.jl") include("heom_matrices/M_S.jl") include("heom_matrices/M_Boson.jl") include("heom_matrices/M_Fermion.jl") include("heom_matrices/M_Boson_Fermion.jl") include("evolution.jl") include("steadystate.jl") include("power_spectrum.jl") include("density_of_states.jl") end @reexport using .HeomAPI end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
709
abstract type AbstractParity end @doc raw""" struct OddParity <: AbstractParity """ struct OddParity <: AbstractParity end @doc raw""" struct EvenParity <: AbstractParity """ struct EvenParity <: AbstractParity end value(p::OddParity) = 1 value(p::EvenParity) = 0 !(p::OddParity) = EVEN !(p::EvenParity) = ODD *(p1::TP1, p2::TP2) where {TP1,TP2<:AbstractParity} = TP1 == TP2 ? EVEN : ODD show(io::IO, p::OddParity) = print(io, "odd-parity") show(io::IO, p::EvenParity) = print(io, "even-parity") # Parity label @doc raw""" const ODD = OddParity() Label of odd-parity """ const ODD = OddParity() @doc raw""" const EVEN = EvenParity() Label of even-parity """ const EVEN = EvenParity()
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
4049
@doc raw""" DensityOfStates(M, ρ, d_op, ωlist; solver, verbose, filename, SOLVEROptions...) Calculate density of states for the fermionic system in frequency domain. ```math \pi A(\omega)=\textrm{Re}\left\{\int_0^\infty dt \left[\langle d(t) d^\dagger(0)\rangle^* + \langle d^\dagger(t) d(0)\rangle \right] e^{-i\omega t}\right\}, ``` # Parameters - `M::AbstractHEOMLSMatrix` : the HEOMLS matrix which acts on `ODD`-parity operators. - `ρ::Union{QuantumObject,ADOs}` : the system density matrix or the auxiliary density operators. - `d_op::QuantumObject` : The annihilation operator (``d`` as shown above) acting on the fermionic system. - `ωlist::AbstractVector` : the specific frequency points to solve. - `solver::SciMLLinearSolveAlgorithm` : solver in package `LinearSolve.jl`. Default to `UMFPACKFactorization()`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. - `filename::String` : If filename was specified, the value of spectrum for each ω will be saved into the file "filename.txt" during the solving process. - `SOLVEROptions` : extra options for solver # Notes - For more details about `solver` and `SOLVEROptions`, please refer to [`LinearSolve.jl`](http://linearsolve.sciml.ai/stable/) # Returns - `dos::AbstractVector` : the list of density of states corresponds to the specified `ωlist` """ @noinline function DensityOfStates( M::AbstractHEOMLSMatrix, ρ::Union{QuantumObject,ADOs}, d_op::QuantumObject, ωlist::AbstractVector; solver::SciMLLinearSolveAlgorithm = UMFPACKFactorization(), verbose::Bool = true, filename::String = "", SOLVEROptions..., ) Size = size(M, 1) # check M if M.parity == EVEN error("The HEOMLS matrix M must be acting on `ODD`-parity operators.") end # Handle ρ if typeof(ρ) == ADOs # ρ::ADOs ados = ρ if ados.parity != EVEN error("The parity of ρ must be `EVEN`.") end else ados = ADOs(ρ, M.N) end _check_sys_dim_and_ADOs_num(M, ados) # Handle d_op MType = Base.typename(typeof(M.data)).wrapper{eltype(M)} _tr = transpose(_Tr(M)) Id_cache = I(M.N) d_normal = HEOMSuperOp(d_op, ODD, M; Id_cache = Id_cache) d_dagger = HEOMSuperOp(d_op', ODD, M; Id_cache = Id_cache) b_m = _HandleVectorType(typeof(M.data), (d_normal * ados).data) b_p = _HandleVectorType(typeof(M.data), (d_dagger * ados).data) _tr_d_normal = _tr * MType(d_normal).data _tr_d_dagger = _tr * MType(d_dagger).data SAVE::Bool = (filename != "") if SAVE FILENAME = filename * ".txt" isfile(FILENAME) && error("FILE: $(FILENAME) already exist.") end ElType = eltype(M) ωList = _HandleFloatType(ElType, ωlist) Length = length(ωList) Aω = Vector{Float64}(undef, Length) if verbose print("Calculating density of states in frequency domain...\n") flush(stdout) end prog = ProgressBar(Length; enable = verbose) i = convert(ElType, 1im) I_total = _HandleIdentityType(typeof(M.data), Size) cache_m = cache_p = nothing for ω in ωList Iω = i * ω * I_total if prog.counter[] == 0 cache_m = init(LinearProblem(M.data - Iω, b_m), solver, SOLVEROptions...) sol_m = solve!(cache_m) cache_p = init(LinearProblem(M.data + Iω, b_p), solver, SOLVEROptions...) sol_p = solve!(cache_p) else cache_m.A = M.data - Iω sol_m = solve!(cache_m) cache_p.A = M.data + Iω sol_p = solve!(cache_p) end # trace over the Hilbert space of system (expectation value) val = -1 * real(dot(_tr_d_normal, sol_p.u) + dot(_tr_d_dagger, sol_m.u)) Aω[prog.counter[]+1] = val if SAVE open(FILENAME, "a") do file return write(file, "$(val),\n") end end next!(prog) end if verbose println("[DONE]") end return Aω end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
12219
evolution(M::AbstractHEOMLSMatrix, args...; kwargs...) = error("`evolution` has been deprecated, please use `HEOMsolve` instead.") const DEFAULT_ODE_SOLVER_OPTIONS = (abstol = 1e-8, reltol = 1e-6, save_everystep = false, save_end = true) @doc raw""" struct TimeEvolutionHEOMSol A structure storing the results and some information from solving time evolution of hierarchical equations of motion (HEOM). # Fields (Attributes) - `Btier` : The tier (cutoff level) for bosonic hierarchy - `Ftier` : The tier (cutoff level) for fermionic hierarchy - `times::AbstractVector`: The time list of the evolution. - `ados::Vector{ADOs}`: The list of result ADOs at each time point. - `expect::Matrix`: The expectation values corresponding to each time point in `times`. - `retcode`: The return code from the solver. - `alg`: The algorithm which is used during the solving process. - `abstol::Real`: The absolute tolerance which is used during the solving process. - `reltol::Real`: The relative tolerance which is used during the solving process. """ struct TimeEvolutionHEOMSol{TT<:Vector{<:Real},TS<:Vector{ADOs},TE<:Matrix{ComplexF64}} Btier::Int Ftier::Int times::TT ados::TS expect::TE retcode::Union{Nothing,Enum} alg::Union{Nothing,OrdinaryDiffEqAlgorithm} abstol::Union{Nothing,Real} reltol::Union{Nothing,Real} end function Base.show(io::IO, sol::TimeEvolutionHEOMSol) print(io, "Solution of hierarchical EOM\n") print(io, "(return code: $(sol.retcode))\n") print(io, "----------------------------\n") print(io, "Btier = $(sol.Btier)\n") print(io, "Ftier = $(sol.Ftier)\n") print(io, "num_states = $(length(sol.ados))\n") print(io, "num_expect = $(size(sol.expect, 1))\n") print(io, "ODE alg.: $(sol.alg)\n") print(io, "abstol = $(sol.abstol)\n") print(io, "reltol = $(sol.reltol)\n") return nothing end @doc raw""" HEOMsolve(M, ρ0, Δt, steps; e_ops, threshold, nonzero_tol, verbose, filename) Solve the time evolution for auxiliary density operators based on propagator (generated by `FastExpm.jl`). # Parameters - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model - `ρ0::Union{QuantumObject,ADOs}` : system initial state (density matrix) or initial auxiliary density operators (`ADOs`) - `Δt::Real` : A specific time step (time interval). - `steps::Int` : The number of time steps - `e_ops::Union{Nothing,AbstractVector}`: List of operators for which to calculate expectation values. - `threshold::Real` : Determines the threshold for the Taylor series. Defaults to `1.0e-6`. - `nonzero_tol::Real` : Strips elements smaller than `nonzero_tol` at each computation step to preserve sparsity. Defaults to `1.0e-14`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. - `filename::String` : If filename was specified, the ADOs at each time point will be saved into the JLD2 file "filename.jld2" after the solving process. # Notes - The [`ADOs`](@ref) will be saved depend on the keyword argument `e_ops`. - If `e_ops` is specified, the solution will only save the final `ADOs`, otherwise, it will save all the `ADOs` corresponding to `tlist = 0:Δt:(Δt * steps)`. - For more details of the propagator, please refer to [`FastExpm.jl`](https://github.com/fmentink/FastExpm.jl) # Returns - `sol::TimeEvolutionHEOMSol` : The solution of the hierarchical EOM. See also [`TimeEvolutionHEOMSol`](@ref) """ function HEOMsolve( M::AbstractHEOMLSMatrix, ρ0::T_state, Δt::Real, steps::Int; e_ops::Union{Nothing,AbstractVector} = nothing, threshold = 1.0e-6, nonzero_tol = 1.0e-14, verbose::Bool = true, filename::String = "", ) where {T_state<:Union{QuantumObject,ADOs}} # check filename if filename != "" FILENAME = filename * ".jld2" isfile(FILENAME) && error("FILE: $(FILENAME) already exist.") end # handle initial state ados = (T_state <: QuantumObject) ? ADOs(ρ0, M.N, M.parity) : ρ0 _check_sys_dim_and_ADOs_num(M, ados) _check_parity(M, ados) ρvec = _HandleVectorType(typeof(M.data), ados.data) if e_ops isa Nothing expvals = Array{ComplexF64}(undef, 0, steps + 1) is_empty_e_ops = true else expvals = Array{ComplexF64}(undef, length(e_ops), steps + 1) tr_op = [transpose(_Tr(M)) * HEOMSuperOp(op, EVEN, M.dims, M.N, "L").data for op in e_ops] is_empty_e_ops = isempty(e_ops) end if is_empty_e_ops ADOs_list = Vector{ADOs}(undef, steps + 1) else ADOs_list = Vector{ADOs}(undef, 1) end # Generate propagator verbose && print("Generating propagator...") exp_Mt = Propagator(M, Δt; threshold = threshold, nonzero_tol = nonzero_tol) verbose && println("[DONE]") # start solving if verbose print("Solving time evolution for ADOs by propagator method...\n") flush(stdout) end prog = ProgressBar(steps + 1, enable = verbose) for n in 0:steps # calculate expectation values if !is_empty_e_ops _expect = op -> dot(op, ρvec) @. expvals[:, prog.counter[]+1] = _expect(tr_op) n == steps ? ADOs_list[1] = ADOs(ρvec, M.dims, M.N, M.parity) : nothing else ADOs_list[n+1] = ADOs(ρvec, M.dims, M.N, M.parity) end ρvec = exp_Mt * ρvec next!(prog) end # save ADOs to file if filename != "" verbose && print("Saving ADOs to $(FILENAME) ... ") jldopen(FILENAME, "w") do file return file["ados"] = ADOs_list end verbose && println("[DONE]\n") end return TimeEvolutionHEOMSol( _getBtier(M), _getFtier(M), collect(0:Δt:(Δt*steps)), ADOs_list, expvals, nothing, nothing, nothing, nothing, ) end @doc raw""" HEOMsolve(M, ρ0, tlist; e_ops, solver, H_t, params, verbose, filename, SOLVEROptions...) Solve the time evolution for auxiliary density operators based on ordinary differential equations. # Parameters - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model - `ρ0::Union{QuantumObject,ADOs}` : system initial state (density matrix) or initial auxiliary density operators (`ADOs`) - `tlist::AbstractVector` : Denote the specific time points to save the solution at, during the solving process. - `e_ops::Union{Nothing,AbstractVector}`: List of operators for which to calculate expectation values. - `solver::OrdinaryDiffEqAlgorithm` : solver in package `DifferentialEquations.jl`. Default to `DP5()`. - `H_t::Union{Nothing,Function,TimeDependentOperatorSum}=nothing`: The time-dependent Hamiltonian or Liouvillian. It will be called by `H_t(t, params)`. - `params::NamedTuple=NamedTuple()`: The parameters of the time evolution. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. - `filename::String` : If filename was specified, the ADOs at each time point will be saved into the JLD2 file "filename.jld2" after the solving process. - `SOLVEROptions` : extra options for solver # Notes - The [`ADOs`](@ref) will be saved depend on the keyword argument `saveat` in `kwargs`. - If `e_ops` is specified, the default value of `saveat=[tlist[end]]` (only save the final `ADOs`), otherwise, `saveat=tlist` (saving the `ADOs` corresponding to `tlist`). You can also specify `e_ops` and `saveat` separately. - The default tolerances in `kwargs` are given as `reltol=1e-6` and `abstol=1e-8`. - For more details about `solver` please refer to [`DifferentialEquations.jl` (ODE Solvers)](https://docs.sciml.ai/DiffEqDocs/stable/solvers/ode_solve/) - For more details about `SOLVEROptions` please refer to [`DifferentialEquations.jl` (Keyword Arguments)](https://docs.sciml.ai/DiffEqDocs/stable/basics/common_solver_opts/) # Returns - sol::TimeEvolutionHEOMSol : The solution of the hierarchical EOM. See also [`TimeEvolutionHEOMSol`](@ref) """ function HEOMsolve( M::AbstractHEOMLSMatrix, ρ0::T_state, tlist::AbstractVector; e_ops::Union{Nothing,AbstractVector} = nothing, solver::OrdinaryDiffEqAlgorithm = DP5(), H_t::Union{Nothing,Function,TimeDependentOperatorSum} = nothing, params::NamedTuple = NamedTuple(), verbose::Bool = true, filename::String = "", SOLVEROptions..., ) where {T_state<:Union{QuantumObject,ADOs}} # check filename if filename != "" FILENAME = filename * ".jld2" isfile(FILENAME) && error("FILE: $(FILENAME) already exist.") end # handle initial state ados = (T_state <: QuantumObject) ? ADOs(ρ0, M.N, M.parity) : ρ0 _check_sys_dim_and_ADOs_num(M, ados) _check_parity(M, ados) u0 = _HandleVectorType(typeof(M.data), ados.data) t_l = convert(Vector{Float64}, tlist) # Convert it into Float64 to avoid type instabilities for OrdinaryDiffEq.jl # handle e_ops Id_cache = I(M.N) if e_ops isa Nothing expvals = Array{ComplexF64}(undef, 0, length(t_l)) tr_e_ops = typeof(M.data)[] is_empty_e_ops = true else expvals = Array{ComplexF64}(undef, length(e_ops), length(t_l)) tr_e_ops = _generate_Eops(M, e_ops, Id_cache) is_empty_e_ops = isempty(e_ops) end # handle kwargs haskey(SOLVEROptions, :save_idxs) && throw(ArgumentError("The keyword argument \"save_idxs\" is not supported in HierarchicalEOM.jl.")) saveat = is_empty_e_ops ? t_l : [t_l[end]] default_values = (DEFAULT_ODE_SOLVER_OPTIONS..., saveat = saveat) kwargs = merge(default_values, SOLVEROptions) cb = PresetTimeCallback(t_l, _HEOM_evolution_callback, save_positions = (false, false)) kwargs2 = haskey(kwargs, :callback) ? merge(kwargs, (callback = CallbackSet(kwargs.callback, cb),)) : merge(kwargs, (callback = cb,)) p = ( L = M.data, dims = M.dims, N = M.N, parity = M.parity, H_t = H_t, Id_cache = Id_cache, params = params, is_empty_e_ops = is_empty_e_ops, tr_e_ops = tr_e_ops, expvals = expvals, prog = ProgressBar(length(t_l), enable = verbose), ) # define ODE problem _dudt! = (H_t isa Nothing) ? _ti_dudt! : _td_dudt! prob = ODEProblem{true,FullSpecialize}(_dudt!, u0, (t_l[1], t_l[end]), p; kwargs2...) # start solving ode if verbose print("Solving time evolution for ADOs by Ordinary Differential Equations method...\n") flush(stdout) end sol = solve(prob, solver) ADOs_list = map(ρvec -> ADOs(_HandleVectorType(ρvec, false), M.dims, M.N, M.parity), sol.u) # save ADOs to file if filename != "" verbose && print("Saving ADOs to $(FILENAME) ... ") jldopen(FILENAME, "w") do file return file["ados"] = ADOs_list end verbose && println("[DONE]\n") end return TimeEvolutionHEOMSol( _getBtier(M), _getFtier(M), sol.t, ADOs_list, sol.prob.p.expvals, sol.retcode, sol.alg, sol.prob.kwargs[:abstol], sol.prob.kwargs[:reltol], ) end function _generate_Eops(M::AbstractHEOMLSMatrix, e_ops, Id_cache) MType = Base.typename(typeof(M.data)).wrapper{eltype(M)} tr_e_ops = [transpose(_Tr(M)) * MType(HEOMSuperOp(op, EVEN, M.dims, M.N, "L"; Id_cache = Id_cache)).data for op in e_ops] return tr_e_ops end function _HEOM_evolution_callback(integrator) p = integrator.p prog = p.prog expvals = p.expvals tr_e_ops = p.tr_e_ops if !p.is_empty_e_ops _expect = op -> dot(op, integrator.u) @. expvals[:, prog.counter[]+1] = _expect(tr_e_ops) end next!(prog) return u_modified!(integrator, false) end _ti_dudt!(du, u, p, t) = mul!(du, p.L, u) # du/dt = L * u(t) function _td_dudt!(du, u, p, t) # check system dimension of H_t _Ht = HandleMatrixType(liouvillian(p.H_t(t, p.params)), p.dims, "H_t at t=$(t)"; type = SuperOperator) L_t = HEOMSuperOp(_Ht, p.parity, p.dims, p.N, "LR"; Id_cache = p.Id_cache).data # du/dt = [L + L(t)] * u(t) mul!(du, p.L, u) return mul!(du, L_t, u, 1, 1) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
5329
@doc raw""" PowerSpectrum(M, ρ, Q_op, ωlist, reverse; solver, verbose, filename, SOLVEROptions...) Calculate power spectrum for the system in frequency domain where `P_op` will be automatically set as the adjoint of `Q_op`. This function is equivalent to: `PowerSpectrum(M, ρ, Q_op', Q_op, ωlist, reverse; solver, verbose, filename, SOLVEROptions...)` """ PowerSpectrum( M::AbstractHEOMLSMatrix, ρ::Union{QuantumObject,ADOs}, Q_op::QuantumObject, ωlist::AbstractVector, reverse::Bool = false; solver::SciMLLinearSolveAlgorithm = UMFPACKFactorization(), verbose::Bool = true, filename::String = "", SOLVEROptions..., ) = PowerSpectrum( M, ρ, Q_op', Q_op, ωlist, reverse; solver = solver, verbose = verbose, filename = filename, SOLVEROptions..., ) @doc raw""" PowerSpectrum(M, ρ, P_op, Q_op, ωlist, reverse; solver, verbose, filename, SOLVEROptions...) Calculate power spectrum for the system in frequency domain. ```math \pi S(\omega)=\textrm{Re}\left\{\int_0^\infty dt \langle P(t) Q(0)\rangle e^{-i\omega t}\right\}, ``` # To calculate spectrum when input operator `Q_op` has `EVEN`-parity: remember to set the parameters: - `M::AbstractHEOMLSMatrix`: should be `EVEN` parity # To calculate spectrum when input operator `Q_op` has `ODD`-parity: remember to set the parameters: - `M::AbstractHEOMLSMatrix`: should be `ODD` parity # Parameters - `M::AbstractHEOMLSMatrix` : the HEOMLS matrix. - `ρ::Union{QuantumObject,ADOs}` : the system density matrix or the auxiliary density operators. - `P_op::Union{QuantumObject,HEOMSuperOp}`: the system operator (or `HEOMSuperOp`) ``P`` acting on the system. - `Q_op::Union{QuantumObject,HEOMSuperOp}`: the system operator (or `HEOMSuperOp`) ``Q`` acting on the system. - `ωlist::AbstractVector` : the specific frequency points to solve. - `reverse::Bool` : If `true`, calculate ``\langle P(-t)Q(0) \rangle = \langle P(0)Q(t) \rangle = \langle P(t)Q(0) \rangle^*`` instead of ``\langle P(t) Q(0) \rangle``. Default to `false`. - `solver::SciMLLinearSolveAlgorithm` : solver in package `LinearSolve.jl`. Default to `UMFPACKFactorization()`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. - `filename::String` : If filename was specified, the value of spectrum for each ω will be saved into the file "filename.txt" during the solving process. - `SOLVEROptions` : extra options for solver # Notes - For more details about `solver` and `SOLVEROptions`, please refer to [`LinearSolve.jl`](http://linearsolve.sciml.ai/stable/) # Returns - `spec::AbstractVector` : the spectrum list corresponds to the specified `ωlist` """ @noinline function PowerSpectrum( M::AbstractHEOMLSMatrix, ρ::Union{QuantumObject,ADOs}, P_op::Union{QuantumObject,HEOMSuperOp}, Q_op::Union{QuantumObject,HEOMSuperOp}, ωlist::AbstractVector, reverse::Bool = false; solver::SciMLLinearSolveAlgorithm = UMFPACKFactorization(), verbose::Bool = true, filename::String = "", SOLVEROptions..., ) Size = size(M, 1) # Handle ρ if typeof(ρ) == ADOs # ρ::ADOs ados = ρ else ados = ADOs(ρ, M.N) end _check_sys_dim_and_ADOs_num(M, ados) Id_cache = I(M.N) # Handle P_op if typeof(P_op) <: HEOMSuperOp _check_sys_dim_and_ADOs_num(M, P_op) _P = P_op else _P = HEOMSuperOp(P_op, EVEN, M; Id_cache = Id_cache) end MType = Base.typename(typeof(M.data)).wrapper{eltype(M)} _tr_P = transpose(_Tr(M)) * MType(_P).data # Handle Q_op if typeof(Q_op) <: HEOMSuperOp _check_sys_dim_and_ADOs_num(M, Q_op) _Q_ados = Q_op * ados _check_parity(M, _Q_ados) else if M.parity == EVEN _Q = HEOMSuperOp(Q_op, ados.parity, M; Id_cache = Id_cache) else _Q = HEOMSuperOp(Q_op, !ados.parity, M; Id_cache = Id_cache) end _Q_ados = _Q * ados end b = _HandleVectorType(typeof(M.data), _Q_ados.data) SAVE::Bool = (filename != "") if SAVE FILENAME = filename * ".txt" isfile(FILENAME) && error("FILE: $(FILENAME) already exist.") end ElType = eltype(M) ωList = _HandleFloatType(ElType, ωlist) Length = length(ωList) Sω = Vector{Float64}(undef, Length) if verbose print("Calculating power spectrum in frequency domain...\n") flush(stdout) end prog = ProgressBar(Length; enable = verbose) i = reverse ? convert(ElType, 1im) : i = convert(ElType, -1im) I_total = _HandleIdentityType(typeof(M.data), Size) cache = nothing for ω in ωList Iω = i * ω * I_total if prog.counter[] == 0 cache = init(LinearProblem(M.data + Iω, b), solver, SOLVEROptions...) sol = solve!(cache) else cache.A = M.data + Iω sol = solve!(cache) end # trace over the Hilbert space of system (expectation value) val = -1 * real(dot(_tr_P, sol.u)) Sω[prog.counter[]+1] = val if SAVE open(FILENAME, "a") do file return write(file, "$(val),\n") end end next!(prog) end if verbose println("[DONE]") end return Sω end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
4673
SteadyState(M::AbstractHEOMLSMatrix, args...; kwargs...) = error("`SteadyState` has been deprecated, please use `steadystate` instead.") @doc raw""" steadystate(M::AbstractHEOMLSMatrix; solver, verbose, SOLVEROptions...) Solve the steady state of the auxiliary density operators based on `LinearSolve.jl` (i.e., solving ``x`` where ``A \times x = b``). # Parameters - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model, where the parity should be `EVEN`. - `solver::SciMLLinearSolveAlgorithm` : solver in package `LinearSolve.jl`. Default to `UMFPACKFactorization()`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. - `SOLVEROptions` : extra options for solver # Notes - For more details about `solver` and `SOLVEROptions`, please refer to [`LinearSolve.jl`](http://linearsolve.sciml.ai/stable/) # Returns - `::ADOs` : The steady state of auxiliary density operators. """ function steadystate( M::AbstractHEOMLSMatrix; solver::SciMLLinearSolveAlgorithm = UMFPACKFactorization(), verbose::Bool = true, SOLVEROptions..., ) # check parity if typeof(M.parity) != EvenParity error("The parity of M should be \"EVEN\".") end S = size(M, 1) A = _HandleSteadyStateMatrix(M, S) b = sparsevec([1], [1.0 + 0.0im], S) # solving x where A * x = b if verbose print("Solving steady state for ADOs by linear-solve method...") flush(stdout) end cache = init(LinearProblem(A, _HandleVectorType(typeof(M.data), b)), solver, SOLVEROptions...) sol = solve!(cache) if verbose println("[DONE]") flush(stdout) end return ADOs(_HandleVectorType(sol.u, false), M.dims, M.N, M.parity) end @doc raw""" steadystate(M::AbstractHEOMLSMatrix, ρ0, tspan; solver, verbose, SOLVEROptions...) Solve the steady state of the auxiliary density operators based on time evolution (`OrdinaryDiffEq.jl`) with initial state is given in the type of density-matrix (`ρ0`). # Parameters - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model, where the parity should be `EVEN`. - `ρ0::Union{QuantumObject,ADOs}` : system initial state (density matrix) or initial auxiliary density operators (`ADOs`) - `tspan::Number` : the time limit to find stationary state. Default to `Inf` - `solver::OrdinaryDiffEqAlgorithm` : The ODE solvers in package `DifferentialEquations.jl`. Default to `DP5()`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. - `SOLVEROptions` : extra options for solver # Notes - For more details about `solver` please refer to [`DifferentialEquations.jl` (ODE Solvers)](https://docs.sciml.ai/DiffEqDocs/stable/solvers/ode_solve/) - For more details about `SOLVEROptions` please refer to [`DifferentialEquations.jl` (Keyword Arguments)](https://docs.sciml.ai/DiffEqDocs/stable/basics/common_solver_opts/) # Returns - `::ADOs` : The steady state of auxiliary density operators. """ function steadystate( M::AbstractHEOMLSMatrix, ρ0::T_state, tspan::Number = Inf; solver::OrdinaryDiffEqAlgorithm = DP5(), verbose::Bool = true, SOLVEROptions..., ) where {T_state<:Union{QuantumObject,ADOs}} # handle initial state ados = (T_state <: QuantumObject) ? ADOs(ρ0, M.N, M.parity) : ρ0 _check_sys_dim_and_ADOs_num(M, ados) _check_parity(M, ados) u0 = _HandleVectorType(typeof(M.data), ados.data) Tspan = (0, tspan) kwargs = merge(DEFAULT_ODE_SOLVER_OPTIONS, SOLVEROptions) cb = TerminateSteadyState(kwargs.abstol, kwargs.reltol, _ss_condition) kwargs2 = haskey(kwargs, :callback) ? merge(kwargs, (callback = CallbackSet(kwargs.callback, cb),)) : merge(kwargs, (callback = cb,)) # define ODE problem prob = ODEProblem{true,FullSpecialize}(MatrixOperator(M.data), u0, Tspan; kwargs2...) # solving steady state of the ODE problem if verbose println("Solving steady state for ADOs by Ordinary Differential Equations method...") flush(stdout) end sol = solve(prob, solver) if verbose println("Last timepoint t = $(sol.t[end])\n[DONE]") flush(stdout) end return ADOs(_HandleVectorType(sol.u[end], false), M.dims, M.N, M.parity) end function _ss_condition(integrator, abstol, reltol, min_t) # this condition is same as DiffEqBase.NormTerminationMode du_dt = (integrator.u - integrator.uprev) / integrator.dt norm_du_dt = norm(du_dt) if (norm_du_dt <= reltol * norm(du_dt + integrator.u)) || (norm_du_dt <= abstol) return true else return false end end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
161
include("utils.jl") # bosonic bath correlation functions include("boson/DrudeLorentz.jl") # fermionic bath correlation functions include("fermion/Lorentz.jl")
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
1442
fb(m) = 2 * m + 1 δ(j, k) = j == k ? 1 : 0 _fermi(x) = 1.0 / (exp(x) + 1.0) # Fermi-Dirac distribution function i_eigval(N, M, p) pf = [] A_matrix = zeros(M, M) for j in 1:M for k in 1:M A_matrix[j, k] = (δ(j, k + 1) + δ(j, k - 1)) / √((fb(j - 1) + p) * (fb(k - 1) + p)) end end for val in eigvals(A_matrix)[1:N] push!(pf, -2 / val) end return pf end function matsubara(N; fermion::Bool) ϵ = [0.0] if fermion for k in 1:N push!(ϵ, (2 * k - 1) * π) end else for k in 1:N push!(ϵ, 2 * π * k) end end return ϵ end # thoss's spectral (N-1/N) pade function pade_NmN(N; fermion::Bool) if fermion local ζ = i_eigval(N, 2 * N, 0) local χ = i_eigval(N - 1, 2 * N - 1, 2) prefactor = 0.5 * N * fb(N) else local ζ = i_eigval(N, 2 * N, 2) local χ = i_eigval(N - 1, 2 * N - 1, 4) prefactor = 0.5 * N * (fb(N) + 2) end κ = [] for j in 1:N term = prefactor for k1 in 1:(N-1) term *= (χ[k1]^2 - ζ[j]^2) / (ζ[k1]^2 - ζ[j]^2 + δ(j, k1)) end term /= (ζ[N]^2 - ζ[j]^2 + δ(j, N)) push!(κ, term) end return append!([0.0], κ), append!([0.0], ζ) end function _fermi_pade(x, κ, ζ, N) f = 0.5 for l in 2:(N+1) f -= 2 * κ[l] * x / (x^2 + ζ[l]^2) end return f end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
3011
function _boson_drude_lorentz_approx_discrepancy( λ::Real, W::Real, kT::Real, N::Int, η::Vector{Ti}, γ::Vector{Tj}, ) where {Ti,Tj<:Number} δ = 2 * λ * kT / W - 1.0im * λ for k in 1:(N+1) δ -= η[k] / γ[k] end return δ end @doc raw""" Boson_DrudeLorentz_Matsubara(op, λ, W, kT, N) Constructing Drude-Lorentz bosonic bath with Matsubara expansion # Parameters - `op` : The system coupling operator, must be Hermitian and, for fermionic systems, even-parity to be compatible with charge conservation. - `λ::Real`: The coupling strength between the system and the bath. - `W::Real`: The reorganization energy (band-width) of the bath. - `kT::Real`: The product of the Boltzmann constant ``k`` and the absolute temperature ``T`` of the bath. - `N::Int`: (N+1)-terms of exponential terms are used to approximate the bath correlation function. # Returns - `bath::BosonBath` : a bosonic bath object with describes the interaction between system and bosonic bath """ function Boson_DrudeLorentz_Matsubara(op, λ::Real, W::Real, kT::Real, N::Int) β = 1.0 / kT ϵ = matsubara(N, fermion = false) η = ComplexF64[λ*W*(cot(W * β / 2.0)-1.0im)] γ = ComplexF64[W] if N > 0 for l in 2:(N+1) append!(η, 4 * λ * W * ϵ[l] * (kT^2) / (((ϵ[l] * kT)^2) - W^2)) append!(γ, ϵ[l] * kT) end end δ = _boson_drude_lorentz_approx_discrepancy(λ, W, kT, N, η, γ) return BosonBath(op, η, γ, δ) end @doc raw""" Boson_DrudeLorentz_Pade(op, λ, W, kT, N) Constructing Drude-Lorentz bosonic bath with Padé expansion A Padé approximant is a sum-over-poles expansion (see [here](https://en.wikipedia.org/wiki/Pad%C3%A9_approximant) for more details). The application of the Padé method to spectrum decompoisitions is described in Ref. [1]. [1] [J. Chem. Phys. 134, 244106 (2011)](https://doi.org/10.1063/1.3602466) # Parameters - `op` : The system coupling operator, must be Hermitian and, for fermionic systems, even-parity to be compatible with charge conservation. - `λ::Real`: The coupling strength between the system and the bath. - `W::Real`: The reorganization energy (band-width) of the bath. - `kT::Real`: The product of the Boltzmann constant ``k`` and the absolute temperature ``T`` of the bath. - `N::Int`: (N+1)-terms of exponential terms are used to approximate the bath correlation function. # Returns - `bath::BosonBath` : a bosonic bath object with describes the interaction between system and bosonic bath """ function Boson_DrudeLorentz_Pade(op, λ::Real, W::Real, kT::Real, N::Int) β = 1.0 / kT κ, ζ = pade_NmN(N, fermion = false) η = ComplexF64[λ*W*(cot(W * β / 2.0)-1.0im)] γ = ComplexF64[W] if N > 0 for l in 2:(N+1) append!(η, κ[l] * 4 * λ * W * ζ[l] * (kT^2) / (((ζ[l] * kT)^2) - W^2)) append!(γ, ζ[l] * kT) end end δ = _boson_drude_lorentz_approx_discrepancy(λ, W, kT, N, η, γ) return BosonBath(op, η, γ, δ) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
3258
function _fermion_lorentz_matsubara_param(σ::Real, λ::Real, μ::Real, W::Real, kT::Real, N::Int) β = 1.0 / kT ϵ = matsubara(N, fermion = true) η = ComplexF64[0.5*λ*W*_fermi(1.0im * β * W)] γ = ComplexF64[W-σ*1.0im*μ] if N > 0 for l in 2:(N+1) append!(η, -1.0im * λ * kT * W^2 / (-(ϵ[l] * kT)^2 + W^2)) append!(γ, ϵ[l] * kT - σ * 1.0im * μ) end end return η, γ end @doc raw""" Fermion_Lorentz_Matsubara(op, λ, μ, W, kT, N) Constructing Lorentzian fermionic bath with Matsubara expansion # Parameters - `op` : The system annihilation operator according to the system-fermionic-bath interaction. - `λ::Real`: The coupling strength between the system and the bath. - `μ::Real`: The chemical potential of the bath. - `W::Real`: The reorganization energy (band-width) of the bath. - `kT::Real`: The product of the Boltzmann constant ``k`` and the absolute temperature ``T`` of the bath. - `N::Int`: (N+1)-terms of exponential terms are used to approximate each correlation functions (``C^{\nu=\pm}``). # Returns - `bath::FermionBath` : a fermionic bath object with describes the interaction between system and fermionic bath """ function Fermion_Lorentz_Matsubara(op, λ::Real, μ::Real, W::Real, kT::Real, N::Int) η_ab, γ_ab = _fermion_lorentz_matsubara_param(1.0, λ, μ, W, kT, N) η_em, γ_em = _fermion_lorentz_matsubara_param(-1.0, λ, μ, W, kT, N) return FermionBath(op, η_ab, γ_ab, η_em, γ_em) end function _fermion_lorentz_pade_param(ν::Real, λ::Real, μ::Real, W::Real, kT::Real, N::Int) β = 1.0 / kT κ, ζ = pade_NmN(N, fermion = true) η = ComplexF64[0.5*λ*W*_fermi_pade(1.0im * β * W, κ, ζ, N)] γ = ComplexF64[W-ν*1.0im*μ] if N > 0 for l in 2:(N+1) append!(η, -1.0im * κ[l] * λ * kT * W^2 / (-(ζ[l] * kT)^2 + W^2)) append!(γ, ζ[l] * kT - ν * 1.0im * μ) end end return η, γ end @doc raw""" Fermion_Lorentz_Pade(op, λ, μ, W, kT, N) Constructing Lorentzian fermionic bath with Padé expansion A Padé approximant is a sum-over-poles expansion (see [here](https://en.wikipedia.org/wiki/Pad%C3%A9_approximant) for more details). The application of the Padé method to spectrum decompoisitions is described in Ref. [1]. [1] [J. Chem. Phys. 134, 244106 (2011)](https://doi.org/10.1063/1.3602466) # Parameters - `op` : The system annihilation operator according to the system-fermionic-bath interaction. - `λ::Real`: The coupling strength between the system and the bath. - `μ::Real`: The chemical potential of the bath. - `W::Real`: The reorganization energy (band-width) of the bath. - `kT::Real`: The product of the Boltzmann constant ``k`` and the absolute temperature ``T`` of the bath. - `N::Int`: (N+1)-terms of exponential terms are used to approximate each correlation functions (``C^{\nu=\pm}``). # Returns - `bath::FermionBath` : a fermionic bath object with describes the interaction between system and fermionic bath """ function Fermion_Lorentz_Pade(op, λ::Real, μ::Real, W::Real, kT::Real, N::Int) η_ab, γ_ab = _fermion_lorentz_pade_param(1.0, λ, μ, W, kT, N) η_em, γ_em = _fermion_lorentz_pade_param(-1.0, λ, μ, W, kT, N) return FermionBath(op, η_ab, γ_ab, η_em, γ_em) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
10601
abstract type AbstractHierarchyDict end @doc raw""" struct HierarchyDict <: AbstractHierarchyDict An object which contains all dictionaries for pure (bosonic or fermionic) bath-ADOs hierarchy. # Fields - `idx2nvec` : Return the `Nvec` from a given index of ADO - `nvec2idx` : Return the index of ADO from a given `Nvec` - `lvl2idx` : Return the list of ADO-indices from a given hierarchy level - `bathPtr` : Records the tuple ``(\alpha, k)`` for each position in `Nvec`, where ``\alpha`` and ``k`` represents the ``k``-th exponential-expansion term of the ``\alpha``-th bath. """ struct HierarchyDict <: AbstractHierarchyDict idx2nvec::Vector{Nvec} nvec2idx::Dict{Nvec,Int} lvl2idx::Dict{Int,Vector{Int}} bathPtr::Vector{Tuple{Int,Int}} end @doc raw""" struct MixHierarchyDict <: AbstractHierarchyDict An object which contains all dictionaries for mixed (bosonic and fermionic) bath-ADOs hierarchy. # Fields - `idx2nvec` : Return the tuple `(Nvec_b, Nvec_f)` from a given index of ADO, where `b` represents boson and `f` represents fermion - `nvec2idx` : Return the index from a given tuple `(Nvec_b, Nvec_f)`, where `b` represents boson and `f` represents fermion - `Blvl2idx` : Return the list of ADO-indices from a given bosonic-hierarchy level - `Flvl2idx` : Return the list of ADO-indices from a given fermionic-hierarchy level - `bosonPtr` : Records the tuple ``(\alpha, k)`` for each position in `Nvec_b`, where ``\alpha`` and ``k`` represents the ``k``-th exponential-expansion term of the ``\alpha``-th bosonic bath. - `fermionPtr` : Records the tuple ``(\alpha, k)`` for each position in `Nvec_f`, where ``\alpha`` and ``k`` represents the ``k``-th exponential-expansion term of the ``\alpha``-th fermionic bath. """ struct MixHierarchyDict <: AbstractHierarchyDict idx2nvec::Vector{Tuple{Nvec,Nvec}} nvec2idx::Dict{Tuple{Nvec,Nvec},Int} Blvl2idx::Dict{Int,Vector{Int}} Flvl2idx::Dict{Int,Vector{Int}} bosonPtr::Vector{Tuple{Int,Int}} fermionPtr::Vector{Tuple{Int,Int}} end # generate index to n vector function _Idx2Nvec(n_max::Vector{Int}, N_exc::Int) len = length(n_max) nvec = zeros(Int, len) result = [Nvec(nvec)] nexc = 0 while true idx = len nvec[end] += 1 nexc += 1 if nvec[idx] < n_max[idx] push!(result, Nvec(nvec)) end while (nexc == N_exc) || (nvec[idx] == n_max[idx]) #nvec[idx] = 0 idx -= 1 if idx < 1 return result end nexc -= nvec[idx+1] - 1 nvec[idx+1] = 0 nvec[idx] += 1 if nvec[idx] < n_max[idx] push!(result, Nvec(nvec)) end end end end function _Importance(B::Vector{T}, bathPtr::AbstractVector, nvec::Nvec) where {T<:AbstractBath} sum_γ = 0.0 value = 1.0 + 0.0im for idx in findall(n_exc -> n_exc > 0, nvec) for _ in 1:(nvec[idx]) α, k = bathPtr[idx] γ = real(B[α][k].γ) sum_γ += γ value *= (B[α][k].η / (γ * sum_γ)) end end return abs(value) end # for pure hierarchy dictionary @noinline function genBathHierarchy( B::Vector{T}, tier::Int, dims::SVector; threshold::Real = 0.0, ) where {T<:AbstractBath} Nterm = 0 bathPtr = Tuple[] if T == BosonBath baths = AbstractBosonBath[] for (α, b) in enumerate(B) if b.op.dims != dims error("The matrix size of the bosonic bath coupling operators are not consistent.") end push!(baths, b.bath...) for k in 1:b.Nterm push!(bathPtr, (α, k)) end Nterm += b.Nterm end n_max = fill((tier + 1), Nterm) elseif T == FermionBath baths = AbstractFermionBath[] for (α, b) in enumerate(B) if b.op.dims != dims error("The matrix size of the fermionic bath coupling operators are not consistent.") end push!(baths, b.bath...) for k in 1:b.Nterm push!(bathPtr, (α, k)) end Nterm += b.Nterm end if tier == 0 n_max = fill(1, Nterm) elseif tier >= 1 n_max = fill(2, Nterm) end end # create idx2nvec and remove nvec when its value of importance is below threshold idx2nvec = _Idx2Nvec(n_max, tier) if threshold > 0.0 splock = SpinLock() drop_idx = Int[] @threads for idx in eachindex(idx2nvec) nvec = idx2nvec[idx] # only neglect the nvec where level ≥ 2 if nvec.level >= 2 Ath = _Importance(B, bathPtr, nvec) if Ath < threshold lock(splock) try push!(drop_idx, idx) finally unlock(splock) end end end end sort!(drop_idx) deleteat!(idx2nvec, drop_idx) end # create lvl2idx and nvec2idx lvl2idx = Dict{Int,Vector{Int}}() nvec2idx = Dict{Nvec,Int}() for level in 0:tier lvl2idx[level] = [] end for (idx, nvec) in enumerate(idx2nvec) push!(lvl2idx[nvec.level], idx) nvec2idx[nvec] = idx end hierarchy = HierarchyDict(idx2nvec, nvec2idx, lvl2idx, bathPtr) return length(idx2nvec), baths, hierarchy end # for mixed hierarchy dictionary @noinline function genBathHierarchy( bB::Vector{BosonBath}, fB::Vector{FermionBath}, tier_b::Int, tier_f::Int, dims::SVector; threshold::Real = 0.0, ) # deal with boson bath Nterm_b = 0 bosonPtr = Tuple[] baths_b = AbstractBosonBath[] for (α, b) in enumerate(bB) if b.op.dims != dims error("The matrix size of the bosonic bath coupling operators are not consistent.") end push!(baths_b, b.bath...) for k in 1:b.Nterm push!(bosonPtr, (α, k)) end Nterm_b += b.Nterm end n_max_b = fill((tier_b + 1), Nterm_b) idx2nvec_b = _Idx2Nvec(n_max_b, tier_b) # deal with fermion bath Nterm_f = 0 fermionPtr = Tuple[] baths_f = AbstractFermionBath[] for (α, b) in enumerate(fB) if b.op.dims != dims error("The matrix size of the fermionic bath coupling operators are not consistent.") end push!(baths_f, b.bath...) for k in 1:b.Nterm push!(fermionPtr, (α, k)) end Nterm_f += b.Nterm end if tier_f == 0 n_max_f = fill(1, Nterm_f) elseif tier_f >= 1 n_max_f = fill(2, Nterm_f) end idx2nvec_f = _Idx2Nvec(n_max_f, tier_f) # only store nvec tuple when its value of importance is above threshold idx2nvec = Tuple{Nvec,Nvec}[] if threshold > 0.0 splock = SpinLock() @threads for nvec_b in idx2nvec_b for nvec_f in idx2nvec_f # only neglect the nvec tuple where level ≥ 2 if (nvec_b.level >= 2) || (nvec_f.level >= 2) Ath = _Importance(bB, bosonPtr, nvec_b) * _Importance(fB, fermionPtr, nvec_f) if Ath >= threshold lock(splock) try push!(idx2nvec, (nvec_b, nvec_f)) finally unlock(splock) end end else lock(splock) try push!(idx2nvec, (nvec_b, nvec_f)) finally unlock(splock) end end end end else for nvec_b in idx2nvec_b for nvec_f in idx2nvec_f push!(idx2nvec, (nvec_b, nvec_f)) end end end # create lvl2idx and nvec2idx nvec2idx = Dict{Tuple{Nvec,Nvec},Int}() blvl2idx = Dict{Int,Vector{Int}}() flvl2idx = Dict{Int,Vector{Int}}() for level in 0:tier_b blvl2idx[level] = [] end for level in 0:tier_f flvl2idx[level] = [] end for (idx, nvecTuple) in enumerate(idx2nvec) push!(blvl2idx[nvecTuple[1].level], idx) push!(flvl2idx[nvecTuple[2].level], idx) nvec2idx[nvecTuple] = idx end hierarchy = MixHierarchyDict(idx2nvec, nvec2idx, blvl2idx, flvl2idx, bosonPtr, fermionPtr) return length(idx2nvec), baths_b, baths_f, hierarchy end @doc raw""" getIndexEnsemble(nvec, bathPtr) Search for all the multi-index ensemble ``(\alpha, k)`` where ``\alpha`` and ``k`` represents the ``k``-th exponential-expansion term in the ``\alpha``-th bath. # Parameters - `nvec::Nvec` : An object which records the repetition number of each multi-index ensembles in ADOs. - `bathPtr::Vector{Tuple{Int, Int}}`: This can be obtained from [`HierarchyDict.bathPtr`](@ref HierarchyDict), [`MixHierarchyDict.bosonPtr`](@ref MixHierarchyDict), or [`MixHierarchyDict.fermionPtr`](@ref MixHierarchyDict). # Returns - `Vector{Tuple{Int, Int, Int}}`: a vector (list) of the tuples ``(\alpha, k, n)``. # Example Here is an example to use [`Bath`](@ref lib-Bath), [`Exponent`](@ref), [`HierarchyDict`](@ref), and `getIndexEnsemble` together: ```julia L::M_Fermion; # suppose this is a fermion type of HEOM Liouvillian superoperator matrix you create HDict = L.hierarchy; # the hierarchy dictionary ados = SteadyState(L); # the stationary state (ADOs) for L # Let's consider all the ADOs for first level idx_list = HDict.lvl2idx[1]; for idx in idx_list ρ1 = ados[idx] # one of the 1st-level ADO nvec = HDict.idx2nvec[idx] # the nvec corresponding to ρ1 for (α, k, n) in getIndexEnsemble(nvec, HDict.bathPtr) α # index of the bath k # the index of the exponential-expansion term in α-th bath n # the repetition number of the ensemble {α, k} in ADOs exponent = L.bath[α][k] # the k-th exponential-expansion term in α-th bath # do some calculations you want end end ``` """ function getIndexEnsemble(nvec::Nvec, bathPtr::Vector{Tuple{Int,Int}}) if length(nvec) != length(bathPtr) error("The given \"nvec\" and \"bathPtr\" are not consistent.") end result = Tuple{Int,Int,Int}[] for idx in nvec.data.nzind α, k = bathPtr[idx] push!(result, (α, k, nvec[idx])) end return result end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
5769
@doc raw""" struct M_Boson <: AbstractHEOMLSMatrix HEOM Liouvillian superoperator matrix for bosonic bath # Fields - `data<:AbstractSparseMatrix` : the sparse matrix of HEOM Liouvillian superoperator - `tier` : the tier (cutoff level) for the bosonic hierarchy - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of total ADOs - `sup_dim` : the dimension of system superoperator - `parity` : the parity label of the operator which HEOMLS is acting on (usually `EVEN`, only set as `ODD` for calculating spectrum of fermionic system). - `bath::Vector{BosonBath}` : the vector which stores all `BosonBath` objects - `hierarchy::HierarchyDict`: the object which contains all dictionaries for boson-bath-ADOs hierarchy. """ struct M_Boson{T<:AbstractSparseMatrix} <: AbstractHEOMLSMatrix{T} data::T tier::Int dims::SVector N::Int sup_dim::Int parity::AbstractParity bath::Vector{BosonBath} hierarchy::HierarchyDict end function M_Boson( Hsys::QuantumObject, tier::Int, Bath::BosonBath, parity::AbstractParity = EVEN; threshold::Real = 0.0, verbose::Bool = true, ) return M_Boson(Hsys, tier, [Bath], parity, threshold = threshold, verbose = verbose) end @doc raw""" M_Boson(Hsys, tier, Bath, parity=EVEN; threshold=0.0, verbose=true) Generate the boson-type HEOM Liouvillian superoperator matrix # Parameters - `Hsys` : The time-independent system Hamiltonian - `tier::Int` : the tier (cutoff level) for the bosonic bath - `Bath::Vector{BosonBath}` : objects for different bosonic baths - `parity::AbstractParity` : the parity label of the operator which HEOMLS is acting on (usually `EVEN`, only set as `ODD` for calculating spectrum of fermionic system). - `threshold::Real` : The threshold of the importance value (see Ref. [1]). Defaults to `0.0`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. Note that the parity only need to be set as `ODD` when the system contains fermionic systems and you need to calculate the spectrum (density of states) of it. [1] [Phys. Rev. B 88, 235426 (2013)](https://doi.org/10.1103/PhysRevB.88.235426) """ @noinline function M_Boson( Hsys::QuantumObject, tier::Int, Bath::Vector{BosonBath}, parity::AbstractParity = EVEN; threshold::Real = 0.0, verbose::Bool = true, ) # check for system dimension _Hsys = HandleMatrixType(Hsys, "Hsys (system Hamiltonian)") sup_dim = prod(_Hsys.dims)^2 I_sup = sparse(one(ComplexF64) * I, sup_dim, sup_dim) # the Liouvillian operator for free Hamiltonian term Lsys = minus_i_L_op(_Hsys) # bosonic bath if verbose && (threshold > 0.0) print("Checking the importance value for each ADOs...") flush(stdout) end Nado, baths, hierarchy = genBathHierarchy(Bath, tier, _Hsys.dims, threshold = threshold) idx2nvec = hierarchy.idx2nvec nvec2idx = hierarchy.nvec2idx if verbose && (threshold > 0.0) println("[DONE]") flush(stdout) end # start to construct the matrix Nthread = nthreads() L_row = [Int[] for _ in 1:Nthread] L_col = [Int[] for _ in 1:Nthread] L_val = [ComplexF64[] for _ in 1:Nthread] if verbose println("Preparing block matrices for HEOM Liouvillian superoperator (using $(Nthread) threads)...") flush(stdout) prog = ProgressBar(Nado) end @threads for idx in 1:Nado tID = threadid() # boson (current level) superoperator nvec = idx2nvec[idx] if nvec.level >= 1 sum_γ = bath_sum_γ(nvec, baths) op = Lsys - sum_γ * I_sup else op = Lsys end add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx) # connect to bosonic (n+1)th- & (n-1)th- level superoperator mode = 0 nvec_neigh = copy(nvec) for bB in baths for k in 1:bB.Nterm mode += 1 n_k = nvec[mode] # connect to bosonic (n-1)th-level superoperator if n_k > 0 Nvec_minus!(nvec_neigh, mode) if (threshold == 0.0) || haskey(nvec2idx, nvec_neigh) idx_neigh = nvec2idx[nvec_neigh] op = minus_i_D_op(bB, k, n_k) add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx_neigh) end Nvec_plus!(nvec_neigh, mode) end # connect to bosonic (n+1)th-level superoperator if nvec.level < tier Nvec_plus!(nvec_neigh, mode) if (threshold == 0.0) || haskey(nvec2idx, nvec_neigh) idx_neigh = nvec2idx[nvec_neigh] op = minus_i_B_op(bB) add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx_neigh) end Nvec_minus!(nvec_neigh, mode) end end end if verbose next!(prog) # trigger a progress bar update end end if verbose print("Constructing matrix...") flush(stdout) end L_he = sparse(reduce(vcat, L_row), reduce(vcat, L_col), reduce(vcat, L_val), Nado * sup_dim, Nado * sup_dim) if verbose println("[DONE]") flush(stdout) end return M_Boson{SparseMatrixCSC{ComplexF64,Int64}}( L_he, tier, copy(_Hsys.dims), Nado, sup_dim, parity, Bath, hierarchy, ) end _getBtier(M::M_Boson) = M.tier _getFtier(M::M_Boson) = 0
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
8757
@doc raw""" struct M_Boson_Fermion <: AbstractHEOMLSMatrix HEOM Liouvillian superoperator matrix for mixtured (bosonic and fermionic) bath # Fields - `data<:AbstractSparseMatrix` : the sparse matrix of HEOM Liouvillian superoperator - `Btier` : the tier (cutoff level) for bosonic hierarchy - `Ftier` : the tier (cutoff level) for fermionic hierarchy - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of total ADOs - `sup_dim` : the dimension of system superoperator - `parity` : the parity label of the operator which HEOMLS is acting on (usually `EVEN`, only set as `ODD` for calculating spectrum of fermionic system). - `Bbath::Vector{BosonBath}` : the vector which stores all `BosonBath` objects - `Fbath::Vector{FermionBath}` : the vector which stores all `FermionBath` objects - `hierarchy::MixHierarchyDict`: the object which contains all dictionaries for mixed-bath-ADOs hierarchy. """ struct M_Boson_Fermion{T<:AbstractSparseMatrix} <: AbstractHEOMLSMatrix{T} data::T Btier::Int Ftier::Int dims::SVector N::Int sup_dim::Int parity::AbstractParity Bbath::Vector{BosonBath} Fbath::Vector{FermionBath} hierarchy::MixHierarchyDict end function M_Boson_Fermion( Hsys::QuantumObject, Btier::Int, Ftier::Int, Bbath::BosonBath, Fbath::FermionBath, parity::AbstractParity = EVEN; threshold::Real = 0.0, verbose::Bool = true, ) return M_Boson_Fermion(Hsys, Btier, Ftier, [Bbath], [Fbath], parity, threshold = threshold, verbose = verbose) end function M_Boson_Fermion( Hsys::QuantumObject, Btier::Int, Ftier::Int, Bbath::Vector{BosonBath}, Fbath::FermionBath, parity::AbstractParity = EVEN; threshold::Real = 0.0, verbose::Bool = true, ) return M_Boson_Fermion(Hsys, Btier, Ftier, Bbath, [Fbath], parity, threshold = threshold, verbose = verbose) end function M_Boson_Fermion( Hsys::QuantumObject, Btier::Int, Ftier::Int, Bbath::BosonBath, Fbath::Vector{FermionBath}, parity::AbstractParity = EVEN; threshold::Real = 0.0, verbose::Bool = true, ) return M_Boson_Fermion(Hsys, Btier, Ftier, [Bbath], Fbath, parity, threshold = threshold, verbose = verbose) end @doc raw""" M_Boson_Fermion(Hsys, Btier, Ftier, Bbath, Fbath, parity=EVEN; threshold=0.0, verbose=true) Generate the boson-fermion-type HEOM Liouvillian superoperator matrix # Parameters - `Hsys` : The time-independent system Hamiltonian - `Btier::Int` : the tier (cutoff level) for the bosonic bath - `Ftier::Int` : the tier (cutoff level) for the fermionic bath - `Bbath::Vector{BosonBath}` : objects for different bosonic baths - `Fbath::Vector{FermionBath}` : objects for different fermionic baths - `parity::AbstractParity` : the parity label of the operator which HEOMLS is acting on (usually `EVEN`, only set as `ODD` for calculating spectrum of fermionic system). - `threshold::Real` : The threshold of the importance value (see Ref. [1, 2]). Defaults to `0.0`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. Note that the parity only need to be set as `ODD` when the system contains fermion systems and you need to calculate the spectrum of it. [1] [Phys. Rev. B 88, 235426 (2013)](https://doi.org/10.1103/PhysRevB.88.235426) [2] [Phys. Rev. B 103, 235413 (2021)](https://doi.org/10.1103/PhysRevB.103.235413) """ @noinline function M_Boson_Fermion( Hsys::QuantumObject, Btier::Int, Ftier::Int, Bbath::Vector{BosonBath}, Fbath::Vector{FermionBath}, parity::AbstractParity = EVEN; threshold::Real = 0.0, verbose::Bool = true, ) # check for system dimension _Hsys = HandleMatrixType(Hsys, "Hsys (system Hamiltonian)") sup_dim = prod(_Hsys.dims)^2 I_sup = sparse(one(ComplexF64) * I, sup_dim, sup_dim) # the Liouvillian operator for free Hamiltonian term Lsys = minus_i_L_op(_Hsys) # check for bosonic and fermionic bath if verbose && (threshold > 0.0) print("Checking the importance value for each ADOs...") flush(stdout) end Nado, baths_b, baths_f, hierarchy = genBathHierarchy(Bbath, Fbath, Btier, Ftier, _Hsys.dims, threshold = threshold) idx2nvec = hierarchy.idx2nvec nvec2idx = hierarchy.nvec2idx if verbose && (threshold > 0.0) println("[DONE]") flush(stdout) end # start to construct the matrix Nthread = nthreads() L_row = [Int[] for _ in 1:Nthread] L_col = [Int[] for _ in 1:Nthread] L_val = [ComplexF64[] for _ in 1:Nthread] if verbose println("Preparing block matrices for HEOM Liouvillian superoperator (using $(Nthread) threads)...") flush(stdout) prog = ProgressBar(Nado) end @threads for idx in 1:Nado tID = threadid() # boson and fermion (current level) superoperator sum_γ = 0.0 nvec_b, nvec_f = idx2nvec[idx] if nvec_b.level >= 1 sum_γ += bath_sum_γ(nvec_b, baths_b) end if nvec_f.level >= 1 sum_γ += bath_sum_γ(nvec_f, baths_f) end add_operator!(Lsys - sum_γ * I_sup, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx) # connect to bosonic (n+1)th- & (n-1)th- level superoperator mode = 0 nvec_neigh = copy(nvec_b) for bB in baths_b for k in 1:bB.Nterm mode += 1 n_k = nvec_b[mode] # connect to bosonic (n-1)th-level superoperator if n_k > 0 Nvec_minus!(nvec_neigh, mode) if (threshold == 0.0) || haskey(nvec2idx, (nvec_neigh, nvec_f)) idx_neigh = nvec2idx[(nvec_neigh, nvec_f)] op = minus_i_D_op(bB, k, n_k) add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx_neigh) end Nvec_plus!(nvec_neigh, mode) end # connect to bosonic (n+1)th-level superoperator if nvec_b.level < Btier Nvec_plus!(nvec_neigh, mode) if (threshold == 0.0) || haskey(nvec2idx, (nvec_neigh, nvec_f)) idx_neigh = nvec2idx[(nvec_neigh, nvec_f)] op = minus_i_B_op(bB) add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx_neigh) end Nvec_minus!(nvec_neigh, mode) end end end # connect to fermionic (n+1)th- & (n-1)th- level superoperator mode = 0 nvec_neigh = copy(nvec_f) for fB in baths_f for k in 1:fB.Nterm mode += 1 n_k = nvec_f[mode] # connect to fermionic (n-1)th-level superoperator if n_k > 0 Nvec_minus!(nvec_neigh, mode) if (threshold == 0.0) || haskey(nvec2idx, (nvec_b, nvec_neigh)) idx_neigh = nvec2idx[(nvec_b, nvec_neigh)] op = minus_i_C_op(fB, k, nvec_f.level, sum(nvec_neigh[1:(mode-1)]), parity) add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx_neigh) end Nvec_plus!(nvec_neigh, mode) # connect to fermionic (n+1)th-level superoperator elseif nvec_f.level < Ftier Nvec_plus!(nvec_neigh, mode) if (threshold == 0.0) || haskey(nvec2idx, (nvec_b, nvec_neigh)) idx_neigh = nvec2idx[(nvec_b, nvec_neigh)] op = minus_i_A_op(fB, nvec_f.level, sum(nvec_neigh[1:(mode-1)]), parity) add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx_neigh) end Nvec_minus!(nvec_neigh, mode) end end end if verbose next!(prog) # trigger a progress bar update end end if verbose print("Constructing matrix...") flush(stdout) end L_he = sparse(reduce(vcat, L_row), reduce(vcat, L_col), reduce(vcat, L_val), Nado * sup_dim, Nado * sup_dim) if verbose println("[DONE]") flush(stdout) end return M_Boson_Fermion{SparseMatrixCSC{ComplexF64,Int64}}( L_he, Btier, Ftier, copy(_Hsys.dims), Nado, sup_dim, parity, Bbath, Fbath, hierarchy, ) end _getBtier(M::M_Boson_Fermion) = M.Btier _getFtier(M::M_Boson_Fermion) = M.Ftier
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
5742
@doc raw""" struct M_Fermion <: AbstractHEOMLSMatrix HEOM Liouvillian superoperator matrix for fermionic bath # Fields - `data<:AbstractSparseMatrix` : the sparse matrix of HEOM Liouvillian superoperator - `tier` : the tier (cutoff level) for the fermionic hierarchy - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of total ADOs - `sup_dim` : the dimension of system superoperator - `parity` : the parity label of the operator which HEOMLS is acting on (usually `EVEN`, only set as `ODD` for calculating spectrum of fermionic system). - `bath::Vector{FermionBath}` : the vector which stores all `FermionBath` objects - `hierarchy::HierarchyDict`: the object which contains all dictionaries for fermion-bath-ADOs hierarchy. """ struct M_Fermion{T<:AbstractSparseMatrix} <: AbstractHEOMLSMatrix{T} data::T tier::Int dims::SVector N::Int sup_dim::Int parity::AbstractParity bath::Vector{FermionBath} hierarchy::HierarchyDict end function M_Fermion( Hsys::QuantumObject, tier::Int, Bath::FermionBath, parity::AbstractParity = EVEN; threshold::Real = 0.0, verbose::Bool = true, ) return M_Fermion(Hsys, tier, [Bath], parity, threshold = threshold, verbose = verbose) end @doc raw""" M_Fermion(Hsys, tier, Bath, parity=EVEN; threshold=0.0, verbose=true) Generate the fermion-type HEOM Liouvillian superoperator matrix # Parameters - `Hsys` : The time-independent system Hamiltonian - `tier::Int` : the tier (cutoff level) for the fermionic bath - `Bath::Vector{FermionBath}` : objects for different fermionic baths - `parity::AbstractParity` : the parity label of the operator which HEOMLS is acting on (usually `EVEN`, only set as `ODD` for calculating spectrum of fermionic system). - `threshold::Real` : The threshold of the importance value (see Ref. [1]). Defaults to `0.0`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. [1] [Phys. Rev. B 88, 235426 (2013)](https://doi.org/10.1103/PhysRevB.88.235426) """ @noinline function M_Fermion( Hsys::QuantumObject, tier::Int, Bath::Vector{FermionBath}, parity::AbstractParity = EVEN; threshold::Real = 0.0, verbose::Bool = true, ) # check for system dimension _Hsys = HandleMatrixType(Hsys, "Hsys (system Hamiltonian)") sup_dim = prod(_Hsys.dims)^2 I_sup = sparse(one(ComplexF64) * I, sup_dim, sup_dim) # the Liouvillian operator for free Hamiltonian term Lsys = minus_i_L_op(_Hsys) # fermionic bath if verbose && (threshold > 0.0) print("Checking the importance value for each ADOs...") flush(stdout) end Nado, baths, hierarchy = genBathHierarchy(Bath, tier, _Hsys.dims, threshold = threshold) idx2nvec = hierarchy.idx2nvec nvec2idx = hierarchy.nvec2idx if verbose && (threshold > 0.0) println("[DONE]") flush(stdout) end # start to construct the matrix Nthread = nthreads() L_row = [Int[] for _ in 1:Nthread] L_col = [Int[] for _ in 1:Nthread] L_val = [ComplexF64[] for _ in 1:Nthread] if verbose println("Preparing block matrices for HEOM Liouvillian superoperator (using $(Nthread) threads)...") flush(stdout) prog = ProgressBar(Nado) end @threads for idx in 1:Nado tID = threadid() # fermion (current level) superoperator nvec = idx2nvec[idx] if nvec.level >= 1 sum_γ = bath_sum_γ(nvec, baths) op = Lsys - sum_γ * I_sup else op = Lsys end add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx) # connect to fermionic (n+1)th- & (n-1)th- level superoperator mode = 0 nvec_neigh = copy(nvec) for fB in baths for k in 1:fB.Nterm mode += 1 n_k = nvec[mode] # connect to fermionic (n-1)th-level superoperator if n_k > 0 Nvec_minus!(nvec_neigh, mode) if (threshold == 0.0) || haskey(nvec2idx, nvec_neigh) idx_neigh = nvec2idx[nvec_neigh] op = minus_i_C_op(fB, k, nvec.level, sum(nvec_neigh[1:(mode-1)]), parity) add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx_neigh) end Nvec_plus!(nvec_neigh, mode) # connect to fermionic (n+1)th-level superoperator elseif nvec.level < tier Nvec_plus!(nvec_neigh, mode) if (threshold == 0.0) || haskey(nvec2idx, nvec_neigh) idx_neigh = nvec2idx[nvec_neigh] op = minus_i_A_op(fB, nvec.level, sum(nvec_neigh[1:(mode-1)]), parity) add_operator!(op, L_row[tID], L_col[tID], L_val[tID], Nado, idx, idx_neigh) end Nvec_minus!(nvec_neigh, mode) end end end if verbose next!(prog) # trigger a progress bar update end end if verbose print("Constructing matrix...") flush(stdout) end L_he = sparse(reduce(vcat, L_row), reduce(vcat, L_col), reduce(vcat, L_val), Nado * sup_dim, Nado * sup_dim) if verbose println("[DONE]") flush(stdout) end return M_Fermion{SparseMatrixCSC{ComplexF64,Int64}}( L_he, tier, copy(_Hsys.dims), Nado, sup_dim, parity, Bath, hierarchy, ) end _getBtier(M::M_Fermion) = 0 _getFtier(M::M_Fermion) = M.tier
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
2569
@doc raw""" struct M_S <: AbstractHEOMLSMatrix HEOM Liouvillian superoperator matrix with cutoff level of the hierarchy equals to `0`. This corresponds to the standard Schrodinger (Liouville-von Neumann) equation, namely ```math M[\cdot]=-i \left[H_{sys}, \cdot \right]_-, ``` where ``[\cdot, \cdot]_-`` stands for commutator. # Fields - `data<:AbstractSparseMatrix` : the sparse matrix of HEOM Liouvillian superoperator - `tier` : the tier (cutoff level) for the hierarchy, which equals to `0` in this case - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of total ADOs, which equals to `1` (only the reduced density operator) in this case - `sup_dim` : the dimension of system superoperator - `parity` : the parity label of the operator which HEOMLS is acting on (usually `EVEN`, only set as `ODD` for calculating spectrum of fermionic system). """ struct M_S{T<:AbstractSparseMatrix} <: AbstractHEOMLSMatrix{T} data::T tier::Int dims::SVector N::Int sup_dim::Int parity::AbstractParity end @doc raw""" M_S(Hsys, parity=EVEN; verbose=true) Generate HEOM Liouvillian superoperator matrix with cutoff level of the hierarchy equals to `0`. This corresponds to the standard Schrodinger (Liouville-von Neumann) equation, namely ```math M[\cdot]=-i \left[H_{sys}, \cdot \right]_-, ``` where ``[\cdot, \cdot]_-`` stands for commutator. # Parameters - `Hsys` : The time-independent system Hamiltonian - `parity::AbstractParity` : the parity label of the operator which HEOMLS is acting on (usually `EVEN`, only set as `ODD` for calculating spectrum of fermionic system). - `verbose::Bool` : To display verbose output during the process or not. Defaults to `true`. Note that the parity only need to be set as `ODD` when the system contains fermionic systems and you need to calculate the spectrum (density of states) of it. """ @noinline function M_S(Hsys::QuantumObject, parity::AbstractParity = EVEN; verbose::Bool = true) # check for system dimension _Hsys = HandleMatrixType(Hsys, "Hsys (system Hamiltonian)") sup_dim = prod(_Hsys.dims)^2 # the Liouvillian operator for free Hamiltonian if verbose println("Constructing Liouville-von Neumann superoperator...") flush(stdout) end Lsys = minus_i_L_op(_Hsys) if verbose println("[DONE]") flush(stdout) end return M_S{SparseMatrixCSC{ComplexF64,Int64}}(Lsys, 0, copy(_Hsys.dims), 1, sup_dim, parity) end _getBtier(M::M_S) = 0 _getFtier(M::M_S) = 0
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
2325
@doc raw""" struct Nvec An object which describes the repetition number of each multi-index ensembles in auxiliary density operators. The `n_vector` (``\vec{n}``) denotes a set of integers: ```math \{ n_{1,1}, ..., n_{\alpha, k}, ... \} ``` associated with the ``k``-th exponential-expansion term in the ``\alpha``-th bath. If ``n_{\alpha, k} = 3`` means that the multi-index ensemble ``\{\alpha, k\}`` appears three times in the multi-index vector of ADOs (see the notations in our paper). The hierarchy level (``L``) for an `n_vector` is given by ``L=\sum_{\alpha, k} n_{\alpha, k}`` # Fields - `data` : the `n_vector` - `level` : The level `L` for the `n_vector` # Methods One can obtain the repetition number for specific index (`idx`) by calling : `n_vector[idx]`. To obtain the corresponding tuple ``(\alpha, k)`` for a given index `idx`, see `bathPtr` in [`HierarchyDict`](@ref) for more details. `HierarchicalEOM.jl` also supports the following calls (methods) : ```julia length(n_vector); # returns the length of `Nvec` n_vector[1:idx]; # returns a vector which contains the excitation number of `n_vector` from index `1` to `idx` n_vector[1:end]; # returns a vector which contains all the excitation number of `n_vector` n_vector[:]; # returns a vector which contains all the excitation number of `n_vector` from n in n_vector # iteration # do something end ``` """ mutable struct Nvec data::SparseVector{Int,Int} level::Int end Nvec(V::Vector{Int}) = Nvec(sparsevec(V), sum(V)) Nvec(V::SparseVector{Int,Int}) = Nvec(copy(V), sum(V)) length(nvec::Nvec) = length(nvec.data) lastindex(nvec::Nvec) = length(nvec) getindex(nvec::Nvec, i::T) where {T<:Any} = nvec.data[i] keys(nvec::Nvec) = keys(nvec.data) iterate(nvec::Nvec, state::Int = 1) = state > length(nvec) ? nothing : (nvec[state], state + 1) show(io::IO, nvec::Nvec) = print(io, "Nvec($(nvec[:]))") show(io::IO, m::MIME"text/plain", nvec::Nvec) = show(io, nvec) hash(nvec::Nvec, h::UInt) = hash(nvec.data, h) (==)(nvec1::Nvec, nvec2::Nvec) = hash(nvec1) == hash(nvec2) copy(nvec::Nvec) = Nvec(copy(nvec.data), nvec.level) function Nvec_plus!(nvec::Nvec, idx::Int) nvec.data[idx] += 1 return nvec.level += 1 end function Nvec_minus!(nvec::Nvec, idx::Int) nvec.data[idx] -= 1 return nvec.level -= 1 end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
19528
@doc raw""" struct HEOMSuperOp General HEOM superoperator matrix. # Fields - `data<:AbstractSparseMatrix` : the HEOM superoperator matrix - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of auxiliary density operators - `parity`: the parity label (`EVEN` or `ODD`). """ struct HEOMSuperOp{T<:AbstractSparseMatrix} data::T dims::SVector N::Int parity::AbstractParity end @doc raw""" HEOMSuperOp(op, opParity, refHEOMLS, mul_basis="L"; Id_cache=I(refHEOMLS.N)) Construct the HEOM superoperator matrix corresponding to the given system operator which acts on all `ADOs`. During the multiplication on all the `ADOs`, the parity of the output `ADOs` might change depend on the parity of this HEOM superoperator. # Parameters - `op` : The system operator which will act on all `ADOs`. - `opParity::AbstractParity` : the parity label of the given operator (`op`), should be `EVEN` or `ODD`. - `refHEOMLS::AbstractHEOMLSMatrix` : copy the system `dims` and number of `ADOs` (`N`) from this reference HEOMLS matrix - `mul_basis::AbstractString` : this specifies the basis for `op` to multiply on all `ADOs`. Defaults to `"L"`. if `mul_basis` is specified as - `"L"` : the matrix `op` has same dimension with the system and acts on left-hand side. - `"R"` : the matrix `op` has same dimension with the system and acts on right-hand side. - `"LR"` : the matrix `op` is a superoperator of the system. """ HEOMSuperOp( op, opParity::AbstractParity, refHEOMLS::AbstractHEOMLSMatrix, mul_basis::AbstractString = "L"; Id_cache = I(refHEOMLS.N), ) = HEOMSuperOp(op, opParity, refHEOMLS.dims, refHEOMLS.N, mul_basis; Id_cache = Id_cache) @doc raw""" HEOMSuperOp(op, opParity, refADOs, mul_basis="L"; Id_cache=I(refADOs.N)) Construct the HEOMLS matrix corresponding to the given system operator which multiplies on the "L"eft-hand ("R"ight-hand) side basis of all `ADOs`. During the multiplication on all the `ADOs`, the parity of the output `ADOs` might change depend on the parity of this HEOM superoperator. # Parameters - `op` : The system operator which will act on all `ADOs`. - `opParity::AbstractParity` : the parity label of the given operator (`op`), should be `EVEN` or `ODD`. - `refADOs::ADOs` : copy the system `dims` and number of `ADOs` (`N`) from this reference `ADOs` - `mul_basis::AbstractString` : this specifies the basis for `op` to multiply on all `ADOs`. Defaults to `"L"`. if `mul_basis` is specified as - `"L"` : the matrix `op` has same dimension with the system and acts on left-hand side. - `"R"` : the matrix `op` has same dimension with the system and acts on right-hand side. - `"LR"` : the matrix `op` is a superoperator of the system. """ HEOMSuperOp(op, opParity::AbstractParity, refADOs::ADOs, mul_basis::AbstractString = "L"; Id_cache = I(refADOs.N)) = HEOMSuperOp(op, opParity, refADOs.dims, refADOs.N, mul_basis; Id_cache = Id_cache) @doc raw""" HEOMSuperOp(op, opParity, dims, N, mul_basis; Id_cache=I(N)) Construct the HEOM superoperator matrix corresponding to the given system operator which acts on all `ADOs`. During the multiplication on all the `ADOs`, the parity of the output `ADOs` might change depend on the parity of this HEOM superoperator. # Parameters - `op` : The system operator which will act on all `ADOs`. - `opParity::AbstractParity` : the parity label of the given operator (`op`), should be `EVEN` or `ODD`. - `dims::SVector` : the dimension list of the coupling operator (should be equal to the system dims). - `N::Int` : the number of `ADOs`. - `mul_basis::AbstractString` : this specifies the basis for `op` to multiply on all `ADOs`. if `mul_basis` is specified as - `"L"` : the matrix `op` has same dimension with the system and acts on left-hand side. - `"R"` : the matrix `op` has same dimension with the system and acts on right-hand side. - `"LR"` : the matrix `op` is a SuperOperator of the system. """ function HEOMSuperOp(op, opParity::AbstractParity, dims::SVector, N::Int, mul_basis::AbstractString; Id_cache = I(N)) if mul_basis == "L" sup_op = spre(HandleMatrixType(op, dims, "op (operator)")) elseif mul_basis == "R" sup_op = spost(HandleMatrixType(op, dims, "op (operator)")) elseif mul_basis == "LR" sup_op = HandleMatrixType(op, dims, "op (operator)"; type = SuperOperator) else error("The multiplication basis (mul_basis) can only be given as a string with either \"L\", \"R\", or \"LR\".") end return HEOMSuperOp(kron(Id_cache, sup_op.data), dims, N, opParity) end HEOMSuperOp(op, opParity::AbstractParity, dims::Int, N::Int, mul_basis::AbstractString; Id_cache = I(N)) = HEOMSuperOp(op, opParity, SVector{1,Int}(dims), N, mul_basis; Id_cache = Id_cache) HEOMSuperOp(op, opParity::AbstractParity, dims::Vector{Int}, N::Int, mul_basis::AbstractString; Id_cache = I(N)) = HEOMSuperOp(op, opParity, SVector{length(dims),Int}(dims), N, mul_basis; Id_cache = Id_cache) HEOMSuperOp(op, opParity::AbstractParity, dims::Tuple, N::Int, mul_basis::AbstractString; Id_cache = I(N)) = HEOMSuperOp(op, opParity, SVector(dims), N, mul_basis; Id_cache = Id_cache) function SparseMatrixCSC{T}(M::HEOMSuperOp) where {T} A = M.data if typeof(A) == SparseMatrixCSC{T} return M else return HEOMSuperOp(SparseMatrixCSC{T}(M.data), M.dims, M.N, M.parity) end end SparseMatrixCSC(M::HEOMSuperOp) = SparseMatrixCSC{ComplexF64}(M) @doc raw""" size(M::HEOMSuperOp) Returns the size of the HEOM superoperator matrix """ size(M::HEOMSuperOp) = size(M.data) @doc raw""" size(M::HEOMSuperOp, dim::Int) Returns the specified dimension of the HEOM superoperator matrix """ size(M::HEOMSuperOp, dim::Int) = size(M.data, dim) @doc raw""" size(M::AbstractHEOMLSMatrix) Returns the size of the HEOM Liouvillian superoperator matrix """ size(M::AbstractHEOMLSMatrix) = size(M.data) @doc raw""" size(M::AbstractHEOMLSMatrix, dim::Int) Returns the specified dimension of the HEOM Liouvillian superoperator matrix """ size(M::AbstractHEOMLSMatrix, dim::Int) = size(M.data, dim) @doc raw""" eltype(M::HEOMSuperOp) Returns the elements' type of the HEOM superoperator matrix """ eltype(M::HEOMSuperOp) = eltype(M.data) @doc raw""" eltype(M::AbstractHEOMLSMatrix) Returns the elements' type of the HEOM Liouvillian superoperator matrix """ eltype(M::AbstractHEOMLSMatrix) = eltype(M.data) getindex(M::HEOMSuperOp, i::Ti, j::Tj) where {Ti,Tj<:Any} = M.data[i, j] getindex(M::AbstractHEOMLSMatrix, i::Ti, j::Tj) where {Ti,Tj<:Any} = M.data[i, j] function show(io::IO, M::HEOMSuperOp) print( io, "$(M.parity) HEOM superoperator matrix acting on arbitrary-parity-ADOs\n", "system dims = $(M.dims)\n", "number of ADOs N = $(M.N)\n", "data =\n", ) return show(io, MIME("text/plain"), M.data) end function show(io::IO, M::AbstractHEOMLSMatrix) T = typeof(M) if T <: M_S type = "Schrodinger Eq." elseif T <: M_Boson type = "Boson" elseif T <: M_Fermion type = "Fermion" else type = "Boson-Fermion" end print( io, type, " type HEOMLS matrix acting on $(M.parity) ADOs\n", "system dims = $(M.dims)\n", "number of ADOs N = $(M.N)\n", "data =\n", ) return show(io, MIME("text/plain"), M.data) end show(io::IO, m::MIME"text/plain", M::HEOMSuperOp) = show(io, M) show(io::IO, m::MIME"text/plain", M::AbstractHEOMLSMatrix) = show(io, M) function *(Sup::HEOMSuperOp, ados::ADOs) _check_sys_dim_and_ADOs_num(Sup, ados) return ADOs(Sup.data * ados.data, ados.dims, ados.N, Sup.parity * ados.parity) end function *(Sup1::HEOMSuperOp, Sup2::HEOMSuperOp) _check_sys_dim_and_ADOs_num(Sup1, Sup2) return HEOMSuperOp(Sup1.data * Sup2.data, Sup1.dims, Sup1.N, Sup1.parity * Sup2.parity) end *(n::Number, Sup::HEOMSuperOp) = HEOMSuperOp(n * Sup.data, Sup.dims, Sup.N, Sup.parity) *(Sup::HEOMSuperOp, n::Number) = n * Sup function +(Sup1::HEOMSuperOp, Sup2::HEOMSuperOp) _check_sys_dim_and_ADOs_num(Sup1, Sup2) _check_parity(Sup1, Sup2) return HEOMSuperOp(Sup1.data + Sup2.data, Sup1.dims, Sup1.N, Sup1.parity) end function +(M::AbstractHEOMLSMatrix, Sup::HEOMSuperOp) _check_sys_dim_and_ADOs_num(M, Sup) _check_parity(M, Sup) return _reset_HEOMLS_data(M, M.data + Sup.data) end function -(Sup1::HEOMSuperOp, Sup2::HEOMSuperOp) _check_sys_dim_and_ADOs_num(Sup1, Sup2) _check_parity(Sup1, Sup2) return HEOMSuperOp(Sup1.data - Sup2.data, Sup1.dims, Sup1.N, Sup1.parity) end function -(M::AbstractHEOMLSMatrix, Sup::HEOMSuperOp) _check_sys_dim_and_ADOs_num(M, Sup) _check_parity(M, Sup) return _reset_HEOMLS_data(M, M.data - Sup.data) end @doc raw""" Propagator(M, Δt; threshold, nonzero_tol) Use `FastExpm.jl` to calculate the propagator matrix from a given HEOM Liouvillian superoperator matrix ``M`` with a specific time step ``\Delta t``. That is, ``\exp(M * \Delta t)``. # Parameters - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model - `Δt::Real` : A specific time step (time interval). - `threshold::Real` : Determines the threshold for the Taylor series. Defaults to `1.0e-6`. - `nonzero_tol::Real` : Strips elements smaller than `nonzero_tol` at each computation step to preserve sparsity. Defaults to `1.0e-14`. For more details, please refer to [`FastExpm.jl`](https://github.com/fmentink/FastExpm.jl) # Returns - `::SparseMatrixCSC{ComplexF64, Int64}` : the propagator matrix """ @noinline function Propagator(M::AbstractHEOMLSMatrix, Δt::Real; threshold = 1.0e-6, nonzero_tol = 1.0e-14) return fastExpm(M.data * Δt; threshold = threshold, nonzero_tol = nonzero_tol) end function _reset_HEOMLS_data(M::T, new_data::SparseMatrixCSC{ComplexF64,Int64}) where {T<:AbstractHEOMLSMatrix} if T <: M_S return M_S(new_data, M.tier, M.dims, M.N, M.sup_dim, M.parity) elseif T <: M_Boson return M_Boson(new_data, M.tier, M.dims, M.N, M.sup_dim, M.parity, M.bath, M.hierarchy) elseif T <: M_Fermion return M_Fermion(new_data, M.tier, M.dims, M.N, M.sup_dim, M.parity, M.bath, M.hierarchy) else return M_Boson_Fermion( new_data, M.Btier, M.Ftier, M.dims, M.N, M.sup_dim, M.parity, M.Bbath, M.Fbath, M.hierarchy, ) end end @doc raw""" addBosonDissipator(M, jumpOP) Adding bosonic dissipator to a given HEOMLS matrix which describes how the system dissipatively interacts with an extra bosonic environment. The dissipator is defined as follows ```math D[J](\cdot) = J(\cdot) J^\dagger - \frac{1}{2}\left(J^\dagger J (\cdot) + (\cdot) J^\dagger J \right), ``` where ``J\equiv \sqrt{\gamma}V`` is the jump operator, ``V`` describes the dissipative part (operator) of the dynamics, ``\gamma`` represents a non-negative damping rate and ``[\cdot, \cdot]_+`` stands for anti-commutator. Note that if ``V`` is acting on fermionic systems, it should be even-parity to be compatible with charge conservation. # Parameters - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model - `jumpOP::AbstractVector` : The list of collapse (jump) operators ``\{J_i\}_i`` to add. Defaults to empty vector `[]`. # Return - `M_new::AbstractHEOMLSMatrix` : the new HEOM Liouvillian superoperator matrix """ function addBosonDissipator(M::AbstractHEOMLSMatrix, jumpOP::Vector{T} = QuantumObject[]) where {T<:QuantumObject} if length(jumpOP) > 0 Id_cache = I(prod(M.dims)) L = QuantumObject(spzeros(ComplexF64, M.sup_dim, M.sup_dim), type = SuperOperator, dims = M.dims) for J in jumpOP L += lindblad_dissipator(J, Id_cache) end return M + HEOMSuperOp(L, M.parity, M, "LR") else return M end end addBosonDissipator(M::AbstractHEOMLSMatrix, jumpOP::QuantumObject) = addBosonDissipator(M, [jumpOP]) @doc raw""" addFermionDissipator(M, jumpOP) Adding fermionic dissipator to a given HEOMLS matrix which describes how the system dissipatively interacts with an extra fermionic environment. The dissipator with `EVEN` parity is defined as follows ```math D_{\textrm{even}}[J](\cdot) = J(\cdot) J^\dagger - \frac{1}{2}\left(J^\dagger J (\cdot) + (\cdot) J^\dagger J \right), ``` where ``J\equiv \sqrt{\gamma}V`` is the jump operator, ``V`` describes the dissipative part (operator) of the dynamics, ``\gamma`` represents a non-negative damping rate and ``[\cdot, \cdot]_+`` stands for anti-commutator. Similary, the dissipator with `ODD` parity is defined as follows ```math D_{\textrm{odd}}[J](\cdot) = - J(\cdot) J^\dagger - \frac{1}{2}\left(J^\dagger J (\cdot) + (\cdot) J^\dagger J \right), ``` Note that the parity of the dissipator will be determined by the parity of the given HEOMLS matrix `M`. # Parameters - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model - `jumpOP::AbstractVector` : The list of collapse (jump) operators to add. Defaults to empty vector `[]`. # Return - `M_new::AbstractHEOMLSMatrix` : the new HEOM Liouvillian superoperator matrix """ function addFermionDissipator(M::AbstractHEOMLSMatrix, jumpOP::Vector{T} = QuantumObject[]) where {T<:QuantumObject} if length(jumpOP) > 0 parity = value(M.parity) Id_cache = I(prod(M.dims)) L = QuantumObject(spzeros(ComplexF64, M.sup_dim, M.sup_dim), type = SuperOperator, dims = M.dims) for J in jumpOP Jd_J = J' * J L += ((-1)^parity) * sprepost(J, J') - spre(Jd_J, Id_cache) / 2 - spost(Jd_J, Id_cache) / 2 end return M + HEOMSuperOp(L, M.parity, M, "LR") else return M end end addFermionDissipator(M::AbstractHEOMLSMatrix, jumpOP::QuantumObject) = addFermionDissipator(M, [jumpOP]) @doc raw""" addTerminator(M, Bath) Adding terminator to a given HEOMLS matrix. The terminator is a Liouvillian term representing the contribution to the system-bath dynamics of all exponential-expansion terms beyond `Bath.Nterm` The difference between the true correlation function and the sum of the `Bath.Nterm`-exponential terms is approximately `2 * δ * dirac(t)`. Here, `δ` is the approximation discrepancy and `dirac(t)` denotes the Dirac-delta function. # Parameters - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model - `Bath::Union{BosonBath, FermionBath}` : The bath object which contains the approximation discrepancy δ # Return - `M_new::AbstractHEOMLSMatrix` : the new HEOM Liouvillian superoperator matrix """ function addTerminator(M::Mtype, Bath::Union{BosonBath,FermionBath}) where {Mtype<:AbstractHEOMLSMatrix} Btype = typeof(Bath) if (Btype == BosonBath) && (Mtype <: M_Fermion) error("For $(Btype), the type of HEOMLS matrix should be either M_Boson or M_Boson_Fermion.") elseif (Btype == FermionBath) && (Mtype <: M_Boson) error("For $(Btype), the type of HEOMLS matrix should be either M_Fermion or M_Boson_Fermion.") elseif Mtype <: M_S error("The type of input HEOMLS matrix does not support this functionality.") end if M.dims != Bath.op.dims error("The system dims between the HEOMLS matrix and Bath coupling operator are not consistent.") end if Bath.δ == 0 @warn "The value of approximation discrepancy δ is 0.0 now, which doesn't make any changes." return M else return M + HEOMSuperOp(2 * Bath.δ * lindblad_dissipator(Bath.op), M.parity, M, "LR") end end function csc2coo(A) len = length(A.nzval) if len == 0 return A.m, A.n, [], [], [] else colidx = Vector{Int}(undef, len) @inbounds for i in 1:(length(A.colptr)-1) @inbounds for j in A.colptr[i]:(A.colptr[i+1]-1) colidx[j] = i end end return A.m, A.n, A.rowval, colidx, A.nzval end end function pad_coo( A::SparseMatrixCSC{T,Int64}, row_scale::Int, col_scale::Int, row_idx = 1::Int, col_idx = 1::Int, ) where {T<:Number} # transform matrix A's format from csc to coo M, N, I, J, V = csc2coo(A) # deal with values if T != ComplexF64 V = convert.(ComplexF64, V) end # deal with rowval if (row_idx > row_scale) || (row_idx < 1) error("row_idx must be \'>= 1\' and \'<= row_scale\'") end # deal with colval if (col_idx > col_scale) || (col_idx < 1) error("col_idx must be \'>= 1\' and \'<= col_scale\'") end @inbounds Inew = I .+ (M * (row_idx - 1)) @inbounds Jnew = J .+ (N * (col_idx - 1)) return Inew, Jnew, V end function add_operator!(op, I, J, V, N_he, row_idx, col_idx) row, col, val = pad_coo(op, N_he, N_he, row_idx, col_idx) append!(I, row) append!(J, col) append!(V, val) return nothing end # sum γ of bath for current level function bath_sum_γ(nvec, baths::Vector{T}) where {T<:Union{AbstractBosonBath,AbstractFermionBath}} p = 0 sum_γ = 0.0 for b in baths n = nvec[(p+1):(p+b.Nterm)] for k in findall(nk -> nk > 0, n) sum_γ += n[k] * b.γ[k] end p += b.Nterm end return sum_γ end # commutator of system Hamiltonian minus_i_L_op(Hsys::QuantumObject, Id = I(size(Hsys, 1))) = -1.0im * (_spre(Hsys.data, Id) - _spost(Hsys.data, Id)) # connect to bosonic (n-1)th-level for "Real & Imag combined operator" minus_i_D_op(bath::bosonRealImag, k, n_k) = n_k * (-1.0im * bath.η_real[k] * bath.Comm + bath.η_imag[k] * bath.anComm) # connect to bosonic (n-1)th-level for (Real & Imag combined) operator "Real operator" minus_i_D_op(bath::bosonReal, k, n_k) = -1.0im * n_k * bath.η[k] * bath.Comm # connect to bosonic (n-1)th-level for "Imag operator" minus_i_D_op(bath::bosonImag, k, n_k) = n_k * bath.η[k] * bath.anComm # connect to bosonic (n-1)th-level for "Absorption operator" minus_i_D_op(bath::bosonAbsorb, k, n_k) = -1.0im * n_k * (bath.η[k] * bath.spre - conj(bath.η_emit[k]) * bath.spost) # connect to bosonic (n-1)th-level for "Emission operator" minus_i_D_op(bath::bosonEmit, k, n_k) = -1.0im * n_k * (bath.η[k] * bath.spre - conj(bath.η_absorb[k]) * bath.spost) # connect to fermionic (n-1)th-level for "absorption operator" function minus_i_C_op(bath::fermionAbsorb, k, n_exc, n_exc_before, parity) return -1.0im * ((-1)^n_exc_before) * (((-1)^value(parity)) * bath.η[k] * bath.spre - (-1)^(n_exc - 1) * conj(bath.η_emit[k]) * bath.spost) end # connect to fermionic (n-1)th-level for "emission operator" function minus_i_C_op(bath::fermionEmit, k, n_exc, n_exc_before, parity) return -1.0im * ((-1)^n_exc_before) * ((-1)^(value(parity)) * bath.η[k] * bath.spre - (-1)^(n_exc - 1) * conj(bath.η_absorb[k]) * bath.spost) end # connect to bosonic (n+1)th-level for real-and-imaginary-type bosonic bath minus_i_B_op(bath::T) where {T<:Union{bosonReal,bosonImag,bosonRealImag}} = -1.0im * bath.Comm # connect to bosonic (n+1)th-level for absorption-and-emission-type bosonic bath minus_i_B_op(bath::T) where {T<:Union{bosonAbsorb,bosonEmit}} = -1.0im * bath.CommD # connect to fermionic (n+1)th-level function minus_i_A_op(bath::T, n_exc, n_exc_before, parity) where {T<:AbstractFermionBath} return -1.0im * ((-1)^n_exc_before) * ((-1)^(value(parity)) * bath.spreD + (-1)^(n_exc + 1) * bath.spostD) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
854
@time @testset "Auxiliary density operators" begin ados_b = ADOs(spzeros(Int64, 20), 5) ados_f = ADOs(spzeros(Int64, 8), 2) ados_bf = ADOs(spzeros(Int64, 40), 10) @test show(devnull, MIME("text/plain"), ados_b) === nothing @test show(devnull, MIME("text/plain"), ados_f) === nothing @test show(devnull, MIME("text/plain"), ados_bf) === nothing @test_throws ErrorException ADOs(zeros(8), 4) ρ_b = ados_b[:] # check iteration for (i, ado) in enumerate(ados_b) @test ρ_b[i] == ado end # expections for expect ados_wrong = ADOs(spzeros(Int64, 18), 2) @test_throws ErrorException expect(Qobj([0 0 0; 0 0 0; 0 0 0]), ados_f) @test_throws ErrorException expect(Qobj([0 0; 0 0]), [ados_b, ados_wrong]) @test_throws ErrorException expect(Qobj([0 0 0; 0 0 0; 0 0 0]), [ados_b, ados_f]) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
4168
using LinearSolve using CUDA CUDA.allowscalar(false) # Avoid unexpected scalar indexing CUDA.versioninfo() CUDA.@time @testset "CUDA Extension" begin # re-define the bath (make the matrix smaller) λ = 0.01 W = 0.5 kT = 0.5 μ = 0 N = 3 tier = 3 # System Hamiltonian Hsys = Qobj([0 0; 0 0]) # system-bath coupling operator Qb = sigmax() Qf = sigmam() E = Qobj(rand(ComplexF64, 2, 2)) e_ops_cpu = [E] e_ops_gpu = [E, cu(E)] # initial state ψ0 = basis(2, 1) Bbath = Boson_DrudeLorentz_Pade(Qb, λ, W, kT, N) Fbath = Fermion_Lorentz_Pade(Qf, λ, μ, W, kT, N) # Solving time Evolution ## Schrodinger HEOMLS L_cpu = M_S(Hsys; verbose = false) L_gpu = cu(L_cpu) sol_cpu = HEOMsolve(L_cpu, ψ0, [0, 10]; e_ops = e_ops_cpu, verbose = false) sol_gpu = HEOMsolve(L_gpu, ψ0, [0, 10]; e_ops = e_ops_gpu, verbose = false) @test all(isapprox.(sol_cpu.expect[1, :], sol_gpu.expect[1, :], atol = 1e-4)) @test all(isapprox.(sol_cpu.expect[1, :], sol_gpu.expect[2, :], atol = 1e-4)) @test isapprox(getRho(sol_cpu.ados[end]), getRho(sol_gpu.ados[end]), atol = 1e-4) ## Boson HEOMLS L_cpu = M_Boson(Hsys, tier, Bbath; verbose = false) L_gpu = cu(L_cpu) sol_cpu = HEOMsolve(L_cpu, ψ0, [0, 10]; e_ops = e_ops_cpu, verbose = false) sol_gpu = HEOMsolve(L_gpu, ψ0, [0, 10]; e_ops = e_ops_gpu, verbose = false) @test all(isapprox.(sol_cpu.expect[1, :], sol_gpu.expect[1, :], atol = 1e-4)) @test all(isapprox.(sol_cpu.expect[1, :], sol_gpu.expect[2, :], atol = 1e-4)) @test isapprox(getRho(sol_cpu.ados[end]), getRho(sol_gpu.ados[end]), atol = 1e-4) ## Fermion HEOMLS L_cpu = M_Fermion(Hsys, tier, Fbath; verbose = false) L_gpu = cu(L_cpu) sol_cpu = HEOMsolve(L_cpu, ψ0, [0, 10]; e_ops = e_ops_cpu, verbose = false) sol_gpu = HEOMsolve(L_gpu, ψ0, [0, 10]; e_ops = e_ops_gpu, verbose = false) @test all(isapprox.(sol_cpu.expect[1, :], sol_gpu.expect[1, :], atol = 1e-4)) @test all(isapprox.(sol_cpu.expect[1, :], sol_gpu.expect[2, :], atol = 1e-4)) @test isapprox(getRho(sol_cpu.ados[end]), getRho(sol_gpu.ados[end]), atol = 1e-4) ## Boson Fermion HEOMLS L_cpu = M_Boson_Fermion(Hsys, tier, tier, Bbath, Fbath; verbose = false) L_gpu = cu(L_cpu) tlist = 0:1:10 sol_cpu = HEOMsolve(L_cpu, ψ0, tlist; e_ops = e_ops_cpu, saveat = tlist, verbose = false) sol_gpu = HEOMsolve(L_gpu, ψ0, tlist; e_ops = e_ops_gpu, saveat = tlist, verbose = false) @test all(isapprox.(sol_cpu.expect[1, :], sol_gpu.expect[1, :], atol = 1e-4)) @test all(isapprox.(sol_cpu.expect[1, :], sol_gpu.expect[2, :], atol = 1e-4)) for i in 1:length(tlist) @test isapprox(getRho(sol_cpu.ados[i]), getRho(sol_gpu.ados[i]), atol = 1e-4) end # SIAM ϵ = -5 U = 10 σm = sigmam() ## σ- σz = sigmaz() ## σz II = qeye(2) ## identity matrix d_up = tensor(σm, II) d_dn = tensor(-1 * σz, σm) ψ0 = tensor(basis(2, 0), basis(2, 0)) Hsys = ϵ * (d_up' * d_up + d_dn' * d_dn) + U * (d_up' * d_up * d_dn' * d_dn) Γ = 2 μ = 0 W = 10 kT = 0.5 N = 5 tier = 3 bath_up = Fermion_Lorentz_Pade(d_up, Γ, μ, W, kT, N) bath_dn = Fermion_Lorentz_Pade(d_dn, Γ, μ, W, kT, N) bath_list = [bath_up, bath_dn] ## solve stationary state L_even_cpu = M_Fermion(Hsys, tier, bath_list; verbose = false) L_even_gpu = cu(L_even_cpu) ados_cpu = steadystate(L_even_cpu; verbose = false) ados_gpu = steadystate(L_even_gpu, ψ0, 10; verbose = false) @test all(isapprox.(ados_cpu.data, ados_gpu.data; atol = 1e-6)) ## solve density of states ωlist = -5:0.5:5 L_odd_cpu = M_Fermion(Hsys, tier, bath_list, ODD; verbose = false) L_odd_gpu = cu(L_odd_cpu) dos_cpu = DensityOfStates(L_odd_cpu, ados_cpu, d_up, ωlist; verbose = false) dos_gpu = DensityOfStates( L_odd_gpu, ados_cpu, d_up, ωlist; solver = KrylovJL_BICGSTAB(rtol = 1.0f-10, atol = 1.0f-12), verbose = false, ) for (i, ω) in enumerate(ωlist) @test dos_cpu[i] ≈ dos_gpu[i] atol = 1e-6 end end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
3844
@time @testset "HEOM superoperator" begin # Take waiting time distribution as an example WTD_ans = [ 0.0, 0.0015096807591478143, 0.0019554827640519456, 0.0019720219482432183, 0.0018278123354472694, 0.0016348729788834187, 0.0014385384773227094, 0.0012559122034857784, 0.0010923035083891884, 0.0009482348815344435, 0.0008224107708326052, 0.0007129580704171314, 0.0006179332764127152, 0.0005355140701828154, 0.00046406230317384855, 0.00040213314306247375, 0.0003484637380485898, 0.0003019551325507645, 0.00026165305303984653, 0.0002267297384879625, 0.0001964675440128574, ] ϵ = -0.1 Γ = 0.01 μ = 0 W = 1 kT = 0.5 N = 5 tier = 3 tlist = 0:50:1000 γ_eL = γ_eR = 0.06676143449267714 # emission rate towards Left and Right lead γ_aL = γ_aR = 0.0737827958503192 # absorption rate towards Left and Right lead d = sigmam() Hs = ϵ * d' * d ## Only local master equation M_me = M_S(Hs; verbose = false) jumpOPs = [γ_eL * d, γ_eR * d, γ_aL * d', γ_aR * d'] M_me = addFermionDissipator(M_me, jumpOPs) # create quantum jump superoperator (only the emission part) J_me = HEOMSuperOp(γ_eR * d, ODD, M_me, "L") * HEOMSuperOp(γ_eR * d', ODD, M_me, "R") @test size(M_me) == size(J_me) @test size(M_me, 1) == size(J_me, 1) @test eltype(M_me) == eltype(J_me) @test nnz(J_me.data) == 1 @test J_me[4, 1] ≈ 0.0044570891355200214 @test J_me.data * 2 ≈ (J_me - (-1) * J_me).data @test J_me.data * 2 ≈ (HEOMSuperOp(√(2) * γ_eR * d, ODD, M_me, "L") * HEOMSuperOp(√(2) * γ_eR * d', ODD, M_me, "R")).data @test show(devnull, MIME("text/plain"), J_me) == nothing # create HEOM Liouvuillian superoperator without quantum jump M0 = M_me - J_me ados_s = steadystate(M_me; verbose = false) ados_list = HEOMsolve(M0, J_me * ados_s, tlist; verbose = false).ados # calculating waiting time distribution WTD_me = [] trJρ = expect(J_me, ados_s) WTD_me = expect(J_me, ados_list) ./ trJρ for i in 1:length(tlist) @test WTD_me[i] ≈ WTD_ans[i] end @test expect(J_me, ados_list[end]) / trJρ ≈ WTD_ans[end] ## Left lead with HEOM method and Right lead with local master equation bath = Fermion_Lorentz_Pade(d, Γ, μ, W, kT, N) jumpOPs = [γ_eR * d, γ_aR * d'] M_heom = M_Fermion(Hs, tier, bath; verbose = false) M_heom = addFermionDissipator(M_heom, jumpOPs) # create quantum jump superoperator (only the emission part) J_heom = HEOMSuperOp(γ_eR * d, ODD, M_heom, "L") * HEOMSuperOp(γ_eR * d', ODD, M_heom, "R") # create HEOM Liouvuillian superoperator without quantum jump M1 = M_heom - J_heom ados_s1 = steadystate(M_heom; verbose = false) ados_list1 = HEOMsolve(M1, J_heom * ados_s1, tlist; verbose = false).ados # calculating waiting time distribution WTD_heom = [] trJρ1 = expect(J_heom, ados_s1) WTD_heom = expect(J_heom, ados_list1) ./ trJρ1 for i in 1:length(tlist) @test WTD_heom[i] ≈ WTD_ans[i] atol = 1e-5 end ## test for ERRORs J_wrong1 = HEOMSuperOp(γ_eR * d, ODD, M_me, "L") J_wrong2 = HEOMSuperOp(γ_eR * d, EVEN, M_heom, "L") @test_throws ErrorException HEOMSuperOp(d, EVEN, M_heom, "LR") @test_throws ErrorException J_me * J_wrong2 @test_throws ErrorException J_me + J_wrong1 @test_throws ErrorException J_me + J_wrong2 @test_throws ErrorException M_me + J_wrong1 @test_throws ErrorException M_me + J_wrong2 @test_throws ErrorException J_me - J_wrong1 @test_throws ErrorException J_me - J_wrong2 @test_throws ErrorException M_me - J_wrong1 @test_throws ErrorException M_me - J_wrong2 end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
2053
@time @testset "M_Boson" begin # Test Boson-type HEOM Liouvillian superoperator matrix λ = 0.1450 W = 0.6464 kT = 0.7414 μ = 0.8787 N = 5 tier = 3 # System Hamiltonian Hsys = Qobj([ 0.6969 0.4364 0.4364 0.3215 ]) # system-bath coupling operator Q = Qobj([ 0.1234 0.1357+0.2468im 0.1357-0.2468im 0.5678 ]) Bbath = Boson_DrudeLorentz_Pade(Q, λ, W, kT, N) # jump operator J = Qobj([0 0.1450-0.7414im; 0.1450+0.7414im 0]) L = M_Boson(Hsys, tier, Bbath; verbose = false) @test show(devnull, MIME("text/plain"), L) === nothing @test size(L) == (336, 336) @test L.N == 84 @test nnz(L.data) == 4422 L = addBosonDissipator(L, J) @test nnz(L.data) == 4760 ados = steadystate(L; verbose = false) @test ados.dims == L.dims @test length(ados) == L.N @test eltype(L) == eltype(ados) ρ0 = ados[1] @test getRho(ados) == ρ0 ρ1 = [ 0.4969521584882579-2.27831302340618e-13im -0.0030829715611090133+0.002534368458048467im -0.0030829715591718203-0.0025343684616701547im 0.5030478415140676+2.3661885315257474e-13im ] @test _is_Matrix_approx(ρ0, ρ1) L = M_Boson(Hsys, tier, [Bbath, Bbath]; verbose = false) @test size(L) == (1820, 1820) @test L.N == 455 @test nnz(L.data) == 27662 L = addBosonDissipator(L, J) @test nnz(L.data) == 29484 ados = steadystate(L; verbose = false) @test ados.dims == L.dims @test length(ados) == L.N ρ0 = ados[1] @test getRho(ados) == ρ0 ρ1 = [ 0.49406682844513267+9.89558173111355e-13im -0.005261234545120281+0.0059968903987593im -0.005261234550122085-0.005996890386139547im 0.5059331715578721-9.413847493320824e-13im ] @test _is_Matrix_approx(ρ0, ρ1) ## check exceptions @test_throws BoundsError L[1, 1821] @test_throws BoundsError L[1:1821, 336] @test_throws ErrorException ados[L.N+1] @test_throws ErrorException M_Boson(Qobj([0, 0]), tier, Bbath; verbose = false) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
2522
@time @testset "M_Boson_Fermion" begin # Test Boson-Fermion-type HEOM Liouvillian superoperator matrix λ = 0.1450 W = 0.6464 kT = 0.7414 μ = 0.8787 N = 3 tierb = 2 tierf = 2 # System Hamiltonian Hsys = Qobj([ 0.6969 0.4364 0.4364 0.3215 ]) # system-bath coupling operator Q = Qobj([ 0.1234 0.1357+0.2468im 0.1357-0.2468im 0.5678 ]) Bbath = Boson_DrudeLorentz_Pade(Q, λ, W, kT, N) Fbath = Fermion_Lorentz_Pade(Q, λ, μ, W, kT, N) # jump operator J = Qobj([0 0.1450-0.7414im; 0.1450+0.7414im 0]) L = M_Boson_Fermion(Hsys, tierb, tierf, Bbath, Fbath; verbose = false) @test show(devnull, MIME("text/plain"), L) === nothing @test size(L) == (2220, 2220) @test L.N == 555 @test nnz(L.data) == 43368 L = addBosonDissipator(L, J) @test nnz(L.data) == 45590 ados = steadystate(L; verbose = false) @test ados.dims == L.dims @test length(ados) == L.N @test eltype(L) == eltype(ados) ρ0 = ados[1] @test getRho(ados) == ρ0 ρ1 = [ 0.496709+4.88415e-12im -0.00324048+0.00286376im -0.00324048-0.00286376im 0.503291-4.91136e-12im ] @test _is_Matrix_approx(ρ0, ρ1) L = M_Boson_Fermion(Hsys, tierb, tierf, [Bbath, Bbath], Fbath; verbose = false) @test size(L) == (6660, 6660) @test L.N == 1665 @test nnz(L.data) == 139210 L = addFermionDissipator(L, J) @test nnz(L.data) == 145872 ados = steadystate(L; verbose = false) @test ados.dims == L.dims @test length(ados) == L.N ρ0 = ados[1] @test getRho(ados) == ρ0 ρ1 = [ 0.493774+6.27624e-13im -0.00536526+0.00651746im -0.00536526-0.00651746im 0.506226-6.15855e-13im ] @test _is_Matrix_approx(ρ0, ρ1) L = M_Boson_Fermion(Hsys, tierb, tierf, Bbath, [Fbath, Fbath]; verbose = false) @test size(L) == (8220, 8220) @test L.N == 2055 @test nnz(L.data) == 167108 L = addBosonDissipator(L, J) @test nnz(L.data) == 175330 ados = steadystate(L; verbose = false) @test ados.dims == L.dims @test length(ados) == L.N ρ0 = ados[1] @test getRho(ados) == ρ0 ρ1 = [ 0.496468-4.32253e-12im -0.00341484+0.00316445im -0.00341484-0.00316445im 0.503532+4.32574e-12im ] @test _is_Matrix_approx(ρ0, ρ1) ## check exceptions @test_throws ErrorException ados[L.N+1] @test_throws ErrorException M_Boson_Fermion(Qobj([0, 0]), tierb, tierf, Bbath, Fbath; verbose = false) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
898
@time @testset "M_Boson (RWA)" begin # Test Boson-type HEOM Liouvillian superoperator matrix under rotating wave approximation ωq = 1.1 Λ = 0.01 Γ = 0.02 tier = 3 Hsys_rwa = 0.5 * ωq * sigmaz() op_rwa = sigmam() ρ0 = ket2dm((basis(2, 0) + basis(2, 1)) / √2) tlist = 0:1:20 d = 1im * √(Λ * (2 * Γ - Λ)) # non-Markov regime B_rwa = BosonBathRWA(op_rwa, [0], [Λ - 1im * ωq], [0.5 * Γ * Λ], [Λ + 1im * ωq]) L = M_Boson(Hsys_rwa, tier, B_rwa; verbose = false) ados_list = HEOMsolve(L, ρ0, tlist; reltol = 1e-10, abstol = 1e-12, verbose = false).ados for (i, t) in enumerate(tlist) ρ_rwa = getRho(ados_list[i]) # analytical result Gt = exp(-1 * (Λ / 2 + 1im * ωq) * t) * (cosh(t * d / 2) + Λ * sinh(t * d / 2) / d) @test ρ_rwa[1, 1] ≈ abs(Gt)^2 * ρ0[1, 1] @test ρ_rwa[1, 2] ≈ Gt * ρ0[1, 2] end end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
2432
@time @testset "M_Fermion" begin # Test Fermion-type HEOM Liouvillian superoperator matrix λ = 0.1450 W = 0.6464 kT = 0.7414 μ = 0.8787 N = 5 tier = 3 # System Hamiltonian Hsys = Qobj([ 0.6969 0.4364 0.4364 0.3215 ]) # system-bath coupling operator Q = Qobj([ 0.1234 0.1357+0.2468im 0.1357-0.2468im 0.5678 ]) Bbath = Boson_DrudeLorentz_Pade(Q, λ, W, kT, N) Fbath = Fermion_Lorentz_Pade(Q, λ, μ, W, kT, N) # jump operator J = Qobj([0 0.1450-0.7414im; 0.1450+0.7414im 0]) L = M_Fermion(Hsys, tier, Fbath; verbose = false) @test show(devnull, MIME("text/plain"), L) === nothing @test size(L) == (1196, 1196) @test L.N == 299 @test nnz(L.data) == 21318 L = addFermionDissipator(L, J) @test nnz(L.data) == 22516 ados = steadystate(L; verbose = false) @test ados.dims == L.dims @test length(ados) == L.N @test eltype(L) == eltype(ados) ρ0 = ados[1] @test getRho(ados) == ρ0 ρ1 = [ 0.49971864340781574+1.5063528845574697e-11im -0.00025004129095353573+0.00028356932981729176im -0.0002500413218393161-0.0002835693203755187im 0.5002813565929579-1.506436545359778e-11im ] @test _is_Matrix_approx(ρ0, ρ1) L = M_Fermion(Hsys, tier, Fbath; threshold = 1e-8, verbose = false) L = addFermionDissipator(L, J) @test size(L) == (148, 148) @test L.N == 37 @test nnz(L.data) == 2054 ados = steadystate(L; verbose = false) ρ2 = ados[1] @test _is_Matrix_approx(ρ2, ρ0.data) L = M_Fermion(Hsys, tier, [Fbath, Fbath]; verbose = false) @test size(L) == (9300, 9300) @test L.N == 2325 @test nnz(L.data) == 174338 L = addFermionDissipator(L, J) @test nnz(L.data) == 183640 ados = steadystate(L; verbose = false) @test ados.dims == L.dims @test length(ados) == L.N ρ0 = ados[1] @test getRho(ados) == ρ0 ρ1 = [ 0.4994229368103249+2.6656157051929377e-12im -0.0005219753638749304+0.0005685093274121244im -0.0005219753958601764-0.0005685092413099392im 0.5005770631903512-2.6376966158390854e-12im ] @test _is_Matrix_approx(ρ0, ρ1) ## check exceptions @test_throws BoundsError L[1, 9301] @test_throws BoundsError L[1:9301, 9300] @test_throws ErrorException ados[L.N+1] @test_throws ErrorException M_Fermion(Qobj([0, 0]), tier, Fbath; verbose = false) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
1368
@time @testset "M_S" begin # Test Schrodinger type HEOM Liouvillian superoperator matrix t = 10 Hsys = sigmax() L = M_S(Hsys; verbose = false) ψ0 = basis(2, 0) @test show(devnull, MIME("text/plain"), L) === nothing @test size(L) == (4, 4) @test L.N == 1 @test nnz(L.data) == 8 ados_list = HEOMsolve(L, ψ0, 0:1:t; reltol = 1e-8, abstol = 1e-10, verbose = false).ados ados = ados_list[end] @test ados.dims == L.dims @test length(ados) == L.N @test eltype(L) == eltype(ados) ρ1 = ados[1] @test getRho(ados) == ρ1 ρ2 = [ cos(t)^2 0.5im*sin(2 * t) -0.5im*sin(2 * t) sin(t)^2 ] @test _is_Matrix_approx(ρ1, ρ2) L = addBosonDissipator(L, √(0.01) * sigmaz()) L = addFermionDissipator(L, √(0.01) * sigmaz()) @test nnz(L.data) == 10 ados_list = HEOMsolve(L, ψ0, 0:0.5:t; reltol = 1e-8, abstol = 1e-10, verbose = false).ados ados = ados_list[end] ρ3 = ados[1] @test getRho(ados) == ρ3 ρ4 = [ 0.6711641119639493+0.0im 0.3735796014268062im -0.3735796014268062im 0.32883588803605024 ] @test _is_Matrix_approx(ρ3, ρ4) ## check exceptions @test_throws BoundsError L[1, 5] @test_throws BoundsError L[1:5, 2] @test_throws ErrorException ados[L.N+1] @test_throws ErrorException M_S(Qobj([0, 0]); verbose = false) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
6014
@time @testset "Bath and Exponent" begin # prepare coupling operator and coefficients of exponential-exponential-expansion terms η0 = [1] γ0 = [2] η1 = [1, 3, 5, 7, 9] η2 = [2, 4, 6, 8, 10] γ1 = [0.1, 0.3, 0.5, 0.3, 0.7] γ2 = [0.1, 0.2, 0.5, 0.6, 0.9] γ3 = [0.1, 0.2 + 0.3im, 0.4 - 0.5im, 0.6 + 0.7im, 0.8 - 0.9im] γ4 = [0.1, 0.2 - 0.3im, 0.4 + 0.5im, 0.6 - 0.7im, 0.8 + 0.9im] op = Qobj([0 0; 0 0]) ################################################ # Boson bath b = BosonBath(op, η1, γ1, combine = false) @test length(b) == 5 ## check for combine b = BosonBath(op, η1, γ1) @test length(b) == 4 ## check for η and γ list, and coupling operator η = [] γ = [] for e in b push!(η, e.η) push!(γ, e.γ) @test e.op == op end @test η == [1.0 + 0.0im, 10.0 + 0.0im, 5.0 + 0.0im, 9.0 + 0.0im] @test γ == [0.1 + 0.0im, 0.3 + 0.0im, 0.5 + 0.0im, 0.7 + 0.0im] ## check for real and image sperarate case bs = BosonBath(op, η1, γ1, η2, γ2, combine = false) @test length(bs) == 10 ## check for combine b = BosonBath(op, η1, γ1, η2, γ2) @test length(b) == 7 @test C(b, [0.183183])[1] ≈ C(bs, [0.183183])[1] ## check for η and γ list, and coupling operator η = [] γ = [] for e in b push!(η, e.η) push!(γ, e.γ) @test e.op == op @test (e.types == "bR") || (e.types == "bI") || (e.types == "bRI") end @test η == [10.0 + 0.0im, 9.0 + 0.0im, 4.0 + 0.0im, 8.0 + 0.0im, 10.0 + 0.0im, 1.0 + 2.0im, 5.0 + 6.0im] @test γ == [0.3 + 0.0im, 0.7 + 0.0im, 0.2 + 0.0im, 0.6 + 0.0im, 0.9 + 0.0im, 0.1 + 0.0im, 0.5 + 0.0im] @test show(devnull, MIME("text/plain"), b) === nothing ## check for exponents @test show(devnull, MIME("text/plain"), b[1]) === nothing @test show(devnull, MIME("text/plain"), b[:]) === nothing @test show(devnull, MIME("text/plain"), b[1:end]) === nothing ## check exceptions @test_throws ErrorException BosonBath(op, [0], [0, 0]) @test_throws ErrorException BosonBath(op, [0, 0], [0, 0], [0], [0, 0]) @test_throws ErrorException BosonBath(op, [0, 0], [0], [0, 0], [0, 0]) @test_throws ErrorException BosonBath(Qobj([0, 0]), [0, 0], [0, 0], [0, 0], [0, 0]) @test_warn "The system-bosonic-bath coupling operator \"op\" should be Hermitian Operator" BosonBath( Qobj([0 1; 0 0]), [0, 0], [0, 0], [0, 0], [0, 0], ) ################################################ ################################################ # Boson bath (RWA) b = BosonBathRWA(op, η1, γ3, η2, γ4) @test length(bs) == 10 cp, cm = C(b, [0.183183]) @test cp[1] ≈ 22.384506765987076 + 0.7399082821797519im @test cm[1] ≈ 26.994911851482776 - 0.799138487523946im ## check for η and γ list, and coupling operator η = [] γ = [] for e in b push!(η, e.η) push!(γ, e.γ) @test e.op == op @test (e.types == "bA") || (e.types == "bE") end @test η == [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] @test γ == [ 0.1, 0.2 + 0.3im, 0.4 - 0.5im, 0.6 + 0.7im, 0.8 - 0.9im, 0.1, 0.2 - 0.3im, 0.4 + 0.5im, 0.6 - 0.7im, 0.8 + 0.9im, ] @test show(devnull, MIME("text/plain"), b) == nothing ## check for exponents @test show(devnull, MIME("text/plain"), b[1]) == nothing @test show(devnull, MIME("text/plain"), b[:]) == nothing @test show(devnull, MIME("text/plain"), b[1:end]) == nothing ## check exceptions @test_throws ErrorException BosonBathRWA(op, [0], [0, 0], [0, 0], [0, 0]) @test_throws ErrorException BosonBathRWA(op, [0, 0], [0], [0, 0], [0, 0]) @test_throws ErrorException BosonBathRWA(op, [0, 0], [0, 0], [0], [0, 0]) @test_throws ErrorException BosonBathRWA(op, [0, 0], [0, 0], [0, 0], [0]) @test_throws ErrorException BosonBathRWA(Qobj([0, 0]), [0, 0], [0, 0], [0, 0], [0, 0]) @test_warn "The elements in \'γ_absorb\' should be complex conjugate of the corresponding elements in \'γ_emit\'." BosonBathRWA( op, [0, 0], [0, 1im], [0, 0], [0, 1im], ) ################################################ ################################################ # Fermion bath b = FermionBath(op, η1, γ3, η2, γ4) @test length(b) == 10 cp, cm = C(b, [0.183183]) @test cp[1] ≈ 22.384506765987076 + 0.7399082821797519im @test cm[1] ≈ 26.994911851482776 - 0.799138487523946im for e in b @test e.op == op @test (e.types == "fA") || (e.types == "fE") end @test show(devnull, MIME("text/plain"), b) === nothing ## check for exponents @test show(devnull, MIME("text/plain"), b[1]) === nothing @test show(devnull, MIME("text/plain"), b[:]) === nothing @test show(devnull, MIME("text/plain"), b[1:end]) === nothing ## check exceptions @test_throws ErrorException FermionBath(op, [0], [0, 0], [0, 0], [0, 0]) @test_throws ErrorException FermionBath(op, [0, 0], [0], [0, 0], [0, 0]) @test_throws ErrorException FermionBath(op, [0, 0], [0, 0], [0], [0, 0]) @test_throws ErrorException FermionBath(op, [0, 0], [0, 0], [0, 0], [0]) @test_throws ErrorException FermionBath(Qobj([0, 0]), [0, 0], [0, 0], [0, 0], [0, 0]) @test_warn "The elements in \'γ_absorb\' should be complex conjugate of the corresponding elements in \'γ_emit\'." FermionBath( op, [0, 0], [0, 1im], [0, 0], [0, 1im], ) ################################################ ################################################ # Exponent @test C(BosonBath(op, η0, γ0), [0.123])[1] ≈ η0[1] * exp(-γ0[1] * 0.123) ## check exceptions @test_throws ErrorException b[11] @test_throws ErrorException b[1:11] @test_throws ErrorException b[0:10] ################################################ end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
3492
@time @testset "Bath correlation functions" begin λ = 0.1450 W = 0.6464 kT = 0.7414 μ = 0.8787 N = 4 op = Qobj([0 0; 0 0]) # Boson DrudeLorentz Matsubara b = Boson_DrudeLorentz_Matsubara(op, λ, W, kT, N) η = [ 0.20121058848333528 - 0.09372799999999999im, 0.06084056770606083 + 0.0im, 0.029978857835967165 + 0.0im, 0.019932342919420813 + 0.0im, 0.014935247906482648 + 0.0im, ] γ = [ 0.6464 + 0.0im, 4.658353586742945 + 0.0im, 9.31670717348589 + 0.0im, 13.975060760228835 + 0.0im, 18.63341434697178 + 0.0im, ] @test length(b) == 5 for (i, e) in enumerate(b) @test e.η ≈ η[i] atol = 1.0e-10 @test e.γ ≈ γ[i] atol = 1.0e-10 end # Boson DrudeLorentz Pade b = Boson_DrudeLorentz_Pade(op, λ, W, kT, N) η = [ 0.20121058848333528 - 0.09372799999999999im, 0.060840591418808695 + 0.0im, 0.03040476731148852 + 0.0im, 0.03480693463462283 + 0.0im, 0.11731872688143469 + 0.0im, ] γ = [ 0.6464 + 0.0im, 4.658353694331594 + 0.0im, 9.326775214941103 + 0.0im, 15.245109836566387 + 0.0im, 42.84397872069647 + 0.0im, ] @test length(b) == 5 for (i, e) in enumerate(b) @test e.η ≈ η[i] atol = 1.0e-10 @test e.γ ≈ γ[i] atol = 1.0e-10 end # Fermion Lorentz Matsubara b = Fermion_Lorentz_Matsubara(op, λ, μ, W, kT, N) η = [ 0.023431999999999998 - 0.010915103984112131im, 0.0 + 0.008970684904033346im, 0.0 + 0.0009279154410418598im, 0.0 + 0.0003322143470478503im, 0.0 + 0.00016924095164942202im, 0.023431999999999998 - 0.010915103984112131im, 0.0 + 0.008970684904033346im, 0.0 + 0.0009279154410418598im, 0.0 + 0.0003322143470478503im, 0.0 + 0.00016924095164942202im, ] γ = [ 0.6464 - 0.8787im, 2.3291767933714724 - 0.8787im, 6.987530380114418 - 0.8787im, 11.645883966857362 - 0.8787im, 16.304237553600306 - 0.8787im, 0.6464 + 0.8787im, 2.3291767933714724 + 0.8787im, 6.987530380114418 + 0.8787im, 11.645883966857362 + 0.8787im, 16.304237553600306 + 0.8787im, ] @test length(b) == 10 for (i, e) in enumerate(b) @test e.η ≈ η[i] atol = 1.0e-10 @test e.γ ≈ γ[i] atol = 1.0e-10 end # Fermion Lorentz Pade b = Fermion_Lorentz_Pade(op, λ, μ, W, kT, N) η = [ 0.023431999999999998 - 0.01091510398411206im, 0.0 + 0.008970684906245254im, 0.0 + 0.0009302651094118784im, 0.0 + 0.0004641563759947782im, 0.0 + 0.0005499975924601513im, 0.023431999999999998 - 0.01091510398411206im, 0.0 + 0.008970684906245254im, 0.0 + 0.0009302651094118784im, 0.0 + 0.0004641563759947782im, 0.0 + 0.0005499975924601513im, ] γ = [ 0.6464 - 0.8787im, 2.329176793410983 - 0.8787im, 6.988999607574685 - 0.8787im, 12.311922289624265 - 0.8787im, 34.341283736701214 - 0.8787im, 0.6464 + 0.8787im, 2.329176793410983 + 0.8787im, 6.988999607574685 + 0.8787im, 12.311922289624265 + 0.8787im, 34.341283736701214 + 0.8787im, ] @test length(b) == 10 for (i, e) in enumerate(b) @test e.η ≈ η[i] atol = 1.0e-10 @test e.γ ≈ γ[i] atol = 1.0e-10 end end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
314
import Aqua import JET @testset "Code quality" verbose = true begin @testset "Aqua.jl" begin Aqua.test_all(HierarchicalEOM; ambiguities = false) end @testset "JET.jl" begin JET.test_package(HierarchicalEOM; target_defined_modules = true, ignore_missing_comparison = true) end end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
2927
@time @testset "Density of states" begin e = -5 U = 10 d_up = tensor(sigmam(), qeye(2)) d_dn = tensor(-1 * sigmaz(), sigmam()) iden = tensor(qeye(2), qeye(2)) H0 = e * (d_up' * d_up + d_dn' * d_dn) H1 = U * (d_up' * d_up * d_dn' * d_dn) Hsys = H0 + H1 λ = 1 μ_l = 1 μ_r = -1 W = 10 kT = 0.5 N = 5 fuL = Fermion_Lorentz_Pade(d_up, λ, μ_l, W, kT, N) fdL = Fermion_Lorentz_Pade(d_dn, λ, μ_l, W, kT, N) fuR = Fermion_Lorentz_Pade(d_up, λ, μ_r, W, kT, N) fdR = Fermion_Lorentz_Pade(d_dn, λ, μ_r, W, kT, N) tier = 2 Le = M_Fermion(Hsys, tier, [fuL, fdL, fuR, fdR]; verbose = false) Lo = M_Fermion(Hsys, tier, [fuL, fdL, fuR, fdR], ODD; verbose = false) ados_s = steadystate(Le; verbose = false) ωlist = -20:2:20 if isfile("DOS.txt") rm("DOS.txt") end d_up_normal = HEOMSuperOp(d_up, ODD, Le) dos1 = DensityOfStates(Lo, ados_s, d_up, ωlist; verbose = false, filename = "DOS") dos2 = PowerSpectrum(Lo, ados_s, d_up_normal, d_up', ωlist, true; verbose = false) .+ PowerSpectrum(Lo, ados_s, d_up', d_up_normal, ωlist, false; verbose = false) dos3 = [ 0.0007920428534358747, 0.0012795202828027256, 0.0022148985361417936, 0.004203651086852703, 0.009091831276694192, 0.024145570990254425, 0.09111929563034224, 0.2984323182857298, 0.1495897397559431, 0.12433521300531171, 0.17217519700362036, 0.1243352130053117, 0.14958973975594306, 0.29843231828572964, 0.09111929563034214, 0.024145570990254432, 0.009091831276694183, 0.004203651086852702, 0.0022148985361417923, 0.0012795202828027236, 0.0007920428534358735, ] for i in 1:length(ωlist) @test dos1[i] ≈ dos3[i] atol = 1.0e-10 @test dos2[i] ≈ dos3[i] atol = 1.0e-10 end @test length(readlines("DOS.txt")) == length(ωlist) mat = Qobj(spzeros(ComplexF64, 2, 2)) mat2 = Qobj(spzeros(ComplexF64, 3, 3)) bathb = Boson_DrudeLorentz_Pade(mat, 1, 1, 1, 2) @test_throws ErrorException DensityOfStates(Lo, ados_s, d_up, ωlist; verbose = false, filename = "DOS") @test_throws ErrorException DensityOfStates(Lo, ados_s, mat2, ωlist; verbose = false) @test_throws ErrorException DensityOfStates(Lo, ADOs(zeros(8), 2), d_up, ωlist; verbose = false) @test_throws ErrorException DensityOfStates(Lo, ADOs(zeros(32), 2), d_up, ωlist; verbose = false) @test_throws ErrorException DensityOfStates(Lo, ADOs(ados_s.data, ados_s.N, ODD), d_up, ωlist; verbose = false) @test_throws ErrorException DensityOfStates(M_Boson(mat, 2, bathb; verbose = false), mat, mat, [0]) @test_throws ErrorException DensityOfStates(M_Fermion(mat, 2, fuL; verbose = false), mat, mat, [0]) # remove all the temporary files rm("DOS.txt") end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
1183
@time @testset "Hierarchy Dictionary" begin Btier = 2 Ftier = 2 Nb = 3 Nf = 3 threshold = 1e-5 Γ = 0.0025 Dα = 30 Λ = 0.0025 ωcα = 0.2 μL = 0.5 μR = -0.5 kT = 0.025 Hsys = Qobj([ 0 0 0 0 0 0.2 0 0 0 0 0.208 0.04 0 0 0.04 0.408 ]) cop = Qobj([ 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1 0 ]) dop = Qobj([ 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 ]) bbath = Boson_DrudeLorentz_Matsubara(cop, Λ, ωcα, kT, Nb) fbath = [Fermion_Lorentz_Pade(dop, Γ, μL, Dα, kT, Nf), Fermion_Lorentz_Pade(dop, Γ, μR, Dα, kT, Nf)] L = M_Boson_Fermion(Hsys, Btier, Ftier, bbath, fbath; threshold = threshold, verbose = false) L = addTerminator(L, bbath) @test size(L) == (1696, 1696) @test L.N == 106 @test nnz(L.data) == 13536 ados = steadystate(L; verbose = false) @test Ic(ados, L, 1) ≈ 0.2883390125832726 nvec_b, nvec_f = L.hierarchy.idx2nvec[1] @test_throws ErrorException getIndexEnsemble(nvec_f, L.hierarchy.bosonPtr) @test_throws ErrorException getIndexEnsemble(nvec_b, L.hierarchy.fermionPtr) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
1943
@time @testset "Power spectrum" begin a = destroy(2) Hsys = a' * a λ = 1e-4 W = 2e-1 kT = 0.5 N = 5 bath = Boson_DrudeLorentz_Matsubara((a' + a), λ, W, kT, N) tier = 3 L = M_Boson(Hsys, tier, bath; verbose = false) L = addBosonDissipator(L, 1e-3 * a') L = addTerminator(L, bath) ados_s = steadystate(L; verbose = false) ωlist = 0.9:0.01:1.1 if isfile("PSD.txt") rm("PSD.txt") end psd1 = PowerSpectrum(L, ados_s, a, ωlist; verbose = false, filename = "PSD") psd2 = [ 8.88036729e-04, 1.06145358e-03, 1.30081318e-03, 1.64528197e-03, 2.16857171e-03, 3.02352743e-03, 4.57224555e-03, 7.85856353e-03, 1.70441286e-02, 6.49071303e-02, 1.64934976e+02, 6.60426108e-02, 1.57205620e-02, 6.74130995e-03, 3.67130512e-03, 2.27825666e-03, 1.53535649e-03, 1.09529424e-03, 8.14605980e-04, 6.25453434e-04, 4.92451868e-04, ] for i in 1:length(ωlist) @test psd1[i] ≈ psd2[i] atol = 1.0e-6 end @test length(readlines("PSD.txt")) == length(ωlist) mat = Qobj(spzeros(ComplexF64, 2, 2)) mat2 = Qobj(spzeros(ComplexF64, 3, 3)) a_even = HEOMSuperOp(a, EVEN, L) a_odd = HEOMSuperOp(a, ODD, L) bathf = Fermion_Lorentz_Pade(mat, 1, 1, 1, 1, 2) @test_throws ErrorException PowerSpectrum(L, ados_s, a, ωlist; verbose = false, filename = "PSD") @test_throws ErrorException PowerSpectrum(L, ados_s, a_even, a_odd, ωlist; verbose = false) @test_throws ErrorException PowerSpectrum(L, ados_s, mat2, ωlist; verbose = false) @test_throws ErrorException PowerSpectrum(L, ADOs(zeros(8), 2), a, ωlist; verbose = false) @test_throws ErrorException PowerSpectrum(L, ADOs(zeros(32), 2), a, ωlist; verbose = false) # remove all the temporary files rm("PSD.txt") end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
1038
using Pkg using Test using HierarchicalEOM import JLD2: jldopen const GROUP = get(ENV, "GROUP", "All") const testdir = dirname(@__FILE__) include("test_utils.jl") # Put Core tests in alphabetical order core_tests = [ "ADOs.jl", "bath.jl", "bath_corr_func.jl", "density_of_states.jl", "HEOMSuperOp.jl", "hierarchy_dictionary.jl", "M_Boson.jl", "M_Boson_Fermion.jl", "M_Boson_RWA.jl", "M_Fermion.jl", "M_S.jl", "power_spectrum.jl", "stationary_state.jl", "time_evolution.jl", ] if (GROUP == "All") || (GROUP == "Code_Quality") Pkg.add(["Aqua", "JET"]) HierarchicalEOM.versioninfo() include(joinpath(testdir, "code_quality.jl")) end if (GROUP == "All") || (GROUP == "Core") GROUP == "All" ? nothing : HierarchicalEOM.versioninfo() for test in core_tests include(joinpath(testdir, test)) end end if (GROUP == "CUDA_Ext")# || (GROUP == "All") Pkg.add("CUDA") HierarchicalEOM.versioninfo() include(joinpath(testdir, "CUDAExt.jl")) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
1453
@time @testset "Stationary state" begin # System Hamiltonian and initial state d = sigmam() Hsys = d' * d ψ0 = basis(2, 0) # Bath properties: Γ = 1.0 W = 1 kT = 0.025851991 μL = 1.0 μR = -1.0 N = 3 baths = [Fermion_Lorentz_Pade(d, Γ, μL, W, kT, N), Fermion_Lorentz_Pade(d, Γ, μR, W, kT, N)] # HEOM Liouvillian superoperator matrix tier = 5 L = M_Fermion(Hsys, tier, baths; verbose = false) ados = steadystate(L, ψ0; verbose = false) ρs = getRho(ados) O = qeye(2) + 0.5 * sigmax() @test expect(O, ados) ≈ real(tr(O * ρs)) @test expect(O, ados, take_real = false) ≈ tr(O * ρs) ρ1 = getRho(steadystate(L; verbose = false)) @test isapprox(ρ1, ρs, atol = 1e-6) mat = Qobj(spzeros(ComplexF64, 2, 2)) mat2 = Qobj(spzeros(ComplexF64, 3, 3)) bathf = Fermion_Lorentz_Pade(mat, 1, 1, 1, 1, 2) @test_throws ErrorException SteadyState(L) @test_throws ErrorException SteadyState(L, ψ0) @test_throws ErrorException steadystate(M_Fermion(mat, 2, bathf, ODD; verbose = false)) @test_throws ErrorException steadystate(M_Fermion(mat, 2, bathf, ODD; verbose = false), mat) @test_throws ErrorException steadystate(L, mat2) @test_throws ErrorException steadystate(L, ADOs(zeros(8), 2)) @test_throws ErrorException steadystate(L, ADOs(ados.data, ados.N, ODD)) @test_throws ErrorException steadystate(L, HEOMSuperOp(d, ODD, L) * ados) end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
1469
function _is_Matrix_approx(M1::QuantumObject, M2; atol = 1.0e-6) s1 = size(M1) s2 = size(M2) if s1 == s2 if !isapprox(M1.data, M2, atol = atol) return false end return true else return false end end # calculate current for a given ADOs # bathIdx: 1 means 1st fermion bath (bath_L); 2 means 2nd fermion bath (bath_R) function Ic(ados, M::M_Boson_Fermion, bathIdx::Int) # the hierarchy dictionary HDict = M.hierarchy # we need all the indices of ADOs for the first level idx_list = HDict.Flvl2idx[1] I = 0.0im for idx in idx_list ρ1 = ados[idx] # 1st-level ADO # find the corresponding bath index (α) and exponent term index (k) nvec_b, nvec_f = HDict.idx2nvec[idx] if nvec_b.level == 0 for (α, k, _) in getIndexEnsemble(nvec_f, HDict.fermionPtr) if α == bathIdx exponent = M.Fbath[α][k] if exponent.types == "fA" # fermion-absorption I += tr(exponent.op' * ρ1) elseif exponent.types == "fE" # fermion-emission I -= tr(exponent.op' * ρ1) end break end end end end eV_to_Joule = 1.60218E-19 # unit conversion # (e / ħ) * I [change unit to μA] return 1.519270639695384E15 * real(1im * I) * eV_to_Joule * 1E6 end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
code
9416
@time @testset "Time evolution" begin # System Hamiltonian and initial state Hsys = 0.25 * sigmaz() + 0.5 * sigmax() ψ0 = basis(2, 0) # Bath properties: λ = 0.1 W = 0.5 kT = 0.5 N = 2 tier = 5 Q = sigmaz() # System-bath coupling operator e_ops = [rand_dm(2), rand_dm(2)] bath = Boson_DrudeLorentz_Pade(Q, λ, W, kT, N) L = M_Boson(Hsys, tier, bath; verbose = false) ρs = getRho(steadystate(L; verbose = false)) ρ_wrong = Qobj(zeros(3, 3)) Δt = 10 steps = 10 tlist = 0:Δt:(Δt*steps) if isfile("evolution_p.jld2") rm("evolution_p.jld2") end # using the method based on propagator ados_list = HEOMsolve(L, ψ0, Δt, steps; verbose = false, filename = "evolution_p").ados sol_p = HEOMsolve(L, ψ0, Δt, steps; e_ops = e_ops, verbose = false) expvals_p = sol_p.expect ados_wrong1 = ADOs(zeros(8), 2) ados_wrong2 = ADOs(zeros(32), 2) ados_wrong3 = ADOs((ados_list[1]).data, (ados_list[1]).N, ODD) ados_wrong4 = HEOMSuperOp(Q, ODD, ados_list[end]) * ados_list[end] ρ_list_p = getRho.(ados_list) @test show(devnull, MIME("text/plain"), sol_p) === nothing @test length(sol_p.ados) == 1 @test_throws ErrorException evolution(L, ψ0, Δt, steps; verbose = false) @test_throws ErrorException HEOMsolve(L, ψ0, Δt, steps; verbose = false, filename = "evolution_p") @test_throws ErrorException HEOMsolve(L, ρ_wrong, Δt, steps; verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong1, Δt, steps; verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong2, Δt, steps; verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong3, Δt, steps; verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong4, Δt, steps; verbose = false) if isfile("evolution_o.jld2") rm("evolution_o.jld2") end # using the method based on ODE solver sol_e = HEOMsolve(L, ψ0, tlist; e_ops = e_ops, saveat = tlist, verbose = false, filename = "evolution_o") ρ_list_e = getRho.(sol_e.ados) expvals_e = sol_e.expect @test show(devnull, MIME("text/plain"), sol_e) === nothing @test_throws ErrorException evolution(L, ψ0, tlist; verbose = false) @test_throws ErrorException HEOMsolve(L, ψ0, tlist; verbose = false, filename = "evolution_o") @test_throws ErrorException HEOMsolve(L, ρ_wrong, tlist; verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong1, tlist; verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong2, tlist; verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong3, tlist; verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong4, tlist; verbose = false) @test all(expvals_p .≈ expvals_e) @test all([ρ_list_p[i] ≈ ρ_list_e[i] for i in 1:(steps+1)]) @test isapprox(ρs, ρ_list_p[end]; atol = 1e-4) @test isapprox(ρs, ρ_list_e[end]; atol = 1e-4) @test isapprox(ρs, getRho(sol_p.ados[1]); atol = 1e-4) jldopen("evolution_p.jld2", "r") do file ados_list = file["ados"] @test typeof(ados_list) == Vector{ADOs} @test length(ados_list) == steps + 1 @test all([ρ_list_p[i] ≈ getRho(ados_list[i]) for i in 1:(steps+1)]) end jldopen("evolution_o.jld2", "r") do file ados_list = file["ados"] @test typeof(ados_list) == Vector{ADOs} @test length(ados_list) == steps + 1 @test all([ρ_list_e[i] ≈ getRho(ados_list[i]) for i in 1:(steps+1)]) end # time-dependent Hamiltonian σz = sigmaz() P01 = basis(2, 0) * basis(2, 1)' H_sys = 0 * σz ψ0 = (basis(2, 0) + basis(2, 1)) / √2 bath = Boson_DrudeLorentz_Pade(σz, 0.0005, 0.005, 0.05, 3) L = M_Boson(H_sys, 6, bath; verbose = false) function Ht(t, p) duration = p.integral / p.amplitude period = duration + p.delay t = t % period if t < duration return p.amplitude * sigmax() else return Qobj([0 0; 0 0]) end end tlist = 0:10:400 if isfile("evolution_t.jld2") rm("evolution_t.jld2") end p_fast = (amplitude = 0.5, delay = 20, integral = π / 2) fastDD_sol = HEOMsolve( L, ψ0, tlist; H_t = Ht, params = p_fast, e_ops = [P01], saveat = tlist, reltol = 1e-12, abstol = 1e-12, verbose = false, filename = "evolution_t", ) fastDD_ados = fastDD_sol.ados fastDD1 = real.(fastDD_sol.expect[1, :]) fastDD2 = expect(P01, fastDD_ados) jldopen("evolution_t.jld2", "r") do file ados_list = file["ados"] @test typeof(ados_list) == Vector{ADOs} @test length(ados_list) == length(tlist) end @test_throws ErrorException HEOMsolve( L, ψ0, tlist; H_t = Ht, params = p_fast, verbose = false, filename = "evolution_t", ) @test_throws ErrorException HEOMsolve(L, ρ_wrong, tlist; H_t = Ht, verbose = false) fastBoFiN = [ 0.4999999999999999, 0.4972948770876402, 0.48575366430956535, 0.48623357850926063, 0.4953126026707093, 0.4956964571136953, 0.4920357760578866, 0.4791950252661603, 0.4892461036798634, 0.4928465660900118, 0.4924652444726348, 0.48681317030861687, 0.4810852414658711, 0.4895850463738865, 0.4883063278114976, 0.4891347504183582, 0.4812529995344225, 0.48397690318479186, 0.48766721173648925, 0.4863478506723415, 0.4853757629933787, 0.47619727575597826, 0.4846116525810951, 0.4838281128868905, 0.4847126978506697, 0.4809571657303493, 0.47862209473563255, 0.4832775448598134, 0.4795481060217657, 0.48232522269103417, 0.47572829624493995, 0.47970784844818903, 0.48020739013048824, 0.47927809262397914, 0.47904939060891494, 0.4728486106129371, 0.47901940281020244, 0.4755943953129941, 0.47816314189739584, 0.47479965067847246, 0.47451220871416044, ] @test show(devnull, MIME("text/plain"), fastDD_sol) === nothing @test length(fastDD_sol.ados) == length(tlist) @test size(fastDD_sol.expect) == (1, length(tlist)) @test typeof(fastDD1) == typeof(fastDD2) == Vector{Float64} @test all(isapprox.(fastDD1, fastBoFiN; atol = 1.0e-6)) @test all(isapprox.(fastDD2, fastBoFiN; atol = 1.0e-6)) p_slow = (amplitude = 0.01, delay = 20, integral = π / 2) slowDD_sol = HEOMsolve( L, ψ0, tlist; H_t = Ht, params = p_slow, e_ops = [P01], saveat = tlist, reltol = 1e-12, abstol = 1e-12, verbose = false, ) slowDD_ados = slowDD_sol.ados slowDD1 = slowDD_sol.expect[1, :] slowDD2 = expect(P01, slowDD_ados; take_real = false) slowBoFiN = [ 0.4999999999999999, 0.4949826158957288, 0.4808740017602084, 0.4593383302633091, 0.43252194834417496, 0.402802685601788, 0.3725210685299983, 0.34375397372926303, 0.3181509506463072, 0.29684111346956915, 0.2804084225914882, 0.26892558062398203, 0.26203207044640237, 0.2590399640129812, 0.25905156533518636, 0.26107507001114955, 0.2639313319708524, 0.26368823254606255, 0.25936367828335455, 0.25399924039230276, 0.2487144584444748, 0.24360738475043517, 0.23875449658047362, 0.23419406109247376, 0.2299206674661969, 0.22588932666421335, 0.22202631685357516, 0.2182434870635807, 0.21445292381955944, 0.210579531547926, 0.20656995199483505, 0.20239715154725021, 0.19806079107370503, 0.19358407389379975, 0.18856981068448642, 0.18126256908840252, 0.17215645949526584, 0.16328689667616822, 0.1552186906255167, 0.14821389956195355, 0.14240802098404504, ] @test show(devnull, MIME("text/plain"), slowDD_sol) === nothing @test length(slowDD_sol.ados) == length(tlist) @test size(slowDD_sol.expect) == (1, length(tlist)) @test typeof(slowDD1) == typeof(slowDD2) == Vector{ComplexF64} @test all(isapprox.(slowDD1, slowBoFiN; atol = 1.0e-6)) @test all(isapprox.(slowDD2, slowBoFiN; atol = 1.0e-6)) H_wrong1(t, p) = Qobj(zeros(3, 3)) H_wrong2(t, p) = t == 0 ? Qobj(zeros(2, 2)) : Qobj(zeros(3, 3)) ados_wrong1 = ADOs(zeros(8), 2) ados_wrong2 = ADOs(zeros(32), 2) ados_wrong3 = ADOs((slowDD_ados[1]).data, (slowDD_ados[1]).N, ODD) @test_throws ErrorException HEOMsolve(L, ψ0, tlist; H_t = H_wrong1, verbose = false) @test_throws ErrorException HEOMsolve(L, ψ0, tlist; H_t = H_wrong2, verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong1, tlist; H_t = Ht, verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong2, tlist; H_t = Ht, verbose = false) @test_throws ErrorException HEOMsolve(L, ados_wrong3, tlist; H_t = Ht, verbose = false) # remove all the temporary files rm("evolution_p.jld2") rm("evolution_o.jld2") rm("evolution_t.jld2") end
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
2036
# Contributor Covenant Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct 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. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the Contributor Covenant , version 1.2.0, available at https://www.contributor-covenant.org/version/1/2/0/code-of-conduct.html [homepage]: https://contributor-covenant.org [version]: https://contributor-covenant.org/version/1/2/
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
4422
![Fancy logo](./docs/src/assets/logo-dark.png#gh-dark-mode-only) ![Fancy logo](./docs/src/assets/logo.png#gh-light-mode-only) # HierarchicalEOM.jl | **Release** | [![Release][release-img]][release-url] [![License][license-img]][license-url] [![arXiv][arxiv-img]][arxiv-url] | |:-----------------:|:-------------| | **Runtests** | [![Runtests][runtests-img]][runtests-url] [![Coverage][codecov-img]][codecov-url] [![Aqua QA][aqua-img]][aqua-url] [![JET][jet-img]][jet-url] | | **Documentation** | [![Doc-Stable][docs-stable-img]][docs-stable-url] [![Doc-Dev][docs-develop-img]][docs-develop-url] | [release-img]: https://img.shields.io/github/release/qutip/HierarchicalEOM.jl.svg [release-url]: https://github.com/qutip/HierarchicalEOM.jl/releases [license-img]: https://img.shields.io/badge/License-Apache%202.0-blue.svg [license-url]: https://opensource.org/licenses/Apache-2.0 [arxiv-img]: https://img.shields.io/badge/arXiv-2306.07522-<COLOR>.svg [arxiv-url]: https://arxiv.org/abs/2306.07522 [runtests-img]: https://github.com/qutip/HierarchicalEOM.jl/actions/workflows/Runtests.yml/badge.svg [runtests-url]: https://github.com/qutip/HierarchicalEOM.jl/actions/workflows/Runtests.yml [codecov-img]: https://codecov.io/gh/qutip/HierarchicalEOM.jl/graph/badge.svg?token=ICFVVNuLHW [codecov-url]: https://codecov.io/gh/qutip/HierarchicalEOM.jl [aqua-img]: https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg [aqua-url]: https://github.com/JuliaTesting/Aqua.jl [jet-img]: https://img.shields.io/badge/%F0%9F%9B%A9%EF%B8%8F_tested_with-JET.jl-233f9a [jet-url]: https://github.com/aviatesk/JET.jl [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://qutip.org/HierarchicalEOM.jl/stable/ [docs-develop-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-develop-url]: https://qutip.org/HierarchicalEOM.jl/dev/ `HierarchicalEOM.jl` is a numerical framework written in [`Julia`](https://julialang.org/). It provides a user-friendly and efficient tool based on hierarchical equations of motion (HEOM) approach to simulate complex open quantum systems, including non-Markovian effects due to non-perturbative interaction with one (or multiple) environment(s). It is built upon [`QuantumToolbox.jl`](https://github.com/qutip/QuantumToolbox.jl). ![](./docs/src/assets/heom_ecosystem.jpeg) ## Installation > **_NOTE:_** `HierarchicalEOM.jl` requires `Julia 1.10+`. To install `HierarchicalEOM.jl`, run the following commands inside Julia's interactive session (also known as REPL): ```julia using Pkg Pkg.add("HierarchicalEOM") ``` Alternatively, this can also be done in Julia's [Pkg REPL](https://julialang.github.io/Pkg.jl/v1/getting-started/) by pressing the key `]` in the REPL to use the package mode, and then type the following command: ```julia-REPL (1.10) pkg> add HierarchicalEOM ``` More information about `Julia`'s package manager can be found at [`Pkg.jl`](https://julialang.github.io/Pkg.jl/v1/). To load the package and check the version information, use the command: ```julia julia> using HierarchicalEOM julia> HierarchicalEOM.versioninfo() ``` ## Documentation The documentation can be found in : - [**STABLE**](https://qutip.org/HierarchicalEOM.jl/stable) : most recently tagged version. - [**DEVELOP**](https://qutip.org/HierarchicalEOM.jl/dev/) : in-development version. ## Cite `HierarchicalEOM.jl` If you like `HierarchicalEOM.jl`, we would appreciate it if you starred the repository in order to help us increase its visibility. Furthermore, if you find the framework useful in your research, we would be grateful if you could cite our publication [ [Commun. Phys. 6, 313 (2023)](https://doi.org/10.1038/s42005-023-01427-2) ] using the following bibtex entry: ```bib @article{HierarchicalEOM-jl2023, doi = {10.1038/s42005-023-01427-2}, url = {https://doi.org/10.1038/s42005-023-01427-2}, year = {2023}, month = {Oct}, publisher = {Nature Portfolio}, volume = {6}, number = {1}, pages = {313}, author = {Huang, Yi-Te and Kuo, Po-Chen and Lambert, Neill and Cirio, Mauro and Cross, Simon and Yang, Shen-Liang and Nori, Franco and Chen, Yueh-Nan}, title = {An efficient {J}ulia framework for hierarchical equations of motion in open quantum systems}, journal = {Communications Physics} } ``` ## License `HierarchicalEOM.jl` is released under the [BSD 3-Clause License](./LICENSE.md).
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
827
# How to build documentation locally ? ## Working Directory All the commands should be run under the root folder of the package: `/path/to/HierarchicalEOM.jl/` The document pages will be generated in the directory: `/path/to/HierarchicalEOM.jl/docs/build/` (which is ignored by git). ## Method 1: Run with `make` command Run the following command: ```shell make docs ``` ## Method 2: Run `julia` command manually ### Build Pkg Run the following command: ```shell julia --project=docs -e 'using Pkg; Pkg.develop(PackageSpec(path=pwd())); Pkg.instantiate()' ``` > **_NOTE:_** `Pkg.develop(PackageSpec(path=pwd()))` adds the local version of `HierarchicalEOM` as dev-dependency instead of pulling from the registered version. ### Build Documentation Run the following command: ```shell julia --project=docs docs/make.jl ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
4858
# [Auxiliary Density Operators](@id doc-ADOs) ## Introduction The auxiliary density operators ([`ADOs`](@ref)) ``\rho_{\textbf{j}\vert\textbf{q}}^{(m,n,p)}(t)`` encode environmental effects related to different exponential terms ([`Exponent`](@ref)) present in the [`Bosonic Bath`](@ref doc-Bosonic-Bath) and [`Fermionic Bath`](@ref doc-Fermionic-Bath) correlation functions and provide an iterative description of high-order system-baths memory effects. In ``\rho_{\textbf{j}\vert\textbf{q}}^{(m,n,p)}(t)``, the tuple ``(m, n, p)`` represents the ``m``th-level-bosonic-and-``n``th-level-fermionic ADO with parity ``p``, and ``\textbf{j}`` (``\textbf{q}``) denotes a vector ``[j_m,\cdots,j_1]`` (``[q_n,\cdots,q_1]``) where each ``j`` (``q``) represents a specific multi-index ensemble ``\{\beta, l\}`` (``\{\alpha, h\}``) with - ``\beta`` : denotes the index of bosonic bath - ``\alpha`` : denotes the index of fermionic bath - ``l`` : denotes the index of exponent in the bosonic bath - ``h`` : denotes the index of exponent in the fermionic bath !!! note "Reduced Density Operator" The system reduced density operator refers to ``m=n=0``, namely ``\rho_{\vert}^{(0,0,p)}(t)``. In `HierarchicalEOM.jl`, we express all the auxiliary density operators into a single column vector and store it in the object defined as : [`struct ADOs`](@ref ADOs), which is usually obtained after solving the [time evolution](@ref doc-Time-Evolution) or [stationary state](@ref doc-Stationary-State) by a given [HEOM Liouvillian superoperator Matrix](@ref doc-HEOMLS-Matrix). ## Fields The fields of the structure [`ADOs`](@ref) are as follows: - `data` : the vectorized auxiliary density operators - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of auxiliary density operators - `parity`: the [parity](@ref doc-Parity) label One obtain the value of each fields as follows: ```julia # usually obtained after solving time evolution or stationary state ados::ADOs ados.data ados.dims ados.N ados.parity ``` !!! warning "Warning" We express all the auxiliary density operators in only a single column vector `ADOs.data`. To obtain each auxiliary density operators in matrix form, please use the following methods and functions. ## Reduced Density Operator In order to obtain the system reduced density operator in the type of `QuantumObject`, just simply call [`getRho`](@ref) ```julia ados::ADOs ρ = getRho(ados) ``` ## High-Level Auxiliary Density Operators Although we express all the auxiliary density operators in the vector `ADOs.data`, we still make the [`ADOs`](@ref) like a list where accessing each element would return a specific auxiliary density operator in matrix type. In order to obtain the auxiliary density operator in the type of `QuantumObject` with a specific index `i`, just simply call [`getADO`](@ref) ```julia ados::ADOs i::Int ρ = getADO(ados, 1) # the first element will always be the reduced density operator ado = getADO(ados, i) # the i-th auxiliary density operator ``` Also, [`ADOs`](@ref) supports all the element-wise methods (functions) : Supports `length(::ADOs)` which returns the total number of auxiliary density operators (same as `ADOs.N`) : ```julia ados::ADOs length(ados) ``` Supports bracket operation `[]` which is similar to access the element of a list : ```julia ados::ADOs # all the following returned ADO will be in matrix form ados[1] # returns the first auxiliary density operator (which is always the reduced density operator) ados[10] # returns the 10-th auxiliary density operator ados[3:10] # returns a list of auxiliary density operators from index 3 to 10 ados[end] # returns the last auxiliary density operator ``` Supports iteration (`for`-loop) process : ```julia ados::ADOs for ado in ados # iteration ado # each auxiliary density operator in matrix form end ``` !!! note "Work on high-level auxiliary density operators with Hierarchy Dictionary" To find the index of the auxiliary density operator and it's corresponding bath [`Exponent`](@ref), please refer to [`Hierarchy Dictionary`](@ref doc-Hierarchy-Dictionary) for more details. ## Expectation Value Given an observable ``A`` and `ADOs` ``\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}``, one can calculate the expectation value by ```math \langle A \rangle = \textrm{Tr}\left[A \rho^{(0,0,p)}_{ \vert }\right], ``` where, ``m=n=0`` represents the reduced density operator. One can directly calculate the expectation values using the function [`QuantumToolbox.expect`](@ref): ```julia A::QuantumObject # observable # with a single ADOs ados::ADOs E = expect(A, ados) # with a list contains many ADOs ados_list::Vector{ADOs} Elist = expect(A, ados_list) ``` Here, `Elist` contains the expectation values corresponding to the `ados_list`.
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
1266
# [LinearSolve solvers](@id LS-solvers) In this page, we list several recommended solvers provided by [LinearSolve.jl](https://docs.sciml.ai/LinearSolve/stable/) for solving [`steadystate`](@ref) and spectrum in hierarchical equations of motion approach. Remember to import `LinearSolve.jl` ```julia using LinearSolve ``` (click [here](https://docs.sciml.ai/LinearSolve/stable/solvers/solvers/) to see the full solver list provided by `LinearSolve.jl`) ### UMFPACKFactorization (Default solver) This solver performs better when there is more structure to the sparsity pattern (depends on the complexity of your system and baths). ```julia UMFPACKFactorization() ``` ### KLUFactorization This solver performs better when there is less structure to the sparsity pattern (depends on the complexity of your system and baths). ```julia KLUFactorization() ``` ### A generic BICGSTAB implementation from Krylov ```julia KrylovJL_BICGSTAB() ``` ### Pardiso This solver is based on Intel openAPI Math Kernel Library (MKL) Pardiso !!! note "Note" Using this solver requires adding the package [Pardiso.jl](https://github.com/JuliaSparse/Pardiso.jl), i.e. `using Pardiso` ```julia using Pardiso using LinearSolve MKLPardisoFactorize() MKLPardisoIterate() ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
1466
# [DifferentialEquations solvers](@id ODE-solvers) In this page, we list several recommended solvers provided by [DifferentialEquations.jl](https://docs.sciml.ai/DiffEqDocs/stable/) for solving time evolution in hierarchical equations of motion approach. Remember to import `OrdinaryDiffEq.jl` (or `DifferentialEquations.jl`) ```julia using OrdinaryDiffEq ## or "using DifferentialEquations" ``` (click [here](https://docs.sciml.ai/DiffEqDocs/stable/solvers/ode_solve/) to see the full solver list provided by `DifferentialEquations.jl`) For any extra solver options, we can add it in the function `HEOMsolve` with keyword arguments. These keyword arguments will be directly pass to the solvers in `DifferentialEquations` (click [here](https://docs.sciml.ai/DiffEqDocs/stable/basics/common_solver_opts/) to see the documentation for the common solver options) ### DP5 (Default solver) Dormand-Prince's 5/4 Runge-Kutta method. (free 4th order interpolant) ```julia DP5() ``` ### RK4 The canonical Runge-Kutta Order 4 method. Uses a defect control for adaptive stepping using maximum error over the whole interval. ```julia RK4() ``` ### Tsit5 Tsitouras 5/4 Runge-Kutta method. (free 4th order interpolant). ```julia Tsit5() ``` ### Vern7 Verner's “Most Efficient” 7/6 Runge-Kutta method. (lazy 7th order interpolant). ```julia Vern7() ``` ### Vern9 Verner's “Most Efficient” 9/8 Runge-Kutta method. (lazy 9th order interpolant) ```julia Vern9() ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
3355
# [Parity Support](@id doc-Parity) ## Introduction When the system Hamiltonian contains fermionic systems, the HEOMLS matrix ``\hat{\mathcal{M}}`` might be constructed into a different one depend on the parity of the input operator which ``\hat{\mathcal{M}}`` is acting on. This dependence intuitively originates from the properties of partial traces over composite fermionic spaces, where operators do not necessarily commute. As an example, for an environment made out of a single fermion, the reduced matrix elements ``\langle{i}|\rho_\textrm{s}^p|{j}\rangle`` (in a basis labeled by ``\langle i|`` and ``|{j}\rangle``) involve the perturbative sum of expressions of the form ``\langle i| (c \tilde{\rho}_\textrm{e} \tilde{\rho}_\textrm{s}^p c^\dagger+\tilde{\rho}_\textrm{e} \tilde{\rho}_\textrm{s}^p)|{j}\rangle`` (in terms of environmental operators ``\tilde{\rho}_{\textrm{e}}``, system operators ``\tilde{\rho}_\textrm{s}^p`` with parity ``p``, and the environment-annihilation operator ``c``). These quantities depend on the commutator between ``\tilde{\rho}_\textrm{s}^p`` and ``c``, which is trivial only for `EVEN`-parity (``p=+``). In the `ODD`-parity (``p=-``) case, the partial trace over the environment requires further anti-commutations, ultimately resulting in extra minus signs in the expression for the effective propagator describing the reduced dynamics. It is important to explicitly note that, here, by `parity` we do not refer to the presence of an odd or even number of fermions in the system but, rather, to the number of fermionic (annihilation or creation) operators needed to represent ``\rho_\textrm{s}^p``. The reduced density matrix of the system should be an `EVEN`-parity operator and can be expressed as ``\rho_{\textrm{s}}^{p=+}(t)``. However, there are some situations (for example, [calculating density of states for fermionic systems](@ref doc-DOS)) where ``\hat{\mathcal{M}}`` is acting on `ODD`-parity ADOs, e.g., ``\rho_{\textrm{s}}^{p=-}(t)=d_{\textrm{s}}\rho_{\textrm{s}}^{+}(t)`` or ``\rho_{\textrm{s}}^{p=-}(t)=d_{\textrm{s}}^\dagger\rho_{\textrm{s}}^{+}(t)``, where ``d_{\textrm{s}}`` is an annihilation operator acting on fermionic systems. ## Parity support for HEOMLS One can specify the parameter `parity::AbstractParity` in the function of constructing ``\hat{\mathcal{M}}`` which describes the dynamics of [`EVEN`](@ref)- or [`ODD`](@ref)-parity auxiliary density operators (ADOs). The default value of the parameter is `parity=EVEN`. ```julia Hs::QuantumObject # system Hamiltonian Bbath::BosonBath # bosonic bath object Fbath::FermionBath # fermionic bath object Btier::Int # bosonic truncation level Ftier::Int # fermionic truncation level # create HEOMLS matrix in EVEN or ODD parity M_even = M_S(Hs, EVEN) M_odd = M_S(Hs, ODD) M_even = M_Boson(Hs, Btier, Bbath, EVEN) M_odd = M_Boson(Hs, Btier, Bbath, ODD) M_even = M_Fermion(Hs, Ftier, Fbath, EVEN) M_odd = M_Fermion(Hs, Ftier, Fbath, ODD) M_even = M_Boson_Fermion(Hs, Btier, Ftier, Bbath, Fbath, EVEN) M_odd = M_Boson_Fermion(Hs, Btier, Ftier, Bbath, Fbath, ODD) ``` ## Base functions support ### Multiplication between Parity labels ```julia EVEN * EVEN # gives EVEN EVEN * ODD # gives ODD ODD * EVEN # gives ODD ODD * ODD # gives EVEN !EVEN # gives ODD !ODD # gives EVEN ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
1151
# [Cite HierarchicalEOM.jl](@id doc-Cite) ### BibTex for [Commun. Phys. 6, 313 (2023)](https://doi.org/10.1038/s42005-023-01427-2) ```bib @article{HierarchicalEOM-jl2023, doi = {10.1038/s42005-023-01427-2}, url = {https://doi.org/10.1038/s42005-023-01427-2}, year = {2023}, month = {Oct}, publisher = {Nature Portfolio}, volume = {6}, number = {1}, pages = {313}, author = {Huang, Yi-Te and Kuo, Po-Chen and Lambert, Neill and Cirio, Mauro and Cross, Simon and Yang, Shen-Liang and Nori, Franco and Chen, Yueh-Nan}, title = {An efficient {J}ulia framework for hierarchical equations of motion in open quantum systems}, journal = {Communications Physics} } ``` ### BibTex for [arXiv:2306.07522 (2023)](https://doi.org/10.48550/arXiv.2306.07522) ```bib @article{HierarchicalEOM-jl2023, title={{HierarchicalEOM.jl}: {A}n efficient {J}ulia framework for hierarchical equations of motion in open quantum systems}, author={Huang, Yi-Te and Kuo, Po-Chen and Lambert, Neill and Cirio, Mauro and Cross, Simon and Yang, Shen-Liang and Nori, Franco and Chen, Yueh-Nan}, journal={arXiv preprint arXiv:2306.07522}, year={2023} } ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
5821
# [Hierarchy Dictionary](@id doc-Hierarchy-Dictionary) ## Introduction For hierarchical equations of motions, there are many indices the users have to deal with including the indices of the `Exponent` in [bosonic baths](@ref doc-Bosonic-Bath), the `Exponent` in [fermionic baths](@ref doc-Fermionic-Bath), and the ADOs formed by the hierarchy. With the auxiliary density operators ``\rho_{\textbf{j}\vert\textbf{q}}^{(m,n,p)}``, we use the following keywords : - `idx` : the index of the [auxiliary density operators](@ref doc-ADOs) - `lvl` : the level ``m`` (``n``) of the bosonic (fermionic) hierarchy - `nvec` : object [`Nvec`](@ref) which stores the number of existence for each multi-index ensemble ``j`` (``q``) in vector ``\textbf{j}`` (``\textbf{q}``). ## Dictionary for Pure Bosonic or Fermionic Baths An object which contains all dictionaries for pure (bosonic or fermionic) bath-ADOs hierarchy, defined as: [`struct HierarchyDict <: AbstractHierarchyDict`](@ref HierarchyDict) [`HierarchyDict`](@ref) can be obtained from the field `.hierarchy` in [`M_Boson`](@ref) or [`M_Fermion`](@ref), and it contains the following fields : - `idx2nvec` : Return the `Nvec` from a given index of ADO - `nvec2idx` : Return the index of ADO from a given `Nvec` - `lvl2idx` : Return the list of ADO-indices from a given hierarchy level - `bathPtr` : Records the tuple ``(\alpha, k)`` for each position in `Nvec`, where ``\alpha`` and ``k`` represents the ``k``-th exponential-expansion term of the ``\alpha``-th bath. ```julia # HEOMLS for bosonic baths M::M_Boson HDict = M.hierarchy # HEOMLS for fermionic baths M::M_Fermion HDict = M.hierarchy # obtain the nvec corresponds to 10-th ADO nvec = HDict.idx2nvec[10] # obtain the index of the ADO corresponds to the given nvec nvec::Nvec idx = HDict.nvec2idx[nvec] # obtain a list of indices which corresponds to all ADOs in 3rd-level of hierarchy idx_list = HDict.lvl2idx[3] ``` `HierarchicalEOM.jl` also provides a function [`getIndexEnsemble(nvec, bathPtr)`](@ref) to obtain the index of the [`Exponent`](@ref) and it's corresponding index of bath: ```julia # HEOMLS M::M_Boson M::Fermion HDict = M.hierarchy # auxiliary density operators ados::ADOs for (idx, ado) in enumerate(ados) ado # the corresponding auxiliary density operator for idx # obtain the nvec corresponds to ado nvec = HDict.idx2nvec[idx] for (α, k, n) in getIndexEnsemble(nvec, HDict.bathPtr) α # index of the bath k # the index of the exponential-expansion term in α-th bath n # the repetition number of the ensemble {α, k} in vector j (or q) in ADOs exponent = M.bath[α][k] # the k-th exponential-expansion term in α-th bath # do some calculations you want end end ``` ## Dictionary for Mixed Bosonic and Fermionic Baths An object which contains all dictionaries for mixed (bosonic and fermionic) bath-ADOs hierarchy, defined as: [`struct MixHierarchyDict <: AbstractHierarchyDict`](@ref MixHierarchyDict) [`MixHierarchyDict`](@ref) can be obtained from the field `.hierarchy` in [`M_Boson_Fermion`](@ref), and it contains the following fields : - `idx2nvec` : Return the tuple `(Nvec_b, Nvec_f)` from a given index of ADO, where `b` represents boson and `f` represents fermion - `nvec2idx` : Return the index from a given tuple `(Nvec_b, Nvec_f)`, where `b` represents boson and `f` represents fermion - `Blvl2idx` : Return the list of ADO-indices from a given bosonic-hierarchy level - `Flvl2idx` : Return the list of ADO-indices from a given fermionic-hierarchy level - `bosonPtr` : Records the tuple ``(\alpha, k)`` for each position in `Nvec_b`, where ``\alpha`` and ``k`` represents the ``k``-th exponential-expansion term of the ``\alpha``-th bosonic bath. - `fermionPtr` : Records the tuple ``(\alpha, k)`` for each position in `Nvec_f`, where ``\alpha`` and ``k`` represents the ``k``-th exponential-expansion term of the ``\alpha``-th fermionic bath. ```julia # HEOMLS M::M_Boson_Fermion HDict = M.hierarchy # obtain the nvec(s) correspond to 10-th ADO nvec_b, nvec_f = HDict.idx2nvec[10] # obtain the index of the ADO corresponds to the given nvec nvec_b::Nvec nvec_f::Nvec idx = HDict.nvec2idx[(nvec_b, nvec_f)] # obtain a list of indices which corresponds to all ADOs in 3rd-bosonic-level of hierarchy idx_list = HDict.Blvl2idx[3] # obtain a list of indices which corresponds to all ADOs in 4rd-fermionic-level of hierarchy idx_list = HDict.Flvl2idx[4] ``` `HierarchicalEOM.jl` also provides a function [`getIndexEnsemble(nvec, bathPtr)`](@ref) to obtain the index of the [`Exponent`](@ref) and it's corresponding index of bath: ```julia # HEOMLS M::M_Boson_Fermion HDict = M.hierarchy # auxiliary density operators ados::ADOs for (idx, ado) in enumerate(ados) ado # the corresponding auxiliary density operator for idx # obtain the nvec(s) correspond to ado nvec_b, nvec_f = HDict.idx2nvec[idx] # bosonic bath indices for (β, k, n) in getIndexEnsemble(nvec_b, HDict.bosonPtr) β # index of the bosonic bath k # the index of the exponential-expansion term in β-th bosonic bath nb # the repetition number of the ensemble {β, k} in vector j in ADOs exponent = M.Bbath[β][k] # the k-th exponential-expansion term in β-th bosonic bath # do some calculations you want end # fermionic bath indices for (α, h, n) in getIndexEnsemble(nvec_f, HDict.fermionPtr) α # index of the fermionic bath h # the index of the exponential-expansion term in α-th fermionic bath nf # the repetition number of the ensemble {α, h} in vector q in ADOs exponent = M.Fbath[α][h] # the h-th exponential-expansion term in α-th fermionic bath # do some calculations you want end end ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
2261
# HierarchicalEOM.jl: An efficient Julia framework for Hierarchical Equations of Motion (HEOM) in open quantum systems `HierarchicalEOM.jl` is a numerical framework written in [`Julia`](https://julialang.org/). It provides a user-friendly and efficient tool based on hierarchical equations of motion (HEOM) approach to simulate complex open quantum systems, including non-Markovian effects due to non-perturbative interaction with one (or multiple) environment(s). It is built upon [`QuantumToolbox.jl`](https://github.com/qutip/QuantumToolbox.jl). While integrating many of the features present in other open-source HEOM packages, `HierarchicalEOM.jl` also includes new functionalities, such as the construction of even- and odd-parity [HEOM Liouvillian superoperator (HEOMLS) matrices](@ref doc-HEOMLS-Matrix), the estimation of [importance values](@ref doc-Importance-Value-and-Threshold) for all [auxiliary density operators (ADOs)](@ref doc-ADOs), and the calculation of [spectra](@ref doc-Spectrum) for both bosonic and fermionic systems. By wrapping some functions from other [`Julia`](https://julialang.org/) packages ([`DifferentialEquations.jl`](https://diffeq.sciml.ai/stable/), [`LinearSolve.jl`](http://linearsolve.sciml.ai/stable/) and [`fastExpm.jl`](https://github.com/fmentink/FastExpm.jl)), `HierarchicalEOM.jl` collects different methods and could further optimize the computation for the [stationary state](@ref doc-Stationary-State), and the [time evolution](@ref doc-Time-Evolution) of all [ADOs](@ref doc-ADOs). The required handling of the [ADOs](@ref doc-ADOs) multi-indexes is achieved through a user-friendly interface called [Hierarchy Dictionary](@ref doc-Hierarchy-Dictionary). ![HEOM Ecosystem](assets/heom_ecosystem.jpeg) We believe that `HierarchicalEOM.jl` will be a valuable tool for researchers working in different fields such as quantum biology, quantum optics, quantum thermodynamics, quantum information, quantum transport, and condensed matter physics. If you like `HierarchicalEOM.jl` and find the framework useful in your research, we would be grateful if you could cite our publication [ [Commun. Phys. 6, 313 (2023)](https://doi.org/10.1038/s42005-023-01427-2) ] using the bibtex entry [here](@ref doc-Cite).
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
3234
# Installation ## HierarchicalEOM.jl To install `HierarchicalEOM.jl`, run the following commands inside Julia's interactive session (also known as REPL): ```julia using Pkg Pkg.add("HierarchicalEOM") ``` Alternatively, this can also be done in Julia's [Pkg REPL](https://julialang.github.io/Pkg.jl/v1/getting-started/) by pressing the key `]` in the REPL to use the package mode, and then type the following command: ```julia-REPL (1.10) pkg> add HierarchicalEOM ``` More information about `Julia`'s package manager can be found at [`Pkg.jl`](https://julialang.github.io/Pkg.jl/v1/). !!! note "Julia 1.10" `HierarchicalEOM.jl` requires Julia 1.10 or higher (we dropped Julia 1.9 since ver.2.1.0) To load the package and check the version information, use the command: ```julia julia> using HierarchicalEOM julia> HierarchicalEOM.versioninfo() ``` ## [QuantumToolbox.jl](https://github.com/qutip/QuantumToolbox.jl) `HierarchicalEOM.jl` is built upon `QuantumToolbox.jl`, which is a cutting-edge Julia package designed for quantum physics simulations, closely emulating the popular Python [`QuTiP`](https://qutip.org/) package. It provides many useful functions to create arbitrary quantum states and operators which can be combined in all the expected ways. It uniquely combines the simplicity and power of Julia with advanced features like GPU acceleration and distributed computing, making simulation of quantum systems more accessible and efficient. !!! note "Note" Start from `HierarchicalEOM v2.0.0+`, the inputs states and operators must be in the type of `QuantumObject` (defined in `QuantumToolbox`) ## Other Useful Packages In order to get a better experience and take full advantage of `HierarchicalEOM`, we recommend to install the following external packages: ### [DifferentialEquations.jl](https://diffeq.sciml.ai/stable/) `DifferentialEquations` is needed to provide the low-level ODE solvers especially for solving [time evolution](@ref doc-Time-Evolution). For [low dependency usage](https://diffeq.sciml.ai/stable/features/low_dep/), users can use [`OrdinaryDiffEq.jl`](https://github.com/JuliaDiffEq/OrdinaryDiffEq.jl) instead. ### [LinearSolve.jl](http://linearsolve.sciml.ai/stable/) `LinearSolve` is a unified interface for the linear solving packages of Julia. It interfaces with other packages of the Julia ecosystem to make it easier to test alternative solver packages and pass small types to control algorithm swapping. It is needed to provide the solvers especially for solving [stationary state](@ref doc-Stationary-State) and [spectra](@ref doc-Spectrum) for both bosonic and fermionic systems. ### [JLD2.jl](https://juliaio.github.io/JLD2.jl/stable/) `JLD2` saves and loads Julia data structures in a format comprising a subset of HDF5. Because the size of matrix in `HierarchicalEOM` is usually super large and leads to long time calculation, we support the functionality for saving and loading the `HierarchicalEOM`-type objects into files by `JLD2 >= 0.4.23`. ### [PyPlot.jl](https://github.com/JuliaPy/PyPlot.jl) `PyPlot.jl` provides a Julia interface to the [`Matplotlib`](https://matplotlib.org/) plotting library from `Python`, and specifically to the `matplotlib.pyplot` module.
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
4052
# Library API ## Contents ```@contents Pages = ["libraryAPI.md"] ``` ## Index ```@index Pages = ["libraryAPI.md"] ``` ## [Bath Module](@id lib-Bath) ```@docs C(bath::BosonBath, tlist::AbstractVector) C(bath::FermionBath, tlist::AbstractVector) Exponent BosonBath BosonBath(op::QuantumObject, η::Vector{Ti}, γ::Vector{Tj}, δ::Number=0.0; combine::Bool=true) where {Ti, Tj <: Number} BosonBath(op::QuantumObject, η_real::Vector{Ti}, γ_real::Vector{Tj}, η_imag::Vector{Tk}, γ_imag::Vector{Tl}, δ::Tm=0.0; combine::Bool=true) where {Ti, Tj, Tk, Tl, Tm <: Number} bosonReal bosonReal(op::QuantumObject, η_real::Vector{Ti}, γ_real::Vector{Tj}) where {Ti, Tj <: Number} bosonImag bosonImag(op::QuantumObject, η_real::Vector{Ti}, γ_real::Vector{Tj}) where {Ti, Tj <: Number} bosonRealImag bosonRealImag(op::QuantumObject, η_real::Vector{Ti}, η_imag::Vector{Tj}, γ::Vector{Tk}) where {Ti, Tj, Tk <: Number} BosonBathRWA bosonAbsorb bosonAbsorb(op::QuantumObject, η_absorb::Vector{Ti}, γ_absorb::Vector{Tj}, η_emit::Vector{Tk}) where {Ti, Tj, Tk <: Number} bosonEmit bosonEmit(op::QuantumObject, η_emit::Vector{Ti}, γ_emit::Vector{Tj}, η_absorb::Vector{Tk}) where {Ti, Tj, Tk <: Number} FermionBath FermionBath(op::QuantumObject, η_absorb::Vector{Ti}, γ_absorb::Vector{Tj}, η_emit::Vector{Tk}, γ_emit::Vector{Tl}, δ::Tm=0.0) where {Ti, Tj, Tk, Tl, Tm <: Number} fermionAbsorb fermionAbsorb(op::QuantumObject, η_absorb::Vector{Ti}, γ_absorb::Vector{Tj}, η_emit::Vector{Tk}) where {Ti, Tj, Tk <: Number} fermionEmit fermionEmit(op::QuantumObject, η_emit::Vector{Ti}, γ_emit::Vector{Tj}, η_absorb::Vector{Tk}) where {Ti, Tj, Tk <: Number} ``` ## Bath Correlation Functions ```@docs Boson_DrudeLorentz_Matsubara Boson_DrudeLorentz_Pade Fermion_Lorentz_Matsubara Fermion_Lorentz_Pade ``` ## Parity ```@docs EvenParity OddParity EVEN ODD ``` ## HEOM Liouvillian superoperator matrices ```@docs HEOMSuperOp HEOMSuperOp(op, opParity::AbstractParity, refHEOMLS::AbstractHEOMLSMatrix, mul_basis::AbstractString="L") HEOMSuperOp(op, opParity::AbstractParity, refADOs::ADOs, mul_basis::AbstractString="L") HEOMSuperOp(op, opParity::AbstractParity, dims::SVector, N::Int, mul_basis::AbstractString) M_S M_S(Hsys::QuantumObject, parity::AbstractParity=EVEN; verbose::Bool=true) M_Boson M_Boson(Hsys::QuantumObject, tier::Int, Bath::Vector{BosonBath}, parity::AbstractParity=EVEN; threshold::Real=0.0, verbose::Bool=true) M_Fermion M_Fermion(Hsys::QuantumObject, tier::Int, Bath::Vector{FermionBath}, parity::AbstractParity=EVEN; threshold::Real=0.0, verbose::Bool=true) M_Boson_Fermion M_Boson_Fermion(Hsys::QuantumObject, tier_b::Int, tier_f::Int, Bath_b::Vector{BosonBath}, Bath_f::Vector{FermionBath}, parity::AbstractParity=EVEN; threshold::Real=0.0, verbose::Bool=true) size(M::HEOMSuperOp) size(M::HEOMSuperOp, dim::Int) size(M::AbstractHEOMLSMatrix) size(M::AbstractHEOMLSMatrix, dim::Int) eltype(M::HEOMSuperOp) eltype(M::AbstractHEOMLSMatrix) Propagator addBosonDissipator addFermionDissipator addTerminator ``` ## Auxiliary Density Operators (ADOs) ```@docs ADOs ADOs(V::AbstractVector, N::Int) length(A::ADOs) eltype(A::ADOs) getRho getADO QuantumToolbox.expect ``` ## [Hierarchy Dictionary](@id lib-Hierarchy-Dictionary) ```@docs Nvec HierarchyDict MixHierarchyDict getIndexEnsemble ``` ## [Time Evolution](@id lib-Time-Evolution) There are two function definitions of `HEOMsolve`, which depend on different methods to solve the time evolution: ```@docs HEOMsolve TimeEvolutionHEOMSol ``` ## Stationary State There are two function definitions of `steadystate`, which depend on different methods to solve the stationary state: ```@docs steadystate ``` ## Spectrum ```@docs PowerSpectrum DensityOfStates ``` ## Misc. ```@docs HierarchicalEOM.versioninfo() ``` The outputs will be something like the following: ```@example using HierarchicalEOM HierarchicalEOM.versioninfo() ``` ```@docs HierarchicalEOM.print_logo(io::IO=stdout) ``` The output will be something like the following: ```@example using HierarchicalEOM HierarchicalEOM.print_logo() ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
9104
# [Spectrum](@id doc-Spectrum) ## Introduction We briefly summarize how to numerically compute the spectrum associated with the system degree of freedom. [Phys. Rev. Lett. 109, 266403 (2012)](https://link.aps.org/doi/10.1103/PhysRevLett.109.266403) showed that the spectrum can be evaluated either in time or frequency domain. `HierarchicalEOM.jl` provides the following listed functions which performs the calculation of spectrum in frequency domain. - [Power Spectrum](@ref doc-PS) - [Density of States](@ref doc-DOS) `HierarchicalEOM.jl` wraps some of the functions in [LinearSolve.jl](http://linearsolve.sciml.ai/stable/), which is a very rich numerical library for solving the linear problems and provides many solvers. It offers quite a few options for the user to tailor the solver to their specific needs. The default solver (and its corresponding settings) are chosen to suit commonly encountered problems and should work fine for most of the cases. If you require more specialized methods, such as the choice of algorithm, please refer to [LinearSolve solvers](@ref LS-solvers) and also the documentation of [LinearSolve.jl](http://linearsolve.sciml.ai/stable/). !!! compat "Extension for CUDA.jl" `HierarchicalEOM.jl` provides an extension to support GPU ([`CUDA.jl`](https://github.com/JuliaGPU/CUDA.jl)) acceleration for solving the spectrum, but this feature requires `Julia 1.9+` and `HierarchicalEOM 1.1+`. See [here](@ref doc-ext-CUDA) for more details. The output of the above listed functions will always be in the type of `Vector{Float64}`, which contains the list of the spectrum values corresponding to the given `ωlist`. ## Common and optional parameters Furthermore, there are two common optional parameters for all the functions provided below: - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. - `filename::String` : If filename was specified, the value of spectrum for each ω will be saved into the file "filename.txt" during the solving process. If the filename is specified, the function will automatically save (update) the value (together with a comma behind it) to a new line in the file (with ".txt" behind the filename) once it obtains the solution of each specified ``\omega``. For example, if you specify `filename="test"` and `ωlist=0:1:5`, you will obtain a file `test.txt` where each line in this file (as shown below) is the result of spectrum corresponding to the given `ωlist`: ``` # (the content inside test.txt) # 0.4242990296334028, 0.28617768129333854, 0.21332961856387556, 0.1751179183484055, 0.15739257286986685, 0.1518018484057393, ``` For your convenience, we add those commas (",") in the end of each line for the users to easily do "copy-and-paste" and load these results back into julia's kernel (construct a vector of the given results) again, namely ```julia results = [ 0.4242990296334028, 0.28617768129333854, 0.21332961856387556, 0.1751179183484055, 0.15739257286986685, 0.1518018484057393 ] ``` ## [Power Spectrum](@id doc-PS) Start from the power spectrum in the time-domain. We write the system two-time correlation function in terms of the propagator ``\hat{\mathcal{G}}(t)=\exp(\hat{\mathcal{M}} t)`` for ``t>0``. The power spectrum ``\pi S(\omega)`` can be obtained as ```math \begin{aligned} \pi S(\omega) &= \textrm{Re}\left\{\int_0^\infty dt \langle P(t)Q(0)\rangle e^{-i\omega t}\right\}\\ &= \textrm{Re}\left\{\int_0^\infty dt \langle P e^{\hat{\mathcal{M}} t}Q\rangle e^{-i\omega t}\right\}\\ &= -\textrm{Re}\left\{\langle P (\hat{\mathcal{M}} -i\omega)^{-1} Q\rangle\right\}\\ &= -\textrm{Re}\left\{\textrm{Tr}\left[ P (\hat{\mathcal{M}} -i\omega)^{-1} Q\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}\right]\right\}, \end{aligned} ``` where a half-Fourier transform has been introduced in the third line. We note that only the reduced density operator (``m=n=0``) is considered when taking the final trace operation. This function solves the linear problem ``\textbf{A x}=\textbf{b}`` at a fixed frequency ``\omega`` where - ``\textbf{A}=\hat{\mathcal{M}}-i\omega`` - ``\textbf{b}=Q\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}`` using the package [LinearSolve.jl](http://linearsolve.sciml.ai/stable/). Finially, one can obtain the value of the power spectrum for specific ``\omega``, namely ```math \pi S(\omega) = -\textrm{Re}\left\{\textrm{Tr}\left[ P \textbf{x}\right]\right\}. ``` !!! note "Odd-Parity for Power Spectrum" When ``Q`` is an operator acting on fermionic systems and has `ODD`-parity, the HEOMLS matrix ``\hat{\mathcal{M}}`` is acting on the `ODD`-parity space because ``\textbf{b}=Q\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}``. Therefore, remember to construct ``\hat{\mathcal{M}}`` with `ODD` [parity](@ref doc-Parity) in this kind of cases. See also the docstring : ```@docs PowerSpectrum(M::AbstractHEOMLSMatrix, ρ::Union{QuantumObject,ADOs}, P_op::Union{QuantumObject,HEOMSuperOp}, Q_op::Union{QuantumObject,HEOMSuperOp}, ωlist::AbstractVector, reverse::Bool = false; solver = UMFPACKFactorization(), verbose::Bool = true, filename::String = "", SOLVEROptions...) ``` ```julia M::AbstractHEOMLSMatrix # the input state can be in either type (but usually ADOs): ρ::QuantumObject # the reduced density operator ρ::ADOs # the ADOs solved from "evolution" or "steadystate" P::QuantumObject Q::QuantumObject # the spectrum value for the specific frequency ω which need to be solved ωlist = 0:0.5:2 # [0.0, 0.5, 1.0, 1.5, 2.0] πSω = spectrum(M, ρ, Q, ωlist) # P will automatically be considered as "the adjoint of Q operator" πSω = spectrum(M, ρ, P, Q, ωlist) # user specify both P and Q operator ``` ## [Density of States](@id doc-DOS) Start from the density of states for fermionic systems in the time-domain. We write the system two-time correlation function in terms of the propagator ``\hat{\mathcal{G}}(t)=\exp(\hat{\mathcal{M}} t)`` for ``t>0``. The density of states ``\pi A(\omega)`` can be obtained as ```math \begin{aligned} \pi A(\omega) &= \textrm{Re}\left\{\int_0^\infty dt \langle d(t)d^\dagger(0)\rangle e^{i\omega t}\right\} + \textrm{Re}\left\{\int_0^\infty dt \langle d^\dagger(t)d(0)\rangle e^{-i\omega t}\right\}\\ &= \textrm{Re}\left\{\int_0^\infty dt \langle d e^{\hat{\mathcal{M}} t}d^\dagger\rangle e^{i\omega t}\right\}+\textrm{Re}\left\{\int_0^\infty dt \langle d^\dagger e^{\hat{\mathcal{M}} t}d\rangle e^{-i\omega t}\right\}\\ &= -\textrm{Re}\left\{\langle d (\hat{\mathcal{M}} +i\omega)^{-1} d^\dagger\rangle + \langle d^\dagger (\hat{\mathcal{M}} -i\omega)^{-1} d\rangle\right\}\\ &= -\textrm{Re}\left\{\textrm{Tr}\left[ d (\hat{\mathcal{M}} +i\omega)^{-1} d^\dagger\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}\right] + \textrm{Tr}\left[ d^\dagger (\hat{\mathcal{M}} -i\omega)^{-1} d\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}\right]\right\}, \end{aligned} ``` where a half-Fourier transform has been introduced in the third line. We note that only the reduced density operator (``m=n=0``) is considered when taking the final trace operation. This functionsolves two linear problems ``\textbf{A}_+ \textbf{x}_+=\textbf{b}_+`` and ``\textbf{A}_- \textbf{x}_-=\textbf{b}_-`` at a fixed frequency ``\omega`` where - ``\textbf{A}_+=\hat{\mathcal{M}}+i\omega`` - ``\textbf{b}_+=d^\dagger\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}`` - ``\textbf{A}_-=\hat{\mathcal{M}}-i\omega`` - ``\textbf{b}_-=d\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}`` using the package [LinearSolve.jl](http://linearsolve.sciml.ai/stable/). Finially, one can obtain the density of states for specific ``\omega``, namely ```math \pi A(\omega) = -\textrm{Re}\left\{\textrm{Tr}\left[ d \textbf{x}_+\right]+\textrm{Tr}\left[ d^\dagger \textbf{x}_-\right]\right\}. ``` !!! note "Odd-Parity for Density of States" As shown above, the HEOMLS matrix ``\hat{\mathcal{M}}`` acts on the `ODD`-parity space, compatibly with the parity of both the operators ``\textbf{b}_-=d\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}`` and ``\textbf{b}_+=d^\dagger\rho^{(m,n,+)}_{\textbf{j} \vert \textbf{q}}``. Therefore, remember to construct ``\hat{\mathcal{M}}`` with `ODD` [parity](@ref doc-Parity) for solving spectrum of fermionic systems. See also the docstring : ```@docs DensityOfStates(M::AbstractHEOMLSMatrix, ρ::QuantumObject, d_op::QuantumObject, ωlist::AbstractVector; solver=UMFPACKFactorization(), verbose::Bool = true, filename::String = "", SOLVEROptions...) ``` ```julia Hs::QuantumObject # system Hamiltonian bath::FermionBath # fermionic bath object tier::Int # fermionic truncation level # create HEOMLS matrix in both :even and ODD parity M_even = M_Fermion(Hs, tier, bath) M_odd = M_Fermion(Hs, tier, bath, ODD) # the input state can be in either type of density operator matrix or ADOs (but usually ADOs): ados = steadystate(M_even) # the (usually annihilation) operator "d" as shown above d::QuantumObject # the spectrum value for the specific frequency ω which need to be solved ω_list = 0:0.5:2 # [0.0, 0.5, 1.0, 1.5, 2.0] πAω = DensityOfStates(M_odd, ados, d, ω_list) ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
3975
# [Stationary State](@id doc-Stationary-State) `HierarchicalEOM.jl` implements two different ways to calculate stationary states of all [Auxiliary Density Operators (ADOs)](@ref doc-ADOs). To solve the stationary state of the reduced state and also all the [ADOs](@ref doc-ADOs), you only need to call [`steadystate`](@ref). Different methods are implemented with different input parameters of the function which makes it easy to switch between different methods. The output of the function [`steadystate`](@ref) for each methods will always be in the type of the auxiliary density operators [`ADOs`](@ref). ## Solve with [LinearSolve.jl](http://linearsolve.sciml.ai/stable/) The first method is implemented by solving the linear problem ```math 0=\hat{\mathcal{M}}\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t) ``` `HierarchicalEOM.jl` wraps some of the functions in [LinearSolve.jl](http://linearsolve.sciml.ai/stable/), which is a very rich numerical library for solving the linear problems and provides many solvers. It offers quite a few options for the user to tailor the solver to their specific needs. The default solver (and its corresponding settings) are chosen to suit commonly encountered problems and should work fine for most of the cases. If you require more specialized methods, such as the choice of algorithm, please refer to [LinearSolve solvers](@ref LS-solvers) and also the documentation of [LinearSolve.jl](http://linearsolve.sciml.ai/stable/). See the docstring of this method: ```@docs steadystate(M::AbstractHEOMLSMatrix; solver=UMFPACKFactorization(), verbose::Bool=true, SOLVEROptions...) ``` ```julia # the HEOMLS matrix M::AbstractHEOMLSMatrix ados_steady = steadystate(M) ``` !!! warning "Unphysical solution" This method does not require an initial condition ``\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(0)``. Although this method works for most of the cases, it does not guarantee that one can obtain a physical (or unique) solution. If there is any problem within the solution, please try the second method which solves with an initial condition, as shown below. ## Solve with [DifferentialEquations.jl](https://diffeq.sciml.ai/stable/) The second method is implemented by solving the ordinary differential equation (ODE) method : ```math \partial_{t}\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t)=\hat{\mathcal{M}}\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t) ``` until finding a stationary solution. `HierarchicalEOM.jl` wraps some of the functions in [DifferentialEquations.jl](https://diffeq.sciml.ai/stable/), which is a very rich numerical library for solving the differential equations and provides many ODE solvers. It offers quite a few options for the user to tailor the solver to their specific needs. The default solver (and its corresponding settings) are chosen to suit commonly encountered problems and should work fine for most of the cases. If you require more specialized methods, such as the choice of algorithm, please refer to the documentation of [DifferentialEquations.jl](https://diffeq.sciml.ai/stable/). ### Given the initial state as Density Operator (`QuantumObject` type) See the docstring of this method: ```@docs steadystate(M::AbstractHEOMLSMatrix, ρ0::QuantumObject, tspan::Number = Inf; solver = DP5(), termination_condition = NormTerminationMode(), verbose::Bool = true, SOLVEROptions...) ``` ```julia # the HEOMLS matrix M::AbstractHEOMLSMatrix # the initial state of the system density operator ρ0::QuantumObject ados_steady = steadystate(M, ρ0) ``` ### Given the initial state as Auxiliary Density Operators See the docstring of this method: ```@docs steadystate(M::AbstractHEOMLSMatrix, ados::ADOs, tspan::Number = Inf; solver = DP5(), termination_condition = NormTerminationMode(), verbose::Bool = true, SOLVEROptions...) ``` ```julia # the HEOMLS matrix M::AbstractHEOMLSMatrix # the initial state of the ADOs ados::ADOs ados_steady = steadystate(M, ados) ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
10499
# [Time Evolution](@id doc-Time-Evolution) ## Introduction `HierarchicalEOM.jl` implements various methods and solvers to simulate the open quantum system dynamics. The [HEOM Liouvillian superoperator (HEOMLS) matrix](@ref doc-HEOMLS-Matrix) ``\hat{\mathcal{M}}`` characterizes the dynamics of the reduce state and in the full extended space of all [auxiliary density operators (ADOs)](@ref doc-ADOs) ``\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t)``, namely ```math \begin{equation} \partial_{t}\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t)=\hat{\mathcal{M}}\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t) \end{equation} ``` ### `HEOMsolve` and `TimeEvolutionHEOMSol` To solve the dynamics of the reduced state and also all the [ADOs](@ref doc-ADOs), you only need to call [`HEOMsolve`](@ref). Different methods (see the contents below) are implemented with different input parameters of the function which makes it easy to switch between different methods. The output of the function [`HEOMsolve`](@ref) for each methods will always be in the type [`TimeEvolutionHEOMSol`](@ref), which contains the results (including [`ADOs`](@ref) and expectation values at each time point) and some information from the solver. One can obtain the value of each fields in [`TimeEvolutionHEOMSol`](@ref) as follows: ```julia sol::TimeEvolutionHEOMSol sol.Btier # the tier (cutoff level) for bosonic hierarchy sol.Ftier # the tier (cutoff level) for fermionic hierarchy sol.times # The time list of the evolution. sol.ados # The list of result ADOs at each time point. sol.expect # The expectation values corresponding to each time point in `times`. sol.retcode # The return code from the solver. sol.alg # The algorithm which is used during the solving process. sol.abstol # The absolute tolerance which is used during the solving process. sol.reltol # The relative tolerance which is used during the solving process. ``` ### Expectation Values Given an observable ``A`` and the [`ADOs`](@ref doc-ADOs) ``\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t)``, one can calculate the expectation value by ```math \langle A(t) \rangle = \textrm{Tr}\left[A \rho^{(0,0,p)}_{ \vert }(t)\right], ``` where, ``m=n=0`` represents the reduced density operator, see [`ADOs`](@ref doc-ADOs) for more details. One can directly calculate the expectation value by specifying the keyword argument `e_ops` (a list of observables), and the expectation values corresponding to each time point and observables will be stored in [`TimeEvolutionHEOMSol`](@ref): ```julia A1::QuantumObject # observable 1 A2::QuantumObject # observable 2 sol = HEOMsolve(...; e_ops = [A1, A2], ...) # the input parameters depend on the different methods you choose. sol.expect[1,:] # the expectation values of observable 1 (`A1`) corresponding to each time point in `sol.times` sol.expect[2,:] # the expectation values of observable 2 (`A2`) corresponding to each time point in `sol.times` ``` An alternative way for calculating the expectation values is to use the function [`QuantumToolbox.expect`](@ref) together with the list of [`ADOs`](@ref) stored in [`TimeEvolutionHEOMSol`](@ref): ```julia A::QuantumObject # observable sol = HEOMsolve(...) # the input parameters depend on the different methods you choose. ados_list = sol.ados Elist = expect(A, ados_list) ``` Here, `Elist` contains the expectation values corresponding to the `ados_list` (i.e., the reduced density operator in each time step). ## Common and optional parameters There are three common optional parameters for all the methods provided below: - `e_ops::Union{Nothing,AbstractVector}`: List of operators for which to calculate expectation values. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. - `filename::String` : If filename was specified, the ADOs at each time point will be saved into the JLD2 file after the solving process. Default to Empty `String`: `""`. If the `filename` is specified, the function will automatically save the [`ADOs`](@ref) to the file (with `.jld2` behind the `filename`) once the solving process is finished. The saving method is based on the package [`JLD2.jl`](https://juliaio.github.io/JLD2.jl/stable/), which saves and loads `Julia` data structures in a format comprising a subset of HDF5. ```julia tlist = 0:0.5:5 ados_list = HEOMsolve(..., tlist, ...; filename="test", ...) ``` The solution of the [`ADOs`](@ref) for each time step in `tlist` is saved in the file named `test.jld2` with a key: `"ados"`. To retrieve the solution the list of [`ADOs`](@ref) from a previously saved file `"text.jld2"`, just read the file with the methods provided by [`JLD2.jl`](https://juliaio.github.io/JLD2.jl/stable/) and specify the key: `"ados"`, namely ```julia using HierarchicalEOM, JLD2 # remember to import these before retrieving the solution filename = "test.jld2" jldopen(filename, "r") do file ados_list = file["ados"] end ``` ## Ordinary Differential Equation (ODE) Method The first method is implemented by solving the ordinary differential equation (ODE). `HierarchicalEOM.jl` wraps some of the functions in [`DifferentialEquations.jl`](https://diffeq.sciml.ai/stable/), which is a very rich numerical library for solving the differential equations and provides many ODE solvers. It offers quite a few options for the user to tailor the solver to their specific needs. The default solver (and its corresponding settings) are chosen to suit commonly encountered problems and should work fine for most of the cases. If you require more specialized methods, such as the choice of algorithm, please refer to [DifferentialEquations solvers](@ref ODE-solvers) and also the documentation of [`DifferentialEquations.jl`](https://diffeq.sciml.ai/stable/). !!! compat "Extension for CUDA.jl" `HierarchicalEOM.jl` provides an extension to support GPU ([`CUDA.jl`](https://github.com/JuliaGPU/CUDA.jl)) acceleration for solving the time evolution (only for ODE method with time-independent system Hamiltonian). See [here](@ref doc-ext-CUDA) for more details. See the docstring of this method: ```@docs HEOMsolve(M::AbstractHEOMLSMatrix, ρ0::T_state, tlist::AbstractVector; e_ops::Union{Nothing,AbstractVector} = nothing, solver::OrdinaryDiffEqAlgorithm = DP5(), H_t::Union{Nothing,Function,TimeDependentOperatorSum} = nothing, params::NamedTuple = NamedTuple(), verbose::Bool = true, filename::String = "", SOLVEROptions...,) where {T_state<:Union{QuantumObject,ADOs}} ``` ```julia # the time-independent HEOMLS matrix M::AbstractHEOMLSMatrix # the initial state can be either the system density operator or ADOs ρ0::QuantumObject ρ0::ADOs # specific time points to save the solution during the solving process. tlist = 0:0.5:2 # [0.0, 0.5, 1.0, 1.5, 2.0] sol = HEOMsolve(M, ρ0, tlist) ``` ## Time Dependent Problems In general, the time-dependent system Hamiltonian can be separated into the time-independent and time-dependent parts, namely ```math H_s (t) = H_0 + H_1(t). ``` We again wrap some of the functions in [`DifferentialEquations.jl`](https://diffeq.sciml.ai/stable/) to solve the time-dependent problems here. To deal with the time-dependent system Hamiltonian problem in `HierarchicalEOM.jl`, we first construct the [HEOMLS matrices](@ref doc-HEOMLS-Matrix) ``\hat{\mathcal{M}}`` with **time-independent** Hamiltonian ``H_0``: ```julia M = M_S(H0, ...) M = M_Boson(H0, ...) M = M_Fermion(H0, ...) M = M_BosonFermion(H0, ...) ``` To solve the dynamics characterized by ``\hat{\mathcal{M}}`` together with the time-dependent part of system Hamiltonian ``H_1(t)``, you can specify keyword arguments `H_t` and `params` while calling [`HEOMsolve`](@ref). Here, the definition of user-defined function `H_1` must be in the form `H_1(t, params::NamedTuple)` and returns the time-dependent part of system Hamiltonian or Liouvillian (in `QuantumObject` type) at any given time point `t`. The parameters `params` should be a `NamedTuple` which contains all the extra parameters you need for the function `H_1`. For example: ```julia # in this case, p should be passed in as a NamedTuple: (p0 = p0, p1 = p1, p2 = p2) function H_1(t, p::NamedTuple) σx = [0 1; 1 0] # Pauli-X matrix return (sin(p.p0 * t) + sin(p.p1 * t) + sin(p.p2 * t)) * σx end ``` The `p` will be passed to your function `H_1` directly from the keyword argument in [`HEOMsolve`](@ref) called `params`: ```julia M::AbstractHEOMLSMatrix ρ0::QuantumObject tlist = 0:0.1:10 p = (p0 = 0.1, p1 = 1, p2 = 10) sol = HEOMsolve(M, ρ0, tlist; H_t = H_1, params = p) ``` !!! warning "Warning" If you don't need any extra `param` in your case, you still need to put a redundant one in the definition of `H_1`, for example: ```julia function H_1(t, p::NamedTuple) σx = [0 1; 1 0] # Pauli-X matrix return sin(0.1 * t) * σx end M::AbstractHEOMLSMatrix ρ0::QuantumObject tlist = 0:0.1:10 sol = HEOMsolve(M, ρ0, tlist; H_t = H_1) ``` !!! note "Note" The default value for `params` in `HEOMsolve` is an empty `NamedTuple()`. ## Propagator Method The second method is implemented by directly construct the propagator of a given [HEOMLS matrix](@ref doc-HEOMLS-Matrix) ``\hat{\mathcal{M}}``. Because ``\hat{\mathcal{M}}`` is time-independent, the equation above can be solved analytically as ```math \rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t)=\hat{\mathcal{G}}(t)\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(0), ``` where ``\hat{\mathcal{G}}(t)\equiv \exp(\hat{\mathcal{M}}t)`` is the propagator for all [ADOs](@ref doc-ADOs) corresponding to ``\hat{\mathcal{M}}``. To construct the propagator, we wrap the function in the package [`fastExpm.jl`](https://github.com/fmentink/FastExpm.jl), which is optimized for the exponentiation of either large-dense or sparse matrices. See the docstring of this method: ```@docs HEOMsolve(M::AbstractHEOMLSMatrix ,ρ0::T_state, Δt::Real, steps::Int; e_ops::Union{Nothing,AbstractVector} = nothing, threshold = 1.0e-6, nonzero_tol = 1.0e-14, verbose::Bool = true, filename::String = "",) where {T_state<:Union{QuantumObject,ADOs}} ``` ```julia # the time-independent HEOMLS matrix M::AbstractHEOMLSMatrix # the initial state can be either the system density operator or ADOs ρ0::QuantumObject ρ0::ADOs # A specific time interval (time step) Δt = 0.5 # The number of time steps for the propagator to apply steps = 4 # equivalent to tlist = 0 : Δt : (Δt * steps) sol = HEOMsolve(M, ρ0, Δt, steps) ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
2031
# [Drude-Lorentz Spectral Density](@id Boson-Drude-Lorentz) ```math J(\omega)=\frac{4\Delta W\omega}{\omega^2+W^2} ``` Here, ``\Delta`` represents the coupling strength between system and the bosonic environment with band-width ``W``. ## Matsubara Expansion With Matsubara Expansion, the correlation function can be analytically solved and expressed as follows: ```math C(t_1, t_2)=\sum_{l=1}^{\infty} \eta_l \exp(-\gamma_l (t_1-t_2)) ``` with ```math \begin{aligned} \gamma_{1} &= W,\\ \eta_{1} &= \Delta W\left[-i+\cot\left(\frac{W}{2 k_B T}\right)\right],\\ \gamma_{l\neq 1} &= 2\pi l k_B T,\\ \eta_{l\neq 1} &= -2 k_B T \cdot \frac{2\Delta W \cdot \gamma_l}{-\gamma_l^2 + W^2}. \end{aligned} ``` This can be constructed by the built-in function [`Boson_DrudeLorentz_Matsubara`](@ref): ```julia Vs # coupling operator Δ # coupling strength W # band-width of the environment kT # the product of the Boltzmann constant k and the absolute temperature T N # Number of exponential terms bath = Boson_DrudeLorentz_Matsubara(Vs, Δ, W, kT, N - 1) ``` ## Padé Expansion With Padé Expansion, the correlation function can be analytically solved and expressed as the following exponential terms: ```math C(t_1, t_2)=\sum_{l=1}^{\infty} \eta_l \exp(-\gamma_l (t_1-t_2)) ``` with ```math \begin{aligned} \gamma_{1} &= W,\\ \eta_{1} &= \Delta W\left[-i+\cot\left(\frac{W}{2 k_B T}\right)\right],\\ \gamma_{l\neq 1} &= \zeta_l k_B T,\\ \eta_{l\neq 1} &= -2 \kappa_l k_B T \cdot \frac{2\Delta W \cdot \zeta_l k_B T}{-(\zeta_l k_B T)^2 + W^2}, \end{aligned} ``` where the parameters ``\kappa_l`` and ``\zeta_l`` are described in [J. Chem. Phys. 134, 244106 (2011)](https://doi.org/10.1063/1.3602466). This can be constructed by the built-in function [`Boson_DrudeLorentz_Pade`](@ref): ```julia Vs # coupling operator Δ # coupling strength W # band-width of the environment kT # the product of the Boltzmann constant k and the absolute temperature T N # Number of exponential terms bath = Boson_DrudeLorentz_Pade(Vs, Δ, W, kT, N - 1) ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
5352
# [Bosonic Bath](@id doc-Bosonic-Bath) ## [Overview](@id Bosonic-Bath-Overview) The [`BosonBath`](@ref) object describes the interaction between the system (``s``) and a exterior bosonic environment (``b``), which can be modeled by ```math H_{sb}=V_{s}\sum_k g_k (b_k + b_k^\dagger), ``` in terms of the coupling strength ``g_k`` and the annihilation (creation) operator ``b_k (b_k^\dagger)`` associated to the ``k``-th mode of the bosonic environment. Here, ``V_s`` refers to the system-interaction operator. In particular, ``V_s`` must be a Hermitian operator which can act on **both bosonic and fermionic systems degree of freedom**. In the fermionic system case, ``V_s`` must have even parity to be compatible with charge conservation. The effects of a bosonic environment (initially in thermal equilibrium and linearly coupled to the system) are completely encoded in the two-time correlation functions, namely ```math C(t_1, t_2) =\frac{1}{2\pi}\int_{0}^{\infty} d\omega J(\omega)\left[n(\omega)e^{i\omega (t_1-t_2)}+(n(\omega)+1)e^{-i\omega (t_1-t_2)}\right], ``` where ``J(\omega)=2\pi\Sigma_k |g_k|^2 \delta(\omega-\omega_k)`` is the spectral density of the bath and ``n(\omega)=\{\exp(\omega/k_B T)-1\}^{-1}`` represents the Bose-Einstein distribution. A more practical representation can be found by expressing the correlation function as a sum of exponential terms ([`Exponent`](@ref)), namely ```math C(t_1, t_2)=\sum_i \eta_i e^{-\gamma_i (t_1-t_2)}. ``` This allows us to define an iterative procedure which leads to the hierarchical equations of motion (HEOM). ## Construct BosonBath (with real and imaginary parts are combined) One can construct the [`BosonBath`](@ref) object with the coupling operator `Vs::QuantumObject` and the two lists `η::AbstractVector` and `γ::AbstractVector` which corresponds to the exponential terms ``\{\eta_i\}_i`` and ``\{\gamma_i\}_i``, respectively. ```julia bath = BosonBath(Vs, η, γ) ``` !!! warning "Warning" Here, the length of `η` and `γ` should be the same. ## Construct BosonBath (with real and imaginary parts are separated) When ``\gamma_i \neq \gamma_i^*``, a closed form for the HEOM can be obtained by further decomposing ``C(t_1, t_2)`` into its real (R) and imaginary (I) parts as ```math C(t_1, t_2)=\sum_{u=\textrm{R},\textrm{I}}(\delta_{u, \textrm{R}} + i\delta_{u, \textrm{I}})C^{u}(t_1, t_2) ``` where ``\delta`` is the Kronecker delta function and ``C^{u}(t_1, t_2)=\sum_i \eta_i^u \exp(-\gamma_i^u (t_1-t_2))`` In this case, the [`BosonBath`](@ref) object can be constructed by the following method: ```julia bath = BosonBath(Vs, η_real, γ_real, η_imag, γ_imag) ``` !!! warning "Warning" Here, the length of `η_real` and `γ_real` should be the same. Also, the length of `η_imag` and `γ_imag` should be the same. Here, `η_real::AbstractVector`, `γ_real::AbstractVector`, `η_imag::AbstractVector` and `γ_imag::AbstractVector` correspond to the exponential terms ``\{\eta_i^{\textrm{R}}\}_i``, ``\{\gamma_i^{\textrm{R}}\}_i``, ``\{\eta_i^{\textrm{I}}\}_i`` and ``\{\gamma_i^{\textrm{I}}\}_i``, respectively. !!! note "Note" Instead of analytically solving the correlation function ``C(t_1, t_2)`` to obtain a sum of exponential terms, one can also use the built-in functions (for different spectral densities ``J(\omega)`` and spectral decomposition methods, which have been analytically solved by the developers already). See the other categories of the Bosonic Bath in the sidebar for more details. ## Print Bosonic Bath One can check the information of the [`BosonBath`](@ref) by the `print` function, for example: ```julia print(bath) ``` ``` BosonBath object with 4 exponential-expansion terms ``` ## Calculate the correlation function To check whether the exponential terms in the [`BosonBath`](@ref) is correct or not, one can call [`C(bath::BosonBath, tlist::AbstractVector)`](@ref) to calculate the correlation function ``C(t)``, where ``t=t_1-t_2``: ```julia c_list = C(bath, tlist) ``` Here, `c_list` is a list which contains the value of ``C(t)`` corresponds to the given time series `tlist`. ## Exponent `HierarchicalEOM.jl` also supports users to access the specific exponential term with brakets `[]`. This returns an [`Exponent`](@ref) object, which contains the corresponding value of ``\eta_i`` and ``\gamma_i``: ```julia e = bath[2] # the 2nd-term print(e) ``` ``` Bath Exponent with types = "bRI", η = 1.5922874021206546e-6 + 0.0im, γ = 0.3141645167860635 + 0.0im. ``` The different types of the (bosonic-bath) [`Exponent`](@ref): - `"bR"` : from real part of bosonic correlation function ``C^{u=\textrm{R}}(t_1, t_2)`` - `"bI"` : from imaginary part of bosonic correlation function ``C^{u=\textrm{I}}(t_1, t_2)`` - `"bRI"` : from combined (real and imaginary part) bosonic bath correlation function ``C(t_1, t_2)`` One can even obtain the [`Exponent`](@ref) with iterative method: ```julia for e in bath println(e) end ``` ``` Bath Exponent with types = "bRI", η = 4.995832638723504e-5 - 2.5e-6im, γ = 0.005 + 0.0im. Bath Exponent with types = "bRI", η = 1.5922874021206546e-6 + 0.0im, γ = 0.3141645167860635 + 0.0im. Bath Exponent with types = "bRI", η = 1.0039844180003819e-6 + 0.0im, γ = 0.6479143347831898 + 0.0im. Bath Exponent with types = "bRI", η = 3.1005439801387293e-6 + 0.0im, γ = 1.8059644711829272 + 0.0im. ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
4362
# [Bosonic Bath (under rotating wave approximation)](@id doc-Bosonic-Bath-RWA) ## [Overview](@id Bosonic-Bath-RWA-Overview) This describes the interaction between the system (``s``) and a exterior bosonic environment (``b``) under the rotating wave approximation (RWA), which can be modeled by ```math H_{sb}=\sum_k g_k b_k^\dagger a_s + g_k^* b_k a_s^\dagger, ``` where ``g_k`` is the coupling strength and ``b_k (b_k^\dagger)`` is the annihilation (creation) operator for the ``k``-th mode of the bosonic environment. Here, ``a_s`` refers to the system annihilation operator. The effects of a bosonic environment (initially in thermal equilibrium, linearly coupled to the system, and under the rotating wave approximation) are completely encoded in the two-time correlation functions, namely ```math C^{\nu}(t_{1},t_{2}) =\frac{1}{2\pi}\int_{0}^{\infty} d\omega J(\omega)\left[\delta_{\nu,-1}+ n(\omega) \right]e^{\nu i\omega (t_{1}-t_{2})}. ``` where ``J(\omega)=2\pi\Sigma_k |g_k|^2 \delta(\omega-\omega_k)`` is the spectral density of the bath and ``n(\omega)=\{\exp[\omega/k_B T]-1\}^{-1}`` represents the Bose-Einstein distribution. Here, ``\nu=+`` and ``\nu=-`` denotes the absorption and emission process of the bosonic system, respectively. A more practical representation can be found by expressing the correlation function as a sum of exponential terms ([`Exponent`](@ref)), namely ```math C^{\nu}(t_1, t_2)=\sum_i \eta_i^{\nu} e^{-\gamma_i^{\nu} (t_1-t_2)}. ``` This allows us to define an iterative procedure which leads to the hierarchical equations of motion (HEOM). ## Construct BosonBath (RWA) One can construct the [`BosonBath`](@ref) object under RWA by calling the function [`BosonBathRWA`](@ref) together with the following parameters: system annihilation operator `a_s::QuantumObject` and the four lists `η_absorb::AbstractVector`, `γ_absorb::AbstractVector`, `η_emit::AbstractVector` and `γ_emit::AbstractVector` which correspond to the exponential terms ``\{\eta_i^{+}\}_i``, ``\{\gamma_i^{+}\}_i``, ``\{\eta_i^{-}\}_i`` and ``\{\gamma_i^{-}\}_i``, respectively. ```julia bath = BosonBathRWA(a_s, η_absorb, γ_absorb, η_emit, γ_emit) ``` !!! warning "Warning" Here, the length of the four lists (`η_absorb`, `γ_absorb`, `η_emit` and `γ_emit`) should all be the same. Also, all the elements in `γ_absorb` should be complex conjugate of the corresponding elements in `γ_emit`. ## Print Bosonic Bath One can check the information of the [`BosonBath`](@ref) by the `print` function, for example: ```julia print(bath) ``` ``` BosonBath object with 4 exponential-expansion terms ``` Note that [`BosonBath`](@ref) under RWA always have even number of exponential terms (half for ``C^{\nu=+}`` and half for ``C^{\nu=-}``) ## Calculate the correlation function To check whether the exponential terms in the [`FermionBath`](@ref) is correct or not, one can call [`C(bath::BosonBath, tlist::AbstractVector)`](@ref) to calculate the correlation function ``C(t)``, where ``t=t_1-t_2``: ```julia cp_list, cm_list = C(bath, tlist) ``` Here, `cp_list` and `cm_list` are the lists which contain the value of ``C^{\nu=+}(t)`` and ``C^{\nu=-}(t)`` correspond to the given time series `tlist`, respectively. ## Exponent `HierarchicalEOM.jl` also supports users to access the specific exponential term with brakets `[]`. This returns an [`Exponent`](@ref) object, which contains the corresponding value of ``\eta_i^\nu`` and ``\gamma_i^\nu``: ```julia e = bath[2] # the 2nd-term print(e) ``` ``` Bath Exponent with types = "bA", η = 0.0 + 3.4090909090909113e-6im, γ = 0.1732050807568877 - 0.005im. ``` The different types of the (bosonic-bath under RWA) [`Exponent`](@ref): - `"bA"` : from absorption bosonic correlation function ``C^{\nu=+}(t_1, t_2)`` - `"bE"` : from emission bosonic correlation function ``C^{\nu=-}(t_1, t_2)`` One can even obtain the [`Exponent`](@ref) with iterative method: ```julia for e in bath println(e) end ``` ``` Bath Exponent with types = "bA", η = 6.25e-6 - 3.4090909090909113e-6im, γ = 0.05 - 0.005im. Bath Exponent with types = "bA", η = 0.0 + 3.4090909090909113e-6im, γ = 0.1732050807568877 - 0.005im. Bath Exponent with types = "bE", η = 6.25e-6 - 3.4090909090909113e-6im, γ = 0.05 + 0.005im. Bath Exponent with types = "bE", η = 0.0 + 3.4090909090909113e-6im, γ = 0.1732050807568877 + 0.005im. ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
2517
# [Lorentz Spectral Density](@id doc-Fermion-Lorentz) ```math J(\omega)=\frac{\Gamma W^2}{(\omega-\mu)^2+W^2} ``` Here, ``\Gamma`` represents the coupling strength between system and the fermionic environment with chemical potential ``\mu`` and band-width ``W``. ## Matsubara Expansion With Matsubara Expansion, the correlation function can be analytically solved and expressed as follows: ```math C^{\nu}(t_1, t_2)=\sum_{l=1}^{\infty} \eta_l^\nu \exp(-\gamma_l^\nu (t_1-t_2)) ``` with ```math \begin{aligned} \gamma_{1}^{\nu} &= W-\nu i \mu,\\ \eta_{1}^{\nu} &= \frac{\Gamma W}{2} f\left(\frac{iW}{k_B T}\right),\\ \gamma_{l\neq 1}^{\nu} &= \zeta_l k_B T - \nu i \mu,\\ \eta_{l\neq 1}^{\nu} &= -i k_B T \cdot \frac{\Gamma W^2}{-(\zeta_l k_B T)^2+W^2},\\ f(x) &= \{\exp(x) + 1\}^{-1}, \end{aligned} ``` where ``\zeta_l=(2 l - 1)\pi``. This can be constructed by the built-in function [`Fermion_Lorentz_Matsubara`](@ref): ```julia ds # coupling operator Γ # coupling strength μ # chemical potential of the environment W # band-width of the environment kT # the product of the Boltzmann constant k and the absolute temperature T N # Number of exponential terms for each correlation functions (C^{+} and C^{-}) bath = Fermion_Lorentz_Matsubara(ds, Γ, μ, W, kT, N - 1) ``` ## Padé Expansion With Padé Expansion, the correlation function can be analytically solved and expressed as the following exponential terms: ```math C^\nu(t_1, t_2)=\sum_{l=1}^{\infty} \eta_l^\nu \exp(-\gamma_l^\nu (t_1-t_2)) ``` with ```math \begin{aligned} \gamma_{1}^{\nu} &= W-\nu i \mu,\\ \eta_{1}^{\nu} &= \frac{\Gamma W}{2} f\left(\frac{iW}{k_B T}\right),\\ \gamma_{l\neq 1}^{\nu} &= \zeta_l k_B T - \nu i \mu,\\ \eta_{l\neq 1}^{\nu} &= -i \kappa_l k_B T \cdot \frac{\Gamma W^2}{-(\zeta_l k_B T)^2+W^2},\\ f(x) &= \frac{1}{2}-\sum_{l=2}^{N} \frac{2\kappa_l x}{x^2+\zeta_l^2}, \end{aligned} ``` where the parameters ``\kappa_l`` and ``\zeta_l`` are described in [J. Chem. Phys. 134, 244106 (2011)](https://doi.org/10.1063/1.3602466) and ``N`` represents the number of exponential terms for ``C^{\nu=\pm}``. This can be constructed by the built-in function [`Fermion_Lorentz_Pade`](@ref): ```julia ds # coupling operator Γ # coupling strength μ # chemical potential of the environment W # band-width of the environment kT # the product of the Boltzmann constant k and the absolute temperature T N # Number of exponential terms for each correlation functions (C^{+} and C^{-}) bath = Fermion_Lorentz_Pade(ds, Γ, μ, W, kT, N - 1) ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
4699
# [Fermionic Bath](@id doc-Fermionic-Bath) ## [Overview](@id Fermionic-Bath-Overview) The [`FermionBath`](@ref) object describes the interaction between the system (``s``) and a exterior fermionic environment (``f``), which can be modeled by ```math H_{sf}=\sum_k g_k c_k^\dagger d_s + g_k^* c_k d_s^\dagger, ``` where ``g_k`` is the coupling strength and ``c_k (c_k^\dagger)`` annihilates (creates) a fermion in the ``k``-th state of the fermionic environment. Here, ``d_s`` refers to the system-interaction operator and should be an odd-parity operator destroying a fermion in the system. The effects of a fermionic environment (initially in thermal equilibrium and linearly coupled to the system) are completely encoded in the two-time correlation functions, namely ```math C^{\nu}(t_{1},t_{2}) =\frac{1}{2\pi}\int_{-\infty}^{\infty} d\omega J(\omega)\left[\frac{1-\nu}{2}+\nu n(\omega) \right]e^{\nu i\omega (t_{1}-t_{2})}. ``` where ``J(\omega)=2\pi\Sigma_k |g_k|^2 \delta(\omega-\omega_k)`` is the spectral density of the bath and ``n(\omega)=\{\exp[(\omega-\mu)/k_B T]+1\}^{-1}`` represents the Fermi-Dirac distribution (with chemical potential ``\mu``). Here, ``\nu=+`` and ``\nu=-`` denotes the absorption and emission process of the fermionic system, respectively. A more practical representation can be found by expressing the correlation function as a sum of exponential terms ([`Exponent`](@ref)), namely ```math C^{\nu}(t_1, t_2)=\sum_i \eta_i^{\nu} e^{-\gamma_i^{\nu} (t_1-t_2)}. ``` This allows us to define an iterative procedure which leads to the hierarchical equations of motion (HEOM). ## Construct FermionBath One can construct the [`FermionBath`](@ref) object with the system annihilation operator `ds::QuantumObject` and the four lists `η_absorb::AbstractVector`, `γ_absorb::AbstractVector`, `η_emit::AbstractVector` and `γ_emit::AbstractVector` which correspond to the exponential terms ``\{\eta_i^{+}\}_i``, ``\{\gamma_i^{+}\}_i``, ``\{\eta_i^{-}\}_i`` and ``\{\gamma_i^{-}\}_i``, respectively. ```julia bath = FermionBath(ds, η_absorb, γ_absorb, η_emit, γ_emit) ``` !!! warning "Warning" Here, the length of the four lists (`η_absorb`, `γ_absorb`, `η_emit` and `γ_emit`) should all be the same. Also, all the elements in `γ_absorb` should be complex conjugate of the corresponding elements in `γ_emit`. !!! note "Note" Instead of analytically solving the correlation function ``C^{\nu=\pm}(t_1, t_2)`` to obtain a sum of exponential terms, one can also use the built-in functions (for different spectral densities ``J(\omega)`` and spectral decomposition methods, which have been analytically solved by the developers already). See the other categories of the Fermionic Bath in the sidebar for more details. ## Print Fermionic Bath One can check the information of the [`FermionBath`](@ref) by the `print` function, for example: ```julia print(bath) ``` ``` FermionBath object with 4 exponential-expansion terms ``` Note that [`FermionBath`](@ref) always have even number of exponential terms (half for ``C^{\nu=+}`` and half for ``C^{\nu=-}``) ## Calculate the correlation function To check whether the exponential terms in the [`FermionBath`](@ref) is correct or not, one can call [`C(bath::FermionBath, tlist::AbstractVector)`](@ref) to calculate the correlation function ``C(t)``, where ``t=t_1-t_2``: ```julia cp_list, cm_list = C(bath, tlist) ``` Here, `cp_list` and `cm_list` are the lists which contain the value of ``C^{\nu=+}(t)`` and ``C^{\nu=-}(t)`` correspond to the given time series `tlist`, respectively. ## Exponent `HierarchicalEOM.jl` also supports users to access the specific exponential term with brakets `[]`. This returns an [`Exponent`](@ref) object, which contains the corresponding value of ``\eta_i^\nu`` and ``\gamma_i^\nu``: ```julia e = bath[2] # the 2nd-term print(e) ``` ``` Bath Exponent with types = "fA", η = 0.0 + 3.4090909090909113e-6im, γ = 0.1732050807568877 - 0.005im. ``` The different types of the (fermionic-bath) [`Exponent`](@ref): - `"fA"` : from absorption fermionic correlation function ``C^{\nu=+}(t_1, t_2)`` - `"fE"` : from emission fermionic correlation function ``C^{\nu=-}(t_1, t_2)`` One can even obtain the [`Exponent`](@ref) with iterative method: ```julia for e in bath println(e) end ``` ``` Bath Exponent with types = "fA", η = 6.25e-6 - 3.4090909090909113e-6im, γ = 0.05 - 0.005im. Bath Exponent with types = "fA", η = 0.0 + 3.4090909090909113e-6im, γ = 0.1732050807568877 - 0.005im. Bath Exponent with types = "fE", η = 6.25e-6 - 3.4090909090909113e-6im, γ = 0.05 + 0.005im. Bath Exponent with types = "fE", η = 0.0 + 3.4090909090909113e-6im, γ = 0.1732050807568877 + 0.005im. ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
3316
# [Extension for CUDA.jl](@id doc-ext-CUDA) This is an extension to support GPU ([`CUDA.jl`](https://github.com/JuliaGPU/CUDA.jl)) acceleration for solving the [time evolution](@ref doc-Time-Evolution) and [spectra](@ref doc-Spectrum). This improves the execution time and memory usage especially when the HEOMLS matrix is super large. !!! compat "Compat" The described feature requires `Julia 1.9+`. The functions of calculating [time evolution](@ref doc-Time-Evolution) (only supports ODE method with time-independent system Hamiltonian) and [spectra](@ref doc-Spectrum) will automatically choose to solve on CPU or GPU depend on the type of the sparse matrix in `M::AbstractHEOMLSMatrix` objects (i.e., the type of the field `M.data`). ```julia typeof(M.data) <: SparseMatrixCSC # solve on CPU typeof(M.data) <: CuSparseMatrixCSC # solve on GPU ``` Therefore, we wrapped several functions in `CUDA` and `CUDA.CUSPARSE` in order to return a new HEOMLS-matrix-type object with `M.data` is in the type of `CuSparseMatrix`, and also change the element type into `ComplexF32` and `Int32` (since GPU performs better in this type). The functions are listed as follows: - `cu(M::AbstractHEOMLSMatrix)` : Translate `M.data` into the type `CuSparseMatrixCSC{ComplexF32, Int32}` - `CuSparseMatrixCSC(M::AbstractHEOMLSMatrix)` : Translate `M.data` into the type `CuSparseMatrixCSC{ComplexF32, Int32}` ### Demonstration The extension will be automatically loaded if user imports the package `CUDA.jl` : ```julia using HierarchicalEOM using LinearSolve # to change the solver for better GPU performance using CUDA CUDA.allowscalar(false) # Avoid unexpected scalar indexing ``` ### Setup Here, we demonstrate this extension by using the example of [the single-impurity Anderson model](@ref exp-SIAM). ```julia ϵ = -5 U = 10 Γ = 2 μ = 0 W = 10 kT = 0.5 N = 5 tier = 3 tlist = 0:0.1:10 ωlist = -10:1:10 σm = [0 1; 0 0] σz = [1 0; 0 -1] II = [1 0; 0 1] d_up = kron( σm, II) d_dn = kron(-1 * σz, σm) ρ0 = kron([1 0; 0 0], [1 0; 0 0]) Hsys = ϵ * (d_up' * d_up + d_dn' * d_dn) + U * (d_up' * d_up * d_dn' * d_dn) bath_up = Fermion_Lorentz_Pade(d_up, Γ, μ, W, kT, N) bath_dn = Fermion_Lorentz_Pade(d_dn, Γ, μ, W, kT, N) bath_list = [bath_up, bath_dn] # even HEOMLS matrix M_even_cpu = M_Fermion(Hsys, tier, bath_list) M_even_gpu = cu(M_even_cpu) # odd HEOMLS matrix M_odd_cpu = M_Fermion(Hsys, tier, bath_list, ODD) M_odd_gpu = cu(M_odd_cpu) # solve steady state with CPU ados_ss = steadystate(M_even_cpu); ``` !!! note "Note" This extension does not support for solving [stationary state](@ref doc-Stationary-State) on GPU since it is not efficient and might get wrong solutions. If you really want to obtain the stationary state with GPU, you can repeatedly solve the [time evolution](@ref doc-Time-Evolution) until you find it. ### Solving time evolution with CPU ```julia ados_list_cpu = HEOMsolve(M_even_cpu, ρ0, tlist) ``` ### Solving time evolution with GPU ```julia ados_list_gpu = HEOMsolve(M_even_gpu, ρ0, tlist) ``` ### Solving Spectrum with CPU ```julia dos_cpu = DensityOfStates(M_odd_cpu, ados_ss, d_up, ωlist) ``` ### Solving Spectrum with GPU ```julia dos_gpu = DensityOfStates(M_odd_gpu, ados_ss, d_up, ωlist; solver=KrylovJL_BICGSTAB(rtol=1f-10, atol=1f-12)) ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
4720
# [Hierarchical Equations of Motion Liouvillian Superoperator (HEOMLS) Matrix](@id doc-HEOMLS-Matrix) ## Overview The hierarchical equations of motion Liouvillian superoperator (HEOMLS) ``\hat{\mathcal{M}}`` characterizes the dynamics in the full [auxiliary density operators (ADOs)](@ref doc-ADOs) space, namely ```math \partial_{t}\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t)=\hat{\mathcal{M}}\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}(t) ``` and it can, numerically, be expressed as a matrix. In `HierarchicalEOM.jl`, all different types of HEOMLS ``\hat{\mathcal{M}}`` are subtype of `AbstractHEOMLSMatrix`. The HEOMLS ``\hat{\mathcal{M}}`` not only characterizes the bare system dynamics (based on system Hamiltonian), but it also encodes the system-and-multiple-bosonic-baths and system-and-multiple-fermionic-baths interactions based on [Bosonic Bath](@ref doc-Bosonic-Bath) and [Fermionic Bath](@ref doc-Fermionic-Bath), respectively. For a specific ``m``th-level-bosonic-and-``n``th-level-fermionic auxiliary density operator ``\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}``, it will be coupled to the following ADOs through ``\hat{\mathcal{M}}``: - ``(m+1)``th-level-bosonic-and-``n``th-level-fermionic ADOs - ``(m-1)``th-level-bosonic-and-``n``th-level-fermionic ADOs - ``m``th-level-bosonic-and-``(n+1)``th-level-fermionic ADOs - ``m``th-level-bosonic-and-``(n-1)``th-level-fermionic ADOs and thus forms the two-fold hierarchy relations. See our paper for more details. In practice, the size of the matrix ``\hat{\mathcal{M}}`` must be finite and the hierarchical equations must be truncated at a suitable bosonic-level (``m_\textrm{max}``) and fermionic-level (``n_\textrm{max}``). These truncation levels (tiers) must be given when constructing ``\hat{\mathcal{M}}``. ```julia Hs::QuantumObject # system Hamiltonian Bbath::BosonBath # bosonic bath object Fbath::FermionBath # fermionic bath object Btier::Int # bosonic truncation level Ftier::Int # fermionic truncation level M = M_Boson(Hs, Btier, Bbath) M = M_Fermion(Hs, Ftier, Fbath) M = M_Boson_Fermion(Hs, Btier, Ftier, Bbath, Fbath) ``` ## [Importance Value and Threshold](@id doc-Importance-Value-and-Threshold) The main computational complexity can be quantified by the total number of [auxiliary density operators (ADOs)](@ref doc-ADOs) because it directly affects the size of ``\hat{\mathcal{M}}``. The computational effort can be further optimized by associating an **importance value** ``\mathcal{I}`` to each ADO and then discarding all the ADOs (in the second and higher levels) whose importance value is smaller than a threshold value ``\mathcal{I}_\textrm{th}``. The importance value for a given ADO : ``\mathcal{I}\left(\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}\right)`` is determined by its corresponding exponential terms of bath correlation function [see [Phys. Rev. B 88, 235426 (2013)](https://doi.org/10.1103/PhysRevB.88.235426) and [Phys. Rev. B 103, 235413 (2021)](https://doi.org/10.1103/PhysRevB.103.235413)]. This allows us to only consider the ADOs which affects the dynamics more, and thus, reduce the size of ``\hat{\mathcal{M}}``. Also see our paper [ [Commun. Phys. 6, 313 (2023)](https://doi.org/10.1038/s42005-023-01427-2) ] for more details. When you specify a threshold value ``\mathcal{I}_\textrm{th}`` with the parameter `threshold` to construct ``\hat{\mathcal{M}}``, we will remain all the ADOs where their hierarchy levels ``(m,n)\in\{(0,0), (0,1), (1,0), (1,1)\}``, and all the other high-level ADOs may be neglected if ``\mathcal{I}\left(\rho^{(m,n,p)}_{\textbf{j} \vert \textbf{q}}\right) < \mathcal{I}_\textrm{th}``. ```julia Hs::QuantumObject # system Hamiltonian Bbath::BosonBath # bosonic bath object Fbath::FermionBath # fermionic bath object Btier::Int # bosonic truncation level Ftier::Int # fermionic truncation level M = M_Boson(Hs, Btier, Bbath; threshold=1e-7) M = M_Fermion(Hs, Ftier, Fbath; threshold=1e-7) M = M_Boson_Fermion(Hs, Btier, Ftier, Bbath, Fbath; threshold=1e-7) ``` !!! note "Default value of importance threshold" The full hierarchical equations can be recovered in the limiting case ``\mathcal{I}_\textrm{th}\rightarrow 0``, which is the default value of the parameter : `threshold=0.0`. This means that all of the ADOs will be taken into account by default. ## Methods All of the HEOMLS matrices supports the following two `Base` Functions : - `size(M::AbstractHEOMLSMatrix)` : Returns the size of the HEOMLS matrix. - Bracket operator `[i,j]` : Returns the `(i, j)`-element(s) in the HEOMLS matrix. ```julia M::AbstractHEOMLSMatrix m, n = size(M) M[10, 12] M[2:4, 2:4] M[1,:] M[:,2] ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
2127
# [HEOMLS Matrix for Bosonic Baths](@id doc-M_Boson) The HEOM Liouvillian superoperator matrix [`struct M_Boson <: AbstractHEOMLSMatrix`](@ref M_Boson) which describes the interactions between the system and multiple [Bosonic baths](@ref doc-Bosonic-Bath). ## Construct Matrix To construct the HEOM matrix in this case, one can call [`M_Boson(Hsys, tier, Bath, parity)`](@ref M_Boson) with the following parameters: *args* (Arguments) - `Hsys` : The time-independent system Hamiltonian - `tier::Int` : the tier (cutoff level) for the bosonic bath - `Bath::Vector{BosonBath}` : objects for different [bosonic baths](@ref doc-Bosonic-Bath) - `parity::AbstractParity` : the [parity](@ref doc-Parity) label of the operator which HEOMLS is acting on. Defaults to `EVEN`. *kwargs* (Keyword Arguments) - `threshold::Real` : The threshold of the [importance value](@ref doc-Importance-Value-and-Threshold). Defaults to `0.0`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. For example: ```julia Hs::QuantumObject # system Hamiltonian tier = 3 Bath::BosonBath # create HEOMLS matrix in both EVEN and ODD parity M_even = M_Boson(Hs, tier, Bath) M_odd = M_Boson(Hs, tier, Bath, ODD) ``` ## Fields The fields of the structure [`M_Boson`](@ref) are as follows: - `data` : the sparse matrix of HEOM Liouvillian superoperator - `tier` : the tier (cutoff level) for the bosonic hierarchy - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of total [ADOs](@ref doc-ADOs) - `sup_dim` : the dimension of system superoperator - `parity` : the [parity](@ref doc-Parity) label of the operator which HEOMLS is acting on. - `bath::Vector{BosonBath}` : the vector which stores all [`BosonBath`](@ref doc-Bosonic-Bath) objects - `hierarchy::HierarchyDict`: the object which contains all [dictionaries](@ref doc-Hierarchy-Dictionary) for boson-bath-ADOs hierarchy. One can obtain the value of each fields as follows: ```julia M::M_Boson M.data M.tier M.dims M.N M.sup_dim M.parity M.bath M.hierarchy ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
2696
# [HEOMLS Matrix for Hybrid (Bosonic and Fermionic) Baths](@id doc-M_Boson_Fermion) The HEOM Liouvillian superoperator matrix [`struct M_Boson_Fermion <: AbstractHEOMLSMatrix`](@ref M_Boson_Fermion) which describes the system simultaneously interacts with multiple [Bosonic baths](@ref doc-Bosonic-Bath) and [Fermionic baths](@ref doc-Fermionic-Bath). ## Construct Matrix To construct the HEOM matrix in this case, one can call [`M_Boson_Fermion(Hsys, Btier, Ftier, Bbath, Fbath, parity)`](@ref M_Boson_Fermion) with the following parameters: *args* (Arguments) - `Hsys` : The time-independent system Hamiltonian - `Btier::Int` : the tier (cutoff level) for the bosonic bath - `Ftier::Int` : the tier (cutoff level) for the fermionic bath - `Bbath::Vector{BosonBath}` : objects for different [bosonic baths](@ref doc-Bosonic-Bath) - `Fbath::Vector{FermionBath}` : objects for different [fermionic baths](@ref doc-Fermionic-Bath) - `parity::AbstractParity` : the [parity](@ref doc-Parity) label of the operator which HEOMLS is acting on. Defaults to `EVEN`. *kwargs* (Keyword Arguments) - `threshold::Real` : The threshold of the [importance value](@ref doc-Importance-Value-and-Threshold). Defaults to `0.0`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. For example: ```julia Hs::QuantumObject # system Hamiltonian Btier = 3 Ftier = 4 Bbath::BosonBath Fbath::FermionBath # create HEOMLS matrix in both EVEN and ODD parity M_even = M_Fermion(Hs, Btier, Ftier, Bbath, Fbath) M_odd = M_Fermion(Hs, Btier, Ftier, Bbath, Fbath, ODD) ``` ## Fields The fields of the structure [`M_Boson_Fermion`](@ref) are as follows: - `data` : the sparse matrix of HEOM Liouvillian superoperator - `Btier` : the tier (cutoff level) for bosonic hierarchy - `Ftier` : the tier (cutoff level) for fermionic hierarchy - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of total [ADOs](@ref doc-ADOs) - `sup_dim` : the dimension of system superoperator - `parity` : the [parity](@ref doc-Parity) label of the operator which HEOMLS is acting on. - `Bbath::Vector{BosonBath}` : the vector which stores all [`BosonBath`](@ref doc-Bosonic-Bath) objects - `Fbath::Vector{FermionBath}` : the vector which stores all [`FermionBath`](@ref doc-Fermionic-Bath) objects - `hierarchy::MixHierarchyDict`: the object which contains all [dictionaries](@ref doc-Hierarchy-Dictionary) for mixed-bath-ADOs hierarchy. One can obtain the value of each fields as follows: ```julia M::M_Boson_Fermion M.data M.Btier M.Ftier M.dims M.N M.sup_dim M.parity M.Bbath M.Fbath M.hierarchy ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
2171
# [HEOMLS Matrix for Fermionic Baths](@id doc-M_Fermion) The HEOM Liouvillian superoperator matrix [`struct M_Fermion <: AbstractHEOMLSMatrix`](@ref M_Fermion) which describes the interactions between the system and multiple [Fermionic baths](@ref doc-Fermionic-Bath). ## Construct Matrix To construct the HEOM matrix in this case, one can call [`M_Fermion(Hsys, tier, Bath, parity)`](@ref M_Fermion) with the following parameters: *args* (Arguments) - `Hsys` : The time-independent system Hamiltonian - `tier::Int` : the tier (cutoff level) for the fermionic bath - `Bath::Vector{FermionBath}` : objects for different [fermionic baths](@ref doc-Fermionic-Bath) - `parity::AbstractParity` : the [parity](@ref doc-Parity) label of the operator which HEOMLS is acting on. Defaults to `EVEN`. *kwargs* (Keyword Arguments) - `threshold::Real` : The threshold of the [importance value](@ref doc-Importance-Value-and-Threshold). Defaults to `0.0`. - `verbose::Bool` : To display verbose output and progress bar during the process or not. Defaults to `true`. For example: ```julia Hs::QuantumObject # system Hamiltonian tier = 3 Bath::FermionBath # create HEOMLS matrix in both EVEN and ODD parity M_even = M_Fermion(Hs, tier, Bath) M_odd = M_Fermion(Hs, tier, Bath, ODD) ``` ## Fields The fields of the structure [`M_Fermion`](@ref) are as follows: - `data` : the sparse matrix of HEOM Liouvillian superoperator - `tier` : the tier (cutoff level) for the fermionic hierarchy - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of total [ADOs](@ref doc-ADOs) - `sup_dim` : the dimension of system superoperator - `parity` : the [parity](@ref doc-Parity) label of the operator which HEOMLS is acting on. - `bath::Vector{FermionBath}` : the vector which stores all [`FermionBath`](@ref doc-Fermionic-Bath) objects - `hierarchy::HierarchyDict`: the object which contains all [dictionaries](@ref doc-Hierarchy-Dictionary) for fermion-bath-ADOs hierarchy. One can obtain the value of each fields as follows: ```julia M::M_Fermion M.data M.tier M.dims M.N M.sup_dim M.parity M.bath M.hierarchy ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
3601
# [HEOMLS Matrix for Master Equation](@id doc-Master-Equation) `HierarchicalEOM.jl` allows users to further add the Lindbladian (superoperator) on any types (`AbstractHEOMLSMatrix`) of HEOM Liouvillian superoperator ``\hat{\mathcal{M}}``. The Lindbladian describes the dissipative interaction between the system and extra environment. This method is more efficient than the full HEOM when some of the baths are weakly coupled to the system since it does not require any extra [ADOs](@ref doc-ADOs) space to describe the dynamics and hence reduces the size of ``\hat{\mathcal{M}}``. ## Bosonic Dissipative Env. If the system is weakly coupled to an extra bosonic environment, the explicit form of the Lindbladian is given by ```math \hat{\mathcal{D}}(J)\Big[\cdot\Big]=J\left[\cdot\right]J^\dagger-\frac{1}{2}\Big[J^\dagger J, \cdot\Big]_+, ``` where ``J\equiv \sqrt{\gamma}V`` is the jump operator, ``V`` describes the dissipative part (operator) of the dynamics, ``\gamma`` represents a non-negative damping rate and ``[\cdot, \cdot]_+`` stands for anti-commutator. !!! note "Note" The system here can be either bosonic or fermionic. However, if ``V`` is acting on fermionic systems, it should be even-parity to be compatible with charge conservation. One can add the Lindbladian ``\hat{\mathcal{D}}`` of bosonic environment to the HEOM Liouvillian superoperator ``\hat{\mathcal{M}}`` by calling [`addBosonDissipator(M::AbstractHEOMLSMatrix, jumpOP)`](@ref addBosonDissipator) with the parameters: - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model - `jumpOP::AbstractVector` : The list of collapse (jump) operators ``\{J_i\}_i`` to add. Defaults to empty vector `[]`. Finally, the function returns a new ``\hat{\mathcal{M}}`` with the same type: ```julia M0::AbstractHEOMLSMatrix J = [J1, J2, ..., Jn] # jump operators M1 = addBosonDissipator(M0, J) ``` ## Fermionic Dissipative Env. If the fermionic system is weakly coupled to an extra fermionic environment, the explicit form of the Lindbladian acting on `EVEN`-parity operators is given by ```math \hat{\mathcal{D}}_{\textrm{even}}(J)\Big[\cdot\Big]=J\left[\cdot\right]J^\dagger-\frac{1}{2}\Big[J^\dagger J, \cdot\Big]_+, ``` where ``J\equiv \sqrt{\gamma}V`` is the jump operator, ``V`` describes the dissipative part (operator) of the dynamics, ``\gamma`` represents a non-negative damping rate and ``[\cdot, \cdot]_+`` stands for anti-commutator. For acting on `ODD`-parity operators, the explicit form of the Lindbladian is given by ```math \hat{\mathcal{D}}_{\textrm{odd}}(J)\Big[\cdot\Big]=-J\left[\cdot\right]J^\dagger-\frac{1}{2}\Big[J^\dagger J, \cdot\Big]_+, ``` One can add the Lindbladian ``\hat{\mathcal{D}}`` of fermionic environment to the HEOM Liouvillian superoperator ``\hat{\mathcal{M}}`` by calling [`addFermionDissipator(M::AbstractHEOMLSMatrix, jumpOP)`](@ref addFermionDissipator) with the parameters: - `M::AbstractHEOMLSMatrix` : the matrix given from HEOM model - `jumpOP::AbstractVector` : The list of collapse (jump) operators ``\{J_i\}_i`` to add. Defaults to empty vector `[]`. !!! note "Parity" The parity of the dissipator will be automatically determined by the [`parity`](@ref doc-Parity) of the given HEOMLS matrix `M`. Finally, the function returns a new ``\hat{\mathcal{M}}`` with the same type and parity: ```julia M0_even::AbstractHEOMLSMatrix # constructed with EVEN-parity M0_odd::AbstractHEOMLSMatrix # constructed with ODD-parity J = [J1, J2, ..., Jn] # jump operators M1_even = addFermionDissipator(M0_even, J) M1_odd = addFermionDissipator(M0_odd, J) ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "BSD-3-Clause" ]
2.2.2
63eb4fb995021485a940b1d95e4b0631e333ded0
docs
1757
# [HEOMLS Matrix for Schrödinger Equation](@id doc-M_S) The HEOM Liouvillian superoperator matrix with cutoff level of the hierarchy equals to `0`: [`struct M_S <: AbstractHEOMLSMatrix`](@ref M_S) This corresponds to the standard Schrodinger (Liouville-von Neumann) equation, namely ```math \hat{\mathcal{M}}[\cdot]=-i \left[H_{s}, \cdot \right]_-, ``` where ``[\cdot, \cdot]_-`` stands for commutator. ## Construct Matrix To construct the HEOM matrix for Schrödinger Equation, one can call [`M_S(Hsys, parity)`](@ref M_S) with the following parameters: *args* (Arguments) - `Hsys` : The time-independent system Hamiltonian - `parity::AbstractParity` : the [parity](@ref doc-Parity) label of the operator which HEOMLS is acting on. Defaults to `EVEN`. *kwargs* (Keyword Arguments) - `verbose::Bool` : To display verbose output during the process or not. Defaults to `true`. For example: ```julia Hs::QuantumObject # system Hamiltonian # create HEOMLS matrix in both EVEN and ODD parity M_even = M_S(Hs) M_odd = M_S(Hs, ODD) ``` ## Fields The fields of the structure [`M_S`](@ref) are as follows: - `data` : the sparse matrix of HEOM Liouvillian superoperator - `tier` : the tier (cutoff level) for the hierarchy, which equals to `0` in this case - `dims` : the dimension list of the coupling operator (should be equal to the system dims). - `N` : the number of total [ADOs](@ref doc-ADOs), which equals to `1` (only the reduced density operator) in this case - `sup_dim` : the dimension of system superoperator - `parity::AbstractParity` : the [parity](@ref doc-Parity) label of the operator which HEOMLS is acting on. One can obtain the value of each fields as follows: ```julia M::M_S M.data M.tier M.dims M.N M.sup_dim M.parity ```
HierarchicalEOM
https://github.com/qutip/HierarchicalEOM.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
code
229
module CollisionDetection using Compat using LinearAlgebra using StaticArrays export Octree export boxes, fitsinbox, boudingbox, boxesoverlap export searchtree, find include("octree.jl") include("searcheq.jl") end # module
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
code
13487
mutable struct Box data::Vector{Int} children::Vector{Box} end Box() = Box(Int[], Box[]) """ T: type of the coordinates P: type of the points stored in the Octree. """ mutable struct Octree{T,P} center::P halfsize::T rootbox::Box points::Vector{P} radii::Vector{T} expanding_ratio::Float64 # This will add the expanding ratio of boxes splitcount::Int minhalfsize::T end """ boundingbox(v) Compute the bounding cube/square for a Array of Point. The return values are the center of the bounding box and the half size of the cube. """ function boundingbox(v::Vector{P}) where {P} #P are points values (x,y) in 2D or (x,y,z) in 3D ll = minimum(v) ur = maximum(v) #ll => LowerLeft #up => UpperRight c = (ll + ur)/2 s = maximum(ur - c) #c => centre #s => biggest half width, i.e in 2D distance between points result in a rectangular # (so we pick the bigger value here to form a rectangular later) return c, s end """ Predicate used for iteration over an Octree. Returns true if two boxes specified by their centers and halfsizes overlap. More carefull investigation of the objects within is required to assess collision. False positives are possible. boxesoverlap(c1, hs1, c2, hs2) """ function boxesoverlap(c1, hs1, c2, hs2) tol = sqrt(eps(typeof(hs1))) # Checking the type of the problem domain 2D or 3D? and making sure the boxes are from same domain dim = length(c1) @assert dim == length(c2) #Note: I have fixed the condition, now it works for 3D and 2D hs = hs1 + hs2 for i in 1 : dim if abs(c1[i] - c2[i]) > hs + tol return false end end return true end function Octree(points::Vector, radii::Vector{T}, expanding_ratio=1.0, splitcount = 10, minhalfsize = zero(T)) where {T} n_points = length(points) n_dims = length(eltype(points)) # compute the bounding box taking into account # the radius of the objects to be inserted radius = maximum(radii) @assert !isempty(points) ll = points[1] ur = points[1] for i in 2:length(points) ll = min.(ll, points[i]) ur = max.(ur, points[i]) end ll = ll .- radius ur = ur .+ radius #ll = minimum(points) - radius #ur = maximum(points) + radius center = (ll + ur) / 2 halfsize = maximum(ur - center) # if the minimal box size is not specified, # make a reasonable guess if minhalfsize == 0 #TODO generalise minhalfsize = 0.1 * halfsize * (splitcount / n_points)^(1/3) end # Create an empty octree rootbox = Box() tree = Octree(center, halfsize, rootbox, points, radii, expanding_ratio, splitcount, minhalfsize) # populate for id in 1:n_points point, radius = points[id], radii[id] insert!(tree, tree.rootbox, center, halfsize, point, radius, id) end return tree end """ Octree(points) Insert zero radius objects at positions `points` in an Octree """ Octree(points) = Octree(points, zeros(eltype(eltype(points)), length(points))) """ childsector(point, center) -> sector Computes the sector w.r.t. `center` that contains point. Sector is an Int that encodes the position of point along each axis in its bit representation """ function childsector(point, center) # in Case of 3D the Octant they are numbered as follows (+,+,+)->7, (+,+,-)->3, (+,-,+)->5, (+,-,-)->1 #(-,+,+)->6, (-,+,-)->2, (-,-,+)->4, (-,-,-)->0 #For 2D (-,-)->0, (-,+)->1, (+,-)->2, (+,+)->3 sct = 0 r = point - center for (i,x) in enumerate(r) if x > zero(x) sct |= (1 << (i-1)) end end return sct # because Julia has 1-based indexing end isleaf(node) = isempty(node.children) """ fitsinbox(pos, radius, center, halfsize) -> true/fasle Finds out if the object with position (pos) and (raduis) fits inside the box. It uses the box dimension (centre, and halfsize(w/2)) to do the comparsion """ function fitsinbox(pos, radius, center, halfsize) for i in 1:length(pos) (pos[i] - radius < center[i] - halfsize) && return false (pos[i] + radius > center[i] + halfsize) && return false end # the code judege by comapring with the box lower left point and uper right point return true end """ itsinbox(Opj_c, Obj_rad, box_c, box_hf, ratio) -> true/fasle Finds out if the object with center position (Opj_c) and (Obj_rad) fits inside the box. It uses the box dimension (box_c, and box_hf(w/2)) to do the comparsion ratio is relative to box half width, so if you want to be just within the box then ratio =1, if the boundaries of the object is slightly bigger and you still want to include them make ratio bigger ex:1.2 """ function fitsinbox(Opj_c, Obj_rad, box_c, box_hf, ratio) for i in 1:length(Opj_c) (Opj_c[i] - Obj_rad < box_c[i] - (box_hf*ratio)) && return false (Opj_c[i] + Obj_rad > box_c[i] + (box_hf*ratio)) && return false end # the code judege by comapring with the box lower left point and uper right point return true end """ childcentersize(center, halfsize, sector) -> center, halfsize Computes the center and halfsize of the child of the input box that resides in octant `sector` """ @generated function childcentersize(center, halfsize, sector) D = length(center) xp1 = :(halfsize = halfsize / 2) xp2 = Expr(:call, center) for d in 1:D push!(xp2.args, :(center[$d] + (sector & (1 << $(d-1)) == 0 ? -halfsize : +halfsize))) end xp = quote $xp1 return $xp2, halfsize end #@show xp #xp end """ insert!(tree, box, center, halfsize, point, radius, id) tree: the tree in which to insert box: the box in which to try insertion center: center of the box halfsize: 0.5 times the length of the box side point: the point at which to insert radius: the radius of the item to insert id: a unique id that identifies the inserted item uniquely """ function insert!(tree, box, center::P, halfsize::T, point::P, radius::T, id) where {T,P} # if not saturated: insert here # if saturated and not internal : create children and redistribute # if saturated and internal and not fat: insert!(childbox,...) # if saturated and internal and fat: insert here # also if not saturated but there are non empty internal boxes try to insert there not here # or shorter: # sat & not internal: create children and redistibute # sat & internal & not fat: insert in childbox # all other cases: insert here # Will find out first if we are solveing octree or quadtree 3D/2D dim = length(P) nch = 2^dim expanding_ratio=tree.expanding_ratio saturated = (length(box.data) + 1) > tree.splitcount fat = !fitsinbox(point, radius, center, halfsize,expanding_ratio) # we test if the point is within the box and the expanswion if there is any internal = !isleaf(box) if (!internal && !saturated) || (internal && fat) # this will only insert in top level in two cases # 1) the object is fat anyway # 2) there is no child boxes and still there is a place in this box ( it is not saturated) push!(box.data, id) elseif internal && !fat # now if the box has a space or not but it has a childern try to insert in the child not here sct = childsector(point, center) chdbox = box.children[sct+1] chdcenter, chdhalfsize = childcentersize(center, halfsize, sct) if fitsinbox(point, radius, chdcenter, chdhalfsize,expanding_ratio) # check if it is fat and please consider the expansion insert!(tree, chdbox, chdcenter, chdhalfsize, point, radius, id) else push!(box.data, id) end else # saturated && not internal # if their was a previous attempt to subdivide this box, # insert the new element in this box for now as we will sort them after we create childrens push!(box.data, id) # if we are not allowed to subdivide any further stop. This will # avoid the contruction of a tree with N levels when N equal points # are inserted. if halfsize/2 < tree.minhalfsize return end # Create an array of childboxes box.children = Array{Box}(undef,nch) for i in 1:nch box.children[i] = Box(Int[], Box[]) end # subdivide: # for every id in this box # find the correspdoning child sector # if it fits in the child box, insert # if not, add to the list of unmovables # replace the current box data with the list of unmovables unmovables = Int[] for id in box.data point = tree.points[id] radius = tree.radii[id] sct = childsector(point, center) chdbox = box.children[sct+1] chdcenter, chdhalfsize = childcentersize(center, halfsize, sct) if fitsinbox(point, radius, chdcenter, chdhalfsize,expanding_ratio)# # check if it is fat for the child and please consider the expansion push!(chdbox.data, id) else push!(unmovables, id) end end box.data = unmovables end end import Base.length function length(tree::Octree) # Traversal order: # data in the box # data in all children # data in the sibilings level = 0 box = tree.rootbox sz = length(box.data) box_stack = [tree.rootbox] sct_stack = [1] sz = -0 box = tree.rootbox sct = 0 box_stack = Box[] sct_stack = Int[] while true # if this is the first time the box is visited, count the data if sct == 0 sz += length(box.data) if length(box.data) != 0 println("Adding ", length(box.data), " contributions at level: ", level) end end # if this box has unprocessed children # push this box on the stack and process the children if sct < length(box.children) push!(box_stack, box) push!(sct_stack, sct+1) level += 1 box = box.children[sct+1] sct = 0 continue end # if box and its children are processed, # and their is no parent above this box: # end the traversal: if isempty(box_stack) break end # if either no children or all children processed: # move up one level box = pop!(box_stack) sct = pop!(sct_stack) level -= 1 end return sz end mutable struct BoxIterator{T,P,F} predicate::F tree::Octree{T,P} end Base.IteratorSize(::BoxIterator) = Base.SizeUnknown() mutable struct BoxIteratorStage{T,P} box::Box sct::Int center::P halfsize::T end boxes(tree::Octree, pred = (ctr,hsz)->true) = BoxIterator(pred, tree) """ advance(it, state) Moves `state` ahead to point at either the next valid position or one-off-end. """ function advance(bi::BoxIterator, state) pred = bi.predicate box = last(state).box sct = last(state).sct hsz = last(state).halfsize ctr = last(state).center while true # scan for a next child box that meets the criterium childbox_found = false while sct < length(box.children) chd_ctr, chd_hsz = childcentersize(ctr, hsz, sct) if bi.predicate(chd_ctr, chd_hsz) childbox_found = true break end sct += 1 end if childbox_found # if this box has unvisited children, increment # the next child sct counter and move down the tree last(state).sct = sct + 1 ctr, hsz = childcentersize(ctr, hsz, sct) stage = BoxIteratorStage(box.children[sct+1], 0, ctr, hsz) push!(state, stage) else pop!(state) end # if we popped the root, we're finished if isempty(state) break end box = last(state).box sct = last(state).sct hsz = last(state).halfsize ctr = last(state).center # only stop the iteration when a new box is found # and if that box is non-empty # (sct == 0) implies that this is the first visit if sct == 0 && !isempty(box.data) break end end return state end function Base.iterate(bi::BoxIterator) state = [ BoxIteratorStage( bi.tree.rootbox, 0, bi.tree.center, bi.tree.halfsize ) ] if !bi.predicate( bi.tree.center, bi.tree.halfsize) state = advance(bi, state) end # at this point state will be either empty or valid @assert isempty(state) || bi.predicate(last(state).center, last(state).halfsize) iterate(bi, state) end function Base.iterate(bi::BoxIterator, state) isempty(state) && return nothing return last(state).box.data, advance(bi, state) end """ find(octree, pos, tolerance=sqrt(eps(eltype(pos)))) Return an array containing the indices of values at `pos` (up to a tolerance) """ function find(tr::Octree, v; tol = sqrt(eps(eltype(v)))) pred = (c,s) -> fitsinbox(v, 0.0, c, s+tol)# i didn't change it because find will get the point anyway, it only chck for its existance I = Int[] for b in boxes(tr, pred) for i in b if norm(tr.points[i] - v) < tol push!(I, i) end end end return I end
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
code
625
""" searchtree(pred, tree, bb) Return an iterator that returns indices stores in tree that correspond to objects for which the supplied predicate holds. `pred` takes an integer an returns true is the corresponding object stores in `tree` collides with the target object. `bb` is a bounding box containing the target. This bounding box is used for effiently excluding entire branches of the tree. """ function searchtree(pred, tree::Octree, bb) ct, st = bb box_pred = (c,s) -> boxesoverlap(c, s, ct, st) box_it = boxes(tree, box_pred) Compat.Iterators.filter(pred, Compat.Iterators.flatten(box_it)) end
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
code
220
using StaticArrays module MyPkgTests using LinearAlgebra using Test using StaticArrays using JLD2 import CollisionDetection include("test_core.jl") include("test_bloated.jl") include("test_searcheq.jl") end # module
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
code
1574
#using FixedSizeArrays CD = CollisionDetection @test CD.fitsinbox([1,1,1],1.2,[0,0,0],1,2.21) == true @test CD.fitsinbox([1,1,1],1.2,[0,0,0],1,2.19) == false @test CD.fitsinbox([-1,-1],1.2,[0,0],1,2.21) == true d, n = 2, 9 data = SVector{d,Float64}[2*rand(SVector{d,Float64}) for i in 1:n] # create the list of points for the tree test push!(data,SVector(2.0,2.0)) # The is the the top right corner push!(data,SVector(0.0,0.0)) # This is the lower left corner push!(data, SVector(0.90,0.5)) # This point is at the edgre of sector(0) (-,-) radii = abs.(zeros(n+2)) # We set raduis for all points to zero to test if they fill in sectors as well push!(radii,0.2) # Now only the test point has a raduis tree = CD.Octree(data, radii) # Create an Octree with normal (ratio=1) so that means the point is unmovable to child sector @test tree.rootbox.data[1]==n+3 # Now we test if the test point is the only unmovable (it should be) tree = CD.Octree(data, radii,1.2) # We create a new tree but with wider boxes to include points at sectors edge @test in(n+3,tree.rootbox.children[1].data)==true # now the point should be located at sector zero (+1) of the direct child push!(data, SVector(0.90,0.5)) # now we add another point but with slightly fatter raduis than the ratio 1.2 push!(radii,0.26) tree = CD.Octree(data, radii,1.2) @test in(n+4,tree.rootbox.children[1].data)==false # Now it should go to the child sector @test tree.rootbox.data[1]==n+4 # but will be definatly the only one in top level,
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
code
2387
CD = CollisionDetection @test CD.childsector([1,1,1],[0,0,0]) == 7 @test CD.childsector([-1,1,-1],[0,0,0]) == 2 @test CD.childsector([-1,1,-1,1],[0,0,0,0]) == 10 @test CD.childsector([1,1],[0,0]) == 3 @test CD.childcentersize(SVector(0.,0.,0.), 1., 3) == (SVector(0.5,0.5,-0.5), 0.5) @test CD.childcentersize(SVector(0.,0.,0.), 2., 7) == (SVector(1.0,1.0,1.0), 1.0) @test CD.childcentersize(SVector(1.,1.,1.,1.), 2., 9) == (SVector(2.,0.,0.,2.), 1.) d, n = 3, 200 data = SVector{d,Float64}[rand(SVector{d,Float64}) for i in 1:n] radii = abs.(rand(n)) tree = CD.Octree(data, radii) @test length(tree) == n println("Testing allways true iterator") sz = 0 for box in CD.boxes(tree) global sz += length(box) end @test sz == n println("Testing allways false iterator") sz = 0 for box in CD.boxes(tree, (c,s)->false) global sz += length(box.data) end @test sz == 0 println("Testing query for box in sector [7,0]") sz = 0 for box in CD.boxes(tree, (c,s)->CD.fitsinbox([1,1,1]/8,0,c,s)) global sz += length(box) end @show sz T = Float64 P = SVector{2,T} n = 40000 data = P[rand(P) for i in 1:n] radii = abs.(rand(T,n)) tree = CD.Octree(data, radii) println("Testing allways true iterator [2D]") sz = 0 for box in CD.boxes(tree) global sz += length(box) end @test sz == n println("Testing allways false iterator [2D]") sz = 0 for box in CD.boxes(tree, (c,s)->false) global sz += length(box.data) end @test sz == 0 println("Testing query for box in sector [7,0], [2D]") sz = 0 for box in CD.boxes(tree, (c,s)->CD.fitsinbox([1,1]/8,0,c,s)) global sz += length(box) end @show sz ## Test the case of degenerate bounding boxes fn = joinpath(dirname(@__FILE__),"assets","back.jld2") jldopen(fn,"r") do file global U = file["V"] global G = file["F"] #read(file, "V"), read(file, "F") end fn = joinpath(dirname(@__FILE__),"assets","front.jld2") jldopen(fn,"r") do file global V = file["V"] global F = file["F"] #read(file, "V"), read(file, "F") end @assert eltype(V) <: SVector radii = zeros(length(V)) tree = CD.Octree(V, radii) tree_ctr, tree_hs = tree.center, tree.halfsize u = U[3] atol = sqrt(eps()) @test norm(u-V[4]) < atol pred(c,s) = CD.fitsinbox(Array(u), 0.0, c, s+atol) @test pred(tree_ctr, tree_hs) it = CD.boxes(tree, pred) #st = start(it) st = iterate(it) #@test !done(it, st) @test st != nothing
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
code
960
fn = normpath(joinpath(dirname(@__FILE__),"center_sizes.jld2")) d = JLD2.jldopen(fn,"r") tmp = d["ctrs"] ctrs = [SVector(q...) for q in tmp] rads = d["rads"] tree = CD.Octree(ctrs, rads) # extract all the triangles that (potentially) intersect octant (+,+,+) pred(i) = all(ctrs[i].+rads[i] .> 0) bb = SVector(0.5, 0.5, 0.5), 0.5 ids = collect(CD.searchtree(pred, tree, bb)) @test length(ids) == 178 N = 100 using DelimitedFiles buf = readdlm(joinpath(@__DIR__,"assets","ctrs.csv")) ctrs = vec(collect(reinterpret(SVector{3,Float64}, buf'))) rads = vec(readdlm(joinpath(@__DIR__,"assets","rads.csv"))) tree = CD.Octree(ctrs, rads) pred(i) = all(ctrs[i] .+ rads[i] .> 0) bb = @SVector[0.5, 0.5, 0.5], 0.5 ids = collect(CD.searchtree(pred, tree, bb)) @show ids ids2 = findall(i -> all(ctrs[i].+rads[i] .> 0), 1:N) @test length(ids2) == length(ids) @test sort(ids2) == sort(ids) @test ids == [26, 46, 54, 93, 34, 94, 75, 23, 86, 57, 44, 40, 67, 73, 77, 80]
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
code
609
# using CollisionDetection # using CompScienceMeshes # using JLD2 m = meshsphere(1.0, 0.2) @show numcells(m) #centroid(ch) = cartesian(meshpoint(ch, [1,1]/3)) #ctrs = [centroid(simplex(cellvertices(m,i))) for i in 1:numcells(m)] ctrs = cartesian.(center.(chart.(m,cells(m)))) #rads = [maximum(norm(v-ctrs[i]) for v in cellvertices(m,i)) for i in eachindex(ctrs)] rads = [maximum(norm(v-ctrs[i]) for v in vertices(m,c)) for (i,c) in enumerate(cells(m))]; tree = Octree(ctrs, rads) fn = joinpath(@__FILE__,"..","center_sizes.jld2") JLD2.@save fn ctrs rads # save(fn, # "ctrs", ctrs, # "rads", rads)
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.6
88a33f2fba4ef1065edd06164c84d8b03ee4d049
docs
1653
# CollisionDetection A package for the log(N) retrieval of colliding objects [![Build Status](https://travis-ci.org/krcools/CollisionDetection.jl.svg?branch=master)](https://travis-ci.org/krcools/CollisionDetection.jl) [![codecov](https://codecov.io/gh/krcools/WiltonInts84.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/krcools/WiltonInts84.jl) Contains an nd-tree data structure for the storage of objects of finite extent (i.e. not just points). Objects inserted in the tree will only descend as long as they fit the box they are assigned too. The main purpose of this tree is to enable logarithmic complexity collision detection. Applications are e.g. the implementation of graph algorithms, testing if a point is inside a boundary. Usage ```julia using CollisionDetection using StaticArrays n = 100 centers = 2 .* [rand(SVector{3,Float64}) for i in 1:n] .- 1 radii = [0.1*rand() for i in 1:n] tree = Octree(centers, radii) ``` To detect colliding objects in a tree, both a bounding box and a collision predicate are required. The bounding box is given by a centre and half the size of the side of the box. The predicate takes an index and returns true or false depending on whether the i-th object stored in the tree collides with the target. ```julia # Given an index, is the corresponding ball eligible? pred(i) = all(centers[i].+radii[i] .> 0) # Bounding box in the (center,halfside) format supplied for effiency bb = @SVector[0.5, 0.5, 0.5], 0.5 # collect the iterator of admissible indices ids = collect(searchtree(pred, tree, bb)) ``` In this example `ids` will contain the indices of objects touching the (+,+,+) octant.
CollisionDetection
https://github.com/krcools/CollisionDetection.jl.git
[ "MIT" ]
0.1.0
9f0e83e5562e2db5d761b4bab87cd72164676967
code
7269
#= = This module returns a dictionary of symbols and alphanumeric values, as given by a single = ASCII line from an International Maritime Meteorological Archive file (IMMA Release 2.5; = following http://rda.ucar.edu/datasets/ds540.0/docs/R2.5-imma_short.pdf). This format = consists of a core entry and up to six attachments, some of which are still in the process = of being standardized. Note that the dictionary returns only defined values (that is, the = original string if a scale parameter is zero, a scaled float if the scale is positive, and = a float converted from a different base if the scale is negative) and for the time being, = attachments 5 and 6 are not parsed (at least until 5 is formalized) - RD March 2016, May 2017 =# module ICOADSDict # first define the values contained in the core export imma # and attachments by symbol, location, and scale const symb0 = [:YR, :MO, :DY, :HR, :LAT, :LON, :IM, :ATTC, :TI, :LI, :DS, :VS, :NID, :II, :ID, :C1, :DI, :D, :WI, :W, :VI, :VV, :WW, :W1, :SLP, :A, :PPP, :IT, :AT, :WBTI, :WBT, :DPTI, :DPT, :SI, :SST, :N, :NH, :CL, :HI, :H, :CM, :CH, :WD, :WP, :WH, :SD, :SP, :SH] const leng0 = [ 4, 2, 2, 4, 5, 6, 2, 1, 1, 1, 1, 1, 2, 2, 9, 2, 1, 3, 1, 3, 1, 2, 2, 1, 5, 1, 3, 1, 4, 1, 4, 1, 4, 2, 4, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2] const scal0 = [ 1, 1, 1, 0.01, 0.01, 0.01, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0.1, 1, 1, 1, 1, 0.1, 1, 0.1, 1, 0.1, 1, 0.1, 1, 0.1, 1, 0.1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1] const symb1 = [:ATTI1, :ATTL1, :BSI, :B10, :B1, :DCK, :SID, :PT, :DUPS, :DUPC, :TC, :PB, :WX, :SX, :C2, :SQZ, :SQA, :AQZ, :AQA, :UQZ, :UQA, :VQZ, :VQA, :PQZ, :PQA, :DQZ, :DQA, :ND, :SF, :AF, :UF, :VF, :PF, :RF, :ZNC, :WNC, :BNC, :XNC, :YNC, :PNC, :ANC, :GNC, :DNC, :SNC, :CNC, :ENC, :FNC, :TNC, :QCE, :LZ, :QCZ] const leng1 = [ 2, 2, 1, 3, 2, 3, 3, 2, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2] const scal1 = [ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, 1, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, -36, 1, 1, 1] const symb2 = [:ATTI2, :ATTL2, :OS, :OP, :FM, :IX, :W2, :SGN, :SGT, :SGH, :WMI, :SD2, :SP2, :SH2, :IS, :ES, :RS, :IC1, :IC2, :IC3, :IC4, :IC5, :IR, :RRR, :TR, :QCI, :QI1, :QI2, :QI3, :QI4, :QI5, :QI6, :QI7, :QI8, :QI9, :QI10, :QI11, :QI12, :QI13, :QI14, :QI15, :QI16, :QI17, :QI18, :QI19, :QI20, :QI21, :HDG, :COG, :SOG, :SLL, :SLHH, :RWD, :RWS] const leng2 = [ 2, 2, 1, 1, 2, 1, 1, 1, 1, 2, 1, 2, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 2, 2, 3, 3, 3] const scal2 = [ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] const symb3 = [:ATTI3, :ATTL3, :CCCC, :BUID, :BMP, :BSWU, :SWU, :BSWV, :SWV, :BSAT, :BSRH, :SRH, :SIX, :BSST, :MST, :MSH, :BY, :BM, :BD, :BH, :BFL] const leng3 = [ 2, 2, 4, 6, 5, 4, 4, 4, 4, 4, 3, 3, 1, 4, 1, 3, 4, 2, 2, 2, 2] const scal3 = [ 1, 1, 0, 0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 1, 1, 1, 0.1, 1, 1, 1, 1, 1, 1, 1] const symb4 = [:ATTI4, :ATTL4, :C1M, :OPM, :KOV, :COR, :TOB, :TOT, :EOT, :LOT, :TOH, :EOH, :SIM, :LOV, :DOS, :HOP, :HOT, :HOB, :HOA, :SMF, :SME, :SMV] const leng4 = [ 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 1, 2, 3, 3, 2, 3, 3, 3, 3, 5, 5, 2] const scal4 = [ 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1] const symb5 = [:ATTI5, :ATTL5, :WFI, :WF, :XWI, :XW, :XDI, :XD, :SLPI, :TAI, :TA, :XNI, :XN, :OTHERSTUFF5] const leng5 = [ 2, 2, 1, 2, 1, 3, 1, 2, 1, 1, 4, 1, 2, 71] const scal5 = [ 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0] const symb6 = [:ATTI6, :ATTL6, :ATTE, :OTHERSTUFF6] const leng6 = [ 2, 2, 1, 999] const scal6 = [ 1, 1, 0, 0] function imma(line::AbstractString) vals = Dict{Symbol, Any}() # initialize a "vals" dictionary linlen = length(line) subsec = 0 # then loop through the core and substa = 1 # all available attachments until while substa < linlen # we're past the end of the line if substa > 1 # (sta/end are section start/end) subsec = parse(Int, line[substa:substa+1]) end symb = eval(Symbol("symb", subsec)) # use the relevant section arrays leng = eval(Symbol("leng", subsec)) scal = eval(Symbol("scal", subsec)) sumlen = sum(leng) subend = substa + sumlen - 1 if subsec < 5 # ignore historical/supplemental if subend <= linlen # isolate this section and pad if sublin = line[substa:subend] # at the end of a truncated line else sublin = rpad(line[substa: end], sumlen, ' ') end # println(subsec, " :", sublin, ": ") index = [0; cumsum(leng)] .+ 1 # add any valid entries from each for (a, sym) in enumerate(symb) # section and return the dictionary tmpval = sublin[index[a]:index[a]+leng[a]-1] if tmpval != " "^leng[a] if scal[a] > 0 vals[sym] = parse(Float64, tmpval) * scal[a] elseif scal[a] == 0 vals[sym] = strip(tmpval) else vals[sym] = float(parse(Int, tmpval, base = 36)) end # println(sym, " ", vals[sym]) end end end substa = subend + 1 end return vals end end # end ICOADSDict module
ICOADSDict
https://github.com/JuliaAtmosOcean/ICOADSDict.jl.git
[ "MIT" ]
0.1.0
9f0e83e5562e2db5d761b4bab87cd72164676967
code
365
line = "2005 1 0 5500 540 120031 1DBBX 0310 102452 60 76 74 71 A 165 14255992114 5 0 111FF1377AAA11A118AA1 594 1 4 9863" val = imma(rstrip(line)) @test val[:SST] == 7.1000000000000005 @test val[:YR] == 2005.0
ICOADSDict
https://github.com/JuliaAtmosOcean/ICOADSDict.jl.git
[ "MIT" ]
0.1.0
9f0e83e5562e2db5d761b4bab87cd72164676967
code
327
using Test, ICOADSDict "Function that returns a valid file name of a non-existing file for all OSs" function tempname2() f, h = mktemp() close(h) rm(f) f end tlist = [Int8, UInt8, Int16, UInt16, Int32,UInt32, Int64,UInt64, Float32, Float64] @testset "lineparsing" begin include("oneliner.jl") end nothing
ICOADSDict
https://github.com/JuliaAtmosOcean/ICOADSDict.jl.git
[ "MIT" ]
0.1.0
9f0e83e5562e2db5d761b4bab87cd72164676967
docs
2812
ICOADSDictionary.jl ============ [![Build Status](https://travis-ci.org/JuliaAtmosOcean/ICOADSDict.jl.png)](https://travis-ci.org/JuliaAtmosOcean/ICOADSDict.jl) The International Comprehensive Ocean-Atmosphere Data Set (ICOADS) is a compilation of the world’s in situ surface marine observations and represents a culmination of efforts to digitize, assemble, and reconcile information collected over the years by many countries. This package returns a dictionary of symbols and alphanumeric values from an ICOADS IMMA file. The files themselves are available by registering at, and then downloading from, http://rda.ucar.edu/datasets/ds540.0/ but before registering, it is worth taking a look at the historical animation generated from the data and courtesy of the UK Met Office: http://rda.ucar.edu/datasets/ds540.0/docs/ICOADS2.5-HD_Brohan2015.mp4 Is it obvious when the Suez (1869) and Panama (1914) canals opened for business? In spite of a slightly earlier introduction of steam engines and paddle steamers, changes in ship speed seem more impressive once screw propellers took over (around 1855?) Wars invariably impacted shipping, but the Crimean (1853-1856) and American Civil (1861-1865) wars had quite different impacts in the Pacific. When did data coverage seriously improve along the Equatorial Pacific (to watch El Nino develop using arrays of moored buoys) and in the Southern Hemisphere (thanks to drifters following the surface currents)? # Installation Pkg.add("ICOADSDict") # Quickstart Given an unpacked ICOADS file, the following script illustrates the use of the dictionary that is returned from the function imma: ``` using ICOADSDict, Printf fil = "ICOADS_R3_Beta3_199910.dat" fpa = open(fil, "r") fpb = open(fil*".flux", "w") for line in eachline(fpa) val = imma(rstrip(line)) if haskey(val, :YR) && haskey(val, :MO) && haskey(val, :DY) && haskey(val, :HR) && haskey(val, :LAT) && haskey(val, :LON) && haskey(val, :D) && haskey(val, :W) && haskey(val, :SLP) && haskey(val, :AT) && haskey(val, :SST) && haskey(val, :DPT) if 0 <= val[:W] < 50 && 880 < val[:SLP] < 1080 && -40 <= val[:AT] < 40 && -40 <= val[:DPT] < 40 && -2 <= val[:SST] < 40 && val[:SF] == 1 && val[:AF] == 1 && val[:UF] == 1 && val[:VF] == 1 && val[:PF] == 1 && val[:RF] == 1 if haskey(val, :ID) iden = val[:ID] else iden = "MISSING" end ; iden = replace(strip(iden), ' ' => '_') date = @sprintf("%4d%2d%2d%4d", val[:YR], val[:MO], val[:DY], val[:HR]) ; date = replace(date, ' ' => '0') form = @sprintf("%9s %14s %7.3f %8.3f %8.2f %8.3f %8.3f %8.2f %8.2f %8.2f\n", iden, date, val[:LAT], val[:LON], val[:SLP], val[:D], val[:W], val[:AT], val[:DPT], val[:SST]) write(fpb, form) end end end close(fpa) close(fpb) ```
ICOADSDict
https://github.com/JuliaAtmosOcean/ICOADSDict.jl.git
[ "MIT" ]
0.3.1
a3d153488e0fe30715835e66585532c0bcf460e9
code
9610
module StructC14N using DataStructures export canonicalize ###################################################################### # Private functions ###################################################################### """ `findabbrv(v::Vector{Symbol})` Find all unique abbreviations of symbols in `v`. Return a tuple of two `Vector{Symbol}`: the first contains all possible abbreviations; the second contains the corresponding non-abbreviated symbols. """ function findabbrv(symLong::Vector{Symbol}) @assert length(symLong) >= 1 symStr = String.(symLong) outAbbrv = Vector{Symbol}() outLong = Vector{Symbol}() # Max length of string representation of keywords maxLen = maximum(length.(symStr)) # Identify all abbreviations for len in 1:maxLen for i in 1:length(symStr) s = symStr[i] if length(s) >= len s = s[1:len] push!(outAbbrv, Symbol(s)) push!(outLong , symLong[i]) end end end # Identify unique abbreviations for sym in outAbbrv i = findall(outAbbrv .== sym) count = length(i) if count > 1 deleteat!(outAbbrv, i) deleteat!(outLong , i) end end @assert length(unique(outLong)) == length(symLong) "Input symbols have ambiguous abbreviations" i = sortperm(outAbbrv) return OrderedDict(Pair.(outAbbrv[i], outLong[i])) end function myconvert(template, vv) if isa(template, Type) tt = template else tt = typeof(template) end if isa(tt, Union) && (tt != nonmissingtype(tt)) ismissing(vv) && (return missing) end if typeof(vv) <: AbstractString && tt <: Number return convert(tt, Meta.parse(vv)) end if typeof(vv) <: Number && tt <: AbstractString return string(vv) end if length(methods(parse, (Type{tt}, typeof(vv)))) > 0 return parse(tt, vv) end if length(methods(convert, (Type{tt}, typeof(vv)))) > 0 return convert(tt, vv) end return tt(vv) end ###################################################################### # Public functions ###################################################################### # Template is a NamedTuple """ `canonicalize(template::NamedTuple, input::NamedTuple)` Canonicalize an input NamedTuple according to a NamedTuple template. Returns a NamedTuple. Default values must be specified in `template`. To avoid specifying a default value the corresponding item must be a `Type` object, and its default value will be `missing` (unless overriden in `input`). # Examples ```julia-repl julia> template = (xrange=NTuple{2, Number}, yrange=NTuple{2, Number}, title="Default string"); julia> c = canonicalize(template, (xr=(1,2),)) (xrange = (1, 2), yrange = missing, title = "Default string") julia> c = canonicalize(template, (xr=(1,2), yrange=(3, 4.), tit="Foo")) (xrange = (1, 2), yrange = (3, 4.0), title = "Foo") ``` """ function canonicalize(template::NamedTuple, input::NamedTuple, dconvert=Dict{Symbol, Function}()) abbrv = findabbrv(collect(keys(template))) # Default values are explicitly provided in `template`. If a slot # in `template` is a `Type` object the corresponding default value # is `missing`. output = OrderedDict{Symbol, Any}() for key in keys(template) val = deepcopy(getproperty(template, key)) if isa(val, Type) output[key] = missing # default value is missing else output[key] = val # default value is copied from the template end end # Override with input values for key in keys(input) val = deepcopy(getproperty(input, key)) @assert haskey(abbrv, key) "Unexpected key: $key" longkey = abbrv[key] if haskey(dconvert, longkey) output[longkey] = dconvert[longkey](val) else output[longkey] = myconvert(getproperty(template, longkey), val) end end return NamedTuple(output) end # Template is a structure definition """ `canonicalize(template::DataType, input::NamedTuple)` Canonicalize an input NamedTuple according to a template in a structure definition. Returns a structure instance. If `input` contains less values than required in the template an attempt will be made to create a structure with `missing` values. If this is forbidden by the structure definition an error is raised. # Examples ```julia-repl julia> struct AStruct xrange::NTuple{2, Number} yrange::NTuple{2, Number} title::Union{Missing, String} end julia> canonicalize(AStruct, (xr=(1,2), yr=(3,4.))) AStruct((1, 2), (3, 4.0), missing) julia> canonicalize(AStruct, (xr=(1,2), yr=(3,4.), tit="Foo")) AStruct((1, 2), (3, 4.0), "Foo") ``` """ function canonicalize(template::DataType, input::NamedTuple, dconvert=Dict{Symbol, Function}()) @assert isstructtype(template) abbrv = findabbrv(collect(fieldnames(template))) # Default value is `missing` for all fields output = OrderedDict{Symbol, Any}() for key in fieldnames(template) output[key] = missing end # Override with input values for key in keys(input) val = deepcopy(getproperty(input, key)) @assert haskey(abbrv, key) "Unexpected key: $key" longkey = abbrv[key] if haskey(dconvert, longkey) output[longkey] = dconvert[longkey](val) else output[longkey] = myconvert(fieldtype(template, longkey), val) end end return template(collect(values(output))...) end # Template is a structure instance """ `canonicalize(template, input::NamedTuple)` Canonicalize an input NamedTuple according to a template in a structure instance. Returns a structure instance. All values in the template are taken as default values. # Examples ```julia-repl julia> struct AStruct xrange::NTuple{2, Number} yrange::NTuple{2, Number} title::Union{Missing, String} end julia> template = AStruct((0,0), (0.,0.), missing); julia> canonicalize(template, (xr=(1,2),)) AStruct((1, 2), (0.0, 0.0), missing) julia> canonicalize(template, (yr=(1,2), xr=(3.3, 4.4), tit="Foo")) AStruct((3.3, 4.4), (1, 2), "Foo") ``` """ function canonicalize(instance, input::NamedTuple, dconvert=Dict{Symbol, Function}()) template = typeof(instance) @assert isstructtype(template) abbrv = findabbrv(collect(fieldnames(template))) # Default values are copied from template output = OrderedDict{Symbol, Any}() for key in fieldnames(template) output[key] = deepcopy(getfield(instance, key)) end # Override with input values for key in keys(input) val = deepcopy(getproperty(input, key)) @assert haskey(abbrv, key) "Unexpected key: $key" longkey = abbrv[key] if haskey(dconvert, longkey) output[longkey] = dconvert[longkey](val) else output[longkey] = myconvert(fieldtype(template, longkey), val) end end return template(collect(values(output))...) end # Input is a Tuple: convert to a NamedTuple using template names and # invoke previous methods """ `canonicalize(template, input::Tuple)` Canonicalize an input tuple according to a template. Returns a NamedTuple or a structure instance according to the type of `template`. The input tuple must have same number of elements as the template. # Examples ```julia-repl julia> template = (xrange=NTuple{2,Number}, yrange=NTuple{2,Number}, title="Default string"); julia> canonicalize(template, ((1,2), (3, 4.), "Foo")) (xrange = (1, 2), yrange = (3, 4.0), title = "Foo") julia> struct AStruct xrange::NTuple{2, Number} yrange::NTuple{2, Number} title::Union{Missing, String} end; julia> canonicalize(AStruct, ((1,2), (3, 4.), "Foo")) AStruct((1, 2), (3, 4.0), "Foo") julia> template = AStruct((0,0), (0.,0.), missing); julia> canonicalize(template, ((1,2), (3, 4.), "Foo")) AStruct((1, 2), (3, 4.0), "Foo") ``` """ function canonicalize(template, input::Tuple, dconvert=Dict{Symbol, Function}()) if isa(template, NamedTuple) @assert length(template) == length(input) "Input tuple must have same length as template" return canonicalize(template, NamedTuple{keys(template)}(input), dconvert) elseif isa(template, DataType) @assert isstructtype(template) @assert length(fieldnames(template)) == length(input) "Input tuple must have same number of fields as the template" return canonicalize(template, NamedTuple{fieldnames(template)}(input), dconvert) elseif isstructtype(typeof(template)) @assert isstructtype(typeof(template)) @assert length(fieldnames(typeof(template))) == length(input) "Input tuple must have same number of fields as the template" return canonicalize(template, NamedTuple{fieldnames(typeof(template))}(input), dconvert) end error("Template must be a NamedTuple, a structure definition or a structure instance") end # Inputs are given as keywords """ `canonicalize(template, kwargs...)` Canonicalize the key/value pairs given as keywords according to the `template` structure or named tuple. """ function canonicalize(template, dconvert=Dict{Symbol, Function}(); kwargs...) return canonicalize(template, NamedTuple(kwargs), dconvert) end end # module
StructC14N
https://github.com/gcalderone/StructC14N.jl.git
[ "MIT" ]
0.3.1
a3d153488e0fe30715835e66585532c0bcf460e9
code
3187
using StructC14N using Test # Template is a NamedTuple template = (xrange=NTuple{2, Number}, yrange=NTuple{2, Number}, title="Default string") c = canonicalize(template, (xr=(1,2),)) @test c.xrange == (1, 2) @test ismissing(c.yrange) @test c.title == "Default string" c = canonicalize(template, (xr=(1,2), yrange=(3, 4.), tit="Foo")) @test c.xrange == (1, 2) @test c.yrange == (3, 4.) @test c.title == "Foo" # ...input is a Tuple @test_throws AssertionError canonicalize(template, ((1,2))) c = canonicalize(template, ((1,2), (3, 4.), "Foo")) @test c.xrange == (1, 2) @test c.yrange == (3, 4.) @test c.title == "Foo" # ...inputs are given as keywords c = canonicalize(template, xr=(1,2), yrange=(3, 4.), tit="Foo") @test c.xrange == (1, 2) @test c.yrange == (3, 4.) @test c.title == "Foo" # Template is a structure definition struct AStruct xrange::NTuple{2, Number} yrange::NTuple{2, Number} title::Union{Missing, String} end @test_throws MethodError canonicalize(AStruct, (xr=(1,2), tit="Foo")) c = canonicalize(AStruct, (xr=(1,2), yrang=(3, 4.))) @test c.xrange == (1, 2) @test c.yrange == (3, 4.) @test ismissing(c.title) c = canonicalize(AStruct, (xr=(1,2), yrang=(3, 4.), tit="Foo")) @test c.xrange == (1, 2) @test c.yrange == (3, 4.) @test c.title == "Foo" # ...input is a Tuple @test_throws AssertionError canonicalize(AStruct, ((1,2))) c = canonicalize(AStruct, ((1,2), (3, 4.), "Foo")) @test c.xrange == (1, 2) @test c.yrange == (3, 4.) @test c.title == "Foo" # ...inputs are given as keywords c = canonicalize(AStruct, xr=(1,2), yrang=(3, 4.), tit="Foo") @test c.xrange == (1, 2) @test c.yrange == (3, 4.) @test c.title == "Foo" # Template is a structure instance template = AStruct((0,0), (0.,0.), missing) c = canonicalize(template, (xr=(1,2),)) @test c.xrange == (1, 2) @test c.yrange == (0., 0.) @test ismissing(c.title) c = canonicalize(template, (yr=(1,2), xr=(3.3, 4.4), tit="Foo")) @test c.yrange == (1, 2) @test c.xrange == (3.3, 4.4) @test c.title == "Foo" # ...input is a Tuple @test_throws AssertionError canonicalize(template, ((1,2))) c = canonicalize(template, ((1,2), (3, 4.), "Foo")) @test c.xrange == (1, 2) @test c.yrange == (3, 4.) @test c.title == "Foo" # ...inputs are given as keywords c = canonicalize(template, yr=(1,2), xr=(3.3, 4.4), tit="Foo") @test c.yrange == (1, 2) @test c.xrange == (3.3, 4.4) @test c.title == "Foo" configtemplate = (optStr=String, optInt=Int, optFloat=Float64) configentry = "aa, 1, 2" c = canonicalize(configtemplate, (split(configentry, ",")...,)) @test c.optStr == "aa" @test c.optInt == 1 @test c.optFloat == 2.0 configentry = "optFloat=20, optStr=\"aaa\", optInt=10" c = canonicalize(configtemplate, eval(Meta.parse("($configentry)"))) @test c.optStr == "aaa" @test c.optInt == 10 @test c.optFloat == 20.0 function myparse(input) if input == "ten" return 10 end return 1 end configentry = "optFloat=20, optStr=\"aaa\", optInt=\"ten\"" c = canonicalize(configtemplate, eval(Meta.parse("($configentry)")), Dict(:optInt=>myparse)) @test c.optStr == "aaa" @test c.optInt == 10 @test c.optFloat == 20.0
StructC14N
https://github.com/gcalderone/StructC14N.jl.git
[ "MIT" ]
0.3.1
a3d153488e0fe30715835e66585532c0bcf460e9
docs
4967
# StructC14N.jl ## Structure and named tuple canonicalization. [![Build Status](https://travis-ci.org/gcalderone/StructC14N.jl.svg?branch=master)](https://travis-ci.org/gcalderone/StructC14N.jl) ## Installation Install with: ```julia ]add StructC14N ``` ## Introduction ________ This package exports the `canonicalize(template, input)` function allowing *canonicalization* of input values according to a *template*. The template must be a structure definition (i.e. a `DataType`), a structure instance or a named tuple, The input values may be given either as a named tuple, as a tuple, or as keywords. A **characterizing feature** of `StructC14N` is that field names in input may be given in abbreviated forms, as long as the abbreviation is unambiguous among the template field names. The output will be either a structure instance or a named tuple (depending on the type of `template`), whose values are copied (and converted, if necessary) from the inputs, or (if a field specification is missing) from the template default values. A further argument of type `Dict{Symbol, Function}` may be given to `canonicalize` to specify the conversion functions to be used to populate output from input values. The following table shows the beahviour details, which depends on the type of `template`: | Template | Return type | Default values | Relation between template field types and output types? | Missing inputs for a field results in | |----------------------------|--------------| ---------------|-------------------------------------------------------------|-------------------------------------------------| | A `NamedTuple` instance | `NamedTuple` | Allowed | Implicit (type of default values) or explicit (as a `Type`) | Default value or `missing` (1) | | A `T` structure definition | `T` instance | Not allowed | Identical to structure definition | `missing` if allowed by struct, otherwise error | | A `T` structure instance | `T` instance | Allowed | Identical to structure definition | Default value | (1): Note that the output named tuple may contain `missing`s even if this is not allowed by the template. Type `? canonicalize` in the REPL to read the documentation for individual methods, and the rest of this file for a few examples. ## Examples ```julia using StructC14N # Create a template template = (xrange=NTuple{2,Number}, yrange=NTuple{2,Number}, title="A string") # Create input named tuple... nt = (xr=(1,2), tit="Foo") # Dump canonicalized version dump(canonicalize(template, nt)) ``` will result in ```julia NamedTuple{(:xrange, :yrange, :title),Tuple{Tuple{Int64,Int64},Missing,String}} xrange: Tuple{Int64,Int64} 1: Int64 1 2: Int64 2 yrange: Missing missing title: String "Foo" ``` One of the main use of `canonicalize` is to call functions using abbreviated keyword names (i.e. it can be used as a replacement for [AbbrvKW.jl](https://github.com/gcalderone/AbbrvKW.jl)). Consider the following function: ``` julia function Foo(; OptionalKW::Union{Missing,Bool}=missing, Keyword1::Int=1, AnotherKeyword::Float64=2.0, StillAnotherOne=3, KeyString::String="bar") @show OptionalKW @show Keyword1 @show AnotherKeyword @show StillAnotherOne @show KeyString end ``` The only way to use the keywords is to type their entire names, resulting in very long code lines, i.e.: ``` julia Foo(Keyword1=10, AnotherKeyword=20.0, StillAnotherOne=30, KeyString="baz") ``` By using `canonicalize` we may re-implement the function as follows ```julia function Foo(; kwargs...) template = (; OptionalKW=Bool, Keyword1=1, AnotherKeyword=2.0, StillAnotherOne=3, KeyString="bar") kw = canonicalize(template; kwargs...) @show kw.OptionalKW @show kw.Keyword1 @show kw.AnotherKeyword @show kw.StillAnotherOne @show kw.KeyString end ``` And call it using abbreviated keyword names: ```julia Foo(Keyw=10, A=20.0, S=30, KeyS="baz") # Much shorter, isn't it? ``` A wrong abbreviation or a wrong type will result in errors: ```julia Foo(aa=1) Foo(Keyw="abc") ``` Another common use of `StructC14N` is in parsing configuration files, e.g.: ```julia configtemplate = (optStr=String, optInt=Int, optFloat=Float64) # Parse a tuple configentry = "aa, 1, 2" c = canonicalize(configtemplate, (split(configentry, ",")...,)) # Parse a named tuple configentry = "optFloat=20, optStr=\"aaa\", optInt=10" c = canonicalize(configtemplate, eval(Meta.parse("($configentry)"))) # Use a custom conversion routine function myparse(input) if input == "ten" return 10 end return 1 end configentry = "optFloat=20, optStr=\"aaa\", optInt=\"ten\"" c = canonicalize(configtemplate, eval(Meta.parse("($configentry)")), Dict(:optInt=>myparse)) ```
StructC14N
https://github.com/gcalderone/StructC14N.jl.git
[ "MIT" ]
1.0.4
29ce1bd02d909df87c078b573c713c4888c1d968
code
721
using Documenter, ProperOrthogonalDecomposition makedocs(; modules = [ProperOrthogonalDecomposition], format = Documenter.HTML( assets = ["assets/favicon.ico"], prettyurls = get(ENV, "CI", nothing) == "true"), sitename = "ProperOrthogonalDecomposition.jl", strict = true, clean = true, checkdocs = :none, pages = Any[ "Home" => "index.md", "Manual" => Any[ "man/POD.md", "man/weightedPOD.md", "man/convergence.md", ] ] ) deploydocs( repo = "github.com/MrUrq/ProperOrthogonalDecomposition.jl.git" )
ProperOrthogonalDecomposition
https://github.com/MrUrq/ProperOrthogonalDecomposition.jl.git
[ "MIT" ]
1.0.4
29ce1bd02d909df87c078b573c713c4888c1d968
code
2290
""" PODeigen(X) Uses the eigenvalue method of snapshots to calculate the POD basis of X. Method of snapshots is efficient when number of data points `n` > number of snapshots `m`. """ function PODeigen(X; subtractmean::Bool = false) Xcop = deepcopy(X) PODeigen!(Xcop, subtractmean = subtractmean) end """ PODeigen(X,W) Same as `PODeigen(X)` but uses weights for each data point. The weights are equal to the cell volume for a volume mesh. """ function PODeigen(X,W::AbstractVector; subtractmean::Bool = false) Xcop = deepcopy(X) PODeigen!(Xcop,W, subtractmean = subtractmean) end """ PODeigen!(X,W) Same as `PODeigen!(X)` but uses weights for each data point. The weights are equal to the cell volume for a volume mesh. """ function PODeigen!(X,W::AbstractVector; subtractmean::Bool = false) if subtractmean X .-= mean(X,dims=2) end # Number of snapshots m = size(X,2) # Correlation matrix for method of snapshots C = X'*Diagonal(W)*X # Eigen Decomposition E = eigen!(C) eigVals = E.values eigVects = E.vectors # Sort the eigen vectors sortInd = sortperm(abs.(eigVals)/m,rev=true) eigVects = eigVects[:,sortInd] eigVals = eigVals[sortInd] # Diagonal matrix containing the square roots of the eigenvalues S = sqrt.(abs.(eigVals)) # Construct the modes and coefficients Φ = X*eigVects*Diagonal(1 ./S) a = Diagonal(S)*eigVects' POD = PODBasis(a, Φ) return POD, S end """ PODeigen!(X) Same as `PODeigen(X)` but overwrites memory. """ function PODeigen!(X; subtractmean::Bool = false) if subtractmean X .-= mean(X,dims=2) end # Number of snapshots m = size(X,2) # Correlation matrix for method of snapshots C = X'*X # Eigen Decomposition E = eigen!(C) eigVals = E.values eigVects = E.vectors # Sort the eigen vectors sortInd = sortperm(abs.(eigVals)/m,rev=true) eigVects = eigVects[:,sortInd] eigVals = eigVals[sortInd] # Diagonal matrix containing the square roots of the eigenvalues S = sqrt.(abs.(eigVals)) # Construct the modes and coefficients Φ = X*eigVects*Diagonal(1 ./S) a = Diagonal(S)*eigVects' POD = PODBasis(a, Φ) return POD, S end
ProperOrthogonalDecomposition
https://github.com/MrUrq/ProperOrthogonalDecomposition.jl.git
[ "MIT" ]
1.0.4
29ce1bd02d909df87c078b573c713c4888c1d968
code
1335
""" PODsvd(X) Uses the SVD based decomposition technique to calculate the POD basis of X. """ function PODsvd(X; subtractmean::Bool = false) Xcop = deepcopy(X) PODsvd!(Xcop, subtractmean = subtractmean) end """ PODsvd(X,W) Same as `PODsvd(X)` but uses weights for each data point. The weights are equal to the cell volume for a volume mesh. """ function PODsvd(X,W::AbstractVector; subtractmean::Bool = false) Xcop = deepcopy(X) PODsvd!(Xcop, W, subtractmean = subtractmean) end """ PODsvd!(X) Same as `PODsvd(X)` but overwrites memory. """ function PODsvd!(X; subtractmean::Bool = false) if subtractmean X .-= mean(X,dims=2) end # Economy sized SVD F = svd!(X) # Mode coefficients a = Diagonal(F.S)*F.Vt POD = PODBasis(a, F.U) return POD, F.S end """ PODsvd!(X,W) Same as `PODsvd!(X)` but uses weights for each data point. The weights are equal to the cell volume for a volume mesh. """ function PODsvd!(X,W::AbstractVector; subtractmean::Bool = false) if subtractmean X .-= mean(X,dims=2) end # Take into account the weights X = sqrt.(W).*X # Economy sized SVD F = svd!(X) # Mode coefficients a = Diagonal(F.S)*F.Vt Φ = 1 ./sqrt.(W).*F.U POD = PODBasis(a, Φ) return POD, F.S end
ProperOrthogonalDecomposition
https://github.com/MrUrq/ProperOrthogonalDecomposition.jl.git
[ "MIT" ]
1.0.4
29ce1bd02d909df87c078b573c713c4888c1d968
code
840
module ProperOrthogonalDecomposition using Statistics using LinearAlgebra export PODBasis, POD, PODsvd, PODsvd!, PODeigen, PODeigen!, modeConvergence, modeConvergence! include("types.jl") include("convergence.jl") include("PODsvd.jl") include("PODeigen.jl") """ POD(X) Computes the Proper Orthogonal Decomposition of `X`. Returns a PODBasis. This method is just a thin wrapper around `PODsvd(X)`. """ function POD(X; subtractmean::Bool = false) PODsvd(X, subtractmean = subtractmean) end """ POD(X, W) Computes the Proper Orthogonal Decomposition of `X` with weights `W`. Returns a PODBasis. This method is just a thin wrapper around `PODsvd(X)`. """ function POD(X, W; subtractmean::Bool = false) PODsvd(X, W, subtractmean = subtractmean) end end # module
ProperOrthogonalDecomposition
https://github.com/MrUrq/ProperOrthogonalDecomposition.jl.git
[ "MIT" ]
1.0.4
29ce1bd02d909df87c078b573c713c4888c1d968
code
2889
""" function modeConvergence(X::AbstractArray, PODfun, stops::AbstractArray{<: AbstractRange}, numModes::Int) Modal convergence check based on l2-norm of modes. The array `stops` contains the ranges to investigate where `stops[end]` is used as the reference modes. The `numModes` largest modes are compared to reduce the computational time. The function used to POD the data is supplied through `PODfun` """ function modeConvergence(X::AbstractArray, PODfun, stops::AbstractArray{<: AbstractRange}, numModes::Int) # The full POD which the subsets are compared to maxPOD = PODfun(X[:,stops[end]])[1].modes[:,1:numModes] numPODs = size(stops,1) output = zeros(eltype(X), numModes, numPODs) # Allocate output for i = 1:numPODs-1 podRes = PODfun(X[:,stops[i]])[1].modes[:,1:numModes] # Compare the first numModes modes. for j = 1:numModes # normalize the mode before comparing maxPODnorm = norm(maxPOD[:,j]) podResnorm = norm(podRes[:,j]) maxComp = maxPOD[:,j]/maxPODnorm podComp = podRes[:,j]/podResnorm # modes do not have a specific sign, compare the positive and negative # to find minimum. l2norm1 = norm(maxComp - podComp) l2norm2 = norm(maxComp + podComp) l2norm = minimum([l2norm1, l2norm2]) output[j,i] = l2norm end end return output end """ function modeConvergence!(loadFun, PODfun, stops::AbstractArray{<: AbstractRange}, numModes::Int) Same as `modeConvergence(X::AbstractArray, PODfun, stops::AbstractArray{<: AbstractRange}, numModes::Int)` but here the data is reloaded for each comparision so that an inplace POD method can be used to reduce maximum memory usage. """ function modeConvergence!(loadFun, PODfun, stops::AbstractArray{<: AbstractRange}, numModes::Int) X = loadFun() # The full POD which the subsets are compared to maxPOD = PODfun(X[:,stops[end]])[1].modes[:,1:numModes] numPODs = size(stops,1) output = zeros(eltype(X), numModes, numPODs) # Allocate output for i = 1:numPODs-1 X = loadFun() podRes = PODfun(X[:,stops[i]])[1].modes[:,1:numModes] # Compare the first numModes modes. for j = 1:numModes # normalize the mode before comparing maxPODnorm = norm(maxPOD[:,j]) podResnorm = norm(podRes[:,j]) maxComp = maxPOD[:,j]/maxPODnorm podComp = podRes[:,j]/podResnorm # modes do not have a specific sign, compare the positive and negative # to find minimum. l2norm1 = norm(maxComp - podComp) l2norm2 = norm(maxComp + podComp) l2norm = minimum([l2norm1, l2norm2]) output[j,i] = l2norm end end return output end
ProperOrthogonalDecomposition
https://github.com/MrUrq/ProperOrthogonalDecomposition.jl.git
[ "MIT" ]
1.0.4
29ce1bd02d909df87c078b573c713c4888c1d968
code
370
""" PODBasis{T}(coefficients::Matrix{T}, modes::Matrix{T}) Datastructure to store a Proper Orthogonal Decomposition basis. The original data which the POD basis is representing can be reconstructed by right- multiplying the modes with the coefficients, i.e. `A = P.modes*P.coefficients`. """ struct PODBasis{T} coefficients::Matrix{T} modes::Matrix{T} end
ProperOrthogonalDecomposition
https://github.com/MrUrq/ProperOrthogonalDecomposition.jl.git
[ "MIT" ]
1.0.4
29ce1bd02d909df87c078b573c713c4888c1d968
code
5147
using ProperOrthogonalDecomposition using Test using StableRNGs using Statistics using DelimitedFiles # Define test matrix X with dimensions n×m, where n is number of data poitns and # m is the number of snapshots # W is the weight matrix representing the cell volume rng = StableRNGs.StableRNG(1) X = rand(rng,1000,10) X .+= 10 rng = StableRNGs.StableRNG(1) W = rand(rng,1:0.2:10,1000) @testset "Standard POD" begin PODbase, Σ = POD(X) PODbaseEig, Σeig = PODeigen(X) PODbaseSvd, Σsvd = PODsvd(X) meanPODbaseEig, meanΣeig = PODeigen(copy(X), subtractmean = true) meanPODbaseSvd, meanΣsvd = PODsvd(copy(X), subtractmean = true) Σ₁ = 1050.0370061587332 Σ₂ = 8.413650551681984 meanΣ₁ = 9.964071096830972 meanΣ₂ = 8.42358075601378 @testset "POD using eigenvalue decomposition" begin @test Σeig[1] ≈ Σ₁ @test Σeig[end] ≈ Σ₂ @test meanΣeig[1] ≈ meanΣ₁ @test meanΣeig[end-1] ≈ meanΣ₂ end @testset "POD using SVD" begin @test Σsvd[1] ≈ Σ₁ @test Σsvd[end] ≈ Σ₂ @test meanΣsvd[1] ≈ meanΣ₁ @test meanΣsvd[end-1] ≈ meanΣ₂ end @testset "Default method" begin @test maximum(abs.(abs.(PODbaseSvd.coefficients) .- abs.(PODbase.coefficients))) ≈ 0 atol=1e-8 @test maximum(abs.(abs.(PODbaseSvd.modes) .- abs.(PODbase.modes))) ≈ 0 atol=1e-8 @test maximum(abs.(Σsvd.-Σ)) ≈ 0 atol=1e-8 end @testset "Method equality of SVD and Eig" begin @test maximum(abs.(abs.(PODbaseSvd.coefficients) .- abs.(PODbaseEig.coefficients))) ≈ 0 atol=1e-8 @test maximum(abs.(abs.(PODbaseSvd.modes) .- abs.(PODbaseEig.modes))) ≈ 0 atol=1e-8 @test maximum(abs.(abs.(meanPODbaseSvd.coefficients) .- abs.(meanPODbaseEig.coefficients))) ≈ 0 atol=1e-7 @test maximum(abs.(abs.(meanPODbaseSvd.modes[:,1:end-1]) .- abs.(meanPODbaseEig.modes[:,1:end-1]))) ≈ 0 atol=1e-7 @test maximum(abs.(Σeig.-Σsvd)) ≈ 0 atol=1e-8 end @testset "Rebuild solution" begin @test PODbaseEig.modes*PODbaseEig.coefficients ≈ X @test PODbaseSvd.modes*PODbaseSvd.coefficients ≈ X @test meanPODbaseEig.modes*meanPODbaseEig.coefficients ≈ X .- mean(X,dims=2) @test meanPODbaseSvd.modes*meanPODbaseSvd.coefficients ≈ X .- mean(X,dims=2) end end @testset "Weighted POD" begin PODbase, Σ = POD(X, W) PODbaseEig, Σeig = PODeigen(X,W) PODbaseSvd, Σsvd = PODsvd(X,W) meanPODbaseEig, meanΣeig = PODeigen(copy(X), W, subtractmean = true) meanPODbaseSvd, meanΣsvd = PODsvd(copy(X), W, subtractmean = true) Σ₁ = 2462.447359829031 Σ₂ = 19.570713247455668 meanΣ₁ = 23.470360231176947 meanΣ₂ = 19.595332053746322 @testset "POD using eigenvalue decomposition" begin @test Σeig[1] ≈ Σ₁ @test Σeig[end] ≈ Σ₂ @test meanΣeig[1] ≈ meanΣ₁ @test meanΣeig[end-1] ≈ meanΣ₂ end @testset "POD using SVD" begin @test Σsvd[1] ≈ Σ₁ @test Σsvd[end] ≈ Σ₂ @test meanΣsvd[1] ≈ meanΣ₁ @test meanΣsvd[end-1] ≈ meanΣ₂ end @testset "Default method with weights" begin @test maximum(abs.(abs.(PODbaseSvd.coefficients) .- abs.(PODbase.coefficients))) ≈ 0 atol=1e-8 @test maximum(abs.(abs.(PODbaseSvd.modes) .- abs.(PODbase.modes))) ≈ 0 atol=1e-8 @test maximum(abs.(Σsvd.-Σ)) ≈ 0 atol=1e-8 end @testset "Method equality of SVD and Eig with weights" begin @test maximum(abs.(abs.(PODbaseSvd.coefficients) .- abs.(PODbaseEig.coefficients))) ≈ 0 atol=1e-8 @test maximum(abs.(abs.(PODbaseSvd.modes) .- abs.(PODbaseEig.modes))) ≈ 0 atol=1e-8 @test maximum(abs.(Σeig.-Σsvd)) ≈ 0 atol=1e-8 end @testset "Rebuild solution with weights" begin @test PODbaseEig.modes*PODbaseEig.coefficients ≈ X @test PODbaseSvd.modes*PODbaseSvd.coefficients ≈ X end end @testset "Mode convergence" begin A = [0.010164609073873544 0.006921747306424847 0.004321454495431182 0.0; 0.7274414547632297 0.6102769856096316 0.2273767387120779 0.0; 1.1710785171906266 1.1955870815537555 0.12812520121296264 0.0] W₂ = ones(1000) testdataPath = joinpath(dirname(pathof(ProperOrthogonalDecomposition)),"..","test","testdata.csv") @testset "Convergence of number of included snapshots" begin @test modeConvergence(X,PODeigen,[1:4,1:6,1:8,1:10],3) ≈ A @test modeConvergence(X,PODsvd,[1:4,1:6,1:8,1:10],3) ≈ A @test modeConvergence!(()->readdlm(testdataPath, ','),PODeigen!,[1:4,1:6,1:8,1:10],3) ≈ A @test modeConvergence!(()->readdlm(testdataPath, ','),PODsvd!,[1:4,1:6,1:8,1:10],3) ≈ A end @testset "Convergence of number of included snapshots with one weights" begin @test modeConvergence(X,x->PODeigen(x,W₂),[1:4,1:6,1:8,1:10],3) ≈ A @test modeConvergence(X,x->PODsvd(x,W₂),[1:4,1:6,1:8,1:10],3) ≈ A @test modeConvergence!(()->readdlm(testdataPath, ','),x->PODeigen!(x,W₂),[1:4,1:6,1:8,1:10],3) ≈ A @test modeConvergence!(()->readdlm(testdataPath, ','),x->PODsvd!(x,W₂),[1:4,1:6,1:8,1:10],3) ≈ A end end
ProperOrthogonalDecomposition
https://github.com/MrUrq/ProperOrthogonalDecomposition.jl.git