├── qutip ├── tests │ ├── __init__.py │ ├── pytest.ini │ ├── Hadamard_params.ini │ ├── test_qubits.py │ ├── test_floquet.py │ ├── test_three_level.py │ ├── test_rhs_reuse.py │ ├── test_qpt.py │ ├── test_parallel.py │ ├── test_qft.py │ ├── test_td_formats.py │ ├── test_cy_structs.py │ ├── test_fastsparse.py │ ├── test_countstat.py │ ├── test_fileio.py │ ├── test_random.py │ ├── test_heom_solver.py │ ├── test_cavityqed.py │ ├── test_partial_transpose.py │ ├── test_propagator.py │ └── test_states.py ├── legacy │ └── __init__.py ├── nonmarkov │ └── __init__.py ├── cy │ ├── openmp │ │ ├── __init__.py │ │ ├── parfuncs.pxd │ │ ├── benchmark.pyx │ │ ├── br_omp.pxd │ │ ├── src │ │ │ └── zspmv_openmp.hpp │ │ ├── omp_sparse_utils.pyx │ │ └── utilities.py │ ├── __init__.py │ ├── parameters.pxi │ ├── cqobjevo_factor.pxd │ ├── complex_math.pxi │ ├── math.pxd │ ├── interpolate.pxd │ ├── spconvert.pxd │ ├── sparse_structs.pxd │ ├── utilities.py │ ├── spmath.pxd │ ├── src │ │ └── zspmv.hpp │ ├── inter.pxd │ ├── pyxbuilder.py │ ├── heom.pyx │ ├── brtools.pxd │ ├── checks.pyx │ ├── cqobjevo.pxd │ └── spmatfuncs.pxd ├── control │ ├── __init__.py │ ├── symplectic.py │ ├── io.py │ ├── termcond.py │ └── errors.py ├── ui │ └── __init__.py ├── _mkl │ ├── __init__.py │ ├── spmv.py │ └── utilities.py ├── configspec.ini ├── qip │ ├── algorithms │ │ └── __init__.py │ ├── compiler │ │ ├── __init__.py │ │ └── gatecompiler.py │ ├── __init__.py │ ├── gates.py │ ├── device │ │ └── __init__.py │ ├── operations │ │ └── __init__.py │ ├── qubits.py │ └── qip_depracation.py ├── testing.py ├── settings.py ├── cite.py ├── three_level_atom.py ├── about.py └── topology.py ├── .coveragerc ├── requirements.txt ├── pyproject.toml ├── MANIFEST.in ├── .gitignore ├── .github ├── ISSUE_TEMPLATE │ ├── others.md │ ├── feature_request.md │ └── bug_report.md └── pull_request_template.md ├── .mailmap ├── .codeclimate.yml ├── qutip.bib ├── LICENSE.txt ├── CODE_OF_CONDUCT.md └── README.md /qutip/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /qutip/legacy/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /qutip/nonmarkov/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /qutip/cy/openmp/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /qutip/cy/__init__.py: -------------------------------------------------------------------------------- 1 | from qutip.cy.spmatfuncs import * 2 | -------------------------------------------------------------------------------- /qutip/control/__init__.py: -------------------------------------------------------------------------------- 1 | from qutip.control.grape import * 2 | -------------------------------------------------------------------------------- /qutip/ui/__init__.py: -------------------------------------------------------------------------------- 1 | from qutip.ui.progressbar import * 2 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | include = */qutip/* 3 | omit = */tests/* 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cython>=0.21 2 | numpy>=1.12 3 | scipy>=1.0 4 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "wheel", "Cython", "numpy", "scipy"] 3 | -------------------------------------------------------------------------------- /qutip/_mkl/__init__.py: -------------------------------------------------------------------------------- 1 | import qutip.settings as qset 2 | from qutip._mkl.utilities import _set_mkl 3 | _set_mkl() -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE.txt 3 | include requirements.txt 4 | include qutip.bib 5 | include pyproject.toml 6 | recursive-include qutip *.pyx 7 | recursive-include qutip *.pxi 8 | recursive-include qutip *.hpp 9 | recursive-include qutip *.pxd 10 | recursive-include qutip *.ini 11 | -------------------------------------------------------------------------------- /qutip/cy/parameters.pxi: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | cimport numpy as cnp 3 | 4 | DTYPE = np.float64 5 | ctypedef cnp.float64_t DTYPE_t 6 | 7 | ITYPE = np.int32 8 | ctypedef cnp.int32_t ITYPE_t 9 | 10 | CTYPE = np.complex128 11 | ctypedef cnp.complex128_t CTYPE_t 12 | 13 | CTYPE = np.int64 14 | ctypedef cnp.int64_t LTYPE_t 15 | -------------------------------------------------------------------------------- /qutip/tests/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | markers = 3 | slow: Mark a test as taking a long time to run, and so can be skipped with `pytest -m "not slow"`. 4 | repeat(n): Repeat the given test 'n' times. 5 | requires_cython: Mark that the given test requires Cython to be installed. Such tests will be skipped if Cython is not available. 6 | -------------------------------------------------------------------------------- /qutip/tests/Hadamard_params.ini: -------------------------------------------------------------------------------- 1 | [optimconfig] 2 | optim_method=FMIN_L_BFGS_B 3 | pulse_type = LIN 4 | 5 | [dynamics] 6 | evo_time = 6 7 | num_tslots = 6 8 | 9 | [termconds] 10 | fid_err_targ = 1e-10 11 | 12 | [optimizer] 13 | amp_lbound = -1.0 14 | amp_ubound = 1.0 15 | 16 | [pulsegen] 17 | scaling = 1.0 18 | lbound = -1.0 19 | ubound = 1.0 20 | -------------------------------------------------------------------------------- /qutip/configspec.ini: -------------------------------------------------------------------------------- 1 | auto_tidyup = boolean(default=True) 2 | auto_herm = boolean(default=True) 3 | atol = float(default=1e-12) 4 | auto_tidyup_atol = float(default=1e-12) 5 | # num_cpus is set at import, but we allow it 6 | # to be overriden here, too. 7 | num_cpus = integer(default=0) 8 | debug = boolean(default=False) 9 | log_handler = string(default=default) 10 | colorblind_safe = boolean(default=False) 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.py[cod] 3 | *.so 4 | .DS_Store 5 | .f2py_f2cmap 6 | .idea/ 7 | 8 | # Packages 9 | *.egg 10 | *.egg-info 11 | dist 12 | build 13 | eggs 14 | parts 15 | bin 16 | var 17 | sdist 18 | develop-eggs 19 | .installed.cfg 20 | lib 21 | lib64 22 | 23 | 24 | qutip/version.py 25 | qutip/__config__.py 26 | rhs*.pyx 27 | 28 | qutip/cy/*.c 29 | qutip/cy/*.cpp 30 | qutip/control/*.cpp 31 | qutip/cy/openmp/*.cpp 32 | *.dat 33 | 34 | *.qo 35 | 36 | benchmark/benchmark_data.js 37 | *-tasks.txt 38 | *compiled_coeff* 39 | 40 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/others.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Others 3 | about: Other issues 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the issue** 11 | Please describe the issue here. 12 | 13 | **To Reproduce** 14 | If applicable, Please provide a minimal working example. For instance: 15 | 16 | ```python 17 | from qutip import identity 18 | print(identity(2)) 19 | ``` 20 | The terminal out put is 21 | ``` 22 | Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True 23 | Qobj data = 24 | [[1. 0.] 25 | [0. 1.]] 26 | ``` 27 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | Paul Nation Paul Nation 2 | Paul Nation Paul Nation 3 | Anubhav Vardhan Anubhav 4 | Christopher Granade Chris Granade 5 | Markus Baden Markus Baden 6 | kafischer kevinf 7 | Alexander Pitchford ajgpitch 8 | Alexander Pitchford Alexander James Pitchford 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: 'ENH' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | checks: 3 | argument-count: 4 | config: 5 | threshold: 10 6 | complex-logic: 7 | config: 8 | threshold: 20 9 | file-lines: 10 | enabled: false 11 | method-complexity: 12 | config: 13 | threshold: 20 14 | method-count: 15 | config: 16 | threshold: 75 17 | method-lines: 18 | config: 19 | threshold: 100 20 | nested-control-flow: 21 | config: 22 | threshold: 4 23 | return-statements: 24 | config: 25 | threshold: 4 26 | similar-code: 27 | config: 28 | threshold: 64 29 | identical-code: 30 | config: 31 | threshold: 64 32 | plugins: 33 | fixme: 34 | enabled: true 35 | pep8: 36 | enabled: true 37 | -------------------------------------------------------------------------------- /qutip/cy/cqobjevo_factor.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | cimport numpy as np 3 | 4 | cdef np.ndarray[complex, ndim=1] zptr2array1d(complex* ptr, int N) 5 | 6 | cdef np.ndarray[complex, ndim=2] zptr2array2d(complex* ptr, int R, int C) 7 | 8 | cdef np.ndarray[int, ndim=1] iprt2array(int* ptr, int N) 9 | 10 | cdef class CoeffFunc: 11 | cdef dict _args 12 | cdef int _num_ops 13 | cdef void _call_core(self, double t, complex* coeff) 14 | cdef void _dyn_args(self, double t, complex* state, int[::1] shape) 15 | 16 | cdef class StrCoeff(CoeffFunc): 17 | cdef list _dyn_args_list 18 | cdef int _num_expect 19 | cdef int[2] _mat_shape 20 | cdef list _expect_op 21 | cdef complex[::1] _expect_vec 22 | cdef complex[::1] _vec 23 | -------------------------------------------------------------------------------- /qutip/tests/test_qubits.py: -------------------------------------------------------------------------------- 1 | from numpy.testing import assert_, run_module_suite 2 | from qutip.qip.qubits import qubit_states 3 | from qutip.tensor import tensor 4 | from qutip.states import basis 5 | 6 | 7 | class TestQubits: 8 | """ 9 | A test class for the QuTiP functions for qubits. 10 | """ 11 | def testQubitStates(self): 12 | """ 13 | Tests the qubit_states function. 14 | """ 15 | psi0_a = basis(2, 0) 16 | psi0_b = qubit_states() 17 | assert_(psi0_a == psi0_b) 18 | 19 | psi1_a = basis(2, 1) 20 | psi1_b = qubit_states(states=[1]) 21 | assert_(psi1_a == psi1_b) 22 | 23 | psi01_a = tensor(psi0_a, psi1_a) 24 | psi01_b = qubit_states(N=2, states=[0, 1]) 25 | assert_(psi01_a == psi01_b) 26 | 27 | 28 | if __name__ == "__main__": 29 | run_module_suite() 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: 'BUG' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Please provide a minimal working example. For instance: 15 | 16 | ```python 17 | from qutip import identity 18 | print(identity(2)) 19 | ``` 20 | The terminal out put is 21 | ``` 22 | Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True 23 | Qobj data = 24 | [[1. 0.] 25 | [0. 1.]] 26 | ``` 27 | 28 | **Expected behavior** 29 | A clear and concise description of what you expected to happen. 30 | 31 | **Your Environment** 32 | Please use `qutip.about()` to get the information about your environment and paste it here. 33 | 34 | **Additional context** 35 | Add any other context about the problem here. 36 | -------------------------------------------------------------------------------- /qutip.bib: -------------------------------------------------------------------------------- 1 | @article{qutip2, 2 | doi = {10.1016/j.cpc.2012.11.019}, 3 | url = {https://doi.org/10.1016/j.cpc.2012.11.019}, 4 | year = {2013}, 5 | month = {apr}, 6 | publisher = {Elsevier {BV}}, 7 | volume = {184}, 8 | number = {4}, 9 | pages = {1234--1240}, 10 | author = {J.R. Johansson and P.D. Nation and F. Nori}, 11 | title = {{QuTiP} 2: A {P}ython framework for the dynamics of open quantum systems}, 12 | journal = {Computer Physics Communications} 13 | } 14 | @article{qutip1, 15 | doi = {10.1016/j.cpc.2012.02.021}, 16 | url = {https://doi.org/10.1016/j.cpc.2012.02.021}, 17 | year = {2012}, 18 | month = {aug}, 19 | publisher = {Elsevier {BV}}, 20 | volume = {183}, 21 | number = {8}, 22 | pages = {1760--1772}, 23 | author = {J.R. Johansson and P.D. Nation and F. Nori}, 24 | title = {{QuTiP}: An open-source {P}ython framework for the dynamics of open quantum systems}, 25 | journal = {Computer Physics Communications} 26 | } -------------------------------------------------------------------------------- /qutip/cy/complex_math.pxi: -------------------------------------------------------------------------------- 1 | cdef extern from "" namespace "std" nogil: 2 | double abs(double complex x) 3 | double complex acos(double complex x) 4 | double complex acosh(double complex x) 5 | double arg(double complex x) 6 | double complex asin(double complex x) 7 | double complex asinh(double complex x) 8 | double complex atan(double complex x) 9 | double complex atanh(double complex x) 10 | double complex conj(double complex x) 11 | double complex cos(double complex x) 12 | double complex cosh(double complex x) 13 | double complex exp(double complex x) 14 | double imag(double complex x) 15 | double complex log(double complex x) 16 | double complex log10(double complex x) 17 | double norm(double complex x) 18 | double complex proj(double complex x) 19 | double real(double complex x) 20 | double complex sin(double complex x) 21 | double complex sinh(double complex x) 22 | double complex sqrt(double complex x) 23 | double complex tan(double complex x) 24 | double complex tanh(double complex x) 25 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | **Checklist** 2 | Thank you for contributing to QuTiP! Please make sure you have finished the following tasks before opening the PR. 3 | 4 | - [ ] Please read [Contributing to QuTiP Development](https://github.com/qutip/qutip-doc/blob/master/CONTRIBUTING.md) 5 | - [ ] Contributions to qutip should follow the [pep8 style](https://www.python.org/dev/peps/pep-0008/). 6 | You can use [pycodestyle](http://pycodestyle.pycqa.org/en/latest/index.html) to check your code automatically 7 | - [ ] Please add tests to cover your changes if applicable. 8 | - [ ] If the behavior of the code has changed or new feature has been added, please also update the [documentation](https://github.com/qutip/qutip-doc) and the [notebook](https://github.com/qutip/qutip-notebooks). Feel free to ask if you are not sure. 9 | 10 | Delete this checklist after you have completed all the tasks. If you have not finished them all, you can also open a [Draft Pull Request](https://github.blog/2019-02-14-introducing-draft-pull-requests/) to let the others know this on-going work and keep this checklist in the PR description. 11 | 12 | **Description** 13 | Describe here the proposed change. 14 | 15 | **Related issues or PRs** 16 | Please mention the related issues or PRs here. If the PR fixes an issue, use the keyword fix/fixes/fixed followed by the issue id, e.g. fix #1184 17 | 18 | **Changelog** 19 | Give a short description of the PR in a few words. This will be shown in the QuTiP change log after the PR gets merged. 20 | For example: 21 | Fixed error checking for null matrix in essolve. 22 | Added option for specifying resolution in Bloch.save function. 23 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | 1. Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names of 15 | its contributors may be used to endorse or promote products derived from this 16 | software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /qutip/qip/algorithms/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | -------------------------------------------------------------------------------- /qutip/cy/math.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, The QuTiP Project. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | cdef double erf(double x) 36 | 37 | cdef double complex zerf(double complex Z) 38 | -------------------------------------------------------------------------------- /qutip/qip/compiler/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | from .gatecompiler import GateCompiler 35 | from .cavityqedcompiler import CavityQEDCompiler 36 | from .spinchaincompiler import SpinChainCompiler 37 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | 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. 4 | 5 | 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. 6 | 7 | Examples of unacceptable behavior by participants include: 8 | 9 | * The use of sexualized language or imagery 10 | * Personal attacks 11 | * Trolling or insulting/derogatory comments 12 | * Public or private harassment 13 | * Publishing other's private information, such as physical or electronic addresses, without explicit permission 14 | * Other unethical or unprofessional conduct 15 | 16 | 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. 17 | 18 | This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. 19 | 20 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. 21 | 22 | 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 23 | 24 | [homepage]: http://contributor-covenant.org 25 | [version]: http://contributor-covenant.org/version/1/2/ 26 | -------------------------------------------------------------------------------- /qutip/cy/interpolate.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | cpdef double interp(double x, double a, double b, double[::1] c) 36 | 37 | cpdef complex zinterp(double x, double a, double b, complex[::1] c) 38 | -------------------------------------------------------------------------------- /qutip/cy/spconvert.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, The QuTiP Project. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | from qutip.cy.sparse_structs cimport CSR_Matrix 36 | 37 | cdef void fdense2D_to_CSR(complex[::1, :] mat, CSR_Matrix * out, 38 | unsigned int nrows, unsigned int ncols) 39 | -------------------------------------------------------------------------------- /qutip/qip/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | # This is used for the deprecation. 34 | # To remove the warning, and finalize the deprecation 35 | # simply delete the file qutip.qip.qip_depracation.py 36 | # and the line bellow. 37 | from qutip.qip.qip_depracation import * 38 | -------------------------------------------------------------------------------- /qutip/qip/gates.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | import warnings 34 | 35 | from qutip.qip.operations.gates import * 36 | warnings.warn( 37 | "Importation from qutip.qip.gates is deprecated." 38 | "Please use e.g.\n from qutip.qip.operations import cnot\n", 39 | DeprecationWarning, stacklevel=2) 40 | -------------------------------------------------------------------------------- /qutip/qip/device/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | from qutip.qip.device.processor import Processor 34 | from qutip.qip.device.spinchain import ( 35 | SpinChain, LinearSpinChain, CircularSpinChain) 36 | from qutip.qip.device.cavityqed import DispersiveCavityQED 37 | from qutip.qip.device.optpulseprocessor import OptPulseProcessor 38 | from qutip.qip.device.modelprocessor import ModelProcessor 39 | -------------------------------------------------------------------------------- /qutip/qip/operations/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | from qutip.qip.operations.gates import ( 34 | rx, ry, rz, x_gate, y_gate, z_gate, s_gate, t_gate, 35 | cy_gate, cz_gate, cs_gate, ct_gate, sqrtnot, snot, 36 | phasegate, qrot, cphase, cnot, 37 | csign, berkeley, swapalpha, swap, iswap, sqrtswap, 38 | sqrtiswap, fredkin, molmer_sorensen, 39 | toffoli, rotation, controlled_gate, 40 | globalphase, hadamard_transform, gate_sequence_product, 41 | gate_expand_1toN, gate_expand_2toN, gate_expand_3toN, 42 | qubit_clifford_group, expand_operator) 43 | -------------------------------------------------------------------------------- /qutip/cy/sparse_structs.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, The QuTiP Project. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | cdef struct _csr_mat: 36 | double complex * data 37 | int * indices 38 | int * indptr 39 | int nnz 40 | int nrows 41 | int ncols 42 | int is_set 43 | int max_length 44 | int numpy_lock 45 | 46 | cdef struct _coo_mat: 47 | double complex * data 48 | int * rows 49 | int * cols 50 | int nnz 51 | int nrows 52 | int ncols 53 | int is_set 54 | int max_length 55 | int numpy_lock 56 | 57 | ctypedef _csr_mat CSR_Matrix 58 | ctypedef _coo_mat COO_Matrix 59 | -------------------------------------------------------------------------------- /qutip/cy/openmp/parfuncs.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | cimport numpy as cnp 35 | cimport cython 36 | 37 | cpdef cnp.ndarray[complex, ndim=1, mode="c"] spmv_csr_openmp(complex[::1] data, 38 | int[::1] ind, int[::1] ptr, complex[::1] vec, unsigned int nthr) 39 | 40 | 41 | cdef void spmvpy_openmp(complex * data, 42 | int * ind, 43 | int * ptr, 44 | complex * vec, 45 | complex a, 46 | complex * out, 47 | unsigned int nrows, 48 | unsigned int nthr) 49 | -------------------------------------------------------------------------------- /qutip/cy/utilities.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | import os 34 | 35 | def _cython_build_cleanup(tdname, build_dir=None): 36 | if build_dir is None: 37 | build_dir = os.path.join(os.path.expanduser('~'), '.pyxbld') 38 | 39 | # Remove tdname.pyx 40 | pyx_file = tdname + ".pyx" 41 | try: 42 | os.remove(pyx_file) 43 | except: 44 | pass 45 | 46 | # Remove temp build files 47 | for dirpath, subdirs, files in os.walk(build_dir): 48 | for f in files: 49 | if f.startswith(tdname): 50 | try: 51 | os.remove(os.path.join(dirpath,f)) 52 | except: 53 | pass 54 | -------------------------------------------------------------------------------- /qutip/tests/test_floquet.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import numpy as np 35 | import qutip 36 | 37 | 38 | def test_unitary_evolution_two_level_system(): 39 | delta = 1.0 * 2 * np.pi 40 | eps0 = 1.0 * 2 * np.pi 41 | A = 0.5 * 2 * np.pi 42 | omega = np.sqrt(delta**2 + eps0**2) 43 | T = 2*np.pi / omega 44 | tlist = np.linspace(0, 2*T, 101) 45 | psi0 = qutip.rand_ket(2) 46 | H0 = -0.5*eps0*qutip.sigmaz() - 0.5*delta*qutip.sigmax() 47 | H1 = 0.5 * A * qutip.sigmax() 48 | args = {'w': omega} 49 | H = [H0, [H1, lambda t, args: np.sin(args['w'] * t)]] 50 | e_ops = [qutip.num(2)] 51 | 52 | trial = qutip.fsesolve(H, psi0, tlist, e_ops, T, args).expect[0] 53 | expected = qutip.mesolve(H, psi0, tlist, [], e_ops, args).expect[0] 54 | 55 | np.testing.assert_allclose(trial, expected, atol=1e-4) 56 | -------------------------------------------------------------------------------- /qutip/qip/qubits.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | __all__ = ['qubit_states'] 35 | 36 | from qutip.tensor import tensor 37 | from numpy import sqrt 38 | from qutip.states import basis 39 | 40 | 41 | def qubit_states(N=1, states=[0]): 42 | """ 43 | Function to define initial state of the qubits. 44 | 45 | Parameters 46 | ---------- 47 | N : Integer 48 | Number of qubits in the register. 49 | states : List 50 | Initial state of each qubit. 51 | 52 | Returns 53 | ---------- 54 | qstates : Qobj 55 | List of qubits. 56 | 57 | """ 58 | state_list = [] 59 | for i in range(N): 60 | if N > len(states) and i >= len(states): 61 | state_list.append(0) 62 | else: 63 | state_list.append(states[i]) 64 | 65 | return tensor([alpha * basis(2, 1) + sqrt(1 - alpha**2) * basis(2, 0) 66 | for alpha in state_list]) 67 | -------------------------------------------------------------------------------- /qutip/cy/openmp/benchmark.pyx: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | cimport cython 35 | from qutip.cy.spmatfuncs cimport spmvpy 36 | from qutip.cy.openmp.parfuncs cimport spmvpy_openmp 37 | 38 | 39 | @cython.boundscheck(False) 40 | @cython.wraparound(False) 41 | def _spmvpy(complex[::1] data, 42 | int[::1] ind, 43 | int[::1] ptr, 44 | complex[::1] vec, 45 | complex a, 46 | complex[::1] out): 47 | spmvpy(&data[0], &ind[0], &ptr[0], &vec[0], a, &out[0], vec.shape[0]) 48 | 49 | 50 | 51 | @cython.boundscheck(False) 52 | @cython.wraparound(False) 53 | def _spmvpy_openmp(complex[::1] data, 54 | int[::1] ind, 55 | int[::1] ptr, 56 | complex[::1] vec, 57 | complex a, 58 | complex[::1] out, 59 | unsigned int num_threads): 60 | spmvpy_openmp(&data[0], &ind[0], &ptr[0], &vec[0], a, &out[0], vec.shape[0], num_threads) 61 | -------------------------------------------------------------------------------- /qutip/cy/openmp/br_omp.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, The QuTiP Project. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | cimport numpy as cnp 35 | 36 | #Spectral function with signature (w,t) 37 | ctypedef complex (*spec_func)(double, double) 38 | 39 | 40 | cdef void cop_super_mult_openmp(complex[::1,:] cop, complex[::1,:] evecs, double complex * vec, 41 | double complex alpha, 42 | double complex * out, 43 | unsigned int nrows, 44 | unsigned int omp_thresh, 45 | unsigned int nthr, 46 | double atol) 47 | 48 | 49 | cdef void br_term_mult_openmp(double t, complex[::1,:] A, complex[::1,:] evecs, 50 | double[:,::1] skew, double dw_min, spec_func spectral, 51 | double complex * vec, double complex * out, 52 | unsigned int nrows, int use_secular, 53 | double sec_cutoff, 54 | unsigned int omp_thresh, 55 | unsigned int nthr, 56 | double atol) 57 | -------------------------------------------------------------------------------- /qutip/control/symplectic.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2014 and later, Alexander J G Pitchford 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | # @author: Alexander Pitchford 36 | # @email1: agp1@aber.ac.uk 37 | # @email2: alex.pitchford@gmail.com 38 | # @organization: Aberystwyth University 39 | # @supervisor: Daniel Burgarth 40 | 41 | """ 42 | Utility functions for symplectic matrices 43 | """ 44 | 45 | import numpy as np 46 | 47 | def calc_omega(n): 48 | """ 49 | Calculate the 2n x 2n Omega matrix 50 | Used as dynamics generator phase to calculate symplectic propagators 51 | 52 | Parameters 53 | ---------- 54 | n : scalar(int) 55 | number of modes in oscillator system 56 | 57 | Returns 58 | ------- 59 | array(float) 60 | Symplectic phase Omega 61 | """ 62 | 63 | omg = np.zeros((2*n, 2*n)) 64 | for j in range(2*n): 65 | for k in range(2*n): 66 | if k == j+1: 67 | omg[j, k] = (1 + (-1)**j)/2 68 | if k == j-1: 69 | omg[j, k] = -(1 - (-1)**j)/2 70 | 71 | return omg 72 | -------------------------------------------------------------------------------- /qutip/tests/test_three_level.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import numpy as np 35 | from numpy.testing import assert_, assert_equal, run_module_suite 36 | from qutip.states import basis 37 | from qutip.three_level_atom import * 38 | 39 | 40 | three_states = three_level_basis() 41 | three_check = np.array([basis(3), basis(3, 1), basis(3, 2)], dtype=object) 42 | three_ops = three_level_ops() 43 | 44 | 45 | def testThreeStates(): 46 | "Three-level atom: States" 47 | assert_equal(np.all(three_states == three_check), True) 48 | 49 | 50 | def testThreeOps(): 51 | "Three-level atom: Operators" 52 | assert_equal((three_ops[0]*three_states[0]).full(), three_check[0].full()) 53 | assert_equal((three_ops[1]*three_states[1]).full(), three_check[1].full()) 54 | assert_equal((three_ops[2]*three_states[2]).full(), three_check[2].full()) 55 | assert_equal((three_ops[3]*three_states[1]).full(), three_check[0].full()) 56 | assert_equal((three_ops[4]*three_states[1]).full(), three_check[2].full()) 57 | 58 | if __name__ == "__main__": 59 | run_module_suite() 60 | -------------------------------------------------------------------------------- /qutip/cy/spmath.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, The QuTiP Project. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | from qutip.cy.sparse_structs cimport CSR_Matrix 36 | 37 | cdef void _zcsr_add(CSR_Matrix * A, CSR_Matrix * B, 38 | CSR_Matrix * C, double complex alpha) 39 | 40 | cdef int _zcsr_add_core(double complex * Adata, int * Aind, int * Aptr, 41 | double complex * Bdata, int * Bind, int * Bptr, 42 | double complex alpha, 43 | CSR_Matrix * C, 44 | int nrows, int ncols) nogil 45 | 46 | cdef void _zcsr_mult(CSR_Matrix * A, CSR_Matrix * B, CSR_Matrix * C) 47 | 48 | 49 | cdef void _zcsr_kron(CSR_Matrix * A, CSR_Matrix * B, CSR_Matrix * C) 50 | 51 | cdef void _zcsr_kron_core(double complex * dataA, int * indsA, int * indptrA, 52 | double complex * dataB, int * indsB, int * indptrB, 53 | CSR_Matrix * out, 54 | int rowsA, int rowsB, int colsB) nogil 55 | 56 | cdef void _zcsr_transpose(CSR_Matrix * A, CSR_Matrix * B) 57 | 58 | cdef void _zcsr_adjoint(CSR_Matrix * A, CSR_Matrix * B) 59 | -------------------------------------------------------------------------------- /qutip/cy/src/zspmv.hpp: -------------------------------------------------------------------------------- 1 | // This file is part of QuTiP: Quantum Toolbox in Python. 2 | // 3 | // Copyright (c) 2011 and later, QuSTaR. 4 | // All rights reserved. 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // 1. Redistributions of source code must retain the above copyright notice, 11 | // this list of conditions and the following disclaimer. 12 | // 13 | // 2. Redistributions in binary form must reproduce the above copyright 14 | // notice, this list of conditions and the following disclaimer in the 15 | // documentation and/or other materials provided with the distribution. 16 | // 17 | // 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | // of its contributors may be used to endorse or promote products derived 19 | // from this software without specific prior written permission. 20 | // 21 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | //############################################################################# 33 | #include 34 | 35 | #ifdef __GNUC__ 36 | void zspmvpy(const std::complex * __restrict__ data, const int * __restrict__ ind, 37 | const int *__restrict__ ptr, 38 | const std::complex * __restrict__ vec, const std::complex a, 39 | std::complex * __restrict__ out, 40 | const unsigned int nrows); 41 | #elif defined(_MSC_VER) 42 | void zspmvpy(const std::complex * __restrict data, const int * __restrict ind, 43 | const int *__restrict ptr, 44 | const std::complex * __restrict vec, const std::complex a, 45 | std::complex * __restrict out, 46 | const unsigned int nrows); 47 | #else 48 | void zspmvpy(const std::complex * data, const int * ind, 49 | const int * ptr, 50 | const std::complex * vec, const std::complex a, 51 | std::complex * out, 52 | const unsigned int nrows); 53 | #endif -------------------------------------------------------------------------------- /qutip/testing.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | from qutip.about import about 34 | from qutip import settings as qset 35 | 36 | def run(full=False): 37 | """ 38 | Run the test scripts for QuTiP. 39 | 40 | Parameters 41 | ---------- 42 | full: bool 43 | If True run all test (30 min). Otherwise skip few variants of the 44 | slowest tests. 45 | """ 46 | # Call about to get all version info printed with tests 47 | about() 48 | import pytest 49 | real_num_cpu = qset.num_cpus 50 | real_thresh = qset.openmp_thresh 51 | if qset.has_openmp: 52 | # For travis which VMs have only 1 cpu. 53 | # Make sure the openmp version of the functions are tested. 54 | qset.num_cpus = 2 55 | qset.openmp_thresh = 100 56 | 57 | test_options = ["--verbosity=1", "--disable-pytest-warnings", "--pyargs"] 58 | if not full: 59 | test_options += ['-m', 'not slow'] 60 | pytest.main(test_options + ["qutip"]) 61 | # runs tests in qutip.tests module only 62 | 63 | # Restore previous settings 64 | if qset.has_openmp: 65 | qset.num_cpus = real_num_cpu 66 | qset.openmp_thresh = real_thresh 67 | -------------------------------------------------------------------------------- /qutip/cy/inter.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | cdef complex _spline_complex_t_second(double x, double[::1] t, 36 | complex[::1] y, complex[::1] M, 37 | int N) 38 | 39 | cdef complex _spline_complex_cte_second(double x, double[::1] t, 40 | complex[::1] y, complex[::1] M, 41 | int N, double dt) 42 | 43 | cdef double _spline_float_t_second(double x, double[::1] t, 44 | double[::1] y, double[::1] M, 45 | int N) 46 | 47 | cdef double _spline_float_cte_second(double x, double[::1] t, 48 | double[::1] y, double[::1] M, 49 | int N, double dt) 50 | 51 | cdef double _step_float_cte(double x, double[::1] t, double[::1] y, int n_t) 52 | 53 | cdef complex _step_complex_cte(double x, double[::1] t, complex[::1] y, int n_t) 54 | 55 | cdef double _step_float_t(double x, double[::1] t, double[::1] y, int n_t) 56 | 57 | cdef complex _step_complex_t(double x, double[::1] t, complex[::1] y, int n_t) 58 | -------------------------------------------------------------------------------- /qutip/cy/openmp/src/zspmv_openmp.hpp: -------------------------------------------------------------------------------- 1 | // This file is part of QuTiP: Quantum Toolbox in Python. 2 | // 3 | // Copyright (c) 2011 and later, QuSTaR. 4 | // All rights reserved. 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // 1. Redistributions of source code must retain the above copyright notice, 11 | // this list of conditions and the following disclaimer. 12 | // 13 | // 2. Redistributions in binary form must reproduce the above copyright 14 | // notice, this list of conditions and the following disclaimer in the 15 | // documentation and/or other materials provided with the distribution. 16 | // 17 | // 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | // of its contributors may be used to endorse or promote products derived 19 | // from this software without specific prior written permission. 20 | // 21 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | //############################################################################# 33 | #include 34 | 35 | #ifdef __GNUC__ 36 | void zspmvpy_openmp(const std::complex * __restrict__ data, const int * __restrict__ ind, 37 | const int *__restrict__ ptr, 38 | const std::complex * __restrict__ vec, const std::complex a, 39 | std::complex * __restrict__ out, 40 | const unsigned int nrows, const unsigned int nthr); 41 | #elif defined(_MSC_VER) 42 | void zspmvpy_openmp(const std::complex * __restrict data, const int * __restrict ind, 43 | const int *__restrict ptr, 44 | const std::complex * __restrict vec, const std::complex a, 45 | std::complex * __restrict out, 46 | const int nrows, const unsigned int nthr); 47 | #else 48 | void zspmvpy_openmp(const std::complex * data, const int * ind, 49 | const int * ptr, 50 | const std::complex * vec, const std::complex a, 51 | std::complex * out, 52 | const unsigned int nrows, const unsigned int nthr); 53 | #endif -------------------------------------------------------------------------------- /qutip/cy/openmp/omp_sparse_utils.pyx: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | import numpy as np 35 | cimport numpy as cnp 36 | cimport cython 37 | from libcpp cimport bool 38 | from libc.math cimport fabs 39 | from cython.parallel cimport parallel, prange 40 | 41 | cdef extern from "" namespace "std" nogil: 42 | double real(double complex x) 43 | double imag(double complex x) 44 | 45 | 46 | @cython.boundscheck(False) 47 | @cython.wraparound(False) 48 | cpdef bool omp_tidyup(complex[::1] data, double atol, int nnz, int nthr): 49 | cdef int kk, 50 | cdef double re, im 51 | cdef bool re_flag, im_flag, out_flag = 0 52 | with nogil, parallel(num_threads = nthr): 53 | for kk in prange(nnz, schedule='static'): 54 | re_flag = 0 55 | im_flag = 0 56 | re = real(data[kk]) 57 | im = imag(data[kk]) 58 | if fabs(re) < atol: 59 | re = 0 60 | re_flag = 1 61 | if fabs(im) < atol: 62 | im = 0 63 | im_flag = 1 64 | if re_flag or im_flag: 65 | data[kk] = re +1j*im 66 | if re_flag and im_flag: 67 | out_flag = 1 68 | return out_flag 69 | -------------------------------------------------------------------------------- /qutip/cy/openmp/utilities.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, QuSTaR, 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | import os 34 | import numpy as np 35 | import qutip.settings as qset 36 | 37 | 38 | def check_use_openmp(options): 39 | """ 40 | Check to see if OPENMP should be used in dynamic solvers. 41 | """ 42 | force_omp = False 43 | if qset.has_openmp and options.use_openmp is None: 44 | options.use_openmp = True 45 | force_omp = False 46 | elif qset.has_openmp and options.use_openmp == True: 47 | force_omp = True 48 | elif qset.has_openmp and options.use_openmp == False: 49 | force_omp = False 50 | elif qset.has_openmp == False and options.use_openmp == True: 51 | raise Exception('OPENMP not available.') 52 | else: 53 | options.use_openmp = False 54 | force_omp = False 55 | #Disable OPENMP in parallel mode unless explicitly set. 56 | if not force_omp and os.environ['QUTIP_IN_PARALLEL'] == 'TRUE': 57 | options.use_openmp = False 58 | 59 | 60 | def use_openmp(): 61 | """ 62 | Check for using openmp in general cases outside of dynamics 63 | """ 64 | if qset.has_openmp and os.environ['QUTIP_IN_PARALLEL'] != 'TRUE': 65 | return True 66 | else: 67 | return False 68 | 69 | 70 | def openmp_components(ptr_list): 71 | return np.array([ptr[-1] >= qset.openmp_thresh for ptr in ptr_list], dtype=bool) 72 | -------------------------------------------------------------------------------- /qutip/_mkl/spmv.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | import numpy as np 34 | import scipy.sparse as sp 35 | import ctypes 36 | from ctypes import POINTER,c_int,c_char,c_double, byref 37 | from numpy import ctypeslib 38 | import qutip.settings as qset 39 | zcsrgemv = qset.mkl_lib.mkl_cspblas_zcsrgemv 40 | 41 | def mkl_spmv(A, x): 42 | """ 43 | sparse csr_spmv using MKL 44 | """ 45 | (m,n) = A.shape 46 | 47 | # Pointers to data of the matrix 48 | data = A.data.ctypes.data_as(ctypeslib.ndpointer(np.complex128, ndim=1, flags='C')) 49 | indptr = A.indptr.ctypes.data_as(POINTER(c_int)) 50 | indices = A.indices.ctypes.data_as(POINTER(c_int)) 51 | 52 | # Allocate output, using same conventions as input 53 | if x.ndim is 1: 54 | y = np.empty(m,dtype=np.complex,order='C') 55 | elif x.ndim==2 and x.shape[1]==1: 56 | y = np.empty((m,1),dtype=np.complex,order='C') 57 | else: 58 | raise Exception('Input vector must be 1D row or 2D column vector') 59 | 60 | np_x = x.ctypes.data_as(ctypeslib.ndpointer(np.complex128, ndim=1, flags='C')) 61 | np_y = y.ctypes.data_as(ctypeslib.ndpointer(np.complex128, ndim=1, flags='C')) 62 | # now call MKL. This returns the answer in np_y, which points to y 63 | zcsrgemv(byref(c_char(bytes(b'N'))), byref(c_int(m)), data ,indptr, indices, np_x, np_y ) 64 | return y 65 | -------------------------------------------------------------------------------- /qutip/cy/pyxbuilder.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, The QuTiP Project 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | import sys, os 34 | try: 35 | import pyximport 36 | from pyximport import install 37 | 38 | old_get_distutils_extension = pyximport.pyximport.get_distutils_extension 39 | 40 | def new_get_distutils_extension(modname, pyxfilename, language_level=None): 41 | extension_mod, setup_args = old_get_distutils_extension(modname, 42 | pyxfilename, 43 | language_level) 44 | extension_mod.language='c++' 45 | # If on Win and Python version >= 3.5 and not in MSYS2 46 | # (i.e. Visual studio compile) 47 | if sys.platform == 'win32' and \ 48 | int(str(sys.version_info[0]) + 49 | str(sys.version_info[1])) >= 35 and \ 50 | os.environ.get('MSYSTEM') is None: 51 | extension_mod.extra_compile_args = ['/w', '/O1'] 52 | else: 53 | extension_mod.extra_compile_args = ['-w', '-O1'] 54 | if sys.platform == 'darwin': 55 | extension_mod.extra_compile_args.append( 56 | '-mmacosx-version-min=10.9') 57 | extension_mod.extra_link_args = ['-mmacosx-version-min=10.9'] 58 | return extension_mod,setup_args 59 | 60 | pyximport.pyximport.get_distutils_extension = new_get_distutils_extension 61 | except Exception: 62 | pass 63 | -------------------------------------------------------------------------------- /qutip/tests/test_rhs_reuse.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import numpy as np 35 | from numpy.testing import assert_, assert_equal, run_module_suite 36 | import qutip as qt 37 | from qutip.solver import config 38 | 39 | """ 40 | def test_rhs_reuse(): 41 | "" " 42 | rhs_reuse : pyx filenames match for rhs_reus= True 43 | "" " 44 | N = 10 45 | a = qt.destroy(N) 46 | H = [a.dag()*a, [a+a.dag(), 'sin(t)']] 47 | psi0 = qt.fock(N,3) 48 | tlist = np.linspace(0,10,10) 49 | e_ops = [a.dag()*a] 50 | c_ops = [0.25*a] 51 | 52 | # Test sesolve 53 | out1 = qt.mesolve(H, psi0,tlist, e_ops=e_ops) 54 | 55 | _temp_config_name = config.tdname 56 | 57 | out2 = qt.mesolve(H, psi0,tlist, e_ops=e_ops) 58 | 59 | assert_(config.tdname != _temp_config_name) 60 | _temp_config_name = config.tdname 61 | 62 | out3 = qt.mesolve(H, psi0,tlist, e_ops=e_ops, 63 | options=qt.Options(rhs_reuse=True)) 64 | 65 | assert_(config.tdname == _temp_config_name) 66 | 67 | # Test mesolve 68 | 69 | out1 = qt.mesolve(H, psi0,tlist, c_ops=c_ops, e_ops=e_ops) 70 | 71 | _temp_config_name = config.tdname 72 | 73 | out2 = qt.mesolve(H, psi0,tlist, c_ops=c_ops, e_ops=e_ops) 74 | 75 | assert_(config.tdname != _temp_config_name) 76 | _temp_config_name = config.tdname 77 | 78 | out3 = qt.mesolve(H, psi0,tlist, e_ops=e_ops, c_ops=c_ops, 79 | options=qt.Options(rhs_reuse=True)) 80 | 81 | assert_(config.tdname == _temp_config_name) 82 | 83 | if __name__ == "__main__": 84 | run_module_suite() 85 | """ 86 | -------------------------------------------------------------------------------- /qutip/tests/test_qpt.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import numpy as np 35 | from numpy.testing import assert_, run_module_suite 36 | import scipy.linalg as la 37 | 38 | from qutip import (spre, spost, qeye, sigmax, sigmay, sigmaz, qpt) 39 | from qutip.qip.operations.gates import snot, cnot 40 | 41 | 42 | def test_qpt_snot(): 43 | "quantum process tomography for snot gate" 44 | 45 | U_psi = snot() 46 | U_rho = spre(U_psi) * spost(U_psi.dag()) 47 | N = 1 48 | op_basis = [[qeye(2), sigmax(), 1j * sigmay(), sigmaz()] for i in range(N)] 49 | # op_label = [["i", "x", "y", "z"] for i in range(N)] 50 | chi1 = qpt(U_rho, op_basis) 51 | 52 | chi2 = np.zeros((2 ** (2 * N), 2 ** (2 * N)), dtype=complex) 53 | chi2[1, 1] = chi2[1, 3] = chi2[3, 1] = chi2[3, 3] = 0.5 54 | 55 | assert_(la.norm(chi2 - chi1) < 1e-8) 56 | 57 | 58 | def test_qpt_cnot(): 59 | "quantum process tomography for cnot gate" 60 | 61 | U_psi = cnot() 62 | U_rho = spre(U_psi) * spost(U_psi.dag()) 63 | N = 2 64 | op_basis = [[qeye(2), sigmax(), 1j * sigmay(), sigmaz()] for i in range(N)] 65 | # op_label = [["i", "x", "y", "z"] for i in range(N)] 66 | chi1 = qpt(U_rho, op_basis) 67 | 68 | chi2 = np.zeros((2 ** (2 * N), 2 ** (2 * N)), dtype=complex) 69 | chi2[0, 0] = chi2[0, 1] = chi2[1, 0] = chi2[1, 1] = 0.25 70 | 71 | chi2[12, 0] = chi2[12, 1] = 0.25 72 | chi2[13, 0] = chi2[13, 1] = -0.25 73 | 74 | chi2[0, 12] = chi2[1, 12] = 0.25 75 | chi2[0, 13] = chi2[1, 13] = -0.25 76 | 77 | chi2[12, 12] = chi2[13, 13] = 0.25 78 | chi2[13, 12] = chi2[12, 13] = -0.25 79 | 80 | assert_(la.norm(chi2 - chi1) < 1e-8) 81 | 82 | if __name__ == "__main__": 83 | run_module_suite() 84 | -------------------------------------------------------------------------------- /qutip/tests/test_parallel.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import numpy as np 35 | import time 36 | from numpy.testing import assert_, run_module_suite 37 | 38 | from qutip.parallel import parfor, parallel_map, serial_map 39 | 40 | 41 | def _func1(x): 42 | time.sleep(np.random.rand() * 0.25) # random delay 43 | return x**2 44 | 45 | 46 | def _func2(x, a, b, c, d=0, e=0, f=0): 47 | time.sleep(np.random.rand() * 0.25) # random delay 48 | return x**2 49 | 50 | 51 | def test_parfor1(): 52 | "parfor" 53 | 54 | x = np.arange(10) 55 | y1 = list(map(_func1, x)) 56 | y2 = parfor(_func1, x) 57 | 58 | assert_((np.array(y1) == np.array(y2)).all()) 59 | 60 | 61 | def test_parallel_map(): 62 | "parallel_map" 63 | 64 | args = (1, 2, 3) 65 | kwargs = {'d': 4, 'e': 5, 'f': 6} 66 | 67 | x = np.arange(10) 68 | y1 = list(map(_func1, x)) 69 | y1 = [_func2(xx, *args, **kwargs)for xx in x] 70 | 71 | y2 = parallel_map(_func2, x, args, kwargs, num_cpus=1) 72 | assert_((np.array(y1) == np.array(y2)).all()) 73 | 74 | y2 = parallel_map(_func2, x, args, kwargs, num_cpus=2) 75 | assert_((np.array(y1) == np.array(y2)).all()) 76 | 77 | 78 | def test_serial_map(): 79 | "serial_map" 80 | 81 | args = (1, 2, 3) 82 | kwargs = {'d': 4, 'e': 5, 'f': 6} 83 | 84 | x = np.arange(10) 85 | y1 = list(map(_func1, x)) 86 | y1 = [_func2(xx, *args, **kwargs)for xx in x] 87 | 88 | y2 = serial_map(_func2, x, args, kwargs, num_cpus=1) 89 | assert_((np.array(y1) == np.array(y2)).all()) 90 | 91 | y2 = serial_map(_func2, x, args, kwargs, num_cpus=2) 92 | assert_((np.array(y1) == np.array(y2)).all()) 93 | 94 | if __name__ == "__main__": 95 | run_module_suite() 96 | -------------------------------------------------------------------------------- /qutip/_mkl/utilities.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import numpy as np 35 | import os, sys 36 | from qutip.utilities import _blas_info 37 | import qutip.settings as qset 38 | from ctypes import cdll 39 | 40 | 41 | def _set_mkl(): 42 | """ 43 | Finds the MKL runtime library for the 44 | Anaconda and Intel Python distributions. 45 | 46 | """ 47 | if _blas_info() == 'INTEL MKL': 48 | plat = sys.platform 49 | python_dir = os.path.dirname(sys.executable) 50 | if plat in ['darwin','linux2', 'linux']: 51 | python_dir = os.path.dirname(python_dir) 52 | 53 | if plat == 'darwin': 54 | lib = '/libmkl_rt.dylib' 55 | elif plat == 'win32': 56 | lib = '\\mkl_rt.dll' 57 | elif plat in ['linux2', 'linux']: 58 | lib = '/libmkl_rt.so' 59 | else: 60 | raise Exception('Unknown platfrom.') 61 | 62 | if plat in ['darwin','linux2', 'linux']: 63 | lib_dir = '/lib' 64 | else: 65 | lib_dir = '\Library\\bin' 66 | 67 | # Try in default Anaconda location first 68 | try: 69 | qset.mkl_lib = cdll.LoadLibrary(python_dir+lib_dir+lib) 70 | qset.has_mkl = True 71 | except: 72 | pass 73 | 74 | # Look in Intel Python distro location 75 | if not qset.has_mkl: 76 | if plat in ['darwin','linux2', 'linux']: 77 | lib_dir = '/ext/lib' 78 | else: 79 | lib_dir = '\ext\\lib' 80 | try: 81 | qset.mkl_lib = cdll.LoadLibrary(python_dir+lib_dir+lib) 82 | qset.has_mkl = True 83 | except: 84 | pass 85 | else: 86 | pass 87 | 88 | 89 | if __name__ == "__main__": 90 | _set_mkl() 91 | print(qset.has_mkl) 92 | -------------------------------------------------------------------------------- /qutip/settings.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | """ 34 | This module contains settings for the QuTiP graphics, multiprocessing, and 35 | tidyup functionality, etc. 36 | """ 37 | from __future__ import absolute_import 38 | # use auto tidyup 39 | auto_tidyup = True 40 | # use auto tidyup dims on multiplication 41 | auto_tidyup_dims = True 42 | # detect hermiticity 43 | auto_herm = True 44 | # general absolute tolerance 45 | atol = 1e-12 46 | # use auto tidyup absolute tolerance 47 | auto_tidyup_atol = 1e-12 48 | # number of cpus (set at qutip import) 49 | num_cpus = 0 50 | # flag indicating if fortran module is installed 51 | fortran = False 52 | # path to the MKL library 53 | mkl_lib = None 54 | # Flag if mkl_lib is found 55 | has_mkl = False 56 | # Has OPENMP 57 | has_openmp = False 58 | # debug mode for development 59 | debug = False 60 | # are we in IPython? Note that this cannot be 61 | # set by the RC file. 62 | ipython = False 63 | # define whether log handler should be 64 | # - default: switch based on IPython detection 65 | # - stream: set up non-propagating StreamHandler 66 | # - basic: call basicConfig 67 | # - null: leave logging to the user 68 | log_handler = 'default' 69 | # Allow for a colorblind mode that uses different colormaps 70 | # and plotting options by default. 71 | colorblind_safe = False 72 | # Sets the threshold for matrix NNZ where OPENMP 73 | # turns on. This is automatically calculated and 74 | # put in the qutiprc file. This value is here in case 75 | # that failts 76 | openmp_thresh = 10000 77 | # Note that since logging depends on settings, 78 | # if we want to do any logging here, it must be manually 79 | # configured, rather than through _logging.get_logger(). 80 | try: 81 | import logging 82 | _logger = logging.getLogger(__name__) 83 | _logger.addHandler(logging.NullHandler()) 84 | del logging # Don't leak names! 85 | except: 86 | _logger = None 87 | -------------------------------------------------------------------------------- /qutip/control/io.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2016 and later, Alexander J G Pitchford 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | import os 36 | import errno 37 | 38 | def create_dir(dir_name, desc='output'): 39 | """ 40 | Checks if the given directory exists, if not it is created 41 | 42 | Returns 43 | ------- 44 | dir_ok : boolean 45 | True if directory exists (previously or created) 46 | False if failed to create the directory 47 | 48 | dir_name : string 49 | Path to the directory, which may be been made absolute 50 | 51 | msg : string 52 | Error msg if directory creation failed 53 | 54 | """ 55 | 56 | dir_ok = True 57 | if '~' in dir_name: 58 | dir_name = os.path.expanduser(dir_name) 59 | elif not os.path.isabs(dir_name): 60 | # Assume relative path from cwd given 61 | dir_name = os.path.abspath(dir_name) 62 | 63 | msg = "{} directory is ready".format(desc) 64 | errmsg = "Failed to create {} directory:\n{}\n".format(desc, 65 | dir_name) 66 | 67 | if os.path.exists(dir_name): 68 | if os.path.isfile(dir_name): 69 | dir_ok = False 70 | errmsg += "A file already exists with the same name" 71 | else: 72 | try: 73 | os.makedirs(dir_name) 74 | msg += ("directory {} created " 75 | "(recursively)".format(dir_name)) 76 | except OSError as e: 77 | if e.errno == errno.EEXIST: 78 | msg += ("Assume directory {} created " 79 | "(recursively) by some other process. ".format(dir_name)) 80 | else: 81 | dir_ok = False 82 | errmsg += "Underling error (makedirs) :({}) {}".format( 83 | type(e).__name__, e) 84 | 85 | if dir_ok: 86 | return dir_ok, dir_name, msg 87 | else: 88 | return dir_ok, dir_name, errmsg 89 | -------------------------------------------------------------------------------- /qutip/cy/heom.pyx: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | import numpy as np 35 | cimport numpy as cnp 36 | cimport cython 37 | 38 | @cython.boundscheck(False) 39 | @cython.wraparound(False) 40 | def cy_pad_csr(object A, int row_scale, int col_scale, int insertrow=0, int insertcol=0): 41 | cdef int nrowin = A.shape[0] 42 | cdef int ncolin = A.shape[1] 43 | cdef int nnz = A.indptr[nrowin] 44 | cdef int nrowout = nrowin*row_scale 45 | cdef int ncolout = ncolin*col_scale 46 | cdef size_t kk 47 | cdef int temp, temp2 48 | cdef int[::1] ind = A.indices 49 | cdef int[::1] ptr_in = A.indptr 50 | cdef cnp.ndarray[int, ndim=1, mode='c'] ptr_out = np.zeros(nrowout+1,dtype=np.int32) 51 | 52 | A._shape = (nrowout, ncolout) 53 | if insertcol == 0: 54 | pass 55 | elif insertcol > 0 and insertcol < col_scale: 56 | temp = insertcol*ncolin 57 | for kk in range(nnz): 58 | ind[kk] += temp 59 | else: 60 | raise ValueError("insertcol must be >= 0 and < col_scale") 61 | 62 | 63 | if insertrow == 0: 64 | temp = ptr_in[nrowin] 65 | for kk in range(nrowin): 66 | ptr_out[kk] = ptr_in[kk] 67 | for kk in range(nrowin, nrowout+1): 68 | ptr_out[kk] = temp 69 | 70 | elif insertrow == row_scale-1: 71 | temp = (row_scale - 1) * nrowin 72 | for kk in range(temp, nrowout+1): 73 | ptr_out[kk] = ptr_in[kk-temp] 74 | 75 | elif insertrow > 0 and insertrow < row_scale - 1: 76 | temp = insertrow*nrowin 77 | for kk in range(temp, temp+nrowin): 78 | ptr_out[kk] = ptr_in[kk-temp] 79 | temp = kk+1 80 | temp2 = ptr_in[nrowin] 81 | for kk in range(temp, nrowout+1): 82 | ptr_out[kk] = temp2 83 | else: 84 | raise ValueError("insertrow must be >= 0 and < row_scale") 85 | 86 | A.indptr = ptr_out 87 | 88 | return A 89 | -------------------------------------------------------------------------------- /qutip/cy/brtools.pxd: -------------------------------------------------------------------------------- 1 | #!python 2 | #cython: language_level=3 3 | # This file is part of QuTiP: Quantum Toolbox in Python. 4 | # 5 | # Copyright (c) 2011 and later, The QuTiP Project. 6 | # All rights reserved. 7 | # 8 | # Redistribution and use in source and binary forms, with or without 9 | # modification, are permitted provided that the following conditions are 10 | # met: 11 | # 12 | # 1. Redistributions of source code must retain the above copyright notice, 13 | # this list of conditions and the following disclaimer. 14 | # 15 | # 2. Redistributions in binary form must reproduce the above copyright 16 | # notice, this list of conditions and the following disclaimer in the 17 | # documentation and/or other materials provided with the distribution. 18 | # 19 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 20 | # of its contributors may be used to endorse or promote products derived 21 | # from this software without specific prior written permission. 22 | # 23 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 24 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 25 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 26 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 27 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 28 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 29 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 30 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 31 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 33 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | ############################################################################### 35 | cimport numpy as np 36 | 37 | #Spectral function with signature (w,t) 38 | ctypedef complex (*spec_func)(double, double) 39 | 40 | cdef complex[::1,:] farray_alloc(int nrows) 41 | 42 | cpdef void dense_add_mult(complex[::1,:] A, complex[::1,:] B, 43 | double complex alpha) nogil 44 | 45 | cdef void ZHEEVR(complex[::1,:] H, double * eigvals, 46 | complex[::1,:] Z, int nrows) 47 | 48 | cdef complex[::1,:] dense_to_eigbasis(complex[::1,:] A, complex[::1,:] evecs, 49 | unsigned int nrows, double atol) 50 | 51 | cdef void diag_liou_mult(double * diags, double complex * vec, 52 | double complex * out, unsigned int nrows) nogil 53 | 54 | cdef double complex * vec_to_eigbasis(complex[::1] vec, complex[::1,:] evecs, 55 | unsigned int nrows) 56 | 57 | cdef np.ndarray[complex, ndim=1, mode='c'] vec_to_fockbasis(double complex * eig_vec, 58 | complex[::1,:] evecs, 59 | unsigned int nrows) 60 | 61 | cdef void cop_super_mult(complex[::1,:] cop, complex[::1,:] evecs, double complex * vec, 62 | double complex alpha, 63 | double complex * out, 64 | unsigned int nrows, 65 | double atol) 66 | 67 | cdef void vec2mat_index(int nrows, int index, int[2] out) nogil 68 | 69 | cdef double skew_and_dwmin(double * evals, double[:,::1] skew, 70 | unsigned int nrows) nogil 71 | 72 | 73 | cdef void br_term_mult(double t, complex[::1,:] A, complex[::1,:] evecs, 74 | double[:,::1] skew, double dw_min, spec_func spectral, 75 | double complex * vec, double complex * out, 76 | unsigned int nrows, int use_secular, double sec_cutoff, 77 | double atol) 78 | -------------------------------------------------------------------------------- /qutip/tests/test_qft.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | from numpy.testing import assert_, assert_equal, assert_string_equal, run_module_suite 35 | from qutip.qip.algorithms.qft import qft, qft_steps, qft_gate_sequence 36 | from qutip.qip.operations.gates import gate_sequence_product 37 | 38 | 39 | class TestQFT: 40 | """ 41 | A test class for the QuTiP functions for QFT 42 | """ 43 | 44 | def testQFTComparison(self): 45 | """ 46 | qft: compare qft and product of qft steps 47 | """ 48 | for N in range(1, 5): 49 | U1 = qft(N) 50 | U2 = gate_sequence_product(qft_steps(N)) 51 | assert_((U1 - U2).norm() < 1e-12) 52 | 53 | def testQFTGateSequenceNoSwapping(self): 54 | """ 55 | qft: Inspect key properties of gate sequences of length N, 56 | with swapping disabled. 57 | """ 58 | for N in range(1, 6): 59 | circuit = qft_gate_sequence(N, swapping=False) 60 | assert_equal(circuit.N, N) 61 | 62 | totsize = N * (N + 1) / 2 63 | assert_equal(len(circuit.gates), totsize) 64 | 65 | snots = sum(g.name == "SNOT" for g in circuit.gates) 66 | assert_equal(snots, N) 67 | 68 | phases = sum(g.name == "CPHASE" for g in circuit.gates) 69 | assert_equal(phases, N * (N - 1) / 2) 70 | 71 | def testQFTGateSequenceWithSwapping(self): 72 | """ 73 | qft: Inspect swap gates added to gate sequences if 74 | swapping is enabled. 75 | """ 76 | for N in range(1, 6): 77 | circuit = qft_gate_sequence(N, swapping=True) 78 | 79 | phases = int(N * (N + 1) / 2) 80 | swaps = int(N // 2) 81 | assert_equal(len(circuit.gates), phases + swaps) 82 | 83 | for i in range(phases, phases + swaps): 84 | assert_string_equal(circuit.gates[i].name, "SWAP") 85 | 86 | if __name__ == "__main__": 87 | run_module_suite() 88 | -------------------------------------------------------------------------------- /qutip/tests/test_td_formats.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | from numpy.testing import assert_, run_module_suite 35 | 36 | from qutip import rand_herm, qeye 37 | from qutip.rhs_generate import _td_format_check 38 | 39 | 40 | def test_setTDFormatCheckMC(): 41 | "td_format_check: monte-carlo" 42 | 43 | # define operators 44 | H = rand_herm(10) 45 | c_op = qeye(10) 46 | 47 | def f_c_op(t, args): 48 | return 0 49 | 50 | def f_H(t, args): 51 | return 0 52 | # check constant H and no C_ops 53 | time_type, h_stuff, c_stuff = _td_format_check(H, [], 'mc') 54 | assert_(time_type == 0) 55 | 56 | # check constant H and constant C_ops 57 | time_type, h_stuff, c_stuff = _td_format_check(H, [c_op], 'mc') 58 | assert_(time_type == 0) 59 | 60 | # check constant H and str C_ops 61 | time_type, h_stuff, c_stuff = _td_format_check(H, [c_op, '1'], 'mc') 62 | # assert_(time_type==1) # this test fails!! 63 | 64 | # check constant H and func C_ops 65 | time_type, h_stuff, c_stuff = _td_format_check(H, [f_c_op], 'mc') 66 | # assert_(time_type==2) # FAILURE 67 | 68 | # check str H and constant C_ops 69 | time_type, h_stuff, c_stuff = _td_format_check([H, '1'], [c_op], 'mc') 70 | # assert_(time_type==10) 71 | 72 | # check str H and str C_ops 73 | time_type, h_stuff, c_stuff = _td_format_check([H, '1'], [c_op, '1'], 'mc') 74 | # assert_(time_type==11) 75 | 76 | # check str H and func C_ops 77 | time_type, h_stuff, c_stuff = _td_format_check([H, '1'], [f_c_op], 'mc') 78 | # assert_(time_type==12) 79 | 80 | # check func H and constant C_ops 81 | time_type, h_stuff, c_stuff = _td_format_check(f_H, [c_op], 'mc') 82 | # assert_(time_type==20) 83 | 84 | # check func H and str C_ops 85 | time_type, h_stuff, c_stuff = _td_format_check(f_H, [c_op, '1'], 'mc') 86 | # assert_(time_type==21) 87 | 88 | # check func H and func C_ops 89 | time_type, h_stuff, c_stuff = _td_format_check(f_H, [f_c_op], 'mc') 90 | # assert_(time_type==22) 91 | 92 | 93 | if __name__ == "__main__": 94 | run_module_suite() 95 | -------------------------------------------------------------------------------- /qutip/tests/test_cy_structs.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import pytest 35 | import numpy as np 36 | import scipy.sparse 37 | import qutip 38 | from qutip.fastsparse import fast_csr_matrix 39 | from qutip.cy.checks import (_test_sorting, _test_coo2csr_inplace_struct, 40 | _test_csr2coo_struct, _test_coo2csr_struct) 41 | from qutip.random_objects import rand_jacobi_rotation 42 | 43 | 44 | def _unsorted_csr(N, density=0.5): 45 | M = scipy.sparse.diags(np.arange(N), 0, dtype=complex, format='csr') 46 | nvals = N**2 * density 47 | while M.nnz < 0.95*nvals: 48 | M = rand_jacobi_rotation(M) 49 | M = M.tocsr() 50 | return fast_csr_matrix((M.data, M.indices, M.indptr), shape=M.shape) 51 | 52 | 53 | def sparse_arrays_equal(a, b): 54 | return not (a != b).data.any() 55 | 56 | 57 | @pytest.mark.repeat(20) 58 | def test_coo2csr_struct(): 59 | "Cython structs : COO to CSR" 60 | A = qutip.rand_dm(5, 0.5).data 61 | assert sparse_arrays_equal(A, _test_coo2csr_struct(A.tocoo())) 62 | 63 | 64 | @pytest.mark.repeat(20) 65 | def test_indices_sort(): 66 | "Cython structs : sort CSR indices inplace" 67 | A = _unsorted_csr(10, 0.25) 68 | B = A.copy() 69 | B.sort_indices() 70 | _test_sorting(A) 71 | assert np.all(A.data == B.data) 72 | assert np.all(A.indices == B.indices) 73 | 74 | 75 | @pytest.mark.repeat(20) 76 | def test_coo2csr_inplace_nosort(): 77 | "Cython structs : COO to CSR inplace (no sort)" 78 | A = qutip.rand_dm(5, 0.5).data 79 | B = _test_coo2csr_inplace_struct(A.tocoo(), sorted=0) 80 | assert sparse_arrays_equal(A, B) 81 | 82 | 83 | @pytest.mark.repeat(20) 84 | def test_coo2csr_inplace_sort(): 85 | "Cython structs : COO to CSR inplace (sorted)" 86 | A = qutip.rand_dm(5, 0.5).data 87 | B = _test_coo2csr_inplace_struct(A.tocoo(), sorted=1) 88 | assert sparse_arrays_equal(A, B) 89 | 90 | 91 | @pytest.mark.repeat(20) 92 | def test_csr2coo(): 93 | "Cython structs : CSR to COO" 94 | A = qutip.rand_dm(5, 0.5).data 95 | B = A.tocoo() 96 | C = _test_csr2coo_struct(A) 97 | assert sparse_arrays_equal(B, C) 98 | -------------------------------------------------------------------------------- /qutip/tests/test_fastsparse.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, The QuTiP Project. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import pytest 35 | import scipy.sparse 36 | import qutip 37 | from qutip.fastsparse import fast_csr_matrix 38 | 39 | 40 | class TestOperationEffectsOnType: 41 | @pytest.mark.parametrize("operation", [ 42 | pytest.param(lambda x: x, id="identity"), 43 | pytest.param(lambda x: x + x, id="addition"), 44 | pytest.param(lambda x: x - x, id="subtraction"), 45 | pytest.param(lambda x: x * x, id="multiplication by op"), 46 | pytest.param(lambda x: 2*x, id="multiplication by scalar"), 47 | pytest.param(lambda x: x/3, id="division by scalar"), 48 | pytest.param(lambda x: -x, id="negation"), 49 | pytest.param(lambda x: x.copy(), id="copy"), 50 | pytest.param(lambda x: x.T, id="transpose [.T]"), 51 | pytest.param(lambda x: x.trans(), id="transpose [.trans()]"), 52 | pytest.param(lambda x: x.transpose(), id="transpose [.transpose()]"), 53 | pytest.param(lambda x: x.H, id="adjoint [.H]"), 54 | pytest.param(lambda x: x.getH(), id="adjoint [.getH()]"), 55 | pytest.param(lambda x: x.adjoint(), id="adjoint [.adjoint()]"), 56 | ]) 57 | def test_operations_preserve_type(self, operation): 58 | op = qutip.rand_herm(5).data 59 | assert isinstance(operation(op), fast_csr_matrix) 60 | 61 | @pytest.mark.parametrize("operation", [ 62 | pytest.param(lambda x, y: y, id="identity of other"), 63 | pytest.param(lambda x, y: x + y, id="addition"), 64 | pytest.param(lambda x, y: y + x, id="r-addition"), 65 | pytest.param(lambda x, y: x - y, id="subtraction"), 66 | pytest.param(lambda x, y: y - x, id="r-subtraction"), 67 | pytest.param(lambda x, y: x * y, id="multiplication"), 68 | pytest.param(lambda x, y: y * x, id="r-multiplication"), 69 | ]) 70 | def test_mixed_operations_yield_type(self, operation): 71 | op = qutip.rand_herm(5).data 72 | other = scipy.sparse.csr_matrix((op.data, op.indices, op.indptr), 73 | copy=True, shape=op.shape) 74 | assert not isinstance(operation(op, other), fast_csr_matrix) 75 | -------------------------------------------------------------------------------- /qutip/tests/test_countstat.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import numpy as np 35 | import qutip 36 | 37 | 38 | def test_dqd_current(): 39 | "Counting statistics: current and current noise in a DQD model" 40 | 41 | G = 0 42 | L = 1 43 | R = 2 44 | 45 | sz = qutip.projection(3, L, L) - qutip.projection(3, R, R) 46 | sx = qutip.projection(3, L, R) + qutip.projection(3, R, L) 47 | sR = qutip.projection(3, G, R) 48 | sL = qutip.projection(3, G, L) 49 | 50 | w0 = 1 51 | tc = 0.6 * w0 52 | GammaR = 0.0075 * w0 53 | GammaL = 0.0075 * w0 54 | nth = 0.00 55 | eps_vec = np.linspace(-1.5*w0, 1.5*w0, 20) 56 | 57 | J_ops = [GammaR * qutip.sprepost(sR, sR.dag())] 58 | 59 | c_ops = [np.sqrt(GammaR * (1 + nth)) * sR, 60 | np.sqrt(GammaR * (nth)) * sR.dag(), 61 | np.sqrt(GammaL * (nth)) * sL, 62 | np.sqrt(GammaL * (1 + nth)) * sL.dag()] 63 | 64 | current = np.zeros(len(eps_vec)) 65 | noise = np.zeros(len(eps_vec)) 66 | 67 | for n, eps in enumerate(eps_vec): 68 | H = (eps/2 * sz + tc * sx) 69 | L = qutip.liouvillian(H, c_ops) 70 | rhoss = qutip.steadystate(L) 71 | current[n], noise[n] = qutip.countstat_current_noise(L, [], 72 | rhoss=rhoss, 73 | J_ops=J_ops) 74 | 75 | current2 = qutip.countstat_current(L, rhoss=rhoss, J_ops=J_ops) 76 | assert abs(current[n] - current2) < 1e-8 77 | 78 | current2 = qutip.countstat_current(L, c_ops, J_ops=J_ops) 79 | assert abs(current[n] - current2) < 1e-8 80 | 81 | current_target = (tc**2 * GammaR 82 | / (tc**2 * (2+GammaR/GammaL) + GammaR**2/4 + eps_vec**2)) 83 | noise_target = current_target * ( 84 | 1 - (8*GammaL*tc**2*(4 * eps_vec**2 * (GammaR - GammaL) 85 | + GammaR*(3*GammaL*GammaR + GammaR**2 + 8*tc**2)) 86 | / (4*tc**2*(2*GammaL + GammaR) + GammaL*GammaR**2 87 | + 4*eps_vec**2*GammaL)**2) 88 | ) 89 | 90 | np.testing.assert_allclose(current, current_target, atol=1e-4) 91 | np.testing.assert_allclose(noise, noise_target, atol=1e-4) 92 | -------------------------------------------------------------------------------- /qutip/tests/test_fileio.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import pytest 35 | import numpy as np 36 | import uuid 37 | import qutip 38 | 39 | # qsave _always_ appends a suffix to the file name at the time of writing, but 40 | # in case this changes in the future, to ensure that we never leak a temporary 41 | # file into the user's folders, we simply apply these tests in a temporary 42 | # directory. Windows also does not allow temporary files to be opened multiple 43 | # times, so using a temporary directory is best. 44 | pytestmark = [pytest.mark.usefixtures("in_temporary_directory")] 45 | 46 | _dimension = 10 47 | 48 | def _random_file_name(): 49 | return "_" + str(uuid.uuid4()) 50 | 51 | 52 | class Test_file_data_store_file_data_read: 53 | # Tests parametrised seprately to give nicer descriptions in verbose mode. 54 | 55 | def case(self, filename, kwargs): 56 | data = 1 - 2*np.random.rand(_dimension, _dimension) 57 | if kwargs.get('numtype', 'complex') == 'complex': 58 | data = data * (0.5*0.5j) 59 | qutip.file_data_store(filename, data, **kwargs) 60 | out = qutip.file_data_read(filename) 61 | np.testing.assert_allclose(data, out, atol=1e-8) 62 | 63 | def test_defaults(self): 64 | return self.case(_random_file_name(), {}) 65 | 66 | @pytest.mark.parametrize("type_", ["real", "complex"]) 67 | @pytest.mark.parametrize("format_", ["decimal", "exp"]) 68 | def test_type_format(self, type_, format_): 69 | 70 | kwargs = {'numtype': type_, 'numformat': format_} 71 | return self.case(_random_file_name(), kwargs) 72 | 73 | @pytest.mark.parametrize("separator", [",", ";", "\t", " ", " \t "], 74 | ids=lambda x: "'" + x + "'") 75 | def test_separator_detection(self, separator): 76 | kwargs = {'numtype': 'complex', 'numformat': 'exp', 'sep': separator} 77 | return self.case(_random_file_name(), kwargs) 78 | 79 | 80 | def test_qsave_qload(): 81 | ops_in = [qutip.sigmax(), 82 | qutip.num(_dimension), 83 | qutip.coherent_dm(_dimension, 1j)] 84 | filename = _random_file_name() 85 | qutip.qsave(ops_in, filename) 86 | ops_out = qutip.qload(filename) 87 | assert ops_in == ops_out 88 | -------------------------------------------------------------------------------- /qutip/cite.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | """ 34 | Citation generator for QuTiP 35 | """ 36 | import sys 37 | import os 38 | 39 | __all__ = ['cite'] 40 | 41 | 42 | def cite(save=False, path=None): 43 | """ 44 | Citation information and bibtex generator for QuTiP 45 | 46 | Parameters 47 | ---------- 48 | save: bool 49 | The flag specifying whether to save the .bib file. 50 | 51 | path: str 52 | The complete directory path to generate the bibtex file. 53 | If not specified then the citation will be generated in cwd 54 | """ 55 | citation = ["@article{qutip2,", 56 | "doi = {10.1016/j.cpc.2012.11.019},", 57 | "url = {https://doi.org/10.1016/j.cpc.2012.11.019},", 58 | "year = {2013},", 59 | "month = {apr},", 60 | "publisher = {Elsevier {BV}},", 61 | "volume = {184},", 62 | "number = {4},", 63 | "pages = {1234--1240},", 64 | "author = {J.R. Johansson and P.D. Nation and F. Nori},", 65 | "title = {{QuTiP} 2: A {P}ython framework for the dynamics of open quantum systems},", 66 | "journal = {Computer Physics Communications}", 67 | "}", 68 | "@article{qutip1,", 69 | "doi = {10.1016/j.cpc.2012.02.021},", 70 | "url = {https://doi.org/10.1016/j.cpc.2012.02.021},", 71 | "year = {2012},", 72 | "month = {aug},", 73 | "publisher = {Elsevier {BV}},", 74 | "volume = {183},", 75 | "number = {8},", 76 | "pages = {1760--1772},", 77 | "author = {J.R. Johansson and P.D. Nation and F. Nori},", 78 | "title = {{QuTiP}: An open-source {P}ython framework for the dynamics of open quantum systems},", 79 | "journal = {Computer Physics Communications}", 80 | "}"] 81 | print("\n".join(citation)) 82 | 83 | if not path: 84 | path = os.getcwd() 85 | 86 | if save: 87 | filename = "qutip.bib" 88 | with open(os.path.join(path, filename), 'w') as f: 89 | f.write("\n".join(citation)) 90 | 91 | 92 | if __name__ == "__main__": 93 | cite() 94 | -------------------------------------------------------------------------------- /qutip/control/termcond.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2014 and later, Alexander J G Pitchford 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | # @author: Alexander Pitchford 36 | # @email1: agp1@aber.ac.uk 37 | # @email2: alex.pitchford@gmail.com 38 | # @organization: Aberystwyth University 39 | # @supervisor: Daniel Burgarth 40 | 41 | """ 42 | Classes containing termination conditions for the control pulse optimisation 43 | i.e. attributes that will be checked during the optimisation, that 44 | will determine if the algorithm has completed its task / exceeded limits 45 | """ 46 | 47 | 48 | class TerminationConditions(object): 49 | """ 50 | Base class for all termination conditions 51 | Used to determine when to stop the optimisation algorithm 52 | Note different subclasses should be used to match the type of 53 | optimisation being used 54 | 55 | Attributes 56 | ---------- 57 | fid_err_targ : float 58 | Target fidelity error 59 | 60 | fid_goal : float 61 | goal fidelity, e.g. 1 - self.fid_err_targ 62 | It its typical to set this for unitary systems 63 | 64 | max_wall_time : float 65 | # maximum time for optimisation (seconds) 66 | 67 | min_gradient_norm : float 68 | Minimum normalised gradient after which optimisation will terminate 69 | 70 | max_iterations : integer 71 | Maximum iterations of the optimisation algorithm 72 | 73 | max_fid_func_calls : integer 74 | Maximum number of calls to the fidelity function during 75 | the optimisation algorithm 76 | 77 | accuracy_factor : float 78 | Determines the accuracy of the result. 79 | Typical values for accuracy_factor are: 1e12 for low accuracy; 80 | 1e7 for moderate accuracy; 10.0 for extremely high accuracy 81 | scipy.optimize.fmin_l_bfgs_b factr argument. 82 | Only set for specific methods (fmin_l_bfgs_b) that uses this 83 | Otherwise the same thing is passed as method_option ftol 84 | (although the scale is different) 85 | Hence it is not defined here, but may be set by the user 86 | """ 87 | def __init__(self): 88 | self.reset() 89 | 90 | def reset(self): 91 | self.fid_err_targ = 1e-5 92 | self.fid_goal = None 93 | self.max_wall_time = 60*60.0 94 | self.min_gradient_norm = 1e-5 95 | self.max_iterations = 1e10 96 | self.max_fid_func_calls = 1e10 97 | -------------------------------------------------------------------------------- /qutip/cy/checks.pyx: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, The QuTiP Project. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | import numpy as np 35 | import scipy.sparse as sp 36 | from qutip.fastsparse import fast_csr_matrix 37 | cimport numpy as cnp 38 | cimport cython 39 | 40 | include "sparse_routines.pxi" 41 | 42 | 43 | def _test_coo2csr_struct(object A): 44 | cdef COO_Matrix mat = COO_from_scipy(A) 45 | cdef CSR_Matrix out 46 | COO_to_CSR(&out, &mat) 47 | return CSR_to_scipy(&out) 48 | 49 | 50 | def _test_sorting(object A): 51 | cdef complex[::1] data = A.data 52 | cdef int[::1] ind = A.indices 53 | cdef int[::1] ptr = A.indptr 54 | cdef int nrows = A.shape[0] 55 | cdef int ncols = A.shape[1] 56 | 57 | cdef CSR_Matrix out 58 | 59 | out.data = &data[0] 60 | out.indices = &ind[0] 61 | out.indptr = &ptr[0] 62 | out.nrows = nrows 63 | out.ncols = ncols 64 | out.is_set = 1 65 | out.numpy_lock = 0 66 | sort_indices(&out) 67 | 68 | 69 | def _test_coo2csr_inplace_struct(object A, int sorted = 0): 70 | cdef complex[::1] data = A.data 71 | cdef int[::1] rows = A.row 72 | cdef int[::1] cols = A.col 73 | cdef int nrows = A.shape[0] 74 | cdef int ncols = A.shape[1] 75 | cdef int nnz = data.shape[0] 76 | cdef size_t kk 77 | #We need to make copies here to test the inplace conversion 78 | #as we cannot use numpy data due to ownership issues. 79 | cdef complex * _data = PyDataMem_NEW(nnz * sizeof(complex)) 80 | cdef int * _rows = PyDataMem_NEW(nnz * sizeof(int)) 81 | cdef int * _cols = PyDataMem_NEW(nnz * sizeof(int)) 82 | for kk in range(nnz): 83 | _data[kk] = data[kk] 84 | _rows[kk] = rows[kk] 85 | _cols[kk] = cols[kk] 86 | 87 | cdef COO_Matrix mat 88 | mat.data = _data 89 | mat.rows = _rows 90 | mat.cols = _cols 91 | mat.nrows = nrows 92 | mat.ncols = ncols 93 | mat.nnz = nnz 94 | mat.max_length = mat.nnz 95 | mat.is_set = 1 96 | mat.numpy_lock = 0 97 | 98 | cdef CSR_Matrix out 99 | 100 | COO_to_CSR_inplace(&out, &mat) 101 | if sorted: 102 | sort_indices(&out) 103 | return CSR_to_scipy(&out) 104 | 105 | 106 | def _test_csr2coo_struct(object A): 107 | cdef CSR_Matrix mat = CSR_from_scipy(A) 108 | cdef COO_Matrix out 109 | CSR_to_COO(&out, &mat) 110 | return COO_to_scipy(&out) 111 | -------------------------------------------------------------------------------- /qutip/tests/test_random.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import scipy.sparse as sp 35 | import scipy.linalg as la 36 | import numpy as np 37 | from numpy.testing import assert_equal, assert_, run_module_suite 38 | 39 | from qutip.random_objects import (rand_ket, rand_dm, rand_herm, rand_unitary, 40 | rand_ket_haar, rand_dm_hs, 41 | rand_super, rand_unitary_haar, rand_dm_ginibre, 42 | rand_super_bcsz) 43 | from qutip.operators import qeye 44 | 45 | def test_rand_unitary_haar_unitarity(): 46 | """ 47 | Random Qobjs: Tests that unitaries are actually unitary. 48 | """ 49 | U = rand_unitary_haar(5) 50 | I = qeye(5) 51 | 52 | assert_(U * U.dag() == I) 53 | 54 | def test_rand_dm_ginibre_rank(): 55 | """ 56 | Random Qobjs: Ginibre-random density ops have correct rank. 57 | """ 58 | rho = rand_dm_ginibre(5, rank=3) 59 | 60 | rank = sum([abs(E) >= 1e-10 for E in rho.eigenenergies()]) 61 | assert_(rank == 3) 62 | 63 | def test_rand_super_bcsz_cptp(): 64 | """ 65 | Random Qobjs: Tests that BCSZ-random superoperators are CPTP. 66 | """ 67 | S = rand_super_bcsz(5) 68 | assert_(S.iscptp) 69 | 70 | def check_func_dims(func, args, kwargs, dims): 71 | # TODO: promote this out of test_random, as it's generically useful 72 | # in writing tests. 73 | resdims = func(*args, **kwargs).dims 74 | assert_(resdims == dims, "Checking {}; epected dimensions of {}, got {}.".format(func.__name__, dims, resdims)) 75 | 76 | def test_rand_vector_dims(): 77 | FUNCS = [rand_ket, rand_ket_haar] 78 | for func in FUNCS: 79 | check_func_dims( func, (7, ), {}, [[7], [1]]) 80 | check_func_dims( func, (6, ), {'dims': [[2,3], [1,1]]}, [[2,3], [1,1]]) 81 | 82 | def test_rand_oper_dims(): 83 | FUNCS = [rand_unitary, rand_herm, rand_dm, rand_unitary_haar, rand_dm_ginibre, rand_dm_hs] 84 | for func in FUNCS: 85 | check_func_dims( func, (7, ), {}, [[7], [7]]) 86 | check_func_dims( func, (6, ), {'dims': [[2, 3], [2, 3]]}, [[2, 3], [2, 3]]) 87 | 88 | def test_rand_super_dims(): 89 | FUNCS = [rand_super, rand_super_bcsz] 90 | for func in FUNCS: 91 | check_func_dims(func, (7, ), {}, [[[7], [7]]] * 2) 92 | check_func_dims(func, (6, ), {'dims': [[[2, 3], [2, 3]], [[2, 3], [2, 3]]]}, [[[2, 3], [2, 3]], [[2, 3], [2, 3]]]) 93 | 94 | if __name__ == "__main__": 95 | run_module_suite() 96 | -------------------------------------------------------------------------------- /qutip/qip/qip_depracation.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | import warnings 34 | import inspect 35 | from functools import wraps as _func_wrap 36 | 37 | from . import circuit 38 | from . import qubits 39 | from .operations import gates 40 | 41 | 42 | __all__ = circuit.__all__ + qubits.__all__ + gates.__all__ 43 | 44 | # modules that are wrapped with deprecation warning 45 | module_list = [gates, circuit, qubits] 46 | 47 | 48 | def _qip_importation_warning(): 49 | warnings.warn( 50 | "Importing functions/classes of the qip submodule directly from " 51 | "the namespace qutip is deprecated. " 52 | "Please import them from the submodule instead, e.g.\n" 53 | "from qutip.qip.operations import cnot\n" 54 | "from qutip.qip.circuit import QubitCircuit\n", 55 | DeprecationWarning, stacklevel=3) 56 | 57 | 58 | def _qip_func_wrapper(func): 59 | """Function wrapper for adding a deprecation warning.""" 60 | @_func_wrap(func) 61 | def deprecated_func(*args, **kwargs): 62 | _qip_importation_warning() 63 | return func(*args, **kwargs) 64 | return deprecated_func 65 | 66 | 67 | for module in module_list: 68 | # Wrap all qip functions with a deprecation warning 69 | _func_pairs = inspect.getmembers(module, inspect.isfunction) 70 | for _name, _func in _func_pairs: 71 | locals()[_name] = _qip_func_wrapper(_func) 72 | del _name, _func, _func_pairs, _qip_func_wrapper 73 | 74 | 75 | def _qip_class_wrapper(original_cls): 76 | """Class wrapper for adding a deprecation warning.""" 77 | class Deprecated_cls(original_cls): 78 | def __init__(self, *args, **kwargs): 79 | _qip_importation_warning() 80 | super(Deprecated_cls, self).__init__(*args, **kwargs) 81 | # copy information form the original class, similar to functools.wraps 82 | for attr in ('__module__', '__name__', '__qualname__', '__doc__'): 83 | try: 84 | value = getattr(original_cls, attr) 85 | except AttributeError: 86 | pass 87 | else: 88 | setattr(Deprecated_cls, attr, value) 89 | return Deprecated_cls 90 | 91 | 92 | # Wrap all qip classes with a deprecation warning 93 | for module in module_list: 94 | _cls_pairs = inspect.getmembers(module, inspect.isclass) 95 | for _name, _cls in _cls_pairs: 96 | locals()[_name] = _qip_class_wrapper(_cls) 97 | del _name, _cls, _cls_pairs, _qip_class_wrapper 98 | 99 | del module_list 100 | -------------------------------------------------------------------------------- /qutip/tests/test_heom_solver.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2014 and later, Alexander J G Pitchford, Neill Lambert 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | """ 36 | Test the Hierarchical Model Solver from qutip.nonmarkov.heom. 37 | """ 38 | 39 | import numpy as np 40 | from scipy.integrate import quad 41 | import pytest 42 | import qutip 43 | from qutip.nonmarkov.heom import HSolverDL 44 | 45 | 46 | @pytest.mark.filterwarnings("ignore::scipy.integrate.IntegrationWarning") 47 | @pytest.mark.parametrize(['renorm', 'bnd_cut_approx', 'stats', 'tol'], [ 48 | pytest.param(True, True, True, 1e-4, id="renorm-bnd_cut_approx-stats"), 49 | pytest.param(True, False, False, 1e-3, id="renorm"), 50 | pytest.param(False, True, False, 1e-4, id="bnd_cut_approx"), 51 | ]) 52 | def test_pure_dephasing_model(renorm, bnd_cut_approx, stats, tol): 53 | """ 54 | HSolverDL: Compare with pure-dephasing analytical assert that the 55 | analytical result and HEOM produce the same time dephasing evoltion. 56 | """ 57 | cut_frequency = 0.05 58 | coupling_strength = 0.025 59 | lam_c = coupling_strength / np.pi 60 | temperature = 1 / 0.95 61 | times = np.linspace(0, 10, 21) 62 | 63 | def _integrand(omega, t): 64 | J = 2*lam_c * omega * cut_frequency / (omega**2 + cut_frequency**2) 65 | return (-4 * J * (1 - np.cos(omega*t)) 66 | / (np.tanh(0.5*omega / temperature) * omega**2)) 67 | 68 | # Calculate the analytical results by numerical integration 69 | expected = [0.5*np.exp(quad(_integrand, 0, np.inf, args=(t,))[0]) 70 | for t in times] 71 | 72 | H_sys = qutip.Qobj(np.zeros((2, 2))) 73 | Q = qutip.sigmaz() 74 | initial_state = 0.5*qutip.Qobj(np.ones((2, 2))) 75 | projector = qutip.basis(2, 0) * qutip.basis(2, 1).dag() 76 | options = qutip.Options(nsteps=15_000, store_states=True) 77 | hsolver = HSolverDL(H_sys, Q, coupling_strength, temperature, 78 | 20, 2, cut_frequency, 79 | renorm=renorm, bnd_cut_approx=bnd_cut_approx, 80 | options=options, stats=stats) 81 | test = qutip.expect(hsolver.run(initial_state, times).states, projector) 82 | if stats: 83 | assert hsolver.stats is not None 84 | else: 85 | assert hsolver.stats is None 86 | np.testing.assert_allclose(test, expected, atol=tol) 87 | 88 | 89 | def test_set_unset_stats(): 90 | # Arbitrary system, just checking that stats can be unset by `configure` 91 | args = [qutip.qeye(2), qutip.sigmaz(), 92 | 0.1, 0.1, 10, 1, 0.1] 93 | hsolver = HSolverDL(*args, stats=True) 94 | hsolver.run(qutip.basis(2, 0).proj(), [0, 1]) 95 | assert hsolver.stats is not None 96 | hsolver.configure(*args, stats=False) 97 | assert hsolver.stats is None 98 | -------------------------------------------------------------------------------- /qutip/cy/cqobjevo.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | from qutip.cy.sparse_structs cimport CSR_Matrix, COO_Matrix 36 | from qutip.cy.cqobjevo_factor cimport CoeffFunc 37 | 38 | cdef class CQobjEvo: 39 | cdef int shape0, shape1 40 | cdef object dims 41 | cdef int super 42 | cdef int num_ops 43 | cdef int dyn_args 44 | 45 | #cdef void (*factor_ptr)(double, complex*) 46 | cdef object factor_func 47 | cdef CoeffFunc factor_cobj 48 | cdef int factor_use_cobj 49 | # prepared buffer 50 | cdef complex[::1] coeff 51 | cdef complex* coeff_ptr 52 | 53 | cdef int _factor(self, double t) except -1 54 | cdef int _factor_dyn(self, double t, complex* state, int[::1] state) except -1 55 | cdef int _mul_vec(self, double t, complex* vec, complex* out) except -1 56 | cdef int _mul_matf(self, double t, complex* mat, complex* out, 57 | int nrow, int ncols) except -1 58 | cdef int _mul_matc(self, double t, complex* mat, complex* out, 59 | int nrow, int ncols) except -1 60 | 61 | cpdef complex expect(self, double t, complex[::1] vec) 62 | cdef complex _expect(self, double t, complex* vec) except * 63 | cdef complex _expect_super(self, double t, complex* rho) except * 64 | cdef complex _overlapse(self, double t, complex* oper) except * 65 | 66 | 67 | cdef class CQobjCte(CQobjEvo): 68 | cdef int total_elem 69 | # pointer to data 70 | cdef CSR_Matrix cte 71 | 72 | 73 | cdef class CQobjCteDense(CQobjEvo): 74 | # pointer to data 75 | cdef complex[:, ::1] cte 76 | 77 | 78 | cdef class CQobjEvoTd(CQobjEvo): 79 | cdef long total_elem 80 | # pointer to data 81 | cdef CSR_Matrix cte 82 | cdef CSR_Matrix ** ops 83 | cdef long[::1] sum_elem 84 | cdef void _call_core(self, CSR_Matrix * out, complex* coeff) 85 | 86 | 87 | cdef class CQobjEvoTdDense(CQobjEvo): 88 | # data as array 89 | cdef complex[:, ::1] cte 90 | cdef complex[:, :, ::1] ops 91 | 92 | # prepared buffer 93 | cdef complex[:, ::1] data_t 94 | cdef complex* data_ptr 95 | 96 | cdef int _factor(self, double t) except -1 97 | cdef void _call_core(self, complex[:,::1] out, complex* coeff) 98 | 99 | 100 | cdef class CQobjEvoTdMatched(CQobjEvo): 101 | cdef int nnz 102 | # data as array 103 | cdef int[::1] indptr 104 | cdef int[::1] indices 105 | cdef complex[::1] cte 106 | cdef complex[:, ::1] ops 107 | 108 | # prepared buffer 109 | cdef complex[::1] data_t 110 | cdef complex* data_ptr 111 | 112 | cdef int _factor(self, double t) except -1 113 | cdef void _call_core(self, complex[::1] out, complex* coeff) 114 | -------------------------------------------------------------------------------- /qutip/control/errors.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2014 and later, Alexander J G Pitchford 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | # @author: Alexander Pitchford 36 | # @email1: agp1@aber.ac.uk 37 | # @email2: alex.pitchford@gmail.com 38 | # @organization: Aberystwyth University 39 | # @supervisor: Daniel Burgarth 40 | 41 | """ 42 | Exception classes for the Quantum Control library 43 | """ 44 | 45 | 46 | class Error(Exception): 47 | """Base class for all qutip control exceptions""" 48 | 49 | def __str__(self): 50 | return repr(self.message) 51 | 52 | 53 | class UsageError(Error): 54 | """ 55 | A function has been used incorrectly. Most likely when a base class 56 | was used when a sub class should have been. 57 | funcname: function name where error occurred 58 | msg: Explanation 59 | 60 | """ 61 | def __init__(self, msg): 62 | self.message = msg 63 | 64 | 65 | class FunctionalError(Error): 66 | """ 67 | A function behaved in an unexpected way 68 | Attributes: 69 | funcname: function name where error occurred 70 | msg: Explanation 71 | 72 | """ 73 | def __init__(self, msg): 74 | self.message = msg 75 | 76 | 77 | class OptimizationTerminate(Error): 78 | """ 79 | Superclass for all early terminations from the optimisation algorithm 80 | 81 | """ 82 | pass 83 | 84 | 85 | class GoalAchievedTerminate(OptimizationTerminate): 86 | """ 87 | Exception raised to terminate execution when the goal has been reached 88 | during the optimisation algorithm 89 | 90 | """ 91 | def __init__(self, fid_err): 92 | self.reason = "Goal achieved" 93 | self.fid_err = fid_err 94 | 95 | 96 | class MaxWallTimeTerminate(OptimizationTerminate): 97 | """ 98 | Exception raised to terminate execution when the optimisation time has 99 | exceeded the maximum set in the config 100 | 101 | """ 102 | def __init__(self): 103 | self.reason = "Max wall time exceeded" 104 | 105 | class MaxFidFuncCallTerminate(OptimizationTerminate): 106 | """ 107 | Exception raised to terminate execution when the number of calls to the 108 | fidelity error function has exceeded the maximum 109 | 110 | """ 111 | def __init__(self): 112 | self.reason = "Number of fidelity error calls has exceeded the maximum" 113 | 114 | class GradMinReachedTerminate(OptimizationTerminate): 115 | """ 116 | Exception raised to terminate execution when the minimum gradient normal 117 | has been reached during the optimisation algorithm 118 | 119 | """ 120 | def __init__(self, gradient): 121 | self.reason = "Gradient normal minimum reached" 122 | self.gradient = gradient 123 | -------------------------------------------------------------------------------- /qutip/three_level_atom.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | ''' 34 | This module provides functions that are useful for simulating the 35 | three level atom with QuTiP. A three level atom (qutrit) has three states, 36 | which are linked by dipole transitions so that 1 <-> 2 <-> 3. 37 | Depending on there relative energies they are in the ladder, lambda or 38 | vee configuration. The structure of the relevant operators is the same 39 | for any of the three configurations:: 40 | 41 | Ladder: Lambda: Vee: 42 | |two> |three> 43 | -------|three> ------- ------- 44 | | / \ |one> / 45 | | / \ ------- / 46 | | / \ \ / 47 | -------|two> / \ \ / 48 | | / \ \ / 49 | | / \ \ / 50 | | / -------- \ / 51 | -------|one> ------- |three> ------- 52 | |one> |two> 53 | 54 | References 55 | ---------- 56 | The naming of qutip operators follows the convention in [1]_ . 57 | 58 | .. [1] Shore, B. W., "The Theory of Coherent Atomic Excitation", 59 | Wiley, 1990. 60 | 61 | Notes 62 | ----- 63 | Contributed by Markus Baden, Oct. 07, 2011 64 | 65 | ''' 66 | 67 | __all__ = ['three_level_basis', 'three_level_ops'] 68 | 69 | from qutip.states import qutrit_basis 70 | from numpy import array 71 | 72 | 73 | def three_level_basis(): 74 | ''' Basis states for a three level atom. 75 | 76 | Returns 77 | ------- 78 | states : array 79 | `array` of three level atom basis vectors. 80 | 81 | ''' 82 | # A three level atom has the same representation as a qutrit, i.e. 83 | # three states 84 | return qutrit_basis() 85 | 86 | 87 | def three_level_ops(): 88 | ''' Operators for a three level system (qutrit) 89 | 90 | Returns 91 | -------- 92 | ops : array 93 | `array` of three level operators. 94 | 95 | ''' 96 | one, two, three = qutrit_basis() 97 | # Note that the three level operators are different 98 | # from the qutrit operators. A three level atom only 99 | # has transitions 1 <-> 2 <-> 3, so we define the 100 | # operators seperately from the qutrit code 101 | sig11 = one * one.dag() 102 | sig22 = two * two.dag() 103 | sig33 = three * three.dag() 104 | sig12 = one * two.dag() 105 | sig32 = three * two.dag() 106 | return array([sig11, sig22, sig33, sig12, sig32], dtype=object) 107 | -------------------------------------------------------------------------------- /qutip/about.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | """ 34 | Command line output of information on QuTiP and dependencies. 35 | """ 36 | __all__ = ['about'] 37 | 38 | import sys 39 | import os 40 | import platform 41 | import numpy 42 | import scipy 43 | import inspect 44 | from qutip.utilities import _blas_info 45 | import qutip.settings 46 | from qutip.hardware_info import hardware_info 47 | 48 | 49 | def about(): 50 | """ 51 | About box for QuTiP. Gives version numbers for 52 | QuTiP, NumPy, SciPy, Cython, and MatPlotLib. 53 | """ 54 | print("") 55 | print("QuTiP: Quantum Toolbox in Python") 56 | print("================================") 57 | print("Copyright (c) QuTiP team 2011 and later.") 58 | print("Original developers: R. J. Johansson & P. D. Nation.") 59 | print("Previous lead developers: Chris Granade & A. Grimsmo.") 60 | print("Current admin team: Alexander Pitchford, Paul D. Nation, " 61 | "Nathan Shammah, Shahnawaz Ahmed, " 62 | "Neill Lambert, Eric Giguère, and Boxi Li") 63 | print("Project Manager: Franco Nori.") 64 | print("Currently developed through wide collaboration. " 65 | "See https://github.com/qutip for details.") 66 | print("") 67 | print("QuTiP Version: %s" % qutip.__version__) 68 | print("Numpy Version: %s" % numpy.__version__) 69 | print("Scipy Version: %s" % scipy.__version__) 70 | try: 71 | import Cython 72 | cython_ver = Cython.__version__ 73 | except: 74 | cython_ver = 'None' 75 | print("Cython Version: %s" % cython_ver) 76 | try: 77 | import matplotlib 78 | matplotlib_ver = matplotlib.__version__ 79 | except: 80 | matplotlib_ver = 'None' 81 | print("Matplotlib Version: %s" % matplotlib_ver) 82 | print("Python Version: %d.%d.%d" % sys.version_info[0:3]) 83 | print("Number of CPUs: %s" % hardware_info()['cpus']) 84 | print("BLAS Info: %s" % _blas_info()) 85 | print("OPENMP Installed: %s" % str(qutip.settings.has_openmp)) 86 | print("INTEL MKL Ext: %s" % str(qutip.settings.has_mkl)) 87 | print("Platform Info: %s (%s)" % (platform.system(), 88 | platform.machine())) 89 | qutip_install_path = os.path.dirname(inspect.getsourcefile(qutip)) 90 | print("Installation path: %s" % qutip_install_path) 91 | 92 | # citation 93 | longbar = "==============================================================" 94 | longbar += "================" 95 | cite_msg = "For your convenience a bibtex reference can be easily generated" 96 | cite_msg += " using `qutip.cite()`" 97 | print(longbar) 98 | print("Please cite QuTiP in your publication.") 99 | print(longbar) 100 | print(cite_msg) 101 | 102 | 103 | if __name__ == "__main__": 104 | about() 105 | -------------------------------------------------------------------------------- /qutip/qip/compiler/gatecompiler.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | import numpy as np 34 | 35 | 36 | __all__ = ['GateCompiler'] 37 | 38 | 39 | class GateCompiler(object): 40 | """ 41 | Base class. It decomposes a :class:`qutip.QubitCircuit` into 42 | the pulse sequence for the processor. 43 | 44 | Parameters 45 | ---------- 46 | N: int 47 | The number of the component systems. 48 | 49 | params: dict 50 | A Python dictionary contains the name and the value of the parameters, 51 | such as laser frequency, detuning etc. 52 | 53 | num_ops: int 54 | Number of control Hamiltonians in the processor. 55 | 56 | Attributes 57 | ---------- 58 | N: int 59 | The number of the component systems. 60 | 61 | params: dict 62 | A Python dictionary contains the name and the value of the parameters, 63 | such as laser frequency, detuning etc. 64 | 65 | num_ops: int 66 | Number of control Hamiltonians in the processor. 67 | 68 | gate_decomps: dict 69 | The Python dictionary in the form of {gate_name: decompose_function}. 70 | It saves the decomposition scheme for each gate. 71 | """ 72 | def __init__(self, N, params, num_ops): 73 | self.gate_decomps = {} 74 | self.N = N 75 | self.params = params 76 | self.num_ops = num_ops 77 | 78 | def decompose(self, gates): 79 | """ 80 | Decompose the the elementary gates 81 | into control pulse sequence. 82 | 83 | Parameters 84 | ---------- 85 | gates: list 86 | A list of elementary gates that can be implemented in this 87 | model. The gate names have to be in `gate_decomps`. 88 | 89 | Returns 90 | ------- 91 | tlist: array_like 92 | A NumPy array specifies the time of each coefficient 93 | 94 | coeffs: array_like 95 | A 2d NumPy array of the shape ``(len(ctrls), len(tlist))``. Each 96 | row corresponds to the control pulse sequence for 97 | one Hamiltonian. 98 | 99 | global_phase: bool 100 | Recorded change of global phase. 101 | """ 102 | # TODO further improvement can be made here, 103 | # e.g. merge single qubit rotation gate, combine XX gates etc. 104 | self.dt_list = [] 105 | self.coeff_list = [] 106 | for gate in gates: 107 | if gate.name not in self.gate_decomps: 108 | raise ValueError("Unsupported gate %s" % gate.name) 109 | self.gate_decomps[gate.name](gate) 110 | coeffs = np.vstack(self.coeff_list).T 111 | 112 | tlist = np.empty(len(self.dt_list)) 113 | t = 0 114 | for i in range(len(self.dt_list)): 115 | t += self.dt_list[i] 116 | tlist[i] = t 117 | return np.hstack([[0], tlist]), coeffs 118 | -------------------------------------------------------------------------------- /qutip/cy/spmatfuncs.pxd: -------------------------------------------------------------------------------- 1 | #cython: language_level=3 2 | # This file is part of QuTiP: Quantum Toolbox in Python. 3 | # 4 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 5 | # All rights reserved. 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are 9 | # met: 10 | # 11 | # 1. Redistributions of source code must retain the above copyright notice, 12 | # this list of conditions and the following disclaimer. 13 | # 14 | # 2. Redistributions in binary form must reproduce the above copyright 15 | # notice, this list of conditions and the following disclaimer in the 16 | # documentation and/or other materials provided with the distribution. 17 | # 18 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 19 | # of its contributors may be used to endorse or promote products derived 20 | # from this software without specific prior written permission. 21 | # 22 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 25 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | ############################################################################### 34 | 35 | cimport numpy as cnp 36 | cimport cython 37 | from libcpp cimport bool 38 | 39 | include "parameters.pxi" 40 | 41 | cpdef cnp.ndarray[CTYPE_t, ndim=1, mode="c"] spmv_csr(complex[::1] data, 42 | int[::1] ind, int[::1] ptr, complex[::1] vec) 43 | 44 | 45 | cdef void spmvpy(complex * data, 46 | int * ind, 47 | int * ptr, 48 | complex * vec, 49 | complex a, 50 | complex * out, 51 | unsigned int nrows) 52 | 53 | 54 | cpdef cy_expect_rho_vec_csr(complex[::1] data, 55 | int[::1] idx, 56 | int[::1] ptr, 57 | complex[::1] rho_vec, 58 | int herm) 59 | 60 | 61 | cpdef cy_expect_psi(object A, 62 | complex[::1] vec, 63 | bool isherm) 64 | 65 | 66 | cpdef cy_expect_psi_csr(complex[::1] data, 67 | int[::1] ind, 68 | int[::1] ptr, 69 | complex[::1] vec, 70 | bool isherm) 71 | 72 | 73 | cdef void _spmm_c_py(complex * data, 74 | int * ind, 75 | int * ptr, 76 | complex * mat, 77 | complex a, 78 | complex * out, 79 | unsigned int sp_rows, 80 | unsigned int nrows, 81 | unsigned int ncols) 82 | 83 | cpdef void spmmpy_c(complex[::1] data, 84 | int[::1] ind, 85 | int[::1] ptr, 86 | complex[:,::1] M, 87 | complex a, 88 | complex[:,::1] out) 89 | 90 | cpdef cnp.ndarray[complex, ndim=1, mode="c"] spmmc(object sparse, 91 | complex[:,::1] mat) 92 | 93 | cdef void _spmm_f_py(complex * data, 94 | int * ind, 95 | int * ptr, 96 | complex * mat, 97 | complex a, 98 | complex * out, 99 | unsigned int sp_rows, 100 | unsigned int nrows, 101 | unsigned int ncols) 102 | 103 | cpdef void spmmpy_f(complex[::1] data, 104 | int[::1] ind, 105 | int[::1] ptr, 106 | complex[::1,:] mat, 107 | complex a, 108 | complex[::1,:] out) 109 | 110 | cpdef cnp.ndarray[complex, ndim=1, mode="c"] spmmf(object sparse, 111 | complex[::1,:] mat) 112 | 113 | cpdef cnp.ndarray[complex, ndim=1, mode="c"] spmm(object sparse, 114 | cnp.ndarray[complex, ndim=2] mat) 115 | -------------------------------------------------------------------------------- /qutip/tests/test_cavityqed.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import warnings 35 | import numpy as np 36 | import pytest 37 | import qutip 38 | from qutip.qip.circuit import Gate 39 | from qutip.qip.operations.gates import gate_sequence_product 40 | from qutip.qip.device.cavityqed import DispersiveCavityQED 41 | 42 | _tol = 1e-2 43 | 44 | _iswap = Gate("ISWAP", targets=[0, 1]) 45 | _sqrt_iswap = Gate("SQRTISWAP", targets=[0, 1]) 46 | _rz = Gate("RZ", targets=[1], arg_value=np.pi/2, arg_label=r"\pi/2") 47 | _rx = Gate("RX", targets=[0], arg_value=np.pi/2, arg_label=r"\pi/2") 48 | 49 | 50 | @pytest.mark.parametrize("gates", [ 51 | pytest.param([_iswap], id="ISWAP"), 52 | pytest.param([_sqrt_iswap], id="SQRTISWAP", marks=pytest.mark.skip), 53 | pytest.param([_iswap, _rz, _rx], id="ISWAP RZ RX"), 54 | ]) 55 | def test_device_against_gate_sequence(gates): 56 | n_qubits = 3 57 | circuit = qutip.qip.circuit.QubitCircuit(n_qubits) 58 | for gate in gates: 59 | circuit.add_gate(gate) 60 | U_ideal = gate_sequence_product(circuit.propagators()) 61 | 62 | device = DispersiveCavityQED(n_qubits, correct_global_phase=True) 63 | U_physical = gate_sequence_product(device.run(circuit)) 64 | assert (U_ideal - U_physical).norm() < _tol 65 | 66 | 67 | def test_analytical_evolution(): 68 | n_qubits = 3 69 | circuit = qutip.qip.circuit.QubitCircuit(n_qubits) 70 | for gate in [_iswap, _rz, _rx]: 71 | circuit.add_gate(gate) 72 | state = qutip.rand_ket(2**n_qubits) 73 | state.dims = [[2]*n_qubits, [1]*n_qubits] 74 | ideal = gate_sequence_product([state] + circuit.propagators()) 75 | device = DispersiveCavityQED(n_qubits, correct_global_phase=True) 76 | operators = device.run_state(init_state=state, qc=circuit, analytical=True) 77 | result = gate_sequence_product(operators) 78 | assert abs(qutip.metrics.fidelity(result, ideal) - 1) < _tol 79 | 80 | 81 | def test_numerical_evolution(): 82 | n_qubits = 3 83 | circuit = qutip.qip.circuit.QubitCircuit(n_qubits) 84 | circuit.add_gate("RX", targets=[0], arg_value=np.pi/2) 85 | circuit.add_gate("CNOT", targets=[0], controls=[1]) 86 | circuit.add_gate("ISWAP", targets=[2, 1]) 87 | circuit.add_gate("CNOT", targets=[0], controls=[2]) 88 | with warnings.catch_warnings(record=True): 89 | device = DispersiveCavityQED(n_qubits, g=0.1) 90 | device.load_circuit(circuit) 91 | 92 | state = qutip.rand_ket(2**n_qubits) 93 | state.dims = [[2]*n_qubits, [1]*n_qubits] 94 | target = gate_sequence_product([state] + circuit.propagators()) 95 | extra = qutip.basis(10, 0) 96 | options = qutip.Options(store_final_state=True, nsteps=50_000) 97 | result = device.run_state(init_state=qutip.tensor(extra, state), 98 | analytical=False, 99 | options=options) 100 | assert _tol > abs(1 - qutip.metrics.fidelity(result.final_state, 101 | qutip.tensor(extra, target))) 102 | -------------------------------------------------------------------------------- /qutip/tests/test_partial_transpose.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | """ 34 | Unit tests for QuTiP partial transpose functions. 35 | """ 36 | 37 | import numpy as np 38 | from numpy.testing import assert_, run_module_suite 39 | 40 | from qutip import Qobj, partial_transpose, tensor, rand_dm 41 | from qutip.partial_transpose import _partial_transpose_reference 42 | 43 | 44 | def test_partial_transpose_bipartite(): 45 | """partial transpose of bipartite systems""" 46 | 47 | rho = Qobj(np.arange(16).reshape(4, 4), dims=[[2, 2], [2, 2]]) 48 | 49 | # no transpose 50 | rho_pt = partial_transpose(rho, [0, 0]) 51 | assert_(np.abs(np.max(rho_pt.full() - rho.full())) < 1e-12) 52 | 53 | # partial transpose subsystem 1 54 | rho_pt = partial_transpose(rho, [1, 0]) 55 | rho_pt_expected = np.array([[0, 1, 8, 9], 56 | [4, 5, 12, 13], 57 | [2, 3, 10, 11], 58 | [6, 7, 14, 15]]) 59 | assert_(np.abs(np.max(rho_pt.full() - rho_pt_expected)) < 1e-12) 60 | 61 | # partial transpose subsystem 2 62 | rho_pt = partial_transpose(rho, [0, 1]) 63 | rho_pt_expected = np.array([[0, 4, 2, 6], 64 | [1, 5, 3, 7], 65 | [8, 12, 10, 14], 66 | [9, 13, 11, 15]]) 67 | assert_(np.abs(np.max(rho_pt.full() - rho_pt_expected)) < 1e-12) 68 | 69 | # full transpose 70 | rho_pt = partial_transpose(rho, [1, 1]) 71 | assert_(np.abs(np.max(rho_pt.full() - rho.trans().full())) < 1e-12) 72 | 73 | 74 | def test_partial_transpose_comparison(): 75 | """partial transpose: comparing sparse and dense implementations""" 76 | 77 | N = 10 78 | rho = tensor(rand_dm(N, density=0.5), rand_dm(N, density=0.5)) 79 | 80 | # partial transpose of system 1 81 | rho_pt1 = partial_transpose(rho, [1, 0], method="dense") 82 | rho_pt2 = partial_transpose(rho, [1, 0], method="sparse") 83 | np.abs(np.max(rho_pt1.full() - rho_pt1.full())) < 1e-12 84 | 85 | # partial transpose of system 2 86 | rho_pt1 = partial_transpose(rho, [0, 1], method="dense") 87 | rho_pt2 = partial_transpose(rho, [0, 1], method="sparse") 88 | np.abs(np.max(rho_pt1.full() - rho_pt2.full())) < 1e-12 89 | 90 | 91 | def test_partial_transpose_randomized(): 92 | """partial transpose: randomized tests on tripartite system""" 93 | 94 | rho = tensor(rand_dm(2, density=1), 95 | rand_dm(2, density=1), 96 | rand_dm(2, density=1)) 97 | 98 | mask = np.random.randint(2, size=3) 99 | 100 | rho_pt_ref = _partial_transpose_reference(rho, mask) 101 | 102 | rho_pt1 = partial_transpose(rho, mask, method="dense") 103 | np.abs(np.max(rho_pt1.full() - rho_pt_ref.full())) < 1e-12 104 | 105 | rho_pt2 = partial_transpose(rho, mask, method="sparse") 106 | np.abs(np.max(rho_pt2.full() - rho_pt_ref.full())) < 1e-12 107 | 108 | 109 | if __name__ == "__main__": 110 | run_module_suite() 111 | -------------------------------------------------------------------------------- /qutip/tests/test_propagator.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import numpy as np 35 | from numpy.testing import assert_, assert_equal, run_module_suite 36 | from qutip import * 37 | 38 | 39 | def testPropHO(): 40 | "Propagator: HO ('single mode')" 41 | a = destroy(5) 42 | H = a.dag()*a 43 | U = propagator(H,1, unitary_mode='single') 44 | U2 = (-1j*H).expm() 45 | assert_(np.abs((U-U2).full()).max() < 1e-4) 46 | 47 | def testPropHOB(): 48 | "Propagator: HO ('batch mode')" 49 | a = destroy(5) 50 | H = a.dag()*a 51 | U = propagator(H,1) 52 | U2 = (-1j*H).expm() 53 | assert_(np.abs((U-U2).full()).max() < 1e-4) 54 | 55 | def testPropHOPar(): 56 | "Propagator: HO parallel" 57 | a = destroy(5) 58 | H = a.dag()*a 59 | U = propagator(H,1, parallel=True) 60 | U2 = (-1j*H).expm() 61 | assert_(np.abs((U-U2).full()).max() < 1e-4) 62 | 63 | 64 | def testPropHOStrTd(): 65 | "Propagator: str td format" 66 | a = destroy(5) 67 | H = a.dag()*a 68 | H = [H,[H,'cos(t)']] 69 | U = propagator(H,1, unitary_mode='single') 70 | U2 = propagator(H,1, parallel=True) 71 | U3 = propagator(H,1) 72 | assert_(np.abs((U-U2).full()).max() < 1e-4) 73 | assert_(np.abs((U-U3).full()).max() < 1e-4) 74 | 75 | 76 | def func(t,*args): 77 | return np.cos(t) 78 | 79 | def testPropHOFuncTd(): 80 | "Propagator: func td format" 81 | a = destroy(5) 82 | H = a.dag()*a 83 | H = [H,[H,func]] 84 | U = propagator(H,1, unitary_mode='single') 85 | U2 = propagator(H,1, parallel=True) 86 | U3 = propagator(H,1) 87 | assert_(np.abs((U-U2).full()).max() < 1e-4) 88 | assert_(np.abs((U-U3).full()).max() < 1e-4) 89 | 90 | 91 | def testPropHOSteady(): 92 | "Propagator: steady state" 93 | a = destroy(5) 94 | H = a.dag()*a 95 | c_op_list = [] 96 | kappa = 0.1 97 | n_th = 2 98 | rate = kappa * (1 + n_th) 99 | c_op_list.append(np.sqrt(rate) * a) 100 | rate = kappa * n_th 101 | c_op_list.append(np.sqrt(rate) * a.dag()) 102 | U = propagator(H,2*np.pi,c_op_list) 103 | rho_prop = propagator_steadystate(U) 104 | rho_ss = steadystate(H,c_op_list) 105 | assert_(np.abs((rho_prop-rho_ss).full()).max() < 1e-4) 106 | 107 | 108 | def testPropHOSteadyPar(): 109 | "Propagator: steady state parallel" 110 | a = destroy(5) 111 | H = a.dag()*a 112 | c_op_list = [] 113 | kappa = 0.1 114 | n_th = 2 115 | rate = kappa * (1 + n_th) 116 | c_op_list.append(np.sqrt(rate) * a) 117 | rate = kappa * n_th 118 | c_op_list.append(np.sqrt(rate) * a.dag()) 119 | U = propagator(H,2*np.pi,c_op_list, parallel=True) 120 | rho_prop = propagator_steadystate(U) 121 | rho_ss = steadystate(H,c_op_list) 122 | assert_(np.abs((rho_prop-rho_ss).full()).max() < 1e-4) 123 | 124 | def testPropHDims(): 125 | "Propagator: preserve H dims (unitary_mode='single', parallel=False)" 126 | H = tensor([qeye(2),qeye(2)]) 127 | U = propagator(H,1, unitary_mode='single') 128 | assert_equal(U.dims,H.dims) 129 | 130 | if __name__ == "__main__": 131 | run_module_suite() 132 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | QuTiP: Quantum Toolbox in Python 2 | ================================ 3 | 4 | [A. Pitchford](https://github.com/ajgpitch), 5 | [C. Granade](https://github.com/cgranade), 6 | [A. Grimsmo](https://github.com/arnelg), 7 | [N. Shammah](https://github.com/nathanshammah), 8 | [S. Ahmed](https://github.com/quantshah), 9 | [N. Lambert](https://github.com/nwlambert), 10 | [E. Giguère](https://github.com/ericgig), 11 | [B. Li](https://github.com/boxili), 12 | [P. D. Nation](https://github.com/nonhermitian), 13 | and [J. R. Johansson](https://github.com/jrjohansson) 14 | 15 | 16 | QuTiP is open-source software for simulating the dynamics of closed and open 17 | quantum systems. The QuTiP library uses the excellent Numpy, Scipy, and Cython packages as numerical backend, and graphical output is provided by Matplotlib. QuTiP aims to provide user-friendly and efficient numerical simulations of a wide 18 | variety of quantum mechanical problems, including those with Hamiltonians 19 | and/or collapse operators with arbitrary time-dependence, commonly found in a 20 | wide range of physics applications. QuTiP is freely available for use and/or 21 | modification, and it can be used on all Unix-based platforms and on Windows. 22 | Being free of any licensing fees, QuTiP is ideal for exploring quantum 23 | mechanics in research as well as in the classroom. 24 | 25 | Build status and test coverage 26 | ------------------------------ 27 | 28 | [![build-status](https://secure.travis-ci.org/qutip/qutip.svg?branch=master)](http://travis-ci.org/qutip/qutip) 29 | [![Coverage Status](https://img.shields.io/coveralls/qutip/qutip.svg)](https://coveralls.io/r/qutip/qutip) 30 | [![Maintainability](https://api.codeclimate.com/v1/badges/df502674f1dfa1f1b67a/maintainability)](https://codeclimate.com/github/qutip/qutip/maintainability) 31 | 32 | Support 33 | -------- 34 | [![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org) 35 | [![Unitary Fund](https://img.shields.io/badge/Supported%20By-UNITARY%20FUND-brightgreen.svg?style=for-the-badge)](http://unitary.fund) 36 | 37 | QuTiP development is supported by [Nori's lab](http://dml.riken.jp/) 38 | at RIKEN, by the University of Sherbrooke, and by Aberystwyth University, 39 | [among other supporting organizations](http://qutip.org/#supporting-organizations). 40 | 41 | Download 42 | -------- 43 | [![Anaconda-Server Badge](https://anaconda.org/conda-forge/qutip/badges/downloads.svg)](https://anaconda.org/conda-forge/qutip) 44 | 45 | The official releases of QuTiP can be downloaded at: 46 | 47 | [http://qutip.org/download.html](http://qutip.org/download.html) 48 | 49 | 50 | Installation 51 | ------------ 52 | 53 | For instructions on how to install QuTiP, see: 54 | 55 | [http://qutip.org/docs/latest/installation.html](http://qutip.org/docs/latest/installation.html) 56 | 57 | 58 | Run notebooks online 59 | ----- 60 | A selection of demonstration notebooks is available at [http://qutip.org/tutorials.html](http://qutip.org/tutorials.html) and can be run online here: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/qutip/qutip-notebooks/master?filepath=index.ipynb) 61 | 62 | or may be found at: [github.com/qutip/qutip-notebooks](http://github.com/qutip/qutip-notebooks). 63 | 64 | 65 | Documentation 66 | ------------- 67 | 68 | The documentation for official releases, in HTML and PDF formats, are available at: 69 | 70 | [http://qutip.org/documentation.html](http://qutip.org/documentation.html) 71 | 72 | and the development documentation is available at [github.com/qutip/qutip-doc](http://github.com/qutip/qutip-doc). 73 | 74 | Contribute 75 | ---------- 76 | 77 | You are most welcome to contribute to QuTiP development by forking this 78 | repository and sending pull requests, or filing bug reports at the 79 | [issues page](http://github.com/qutip/qutip/issues), or send us bug reports, 80 | questions, or your proposed changes to our 81 | [QuTiP discussion group](http://groups.google.com/group/qutip). 82 | 83 | All contributions are acknowledged in the 84 | [contributors](http://github.com/qutip/qutip-doc/blob/master/contributors.rst) 85 | section in the documentation. 86 | 87 | Note that all contributions must adhere to the [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/). 88 | 89 | For more information, including technical advice, please see [Contributing to QuTiP development](https://github.com/qutip/qutip-doc/blob/master/CONTRIBUTING.md). 90 | 91 | Changelog 92 | --------- 93 | 94 | For release notes and a change log, see the 95 | [changelog](http://github.com/qutip/qutip-doc/blob/master/changelog.rst) 96 | section in the documentation. 97 | 98 | License 99 | ------- 100 | [![license](https://img.shields.io/badge/license-New%20BSD-blue.svg)](http://en.wikipedia.org/wiki/BSD_licenses#3-clause_license_.28.22Revised_BSD_License.22.2C_.22New_BSD_License.22.2C_or_.22Modified_BSD_License.22.29) 101 | 102 | You are free to use this software, with or without modification, provided that the conditions listed in the LICENSE.txt file are satisfied. 103 | -------------------------------------------------------------------------------- /qutip/tests/test_states.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | import pytest 35 | import numpy as np 36 | from numpy.testing import assert_, run_module_suite 37 | import qutip 38 | from qutip import (expect, destroy, coherent, coherent_dm, thermal_dm, 39 | fock_dm, triplet_states) 40 | 41 | 42 | @pytest.mark.parametrize("size, n", [(2, 0), (2, 1), (100, 99)]) 43 | def test_basis_simple(size, n): 44 | qobj = qutip.basis(size, n) 45 | numpy = np.zeros((size, 1), dtype=complex) 46 | numpy[n, 0] = 1 47 | assert np.array_equal(qobj.full(), numpy) 48 | 49 | 50 | @pytest.mark.parametrize("to_test", [qutip.basis, qutip.fock, qutip.fock_dm]) 51 | @pytest.mark.parametrize("size, n", [([2, 2], [0, 1]), ([2, 3, 4], [1, 2, 0])]) 52 | def test_implicit_tensor_basis_like(to_test, size, n): 53 | implicit = to_test(size, n) 54 | explicit = qutip.tensor(*[to_test(ss, nn) for ss, nn in zip(size, n)]) 55 | assert implicit == explicit 56 | 57 | 58 | @pytest.mark.parametrize("size, n, m", [ 59 | ([2, 2], [0, 0], [1, 1]), 60 | ([2, 3, 4], [1, 2, 0], [0, 1, 3]), 61 | ]) 62 | def test_implicit_tensor_projection(size, n, m): 63 | implicit = qutip.projection(size, n, m) 64 | explicit = qutip.tensor(*[qutip.projection(ss, nn, mm) 65 | for ss, nn, mm in zip(size, n, m)]) 66 | assert implicit == explicit 67 | 68 | 69 | class TestStates: 70 | """ 71 | A test class for the QuTiP functions for generating quantum states 72 | """ 73 | 74 | def testCoherentState(self): 75 | """ 76 | states: coherent state 77 | """ 78 | N = 10 79 | alpha = 0.5 80 | c1 = coherent(N, alpha) # displacement method 81 | c2 = coherent(7, alpha, offset=3) # analytic method 82 | assert_(abs(expect(destroy(N), c1) - alpha) < 1e-10) 83 | assert_((c1[3:]-c2).norm() < 1e-7) 84 | 85 | 86 | def testCoherentDensityMatrix(self): 87 | """ 88 | states: coherent density matrix 89 | """ 90 | N = 10 91 | 92 | rho = coherent_dm(N, 1) 93 | 94 | # make sure rho has trace close to 1.0 95 | assert_(abs(rho.tr() - 1.0) < 1e-12) 96 | 97 | def testThermalDensityMatrix(self): 98 | """ 99 | states: thermal density matrix 100 | """ 101 | N = 40 102 | 103 | rho = thermal_dm(N, 1) 104 | 105 | # make sure rho has trace close to 1.0 106 | assert_(abs(rho.tr() - 1.0) < 1e-12) 107 | 108 | def testFockDensityMatrix(self): 109 | """ 110 | states: Fock density matrix 111 | """ 112 | N = 10 113 | for i in range(N): 114 | rho = fock_dm(N, i) 115 | # make sure rho has trace close to 1.0 116 | assert_(abs(rho.tr() - 1.0) < 1e-12) 117 | assert_(rho.data[i, i] == 1.0) 118 | 119 | def testTripletStateNorm(self): 120 | """ 121 | Test the states returned by function triplet_states are normalized. 122 | """ 123 | for triplet in triplet_states(): 124 | assert_(abs(triplet.norm() - 1.) < 1e-12) 125 | 126 | 127 | if __name__ == "__main__": 128 | run_module_suite() 129 | -------------------------------------------------------------------------------- /qutip/topology.py: -------------------------------------------------------------------------------- 1 | # This file is part of QuTiP: Quantum Toolbox in Python. 2 | # 3 | # Copyright (c) 2011 and later, The QuTiP Project. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # 1. Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # 13 | # 2. Redistributions in binary form must reproduce the above copyright 14 | # notice, this list of conditions and the following disclaimer in the 15 | # documentation and/or other materials provided with the distribution. 16 | # 17 | # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names 18 | # of its contributors may be used to endorse or promote products derived 19 | # from this software without specific prior written permission. 20 | # 21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 25 | # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | ############################################################################### 33 | 34 | __all__ = ['berry_curvature', 'plot_berry_curvature'] 35 | 36 | from qutip import (Qobj, tensor, basis, qeye, isherm, sigmax, sigmay, sigmaz) 37 | import numpy as np 38 | 39 | try: 40 | import matplotlib.pyplot as plt 41 | except: 42 | pass 43 | 44 | 45 | def berry_curvature(eigfs): 46 | """Computes the discretized Berry curvature on the two dimensional grid 47 | of parameters. The function works well for cases with no band mixing. 48 | 49 | Parameters 50 | ========== 51 | eigfs : numpy ndarray 52 | 4 dimensional numpy ndarray where the first two indices are for the two 53 | discrete values of the two parameters and the third is the index of the 54 | occupied bands. The fourth dimension holds the eigenfunctions. 55 | 56 | Returns 57 | ------- 58 | b_curv : numpy ndarray 59 | A two dimensional array of the discretized Berry curvature defined for 60 | the values of the two parameters defined in the eigfs. 61 | """ 62 | nparam0 = eigfs.shape[0] 63 | nparam1 = eigfs.shape[1] 64 | nocc = eigfs.shape[2] 65 | b_curv = np.zeros((nparam0-1, nparam1-1), dtype=float) 66 | 67 | for i in range(nparam0-1): 68 | for j in range(nparam1-1): 69 | rect_prd = np.identity(nocc, dtype=complex) 70 | innP0 = np.zeros([nocc, nocc], dtype=complex) 71 | innP1 = np.zeros([nocc, nocc], dtype=complex) 72 | innP2 = np.zeros([nocc, nocc], dtype=complex) 73 | innP3 = np.zeros([nocc, nocc], dtype=complex) 74 | 75 | for k in range(nocc): 76 | for l in range(nocc): 77 | wf0 = eigfs[i, j, k, :] 78 | wf1 = eigfs[i+1, j, l, :] 79 | innP0[k, l] = np.dot(wf0.conjugate(), wf1) 80 | 81 | wf1 = eigfs[i+1, j, k, :] 82 | wf2 = eigfs[i+1, j+1, l, :] 83 | innP1[k, l] = np.dot(wf1.conjugate(), wf2) 84 | 85 | wf2 = eigfs[i+1, j+1, k, :] 86 | wf3 = eigfs[i, j+1, l, :] 87 | innP2[k, l] = np.dot(wf2.conjugate(), wf3) 88 | 89 | wf3 = eigfs[i, j+1, k, :] 90 | wf0 = eigfs[i, j, l, :] 91 | innP3[k, l] = np.dot(wf3.conjugate(), wf0) 92 | 93 | rect_prd = np.dot(rect_prd, innP0) 94 | rect_prd = np.dot(rect_prd, innP1) 95 | rect_prd = np.dot(rect_prd, innP2) 96 | rect_prd = np.dot(rect_prd, innP3) 97 | 98 | dett = np.linalg.det(rect_prd) 99 | curl_z = np.angle(dett) 100 | b_curv[i, j] = curl_z 101 | 102 | return b_curv 103 | 104 | 105 | def plot_berry_curvature(eigfs): 106 | """Plots the discretized Berry curvature on the two dimensional grid 107 | of parameters. The function works well for cases with no band mixing.""" 108 | b_curv = berry_curvature(eigfs) 109 | fig, ax = plt.subplots() 110 | ax.imshow(b_curv, origin="lower") 111 | ax.set_title("Berry curvature") 112 | ax.set_xlabel(r"$Parameter0$") 113 | ax.set_ylabel(r"$Parameter1$") 114 | fig.tight_layout() 115 | fig.savefig("berry_curvature.pdf") 116 | --------------------------------------------------------------------------------