Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- omnilmm/lib/python3.10/site-packages/nvidia/cuda_cupti/include/generated_cudaVDPAU_meta.h +46 -0
- omnilmm/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcheckpoint.so +3 -0
- wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/hydrogen.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/matrices.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/pring.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/qho_1d.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/secondquant.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/activation.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/musculotendon.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/curve.py +1763 -0
- wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__init__.py +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_activation.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/cable.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/truss.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_cable.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/__init__.py +16 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/__pycache__/control_plots.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/control_plots.py +978 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/lti.py +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_control_plots.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_lti.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py +299 -0
- wemm/lib/python3.10/site-packages/sympy/physics/control/tests/test_lti.py +1750 -0
- wemm/lib/python3.10/site-packages/sympy/physics/optics/gaussopt.py +923 -0
- wemm/lib/python3.10/site-packages/sympy/physics/optics/tests/test_waves.py +82 -0
- wemm/lib/python3.10/site-packages/sympy/physics/optics/utils.py +698 -0
- wemm/lib/python3.10/site-packages/sympy/physics/optics/waves.py +340 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/boson.py +259 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py +239 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/gate.py +1309 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/grover.py +345 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py +653 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py +853 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/operator.py +657 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/shor.py +173 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/spin.py +2150 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_identitysearch.py +492 -0
- wemm/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_represent.py +186 -0
- wemm/lib/python3.10/site-packages/sympy/physics/tests/__init__.py +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -979,3 +979,4 @@ parrot/lib/python3.10/site-packages/scipy/stats/_stats.cpython-310-x86_64-linux-
|
|
| 979 |
videollama2/lib/python3.10/site-packages/altair/vegalite/v5/schema/__pycache__/channels.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 980 |
omnilmm/lib/python3.10/site-packages/fontTools/__pycache__/agl.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 981 |
omnilmm/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn.so.8 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 979 |
videollama2/lib/python3.10/site-packages/altair/vegalite/v5/schema/__pycache__/channels.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 980 |
omnilmm/lib/python3.10/site-packages/fontTools/__pycache__/agl.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 981 |
omnilmm/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn.so.8 filter=lfs diff=lfs merge=lfs -text
|
| 982 |
+
omnilmm/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcheckpoint.so filter=lfs diff=lfs merge=lfs -text
|
omnilmm/lib/python3.10/site-packages/nvidia/cuda_cupti/include/generated_cudaVDPAU_meta.h
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// This file is generated. Any changes you make will be lost during the next clean build.
|
| 2 |
+
|
| 3 |
+
// Dependent includes
|
| 4 |
+
#include <vdpau/vdpau.h>
|
| 5 |
+
|
| 6 |
+
// CUDA public interface, for type definitions and cu* function prototypes
|
| 7 |
+
#include "cudaVDPAU.h"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
// *************************************************************************
|
| 11 |
+
// Definitions of structs to hold parameters for each function
|
| 12 |
+
// *************************************************************************
|
| 13 |
+
|
| 14 |
+
typedef struct cuVDPAUGetDevice_params_st {
|
| 15 |
+
CUdevice *pDevice;
|
| 16 |
+
VdpDevice vdpDevice;
|
| 17 |
+
VdpGetProcAddress *vdpGetProcAddress;
|
| 18 |
+
} cuVDPAUGetDevice_params;
|
| 19 |
+
|
| 20 |
+
typedef struct cuVDPAUCtxCreate_v2_params_st {
|
| 21 |
+
CUcontext *pCtx;
|
| 22 |
+
unsigned int flags;
|
| 23 |
+
CUdevice device;
|
| 24 |
+
VdpDevice vdpDevice;
|
| 25 |
+
VdpGetProcAddress *vdpGetProcAddress;
|
| 26 |
+
} cuVDPAUCtxCreate_v2_params;
|
| 27 |
+
|
| 28 |
+
typedef struct cuGraphicsVDPAURegisterVideoSurface_params_st {
|
| 29 |
+
CUgraphicsResource *pCudaResource;
|
| 30 |
+
VdpVideoSurface vdpSurface;
|
| 31 |
+
unsigned int flags;
|
| 32 |
+
} cuGraphicsVDPAURegisterVideoSurface_params;
|
| 33 |
+
|
| 34 |
+
typedef struct cuGraphicsVDPAURegisterOutputSurface_params_st {
|
| 35 |
+
CUgraphicsResource *pCudaResource;
|
| 36 |
+
VdpOutputSurface vdpSurface;
|
| 37 |
+
unsigned int flags;
|
| 38 |
+
} cuGraphicsVDPAURegisterOutputSurface_params;
|
| 39 |
+
|
| 40 |
+
typedef struct cuVDPAUCtxCreate_params_st {
|
| 41 |
+
CUcontext *pCtx;
|
| 42 |
+
unsigned int flags;
|
| 43 |
+
CUdevice device;
|
| 44 |
+
VdpDevice vdpDevice;
|
| 45 |
+
VdpGetProcAddress *vdpGetProcAddress;
|
| 46 |
+
} cuVDPAUCtxCreate_params;
|
omnilmm/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcheckpoint.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1626ff119582bca46605bc6d49769ab75314b9993dd647bd64a90dec747bc843
|
| 3 |
+
size 1534104
|
wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (404 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/hydrogen.cpython-310.pyc
ADDED
|
Binary file (7.35 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/matrices.cpython-310.pyc
ADDED
|
Binary file (3.62 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/pring.cpython-310.pyc
ADDED
|
Binary file (2.58 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/qho_1d.cpython-310.pyc
ADDED
|
Binary file (2.41 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/__pycache__/secondquant.cpython-310.pyc
ADDED
|
Binary file (83.7 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/activation.cpython-310.pyc
ADDED
|
Binary file (25.8 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/__pycache__/musculotendon.cpython-310.pyc
ADDED
|
Binary file (52.3 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/curve.py
ADDED
|
@@ -0,0 +1,1763 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Implementations of characteristic curves for musculotendon models."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
|
| 5 |
+
from sympy.core.expr import UnevaluatedExpr
|
| 6 |
+
from sympy.core.function import ArgumentIndexError, Function
|
| 7 |
+
from sympy.core.numbers import Float, Integer
|
| 8 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 9 |
+
from sympy.functions.elementary.hyperbolic import cosh, sinh
|
| 10 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 11 |
+
from sympy.printing.precedence import PRECEDENCE
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
'CharacteristicCurveCollection',
|
| 16 |
+
'CharacteristicCurveFunction',
|
| 17 |
+
'FiberForceLengthActiveDeGroote2016',
|
| 18 |
+
'FiberForceLengthPassiveDeGroote2016',
|
| 19 |
+
'FiberForceLengthPassiveInverseDeGroote2016',
|
| 20 |
+
'FiberForceVelocityDeGroote2016',
|
| 21 |
+
'FiberForceVelocityInverseDeGroote2016',
|
| 22 |
+
'TendonForceLengthDeGroote2016',
|
| 23 |
+
'TendonForceLengthInverseDeGroote2016',
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class CharacteristicCurveFunction(Function):
|
| 28 |
+
"""Base class for all musculotendon characteristic curve functions."""
|
| 29 |
+
|
| 30 |
+
@classmethod
|
| 31 |
+
def eval(cls):
|
| 32 |
+
msg = (
|
| 33 |
+
f'Cannot directly instantiate {cls.__name__!r}, instances of '
|
| 34 |
+
f'characteristic curves must be of a concrete subclass.'
|
| 35 |
+
|
| 36 |
+
)
|
| 37 |
+
raise TypeError(msg)
|
| 38 |
+
|
| 39 |
+
def _print_code(self, printer):
|
| 40 |
+
"""Print code for the function defining the curve using a printer.
|
| 41 |
+
|
| 42 |
+
Explanation
|
| 43 |
+
===========
|
| 44 |
+
|
| 45 |
+
The order of operations may need to be controlled as constant folding
|
| 46 |
+
the numeric terms within the equations of a musculotendon
|
| 47 |
+
characteristic curve can sometimes results in a numerically-unstable
|
| 48 |
+
expression.
|
| 49 |
+
|
| 50 |
+
Parameters
|
| 51 |
+
==========
|
| 52 |
+
|
| 53 |
+
printer : Printer
|
| 54 |
+
The printer to be used to print a string representation of the
|
| 55 |
+
characteristic curve as valid code in the target language.
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
return printer._print(printer.parenthesize(
|
| 59 |
+
self.doit(deep=False, evaluate=False), PRECEDENCE['Atom'],
|
| 60 |
+
))
|
| 61 |
+
|
| 62 |
+
_ccode = _print_code
|
| 63 |
+
_cupycode = _print_code
|
| 64 |
+
_cxxcode = _print_code
|
| 65 |
+
_fcode = _print_code
|
| 66 |
+
_jaxcode = _print_code
|
| 67 |
+
_lambdacode = _print_code
|
| 68 |
+
_mpmathcode = _print_code
|
| 69 |
+
_octave = _print_code
|
| 70 |
+
_pythoncode = _print_code
|
| 71 |
+
_numpycode = _print_code
|
| 72 |
+
_scipycode = _print_code
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TendonForceLengthDeGroote2016(CharacteristicCurveFunction):
|
| 76 |
+
r"""Tendon force-length curve based on De Groote et al., 2016 [1]_.
|
| 77 |
+
|
| 78 |
+
Explanation
|
| 79 |
+
===========
|
| 80 |
+
|
| 81 |
+
Gives the normalized tendon force produced as a function of normalized
|
| 82 |
+
tendon length.
|
| 83 |
+
|
| 84 |
+
The function is defined by the equation:
|
| 85 |
+
|
| 86 |
+
$fl^T = c_0 \exp{c_3 \left( \tilde{l}^T - c_1 \right)} - c_2$
|
| 87 |
+
|
| 88 |
+
with constant values of $c_0 = 0.2$, $c_1 = 0.995$, $c_2 = 0.25$, and
|
| 89 |
+
$c_3 = 33.93669377311689$.
|
| 90 |
+
|
| 91 |
+
While it is possible to change the constant values, these were carefully
|
| 92 |
+
selected in the original publication to give the characteristic curve
|
| 93 |
+
specific and required properties. For example, the function produces no
|
| 94 |
+
force when the tendon is in an unstrained state. It also produces a force
|
| 95 |
+
of 1 normalized unit when the tendon is under a 5% strain.
|
| 96 |
+
|
| 97 |
+
Examples
|
| 98 |
+
========
|
| 99 |
+
|
| 100 |
+
The preferred way to instantiate :class:`TendonForceLengthDeGroote2016` is using
|
| 101 |
+
the :meth:`~.with_defaults` constructor because this will automatically
|
| 102 |
+
populate the constants within the characteristic curve equation with the
|
| 103 |
+
floating point values from the original publication. This constructor takes
|
| 104 |
+
a single argument corresponding to normalized tendon length. We'll create a
|
| 105 |
+
:class:`~.Symbol` called ``l_T_tilde`` to represent this.
|
| 106 |
+
|
| 107 |
+
>>> from sympy import Symbol
|
| 108 |
+
>>> from sympy.physics.biomechanics import TendonForceLengthDeGroote2016
|
| 109 |
+
>>> l_T_tilde = Symbol('l_T_tilde')
|
| 110 |
+
>>> fl_T = TendonForceLengthDeGroote2016.with_defaults(l_T_tilde)
|
| 111 |
+
>>> fl_T
|
| 112 |
+
TendonForceLengthDeGroote2016(l_T_tilde, 0.2, 0.995, 0.25,
|
| 113 |
+
33.93669377311689)
|
| 114 |
+
|
| 115 |
+
It's also possible to populate the four constants with your own values too.
|
| 116 |
+
|
| 117 |
+
>>> from sympy import symbols
|
| 118 |
+
>>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
|
| 119 |
+
>>> fl_T = TendonForceLengthDeGroote2016(l_T_tilde, c0, c1, c2, c3)
|
| 120 |
+
>>> fl_T
|
| 121 |
+
TendonForceLengthDeGroote2016(l_T_tilde, c0, c1, c2, c3)
|
| 122 |
+
|
| 123 |
+
You don't just have to use symbols as the arguments, it's also possible to
|
| 124 |
+
use expressions. Let's create a new pair of symbols, ``l_T`` and
|
| 125 |
+
``l_T_slack``, representing tendon length and tendon slack length
|
| 126 |
+
respectively. We can then represent ``l_T_tilde`` as an expression, the
|
| 127 |
+
ratio of these.
|
| 128 |
+
|
| 129 |
+
>>> l_T, l_T_slack = symbols('l_T l_T_slack')
|
| 130 |
+
>>> l_T_tilde = l_T/l_T_slack
|
| 131 |
+
>>> fl_T = TendonForceLengthDeGroote2016.with_defaults(l_T_tilde)
|
| 132 |
+
>>> fl_T
|
| 133 |
+
TendonForceLengthDeGroote2016(l_T/l_T_slack, 0.2, 0.995, 0.25,
|
| 134 |
+
33.93669377311689)
|
| 135 |
+
|
| 136 |
+
To inspect the actual symbolic expression that this function represents,
|
| 137 |
+
we can call the :meth:`~.doit` method on an instance. We'll use the keyword
|
| 138 |
+
argument ``evaluate=False`` as this will keep the expression in its
|
| 139 |
+
canonical form and won't simplify any constants.
|
| 140 |
+
|
| 141 |
+
>>> fl_T.doit(evaluate=False)
|
| 142 |
+
-0.25 + 0.2*exp(33.93669377311689*(l_T/l_T_slack - 0.995))
|
| 143 |
+
|
| 144 |
+
The function can also be differentiated. We'll differentiate with respect
|
| 145 |
+
to l_T using the ``diff`` method on an instance with the single positional
|
| 146 |
+
argument ``l_T``.
|
| 147 |
+
|
| 148 |
+
>>> fl_T.diff(l_T)
|
| 149 |
+
6.787338754623378*exp(33.93669377311689*(l_T/l_T_slack - 0.995))/l_T_slack
|
| 150 |
+
|
| 151 |
+
References
|
| 152 |
+
==========
|
| 153 |
+
|
| 154 |
+
.. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
|
| 155 |
+
of direct collocation optimal control problem formulations for
|
| 156 |
+
solving the muscle redundancy problem, Annals of biomedical
|
| 157 |
+
engineering, 44(10), (2016) pp. 2922-2936
|
| 158 |
+
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
@classmethod
|
| 162 |
+
def with_defaults(cls, l_T_tilde):
|
| 163 |
+
r"""Recommended constructor that will use the published constants.
|
| 164 |
+
|
| 165 |
+
Explanation
|
| 166 |
+
===========
|
| 167 |
+
|
| 168 |
+
Returns a new instance of the tendon force-length function using the
|
| 169 |
+
four constant values specified in the original publication.
|
| 170 |
+
|
| 171 |
+
These have the values:
|
| 172 |
+
|
| 173 |
+
$c_0 = 0.2$
|
| 174 |
+
$c_1 = 0.995$
|
| 175 |
+
$c_2 = 0.25$
|
| 176 |
+
$c_3 = 33.93669377311689$
|
| 177 |
+
|
| 178 |
+
Parameters
|
| 179 |
+
==========
|
| 180 |
+
|
| 181 |
+
l_T_tilde : Any (sympifiable)
|
| 182 |
+
Normalized tendon length.
|
| 183 |
+
|
| 184 |
+
"""
|
| 185 |
+
c0 = Float('0.2')
|
| 186 |
+
c1 = Float('0.995')
|
| 187 |
+
c2 = Float('0.25')
|
| 188 |
+
c3 = Float('33.93669377311689')
|
| 189 |
+
return cls(l_T_tilde, c0, c1, c2, c3)
|
| 190 |
+
|
| 191 |
+
@classmethod
|
| 192 |
+
def eval(cls, l_T_tilde, c0, c1, c2, c3):
|
| 193 |
+
"""Evaluation of basic inputs.
|
| 194 |
+
|
| 195 |
+
Parameters
|
| 196 |
+
==========
|
| 197 |
+
|
| 198 |
+
l_T_tilde : Any (sympifiable)
|
| 199 |
+
Normalized tendon length.
|
| 200 |
+
c0 : Any (sympifiable)
|
| 201 |
+
The first constant in the characteristic equation. The published
|
| 202 |
+
value is ``0.2``.
|
| 203 |
+
c1 : Any (sympifiable)
|
| 204 |
+
The second constant in the characteristic equation. The published
|
| 205 |
+
value is ``0.995``.
|
| 206 |
+
c2 : Any (sympifiable)
|
| 207 |
+
The third constant in the characteristic equation. The published
|
| 208 |
+
value is ``0.25``.
|
| 209 |
+
c3 : Any (sympifiable)
|
| 210 |
+
The fourth constant in the characteristic equation. The published
|
| 211 |
+
value is ``33.93669377311689``.
|
| 212 |
+
|
| 213 |
+
"""
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
def _eval_evalf(self, prec):
|
| 217 |
+
"""Evaluate the expression numerically using ``evalf``."""
|
| 218 |
+
return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
|
| 219 |
+
|
| 220 |
+
def doit(self, deep=True, evaluate=True, **hints):
|
| 221 |
+
"""Evaluate the expression defining the function.
|
| 222 |
+
|
| 223 |
+
Parameters
|
| 224 |
+
==========
|
| 225 |
+
|
| 226 |
+
deep : bool
|
| 227 |
+
Whether ``doit`` should be recursively called. Default is ``True``.
|
| 228 |
+
evaluate : bool.
|
| 229 |
+
Whether the SymPy expression should be evaluated as it is
|
| 230 |
+
constructed. If ``False``, then no constant folding will be
|
| 231 |
+
conducted which will leave the expression in a more numerically-
|
| 232 |
+
stable for values of ``l_T_tilde`` that correspond to a sensible
|
| 233 |
+
operating range for a musculotendon. Default is ``True``.
|
| 234 |
+
**kwargs : dict[str, Any]
|
| 235 |
+
Additional keyword argument pairs to be recursively passed to
|
| 236 |
+
``doit``.
|
| 237 |
+
|
| 238 |
+
"""
|
| 239 |
+
l_T_tilde, *constants = self.args
|
| 240 |
+
if deep:
|
| 241 |
+
hints['evaluate'] = evaluate
|
| 242 |
+
l_T_tilde = l_T_tilde.doit(deep=deep, **hints)
|
| 243 |
+
c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
|
| 244 |
+
else:
|
| 245 |
+
c0, c1, c2, c3 = constants
|
| 246 |
+
|
| 247 |
+
if evaluate:
|
| 248 |
+
return c0*exp(c3*(l_T_tilde - c1)) - c2
|
| 249 |
+
|
| 250 |
+
return c0*exp(c3*UnevaluatedExpr(l_T_tilde - c1)) - c2
|
| 251 |
+
|
| 252 |
+
def fdiff(self, argindex=1):
|
| 253 |
+
"""Derivative of the function with respect to a single argument.
|
| 254 |
+
|
| 255 |
+
Parameters
|
| 256 |
+
==========
|
| 257 |
+
|
| 258 |
+
argindex : int
|
| 259 |
+
The index of the function's arguments with respect to which the
|
| 260 |
+
derivative should be taken. Argument indexes start at ``1``.
|
| 261 |
+
Default is ``1``.
|
| 262 |
+
|
| 263 |
+
"""
|
| 264 |
+
l_T_tilde, c0, c1, c2, c3 = self.args
|
| 265 |
+
if argindex == 1:
|
| 266 |
+
return c0*c3*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
|
| 267 |
+
elif argindex == 2:
|
| 268 |
+
return exp(c3*UnevaluatedExpr(l_T_tilde - c1))
|
| 269 |
+
elif argindex == 3:
|
| 270 |
+
return -c0*c3*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
|
| 271 |
+
elif argindex == 4:
|
| 272 |
+
return Integer(-1)
|
| 273 |
+
elif argindex == 5:
|
| 274 |
+
return c0*(l_T_tilde - c1)*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
|
| 275 |
+
|
| 276 |
+
raise ArgumentIndexError(self, argindex)
|
| 277 |
+
|
| 278 |
+
def inverse(self, argindex=1):
|
| 279 |
+
"""Inverse function.
|
| 280 |
+
|
| 281 |
+
Parameters
|
| 282 |
+
==========
|
| 283 |
+
|
| 284 |
+
argindex : int
|
| 285 |
+
Value to start indexing the arguments at. Default is ``1``.
|
| 286 |
+
|
| 287 |
+
"""
|
| 288 |
+
return TendonForceLengthInverseDeGroote2016
|
| 289 |
+
|
| 290 |
+
def _latex(self, printer):
|
| 291 |
+
"""Print a LaTeX representation of the function defining the curve.
|
| 292 |
+
|
| 293 |
+
Parameters
|
| 294 |
+
==========
|
| 295 |
+
|
| 296 |
+
printer : Printer
|
| 297 |
+
The printer to be used to print the LaTeX string representation.
|
| 298 |
+
|
| 299 |
+
"""
|
| 300 |
+
l_T_tilde = self.args[0]
|
| 301 |
+
_l_T_tilde = printer._print(l_T_tilde)
|
| 302 |
+
return r'\operatorname{fl}^T \left( %s \right)' % _l_T_tilde
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class TendonForceLengthInverseDeGroote2016(CharacteristicCurveFunction):
|
| 306 |
+
r"""Inverse tendon force-length curve based on De Groote et al., 2016 [1]_.
|
| 307 |
+
|
| 308 |
+
Explanation
|
| 309 |
+
===========
|
| 310 |
+
|
| 311 |
+
Gives the normalized tendon length that produces a specific normalized
|
| 312 |
+
tendon force.
|
| 313 |
+
|
| 314 |
+
The function is defined by the equation:
|
| 315 |
+
|
| 316 |
+
${fl^T}^{-1} = frac{\log{\frac{fl^T + c_2}{c_0}}}{c_3} + c_1$
|
| 317 |
+
|
| 318 |
+
with constant values of $c_0 = 0.2$, $c_1 = 0.995$, $c_2 = 0.25$, and
|
| 319 |
+
$c_3 = 33.93669377311689$. This function is the exact analytical inverse
|
| 320 |
+
of the related tendon force-length curve ``TendonForceLengthDeGroote2016``.
|
| 321 |
+
|
| 322 |
+
While it is possible to change the constant values, these were carefully
|
| 323 |
+
selected in the original publication to give the characteristic curve
|
| 324 |
+
specific and required properties. For example, the function produces no
|
| 325 |
+
force when the tendon is in an unstrained state. It also produces a force
|
| 326 |
+
of 1 normalized unit when the tendon is under a 5% strain.
|
| 327 |
+
|
| 328 |
+
Examples
|
| 329 |
+
========
|
| 330 |
+
|
| 331 |
+
The preferred way to instantiate :class:`TendonForceLengthInverseDeGroote2016` is
|
| 332 |
+
using the :meth:`~.with_defaults` constructor because this will automatically
|
| 333 |
+
populate the constants within the characteristic curve equation with the
|
| 334 |
+
floating point values from the original publication. This constructor takes
|
| 335 |
+
a single argument corresponding to normalized tendon force-length, which is
|
| 336 |
+
equal to the tendon force. We'll create a :class:`~.Symbol` called ``fl_T`` to
|
| 337 |
+
represent this.
|
| 338 |
+
|
| 339 |
+
>>> from sympy import Symbol
|
| 340 |
+
>>> from sympy.physics.biomechanics import TendonForceLengthInverseDeGroote2016
|
| 341 |
+
>>> fl_T = Symbol('fl_T')
|
| 342 |
+
>>> l_T_tilde = TendonForceLengthInverseDeGroote2016.with_defaults(fl_T)
|
| 343 |
+
>>> l_T_tilde
|
| 344 |
+
TendonForceLengthInverseDeGroote2016(fl_T, 0.2, 0.995, 0.25,
|
| 345 |
+
33.93669377311689)
|
| 346 |
+
|
| 347 |
+
It's also possible to populate the four constants with your own values too.
|
| 348 |
+
|
| 349 |
+
>>> from sympy import symbols
|
| 350 |
+
>>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
|
| 351 |
+
>>> l_T_tilde = TendonForceLengthInverseDeGroote2016(fl_T, c0, c1, c2, c3)
|
| 352 |
+
>>> l_T_tilde
|
| 353 |
+
TendonForceLengthInverseDeGroote2016(fl_T, c0, c1, c2, c3)
|
| 354 |
+
|
| 355 |
+
To inspect the actual symbolic expression that this function represents,
|
| 356 |
+
we can call the :meth:`~.doit` method on an instance. We'll use the keyword
|
| 357 |
+
argument ``evaluate=False`` as this will keep the expression in its
|
| 358 |
+
canonical form and won't simplify any constants.
|
| 359 |
+
|
| 360 |
+
>>> l_T_tilde.doit(evaluate=False)
|
| 361 |
+
c1 + log((c2 + fl_T)/c0)/c3
|
| 362 |
+
|
| 363 |
+
The function can also be differentiated. We'll differentiate with respect
|
| 364 |
+
to l_T using the ``diff`` method on an instance with the single positional
|
| 365 |
+
argument ``l_T``.
|
| 366 |
+
|
| 367 |
+
>>> l_T_tilde.diff(fl_T)
|
| 368 |
+
1/(c3*(c2 + fl_T))
|
| 369 |
+
|
| 370 |
+
References
|
| 371 |
+
==========
|
| 372 |
+
|
| 373 |
+
.. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
|
| 374 |
+
of direct collocation optimal control problem formulations for
|
| 375 |
+
solving the muscle redundancy problem, Annals of biomedical
|
| 376 |
+
engineering, 44(10), (2016) pp. 2922-2936
|
| 377 |
+
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
@classmethod
|
| 381 |
+
def with_defaults(cls, fl_T):
|
| 382 |
+
r"""Recommended constructor that will use the published constants.
|
| 383 |
+
|
| 384 |
+
Explanation
|
| 385 |
+
===========
|
| 386 |
+
|
| 387 |
+
Returns a new instance of the inverse tendon force-length function
|
| 388 |
+
using the four constant values specified in the original publication.
|
| 389 |
+
|
| 390 |
+
These have the values:
|
| 391 |
+
|
| 392 |
+
$c_0 = 0.2$
|
| 393 |
+
$c_1 = 0.995$
|
| 394 |
+
$c_2 = 0.25$
|
| 395 |
+
$c_3 = 33.93669377311689$
|
| 396 |
+
|
| 397 |
+
Parameters
|
| 398 |
+
==========
|
| 399 |
+
|
| 400 |
+
fl_T : Any (sympifiable)
|
| 401 |
+
Normalized tendon force as a function of tendon length.
|
| 402 |
+
|
| 403 |
+
"""
|
| 404 |
+
c0 = Float('0.2')
|
| 405 |
+
c1 = Float('0.995')
|
| 406 |
+
c2 = Float('0.25')
|
| 407 |
+
c3 = Float('33.93669377311689')
|
| 408 |
+
return cls(fl_T, c0, c1, c2, c3)
|
| 409 |
+
|
| 410 |
+
@classmethod
|
| 411 |
+
def eval(cls, fl_T, c0, c1, c2, c3):
|
| 412 |
+
"""Evaluation of basic inputs.
|
| 413 |
+
|
| 414 |
+
Parameters
|
| 415 |
+
==========
|
| 416 |
+
|
| 417 |
+
fl_T : Any (sympifiable)
|
| 418 |
+
Normalized tendon force as a function of tendon length.
|
| 419 |
+
c0 : Any (sympifiable)
|
| 420 |
+
The first constant in the characteristic equation. The published
|
| 421 |
+
value is ``0.2``.
|
| 422 |
+
c1 : Any (sympifiable)
|
| 423 |
+
The second constant in the characteristic equation. The published
|
| 424 |
+
value is ``0.995``.
|
| 425 |
+
c2 : Any (sympifiable)
|
| 426 |
+
The third constant in the characteristic equation. The published
|
| 427 |
+
value is ``0.25``.
|
| 428 |
+
c3 : Any (sympifiable)
|
| 429 |
+
The fourth constant in the characteristic equation. The published
|
| 430 |
+
value is ``33.93669377311689``.
|
| 431 |
+
|
| 432 |
+
"""
|
| 433 |
+
pass
|
| 434 |
+
|
| 435 |
+
def _eval_evalf(self, prec):
|
| 436 |
+
"""Evaluate the expression numerically using ``evalf``."""
|
| 437 |
+
return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
|
| 438 |
+
|
| 439 |
+
def doit(self, deep=True, evaluate=True, **hints):
|
| 440 |
+
"""Evaluate the expression defining the function.
|
| 441 |
+
|
| 442 |
+
Parameters
|
| 443 |
+
==========
|
| 444 |
+
|
| 445 |
+
deep : bool
|
| 446 |
+
Whether ``doit`` should be recursively called. Default is ``True``.
|
| 447 |
+
evaluate : bool.
|
| 448 |
+
Whether the SymPy expression should be evaluated as it is
|
| 449 |
+
constructed. If ``False``, then no constant folding will be
|
| 450 |
+
conducted which will leave the expression in a more numerically-
|
| 451 |
+
stable for values of ``l_T_tilde`` that correspond to a sensible
|
| 452 |
+
operating range for a musculotendon. Default is ``True``.
|
| 453 |
+
**kwargs : dict[str, Any]
|
| 454 |
+
Additional keyword argument pairs to be recursively passed to
|
| 455 |
+
``doit``.
|
| 456 |
+
|
| 457 |
+
"""
|
| 458 |
+
fl_T, *constants = self.args
|
| 459 |
+
if deep:
|
| 460 |
+
hints['evaluate'] = evaluate
|
| 461 |
+
fl_T = fl_T.doit(deep=deep, **hints)
|
| 462 |
+
c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
|
| 463 |
+
else:
|
| 464 |
+
c0, c1, c2, c3 = constants
|
| 465 |
+
|
| 466 |
+
if evaluate:
|
| 467 |
+
return log((fl_T + c2)/c0)/c3 + c1
|
| 468 |
+
|
| 469 |
+
return log(UnevaluatedExpr((fl_T + c2)/c0))/c3 + c1
|
| 470 |
+
|
| 471 |
+
def fdiff(self, argindex=1):
|
| 472 |
+
"""Derivative of the function with respect to a single argument.
|
| 473 |
+
|
| 474 |
+
Parameters
|
| 475 |
+
==========
|
| 476 |
+
|
| 477 |
+
argindex : int
|
| 478 |
+
The index of the function's arguments with respect to which the
|
| 479 |
+
derivative should be taken. Argument indexes start at ``1``.
|
| 480 |
+
Default is ``1``.
|
| 481 |
+
|
| 482 |
+
"""
|
| 483 |
+
fl_T, c0, c1, c2, c3 = self.args
|
| 484 |
+
if argindex == 1:
|
| 485 |
+
return 1/(c3*(fl_T + c2))
|
| 486 |
+
elif argindex == 2:
|
| 487 |
+
return -1/(c0*c3)
|
| 488 |
+
elif argindex == 3:
|
| 489 |
+
return Integer(1)
|
| 490 |
+
elif argindex == 4:
|
| 491 |
+
return 1/(c3*(fl_T + c2))
|
| 492 |
+
elif argindex == 5:
|
| 493 |
+
return -log(UnevaluatedExpr((fl_T + c2)/c0))/c3**2
|
| 494 |
+
|
| 495 |
+
raise ArgumentIndexError(self, argindex)
|
| 496 |
+
|
| 497 |
+
def inverse(self, argindex=1):
|
| 498 |
+
"""Inverse function.
|
| 499 |
+
|
| 500 |
+
Parameters
|
| 501 |
+
==========
|
| 502 |
+
|
| 503 |
+
argindex : int
|
| 504 |
+
Value to start indexing the arguments at. Default is ``1``.
|
| 505 |
+
|
| 506 |
+
"""
|
| 507 |
+
return TendonForceLengthDeGroote2016
|
| 508 |
+
|
| 509 |
+
def _latex(self, printer):
|
| 510 |
+
"""Print a LaTeX representation of the function defining the curve.
|
| 511 |
+
|
| 512 |
+
Parameters
|
| 513 |
+
==========
|
| 514 |
+
|
| 515 |
+
printer : Printer
|
| 516 |
+
The printer to be used to print the LaTeX string representation.
|
| 517 |
+
|
| 518 |
+
"""
|
| 519 |
+
fl_T = self.args[0]
|
| 520 |
+
_fl_T = printer._print(fl_T)
|
| 521 |
+
return r'\left( \operatorname{fl}^T \right)^{-1} \left( %s \right)' % _fl_T
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class FiberForceLengthPassiveDeGroote2016(CharacteristicCurveFunction):
|
| 525 |
+
r"""Passive muscle fiber force-length curve based on De Groote et al., 2016
|
| 526 |
+
[1]_.
|
| 527 |
+
|
| 528 |
+
Explanation
|
| 529 |
+
===========
|
| 530 |
+
|
| 531 |
+
The function is defined by the equation:
|
| 532 |
+
|
| 533 |
+
$fl^M_{pas} = \frac{\frac{\exp{c_1 \left(\tilde{l^M} - 1\right)}}{c_0} - 1}{\exp{c_1} - 1}$
|
| 534 |
+
|
| 535 |
+
with constant values of $c_0 = 0.6$ and $c_1 = 4.0$.
|
| 536 |
+
|
| 537 |
+
While it is possible to change the constant values, these were carefully
|
| 538 |
+
selected in the original publication to give the characteristic curve
|
| 539 |
+
specific and required properties. For example, the function produces a
|
| 540 |
+
passive fiber force very close to 0 for all normalized fiber lengths
|
| 541 |
+
between 0 and 1.
|
| 542 |
+
|
| 543 |
+
Examples
|
| 544 |
+
========
|
| 545 |
+
|
| 546 |
+
The preferred way to instantiate :class:`FiberForceLengthPassiveDeGroote2016` is
|
| 547 |
+
using the :meth:`~.with_defaults` constructor because this will automatically
|
| 548 |
+
populate the constants within the characteristic curve equation with the
|
| 549 |
+
floating point values from the original publication. This constructor takes
|
| 550 |
+
a single argument corresponding to normalized muscle fiber length. We'll
|
| 551 |
+
create a :class:`~.Symbol` called ``l_M_tilde`` to represent this.
|
| 552 |
+
|
| 553 |
+
>>> from sympy import Symbol
|
| 554 |
+
>>> from sympy.physics.biomechanics import FiberForceLengthPassiveDeGroote2016
|
| 555 |
+
>>> l_M_tilde = Symbol('l_M_tilde')
|
| 556 |
+
>>> fl_M = FiberForceLengthPassiveDeGroote2016.with_defaults(l_M_tilde)
|
| 557 |
+
>>> fl_M
|
| 558 |
+
FiberForceLengthPassiveDeGroote2016(l_M_tilde, 0.6, 4.0)
|
| 559 |
+
|
| 560 |
+
It's also possible to populate the two constants with your own values too.
|
| 561 |
+
|
| 562 |
+
>>> from sympy import symbols
|
| 563 |
+
>>> c0, c1 = symbols('c0 c1')
|
| 564 |
+
>>> fl_M = FiberForceLengthPassiveDeGroote2016(l_M_tilde, c0, c1)
|
| 565 |
+
>>> fl_M
|
| 566 |
+
FiberForceLengthPassiveDeGroote2016(l_M_tilde, c0, c1)
|
| 567 |
+
|
| 568 |
+
You don't just have to use symbols as the arguments, it's also possible to
|
| 569 |
+
use expressions. Let's create a new pair of symbols, ``l_M`` and
|
| 570 |
+
``l_M_opt``, representing muscle fiber length and optimal muscle fiber
|
| 571 |
+
length respectively. We can then represent ``l_M_tilde`` as an expression,
|
| 572 |
+
the ratio of these.
|
| 573 |
+
|
| 574 |
+
>>> l_M, l_M_opt = symbols('l_M l_M_opt')
|
| 575 |
+
>>> l_M_tilde = l_M/l_M_opt
|
| 576 |
+
>>> fl_M = FiberForceLengthPassiveDeGroote2016.with_defaults(l_M_tilde)
|
| 577 |
+
>>> fl_M
|
| 578 |
+
FiberForceLengthPassiveDeGroote2016(l_M/l_M_opt, 0.6, 4.0)
|
| 579 |
+
|
| 580 |
+
To inspect the actual symbolic expression that this function represents,
|
| 581 |
+
we can call the :meth:`~.doit` method on an instance. We'll use the keyword
|
| 582 |
+
argument ``evaluate=False`` as this will keep the expression in its
|
| 583 |
+
canonical form and won't simplify any constants.
|
| 584 |
+
|
| 585 |
+
>>> fl_M.doit(evaluate=False)
|
| 586 |
+
0.0186573603637741*(-1 + exp(6.66666666666667*(l_M/l_M_opt - 1)))
|
| 587 |
+
|
| 588 |
+
The function can also be differentiated. We'll differentiate with respect
|
| 589 |
+
to l_M using the ``diff`` method on an instance with the single positional
|
| 590 |
+
argument ``l_M``.
|
| 591 |
+
|
| 592 |
+
>>> fl_M.diff(l_M)
|
| 593 |
+
0.12438240242516*exp(6.66666666666667*(l_M/l_M_opt - 1))/l_M_opt
|
| 594 |
+
|
| 595 |
+
References
|
| 596 |
+
==========
|
| 597 |
+
|
| 598 |
+
.. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
|
| 599 |
+
of direct collocation optimal control problem formulations for
|
| 600 |
+
solving the muscle redundancy problem, Annals of biomedical
|
| 601 |
+
engineering, 44(10), (2016) pp. 2922-2936
|
| 602 |
+
|
| 603 |
+
"""
|
| 604 |
+
|
| 605 |
+
@classmethod
|
| 606 |
+
def with_defaults(cls, l_M_tilde):
|
| 607 |
+
r"""Recommended constructor that will use the published constants.
|
| 608 |
+
|
| 609 |
+
Explanation
|
| 610 |
+
===========
|
| 611 |
+
|
| 612 |
+
Returns a new instance of the muscle fiber passive force-length
|
| 613 |
+
function using the four constant values specified in the original
|
| 614 |
+
publication.
|
| 615 |
+
|
| 616 |
+
These have the values:
|
| 617 |
+
|
| 618 |
+
$c_0 = 0.6$
|
| 619 |
+
$c_1 = 4.0$
|
| 620 |
+
|
| 621 |
+
Parameters
|
| 622 |
+
==========
|
| 623 |
+
|
| 624 |
+
l_M_tilde : Any (sympifiable)
|
| 625 |
+
Normalized muscle fiber length.
|
| 626 |
+
|
| 627 |
+
"""
|
| 628 |
+
c0 = Float('0.6')
|
| 629 |
+
c1 = Float('4.0')
|
| 630 |
+
return cls(l_M_tilde, c0, c1)
|
| 631 |
+
|
| 632 |
+
@classmethod
|
| 633 |
+
def eval(cls, l_M_tilde, c0, c1):
|
| 634 |
+
"""Evaluation of basic inputs.
|
| 635 |
+
|
| 636 |
+
Parameters
|
| 637 |
+
==========
|
| 638 |
+
|
| 639 |
+
l_M_tilde : Any (sympifiable)
|
| 640 |
+
Normalized muscle fiber length.
|
| 641 |
+
c0 : Any (sympifiable)
|
| 642 |
+
The first constant in the characteristic equation. The published
|
| 643 |
+
value is ``0.6``.
|
| 644 |
+
c1 : Any (sympifiable)
|
| 645 |
+
The second constant in the characteristic equation. The published
|
| 646 |
+
value is ``4.0``.
|
| 647 |
+
|
| 648 |
+
"""
|
| 649 |
+
pass
|
| 650 |
+
|
| 651 |
+
def _eval_evalf(self, prec):
|
| 652 |
+
"""Evaluate the expression numerically using ``evalf``."""
|
| 653 |
+
return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
|
| 654 |
+
|
| 655 |
+
def doit(self, deep=True, evaluate=True, **hints):
|
| 656 |
+
"""Evaluate the expression defining the function.
|
| 657 |
+
|
| 658 |
+
Parameters
|
| 659 |
+
==========
|
| 660 |
+
|
| 661 |
+
deep : bool
|
| 662 |
+
Whether ``doit`` should be recursively called. Default is ``True``.
|
| 663 |
+
evaluate : bool.
|
| 664 |
+
Whether the SymPy expression should be evaluated as it is
|
| 665 |
+
constructed. If ``False``, then no constant folding will be
|
| 666 |
+
conducted which will leave the expression in a more numerically-
|
| 667 |
+
stable for values of ``l_T_tilde`` that correspond to a sensible
|
| 668 |
+
operating range for a musculotendon. Default is ``True``.
|
| 669 |
+
**kwargs : dict[str, Any]
|
| 670 |
+
Additional keyword argument pairs to be recursively passed to
|
| 671 |
+
``doit``.
|
| 672 |
+
|
| 673 |
+
"""
|
| 674 |
+
l_M_tilde, *constants = self.args
|
| 675 |
+
if deep:
|
| 676 |
+
hints['evaluate'] = evaluate
|
| 677 |
+
l_M_tilde = l_M_tilde.doit(deep=deep, **hints)
|
| 678 |
+
c0, c1 = [c.doit(deep=deep, **hints) for c in constants]
|
| 679 |
+
else:
|
| 680 |
+
c0, c1 = constants
|
| 681 |
+
|
| 682 |
+
if evaluate:
|
| 683 |
+
return (exp((c1*(l_M_tilde - 1))/c0) - 1)/(exp(c1) - 1)
|
| 684 |
+
|
| 685 |
+
return (exp((c1*UnevaluatedExpr(l_M_tilde - 1))/c0) - 1)/(exp(c1) - 1)
|
| 686 |
+
|
| 687 |
+
def fdiff(self, argindex=1):
|
| 688 |
+
"""Derivative of the function with respect to a single argument.
|
| 689 |
+
|
| 690 |
+
Parameters
|
| 691 |
+
==========
|
| 692 |
+
|
| 693 |
+
argindex : int
|
| 694 |
+
The index of the function's arguments with respect to which the
|
| 695 |
+
derivative should be taken. Argument indexes start at ``1``.
|
| 696 |
+
Default is ``1``.
|
| 697 |
+
|
| 698 |
+
"""
|
| 699 |
+
l_M_tilde, c0, c1 = self.args
|
| 700 |
+
if argindex == 1:
|
| 701 |
+
return c1*exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)/(c0*(exp(c1) - 1))
|
| 702 |
+
elif argindex == 2:
|
| 703 |
+
return (
|
| 704 |
+
-c1*exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)
|
| 705 |
+
*UnevaluatedExpr(l_M_tilde - 1)/(c0**2*(exp(c1) - 1))
|
| 706 |
+
)
|
| 707 |
+
elif argindex == 3:
|
| 708 |
+
return (
|
| 709 |
+
-exp(c1)*(-1 + exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0))/(exp(c1) - 1)**2
|
| 710 |
+
+ exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)*(l_M_tilde - 1)/(c0*(exp(c1) - 1))
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
raise ArgumentIndexError(self, argindex)
|
| 714 |
+
|
| 715 |
+
def inverse(self, argindex=1):
|
| 716 |
+
"""Inverse function.
|
| 717 |
+
|
| 718 |
+
Parameters
|
| 719 |
+
==========
|
| 720 |
+
|
| 721 |
+
argindex : int
|
| 722 |
+
Value to start indexing the arguments at. Default is ``1``.
|
| 723 |
+
|
| 724 |
+
"""
|
| 725 |
+
return FiberForceLengthPassiveInverseDeGroote2016
|
| 726 |
+
|
| 727 |
+
def _latex(self, printer):
|
| 728 |
+
"""Print a LaTeX representation of the function defining the curve.
|
| 729 |
+
|
| 730 |
+
Parameters
|
| 731 |
+
==========
|
| 732 |
+
|
| 733 |
+
printer : Printer
|
| 734 |
+
The printer to be used to print the LaTeX string representation.
|
| 735 |
+
|
| 736 |
+
"""
|
| 737 |
+
l_M_tilde = self.args[0]
|
| 738 |
+
_l_M_tilde = printer._print(l_M_tilde)
|
| 739 |
+
return r'\operatorname{fl}^M_{pas} \left( %s \right)' % _l_M_tilde
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
class FiberForceLengthPassiveInverseDeGroote2016(CharacteristicCurveFunction):
|
| 743 |
+
r"""Inverse passive muscle fiber force-length curve based on De Groote et
|
| 744 |
+
al., 2016 [1]_.
|
| 745 |
+
|
| 746 |
+
Explanation
|
| 747 |
+
===========
|
| 748 |
+
|
| 749 |
+
Gives the normalized muscle fiber length that produces a specific normalized
|
| 750 |
+
passive muscle fiber force.
|
| 751 |
+
|
| 752 |
+
The function is defined by the equation:
|
| 753 |
+
|
| 754 |
+
${fl^M_{pas}}^{-1} = \frac{c_0 \log{\left(\exp{c_1} - 1\right)fl^M_pas + 1}}{c_1} + 1$
|
| 755 |
+
|
| 756 |
+
with constant values of $c_0 = 0.6$ and $c_1 = 4.0$. This function is the
|
| 757 |
+
exact analytical inverse of the related tendon force-length curve
|
| 758 |
+
``FiberForceLengthPassiveDeGroote2016``.
|
| 759 |
+
|
| 760 |
+
While it is possible to change the constant values, these were carefully
|
| 761 |
+
selected in the original publication to give the characteristic curve
|
| 762 |
+
specific and required properties. For example, the function produces a
|
| 763 |
+
passive fiber force very close to 0 for all normalized fiber lengths
|
| 764 |
+
between 0 and 1.
|
| 765 |
+
|
| 766 |
+
Examples
|
| 767 |
+
========
|
| 768 |
+
|
| 769 |
+
The preferred way to instantiate
|
| 770 |
+
:class:`FiberForceLengthPassiveInverseDeGroote2016` is using the
|
| 771 |
+
:meth:`~.with_defaults` constructor because this will automatically populate the
|
| 772 |
+
constants within the characteristic curve equation with the floating point
|
| 773 |
+
values from the original publication. This constructor takes a single
|
| 774 |
+
argument corresponding to the normalized passive muscle fiber length-force
|
| 775 |
+
component of the muscle fiber force. We'll create a :class:`~.Symbol` called
|
| 776 |
+
``fl_M_pas`` to represent this.
|
| 777 |
+
|
| 778 |
+
>>> from sympy import Symbol
|
| 779 |
+
>>> from sympy.physics.biomechanics import FiberForceLengthPassiveInverseDeGroote2016
|
| 780 |
+
>>> fl_M_pas = Symbol('fl_M_pas')
|
| 781 |
+
>>> l_M_tilde = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(fl_M_pas)
|
| 782 |
+
>>> l_M_tilde
|
| 783 |
+
FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, 0.6, 4.0)
|
| 784 |
+
|
| 785 |
+
It's also possible to populate the two constants with your own values too.
|
| 786 |
+
|
| 787 |
+
>>> from sympy import symbols
|
| 788 |
+
>>> c0, c1 = symbols('c0 c1')
|
| 789 |
+
>>> l_M_tilde = FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, c0, c1)
|
| 790 |
+
>>> l_M_tilde
|
| 791 |
+
FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, c0, c1)
|
| 792 |
+
|
| 793 |
+
To inspect the actual symbolic expression that this function represents,
|
| 794 |
+
we can call the :meth:`~.doit` method on an instance. We'll use the keyword
|
| 795 |
+
argument ``evaluate=False`` as this will keep the expression in its
|
| 796 |
+
canonical form and won't simplify any constants.
|
| 797 |
+
|
| 798 |
+
>>> l_M_tilde.doit(evaluate=False)
|
| 799 |
+
c0*log(1 + fl_M_pas*(exp(c1) - 1))/c1 + 1
|
| 800 |
+
|
| 801 |
+
The function can also be differentiated. We'll differentiate with respect
|
| 802 |
+
to fl_M_pas using the ``diff`` method on an instance with the single positional
|
| 803 |
+
argument ``fl_M_pas``.
|
| 804 |
+
|
| 805 |
+
>>> l_M_tilde.diff(fl_M_pas)
|
| 806 |
+
c0*(exp(c1) - 1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
|
| 807 |
+
|
| 808 |
+
References
|
| 809 |
+
==========
|
| 810 |
+
|
| 811 |
+
.. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
|
| 812 |
+
of direct collocation optimal control problem formulations for
|
| 813 |
+
solving the muscle redundancy problem, Annals of biomedical
|
| 814 |
+
engineering, 44(10), (2016) pp. 2922-2936
|
| 815 |
+
|
| 816 |
+
"""
|
| 817 |
+
|
| 818 |
+
@classmethod
|
| 819 |
+
def with_defaults(cls, fl_M_pas):
|
| 820 |
+
r"""Recommended constructor that will use the published constants.
|
| 821 |
+
|
| 822 |
+
Explanation
|
| 823 |
+
===========
|
| 824 |
+
|
| 825 |
+
Returns a new instance of the inverse muscle fiber passive force-length
|
| 826 |
+
function using the four constant values specified in the original
|
| 827 |
+
publication.
|
| 828 |
+
|
| 829 |
+
These have the values:
|
| 830 |
+
|
| 831 |
+
$c_0 = 0.6$
|
| 832 |
+
$c_1 = 4.0$
|
| 833 |
+
|
| 834 |
+
Parameters
|
| 835 |
+
==========
|
| 836 |
+
|
| 837 |
+
fl_M_pas : Any (sympifiable)
|
| 838 |
+
Normalized passive muscle fiber force as a function of muscle fiber
|
| 839 |
+
length.
|
| 840 |
+
|
| 841 |
+
"""
|
| 842 |
+
c0 = Float('0.6')
|
| 843 |
+
c1 = Float('4.0')
|
| 844 |
+
return cls(fl_M_pas, c0, c1)
|
| 845 |
+
|
| 846 |
+
@classmethod
|
| 847 |
+
def eval(cls, fl_M_pas, c0, c1):
|
| 848 |
+
"""Evaluation of basic inputs.
|
| 849 |
+
|
| 850 |
+
Parameters
|
| 851 |
+
==========
|
| 852 |
+
|
| 853 |
+
fl_M_pas : Any (sympifiable)
|
| 854 |
+
Normalized passive muscle fiber force.
|
| 855 |
+
c0 : Any (sympifiable)
|
| 856 |
+
The first constant in the characteristic equation. The published
|
| 857 |
+
value is ``0.6``.
|
| 858 |
+
c1 : Any (sympifiable)
|
| 859 |
+
The second constant in the characteristic equation. The published
|
| 860 |
+
value is ``4.0``.
|
| 861 |
+
|
| 862 |
+
"""
|
| 863 |
+
pass
|
| 864 |
+
|
| 865 |
+
def _eval_evalf(self, prec):
|
| 866 |
+
"""Evaluate the expression numerically using ``evalf``."""
|
| 867 |
+
return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
|
| 868 |
+
|
| 869 |
+
def doit(self, deep=True, evaluate=True, **hints):
|
| 870 |
+
"""Evaluate the expression defining the function.
|
| 871 |
+
|
| 872 |
+
Parameters
|
| 873 |
+
==========
|
| 874 |
+
|
| 875 |
+
deep : bool
|
| 876 |
+
Whether ``doit`` should be recursively called. Default is ``True``.
|
| 877 |
+
evaluate : bool.
|
| 878 |
+
Whether the SymPy expression should be evaluated as it is
|
| 879 |
+
constructed. If ``False``, then no constant folding will be
|
| 880 |
+
conducted which will leave the expression in a more numerically-
|
| 881 |
+
stable for values of ``l_T_tilde`` that correspond to a sensible
|
| 882 |
+
operating range for a musculotendon. Default is ``True``.
|
| 883 |
+
**kwargs : dict[str, Any]
|
| 884 |
+
Additional keyword argument pairs to be recursively passed to
|
| 885 |
+
``doit``.
|
| 886 |
+
|
| 887 |
+
"""
|
| 888 |
+
fl_M_pas, *constants = self.args
|
| 889 |
+
if deep:
|
| 890 |
+
hints['evaluate'] = evaluate
|
| 891 |
+
fl_M_pas = fl_M_pas.doit(deep=deep, **hints)
|
| 892 |
+
c0, c1 = [c.doit(deep=deep, **hints) for c in constants]
|
| 893 |
+
else:
|
| 894 |
+
c0, c1 = constants
|
| 895 |
+
|
| 896 |
+
if evaluate:
|
| 897 |
+
return c0*log(fl_M_pas*(exp(c1) - 1) + 1)/c1 + 1
|
| 898 |
+
|
| 899 |
+
return c0*log(UnevaluatedExpr(fl_M_pas*(exp(c1) - 1)) + 1)/c1 + 1
|
| 900 |
+
|
| 901 |
+
def fdiff(self, argindex=1):
|
| 902 |
+
"""Derivative of the function with respect to a single argument.
|
| 903 |
+
|
| 904 |
+
Parameters
|
| 905 |
+
==========
|
| 906 |
+
|
| 907 |
+
argindex : int
|
| 908 |
+
The index of the function's arguments with respect to which the
|
| 909 |
+
derivative should be taken. Argument indexes start at ``1``.
|
| 910 |
+
Default is ``1``.
|
| 911 |
+
|
| 912 |
+
"""
|
| 913 |
+
fl_M_pas, c0, c1 = self.args
|
| 914 |
+
if argindex == 1:
|
| 915 |
+
return c0*(exp(c1) - 1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
|
| 916 |
+
elif argindex == 2:
|
| 917 |
+
return log(fl_M_pas*(exp(c1) - 1) + 1)/c1
|
| 918 |
+
elif argindex == 3:
|
| 919 |
+
return (
|
| 920 |
+
c0*fl_M_pas*exp(c1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
|
| 921 |
+
- c0*log(fl_M_pas*(exp(c1) - 1) + 1)/c1**2
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
raise ArgumentIndexError(self, argindex)
|
| 925 |
+
|
| 926 |
+
def inverse(self, argindex=1):
|
| 927 |
+
"""Inverse function.
|
| 928 |
+
|
| 929 |
+
Parameters
|
| 930 |
+
==========
|
| 931 |
+
|
| 932 |
+
argindex : int
|
| 933 |
+
Value to start indexing the arguments at. Default is ``1``.
|
| 934 |
+
|
| 935 |
+
"""
|
| 936 |
+
return FiberForceLengthPassiveDeGroote2016
|
| 937 |
+
|
| 938 |
+
def _latex(self, printer):
|
| 939 |
+
"""Print a LaTeX representation of the function defining the curve.
|
| 940 |
+
|
| 941 |
+
Parameters
|
| 942 |
+
==========
|
| 943 |
+
|
| 944 |
+
printer : Printer
|
| 945 |
+
The printer to be used to print the LaTeX string representation.
|
| 946 |
+
|
| 947 |
+
"""
|
| 948 |
+
fl_M_pas = self.args[0]
|
| 949 |
+
_fl_M_pas = printer._print(fl_M_pas)
|
| 950 |
+
return r'\left( \operatorname{fl}^M_{pas} \right)^{-1} \left( %s \right)' % _fl_M_pas
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
class FiberForceLengthActiveDeGroote2016(CharacteristicCurveFunction):
|
| 954 |
+
r"""Active muscle fiber force-length curve based on De Groote et al., 2016
|
| 955 |
+
[1]_.
|
| 956 |
+
|
| 957 |
+
Explanation
|
| 958 |
+
===========
|
| 959 |
+
|
| 960 |
+
The function is defined by the equation:
|
| 961 |
+
|
| 962 |
+
$fl_{\text{act}}^M = c_0 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_1}{c_2 + c_3 \tilde{l}^M}\right)^2\right)
|
| 963 |
+
+ c_4 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_5}{c_6 + c_7 \tilde{l}^M}\right)^2\right)
|
| 964 |
+
+ c_8 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_9}{c_{10} + c_{11} \tilde{l}^M}\right)^2\right)$
|
| 965 |
+
|
| 966 |
+
with constant values of $c0 = 0.814$, $c1 = 1.06$, $c2 = 0.162$,
|
| 967 |
+
$c3 = 0.0633$, $c4 = 0.433$, $c5 = 0.717$, $c6 = -0.0299$, $c7 = 0.2$,
|
| 968 |
+
$c8 = 0.1$, $c9 = 1.0$, $c10 = 0.354$, and $c11 = 0.0$.
|
| 969 |
+
|
| 970 |
+
While it is possible to change the constant values, these were carefully
|
| 971 |
+
selected in the original publication to give the characteristic curve
|
| 972 |
+
specific and required properties. For example, the function produces a
|
| 973 |
+
active fiber force of 1 at a normalized fiber length of 1, and an active
|
| 974 |
+
fiber force of 0 at normalized fiber lengths of 0 and 2.
|
| 975 |
+
|
| 976 |
+
Examples
|
| 977 |
+
========
|
| 978 |
+
|
| 979 |
+
The preferred way to instantiate :class:`FiberForceLengthActiveDeGroote2016` is
|
| 980 |
+
using the :meth:`~.with_defaults` constructor because this will automatically
|
| 981 |
+
populate the constants within the characteristic curve equation with the
|
| 982 |
+
floating point values from the original publication. This constructor takes
|
| 983 |
+
a single argument corresponding to normalized muscle fiber length. We'll
|
| 984 |
+
create a :class:`~.Symbol` called ``l_M_tilde`` to represent this.
|
| 985 |
+
|
| 986 |
+
>>> from sympy import Symbol
|
| 987 |
+
>>> from sympy.physics.biomechanics import FiberForceLengthActiveDeGroote2016
|
| 988 |
+
>>> l_M_tilde = Symbol('l_M_tilde')
|
| 989 |
+
>>> fl_M = FiberForceLengthActiveDeGroote2016.with_defaults(l_M_tilde)
|
| 990 |
+
>>> fl_M
|
| 991 |
+
FiberForceLengthActiveDeGroote2016(l_M_tilde, 0.814, 1.06, 0.162, 0.0633,
|
| 992 |
+
0.433, 0.717, -0.0299, 0.2, 0.1, 1.0, 0.354, 0.0)
|
| 993 |
+
|
| 994 |
+
It's also possible to populate the two constants with your own values too.
|
| 995 |
+
|
| 996 |
+
>>> from sympy import symbols
|
| 997 |
+
>>> c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = symbols('c0:12')
|
| 998 |
+
>>> fl_M = FiberForceLengthActiveDeGroote2016(l_M_tilde, c0, c1, c2, c3,
|
| 999 |
+
... c4, c5, c6, c7, c8, c9, c10, c11)
|
| 1000 |
+
>>> fl_M
|
| 1001 |
+
FiberForceLengthActiveDeGroote2016(l_M_tilde, c0, c1, c2, c3, c4, c5, c6,
|
| 1002 |
+
c7, c8, c9, c10, c11)
|
| 1003 |
+
|
| 1004 |
+
You don't just have to use symbols as the arguments, it's also possible to
|
| 1005 |
+
use expressions. Let's create a new pair of symbols, ``l_M`` and
|
| 1006 |
+
``l_M_opt``, representing muscle fiber length and optimal muscle fiber
|
| 1007 |
+
length respectively. We can then represent ``l_M_tilde`` as an expression,
|
| 1008 |
+
the ratio of these.
|
| 1009 |
+
|
| 1010 |
+
>>> l_M, l_M_opt = symbols('l_M l_M_opt')
|
| 1011 |
+
>>> l_M_tilde = l_M/l_M_opt
|
| 1012 |
+
>>> fl_M = FiberForceLengthActiveDeGroote2016.with_defaults(l_M_tilde)
|
| 1013 |
+
>>> fl_M
|
| 1014 |
+
FiberForceLengthActiveDeGroote2016(l_M/l_M_opt, 0.814, 1.06, 0.162, 0.0633,
|
| 1015 |
+
0.433, 0.717, -0.0299, 0.2, 0.1, 1.0, 0.354, 0.0)
|
| 1016 |
+
|
| 1017 |
+
To inspect the actual symbolic expression that this function represents,
|
| 1018 |
+
we can call the :meth:`~.doit` method on an instance. We'll use the keyword
|
| 1019 |
+
argument ``evaluate=False`` as this will keep the expression in its
|
| 1020 |
+
canonical form and won't simplify any constants.
|
| 1021 |
+
|
| 1022 |
+
>>> fl_M.doit(evaluate=False)
|
| 1023 |
+
0.814*exp(-19.0519737844841*(l_M/l_M_opt
|
| 1024 |
+
- 1.06)**2/(0.390740740740741*l_M/l_M_opt + 1)**2)
|
| 1025 |
+
+ 0.433*exp(-12.5*(l_M/l_M_opt - 0.717)**2/(l_M/l_M_opt - 0.1495)**2)
|
| 1026 |
+
+ 0.1*exp(-3.98991349867535*(l_M/l_M_opt - 1.0)**2)
|
| 1027 |
+
|
| 1028 |
+
The function can also be differentiated. We'll differentiate with respect
|
| 1029 |
+
to l_M using the ``diff`` method on an instance with the single positional
|
| 1030 |
+
argument ``l_M``.
|
| 1031 |
+
|
| 1032 |
+
>>> fl_M.diff(l_M)
|
| 1033 |
+
((-0.79798269973507*l_M/l_M_opt
|
| 1034 |
+
+ 0.79798269973507)*exp(-3.98991349867535*(l_M/l_M_opt - 1.0)**2)
|
| 1035 |
+
+ (10.825*(-l_M/l_M_opt + 0.717)/(l_M/l_M_opt - 0.1495)**2
|
| 1036 |
+
+ 10.825*(l_M/l_M_opt - 0.717)**2/(l_M/l_M_opt
|
| 1037 |
+
- 0.1495)**3)*exp(-12.5*(l_M/l_M_opt - 0.717)**2/(l_M/l_M_opt - 0.1495)**2)
|
| 1038 |
+
+ (31.0166133211401*(-l_M/l_M_opt + 1.06)/(0.390740740740741*l_M/l_M_opt
|
| 1039 |
+
+ 1)**2 + 13.6174190361677*(0.943396226415094*l_M/l_M_opt
|
| 1040 |
+
- 1)**2/(0.390740740740741*l_M/l_M_opt
|
| 1041 |
+
+ 1)**3)*exp(-21.4067977442463*(0.943396226415094*l_M/l_M_opt
|
| 1042 |
+
- 1)**2/(0.390740740740741*l_M/l_M_opt + 1)**2))/l_M_opt
|
| 1043 |
+
|
| 1044 |
+
References
|
| 1045 |
+
==========
|
| 1046 |
+
|
| 1047 |
+
.. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
|
| 1048 |
+
of direct collocation optimal control problem formulations for
|
| 1049 |
+
solving the muscle redundancy problem, Annals of biomedical
|
| 1050 |
+
engineering, 44(10), (2016) pp. 2922-2936
|
| 1051 |
+
|
| 1052 |
+
"""
|
| 1053 |
+
|
| 1054 |
+
@classmethod
|
| 1055 |
+
def with_defaults(cls, l_M_tilde):
|
| 1056 |
+
r"""Recommended constructor that will use the published constants.
|
| 1057 |
+
|
| 1058 |
+
Explanation
|
| 1059 |
+
===========
|
| 1060 |
+
|
| 1061 |
+
Returns a new instance of the inverse muscle fiber act force-length
|
| 1062 |
+
function using the four constant values specified in the original
|
| 1063 |
+
publication.
|
| 1064 |
+
|
| 1065 |
+
These have the values:
|
| 1066 |
+
|
| 1067 |
+
$c0 = 0.814$
|
| 1068 |
+
$c1 = 1.06$
|
| 1069 |
+
$c2 = 0.162$
|
| 1070 |
+
$c3 = 0.0633$
|
| 1071 |
+
$c4 = 0.433$
|
| 1072 |
+
$c5 = 0.717$
|
| 1073 |
+
$c6 = -0.0299$
|
| 1074 |
+
$c7 = 0.2$
|
| 1075 |
+
$c8 = 0.1$
|
| 1076 |
+
$c9 = 1.0$
|
| 1077 |
+
$c10 = 0.354$
|
| 1078 |
+
$c11 = 0.0$
|
| 1079 |
+
|
| 1080 |
+
Parameters
|
| 1081 |
+
==========
|
| 1082 |
+
|
| 1083 |
+
fl_M_act : Any (sympifiable)
|
| 1084 |
+
Normalized passive muscle fiber force as a function of muscle fiber
|
| 1085 |
+
length.
|
| 1086 |
+
|
| 1087 |
+
"""
|
| 1088 |
+
c0 = Float('0.814')
|
| 1089 |
+
c1 = Float('1.06')
|
| 1090 |
+
c2 = Float('0.162')
|
| 1091 |
+
c3 = Float('0.0633')
|
| 1092 |
+
c4 = Float('0.433')
|
| 1093 |
+
c5 = Float('0.717')
|
| 1094 |
+
c6 = Float('-0.0299')
|
| 1095 |
+
c7 = Float('0.2')
|
| 1096 |
+
c8 = Float('0.1')
|
| 1097 |
+
c9 = Float('1.0')
|
| 1098 |
+
c10 = Float('0.354')
|
| 1099 |
+
c11 = Float('0.0')
|
| 1100 |
+
return cls(l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11)
|
| 1101 |
+
|
| 1102 |
+
@classmethod
|
| 1103 |
+
def eval(cls, l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11):
|
| 1104 |
+
"""Evaluation of basic inputs.
|
| 1105 |
+
|
| 1106 |
+
Parameters
|
| 1107 |
+
==========
|
| 1108 |
+
|
| 1109 |
+
l_M_tilde : Any (sympifiable)
|
| 1110 |
+
Normalized muscle fiber length.
|
| 1111 |
+
c0 : Any (sympifiable)
|
| 1112 |
+
The first constant in the characteristic equation. The published
|
| 1113 |
+
value is ``0.814``.
|
| 1114 |
+
c1 : Any (sympifiable)
|
| 1115 |
+
The second constant in the characteristic equation. The published
|
| 1116 |
+
value is ``1.06``.
|
| 1117 |
+
c2 : Any (sympifiable)
|
| 1118 |
+
The third constant in the characteristic equation. The published
|
| 1119 |
+
value is ``0.162``.
|
| 1120 |
+
c3 : Any (sympifiable)
|
| 1121 |
+
The fourth constant in the characteristic equation. The published
|
| 1122 |
+
value is ``0.0633``.
|
| 1123 |
+
c4 : Any (sympifiable)
|
| 1124 |
+
The fifth constant in the characteristic equation. The published
|
| 1125 |
+
value is ``0.433``.
|
| 1126 |
+
c5 : Any (sympifiable)
|
| 1127 |
+
The sixth constant in the characteristic equation. The published
|
| 1128 |
+
value is ``0.717``.
|
| 1129 |
+
c6 : Any (sympifiable)
|
| 1130 |
+
The seventh constant in the characteristic equation. The published
|
| 1131 |
+
value is ``-0.0299``.
|
| 1132 |
+
c7 : Any (sympifiable)
|
| 1133 |
+
The eighth constant in the characteristic equation. The published
|
| 1134 |
+
value is ``0.2``.
|
| 1135 |
+
c8 : Any (sympifiable)
|
| 1136 |
+
The ninth constant in the characteristic equation. The published
|
| 1137 |
+
value is ``0.1``.
|
| 1138 |
+
c9 : Any (sympifiable)
|
| 1139 |
+
The tenth constant in the characteristic equation. The published
|
| 1140 |
+
value is ``1.0``.
|
| 1141 |
+
c10 : Any (sympifiable)
|
| 1142 |
+
The eleventh constant in the characteristic equation. The published
|
| 1143 |
+
value is ``0.354``.
|
| 1144 |
+
c11 : Any (sympifiable)
|
| 1145 |
+
The tweflth constant in the characteristic equation. The published
|
| 1146 |
+
value is ``0.0``.
|
| 1147 |
+
|
| 1148 |
+
"""
|
| 1149 |
+
pass
|
| 1150 |
+
|
| 1151 |
+
def _eval_evalf(self, prec):
|
| 1152 |
+
"""Evaluate the expression numerically using ``evalf``."""
|
| 1153 |
+
return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
|
| 1154 |
+
|
| 1155 |
+
def doit(self, deep=True, evaluate=True, **hints):
|
| 1156 |
+
"""Evaluate the expression defining the function.
|
| 1157 |
+
|
| 1158 |
+
Parameters
|
| 1159 |
+
==========
|
| 1160 |
+
|
| 1161 |
+
deep : bool
|
| 1162 |
+
Whether ``doit`` should be recursively called. Default is ``True``.
|
| 1163 |
+
evaluate : bool.
|
| 1164 |
+
Whether the SymPy expression should be evaluated as it is
|
| 1165 |
+
constructed. If ``False``, then no constant folding will be
|
| 1166 |
+
conducted which will leave the expression in a more numerically-
|
| 1167 |
+
stable for values of ``l_M_tilde`` that correspond to a sensible
|
| 1168 |
+
operating range for a musculotendon. Default is ``True``.
|
| 1169 |
+
**kwargs : dict[str, Any]
|
| 1170 |
+
Additional keyword argument pairs to be recursively passed to
|
| 1171 |
+
``doit``.
|
| 1172 |
+
|
| 1173 |
+
"""
|
| 1174 |
+
l_M_tilde, *constants = self.args
|
| 1175 |
+
if deep:
|
| 1176 |
+
hints['evaluate'] = evaluate
|
| 1177 |
+
l_M_tilde = l_M_tilde.doit(deep=deep, **hints)
|
| 1178 |
+
constants = [c.doit(deep=deep, **hints) for c in constants]
|
| 1179 |
+
c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = constants
|
| 1180 |
+
|
| 1181 |
+
if evaluate:
|
| 1182 |
+
return (
|
| 1183 |
+
c0*exp(-(((l_M_tilde - c1)/(c2 + c3*l_M_tilde))**2)/2)
|
| 1184 |
+
+ c4*exp(-(((l_M_tilde - c5)/(c6 + c7*l_M_tilde))**2)/2)
|
| 1185 |
+
+ c8*exp(-(((l_M_tilde - c9)/(c10 + c11*l_M_tilde))**2)/2)
|
| 1186 |
+
)
|
| 1187 |
+
|
| 1188 |
+
return (
|
| 1189 |
+
c0*exp(-((UnevaluatedExpr(l_M_tilde - c1)/(c2 + c3*l_M_tilde))**2)/2)
|
| 1190 |
+
+ c4*exp(-((UnevaluatedExpr(l_M_tilde - c5)/(c6 + c7*l_M_tilde))**2)/2)
|
| 1191 |
+
+ c8*exp(-((UnevaluatedExpr(l_M_tilde - c9)/(c10 + c11*l_M_tilde))**2)/2)
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
def fdiff(self, argindex=1):
|
| 1195 |
+
"""Derivative of the function with respect to a single argument.
|
| 1196 |
+
|
| 1197 |
+
Parameters
|
| 1198 |
+
==========
|
| 1199 |
+
|
| 1200 |
+
argindex : int
|
| 1201 |
+
The index of the function's arguments with respect to which the
|
| 1202 |
+
derivative should be taken. Argument indexes start at ``1``.
|
| 1203 |
+
Default is ``1``.
|
| 1204 |
+
|
| 1205 |
+
"""
|
| 1206 |
+
l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = self.args
|
| 1207 |
+
if argindex == 1:
|
| 1208 |
+
return (
|
| 1209 |
+
c0*(
|
| 1210 |
+
c3*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
|
| 1211 |
+
+ (c1 - l_M_tilde)/((c2 + c3*l_M_tilde)**2)
|
| 1212 |
+
)*exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
|
| 1213 |
+
+ c4*(
|
| 1214 |
+
c7*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
|
| 1215 |
+
+ (c5 - l_M_tilde)/((c6 + c7*l_M_tilde)**2)
|
| 1216 |
+
)*exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
|
| 1217 |
+
+ c8*(
|
| 1218 |
+
c11*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
|
| 1219 |
+
+ (c9 - l_M_tilde)/((c10 + c11*l_M_tilde)**2)
|
| 1220 |
+
)*exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
|
| 1221 |
+
)
|
| 1222 |
+
elif argindex == 2:
|
| 1223 |
+
return exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
|
| 1224 |
+
elif argindex == 3:
|
| 1225 |
+
return (
|
| 1226 |
+
c0*(l_M_tilde - c1)/(c2 + c3*l_M_tilde)**2
|
| 1227 |
+
*exp(-(l_M_tilde - c1)**2 /(2*(c2 + c3*l_M_tilde)**2))
|
| 1228 |
+
)
|
| 1229 |
+
elif argindex == 4:
|
| 1230 |
+
return (
|
| 1231 |
+
c0*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
|
| 1232 |
+
*exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
|
| 1233 |
+
)
|
| 1234 |
+
elif argindex == 5:
|
| 1235 |
+
return (
|
| 1236 |
+
c0*l_M_tilde*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
|
| 1237 |
+
*exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
|
| 1238 |
+
)
|
| 1239 |
+
elif argindex == 6:
|
| 1240 |
+
return exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
|
| 1241 |
+
elif argindex == 7:
|
| 1242 |
+
return (
|
| 1243 |
+
c4*(l_M_tilde - c5)/(c6 + c7*l_M_tilde)**2
|
| 1244 |
+
*exp(-(l_M_tilde - c5)**2 /(2*(c6 + c7*l_M_tilde)**2))
|
| 1245 |
+
)
|
| 1246 |
+
elif argindex == 8:
|
| 1247 |
+
return (
|
| 1248 |
+
c4*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
|
| 1249 |
+
*exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
|
| 1250 |
+
)
|
| 1251 |
+
elif argindex == 9:
|
| 1252 |
+
return (
|
| 1253 |
+
c4*l_M_tilde*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
|
| 1254 |
+
*exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
|
| 1255 |
+
)
|
| 1256 |
+
elif argindex == 10:
|
| 1257 |
+
return exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
|
| 1258 |
+
elif argindex == 11:
|
| 1259 |
+
return (
|
| 1260 |
+
c8*(l_M_tilde - c9)/(c10 + c11*l_M_tilde)**2
|
| 1261 |
+
*exp(-(l_M_tilde - c9)**2 /(2*(c10 + c11*l_M_tilde)**2))
|
| 1262 |
+
)
|
| 1263 |
+
elif argindex == 12:
|
| 1264 |
+
return (
|
| 1265 |
+
c8*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
|
| 1266 |
+
*exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
|
| 1267 |
+
)
|
| 1268 |
+
elif argindex == 13:
|
| 1269 |
+
return (
|
| 1270 |
+
c8*l_M_tilde*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
|
| 1271 |
+
*exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
|
| 1272 |
+
)
|
| 1273 |
+
|
| 1274 |
+
raise ArgumentIndexError(self, argindex)
|
| 1275 |
+
|
| 1276 |
+
def _latex(self, printer):
|
| 1277 |
+
"""Print a LaTeX representation of the function defining the curve.
|
| 1278 |
+
|
| 1279 |
+
Parameters
|
| 1280 |
+
==========
|
| 1281 |
+
|
| 1282 |
+
printer : Printer
|
| 1283 |
+
The printer to be used to print the LaTeX string representation.
|
| 1284 |
+
|
| 1285 |
+
"""
|
| 1286 |
+
l_M_tilde = self.args[0]
|
| 1287 |
+
_l_M_tilde = printer._print(l_M_tilde)
|
| 1288 |
+
return r'\operatorname{fl}^M_{act} \left( %s \right)' % _l_M_tilde
|
| 1289 |
+
|
| 1290 |
+
|
| 1291 |
+
class FiberForceVelocityDeGroote2016(CharacteristicCurveFunction):
|
| 1292 |
+
r"""Muscle fiber force-velocity curve based on De Groote et al., 2016 [1]_.
|
| 1293 |
+
|
| 1294 |
+
Explanation
|
| 1295 |
+
===========
|
| 1296 |
+
|
| 1297 |
+
Gives the normalized muscle fiber force produced as a function of
|
| 1298 |
+
normalized tendon velocity.
|
| 1299 |
+
|
| 1300 |
+
The function is defined by the equation:
|
| 1301 |
+
|
| 1302 |
+
$fv^M = c_0 \log{\left(c_1 \tilde{v}_m + c_2\right) + \sqrt{\left(c_1 \tilde{v}_m + c_2\right)^2 + 1}} + c_3$
|
| 1303 |
+
|
| 1304 |
+
with constant values of $c_0 = -0.318$, $c_1 = -8.149$, $c_2 = -0.374$, and
|
| 1305 |
+
$c_3 = 0.886$.
|
| 1306 |
+
|
| 1307 |
+
While it is possible to change the constant values, these were carefully
|
| 1308 |
+
selected in the original publication to give the characteristic curve
|
| 1309 |
+
specific and required properties. For example, the function produces a
|
| 1310 |
+
normalized muscle fiber force of 1 when the muscle fibers are contracting
|
| 1311 |
+
isometrically (they have an extension rate of 0).
|
| 1312 |
+
|
| 1313 |
+
Examples
|
| 1314 |
+
========
|
| 1315 |
+
|
| 1316 |
+
The preferred way to instantiate :class:`FiberForceVelocityDeGroote2016` is using
|
| 1317 |
+
the :meth:`~.with_defaults` constructor because this will automatically populate
|
| 1318 |
+
the constants within the characteristic curve equation with the floating
|
| 1319 |
+
point values from the original publication. This constructor takes a single
|
| 1320 |
+
argument corresponding to normalized muscle fiber extension velocity. We'll
|
| 1321 |
+
create a :class:`~.Symbol` called ``v_M_tilde`` to represent this.
|
| 1322 |
+
|
| 1323 |
+
>>> from sympy import Symbol
|
| 1324 |
+
>>> from sympy.physics.biomechanics import FiberForceVelocityDeGroote2016
|
| 1325 |
+
>>> v_M_tilde = Symbol('v_M_tilde')
|
| 1326 |
+
>>> fv_M = FiberForceVelocityDeGroote2016.with_defaults(v_M_tilde)
|
| 1327 |
+
>>> fv_M
|
| 1328 |
+
FiberForceVelocityDeGroote2016(v_M_tilde, -0.318, -8.149, -0.374, 0.886)
|
| 1329 |
+
|
| 1330 |
+
It's also possible to populate the four constants with your own values too.
|
| 1331 |
+
|
| 1332 |
+
>>> from sympy import symbols
|
| 1333 |
+
>>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
|
| 1334 |
+
>>> fv_M = FiberForceVelocityDeGroote2016(v_M_tilde, c0, c1, c2, c3)
|
| 1335 |
+
>>> fv_M
|
| 1336 |
+
FiberForceVelocityDeGroote2016(v_M_tilde, c0, c1, c2, c3)
|
| 1337 |
+
|
| 1338 |
+
You don't just have to use symbols as the arguments, it's also possible to
|
| 1339 |
+
use expressions. Let's create a new pair of symbols, ``v_M`` and
|
| 1340 |
+
``v_M_max``, representing muscle fiber extension velocity and maximum
|
| 1341 |
+
muscle fiber extension velocity respectively. We can then represent
|
| 1342 |
+
``v_M_tilde`` as an expression, the ratio of these.
|
| 1343 |
+
|
| 1344 |
+
>>> v_M, v_M_max = symbols('v_M v_M_max')
|
| 1345 |
+
>>> v_M_tilde = v_M/v_M_max
|
| 1346 |
+
>>> fv_M = FiberForceVelocityDeGroote2016.with_defaults(v_M_tilde)
|
| 1347 |
+
>>> fv_M
|
| 1348 |
+
FiberForceVelocityDeGroote2016(v_M/v_M_max, -0.318, -8.149, -0.374, 0.886)
|
| 1349 |
+
|
| 1350 |
+
To inspect the actual symbolic expression that this function represents,
|
| 1351 |
+
we can call the :meth:`~.doit` method on an instance. We'll use the keyword
|
| 1352 |
+
argument ``evaluate=False`` as this will keep the expression in its
|
| 1353 |
+
canonical form and won't simplify any constants.
|
| 1354 |
+
|
| 1355 |
+
>>> fv_M.doit(evaluate=False)
|
| 1356 |
+
0.886 - 0.318*log(-8.149*v_M/v_M_max - 0.374 + sqrt(1 + (-8.149*v_M/v_M_max
|
| 1357 |
+
- 0.374)**2))
|
| 1358 |
+
|
| 1359 |
+
The function can also be differentiated. We'll differentiate with respect
|
| 1360 |
+
to v_M using the ``diff`` method on an instance with the single positional
|
| 1361 |
+
argument ``v_M``.
|
| 1362 |
+
|
| 1363 |
+
>>> fv_M.diff(v_M)
|
| 1364 |
+
2.591382*(1 + (-8.149*v_M/v_M_max - 0.374)**2)**(-1/2)/v_M_max
|
| 1365 |
+
|
| 1366 |
+
References
|
| 1367 |
+
==========
|
| 1368 |
+
|
| 1369 |
+
.. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
|
| 1370 |
+
of direct collocation optimal control problem formulations for
|
| 1371 |
+
solving the muscle redundancy problem, Annals of biomedical
|
| 1372 |
+
engineering, 44(10), (2016) pp. 2922-2936
|
| 1373 |
+
|
| 1374 |
+
"""
|
| 1375 |
+
|
| 1376 |
+
@classmethod
|
| 1377 |
+
def with_defaults(cls, v_M_tilde):
|
| 1378 |
+
r"""Recommended constructor that will use the published constants.
|
| 1379 |
+
|
| 1380 |
+
Explanation
|
| 1381 |
+
===========
|
| 1382 |
+
|
| 1383 |
+
Returns a new instance of the muscle fiber force-velocity function
|
| 1384 |
+
using the four constant values specified in the original publication.
|
| 1385 |
+
|
| 1386 |
+
These have the values:
|
| 1387 |
+
|
| 1388 |
+
$c_0 = -0.318$
|
| 1389 |
+
$c_1 = -8.149$
|
| 1390 |
+
$c_2 = -0.374$
|
| 1391 |
+
$c_3 = 0.886$
|
| 1392 |
+
|
| 1393 |
+
Parameters
|
| 1394 |
+
==========
|
| 1395 |
+
|
| 1396 |
+
v_M_tilde : Any (sympifiable)
|
| 1397 |
+
Normalized muscle fiber extension velocity.
|
| 1398 |
+
|
| 1399 |
+
"""
|
| 1400 |
+
c0 = Float('-0.318')
|
| 1401 |
+
c1 = Float('-8.149')
|
| 1402 |
+
c2 = Float('-0.374')
|
| 1403 |
+
c3 = Float('0.886')
|
| 1404 |
+
return cls(v_M_tilde, c0, c1, c2, c3)
|
| 1405 |
+
|
| 1406 |
+
@classmethod
|
| 1407 |
+
def eval(cls, v_M_tilde, c0, c1, c2, c3):
|
| 1408 |
+
"""Evaluation of basic inputs.
|
| 1409 |
+
|
| 1410 |
+
Parameters
|
| 1411 |
+
==========
|
| 1412 |
+
|
| 1413 |
+
v_M_tilde : Any (sympifiable)
|
| 1414 |
+
Normalized muscle fiber extension velocity.
|
| 1415 |
+
c0 : Any (sympifiable)
|
| 1416 |
+
The first constant in the characteristic equation. The published
|
| 1417 |
+
value is ``-0.318``.
|
| 1418 |
+
c1 : Any (sympifiable)
|
| 1419 |
+
The second constant in the characteristic equation. The published
|
| 1420 |
+
value is ``-8.149``.
|
| 1421 |
+
c2 : Any (sympifiable)
|
| 1422 |
+
The third constant in the characteristic equation. The published
|
| 1423 |
+
value is ``-0.374``.
|
| 1424 |
+
c3 : Any (sympifiable)
|
| 1425 |
+
The fourth constant in the characteristic equation. The published
|
| 1426 |
+
value is ``0.886``.
|
| 1427 |
+
|
| 1428 |
+
"""
|
| 1429 |
+
pass
|
| 1430 |
+
|
| 1431 |
+
def _eval_evalf(self, prec):
|
| 1432 |
+
"""Evaluate the expression numerically using ``evalf``."""
|
| 1433 |
+
return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
|
| 1434 |
+
|
| 1435 |
+
def doit(self, deep=True, evaluate=True, **hints):
|
| 1436 |
+
"""Evaluate the expression defining the function.
|
| 1437 |
+
|
| 1438 |
+
Parameters
|
| 1439 |
+
==========
|
| 1440 |
+
|
| 1441 |
+
deep : bool
|
| 1442 |
+
Whether ``doit`` should be recursively called. Default is ``True``.
|
| 1443 |
+
evaluate : bool.
|
| 1444 |
+
Whether the SymPy expression should be evaluated as it is
|
| 1445 |
+
constructed. If ``False``, then no constant folding will be
|
| 1446 |
+
conducted which will leave the expression in a more numerically-
|
| 1447 |
+
stable for values of ``v_M_tilde`` that correspond to a sensible
|
| 1448 |
+
operating range for a musculotendon. Default is ``True``.
|
| 1449 |
+
**kwargs : dict[str, Any]
|
| 1450 |
+
Additional keyword argument pairs to be recursively passed to
|
| 1451 |
+
``doit``.
|
| 1452 |
+
|
| 1453 |
+
"""
|
| 1454 |
+
v_M_tilde, *constants = self.args
|
| 1455 |
+
if deep:
|
| 1456 |
+
hints['evaluate'] = evaluate
|
| 1457 |
+
v_M_tilde = v_M_tilde.doit(deep=deep, **hints)
|
| 1458 |
+
c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
|
| 1459 |
+
else:
|
| 1460 |
+
c0, c1, c2, c3 = constants
|
| 1461 |
+
|
| 1462 |
+
if evaluate:
|
| 1463 |
+
return c0*log(c1*v_M_tilde + c2 + sqrt((c1*v_M_tilde + c2)**2 + 1)) + c3
|
| 1464 |
+
|
| 1465 |
+
return c0*log(c1*v_M_tilde + c2 + sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)) + c3
|
| 1466 |
+
|
| 1467 |
+
def fdiff(self, argindex=1):
|
| 1468 |
+
"""Derivative of the function with respect to a single argument.
|
| 1469 |
+
|
| 1470 |
+
Parameters
|
| 1471 |
+
==========
|
| 1472 |
+
|
| 1473 |
+
argindex : int
|
| 1474 |
+
The index of the function's arguments with respect to which the
|
| 1475 |
+
derivative should be taken. Argument indexes start at ``1``.
|
| 1476 |
+
Default is ``1``.
|
| 1477 |
+
|
| 1478 |
+
"""
|
| 1479 |
+
v_M_tilde, c0, c1, c2, c3 = self.args
|
| 1480 |
+
if argindex == 1:
|
| 1481 |
+
return c0*c1/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
|
| 1482 |
+
elif argindex == 2:
|
| 1483 |
+
return log(
|
| 1484 |
+
c1*v_M_tilde + c2
|
| 1485 |
+
+ sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
|
| 1486 |
+
)
|
| 1487 |
+
elif argindex == 3:
|
| 1488 |
+
return c0*v_M_tilde/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
|
| 1489 |
+
elif argindex == 4:
|
| 1490 |
+
return c0/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
|
| 1491 |
+
elif argindex == 5:
|
| 1492 |
+
return Integer(1)
|
| 1493 |
+
|
| 1494 |
+
raise ArgumentIndexError(self, argindex)
|
| 1495 |
+
|
| 1496 |
+
def inverse(self, argindex=1):
|
| 1497 |
+
"""Inverse function.
|
| 1498 |
+
|
| 1499 |
+
Parameters
|
| 1500 |
+
==========
|
| 1501 |
+
|
| 1502 |
+
argindex : int
|
| 1503 |
+
Value to start indexing the arguments at. Default is ``1``.
|
| 1504 |
+
|
| 1505 |
+
"""
|
| 1506 |
+
return FiberForceVelocityInverseDeGroote2016
|
| 1507 |
+
|
| 1508 |
+
def _latex(self, printer):
|
| 1509 |
+
"""Print a LaTeX representation of the function defining the curve.
|
| 1510 |
+
|
| 1511 |
+
Parameters
|
| 1512 |
+
==========
|
| 1513 |
+
|
| 1514 |
+
printer : Printer
|
| 1515 |
+
The printer to be used to print the LaTeX string representation.
|
| 1516 |
+
|
| 1517 |
+
"""
|
| 1518 |
+
v_M_tilde = self.args[0]
|
| 1519 |
+
_v_M_tilde = printer._print(v_M_tilde)
|
| 1520 |
+
return r'\operatorname{fv}^M \left( %s \right)' % _v_M_tilde
|
| 1521 |
+
|
| 1522 |
+
|
| 1523 |
+
class FiberForceVelocityInverseDeGroote2016(CharacteristicCurveFunction):
|
| 1524 |
+
r"""Inverse muscle fiber force-velocity curve based on De Groote et al.,
|
| 1525 |
+
2016 [1]_.
|
| 1526 |
+
|
| 1527 |
+
Explanation
|
| 1528 |
+
===========
|
| 1529 |
+
|
| 1530 |
+
Gives the normalized muscle fiber velocity that produces a specific
|
| 1531 |
+
normalized muscle fiber force.
|
| 1532 |
+
|
| 1533 |
+
The function is defined by the equation:
|
| 1534 |
+
|
| 1535 |
+
${fv^M}^{-1} = \frac{\sinh{\frac{fv^M - c_3}{c_0}} - c_2}{c_1}$
|
| 1536 |
+
|
| 1537 |
+
with constant values of $c_0 = -0.318$, $c_1 = -8.149$, $c_2 = -0.374$, and
|
| 1538 |
+
$c_3 = 0.886$. This function is the exact analytical inverse of the related
|
| 1539 |
+
muscle fiber force-velocity curve ``FiberForceVelocityDeGroote2016``.
|
| 1540 |
+
|
| 1541 |
+
While it is possible to change the constant values, these were carefully
|
| 1542 |
+
selected in the original publication to give the characteristic curve
|
| 1543 |
+
specific and required properties. For example, the function produces a
|
| 1544 |
+
normalized muscle fiber force of 1 when the muscle fibers are contracting
|
| 1545 |
+
isometrically (they have an extension rate of 0).
|
| 1546 |
+
|
| 1547 |
+
Examples
|
| 1548 |
+
========
|
| 1549 |
+
|
| 1550 |
+
The preferred way to instantiate :class:`FiberForceVelocityInverseDeGroote2016`
|
| 1551 |
+
is using the :meth:`~.with_defaults` constructor because this will automatically
|
| 1552 |
+
populate the constants within the characteristic curve equation with the
|
| 1553 |
+
floating point values from the original publication. This constructor takes
|
| 1554 |
+
a single argument corresponding to normalized muscle fiber force-velocity
|
| 1555 |
+
component of the muscle fiber force. We'll create a :class:`~.Symbol` called
|
| 1556 |
+
``fv_M`` to represent this.
|
| 1557 |
+
|
| 1558 |
+
>>> from sympy import Symbol
|
| 1559 |
+
>>> from sympy.physics.biomechanics import FiberForceVelocityInverseDeGroote2016
|
| 1560 |
+
>>> fv_M = Symbol('fv_M')
|
| 1561 |
+
>>> v_M_tilde = FiberForceVelocityInverseDeGroote2016.with_defaults(fv_M)
|
| 1562 |
+
>>> v_M_tilde
|
| 1563 |
+
FiberForceVelocityInverseDeGroote2016(fv_M, -0.318, -8.149, -0.374, 0.886)
|
| 1564 |
+
|
| 1565 |
+
It's also possible to populate the four constants with your own values too.
|
| 1566 |
+
|
| 1567 |
+
>>> from sympy import symbols
|
| 1568 |
+
>>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
|
| 1569 |
+
>>> v_M_tilde = FiberForceVelocityInverseDeGroote2016(fv_M, c0, c1, c2, c3)
|
| 1570 |
+
>>> v_M_tilde
|
| 1571 |
+
FiberForceVelocityInverseDeGroote2016(fv_M, c0, c1, c2, c3)
|
| 1572 |
+
|
| 1573 |
+
To inspect the actual symbolic expression that this function represents,
|
| 1574 |
+
we can call the :meth:`~.doit` method on an instance. We'll use the keyword
|
| 1575 |
+
argument ``evaluate=False`` as this will keep the expression in its
|
| 1576 |
+
canonical form and won't simplify any constants.
|
| 1577 |
+
|
| 1578 |
+
>>> v_M_tilde.doit(evaluate=False)
|
| 1579 |
+
(-c2 + sinh((-c3 + fv_M)/c0))/c1
|
| 1580 |
+
|
| 1581 |
+
The function can also be differentiated. We'll differentiate with respect
|
| 1582 |
+
to fv_M using the ``diff`` method on an instance with the single positional
|
| 1583 |
+
argument ``fv_M``.
|
| 1584 |
+
|
| 1585 |
+
>>> v_M_tilde.diff(fv_M)
|
| 1586 |
+
cosh((-c3 + fv_M)/c0)/(c0*c1)
|
| 1587 |
+
|
| 1588 |
+
References
|
| 1589 |
+
==========
|
| 1590 |
+
|
| 1591 |
+
.. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
|
| 1592 |
+
of direct collocation optimal control problem formulations for
|
| 1593 |
+
solving the muscle redundancy problem, Annals of biomedical
|
| 1594 |
+
engineering, 44(10), (2016) pp. 2922-2936
|
| 1595 |
+
|
| 1596 |
+
"""
|
| 1597 |
+
|
| 1598 |
+
@classmethod
|
| 1599 |
+
def with_defaults(cls, fv_M):
|
| 1600 |
+
r"""Recommended constructor that will use the published constants.
|
| 1601 |
+
|
| 1602 |
+
Explanation
|
| 1603 |
+
===========
|
| 1604 |
+
|
| 1605 |
+
Returns a new instance of the inverse muscle fiber force-velocity
|
| 1606 |
+
function using the four constant values specified in the original
|
| 1607 |
+
publication.
|
| 1608 |
+
|
| 1609 |
+
These have the values:
|
| 1610 |
+
|
| 1611 |
+
$c_0 = -0.318$
|
| 1612 |
+
$c_1 = -8.149$
|
| 1613 |
+
$c_2 = -0.374$
|
| 1614 |
+
$c_3 = 0.886$
|
| 1615 |
+
|
| 1616 |
+
Parameters
|
| 1617 |
+
==========
|
| 1618 |
+
|
| 1619 |
+
fv_M : Any (sympifiable)
|
| 1620 |
+
Normalized muscle fiber extension velocity.
|
| 1621 |
+
|
| 1622 |
+
"""
|
| 1623 |
+
c0 = Float('-0.318')
|
| 1624 |
+
c1 = Float('-8.149')
|
| 1625 |
+
c2 = Float('-0.374')
|
| 1626 |
+
c3 = Float('0.886')
|
| 1627 |
+
return cls(fv_M, c0, c1, c2, c3)
|
| 1628 |
+
|
| 1629 |
+
@classmethod
|
| 1630 |
+
def eval(cls, fv_M, c0, c1, c2, c3):
|
| 1631 |
+
"""Evaluation of basic inputs.
|
| 1632 |
+
|
| 1633 |
+
Parameters
|
| 1634 |
+
==========
|
| 1635 |
+
|
| 1636 |
+
fv_M : Any (sympifiable)
|
| 1637 |
+
Normalized muscle fiber force as a function of muscle fiber
|
| 1638 |
+
extension velocity.
|
| 1639 |
+
c0 : Any (sympifiable)
|
| 1640 |
+
The first constant in the characteristic equation. The published
|
| 1641 |
+
value is ``-0.318``.
|
| 1642 |
+
c1 : Any (sympifiable)
|
| 1643 |
+
The second constant in the characteristic equation. The published
|
| 1644 |
+
value is ``-8.149``.
|
| 1645 |
+
c2 : Any (sympifiable)
|
| 1646 |
+
The third constant in the characteristic equation. The published
|
| 1647 |
+
value is ``-0.374``.
|
| 1648 |
+
c3 : Any (sympifiable)
|
| 1649 |
+
The fourth constant in the characteristic equation. The published
|
| 1650 |
+
value is ``0.886``.
|
| 1651 |
+
|
| 1652 |
+
"""
|
| 1653 |
+
pass
|
| 1654 |
+
|
| 1655 |
+
def _eval_evalf(self, prec):
|
| 1656 |
+
"""Evaluate the expression numerically using ``evalf``."""
|
| 1657 |
+
return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
|
| 1658 |
+
|
| 1659 |
+
def doit(self, deep=True, evaluate=True, **hints):
|
| 1660 |
+
"""Evaluate the expression defining the function.
|
| 1661 |
+
|
| 1662 |
+
Parameters
|
| 1663 |
+
==========
|
| 1664 |
+
|
| 1665 |
+
deep : bool
|
| 1666 |
+
Whether ``doit`` should be recursively called. Default is ``True``.
|
| 1667 |
+
evaluate : bool.
|
| 1668 |
+
Whether the SymPy expression should be evaluated as it is
|
| 1669 |
+
constructed. If ``False``, then no constant folding will be
|
| 1670 |
+
conducted which will leave the expression in a more numerically-
|
| 1671 |
+
stable for values of ``fv_M`` that correspond to a sensible
|
| 1672 |
+
operating range for a musculotendon. Default is ``True``.
|
| 1673 |
+
**kwargs : dict[str, Any]
|
| 1674 |
+
Additional keyword argument pairs to be recursively passed to
|
| 1675 |
+
``doit``.
|
| 1676 |
+
|
| 1677 |
+
"""
|
| 1678 |
+
fv_M, *constants = self.args
|
| 1679 |
+
if deep:
|
| 1680 |
+
hints['evaluate'] = evaluate
|
| 1681 |
+
fv_M = fv_M.doit(deep=deep, **hints)
|
| 1682 |
+
c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
|
| 1683 |
+
else:
|
| 1684 |
+
c0, c1, c2, c3 = constants
|
| 1685 |
+
|
| 1686 |
+
if evaluate:
|
| 1687 |
+
return (sinh((fv_M - c3)/c0) - c2)/c1
|
| 1688 |
+
|
| 1689 |
+
return (sinh(UnevaluatedExpr(fv_M - c3)/c0) - c2)/c1
|
| 1690 |
+
|
| 1691 |
+
def fdiff(self, argindex=1):
|
| 1692 |
+
"""Derivative of the function with respect to a single argument.
|
| 1693 |
+
|
| 1694 |
+
Parameters
|
| 1695 |
+
==========
|
| 1696 |
+
|
| 1697 |
+
argindex : int
|
| 1698 |
+
The index of the function's arguments with respect to which the
|
| 1699 |
+
derivative should be taken. Argument indexes start at ``1``.
|
| 1700 |
+
Default is ``1``.
|
| 1701 |
+
|
| 1702 |
+
"""
|
| 1703 |
+
fv_M, c0, c1, c2, c3 = self.args
|
| 1704 |
+
if argindex == 1:
|
| 1705 |
+
return cosh((fv_M - c3)/c0)/(c0*c1)
|
| 1706 |
+
elif argindex == 2:
|
| 1707 |
+
return (c3 - fv_M)*cosh((fv_M - c3)/c0)/(c0**2*c1)
|
| 1708 |
+
elif argindex == 3:
|
| 1709 |
+
return (c2 - sinh((fv_M - c3)/c0))/c1**2
|
| 1710 |
+
elif argindex == 4:
|
| 1711 |
+
return -1/c1
|
| 1712 |
+
elif argindex == 5:
|
| 1713 |
+
return -cosh((fv_M - c3)/c0)/(c0*c1)
|
| 1714 |
+
|
| 1715 |
+
raise ArgumentIndexError(self, argindex)
|
| 1716 |
+
|
| 1717 |
+
def inverse(self, argindex=1):
|
| 1718 |
+
"""Inverse function.
|
| 1719 |
+
|
| 1720 |
+
Parameters
|
| 1721 |
+
==========
|
| 1722 |
+
|
| 1723 |
+
argindex : int
|
| 1724 |
+
Value to start indexing the arguments at. Default is ``1``.
|
| 1725 |
+
|
| 1726 |
+
"""
|
| 1727 |
+
return FiberForceVelocityDeGroote2016
|
| 1728 |
+
|
| 1729 |
+
def _latex(self, printer):
|
| 1730 |
+
"""Print a LaTeX representation of the function defining the curve.
|
| 1731 |
+
|
| 1732 |
+
Parameters
|
| 1733 |
+
==========
|
| 1734 |
+
|
| 1735 |
+
printer : Printer
|
| 1736 |
+
The printer to be used to print the LaTeX string representation.
|
| 1737 |
+
|
| 1738 |
+
"""
|
| 1739 |
+
fv_M = self.args[0]
|
| 1740 |
+
_fv_M = printer._print(fv_M)
|
| 1741 |
+
return r'\left( \operatorname{fv}^M \right)^{-1} \left( %s \right)' % _fv_M
|
| 1742 |
+
|
| 1743 |
+
|
| 1744 |
+
@dataclass(frozen=True)
|
| 1745 |
+
class CharacteristicCurveCollection:
|
| 1746 |
+
"""Simple data container to group together related characteristic curves."""
|
| 1747 |
+
tendon_force_length: CharacteristicCurveFunction
|
| 1748 |
+
tendon_force_length_inverse: CharacteristicCurveFunction
|
| 1749 |
+
fiber_force_length_passive: CharacteristicCurveFunction
|
| 1750 |
+
fiber_force_length_passive_inverse: CharacteristicCurveFunction
|
| 1751 |
+
fiber_force_length_active: CharacteristicCurveFunction
|
| 1752 |
+
fiber_force_velocity: CharacteristicCurveFunction
|
| 1753 |
+
fiber_force_velocity_inverse: CharacteristicCurveFunction
|
| 1754 |
+
|
| 1755 |
+
def __iter__(self):
|
| 1756 |
+
"""Iterator support for ``CharacteristicCurveCollection``."""
|
| 1757 |
+
yield self.tendon_force_length
|
| 1758 |
+
yield self.tendon_force_length_inverse
|
| 1759 |
+
yield self.fiber_force_length_passive
|
| 1760 |
+
yield self.fiber_force_length_passive_inverse
|
| 1761 |
+
yield self.fiber_force_length_active
|
| 1762 |
+
yield self.fiber_force_velocity
|
| 1763 |
+
yield self.fiber_force_velocity_inverse
|
wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__init__.py
ADDED
|
File without changes
|
wemm/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_activation.cpython-310.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (322 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/cable.cpython-310.pyc
ADDED
|
Binary file (16.6 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/truss.cpython-310.pyc
ADDED
|
Binary file (31.5 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc
ADDED
|
Binary file (21.6 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_cable.cpython-310.pyc
ADDED
|
Binary file (2.53 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-310.pyc
ADDED
|
Binary file (2.59 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/control/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .lti import (TransferFunction, Series, MIMOSeries, Parallel, MIMOParallel,
|
| 2 |
+
Feedback, MIMOFeedback, TransferFunctionMatrix, StateSpace, gbt, bilinear, forward_diff,
|
| 3 |
+
backward_diff, phase_margin, gain_margin)
|
| 4 |
+
from .control_plots import (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
|
| 5 |
+
step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data,
|
| 6 |
+
ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_magnitude_plot,
|
| 7 |
+
bode_phase_plot, bode_plot)
|
| 8 |
+
|
| 9 |
+
__all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel',
|
| 10 |
+
'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix', 'StateSpace',
|
| 11 |
+
'gbt', 'bilinear', 'forward_diff', 'backward_diff', 'phase_margin', 'gain_margin',
|
| 12 |
+
'pole_zero_numerical_data', 'pole_zero_plot', 'step_response_numerical_data',
|
| 13 |
+
'step_response_plot', 'impulse_response_numerical_data', 'impulse_response_plot',
|
| 14 |
+
'ramp_response_numerical_data', 'ramp_response_plot',
|
| 15 |
+
'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
|
| 16 |
+
'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
|
wemm/lib/python3.10/site-packages/sympy/physics/control/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/control/__pycache__/control_plots.cpython-310.pyc
ADDED
|
Binary file (30.3 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/control/control_plots.py
ADDED
|
@@ -0,0 +1,978 @@
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import I, pi
|
| 2 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 3 |
+
from sympy.polys.partfrac import apart
|
| 4 |
+
from sympy.core.symbol import Dummy
|
| 5 |
+
from sympy.external import import_module
|
| 6 |
+
from sympy.functions import arg, Abs
|
| 7 |
+
from sympy.integrals.laplace import _fast_inverse_laplace
|
| 8 |
+
from sympy.physics.control.lti import SISOLinearTimeInvariant
|
| 9 |
+
from sympy.plotting.series import LineOver1DRangeSeries
|
| 10 |
+
from sympy.polys.polytools import Poly
|
| 11 |
+
from sympy.printing.latex import latex
|
| 12 |
+
|
| 13 |
+
__all__ = ['pole_zero_numerical_data', 'pole_zero_plot',
|
| 14 |
+
'step_response_numerical_data', 'step_response_plot',
|
| 15 |
+
'impulse_response_numerical_data', 'impulse_response_plot',
|
| 16 |
+
'ramp_response_numerical_data', 'ramp_response_plot',
|
| 17 |
+
'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
|
| 18 |
+
'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
|
| 19 |
+
|
| 20 |
+
matplotlib = import_module(
|
| 21 |
+
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
|
| 22 |
+
catch=(RuntimeError,))
|
| 23 |
+
|
| 24 |
+
numpy = import_module('numpy')
|
| 25 |
+
|
| 26 |
+
if matplotlib:
|
| 27 |
+
plt = matplotlib.pyplot
|
| 28 |
+
|
| 29 |
+
if numpy:
|
| 30 |
+
np = numpy # Matplotlib already has numpy as a compulsory dependency. No need to install it separately.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _check_system(system):
|
| 34 |
+
"""Function to check whether the dynamical system passed for plots is
|
| 35 |
+
compatible or not."""
|
| 36 |
+
if not isinstance(system, SISOLinearTimeInvariant):
|
| 37 |
+
raise NotImplementedError("Only SISO LTI systems are currently supported.")
|
| 38 |
+
sys = system.to_expr()
|
| 39 |
+
len_free_symbols = len(sys.free_symbols)
|
| 40 |
+
if len_free_symbols > 1:
|
| 41 |
+
raise ValueError("Extra degree of freedom found. Make sure"
|
| 42 |
+
" that there are no free symbols in the dynamical system other"
|
| 43 |
+
" than the variable of Laplace transform.")
|
| 44 |
+
if sys.has(exp):
|
| 45 |
+
# Should test that exp is not part of a constant, in which case
|
| 46 |
+
# no exception is required, compare exp(s) with s*exp(1)
|
| 47 |
+
raise NotImplementedError("Time delay terms are not supported.")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def pole_zero_numerical_data(system):
|
| 51 |
+
"""
|
| 52 |
+
Returns the numerical data of poles and zeros of the system.
|
| 53 |
+
It is internally used by ``pole_zero_plot`` to get the data
|
| 54 |
+
for plotting poles and zeros. Users can use this data to further
|
| 55 |
+
analyse the dynamics of the system or plot using a different
|
| 56 |
+
backend/plotting-module.
|
| 57 |
+
|
| 58 |
+
Parameters
|
| 59 |
+
==========
|
| 60 |
+
|
| 61 |
+
system : SISOLinearTimeInvariant
|
| 62 |
+
The system for which the pole-zero data is to be computed.
|
| 63 |
+
|
| 64 |
+
Returns
|
| 65 |
+
=======
|
| 66 |
+
|
| 67 |
+
tuple : (zeros, poles)
|
| 68 |
+
zeros = Zeros of the system. NumPy array of complex numbers.
|
| 69 |
+
poles = Poles of the system. NumPy array of complex numbers.
|
| 70 |
+
|
| 71 |
+
Raises
|
| 72 |
+
======
|
| 73 |
+
|
| 74 |
+
NotImplementedError
|
| 75 |
+
When a SISO LTI system is not passed.
|
| 76 |
+
|
| 77 |
+
When time delay terms are present in the system.
|
| 78 |
+
|
| 79 |
+
ValueError
|
| 80 |
+
When more than one free symbol is present in the system.
|
| 81 |
+
The only variable in the transfer function should be
|
| 82 |
+
the variable of the Laplace transform.
|
| 83 |
+
|
| 84 |
+
Examples
|
| 85 |
+
========
|
| 86 |
+
|
| 87 |
+
>>> from sympy.abc import s
|
| 88 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 89 |
+
>>> from sympy.physics.control.control_plots import pole_zero_numerical_data
|
| 90 |
+
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
|
| 91 |
+
>>> pole_zero_numerical_data(tf1) # doctest: +SKIP
|
| 92 |
+
([-0.+1.j 0.-1.j], [-2. +0.j -0.5+0.8660254j -0.5-0.8660254j -1. +0.j ])
|
| 93 |
+
|
| 94 |
+
See Also
|
| 95 |
+
========
|
| 96 |
+
|
| 97 |
+
pole_zero_plot
|
| 98 |
+
|
| 99 |
+
"""
|
| 100 |
+
_check_system(system)
|
| 101 |
+
system = system.doit() # Get the equivalent TransferFunction object.
|
| 102 |
+
|
| 103 |
+
num_poly = Poly(system.num, system.var).all_coeffs()
|
| 104 |
+
den_poly = Poly(system.den, system.var).all_coeffs()
|
| 105 |
+
|
| 106 |
+
num_poly = np.array(num_poly, dtype=np.complex128)
|
| 107 |
+
den_poly = np.array(den_poly, dtype=np.complex128)
|
| 108 |
+
|
| 109 |
+
zeros = np.roots(num_poly)
|
| 110 |
+
poles = np.roots(den_poly)
|
| 111 |
+
|
| 112 |
+
return zeros, poles
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def pole_zero_plot(system, pole_color='blue', pole_markersize=10,
|
| 116 |
+
zero_color='orange', zero_markersize=7, grid=True, show_axes=True,
|
| 117 |
+
show=True, **kwargs):
|
| 118 |
+
r"""
|
| 119 |
+
Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system.
|
| 120 |
+
|
| 121 |
+
A Pole-Zero plot is a graphical representation of a system's poles and
|
| 122 |
+
zeros. It is plotted on a complex plane, with circular markers representing
|
| 123 |
+
the system's zeros and 'x' shaped markers representing the system's poles.
|
| 124 |
+
|
| 125 |
+
Parameters
|
| 126 |
+
==========
|
| 127 |
+
|
| 128 |
+
system : SISOLinearTimeInvariant type systems
|
| 129 |
+
The system for which the pole-zero plot is to be computed.
|
| 130 |
+
pole_color : str, tuple, optional
|
| 131 |
+
The color of the pole points on the plot. Default color
|
| 132 |
+
is blue. The color can be provided as a matplotlib color string,
|
| 133 |
+
or a 3-tuple of floats each in the 0-1 range.
|
| 134 |
+
pole_markersize : Number, optional
|
| 135 |
+
The size of the markers used to mark the poles in the plot.
|
| 136 |
+
Default pole markersize is 10.
|
| 137 |
+
zero_color : str, tuple, optional
|
| 138 |
+
The color of the zero points on the plot. Default color
|
| 139 |
+
is orange. The color can be provided as a matplotlib color string,
|
| 140 |
+
or a 3-tuple of floats each in the 0-1 range.
|
| 141 |
+
zero_markersize : Number, optional
|
| 142 |
+
The size of the markers used to mark the zeros in the plot.
|
| 143 |
+
Default zero markersize is 7.
|
| 144 |
+
grid : boolean, optional
|
| 145 |
+
If ``True``, the plot will have a grid. Defaults to True.
|
| 146 |
+
show_axes : boolean, optional
|
| 147 |
+
If ``True``, the coordinate axes will be shown. Defaults to False.
|
| 148 |
+
show : boolean, optional
|
| 149 |
+
If ``True``, the plot will be displayed otherwise
|
| 150 |
+
the equivalent matplotlib ``plot`` object will be returned.
|
| 151 |
+
Defaults to True.
|
| 152 |
+
|
| 153 |
+
Examples
|
| 154 |
+
========
|
| 155 |
+
|
| 156 |
+
.. plot::
|
| 157 |
+
:context: close-figs
|
| 158 |
+
:format: doctest
|
| 159 |
+
:include-source: True
|
| 160 |
+
|
| 161 |
+
>>> from sympy.abc import s
|
| 162 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 163 |
+
>>> from sympy.physics.control.control_plots import pole_zero_plot
|
| 164 |
+
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
|
| 165 |
+
>>> pole_zero_plot(tf1) # doctest: +SKIP
|
| 166 |
+
|
| 167 |
+
See Also
|
| 168 |
+
========
|
| 169 |
+
|
| 170 |
+
pole_zero_numerical_data
|
| 171 |
+
|
| 172 |
+
References
|
| 173 |
+
==========
|
| 174 |
+
|
| 175 |
+
.. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot
|
| 176 |
+
|
| 177 |
+
"""
|
| 178 |
+
zeros, poles = pole_zero_numerical_data(system)
|
| 179 |
+
|
| 180 |
+
zero_real = np.real(zeros)
|
| 181 |
+
zero_imag = np.imag(zeros)
|
| 182 |
+
|
| 183 |
+
pole_real = np.real(poles)
|
| 184 |
+
pole_imag = np.imag(poles)
|
| 185 |
+
|
| 186 |
+
plt.plot(pole_real, pole_imag, 'x', mfc='none',
|
| 187 |
+
markersize=pole_markersize, color=pole_color)
|
| 188 |
+
plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize,
|
| 189 |
+
color=zero_color)
|
| 190 |
+
plt.xlabel('Real Axis')
|
| 191 |
+
plt.ylabel('Imaginary Axis')
|
| 192 |
+
plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20)
|
| 193 |
+
|
| 194 |
+
if grid:
|
| 195 |
+
plt.grid()
|
| 196 |
+
if show_axes:
|
| 197 |
+
plt.axhline(0, color='black')
|
| 198 |
+
plt.axvline(0, color='black')
|
| 199 |
+
if show:
|
| 200 |
+
plt.show()
|
| 201 |
+
return
|
| 202 |
+
|
| 203 |
+
return plt
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def step_response_numerical_data(system, prec=8, lower_limit=0,
|
| 207 |
+
upper_limit=10, **kwargs):
|
| 208 |
+
"""
|
| 209 |
+
Returns the numerical values of the points in the step response plot
|
| 210 |
+
of a SISO continuous-time system. By default, adaptive sampling
|
| 211 |
+
is used. If the user wants to instead get an uniformly
|
| 212 |
+
sampled response, then ``adaptive`` kwarg should be passed ``False``
|
| 213 |
+
and ``n`` must be passed as additional kwargs.
|
| 214 |
+
Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
|
| 215 |
+
for more details.
|
| 216 |
+
|
| 217 |
+
Parameters
|
| 218 |
+
==========
|
| 219 |
+
|
| 220 |
+
system : SISOLinearTimeInvariant
|
| 221 |
+
The system for which the unit step response data is to be computed.
|
| 222 |
+
prec : int, optional
|
| 223 |
+
The decimal point precision for the point coordinate values.
|
| 224 |
+
Defaults to 8.
|
| 225 |
+
lower_limit : Number, optional
|
| 226 |
+
The lower limit of the plot range. Defaults to 0.
|
| 227 |
+
upper_limit : Number, optional
|
| 228 |
+
The upper limit of the plot range. Defaults to 10.
|
| 229 |
+
kwargs :
|
| 230 |
+
Additional keyword arguments are passed to the underlying
|
| 231 |
+
:class:`sympy.plotting.series.LineOver1DRangeSeries` class.
|
| 232 |
+
|
| 233 |
+
Returns
|
| 234 |
+
=======
|
| 235 |
+
|
| 236 |
+
tuple : (x, y)
|
| 237 |
+
x = Time-axis values of the points in the step response. NumPy array.
|
| 238 |
+
y = Amplitude-axis values of the points in the step response. NumPy array.
|
| 239 |
+
|
| 240 |
+
Raises
|
| 241 |
+
======
|
| 242 |
+
|
| 243 |
+
NotImplementedError
|
| 244 |
+
When a SISO LTI system is not passed.
|
| 245 |
+
|
| 246 |
+
When time delay terms are present in the system.
|
| 247 |
+
|
| 248 |
+
ValueError
|
| 249 |
+
When more than one free symbol is present in the system.
|
| 250 |
+
The only variable in the transfer function should be
|
| 251 |
+
the variable of the Laplace transform.
|
| 252 |
+
|
| 253 |
+
When ``lower_limit`` parameter is less than 0.
|
| 254 |
+
|
| 255 |
+
Examples
|
| 256 |
+
========
|
| 257 |
+
|
| 258 |
+
>>> from sympy.abc import s
|
| 259 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 260 |
+
>>> from sympy.physics.control.control_plots import step_response_numerical_data
|
| 261 |
+
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
|
| 262 |
+
>>> step_response_numerical_data(tf1) # doctest: +SKIP
|
| 263 |
+
([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0],
|
| 264 |
+
[0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12])
|
| 265 |
+
|
| 266 |
+
See Also
|
| 267 |
+
========
|
| 268 |
+
|
| 269 |
+
step_response_plot
|
| 270 |
+
|
| 271 |
+
"""
|
| 272 |
+
if lower_limit < 0:
|
| 273 |
+
raise ValueError("Lower limit of time must be greater "
|
| 274 |
+
"than or equal to zero.")
|
| 275 |
+
_check_system(system)
|
| 276 |
+
_x = Dummy("x")
|
| 277 |
+
expr = system.to_expr()/(system.var)
|
| 278 |
+
expr = apart(expr, system.var, full=True)
|
| 279 |
+
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
|
| 280 |
+
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
|
| 281 |
+
**kwargs).get_points()
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def step_response_plot(system, color='b', prec=8, lower_limit=0,
|
| 285 |
+
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
|
| 286 |
+
r"""
|
| 287 |
+
Returns the unit step response of a continuous-time system. It is
|
| 288 |
+
the response of the system when the input signal is a step function.
|
| 289 |
+
|
| 290 |
+
Parameters
|
| 291 |
+
==========
|
| 292 |
+
|
| 293 |
+
system : SISOLinearTimeInvariant type
|
| 294 |
+
The LTI SISO system for which the Step Response is to be computed.
|
| 295 |
+
color : str, tuple, optional
|
| 296 |
+
The color of the line. Default is Blue.
|
| 297 |
+
show : boolean, optional
|
| 298 |
+
If ``True``, the plot will be displayed otherwise
|
| 299 |
+
the equivalent matplotlib ``plot`` object will be returned.
|
| 300 |
+
Defaults to True.
|
| 301 |
+
lower_limit : Number, optional
|
| 302 |
+
The lower limit of the plot range. Defaults to 0.
|
| 303 |
+
upper_limit : Number, optional
|
| 304 |
+
The upper limit of the plot range. Defaults to 10.
|
| 305 |
+
prec : int, optional
|
| 306 |
+
The decimal point precision for the point coordinate values.
|
| 307 |
+
Defaults to 8.
|
| 308 |
+
show_axes : boolean, optional
|
| 309 |
+
If ``True``, the coordinate axes will be shown. Defaults to False.
|
| 310 |
+
grid : boolean, optional
|
| 311 |
+
If ``True``, the plot will have a grid. Defaults to True.
|
| 312 |
+
|
| 313 |
+
Examples
|
| 314 |
+
========
|
| 315 |
+
|
| 316 |
+
.. plot::
|
| 317 |
+
:context: close-figs
|
| 318 |
+
:format: doctest
|
| 319 |
+
:include-source: True
|
| 320 |
+
|
| 321 |
+
>>> from sympy.abc import s
|
| 322 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 323 |
+
>>> from sympy.physics.control.control_plots import step_response_plot
|
| 324 |
+
>>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
|
| 325 |
+
>>> step_response_plot(tf1) # doctest: +SKIP
|
| 326 |
+
|
| 327 |
+
See Also
|
| 328 |
+
========
|
| 329 |
+
|
| 330 |
+
impulse_response_plot, ramp_response_plot
|
| 331 |
+
|
| 332 |
+
References
|
| 333 |
+
==========
|
| 334 |
+
|
| 335 |
+
.. [1] https://www.mathworks.com/help/control/ref/lti.step.html
|
| 336 |
+
|
| 337 |
+
"""
|
| 338 |
+
x, y = step_response_numerical_data(system, prec=prec,
|
| 339 |
+
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
|
| 340 |
+
plt.plot(x, y, color=color)
|
| 341 |
+
plt.xlabel('Time (s)')
|
| 342 |
+
plt.ylabel('Amplitude')
|
| 343 |
+
plt.title(f'Unit Step Response of ${latex(system)}$', pad=20)
|
| 344 |
+
|
| 345 |
+
if grid:
|
| 346 |
+
plt.grid()
|
| 347 |
+
if show_axes:
|
| 348 |
+
plt.axhline(0, color='black')
|
| 349 |
+
plt.axvline(0, color='black')
|
| 350 |
+
if show:
|
| 351 |
+
plt.show()
|
| 352 |
+
return
|
| 353 |
+
|
| 354 |
+
return plt
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def impulse_response_numerical_data(system, prec=8, lower_limit=0,
|
| 358 |
+
upper_limit=10, **kwargs):
|
| 359 |
+
"""
|
| 360 |
+
Returns the numerical values of the points in the impulse response plot
|
| 361 |
+
of a SISO continuous-time system. By default, adaptive sampling
|
| 362 |
+
is used. If the user wants to instead get an uniformly
|
| 363 |
+
sampled response, then ``adaptive`` kwarg should be passed ``False``
|
| 364 |
+
and ``n`` must be passed as additional kwargs.
|
| 365 |
+
Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
|
| 366 |
+
for more details.
|
| 367 |
+
|
| 368 |
+
Parameters
|
| 369 |
+
==========
|
| 370 |
+
|
| 371 |
+
system : SISOLinearTimeInvariant
|
| 372 |
+
The system for which the impulse response data is to be computed.
|
| 373 |
+
prec : int, optional
|
| 374 |
+
The decimal point precision for the point coordinate values.
|
| 375 |
+
Defaults to 8.
|
| 376 |
+
lower_limit : Number, optional
|
| 377 |
+
The lower limit of the plot range. Defaults to 0.
|
| 378 |
+
upper_limit : Number, optional
|
| 379 |
+
The upper limit of the plot range. Defaults to 10.
|
| 380 |
+
kwargs :
|
| 381 |
+
Additional keyword arguments are passed to the underlying
|
| 382 |
+
:class:`sympy.plotting.series.LineOver1DRangeSeries` class.
|
| 383 |
+
|
| 384 |
+
Returns
|
| 385 |
+
=======
|
| 386 |
+
|
| 387 |
+
tuple : (x, y)
|
| 388 |
+
x = Time-axis values of the points in the impulse response. NumPy array.
|
| 389 |
+
y = Amplitude-axis values of the points in the impulse response. NumPy array.
|
| 390 |
+
|
| 391 |
+
Raises
|
| 392 |
+
======
|
| 393 |
+
|
| 394 |
+
NotImplementedError
|
| 395 |
+
When a SISO LTI system is not passed.
|
| 396 |
+
|
| 397 |
+
When time delay terms are present in the system.
|
| 398 |
+
|
| 399 |
+
ValueError
|
| 400 |
+
When more than one free symbol is present in the system.
|
| 401 |
+
The only variable in the transfer function should be
|
| 402 |
+
the variable of the Laplace transform.
|
| 403 |
+
|
| 404 |
+
When ``lower_limit`` parameter is less than 0.
|
| 405 |
+
|
| 406 |
+
Examples
|
| 407 |
+
========
|
| 408 |
+
|
| 409 |
+
>>> from sympy.abc import s
|
| 410 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 411 |
+
>>> from sympy.physics.control.control_plots import impulse_response_numerical_data
|
| 412 |
+
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
|
| 413 |
+
>>> impulse_response_numerical_data(tf1) # doctest: +SKIP
|
| 414 |
+
([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0],
|
| 415 |
+
[0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12])
|
| 416 |
+
|
| 417 |
+
See Also
|
| 418 |
+
========
|
| 419 |
+
|
| 420 |
+
impulse_response_plot
|
| 421 |
+
|
| 422 |
+
"""
|
| 423 |
+
if lower_limit < 0:
|
| 424 |
+
raise ValueError("Lower limit of time must be greater "
|
| 425 |
+
"than or equal to zero.")
|
| 426 |
+
_check_system(system)
|
| 427 |
+
_x = Dummy("x")
|
| 428 |
+
expr = system.to_expr()
|
| 429 |
+
expr = apart(expr, system.var, full=True)
|
| 430 |
+
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
|
| 431 |
+
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
|
| 432 |
+
**kwargs).get_points()
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def impulse_response_plot(system, color='b', prec=8, lower_limit=0,
|
| 436 |
+
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
|
| 437 |
+
r"""
|
| 438 |
+
Returns the unit impulse response (Input is the Dirac-Delta Function) of a
|
| 439 |
+
continuous-time system.
|
| 440 |
+
|
| 441 |
+
Parameters
|
| 442 |
+
==========
|
| 443 |
+
|
| 444 |
+
system : SISOLinearTimeInvariant type
|
| 445 |
+
The LTI SISO system for which the Impulse Response is to be computed.
|
| 446 |
+
color : str, tuple, optional
|
| 447 |
+
The color of the line. Default is Blue.
|
| 448 |
+
show : boolean, optional
|
| 449 |
+
If ``True``, the plot will be displayed otherwise
|
| 450 |
+
the equivalent matplotlib ``plot`` object will be returned.
|
| 451 |
+
Defaults to True.
|
| 452 |
+
lower_limit : Number, optional
|
| 453 |
+
The lower limit of the plot range. Defaults to 0.
|
| 454 |
+
upper_limit : Number, optional
|
| 455 |
+
The upper limit of the plot range. Defaults to 10.
|
| 456 |
+
prec : int, optional
|
| 457 |
+
The decimal point precision for the point coordinate values.
|
| 458 |
+
Defaults to 8.
|
| 459 |
+
show_axes : boolean, optional
|
| 460 |
+
If ``True``, the coordinate axes will be shown. Defaults to False.
|
| 461 |
+
grid : boolean, optional
|
| 462 |
+
If ``True``, the plot will have a grid. Defaults to True.
|
| 463 |
+
|
| 464 |
+
Examples
|
| 465 |
+
========
|
| 466 |
+
|
| 467 |
+
.. plot::
|
| 468 |
+
:context: close-figs
|
| 469 |
+
:format: doctest
|
| 470 |
+
:include-source: True
|
| 471 |
+
|
| 472 |
+
>>> from sympy.abc import s
|
| 473 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 474 |
+
>>> from sympy.physics.control.control_plots import impulse_response_plot
|
| 475 |
+
>>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
|
| 476 |
+
>>> impulse_response_plot(tf1) # doctest: +SKIP
|
| 477 |
+
|
| 478 |
+
See Also
|
| 479 |
+
========
|
| 480 |
+
|
| 481 |
+
step_response_plot, ramp_response_plot
|
| 482 |
+
|
| 483 |
+
References
|
| 484 |
+
==========
|
| 485 |
+
|
| 486 |
+
.. [1] https://www.mathworks.com/help/control/ref/dynamicsystem.impulse.html
|
| 487 |
+
|
| 488 |
+
"""
|
| 489 |
+
x, y = impulse_response_numerical_data(system, prec=prec,
|
| 490 |
+
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
|
| 491 |
+
plt.plot(x, y, color=color)
|
| 492 |
+
plt.xlabel('Time (s)')
|
| 493 |
+
plt.ylabel('Amplitude')
|
| 494 |
+
plt.title(f'Impulse Response of ${latex(system)}$', pad=20)
|
| 495 |
+
|
| 496 |
+
if grid:
|
| 497 |
+
plt.grid()
|
| 498 |
+
if show_axes:
|
| 499 |
+
plt.axhline(0, color='black')
|
| 500 |
+
plt.axvline(0, color='black')
|
| 501 |
+
if show:
|
| 502 |
+
plt.show()
|
| 503 |
+
return
|
| 504 |
+
|
| 505 |
+
return plt
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def ramp_response_numerical_data(system, slope=1, prec=8,
|
| 509 |
+
lower_limit=0, upper_limit=10, **kwargs):
|
| 510 |
+
"""
|
| 511 |
+
Returns the numerical values of the points in the ramp response plot
|
| 512 |
+
of a SISO continuous-time system. By default, adaptive sampling
|
| 513 |
+
is used. If the user wants to instead get an uniformly
|
| 514 |
+
sampled response, then ``adaptive`` kwarg should be passed ``False``
|
| 515 |
+
and ``n`` must be passed as additional kwargs.
|
| 516 |
+
Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
|
| 517 |
+
for more details.
|
| 518 |
+
|
| 519 |
+
Parameters
|
| 520 |
+
==========
|
| 521 |
+
|
| 522 |
+
system : SISOLinearTimeInvariant
|
| 523 |
+
The system for which the ramp response data is to be computed.
|
| 524 |
+
slope : Number, optional
|
| 525 |
+
The slope of the input ramp function. Defaults to 1.
|
| 526 |
+
prec : int, optional
|
| 527 |
+
The decimal point precision for the point coordinate values.
|
| 528 |
+
Defaults to 8.
|
| 529 |
+
lower_limit : Number, optional
|
| 530 |
+
The lower limit of the plot range. Defaults to 0.
|
| 531 |
+
upper_limit : Number, optional
|
| 532 |
+
The upper limit of the plot range. Defaults to 10.
|
| 533 |
+
kwargs :
|
| 534 |
+
Additional keyword arguments are passed to the underlying
|
| 535 |
+
:class:`sympy.plotting.series.LineOver1DRangeSeries` class.
|
| 536 |
+
|
| 537 |
+
Returns
|
| 538 |
+
=======
|
| 539 |
+
|
| 540 |
+
tuple : (x, y)
|
| 541 |
+
x = Time-axis values of the points in the ramp response plot. NumPy array.
|
| 542 |
+
y = Amplitude-axis values of the points in the ramp response plot. NumPy array.
|
| 543 |
+
|
| 544 |
+
Raises
|
| 545 |
+
======
|
| 546 |
+
|
| 547 |
+
NotImplementedError
|
| 548 |
+
When a SISO LTI system is not passed.
|
| 549 |
+
|
| 550 |
+
When time delay terms are present in the system.
|
| 551 |
+
|
| 552 |
+
ValueError
|
| 553 |
+
When more than one free symbol is present in the system.
|
| 554 |
+
The only variable in the transfer function should be
|
| 555 |
+
the variable of the Laplace transform.
|
| 556 |
+
|
| 557 |
+
When ``lower_limit`` parameter is less than 0.
|
| 558 |
+
|
| 559 |
+
When ``slope`` is negative.
|
| 560 |
+
|
| 561 |
+
Examples
|
| 562 |
+
========
|
| 563 |
+
|
| 564 |
+
>>> from sympy.abc import s
|
| 565 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 566 |
+
>>> from sympy.physics.control.control_plots import ramp_response_numerical_data
|
| 567 |
+
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
|
| 568 |
+
>>> ramp_response_numerical_data(tf1) # doctest: +SKIP
|
| 569 |
+
(([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0],
|
| 570 |
+
[1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349]))
|
| 571 |
+
|
| 572 |
+
See Also
|
| 573 |
+
========
|
| 574 |
+
|
| 575 |
+
ramp_response_plot
|
| 576 |
+
|
| 577 |
+
"""
|
| 578 |
+
if slope < 0:
|
| 579 |
+
raise ValueError("Slope must be greater than or equal"
|
| 580 |
+
" to zero.")
|
| 581 |
+
if lower_limit < 0:
|
| 582 |
+
raise ValueError("Lower limit of time must be greater "
|
| 583 |
+
"than or equal to zero.")
|
| 584 |
+
_check_system(system)
|
| 585 |
+
_x = Dummy("x")
|
| 586 |
+
expr = (slope*system.to_expr())/((system.var)**2)
|
| 587 |
+
expr = apart(expr, system.var, full=True)
|
| 588 |
+
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
|
| 589 |
+
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
|
| 590 |
+
**kwargs).get_points()
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0,
|
| 594 |
+
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
|
| 595 |
+
r"""
|
| 596 |
+
Returns the ramp response of a continuous-time system.
|
| 597 |
+
|
| 598 |
+
Ramp function is defined as the straight line
|
| 599 |
+
passing through origin ($f(x) = mx$). The slope of
|
| 600 |
+
the ramp function can be varied by the user and
|
| 601 |
+
the default value is 1.
|
| 602 |
+
|
| 603 |
+
Parameters
|
| 604 |
+
==========
|
| 605 |
+
|
| 606 |
+
system : SISOLinearTimeInvariant type
|
| 607 |
+
The LTI SISO system for which the Ramp Response is to be computed.
|
| 608 |
+
slope : Number, optional
|
| 609 |
+
The slope of the input ramp function. Defaults to 1.
|
| 610 |
+
color : str, tuple, optional
|
| 611 |
+
The color of the line. Default is Blue.
|
| 612 |
+
show : boolean, optional
|
| 613 |
+
If ``True``, the plot will be displayed otherwise
|
| 614 |
+
the equivalent matplotlib ``plot`` object will be returned.
|
| 615 |
+
Defaults to True.
|
| 616 |
+
lower_limit : Number, optional
|
| 617 |
+
The lower limit of the plot range. Defaults to 0.
|
| 618 |
+
upper_limit : Number, optional
|
| 619 |
+
The upper limit of the plot range. Defaults to 10.
|
| 620 |
+
prec : int, optional
|
| 621 |
+
The decimal point precision for the point coordinate values.
|
| 622 |
+
Defaults to 8.
|
| 623 |
+
show_axes : boolean, optional
|
| 624 |
+
If ``True``, the coordinate axes will be shown. Defaults to False.
|
| 625 |
+
grid : boolean, optional
|
| 626 |
+
If ``True``, the plot will have a grid. Defaults to True.
|
| 627 |
+
|
| 628 |
+
Examples
|
| 629 |
+
========
|
| 630 |
+
|
| 631 |
+
.. plot::
|
| 632 |
+
:context: close-figs
|
| 633 |
+
:format: doctest
|
| 634 |
+
:include-source: True
|
| 635 |
+
|
| 636 |
+
>>> from sympy.abc import s
|
| 637 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 638 |
+
>>> from sympy.physics.control.control_plots import ramp_response_plot
|
| 639 |
+
>>> tf1 = TransferFunction(s, (s+4)*(s+8), s)
|
| 640 |
+
>>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP
|
| 641 |
+
|
| 642 |
+
See Also
|
| 643 |
+
========
|
| 644 |
+
|
| 645 |
+
step_response_plot, impulse_response_plot
|
| 646 |
+
|
| 647 |
+
References
|
| 648 |
+
==========
|
| 649 |
+
|
| 650 |
+
.. [1] https://en.wikipedia.org/wiki/Ramp_function
|
| 651 |
+
|
| 652 |
+
"""
|
| 653 |
+
x, y = ramp_response_numerical_data(system, slope=slope, prec=prec,
|
| 654 |
+
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
|
| 655 |
+
plt.plot(x, y, color=color)
|
| 656 |
+
plt.xlabel('Time (s)')
|
| 657 |
+
plt.ylabel('Amplitude')
|
| 658 |
+
plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20)
|
| 659 |
+
|
| 660 |
+
if grid:
|
| 661 |
+
plt.grid()
|
| 662 |
+
if show_axes:
|
| 663 |
+
plt.axhline(0, color='black')
|
| 664 |
+
plt.axvline(0, color='black')
|
| 665 |
+
if show:
|
| 666 |
+
plt.show()
|
| 667 |
+
return
|
| 668 |
+
|
| 669 |
+
return plt
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', **kwargs):
|
| 673 |
+
"""
|
| 674 |
+
Returns the numerical data of the Bode magnitude plot of the system.
|
| 675 |
+
It is internally used by ``bode_magnitude_plot`` to get the data
|
| 676 |
+
for plotting Bode magnitude plot. Users can use this data to further
|
| 677 |
+
analyse the dynamics of the system or plot using a different
|
| 678 |
+
backend/plotting-module.
|
| 679 |
+
|
| 680 |
+
Parameters
|
| 681 |
+
==========
|
| 682 |
+
|
| 683 |
+
system : SISOLinearTimeInvariant
|
| 684 |
+
The system for which the data is to be computed.
|
| 685 |
+
initial_exp : Number, optional
|
| 686 |
+
The initial exponent of 10 of the semilog plot. Defaults to -5.
|
| 687 |
+
final_exp : Number, optional
|
| 688 |
+
The final exponent of 10 of the semilog plot. Defaults to 5.
|
| 689 |
+
freq_unit : string, optional
|
| 690 |
+
User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
|
| 691 |
+
|
| 692 |
+
Returns
|
| 693 |
+
=======
|
| 694 |
+
|
| 695 |
+
tuple : (x, y)
|
| 696 |
+
x = x-axis values of the Bode magnitude plot.
|
| 697 |
+
y = y-axis values of the Bode magnitude plot.
|
| 698 |
+
|
| 699 |
+
Raises
|
| 700 |
+
======
|
| 701 |
+
|
| 702 |
+
NotImplementedError
|
| 703 |
+
When a SISO LTI system is not passed.
|
| 704 |
+
|
| 705 |
+
When time delay terms are present in the system.
|
| 706 |
+
|
| 707 |
+
ValueError
|
| 708 |
+
When more than one free symbol is present in the system.
|
| 709 |
+
The only variable in the transfer function should be
|
| 710 |
+
the variable of the Laplace transform.
|
| 711 |
+
|
| 712 |
+
When incorrect frequency units are given as input.
|
| 713 |
+
|
| 714 |
+
Examples
|
| 715 |
+
========
|
| 716 |
+
|
| 717 |
+
>>> from sympy.abc import s
|
| 718 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 719 |
+
>>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data
|
| 720 |
+
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
|
| 721 |
+
>>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP
|
| 722 |
+
([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0],
|
| 723 |
+
[-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573])
|
| 724 |
+
|
| 725 |
+
See Also
|
| 726 |
+
========
|
| 727 |
+
|
| 728 |
+
bode_magnitude_plot, bode_phase_numerical_data
|
| 729 |
+
|
| 730 |
+
"""
|
| 731 |
+
_check_system(system)
|
| 732 |
+
expr = system.to_expr()
|
| 733 |
+
freq_units = ('rad/sec', 'Hz')
|
| 734 |
+
if freq_unit not in freq_units:
|
| 735 |
+
raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
|
| 736 |
+
|
| 737 |
+
_w = Dummy("w", real=True)
|
| 738 |
+
if freq_unit == 'Hz':
|
| 739 |
+
repl = I*_w*2*pi
|
| 740 |
+
else:
|
| 741 |
+
repl = I*_w
|
| 742 |
+
w_expr = expr.subs({system.var: repl})
|
| 743 |
+
|
| 744 |
+
mag = 20*log(Abs(w_expr), 10)
|
| 745 |
+
|
| 746 |
+
x, y = LineOver1DRangeSeries(mag,
|
| 747 |
+
(_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
|
| 748 |
+
|
| 749 |
+
return x, y
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
def bode_magnitude_plot(system, initial_exp=-5, final_exp=5,
|
| 753 |
+
color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', **kwargs):
|
| 754 |
+
r"""
|
| 755 |
+
Returns the Bode magnitude plot of a continuous-time system.
|
| 756 |
+
|
| 757 |
+
See ``bode_plot`` for all the parameters.
|
| 758 |
+
"""
|
| 759 |
+
x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp,
|
| 760 |
+
final_exp=final_exp, freq_unit=freq_unit)
|
| 761 |
+
plt.plot(x, y, color=color, **kwargs)
|
| 762 |
+
plt.xscale('log')
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
|
| 766 |
+
plt.ylabel('Magnitude (dB)')
|
| 767 |
+
plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20)
|
| 768 |
+
|
| 769 |
+
if grid:
|
| 770 |
+
plt.grid(True)
|
| 771 |
+
if show_axes:
|
| 772 |
+
plt.axhline(0, color='black')
|
| 773 |
+
plt.axvline(0, color='black')
|
| 774 |
+
if show:
|
| 775 |
+
plt.show()
|
| 776 |
+
return
|
| 777 |
+
|
| 778 |
+
return plt
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', phase_unit='rad', phase_unwrap = True, **kwargs):
|
| 782 |
+
"""
|
| 783 |
+
Returns the numerical data of the Bode phase plot of the system.
|
| 784 |
+
It is internally used by ``bode_phase_plot`` to get the data
|
| 785 |
+
for plotting Bode phase plot. Users can use this data to further
|
| 786 |
+
analyse the dynamics of the system or plot using a different
|
| 787 |
+
backend/plotting-module.
|
| 788 |
+
|
| 789 |
+
Parameters
|
| 790 |
+
==========
|
| 791 |
+
|
| 792 |
+
system : SISOLinearTimeInvariant
|
| 793 |
+
The system for which the Bode phase plot data is to be computed.
|
| 794 |
+
initial_exp : Number, optional
|
| 795 |
+
The initial exponent of 10 of the semilog plot. Defaults to -5.
|
| 796 |
+
final_exp : Number, optional
|
| 797 |
+
The final exponent of 10 of the semilog plot. Defaults to 5.
|
| 798 |
+
freq_unit : string, optional
|
| 799 |
+
User can choose between ``'rad/sec'`` (radians/second) and '``'Hz'`` (Hertz) as frequency units.
|
| 800 |
+
phase_unit : string, optional
|
| 801 |
+
User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
|
| 802 |
+
phase_unwrap : bool, optional
|
| 803 |
+
Set to ``True`` by default.
|
| 804 |
+
|
| 805 |
+
Returns
|
| 806 |
+
=======
|
| 807 |
+
|
| 808 |
+
tuple : (x, y)
|
| 809 |
+
x = x-axis values of the Bode phase plot.
|
| 810 |
+
y = y-axis values of the Bode phase plot.
|
| 811 |
+
|
| 812 |
+
Raises
|
| 813 |
+
======
|
| 814 |
+
|
| 815 |
+
NotImplementedError
|
| 816 |
+
When a SISO LTI system is not passed.
|
| 817 |
+
|
| 818 |
+
When time delay terms are present in the system.
|
| 819 |
+
|
| 820 |
+
ValueError
|
| 821 |
+
When more than one free symbol is present in the system.
|
| 822 |
+
The only variable in the transfer function should be
|
| 823 |
+
the variable of the Laplace transform.
|
| 824 |
+
|
| 825 |
+
When incorrect frequency or phase units are given as input.
|
| 826 |
+
|
| 827 |
+
Examples
|
| 828 |
+
========
|
| 829 |
+
|
| 830 |
+
>>> from sympy.abc import s
|
| 831 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 832 |
+
>>> from sympy.physics.control.control_plots import bode_phase_numerical_data
|
| 833 |
+
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
|
| 834 |
+
>>> bode_phase_numerical_data(tf1) # doctest: +SKIP
|
| 835 |
+
([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0],
|
| 836 |
+
[-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979])
|
| 837 |
+
|
| 838 |
+
See Also
|
| 839 |
+
========
|
| 840 |
+
|
| 841 |
+
bode_magnitude_plot, bode_phase_numerical_data
|
| 842 |
+
|
| 843 |
+
"""
|
| 844 |
+
_check_system(system)
|
| 845 |
+
expr = system.to_expr()
|
| 846 |
+
freq_units = ('rad/sec', 'Hz')
|
| 847 |
+
phase_units = ('rad', 'deg')
|
| 848 |
+
if freq_unit not in freq_units:
|
| 849 |
+
raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
|
| 850 |
+
if phase_unit not in phase_units:
|
| 851 |
+
raise ValueError('Only "rad" and "deg" are accepted phase units.')
|
| 852 |
+
|
| 853 |
+
_w = Dummy("w", real=True)
|
| 854 |
+
if freq_unit == 'Hz':
|
| 855 |
+
repl = I*_w*2*pi
|
| 856 |
+
else:
|
| 857 |
+
repl = I*_w
|
| 858 |
+
w_expr = expr.subs({system.var: repl})
|
| 859 |
+
|
| 860 |
+
if phase_unit == 'deg':
|
| 861 |
+
phase = arg(w_expr)*180/pi
|
| 862 |
+
else:
|
| 863 |
+
phase = arg(w_expr)
|
| 864 |
+
|
| 865 |
+
x, y = LineOver1DRangeSeries(phase,
|
| 866 |
+
(_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
|
| 867 |
+
|
| 868 |
+
half = None
|
| 869 |
+
if phase_unwrap:
|
| 870 |
+
if(phase_unit == 'rad'):
|
| 871 |
+
half = pi
|
| 872 |
+
elif(phase_unit == 'deg'):
|
| 873 |
+
half = 180
|
| 874 |
+
if half:
|
| 875 |
+
unit = 2*half
|
| 876 |
+
for i in range(1, len(y)):
|
| 877 |
+
diff = y[i] - y[i - 1]
|
| 878 |
+
if diff > half: # Jump from -half to half
|
| 879 |
+
y[i] = (y[i] - unit)
|
| 880 |
+
elif diff < -half: # Jump from half to -half
|
| 881 |
+
y[i] = (y[i] + unit)
|
| 882 |
+
|
| 883 |
+
return x, y
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
def bode_phase_plot(system, initial_exp=-5, final_exp=5,
|
| 887 |
+
color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', phase_unit='rad', phase_unwrap=True, **kwargs):
|
| 888 |
+
r"""
|
| 889 |
+
Returns the Bode phase plot of a continuous-time system.
|
| 890 |
+
|
| 891 |
+
See ``bode_plot`` for all the parameters.
|
| 892 |
+
"""
|
| 893 |
+
x, y = bode_phase_numerical_data(system, initial_exp=initial_exp,
|
| 894 |
+
final_exp=final_exp, freq_unit=freq_unit, phase_unit=phase_unit, phase_unwrap=phase_unwrap)
|
| 895 |
+
plt.plot(x, y, color=color, **kwargs)
|
| 896 |
+
plt.xscale('log')
|
| 897 |
+
|
| 898 |
+
plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
|
| 899 |
+
plt.ylabel('Phase (%s)' % phase_unit)
|
| 900 |
+
plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20)
|
| 901 |
+
|
| 902 |
+
if grid:
|
| 903 |
+
plt.grid(True)
|
| 904 |
+
if show_axes:
|
| 905 |
+
plt.axhline(0, color='black')
|
| 906 |
+
plt.axvline(0, color='black')
|
| 907 |
+
if show:
|
| 908 |
+
plt.show()
|
| 909 |
+
return
|
| 910 |
+
|
| 911 |
+
return plt
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
def bode_plot(system, initial_exp=-5, final_exp=5,
|
| 915 |
+
grid=True, show_axes=False, show=True, freq_unit='rad/sec', phase_unit='rad', phase_unwrap=True, **kwargs):
|
| 916 |
+
r"""
|
| 917 |
+
Returns the Bode phase and magnitude plots of a continuous-time system.
|
| 918 |
+
|
| 919 |
+
Parameters
|
| 920 |
+
==========
|
| 921 |
+
|
| 922 |
+
system : SISOLinearTimeInvariant type
|
| 923 |
+
The LTI SISO system for which the Bode Plot is to be computed.
|
| 924 |
+
initial_exp : Number, optional
|
| 925 |
+
The initial exponent of 10 of the semilog plot. Defaults to -5.
|
| 926 |
+
final_exp : Number, optional
|
| 927 |
+
The final exponent of 10 of the semilog plot. Defaults to 5.
|
| 928 |
+
show : boolean, optional
|
| 929 |
+
If ``True``, the plot will be displayed otherwise
|
| 930 |
+
the equivalent matplotlib ``plot`` object will be returned.
|
| 931 |
+
Defaults to True.
|
| 932 |
+
prec : int, optional
|
| 933 |
+
The decimal point precision for the point coordinate values.
|
| 934 |
+
Defaults to 8.
|
| 935 |
+
grid : boolean, optional
|
| 936 |
+
If ``True``, the plot will have a grid. Defaults to True.
|
| 937 |
+
show_axes : boolean, optional
|
| 938 |
+
If ``True``, the coordinate axes will be shown. Defaults to False.
|
| 939 |
+
freq_unit : string, optional
|
| 940 |
+
User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
|
| 941 |
+
phase_unit : string, optional
|
| 942 |
+
User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
|
| 943 |
+
|
| 944 |
+
Examples
|
| 945 |
+
========
|
| 946 |
+
|
| 947 |
+
.. plot::
|
| 948 |
+
:context: close-figs
|
| 949 |
+
:format: doctest
|
| 950 |
+
:include-source: True
|
| 951 |
+
|
| 952 |
+
>>> from sympy.abc import s
|
| 953 |
+
>>> from sympy.physics.control.lti import TransferFunction
|
| 954 |
+
>>> from sympy.physics.control.control_plots import bode_plot
|
| 955 |
+
>>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s)
|
| 956 |
+
>>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP
|
| 957 |
+
|
| 958 |
+
See Also
|
| 959 |
+
========
|
| 960 |
+
|
| 961 |
+
bode_magnitude_plot, bode_phase_plot
|
| 962 |
+
|
| 963 |
+
"""
|
| 964 |
+
plt.subplot(211)
|
| 965 |
+
mag = bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp,
|
| 966 |
+
show=False, grid=grid, show_axes=show_axes,
|
| 967 |
+
freq_unit=freq_unit, **kwargs)
|
| 968 |
+
mag.title(f'Bode Plot of ${latex(system)}$', pad=20)
|
| 969 |
+
mag.xlabel(None)
|
| 970 |
+
plt.subplot(212)
|
| 971 |
+
bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp,
|
| 972 |
+
show=False, grid=grid, show_axes=show_axes, freq_unit=freq_unit, phase_unit=phase_unit, phase_unwrap=phase_unwrap, **kwargs).title(None)
|
| 973 |
+
|
| 974 |
+
if show:
|
| 975 |
+
plt.show()
|
| 976 |
+
return
|
| 977 |
+
|
| 978 |
+
return plt
|
wemm/lib/python3.10/site-packages/sympy/physics/control/lti.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py
ADDED
|
File without changes
|
wemm/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (177 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_control_plots.cpython-310.pyc
ADDED
|
Binary file (11.5 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_lti.cpython-310.pyc
ADDED
|
Binary file (70.3 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import isclose
|
| 2 |
+
from sympy.core.numbers import I
|
| 3 |
+
from sympy.core.symbol import Dummy
|
| 4 |
+
from sympy.functions.elementary.complexes import (Abs, arg)
|
| 5 |
+
from sympy.functions.elementary.exponential import log
|
| 6 |
+
from sympy.abc import s, p, a
|
| 7 |
+
from sympy.external import import_module
|
| 8 |
+
from sympy.physics.control.control_plots import \
|
| 9 |
+
(pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
|
| 10 |
+
step_response_plot, impulse_response_numerical_data,
|
| 11 |
+
impulse_response_plot, ramp_response_numerical_data,
|
| 12 |
+
ramp_response_plot, bode_magnitude_numerical_data,
|
| 13 |
+
bode_phase_numerical_data, bode_plot)
|
| 14 |
+
from sympy.physics.control.lti import (TransferFunction,
|
| 15 |
+
Series, Parallel, TransferFunctionMatrix)
|
| 16 |
+
from sympy.testing.pytest import raises, skip
|
| 17 |
+
|
| 18 |
+
matplotlib = import_module(
|
| 19 |
+
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
|
| 20 |
+
catch=(RuntimeError,))
|
| 21 |
+
|
| 22 |
+
numpy = import_module('numpy')
|
| 23 |
+
|
| 24 |
+
tf1 = TransferFunction(1, p**2 + 0.5*p + 2, p)
|
| 25 |
+
tf2 = TransferFunction(p, 6*p**2 + 3*p + 1, p)
|
| 26 |
+
tf3 = TransferFunction(p, p**3 - 1, p)
|
| 27 |
+
tf4 = TransferFunction(10, p**3, p)
|
| 28 |
+
tf5 = TransferFunction(5, s**2 + 2*s + 10, s)
|
| 29 |
+
tf6 = TransferFunction(1, 1, s)
|
| 30 |
+
tf7 = TransferFunction(4*s*3 + 9*s**2 + 0.1*s + 11, 8*s**6 + 9*s**4 + 11, s)
|
| 31 |
+
tf8 = TransferFunction(5, s**2 + (2+I)*s + 10, s)
|
| 32 |
+
|
| 33 |
+
ser1 = Series(tf4, TransferFunction(1, p - 5, p))
|
| 34 |
+
ser2 = Series(tf3, TransferFunction(p, p + 2, p))
|
| 35 |
+
|
| 36 |
+
par1 = Parallel(tf1, tf2)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _to_tuple(a, b):
|
| 40 |
+
return tuple(a), tuple(b)
|
| 41 |
+
|
| 42 |
+
def _trim_tuple(a, b):
|
| 43 |
+
a, b = _to_tuple(a, b)
|
| 44 |
+
return tuple(a[0: 2] + a[len(a)//2 : len(a)//2 + 1] + a[-2:]), \
|
| 45 |
+
tuple(b[0: 2] + b[len(b)//2 : len(b)//2 + 1] + b[-2:])
|
| 46 |
+
|
| 47 |
+
def y_coordinate_equality(plot_data_func, evalf_func, system):
|
| 48 |
+
"""Checks whether the y-coordinate value of the plotted
|
| 49 |
+
data point is equal to the value of the function at a
|
| 50 |
+
particular x."""
|
| 51 |
+
x, y = plot_data_func(system)
|
| 52 |
+
x, y = _trim_tuple(x, y)
|
| 53 |
+
y_exp = tuple(evalf_func(system, x_i) for x_i in x)
|
| 54 |
+
return all(Abs(y_exp_i - y_i) < 1e-8 for y_exp_i, y_i in zip(y_exp, y))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_errors():
|
| 58 |
+
if not matplotlib:
|
| 59 |
+
skip("Matplotlib not the default backend")
|
| 60 |
+
|
| 61 |
+
# Invalid `system` check
|
| 62 |
+
tfm = TransferFunctionMatrix([[tf6, tf5], [tf5, tf6]])
|
| 63 |
+
expr = 1/(s**2 - 1)
|
| 64 |
+
raises(NotImplementedError, lambda: pole_zero_plot(tfm))
|
| 65 |
+
raises(NotImplementedError, lambda: pole_zero_numerical_data(expr))
|
| 66 |
+
raises(NotImplementedError, lambda: impulse_response_plot(expr))
|
| 67 |
+
raises(NotImplementedError, lambda: impulse_response_numerical_data(tfm))
|
| 68 |
+
raises(NotImplementedError, lambda: step_response_plot(tfm))
|
| 69 |
+
raises(NotImplementedError, lambda: step_response_numerical_data(expr))
|
| 70 |
+
raises(NotImplementedError, lambda: ramp_response_plot(expr))
|
| 71 |
+
raises(NotImplementedError, lambda: ramp_response_numerical_data(tfm))
|
| 72 |
+
raises(NotImplementedError, lambda: bode_plot(tfm))
|
| 73 |
+
|
| 74 |
+
# More than 1 variables
|
| 75 |
+
tf_a = TransferFunction(a, s + 1, s)
|
| 76 |
+
raises(ValueError, lambda: pole_zero_plot(tf_a))
|
| 77 |
+
raises(ValueError, lambda: pole_zero_numerical_data(tf_a))
|
| 78 |
+
raises(ValueError, lambda: impulse_response_plot(tf_a))
|
| 79 |
+
raises(ValueError, lambda: impulse_response_numerical_data(tf_a))
|
| 80 |
+
raises(ValueError, lambda: step_response_plot(tf_a))
|
| 81 |
+
raises(ValueError, lambda: step_response_numerical_data(tf_a))
|
| 82 |
+
raises(ValueError, lambda: ramp_response_plot(tf_a))
|
| 83 |
+
raises(ValueError, lambda: ramp_response_numerical_data(tf_a))
|
| 84 |
+
raises(ValueError, lambda: bode_plot(tf_a))
|
| 85 |
+
|
| 86 |
+
# lower_limit > 0 for response plots
|
| 87 |
+
raises(ValueError, lambda: impulse_response_plot(tf1, lower_limit=-1))
|
| 88 |
+
raises(ValueError, lambda: step_response_plot(tf1, lower_limit=-0.1))
|
| 89 |
+
raises(ValueError, lambda: ramp_response_plot(tf1, lower_limit=-4/3))
|
| 90 |
+
|
| 91 |
+
# slope in ramp_response_plot() is negative
|
| 92 |
+
raises(ValueError, lambda: ramp_response_plot(tf1, slope=-0.1))
|
| 93 |
+
|
| 94 |
+
# incorrect frequency or phase unit
|
| 95 |
+
raises(ValueError, lambda: bode_plot(tf1,freq_unit = 'hz'))
|
| 96 |
+
raises(ValueError, lambda: bode_plot(tf1,phase_unit = 'degree'))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_pole_zero():
|
| 100 |
+
if not numpy:
|
| 101 |
+
skip("NumPy is required for this test")
|
| 102 |
+
|
| 103 |
+
def pz_tester(sys, expected_value):
|
| 104 |
+
z, p = pole_zero_numerical_data(sys)
|
| 105 |
+
z_check = numpy.allclose(z, expected_value[0])
|
| 106 |
+
p_check = numpy.allclose(p, expected_value[1])
|
| 107 |
+
return p_check and z_check
|
| 108 |
+
|
| 109 |
+
exp1 = [[], [-0.24999999999999994+1.3919410907075054j, -0.24999999999999994-1.3919410907075054j]]
|
| 110 |
+
exp2 = [[0.0], [-0.25+0.3227486121839514j, -0.25-0.3227486121839514j]]
|
| 111 |
+
exp3 = [[0.0], [-0.5000000000000004+0.8660254037844395j,
|
| 112 |
+
-0.5000000000000004-0.8660254037844395j, 0.9999999999999998+0j]]
|
| 113 |
+
exp4 = [[], [5.0, 0.0, 0.0, 0.0]]
|
| 114 |
+
exp5 = [[-5.645751311064592, -0.5000000000000008, -0.3542486889354093],
|
| 115 |
+
[-0.24999999999999986+1.3919410907075052j,
|
| 116 |
+
-0.24999999999999986-1.3919410907075052j, -0.2499999999999998+0.32274861218395134j,
|
| 117 |
+
-0.2499999999999998-0.32274861218395134j]]
|
| 118 |
+
exp6 = [[], [-1.1641600331447917-3.545808351896439j,
|
| 119 |
+
-0.8358399668552097+2.5458083518964383j]]
|
| 120 |
+
|
| 121 |
+
assert pz_tester(tf1, exp1)
|
| 122 |
+
assert pz_tester(tf2, exp2)
|
| 123 |
+
assert pz_tester(tf3, exp3)
|
| 124 |
+
assert pz_tester(ser1, exp4)
|
| 125 |
+
assert pz_tester(par1, exp5)
|
| 126 |
+
assert pz_tester(tf8, exp6)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_bode():
|
| 130 |
+
if not numpy:
|
| 131 |
+
skip("NumPy is required for this test")
|
| 132 |
+
|
| 133 |
+
def bode_phase_evalf(system, point):
|
| 134 |
+
expr = system.to_expr()
|
| 135 |
+
_w = Dummy("w", real=True)
|
| 136 |
+
w_expr = expr.subs({system.var: I*_w})
|
| 137 |
+
return arg(w_expr).subs({_w: point}).evalf()
|
| 138 |
+
|
| 139 |
+
def bode_mag_evalf(system, point):
|
| 140 |
+
expr = system.to_expr()
|
| 141 |
+
_w = Dummy("w", real=True)
|
| 142 |
+
w_expr = expr.subs({system.var: I*_w})
|
| 143 |
+
return 20*log(Abs(w_expr), 10).subs({_w: point}).evalf()
|
| 144 |
+
|
| 145 |
+
def test_bode_data(sys):
|
| 146 |
+
return y_coordinate_equality(bode_magnitude_numerical_data, bode_mag_evalf, sys) \
|
| 147 |
+
and y_coordinate_equality(bode_phase_numerical_data, bode_phase_evalf, sys)
|
| 148 |
+
|
| 149 |
+
assert test_bode_data(tf1)
|
| 150 |
+
assert test_bode_data(tf2)
|
| 151 |
+
assert test_bode_data(tf3)
|
| 152 |
+
assert test_bode_data(tf4)
|
| 153 |
+
assert test_bode_data(tf5)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def check_point_accuracy(a, b):
|
| 157 |
+
return all(isclose(*_, rel_tol=1e-1, abs_tol=1e-6
|
| 158 |
+
) for _ in zip(a, b))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_impulse_response():
|
| 162 |
+
if not numpy:
|
| 163 |
+
skip("NumPy is required for this test")
|
| 164 |
+
|
| 165 |
+
def impulse_res_tester(sys, expected_value):
|
| 166 |
+
x, y = _to_tuple(*impulse_response_numerical_data(sys,
|
| 167 |
+
adaptive=False, n=10))
|
| 168 |
+
x_check = check_point_accuracy(x, expected_value[0])
|
| 169 |
+
y_check = check_point_accuracy(y, expected_value[1])
|
| 170 |
+
return x_check and y_check
|
| 171 |
+
|
| 172 |
+
exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 173 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 174 |
+
(0.0, 0.544019738507865, 0.01993849743234938, -0.31140243360893216, -0.022852779906491996, 0.1778306498155759,
|
| 175 |
+
0.01962941084328499, -0.1013115194573652, -0.014975541213105696, 0.0575789724730714))
|
| 176 |
+
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
|
| 177 |
+
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.1666666675, 0.08389223412935855,
|
| 178 |
+
0.02338051973475047, -0.014966807776379383, -0.034645954223054234, -0.040560075735512804,
|
| 179 |
+
-0.037658628907103885, -0.030149507719590022, -0.021162090730736834, -0.012721292737437523))
|
| 180 |
+
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
|
| 181 |
+
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (4.369893391586999e-09, 1.1750333000630964,
|
| 182 |
+
3.2922404058312473, 9.432290008148343, 28.37098083007151, 86.18577464367974, 261.90356653762115,
|
| 183 |
+
795.6538758627842, 2416.9920942096983, 7342.159505206647))
|
| 184 |
+
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
|
| 185 |
+
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 6.17283950617284, 24.69135802469136,
|
| 186 |
+
55.555555555555564, 98.76543209876544, 154.320987654321, 222.22222222222226, 302.46913580246917,
|
| 187 |
+
395.0617283950618, 500.0))
|
| 188 |
+
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
|
| 189 |
+
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, -0.10455606138085417,
|
| 190 |
+
0.06757671513476461, -0.03234567568833768, 0.013582514927757873, -0.005273419510705473,
|
| 191 |
+
0.0019364083003354075, -0.000680070134067832, 0.00022969845960406913, -7.476094359583917e-05))
|
| 192 |
+
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 193 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 194 |
+
(-6.016699583000218e-09, 0.35039802056107394, 3.3728423827689884, 12.119846079276684,
|
| 195 |
+
25.86101014293389, 29.352480635282088, -30.49475907497664, -273.8717189554019, -863.2381702029659,
|
| 196 |
+
-1747.0262164682233))
|
| 197 |
+
exp7 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335,
|
| 198 |
+
4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779,
|
| 199 |
+
8.88888888888889, 10.0), (0.0, 18.934638095560974, 5346.93244680907, 1384609.8718249386,
|
| 200 |
+
358161126.65801865, 92645770015.70108, 23964739753087.42, 6198974342083139.0, 1.603492601616059e+18,
|
| 201 |
+
4.147764422869658e+20))
|
| 202 |
+
|
| 203 |
+
assert impulse_res_tester(tf1, exp1)
|
| 204 |
+
assert impulse_res_tester(tf2, exp2)
|
| 205 |
+
assert impulse_res_tester(tf3, exp3)
|
| 206 |
+
assert impulse_res_tester(tf4, exp4)
|
| 207 |
+
assert impulse_res_tester(tf5, exp5)
|
| 208 |
+
assert impulse_res_tester(tf7, exp6)
|
| 209 |
+
assert impulse_res_tester(ser1, exp7)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def test_step_response():
|
| 213 |
+
if not numpy:
|
| 214 |
+
skip("NumPy is required for this test")
|
| 215 |
+
|
| 216 |
+
def step_res_tester(sys, expected_value):
|
| 217 |
+
x, y = _to_tuple(*step_response_numerical_data(sys,
|
| 218 |
+
adaptive=False, n=10))
|
| 219 |
+
x_check = check_point_accuracy(x, expected_value[0])
|
| 220 |
+
y_check = check_point_accuracy(y, expected_value[1])
|
| 221 |
+
return x_check and y_check
|
| 222 |
+
|
| 223 |
+
exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 224 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 225 |
+
(-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717,
|
| 226 |
+
0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071,
|
| 227 |
+
0.4486997874319281, 0.4839358435839171))
|
| 228 |
+
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 229 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 230 |
+
(0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073,
|
| 231 |
+
0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221,
|
| 232 |
+
-0.003636420058445484))
|
| 233 |
+
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 234 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 235 |
+
(0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376,
|
| 236 |
+
86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917))
|
| 237 |
+
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 238 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 239 |
+
(0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532,
|
| 240 |
+
493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667))
|
| 241 |
+
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 242 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 243 |
+
(-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518,
|
| 244 |
+
0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325,
|
| 245 |
+
0.49997448824584123, 0.5000039745919259))
|
| 246 |
+
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 247 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 248 |
+
(-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517,
|
| 249 |
+
9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757,
|
| 250 |
+
2447.387582370878))
|
| 251 |
+
|
| 252 |
+
assert step_res_tester(tf1, exp1)
|
| 253 |
+
assert step_res_tester(tf2, exp2)
|
| 254 |
+
assert step_res_tester(tf3, exp3)
|
| 255 |
+
assert step_res_tester(tf4, exp4)
|
| 256 |
+
assert step_res_tester(tf5, exp5)
|
| 257 |
+
assert step_res_tester(ser2, exp6)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def test_ramp_response():
|
| 261 |
+
if not numpy:
|
| 262 |
+
skip("NumPy is required for this test")
|
| 263 |
+
|
| 264 |
+
def ramp_res_tester(sys, num_points, expected_value, slope=1):
|
| 265 |
+
x, y = _to_tuple(*ramp_response_numerical_data(sys,
|
| 266 |
+
slope=slope, adaptive=False, n=num_points))
|
| 267 |
+
x_check = check_point_accuracy(x, expected_value[0])
|
| 268 |
+
y_check = check_point_accuracy(y, expected_value[1])
|
| 269 |
+
return x_check and y_check
|
| 270 |
+
|
| 271 |
+
exp1 = ((0.0, 2.0, 4.0, 6.0, 8.0, 10.0), (0.0, 0.7324667795033895, 1.9909720978650398,
|
| 272 |
+
2.7956587704217783, 3.9224897567931514, 4.85022655284895))
|
| 273 |
+
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
|
| 274 |
+
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
|
| 275 |
+
(2.4360213402019326e-08, 0.10175320182493253, 0.33057612497658406, 0.5967937263298935,
|
| 276 |
+
0.8431511866718248, 1.0398805391471613, 1.1776043125035738, 1.2600994825747305, 1.2981042689274653,
|
| 277 |
+
1.304684417610106))
|
| 278 |
+
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
|
| 279 |
+
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.9329040468771836e-08,
|
| 280 |
+
0.34686634635794555, 2.9998828170537903, 12.33303690737476, 40.993913948137795, 127.84145222317912,
|
| 281 |
+
391.41713691996, 1192.0006858708389, 3623.9808672503405, 11011.728034546572))
|
| 282 |
+
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
|
| 283 |
+
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.9051973784484078, 30.483158055174524,
|
| 284 |
+
154.32098765432104, 487.7305288827924, 1190.7483615302544, 2469.1358024691367, 4574.3789056546275,
|
| 285 |
+
7803.688462124678, 12500.0))
|
| 286 |
+
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
|
| 287 |
+
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 3.8844361856975635, 9.141792069209865,
|
| 288 |
+
14.096349157657231, 19.09783068994694, 24.10179770390321, 29.09907319114121, 34.10040420185154,
|
| 289 |
+
39.09983919254265, 44.10006013058409))
|
| 290 |
+
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
|
| 291 |
+
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.1111111111111112, 2.2222222222222223,
|
| 292 |
+
3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0))
|
| 293 |
+
|
| 294 |
+
assert ramp_res_tester(tf1, 6, exp1)
|
| 295 |
+
assert ramp_res_tester(tf2, 10, exp2, 1.2)
|
| 296 |
+
assert ramp_res_tester(tf3, 10, exp3, 1.5)
|
| 297 |
+
assert ramp_res_tester(tf4, 10, exp4, 3)
|
| 298 |
+
assert ramp_res_tester(tf5, 10, exp5, 9)
|
| 299 |
+
assert ramp_res_tester(tf6, 10, exp6)
|
wemm/lib/python3.10/site-packages/sympy/physics/control/tests/test_lti.py
ADDED
|
@@ -0,0 +1,1750 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.add import Add
|
| 2 |
+
from sympy.core.function import Function
|
| 3 |
+
from sympy.core.mul import Mul
|
| 4 |
+
from sympy.core.numbers import (I, pi, Rational, oo)
|
| 5 |
+
from sympy.core.power import Pow
|
| 6 |
+
from sympy.core.singleton import S
|
| 7 |
+
from sympy.core.symbol import symbols
|
| 8 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 10 |
+
from sympy.functions.elementary.trigonometric import atan
|
| 11 |
+
from sympy.matrices.dense import eye
|
| 12 |
+
from sympy.polys.polytools import factor
|
| 13 |
+
from sympy.polys.rootoftools import CRootOf
|
| 14 |
+
from sympy.simplify.simplify import simplify
|
| 15 |
+
from sympy.core.containers import Tuple
|
| 16 |
+
from sympy.matrices import ImmutableMatrix, Matrix, ShapeError
|
| 17 |
+
from sympy.physics.control import (TransferFunction, Series, Parallel,
|
| 18 |
+
Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback,
|
| 19 |
+
StateSpace, gbt, bilinear, forward_diff, backward_diff, phase_margin, gain_margin)
|
| 20 |
+
from sympy.testing.pytest import raises
|
| 21 |
+
|
| 22 |
+
a, x, b, c, s, g, d, p, k, tau, zeta, wn, T = symbols('a, x, b, c, s, g, d, p, k,\
|
| 23 |
+
tau, zeta, wn, T')
|
| 24 |
+
a0, a1, a2, a3, b0, b1, b2, b3, c0, c1, c2, c3, d0, d1, d2, d3 = symbols('a0:4,\
|
| 25 |
+
b0:4, c0:4, d0:4')
|
| 26 |
+
TF1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
|
| 27 |
+
TF2 = TransferFunction(k, 1, s)
|
| 28 |
+
TF3 = TransferFunction(a2*p - s, a2*s + p, s)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_TransferFunction_construction():
|
| 32 |
+
tf = TransferFunction(s + 1, s**2 + s + 1, s)
|
| 33 |
+
assert tf.num == (s + 1)
|
| 34 |
+
assert tf.den == (s**2 + s + 1)
|
| 35 |
+
assert tf.args == (s + 1, s**2 + s + 1, s)
|
| 36 |
+
|
| 37 |
+
tf1 = TransferFunction(s + 4, s - 5, s)
|
| 38 |
+
assert tf1.num == (s + 4)
|
| 39 |
+
assert tf1.den == (s - 5)
|
| 40 |
+
assert tf1.args == (s + 4, s - 5, s)
|
| 41 |
+
|
| 42 |
+
# using different polynomial variables.
|
| 43 |
+
tf2 = TransferFunction(p + 3, p**2 - 9, p)
|
| 44 |
+
assert tf2.num == (p + 3)
|
| 45 |
+
assert tf2.den == (p**2 - 9)
|
| 46 |
+
assert tf2.args == (p + 3, p**2 - 9, p)
|
| 47 |
+
|
| 48 |
+
tf3 = TransferFunction(p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
|
| 49 |
+
assert tf3.args == (p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
|
| 50 |
+
|
| 51 |
+
# no pole-zero cancellation on its own.
|
| 52 |
+
tf4 = TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)
|
| 53 |
+
assert tf4.den == (s - 1)*(s + 5)
|
| 54 |
+
assert tf4.args == ((s + 3)*(s - 1), (s - 1)*(s + 5), s)
|
| 55 |
+
|
| 56 |
+
tf4_ = TransferFunction(p + 2, p + 2, p)
|
| 57 |
+
assert tf4_.args == (p + 2, p + 2, p)
|
| 58 |
+
|
| 59 |
+
tf5 = TransferFunction(s - 1, 4 - p, s)
|
| 60 |
+
assert tf5.args == (s - 1, 4 - p, s)
|
| 61 |
+
|
| 62 |
+
tf5_ = TransferFunction(s - 1, s - 1, s)
|
| 63 |
+
assert tf5_.args == (s - 1, s - 1, s)
|
| 64 |
+
|
| 65 |
+
tf6 = TransferFunction(5, 6, s)
|
| 66 |
+
assert tf6.num == 5
|
| 67 |
+
assert tf6.den == 6
|
| 68 |
+
assert tf6.args == (5, 6, s)
|
| 69 |
+
|
| 70 |
+
tf6_ = TransferFunction(1/2, 4, s)
|
| 71 |
+
assert tf6_.num == 0.5
|
| 72 |
+
assert tf6_.den == 4
|
| 73 |
+
assert tf6_.args == (0.500000000000000, 4, s)
|
| 74 |
+
|
| 75 |
+
tf7 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, s)
|
| 76 |
+
tf8 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, p)
|
| 77 |
+
assert not tf7 == tf8
|
| 78 |
+
|
| 79 |
+
tf7_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
|
| 80 |
+
tf8_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
|
| 81 |
+
assert tf7_ == tf8_
|
| 82 |
+
assert -(-tf7_) == tf7_ == -(-(-(-tf7_)))
|
| 83 |
+
|
| 84 |
+
tf9 = TransferFunction(a*s**3 + b*s**2 + g*s + d, d*p + g*p**2 + g*s, s)
|
| 85 |
+
assert tf9.args == (a*s**3 + b*s**2 + d + g*s, d*p + g*p**2 + g*s, s)
|
| 86 |
+
|
| 87 |
+
tf10 = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
|
| 88 |
+
tf10_ = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
|
| 89 |
+
assert tf10.args == (d + p**3, a + d*s + g*s**2, p)
|
| 90 |
+
assert tf10_ == tf10
|
| 91 |
+
|
| 92 |
+
tf11 = TransferFunction(a1*s + a0, b2*s**2 + b1*s + b0, s)
|
| 93 |
+
assert tf11.num == (a0 + a1*s)
|
| 94 |
+
assert tf11.den == (b0 + b1*s + b2*s**2)
|
| 95 |
+
assert tf11.args == (a0 + a1*s, b0 + b1*s + b2*s**2, s)
|
| 96 |
+
|
| 97 |
+
# when just the numerator is 0, leave the denominator alone.
|
| 98 |
+
tf12 = TransferFunction(0, p**2 - p + 1, p)
|
| 99 |
+
assert tf12.args == (0, p**2 - p + 1, p)
|
| 100 |
+
|
| 101 |
+
tf13 = TransferFunction(0, 1, s)
|
| 102 |
+
assert tf13.args == (0, 1, s)
|
| 103 |
+
|
| 104 |
+
# float exponents
|
| 105 |
+
tf14 = TransferFunction(a0*s**0.5 + a2*s**0.6 - a1, a1*p**(-8.7), s)
|
| 106 |
+
assert tf14.args == (a0*s**0.5 - a1 + a2*s**0.6, a1*p**(-8.7), s)
|
| 107 |
+
|
| 108 |
+
tf15 = TransferFunction(a2**2*p**(1/4) + a1*s**(-4/5), a0*s - p, p)
|
| 109 |
+
assert tf15.args == (a1*s**(-0.8) + a2**2*p**0.25, a0*s - p, p)
|
| 110 |
+
|
| 111 |
+
omega_o, k_p, k_o, k_i = symbols('omega_o, k_p, k_o, k_i')
|
| 112 |
+
tf18 = TransferFunction((k_p + k_o*s + k_i/s), s**2 + 2*omega_o*s + omega_o**2, s)
|
| 113 |
+
assert tf18.num == k_i/s + k_o*s + k_p
|
| 114 |
+
assert tf18.args == (k_i/s + k_o*s + k_p, omega_o**2 + 2*omega_o*s + s**2, s)
|
| 115 |
+
|
| 116 |
+
# ValueError when denominator is zero.
|
| 117 |
+
raises(ValueError, lambda: TransferFunction(4, 0, s))
|
| 118 |
+
raises(ValueError, lambda: TransferFunction(s, 0, s))
|
| 119 |
+
raises(ValueError, lambda: TransferFunction(0, 0, s))
|
| 120 |
+
|
| 121 |
+
raises(TypeError, lambda: TransferFunction(Matrix([1, 2, 3]), s, s))
|
| 122 |
+
|
| 123 |
+
raises(TypeError, lambda: TransferFunction(s**2 + 2*s - 1, s + 3, 3))
|
| 124 |
+
raises(TypeError, lambda: TransferFunction(p + 1, 5 - p, 4))
|
| 125 |
+
raises(TypeError, lambda: TransferFunction(3, 4, 8))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_TransferFunction_functions():
|
| 129 |
+
# classmethod from_rational_expression
|
| 130 |
+
expr_1 = Mul(0, Pow(s, -1, evaluate=False), evaluate=False)
|
| 131 |
+
expr_2 = s/0
|
| 132 |
+
expr_3 = (p*s**2 + 5*s)/(s + 1)**3
|
| 133 |
+
expr_4 = 6
|
| 134 |
+
expr_5 = ((2 + 3*s)*(5 + 2*s))/((9 + 3*s)*(5 + 2*s**2))
|
| 135 |
+
expr_6 = (9*s**4 + 4*s**2 + 8)/((s + 1)*(s + 9))
|
| 136 |
+
tf = TransferFunction(s + 1, s**2 + 2, s)
|
| 137 |
+
delay = exp(-s/tau)
|
| 138 |
+
expr_7 = delay*tf.to_expr()
|
| 139 |
+
H1 = TransferFunction.from_rational_expression(expr_7, s)
|
| 140 |
+
H2 = TransferFunction(s + 1, (s**2 + 2)*exp(s/tau), s)
|
| 141 |
+
expr_8 = Add(2, 3*s/(s**2 + 1), evaluate=False)
|
| 142 |
+
|
| 143 |
+
assert TransferFunction.from_rational_expression(expr_1) == TransferFunction(0, s, s)
|
| 144 |
+
raises(ZeroDivisionError, lambda: TransferFunction.from_rational_expression(expr_2))
|
| 145 |
+
raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_3))
|
| 146 |
+
assert TransferFunction.from_rational_expression(expr_3, s) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, s)
|
| 147 |
+
assert TransferFunction.from_rational_expression(expr_3, p) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, p)
|
| 148 |
+
raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_4))
|
| 149 |
+
assert TransferFunction.from_rational_expression(expr_4, s) == TransferFunction(6, 1, s)
|
| 150 |
+
assert TransferFunction.from_rational_expression(expr_5, s) == \
|
| 151 |
+
TransferFunction((2 + 3*s)*(5 + 2*s), (9 + 3*s)*(5 + 2*s**2), s)
|
| 152 |
+
assert TransferFunction.from_rational_expression(expr_6, s) == \
|
| 153 |
+
TransferFunction((9*s**4 + 4*s**2 + 8), (s + 1)*(s + 9), s)
|
| 154 |
+
assert H1 == H2
|
| 155 |
+
assert TransferFunction.from_rational_expression(expr_8, s) == \
|
| 156 |
+
TransferFunction(2*s**2 + 3*s + 2, s**2 + 1, s)
|
| 157 |
+
|
| 158 |
+
# classmethod from_coeff_lists
|
| 159 |
+
tf1 = TransferFunction.from_coeff_lists([1, 2], [3, 4, 5], s)
|
| 160 |
+
num2 = [p**2, 2*p]
|
| 161 |
+
den2 = [p**3, p + 1, 4]
|
| 162 |
+
tf2 = TransferFunction.from_coeff_lists(num2, den2, s)
|
| 163 |
+
num3 = [1, 2, 3]
|
| 164 |
+
den3 = [0, 0]
|
| 165 |
+
|
| 166 |
+
assert tf1 == TransferFunction(s + 2, 3*s**2 + 4*s + 5, s)
|
| 167 |
+
assert tf2 == TransferFunction(p**2*s + 2*p, p**3*s**2 + s*(p + 1) + 4, s)
|
| 168 |
+
raises(ZeroDivisionError, lambda: TransferFunction.from_coeff_lists(num3, den3, s))
|
| 169 |
+
|
| 170 |
+
# classmethod from_zpk
|
| 171 |
+
zeros = [4]
|
| 172 |
+
poles = [-1+2j, -1-2j]
|
| 173 |
+
gain = 3
|
| 174 |
+
tf1 = TransferFunction.from_zpk(zeros, poles, gain, s)
|
| 175 |
+
|
| 176 |
+
assert tf1 == TransferFunction(3*s - 12, (s + 1.0 - 2.0*I)*(s + 1.0 + 2.0*I), s)
|
| 177 |
+
|
| 178 |
+
# explicitly cancel poles and zeros.
|
| 179 |
+
tf0 = TransferFunction(s**5 + s**3 + s, s - s**2, s)
|
| 180 |
+
a = TransferFunction(-(s**4 + s**2 + 1), s - 1, s)
|
| 181 |
+
assert tf0.simplify() == simplify(tf0) == a
|
| 182 |
+
|
| 183 |
+
tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
|
| 184 |
+
b = TransferFunction(p + 3, p + 5, p)
|
| 185 |
+
assert tf1.simplify() == simplify(tf1) == b
|
| 186 |
+
|
| 187 |
+
# expand the numerator and the denominator.
|
| 188 |
+
G1 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
|
| 189 |
+
G2 = TransferFunction(1, -3, p)
|
| 190 |
+
c = (a2*s**p + a1*s**s + a0*p**p)*(p**s + s**p)
|
| 191 |
+
d = (b0*s**s + b1*p**s)*(b2*s*p + p**p)
|
| 192 |
+
e = a0*p**p*p**s + a0*p**p*s**p + a1*p**s*s**s + a1*s**p*s**s + a2*p**s*s**p + a2*s**(2*p)
|
| 193 |
+
f = b0*b2*p*s*s**s + b0*p**p*s**s + b1*b2*p*p**s*s + b1*p**p*p**s
|
| 194 |
+
g = a1*a2*s*s**p + a1*p*s + a2*b1*p*s*s**p + b1*p**2*s
|
| 195 |
+
G3 = TransferFunction(c, d, s)
|
| 196 |
+
G4 = TransferFunction(a0*s**s - b0*p**p, (a1*s + b1*s*p)*(a2*s**p + p), p)
|
| 197 |
+
|
| 198 |
+
assert G1.expand() == TransferFunction(s**2 - 2*s + 1, s**4 + 2*s**2 + 1, s)
|
| 199 |
+
assert tf1.expand() == TransferFunction(p**2 + 2*p - 3, p**2 + 4*p - 5, p)
|
| 200 |
+
assert G2.expand() == G2
|
| 201 |
+
assert G3.expand() == TransferFunction(e, f, s)
|
| 202 |
+
assert G4.expand() == TransferFunction(a0*s**s - b0*p**p, g, p)
|
| 203 |
+
|
| 204 |
+
# purely symbolic polynomials.
|
| 205 |
+
p1 = a1*s + a0
|
| 206 |
+
p2 = b2*s**2 + b1*s + b0
|
| 207 |
+
SP1 = TransferFunction(p1, p2, s)
|
| 208 |
+
expect1 = TransferFunction(2.0*s + 1.0, 5.0*s**2 + 4.0*s + 3.0, s)
|
| 209 |
+
expect1_ = TransferFunction(2*s + 1, 5*s**2 + 4*s + 3, s)
|
| 210 |
+
assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect1_
|
| 211 |
+
assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect1
|
| 212 |
+
assert expect1_.evalf() == expect1
|
| 213 |
+
|
| 214 |
+
c1, d0, d1, d2 = symbols('c1, d0:3')
|
| 215 |
+
p3, p4 = c1*p, d2*p**3 + d1*p**2 - d0
|
| 216 |
+
SP2 = TransferFunction(p3, p4, p)
|
| 217 |
+
expect2 = TransferFunction(2.0*p, 5.0*p**3 + 2.0*p**2 - 3.0, p)
|
| 218 |
+
expect2_ = TransferFunction(2*p, 5*p**3 + 2*p**2 - 3, p)
|
| 219 |
+
assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}) == expect2_
|
| 220 |
+
assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}).evalf() == expect2
|
| 221 |
+
assert expect2_.evalf() == expect2
|
| 222 |
+
|
| 223 |
+
SP3 = TransferFunction(a0*p**3 + a1*s**2 - b0*s + b1, a1*s + p, s)
|
| 224 |
+
expect3 = TransferFunction(2.0*p**3 + 4.0*s**2 - s + 5.0, p + 4.0*s, s)
|
| 225 |
+
expect3_ = TransferFunction(2*p**3 + 4*s**2 - s + 5, p + 4*s, s)
|
| 226 |
+
assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}) == expect3_
|
| 227 |
+
assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}).evalf() == expect3
|
| 228 |
+
assert expect3_.evalf() == expect3
|
| 229 |
+
|
| 230 |
+
SP4 = TransferFunction(s - a1*p**3, a0*s + p, p)
|
| 231 |
+
expect4 = TransferFunction(7.0*p**3 + s, p - s, p)
|
| 232 |
+
expect4_ = TransferFunction(7*p**3 + s, p - s, p)
|
| 233 |
+
assert SP4.subs({a0: -1, a1: -7}) == expect4_
|
| 234 |
+
assert SP4.subs({a0: -1, a1: -7}).evalf() == expect4
|
| 235 |
+
assert expect4_.evalf() == expect4
|
| 236 |
+
|
| 237 |
+
# evaluate the transfer function at particular frequencies.
|
| 238 |
+
assert tf1.eval_frequency(wn) == wn**2/(wn**2 + 4*wn - 5) + 2*wn/(wn**2 + 4*wn - 5) - 3/(wn**2 + 4*wn - 5)
|
| 239 |
+
assert G1.eval_frequency(1 + I) == S(3)/25 + S(4)*I/25
|
| 240 |
+
assert G4.eval_frequency(S(5)/3) == \
|
| 241 |
+
a0*s**s/(a1*a2*s**(S(8)/3) + S(5)*a1*s/3 + 5*a2*b1*s**(S(8)/3)/3 + S(25)*b1*s/9) - 5*3**(S(1)/3)*5**(S(2)/3)*b0/(9*a1*a2*s**(S(8)/3) + 15*a1*s + 15*a2*b1*s**(S(8)/3) + 25*b1*s)
|
| 242 |
+
|
| 243 |
+
# Low-frequency (or DC) gain.
|
| 244 |
+
assert tf0.dc_gain() == 1
|
| 245 |
+
assert tf1.dc_gain() == Rational(3, 5)
|
| 246 |
+
assert SP2.dc_gain() == 0
|
| 247 |
+
assert expect4.dc_gain() == -1
|
| 248 |
+
assert expect2_.dc_gain() == 0
|
| 249 |
+
assert TransferFunction(1, s, s).dc_gain() == oo
|
| 250 |
+
|
| 251 |
+
# Poles of a transfer function.
|
| 252 |
+
tf_ = TransferFunction(x**3 - k, k, x)
|
| 253 |
+
_tf = TransferFunction(k, x**4 - k, x)
|
| 254 |
+
TF_ = TransferFunction(x**2, x**10 + x + x**2, x)
|
| 255 |
+
_TF = TransferFunction(x**10 + x + x**2, x**2, x)
|
| 256 |
+
assert G1.poles() == [I, I, -I, -I]
|
| 257 |
+
assert G2.poles() == []
|
| 258 |
+
assert tf1.poles() == [-5, 1]
|
| 259 |
+
assert expect4_.poles() == [s]
|
| 260 |
+
assert SP4.poles() == [-a0*s]
|
| 261 |
+
assert expect3.poles() == [-0.25*p]
|
| 262 |
+
assert str(expect2.poles()) == str([0.729001428685125, -0.564500714342563 - 0.710198984796332*I, -0.564500714342563 + 0.710198984796332*I])
|
| 263 |
+
assert str(expect1.poles()) == str([-0.4 - 0.66332495807108*I, -0.4 + 0.66332495807108*I])
|
| 264 |
+
assert _tf.poles() == [k**(Rational(1, 4)), -k**(Rational(1, 4)), I*k**(Rational(1, 4)), -I*k**(Rational(1, 4))]
|
| 265 |
+
assert TF_.poles() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
|
| 266 |
+
CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
|
| 267 |
+
CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
|
| 268 |
+
raises(NotImplementedError, lambda: TransferFunction(x**2, a0*x**10 + x + x**2, x).poles())
|
| 269 |
+
|
| 270 |
+
# Stability of a transfer function.
|
| 271 |
+
q, r = symbols('q, r', negative=True)
|
| 272 |
+
t = symbols('t', positive=True)
|
| 273 |
+
TF_ = TransferFunction(s**2 + a0 - a1*p, q*s - r, s)
|
| 274 |
+
stable_tf = TransferFunction(s**2 + a0 - a1*p, q*s - 1, s)
|
| 275 |
+
stable_tf_ = TransferFunction(s**2 + a0 - a1*p, q*s - t, s)
|
| 276 |
+
|
| 277 |
+
assert G1.is_stable() is False
|
| 278 |
+
assert G2.is_stable() is True
|
| 279 |
+
assert tf1.is_stable() is False # as one pole is +ve, and the other is -ve.
|
| 280 |
+
assert expect2.is_stable() is False
|
| 281 |
+
assert expect1.is_stable() is True
|
| 282 |
+
assert stable_tf.is_stable() is True
|
| 283 |
+
assert stable_tf_.is_stable() is True
|
| 284 |
+
assert TF_.is_stable() is False
|
| 285 |
+
assert expect4_.is_stable() is None # no assumption provided for the only pole 's'.
|
| 286 |
+
assert SP4.is_stable() is None
|
| 287 |
+
|
| 288 |
+
# Zeros of a transfer function.
|
| 289 |
+
assert G1.zeros() == [1, 1]
|
| 290 |
+
assert G2.zeros() == []
|
| 291 |
+
assert tf1.zeros() == [-3, 1]
|
| 292 |
+
assert expect4_.zeros() == [7**(Rational(2, 3))*(-s)**(Rational(1, 3))/7, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 -
|
| 293 |
+
sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 + sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14]
|
| 294 |
+
assert SP4.zeros() == [(s/a1)**(Rational(1, 3)), -(s/a1)**(Rational(1, 3))/2 - sqrt(3)*I*(s/a1)**(Rational(1, 3))/2,
|
| 295 |
+
-(s/a1)**(Rational(1, 3))/2 + sqrt(3)*I*(s/a1)**(Rational(1, 3))/2]
|
| 296 |
+
assert str(expect3.zeros()) == str([0.125 - 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0),
|
| 297 |
+
1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0) + 0.125])
|
| 298 |
+
assert tf_.zeros() == [k**(Rational(1, 3)), -k**(Rational(1, 3))/2 - sqrt(3)*I*k**(Rational(1, 3))/2,
|
| 299 |
+
-k**(Rational(1, 3))/2 + sqrt(3)*I*k**(Rational(1, 3))/2]
|
| 300 |
+
assert _TF.zeros() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
|
| 301 |
+
CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
|
| 302 |
+
CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
|
| 303 |
+
raises(NotImplementedError, lambda: TransferFunction(a0*x**10 + x + x**2, x**2, x).zeros())
|
| 304 |
+
|
| 305 |
+
# negation of TF.
|
| 306 |
+
tf2 = TransferFunction(s + 3, s**2 - s**3 + 9, s)
|
| 307 |
+
tf3 = TransferFunction(-3*p + 3, 1 - p, p)
|
| 308 |
+
assert -tf2 == TransferFunction(-s - 3, s**2 - s**3 + 9, s)
|
| 309 |
+
assert -tf3 == TransferFunction(3*p - 3, 1 - p, p)
|
| 310 |
+
|
| 311 |
+
# taking power of a TF.
|
| 312 |
+
tf4 = TransferFunction(p + 4, p - 3, p)
|
| 313 |
+
tf5 = TransferFunction(s**2 + 1, 1 - s, s)
|
| 314 |
+
expect2 = TransferFunction((s**2 + 1)**3, (1 - s)**3, s)
|
| 315 |
+
expect1 = TransferFunction((p + 4)**2, (p - 3)**2, p)
|
| 316 |
+
assert (tf4*tf4).doit() == tf4**2 == pow(tf4, 2) == expect1
|
| 317 |
+
assert (tf5*tf5*tf5).doit() == tf5**3 == pow(tf5, 3) == expect2
|
| 318 |
+
assert tf5**0 == pow(tf5, 0) == TransferFunction(1, 1, s)
|
| 319 |
+
assert Series(tf4).doit()**-1 == tf4**-1 == pow(tf4, -1) == TransferFunction(p - 3, p + 4, p)
|
| 320 |
+
assert (tf5*tf5).doit()**-1 == tf5**-2 == pow(tf5, -2) == TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
|
| 321 |
+
|
| 322 |
+
raises(ValueError, lambda: tf4**(s**2 + s - 1))
|
| 323 |
+
raises(ValueError, lambda: tf5**s)
|
| 324 |
+
raises(ValueError, lambda: tf4**tf5)
|
| 325 |
+
|
| 326 |
+
# SymPy's own functions.
|
| 327 |
+
tf = TransferFunction(s - 1, s**2 - 2*s + 1, s)
|
| 328 |
+
tf6 = TransferFunction(s + p, p**2 - 5, s)
|
| 329 |
+
assert factor(tf) == TransferFunction(s - 1, (s - 1)**2, s)
|
| 330 |
+
assert tf.num.subs(s, 2) == tf.den.subs(s, 2) == 1
|
| 331 |
+
# subs & xreplace
|
| 332 |
+
assert tf.subs(s, 2) == TransferFunction(s - 1, s**2 - 2*s + 1, s)
|
| 333 |
+
assert tf6.subs(p, 3) == TransferFunction(s + 3, 4, s)
|
| 334 |
+
assert tf3.xreplace({p: s}) == TransferFunction(-3*s + 3, 1 - s, s)
|
| 335 |
+
raises(TypeError, lambda: tf3.xreplace({p: exp(2)}))
|
| 336 |
+
assert tf3.subs(p, exp(2)) == tf3
|
| 337 |
+
|
| 338 |
+
tf7 = TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
|
| 339 |
+
assert tf7.xreplace({s: k}) == TransferFunction(a0*k**p + a1*p**k, a2*p - k, k)
|
| 340 |
+
assert tf7.subs(s, k) == TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
|
| 341 |
+
|
| 342 |
+
# Conversion to Expr with to_expr()
|
| 343 |
+
tf8 = TransferFunction(a0*s**5 + 5*s**2 + 3, s**6 - 3, s)
|
| 344 |
+
tf9 = TransferFunction((5 + s), (5 + s)*(6 + s), s)
|
| 345 |
+
tf10 = TransferFunction(0, 1, s)
|
| 346 |
+
tf11 = TransferFunction(1, 1, s)
|
| 347 |
+
assert tf8.to_expr() == Mul((a0*s**5 + 5*s**2 + 3), Pow((s**6 - 3), -1, evaluate=False), evaluate=False)
|
| 348 |
+
assert tf9.to_expr() == Mul((s + 5), Pow((5 + s)*(6 + s), -1, evaluate=False), evaluate=False)
|
| 349 |
+
assert tf10.to_expr() == Mul(S(0), Pow(1, -1, evaluate=False), evaluate=False)
|
| 350 |
+
assert tf11.to_expr() == Pow(1, -1, evaluate=False)
|
| 351 |
+
|
| 352 |
+
def test_TransferFunction_addition_and_subtraction():
|
| 353 |
+
tf1 = TransferFunction(s + 6, s - 5, s)
|
| 354 |
+
tf2 = TransferFunction(s + 3, s + 1, s)
|
| 355 |
+
tf3 = TransferFunction(s + 1, s**2 + s + 1, s)
|
| 356 |
+
tf4 = TransferFunction(p, 2 - p, p)
|
| 357 |
+
|
| 358 |
+
# addition
|
| 359 |
+
assert tf1 + tf2 == Parallel(tf1, tf2)
|
| 360 |
+
assert tf3 + tf1 == Parallel(tf3, tf1)
|
| 361 |
+
assert -tf1 + tf2 + tf3 == Parallel(-tf1, tf2, tf3)
|
| 362 |
+
assert tf1 + (tf2 + tf3) == Parallel(tf1, tf2, tf3)
|
| 363 |
+
|
| 364 |
+
c = symbols("c", commutative=False)
|
| 365 |
+
raises(ValueError, lambda: tf1 + Matrix([1, 2, 3]))
|
| 366 |
+
raises(ValueError, lambda: tf2 + c)
|
| 367 |
+
raises(ValueError, lambda: tf3 + tf4)
|
| 368 |
+
raises(ValueError, lambda: tf1 + (s - 1))
|
| 369 |
+
raises(ValueError, lambda: tf1 + 8)
|
| 370 |
+
raises(ValueError, lambda: (1 - p**3) + tf1)
|
| 371 |
+
|
| 372 |
+
# subtraction
|
| 373 |
+
assert tf1 - tf2 == Parallel(tf1, -tf2)
|
| 374 |
+
assert tf3 - tf2 == Parallel(tf3, -tf2)
|
| 375 |
+
assert -tf1 - tf3 == Parallel(-tf1, -tf3)
|
| 376 |
+
assert tf1 - tf2 + tf3 == Parallel(tf1, -tf2, tf3)
|
| 377 |
+
|
| 378 |
+
raises(ValueError, lambda: tf1 - Matrix([1, 2, 3]))
|
| 379 |
+
raises(ValueError, lambda: tf3 - tf4)
|
| 380 |
+
raises(ValueError, lambda: tf1 - (s - 1))
|
| 381 |
+
raises(ValueError, lambda: tf1 - 8)
|
| 382 |
+
raises(ValueError, lambda: (s + 5) - tf2)
|
| 383 |
+
raises(ValueError, lambda: (1 + p**4) - tf1)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def test_TransferFunction_multiplication_and_division():
|
| 387 |
+
G1 = TransferFunction(s + 3, -s**3 + 9, s)
|
| 388 |
+
G2 = TransferFunction(s + 1, s - 5, s)
|
| 389 |
+
G3 = TransferFunction(p, p**4 - 6, p)
|
| 390 |
+
G4 = TransferFunction(p + 4, p - 5, p)
|
| 391 |
+
G5 = TransferFunction(s + 6, s - 5, s)
|
| 392 |
+
G6 = TransferFunction(s + 3, s + 1, s)
|
| 393 |
+
G7 = TransferFunction(1, 1, s)
|
| 394 |
+
|
| 395 |
+
# multiplication
|
| 396 |
+
assert G1*G2 == Series(G1, G2)
|
| 397 |
+
assert -G1*G5 == Series(-G1, G5)
|
| 398 |
+
assert -G2*G5*-G6 == Series(-G2, G5, -G6)
|
| 399 |
+
assert -G1*-G2*-G5*-G6 == Series(-G1, -G2, -G5, -G6)
|
| 400 |
+
assert G3*G4 == Series(G3, G4)
|
| 401 |
+
assert (G1*G2)*-(G5*G6) == \
|
| 402 |
+
Series(G1, G2, TransferFunction(-1, 1, s), Series(G5, G6))
|
| 403 |
+
assert G1*G2*(G5 + G6) == Series(G1, G2, Parallel(G5, G6))
|
| 404 |
+
|
| 405 |
+
# division - See ``test_Feedback_functions()`` for division by Parallel objects.
|
| 406 |
+
assert G5/G6 == Series(G5, pow(G6, -1))
|
| 407 |
+
assert -G3/G4 == Series(-G3, pow(G4, -1))
|
| 408 |
+
assert (G5*G6)/G7 == Series(G5, G6, pow(G7, -1))
|
| 409 |
+
|
| 410 |
+
c = symbols("c", commutative=False)
|
| 411 |
+
raises(ValueError, lambda: G3 * Matrix([1, 2, 3]))
|
| 412 |
+
raises(ValueError, lambda: G1 * c)
|
| 413 |
+
raises(ValueError, lambda: G3 * G5)
|
| 414 |
+
raises(ValueError, lambda: G5 * (s - 1))
|
| 415 |
+
raises(ValueError, lambda: 9 * G5)
|
| 416 |
+
|
| 417 |
+
raises(ValueError, lambda: G3 / Matrix([1, 2, 3]))
|
| 418 |
+
raises(ValueError, lambda: G6 / 0)
|
| 419 |
+
raises(ValueError, lambda: G3 / G5)
|
| 420 |
+
raises(ValueError, lambda: G5 / 2)
|
| 421 |
+
raises(ValueError, lambda: G5 / s**2)
|
| 422 |
+
raises(ValueError, lambda: (s - 4*s**2) / G2)
|
| 423 |
+
raises(ValueError, lambda: 0 / G4)
|
| 424 |
+
raises(ValueError, lambda: G7 / (1 + G6))
|
| 425 |
+
raises(ValueError, lambda: G7 / (G5 * G6))
|
| 426 |
+
raises(ValueError, lambda: G7 / (G7 + (G5 + G6)))
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def test_TransferFunction_is_proper():
|
| 430 |
+
omega_o, zeta, tau = symbols('omega_o, zeta, tau')
|
| 431 |
+
G1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
|
| 432 |
+
G2 = TransferFunction(tau - s**3, tau + p**4, tau)
|
| 433 |
+
G3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
|
| 434 |
+
G4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
|
| 435 |
+
assert G1.is_proper
|
| 436 |
+
assert G2.is_proper
|
| 437 |
+
assert G3.is_proper
|
| 438 |
+
assert not G4.is_proper
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def test_TransferFunction_is_strictly_proper():
|
| 442 |
+
omega_o, zeta, tau = symbols('omega_o, zeta, tau')
|
| 443 |
+
tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
|
| 444 |
+
tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
|
| 445 |
+
tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
|
| 446 |
+
tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
|
| 447 |
+
assert not tf1.is_strictly_proper
|
| 448 |
+
assert not tf2.is_strictly_proper
|
| 449 |
+
assert tf3.is_strictly_proper
|
| 450 |
+
assert not tf4.is_strictly_proper
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def test_TransferFunction_is_biproper():
|
| 454 |
+
tau, omega_o, zeta = symbols('tau, omega_o, zeta')
|
| 455 |
+
tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
|
| 456 |
+
tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
|
| 457 |
+
tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
|
| 458 |
+
tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
|
| 459 |
+
assert tf1.is_biproper
|
| 460 |
+
assert tf2.is_biproper
|
| 461 |
+
assert not tf3.is_biproper
|
| 462 |
+
assert not tf4.is_biproper
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def test_Series_construction():
|
| 466 |
+
tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
|
| 467 |
+
tf2 = TransferFunction(a2*p - s, a2*s + p, s)
|
| 468 |
+
tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
|
| 469 |
+
tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
|
| 470 |
+
inp = Function('X_d')(s)
|
| 471 |
+
out = Function('X')(s)
|
| 472 |
+
|
| 473 |
+
s0 = Series(tf, tf2)
|
| 474 |
+
assert s0.args == (tf, tf2)
|
| 475 |
+
assert s0.var == s
|
| 476 |
+
|
| 477 |
+
s1 = Series(Parallel(tf, -tf2), tf2)
|
| 478 |
+
assert s1.args == (Parallel(tf, -tf2), tf2)
|
| 479 |
+
assert s1.var == s
|
| 480 |
+
|
| 481 |
+
tf3_ = TransferFunction(inp, 1, s)
|
| 482 |
+
tf4_ = TransferFunction(-out, 1, s)
|
| 483 |
+
s2 = Series(tf, Parallel(tf3_, tf4_), tf2)
|
| 484 |
+
assert s2.args == (tf, Parallel(tf3_, tf4_), tf2)
|
| 485 |
+
|
| 486 |
+
s3 = Series(tf, tf2, tf4)
|
| 487 |
+
assert s3.args == (tf, tf2, tf4)
|
| 488 |
+
|
| 489 |
+
s4 = Series(tf3_, tf4_)
|
| 490 |
+
assert s4.args == (tf3_, tf4_)
|
| 491 |
+
assert s4.var == s
|
| 492 |
+
|
| 493 |
+
s6 = Series(tf2, tf4, Parallel(tf2, -tf), tf4)
|
| 494 |
+
assert s6.args == (tf2, tf4, Parallel(tf2, -tf), tf4)
|
| 495 |
+
|
| 496 |
+
s7 = Series(tf, tf2)
|
| 497 |
+
assert s0 == s7
|
| 498 |
+
assert not s0 == s2
|
| 499 |
+
|
| 500 |
+
raises(ValueError, lambda: Series(tf, tf3))
|
| 501 |
+
raises(ValueError, lambda: Series(tf, tf2, tf3, tf4))
|
| 502 |
+
raises(ValueError, lambda: Series(-tf3, tf2))
|
| 503 |
+
raises(TypeError, lambda: Series(2, tf, tf4))
|
| 504 |
+
raises(TypeError, lambda: Series(s**2 + p*s, tf3, tf2))
|
| 505 |
+
raises(TypeError, lambda: Series(tf3, Matrix([1, 2, 3, 4])))
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def test_MIMOSeries_construction():
|
| 509 |
+
tf_1 = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
|
| 510 |
+
tf_2 = TransferFunction(a2*p - s, a2*s + p, s)
|
| 511 |
+
tf_3 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
|
| 512 |
+
|
| 513 |
+
tfm_1 = TransferFunctionMatrix([[tf_1, tf_2, tf_3], [-tf_3, -tf_2, tf_1]])
|
| 514 |
+
tfm_2 = TransferFunctionMatrix([[-tf_2], [-tf_2], [-tf_3]])
|
| 515 |
+
tfm_3 = TransferFunctionMatrix([[-tf_3]])
|
| 516 |
+
tfm_4 = TransferFunctionMatrix([[TF3], [TF2], [-TF1]])
|
| 517 |
+
tfm_5 = TransferFunctionMatrix.from_Matrix(Matrix([1/p]), p)
|
| 518 |
+
|
| 519 |
+
s8 = MIMOSeries(tfm_2, tfm_1)
|
| 520 |
+
assert s8.args == (tfm_2, tfm_1)
|
| 521 |
+
assert s8.var == s
|
| 522 |
+
assert s8.shape == (s8.num_outputs, s8.num_inputs) == (2, 1)
|
| 523 |
+
|
| 524 |
+
s9 = MIMOSeries(tfm_3, tfm_2, tfm_1)
|
| 525 |
+
assert s9.args == (tfm_3, tfm_2, tfm_1)
|
| 526 |
+
assert s9.var == s
|
| 527 |
+
assert s9.shape == (s9.num_outputs, s9.num_inputs) == (2, 1)
|
| 528 |
+
|
| 529 |
+
s11 = MIMOSeries(tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
|
| 530 |
+
assert s11.args == (tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
|
| 531 |
+
assert s11.shape == (s11.num_outputs, s11.num_inputs) == (2, 1)
|
| 532 |
+
|
| 533 |
+
# arg cannot be empty tuple.
|
| 534 |
+
raises(ValueError, lambda: MIMOSeries())
|
| 535 |
+
|
| 536 |
+
# arg cannot contain SISO as well as MIMO systems.
|
| 537 |
+
raises(TypeError, lambda: MIMOSeries(tfm_1, tf_1))
|
| 538 |
+
|
| 539 |
+
# for all the adjacent transfer function matrices:
|
| 540 |
+
# no. of inputs of first TFM must be equal to the no. of outputs of the second TFM.
|
| 541 |
+
raises(ValueError, lambda: MIMOSeries(tfm_1, tfm_2, -tfm_1))
|
| 542 |
+
|
| 543 |
+
# all the TFMs must use the same complex variable.
|
| 544 |
+
raises(ValueError, lambda: MIMOSeries(tfm_3, tfm_5))
|
| 545 |
+
|
| 546 |
+
# Number or expression not allowed in the arguments.
|
| 547 |
+
raises(TypeError, lambda: MIMOSeries(2, tfm_2, tfm_3))
|
| 548 |
+
raises(TypeError, lambda: MIMOSeries(s**2 + p*s, -tfm_2, tfm_3))
|
| 549 |
+
raises(TypeError, lambda: MIMOSeries(Matrix([1/p]), tfm_3))
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def test_Series_functions():
|
| 553 |
+
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
|
| 554 |
+
tf2 = TransferFunction(k, 1, s)
|
| 555 |
+
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
|
| 556 |
+
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
|
| 557 |
+
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
|
| 558 |
+
|
| 559 |
+
assert tf1*tf2*tf3 == Series(tf1, tf2, tf3) == Series(Series(tf1, tf2), tf3) \
|
| 560 |
+
== Series(tf1, Series(tf2, tf3))
|
| 561 |
+
assert tf1*(tf2 + tf3) == Series(tf1, Parallel(tf2, tf3))
|
| 562 |
+
assert tf1*tf2 + tf5 == Parallel(Series(tf1, tf2), tf5)
|
| 563 |
+
assert tf1*tf2 - tf5 == Parallel(Series(tf1, tf2), -tf5)
|
| 564 |
+
assert tf1*tf2 + tf3 + tf5 == Parallel(Series(tf1, tf2), tf3, tf5)
|
| 565 |
+
assert tf1*tf2 - tf3 - tf5 == Parallel(Series(tf1, tf2), -tf3, -tf5)
|
| 566 |
+
assert tf1*tf2 - tf3 + tf5 == Parallel(Series(tf1, tf2), -tf3, tf5)
|
| 567 |
+
assert tf1*tf2 + tf3*tf5 == Parallel(Series(tf1, tf2), Series(tf3, tf5))
|
| 568 |
+
assert tf1*tf2 - tf3*tf5 == Parallel(Series(tf1, tf2), Series(TransferFunction(-1, 1, s), Series(tf3, tf5)))
|
| 569 |
+
assert tf2*tf3*(tf2 - tf1)*tf3 == Series(tf2, tf3, Parallel(tf2, -tf1), tf3)
|
| 570 |
+
assert -tf1*tf2 == Series(-tf1, tf2)
|
| 571 |
+
assert -(tf1*tf2) == Series(TransferFunction(-1, 1, s), Series(tf1, tf2))
|
| 572 |
+
raises(ValueError, lambda: tf1*tf2*tf4)
|
| 573 |
+
raises(ValueError, lambda: tf1*(tf2 - tf4))
|
| 574 |
+
raises(ValueError, lambda: tf3*Matrix([1, 2, 3]))
|
| 575 |
+
|
| 576 |
+
# evaluate=True -> doit()
|
| 577 |
+
assert Series(tf1, tf2, evaluate=True) == Series(tf1, tf2).doit() == \
|
| 578 |
+
TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
|
| 579 |
+
assert Series(tf1, tf2, Parallel(tf1, -tf3), evaluate=True) == Series(tf1, tf2, Parallel(tf1, -tf3)).doit() == \
|
| 580 |
+
TransferFunction(k*(a2*s + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2, s)
|
| 581 |
+
assert Series(tf2, tf1, -tf3, evaluate=True) == Series(tf2, tf1, -tf3).doit() == \
|
| 582 |
+
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 583 |
+
assert not Series(tf1, -tf2, evaluate=False) == Series(tf1, -tf2).doit()
|
| 584 |
+
|
| 585 |
+
assert Series(Parallel(tf1, tf2), Parallel(tf2, -tf3)).doit() == \
|
| 586 |
+
TransferFunction((k*(s**2 + 2*s*wn*zeta + wn**2) + 1)*(-a2*p + k*(a2*s + p) + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 587 |
+
assert Series(-tf1, -tf2, -tf3).doit() == \
|
| 588 |
+
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 589 |
+
assert -Series(tf1, tf2, tf3).doit() == \
|
| 590 |
+
TransferFunction(-k*(a2*p - s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 591 |
+
assert Series(tf2, tf3, Parallel(tf2, -tf1), tf3).doit() == \
|
| 592 |
+
TransferFunction(k*(a2*p - s)**2*(k*(s**2 + 2*s*wn*zeta + wn**2) - 1), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 593 |
+
|
| 594 |
+
assert Series(tf1, tf2).rewrite(TransferFunction) == TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
|
| 595 |
+
assert Series(tf2, tf1, -tf3).rewrite(TransferFunction) == \
|
| 596 |
+
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 597 |
+
|
| 598 |
+
S1 = Series(Parallel(tf1, tf2), Parallel(tf2, -tf3))
|
| 599 |
+
assert S1.is_proper
|
| 600 |
+
assert not S1.is_strictly_proper
|
| 601 |
+
assert S1.is_biproper
|
| 602 |
+
|
| 603 |
+
S2 = Series(tf1, tf2, tf3)
|
| 604 |
+
assert S2.is_proper
|
| 605 |
+
assert S2.is_strictly_proper
|
| 606 |
+
assert not S2.is_biproper
|
| 607 |
+
|
| 608 |
+
S3 = Series(tf1, -tf2, Parallel(tf1, -tf3))
|
| 609 |
+
assert S3.is_proper
|
| 610 |
+
assert S3.is_strictly_proper
|
| 611 |
+
assert not S3.is_biproper
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def test_MIMOSeries_functions():
|
| 615 |
+
tfm1 = TransferFunctionMatrix([[TF1, TF2, TF3], [-TF3, -TF2, TF1]])
|
| 616 |
+
tfm2 = TransferFunctionMatrix([[-TF1], [-TF2], [-TF3]])
|
| 617 |
+
tfm3 = TransferFunctionMatrix([[-TF1]])
|
| 618 |
+
tfm4 = TransferFunctionMatrix([[-TF2, -TF3], [-TF1, TF2]])
|
| 619 |
+
tfm5 = TransferFunctionMatrix([[TF2, -TF2], [-TF3, -TF2]])
|
| 620 |
+
tfm6 = TransferFunctionMatrix([[-TF3], [TF1]])
|
| 621 |
+
tfm7 = TransferFunctionMatrix([[TF1], [-TF2]])
|
| 622 |
+
|
| 623 |
+
assert tfm1*tfm2 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm6)
|
| 624 |
+
assert tfm1*tfm2 + tfm7 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm7, tfm6)
|
| 625 |
+
assert tfm1*tfm2 - tfm6 - tfm7 == MIMOParallel(MIMOSeries(tfm2, tfm1), -tfm6, -tfm7)
|
| 626 |
+
assert tfm4*tfm5 + (tfm4 - tfm5) == MIMOParallel(MIMOSeries(tfm5, tfm4), tfm4, -tfm5)
|
| 627 |
+
assert tfm4*-tfm6 + (-tfm4*tfm6) == MIMOParallel(MIMOSeries(-tfm6, tfm4), MIMOSeries(tfm6, -tfm4))
|
| 628 |
+
|
| 629 |
+
raises(ValueError, lambda: tfm1*tfm2 + TF1)
|
| 630 |
+
raises(TypeError, lambda: tfm1*tfm2 + a0)
|
| 631 |
+
raises(TypeError, lambda: tfm4*tfm6 - (s - 1))
|
| 632 |
+
raises(TypeError, lambda: tfm4*-tfm6 - 8)
|
| 633 |
+
raises(TypeError, lambda: (-1 + p**5) + tfm1*tfm2)
|
| 634 |
+
|
| 635 |
+
# Shape criteria.
|
| 636 |
+
|
| 637 |
+
raises(TypeError, lambda: -tfm1*tfm2 + tfm4)
|
| 638 |
+
raises(TypeError, lambda: tfm1*tfm2 - tfm4 + tfm5)
|
| 639 |
+
raises(TypeError, lambda: tfm1*tfm2 - tfm4*tfm5)
|
| 640 |
+
|
| 641 |
+
assert tfm1*tfm2*-tfm3 == MIMOSeries(-tfm3, tfm2, tfm1)
|
| 642 |
+
assert (tfm1*-tfm2)*tfm3 == MIMOSeries(tfm3, -tfm2, tfm1)
|
| 643 |
+
|
| 644 |
+
# Multiplication of a Series object with a SISO TF not allowed.
|
| 645 |
+
|
| 646 |
+
raises(ValueError, lambda: tfm4*tfm5*TF1)
|
| 647 |
+
raises(TypeError, lambda: tfm4*tfm5*a1)
|
| 648 |
+
raises(TypeError, lambda: tfm4*-tfm5*(s - 2))
|
| 649 |
+
raises(TypeError, lambda: tfm5*tfm4*9)
|
| 650 |
+
raises(TypeError, lambda: (-p**3 + 1)*tfm5*tfm4)
|
| 651 |
+
|
| 652 |
+
# Transfer function matrix in the arguments.
|
| 653 |
+
assert (MIMOSeries(tfm2, tfm1, evaluate=True) == MIMOSeries(tfm2, tfm1).doit()
|
| 654 |
+
== TransferFunctionMatrix(((TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2)**2 - (a2*s + p)**2,
|
| 655 |
+
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),),
|
| 656 |
+
(TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
|
| 657 |
+
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),))))
|
| 658 |
+
|
| 659 |
+
# doit() should not cancel poles and zeros.
|
| 660 |
+
mat_1 = Matrix([[1/(1+s), (1+s)/(1+s**2+2*s)**3]])
|
| 661 |
+
mat_2 = Matrix([[(1+s)], [(1+s**2+2*s)**3/(1+s)]])
|
| 662 |
+
tm_1, tm_2 = TransferFunctionMatrix.from_Matrix(mat_1, s), TransferFunctionMatrix.from_Matrix(mat_2, s)
|
| 663 |
+
assert (MIMOSeries(tm_2, tm_1).doit()
|
| 664 |
+
== TransferFunctionMatrix(((TransferFunction(2*(s + 1)**2*(s**2 + 2*s + 1)**3, (s + 1)**2*(s**2 + 2*s + 1)**3, s),),)))
|
| 665 |
+
assert MIMOSeries(tm_2, tm_1).doit().simplify() == TransferFunctionMatrix(((TransferFunction(2, 1, s),),))
|
| 666 |
+
|
| 667 |
+
# calling doit() will expand the internal Series and Parallel objects.
|
| 668 |
+
assert (MIMOSeries(-tfm3, -tfm2, tfm1, evaluate=True)
|
| 669 |
+
== MIMOSeries(-tfm3, -tfm2, tfm1).doit()
|
| 670 |
+
== TransferFunctionMatrix(((TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*p - s)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*s + p)**2,
|
| 671 |
+
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),),
|
| 672 |
+
(TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
|
| 673 |
+
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),))))
|
| 674 |
+
assert (MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5, evaluate=True)
|
| 675 |
+
== MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).doit()
|
| 676 |
+
== TransferFunctionMatrix(((TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), TransferFunction(k*(-a2*p - \
|
| 677 |
+
k*(a2*s + p) + s), a2*s + p, s)), (TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), \
|
| 678 |
+
TransferFunction((-a2*p + s)*(-a2*p - k*(a2*s + p) + s), (a2*s + p)**2, s)))) == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).rewrite(TransferFunctionMatrix))
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
def test_Parallel_construction():
|
| 682 |
+
tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
|
| 683 |
+
tf2 = TransferFunction(a2*p - s, a2*s + p, s)
|
| 684 |
+
tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
|
| 685 |
+
tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
|
| 686 |
+
inp = Function('X_d')(s)
|
| 687 |
+
out = Function('X')(s)
|
| 688 |
+
|
| 689 |
+
p0 = Parallel(tf, tf2)
|
| 690 |
+
assert p0.args == (tf, tf2)
|
| 691 |
+
assert p0.var == s
|
| 692 |
+
|
| 693 |
+
p1 = Parallel(Series(tf, -tf2), tf2)
|
| 694 |
+
assert p1.args == (Series(tf, -tf2), tf2)
|
| 695 |
+
assert p1.var == s
|
| 696 |
+
|
| 697 |
+
tf3_ = TransferFunction(inp, 1, s)
|
| 698 |
+
tf4_ = TransferFunction(-out, 1, s)
|
| 699 |
+
p2 = Parallel(tf, Series(tf3_, -tf4_), tf2)
|
| 700 |
+
assert p2.args == (tf, Series(tf3_, -tf4_), tf2)
|
| 701 |
+
|
| 702 |
+
p3 = Parallel(tf, tf2, tf4)
|
| 703 |
+
assert p3.args == (tf, tf2, tf4)
|
| 704 |
+
|
| 705 |
+
p4 = Parallel(tf3_, tf4_)
|
| 706 |
+
assert p4.args == (tf3_, tf4_)
|
| 707 |
+
assert p4.var == s
|
| 708 |
+
|
| 709 |
+
p5 = Parallel(tf, tf2)
|
| 710 |
+
assert p0 == p5
|
| 711 |
+
assert not p0 == p1
|
| 712 |
+
|
| 713 |
+
p6 = Parallel(tf2, tf4, Series(tf2, -tf4))
|
| 714 |
+
assert p6.args == (tf2, tf4, Series(tf2, -tf4))
|
| 715 |
+
|
| 716 |
+
p7 = Parallel(tf2, tf4, Series(tf2, -tf), tf4)
|
| 717 |
+
assert p7.args == (tf2, tf4, Series(tf2, -tf), tf4)
|
| 718 |
+
|
| 719 |
+
raises(ValueError, lambda: Parallel(tf, tf3))
|
| 720 |
+
raises(ValueError, lambda: Parallel(tf, tf2, tf3, tf4))
|
| 721 |
+
raises(ValueError, lambda: Parallel(-tf3, tf4))
|
| 722 |
+
raises(TypeError, lambda: Parallel(2, tf, tf4))
|
| 723 |
+
raises(TypeError, lambda: Parallel(s**2 + p*s, tf3, tf2))
|
| 724 |
+
raises(TypeError, lambda: Parallel(tf3, Matrix([1, 2, 3, 4])))
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
def test_MIMOParallel_construction():
|
| 728 |
+
tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
|
| 729 |
+
tfm2 = TransferFunctionMatrix([[-TF3], [TF2], [TF1]])
|
| 730 |
+
tfm3 = TransferFunctionMatrix([[TF1]])
|
| 731 |
+
tfm4 = TransferFunctionMatrix([[TF2], [TF1], [TF3]])
|
| 732 |
+
tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF2, TF1]])
|
| 733 |
+
tfm6 = TransferFunctionMatrix([[TF2, TF1], [TF1, TF2]])
|
| 734 |
+
tfm7 = TransferFunctionMatrix.from_Matrix(Matrix([[1/p]]), p)
|
| 735 |
+
|
| 736 |
+
p8 = MIMOParallel(tfm1, tfm2)
|
| 737 |
+
assert p8.args == (tfm1, tfm2)
|
| 738 |
+
assert p8.var == s
|
| 739 |
+
assert p8.shape == (p8.num_outputs, p8.num_inputs) == (3, 1)
|
| 740 |
+
|
| 741 |
+
p9 = MIMOParallel(MIMOSeries(tfm3, tfm1), tfm2)
|
| 742 |
+
assert p9.args == (MIMOSeries(tfm3, tfm1), tfm2)
|
| 743 |
+
assert p9.var == s
|
| 744 |
+
assert p9.shape == (p9.num_outputs, p9.num_inputs) == (3, 1)
|
| 745 |
+
|
| 746 |
+
p10 = MIMOParallel(tfm1, MIMOSeries(tfm3, tfm4), tfm2)
|
| 747 |
+
assert p10.args == (tfm1, MIMOSeries(tfm3, tfm4), tfm2)
|
| 748 |
+
assert p10.var == s
|
| 749 |
+
assert p10.shape == (p10.num_outputs, p10.num_inputs) == (3, 1)
|
| 750 |
+
|
| 751 |
+
p11 = MIMOParallel(tfm2, tfm1, tfm4)
|
| 752 |
+
assert p11.args == (tfm2, tfm1, tfm4)
|
| 753 |
+
assert p11.shape == (p11.num_outputs, p11.num_inputs) == (3, 1)
|
| 754 |
+
|
| 755 |
+
p12 = MIMOParallel(tfm6, tfm5)
|
| 756 |
+
assert p12.args == (tfm6, tfm5)
|
| 757 |
+
assert p12.shape == (p12.num_outputs, p12.num_inputs) == (2, 2)
|
| 758 |
+
|
| 759 |
+
p13 = MIMOParallel(tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
|
| 760 |
+
assert p13.args == (tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
|
| 761 |
+
assert p13.shape == (p13.num_outputs, p13.num_inputs) == (3, 1)
|
| 762 |
+
|
| 763 |
+
# arg cannot be empty tuple.
|
| 764 |
+
raises(TypeError, lambda: MIMOParallel(()))
|
| 765 |
+
|
| 766 |
+
# arg cannot contain SISO as well as MIMO systems.
|
| 767 |
+
raises(TypeError, lambda: MIMOParallel(tfm1, tfm2, TF1))
|
| 768 |
+
|
| 769 |
+
# all TFMs must have same shapes.
|
| 770 |
+
raises(TypeError, lambda: MIMOParallel(tfm1, tfm3, tfm4))
|
| 771 |
+
|
| 772 |
+
# all TFMs must be using the same complex variable.
|
| 773 |
+
raises(ValueError, lambda: MIMOParallel(tfm3, tfm7))
|
| 774 |
+
|
| 775 |
+
# Number or expression not allowed in the arguments.
|
| 776 |
+
raises(TypeError, lambda: MIMOParallel(2, tfm1, tfm4))
|
| 777 |
+
raises(TypeError, lambda: MIMOParallel(s**2 + p*s, -tfm4, tfm2))
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
def test_Parallel_functions():
|
| 781 |
+
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
|
| 782 |
+
tf2 = TransferFunction(k, 1, s)
|
| 783 |
+
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
|
| 784 |
+
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
|
| 785 |
+
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
|
| 786 |
+
|
| 787 |
+
assert tf1 + tf2 + tf3 == Parallel(tf1, tf2, tf3)
|
| 788 |
+
assert tf1 + tf2 + tf3 + tf5 == Parallel(tf1, tf2, tf3, tf5)
|
| 789 |
+
assert tf1 + tf2 - tf3 - tf5 == Parallel(tf1, tf2, -tf3, -tf5)
|
| 790 |
+
assert tf1 + tf2*tf3 == Parallel(tf1, Series(tf2, tf3))
|
| 791 |
+
assert tf1 - tf2*tf3 == Parallel(tf1, -Series(tf2,tf3))
|
| 792 |
+
assert -tf1 - tf2 == Parallel(-tf1, -tf2)
|
| 793 |
+
assert -(tf1 + tf2) == Series(TransferFunction(-1, 1, s), Parallel(tf1, tf2))
|
| 794 |
+
assert (tf2 + tf3)*tf1 == Series(Parallel(tf2, tf3), tf1)
|
| 795 |
+
assert (tf1 + tf2)*(tf3*tf5) == Series(Parallel(tf1, tf2), tf3, tf5)
|
| 796 |
+
assert -(tf2 + tf3)*-tf5 == Series(TransferFunction(-1, 1, s), Parallel(tf2, tf3), -tf5)
|
| 797 |
+
assert tf2 + tf3 + tf2*tf1 + tf5 == Parallel(tf2, tf3, Series(tf2, tf1), tf5)
|
| 798 |
+
assert tf2 + tf3 + tf2*tf1 - tf3 == Parallel(tf2, tf3, Series(tf2, tf1), -tf3)
|
| 799 |
+
assert (tf1 + tf2 + tf5)*(tf3 + tf5) == Series(Parallel(tf1, tf2, tf5), Parallel(tf3, tf5))
|
| 800 |
+
raises(ValueError, lambda: tf1 + tf2 + tf4)
|
| 801 |
+
raises(ValueError, lambda: tf1 - tf2*tf4)
|
| 802 |
+
raises(ValueError, lambda: tf3 + Matrix([1, 2, 3]))
|
| 803 |
+
|
| 804 |
+
# evaluate=True -> doit()
|
| 805 |
+
assert Parallel(tf1, tf2, evaluate=True) == Parallel(tf1, tf2).doit() == \
|
| 806 |
+
TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
|
| 807 |
+
assert Parallel(tf1, tf2, Series(-tf1, tf3), evaluate=True) == \
|
| 808 |
+
Parallel(tf1, tf2, Series(-tf1, tf3)).doit() == TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2 + \
|
| 809 |
+
(-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + \
|
| 810 |
+
2*s*wn*zeta + wn**2)**2, s)
|
| 811 |
+
assert Parallel(tf2, tf1, -tf3, evaluate=True) == Parallel(tf2, tf1, -tf3).doit() == \
|
| 812 |
+
TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) \
|
| 813 |
+
, (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 814 |
+
assert not Parallel(tf1, -tf2, evaluate=False) == Parallel(tf1, -tf2).doit()
|
| 815 |
+
|
| 816 |
+
assert Parallel(Series(tf1, tf2), Series(tf2, tf3)).doit() == \
|
| 817 |
+
TransferFunction(k*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + k*(a2*s + p), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 818 |
+
assert Parallel(-tf1, -tf2, -tf3).doit() == \
|
| 819 |
+
TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2), \
|
| 820 |
+
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 821 |
+
assert -Parallel(tf1, tf2, tf3).doit() == \
|
| 822 |
+
TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p - (a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2), \
|
| 823 |
+
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 824 |
+
assert Parallel(tf2, tf3, Series(tf2, -tf1), tf3).doit() == \
|
| 825 |
+
TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - k*(a2*s + p) + (2*a2*p - 2*s)*(s**2 + 2*s*wn*zeta \
|
| 826 |
+
+ wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 827 |
+
|
| 828 |
+
assert Parallel(tf1, tf2).rewrite(TransferFunction) == \
|
| 829 |
+
TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
|
| 830 |
+
assert Parallel(tf2, tf1, -tf3).rewrite(TransferFunction) == \
|
| 831 |
+
TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + \
|
| 832 |
+
wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 833 |
+
|
| 834 |
+
assert Parallel(tf1, Parallel(tf2, tf3)) == Parallel(tf1, tf2, tf3) == Parallel(Parallel(tf1, tf2), tf3)
|
| 835 |
+
|
| 836 |
+
P1 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
|
| 837 |
+
assert P1.is_proper
|
| 838 |
+
assert not P1.is_strictly_proper
|
| 839 |
+
assert P1.is_biproper
|
| 840 |
+
|
| 841 |
+
P2 = Parallel(tf1, -tf2, -tf3)
|
| 842 |
+
assert P2.is_proper
|
| 843 |
+
assert not P2.is_strictly_proper
|
| 844 |
+
assert P2.is_biproper
|
| 845 |
+
|
| 846 |
+
P3 = Parallel(tf1, -tf2, Series(tf1, tf3))
|
| 847 |
+
assert P3.is_proper
|
| 848 |
+
assert not P3.is_strictly_proper
|
| 849 |
+
assert P3.is_biproper
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
def test_MIMOParallel_functions():
|
| 853 |
+
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
|
| 854 |
+
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
|
| 855 |
+
|
| 856 |
+
tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
|
| 857 |
+
tfm2 = TransferFunctionMatrix([[-TF2], [tf5], [-TF1]])
|
| 858 |
+
tfm3 = TransferFunctionMatrix([[tf5], [-tf5], [TF2]])
|
| 859 |
+
tfm4 = TransferFunctionMatrix([[TF2, -tf5], [TF1, tf5]])
|
| 860 |
+
tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5]])
|
| 861 |
+
tfm6 = TransferFunctionMatrix([[-TF2]])
|
| 862 |
+
tfm7 = TransferFunctionMatrix([[tf4], [-tf4], [tf4]])
|
| 863 |
+
|
| 864 |
+
assert tfm1 + tfm2 + tfm3 == MIMOParallel(tfm1, tfm2, tfm3) == MIMOParallel(MIMOParallel(tfm1, tfm2), tfm3)
|
| 865 |
+
assert tfm2 - tfm1 - tfm3 == MIMOParallel(tfm2, -tfm1, -tfm3)
|
| 866 |
+
assert tfm2 - tfm3 + (-tfm1*tfm6*-tfm6) == MIMOParallel(tfm2, -tfm3, MIMOSeries(-tfm6, tfm6, -tfm1))
|
| 867 |
+
assert tfm1 + tfm1 - (-tfm1*tfm6) == MIMOParallel(tfm1, tfm1, -MIMOSeries(tfm6, -tfm1))
|
| 868 |
+
assert tfm2 - tfm3 - tfm1 + tfm2 == MIMOParallel(tfm2, -tfm3, -tfm1, tfm2)
|
| 869 |
+
assert tfm1 + tfm2 - tfm3 - tfm1 == MIMOParallel(tfm1, tfm2, -tfm3, -tfm1)
|
| 870 |
+
raises(ValueError, lambda: tfm1 + tfm2 + TF2)
|
| 871 |
+
raises(TypeError, lambda: tfm1 - tfm2 - a1)
|
| 872 |
+
raises(TypeError, lambda: tfm2 - tfm3 - (s - 1))
|
| 873 |
+
raises(TypeError, lambda: -tfm3 - tfm2 - 9)
|
| 874 |
+
raises(TypeError, lambda: (1 - p**3) - tfm3 - tfm2)
|
| 875 |
+
# All TFMs must use the same complex var. tfm7 uses 'p'.
|
| 876 |
+
raises(ValueError, lambda: tfm3 - tfm2 - tfm7)
|
| 877 |
+
raises(ValueError, lambda: tfm2 - tfm1 + tfm7)
|
| 878 |
+
# (tfm1 +/- tfm2) has (3, 1) shape while tfm4 has (2, 2) shape.
|
| 879 |
+
raises(TypeError, lambda: tfm1 + tfm2 + tfm4)
|
| 880 |
+
raises(TypeError, lambda: (tfm1 - tfm2) - tfm4)
|
| 881 |
+
|
| 882 |
+
assert (tfm1 + tfm2)*tfm6 == MIMOSeries(tfm6, MIMOParallel(tfm1, tfm2))
|
| 883 |
+
assert (tfm2 - tfm3)*tfm6*-tfm6 == MIMOSeries(-tfm6, tfm6, MIMOParallel(tfm2, -tfm3))
|
| 884 |
+
assert (tfm2 - tfm1 - tfm3)*(tfm6 + tfm6) == MIMOSeries(MIMOParallel(tfm6, tfm6), MIMOParallel(tfm2, -tfm1, -tfm3))
|
| 885 |
+
raises(ValueError, lambda: (tfm4 + tfm5)*TF1)
|
| 886 |
+
raises(TypeError, lambda: (tfm2 - tfm3)*a2)
|
| 887 |
+
raises(TypeError, lambda: (tfm3 + tfm2)*(s - 6))
|
| 888 |
+
raises(TypeError, lambda: (tfm1 + tfm2 + tfm3)*0)
|
| 889 |
+
raises(TypeError, lambda: (1 - p**3)*(tfm1 + tfm3))
|
| 890 |
+
|
| 891 |
+
# (tfm3 - tfm2) has (3, 1) shape while tfm4*tfm5 has (2, 2) shape.
|
| 892 |
+
raises(ValueError, lambda: (tfm3 - tfm2)*tfm4*tfm5)
|
| 893 |
+
# (tfm1 - tfm2) has (3, 1) shape while tfm5 has (2, 2) shape.
|
| 894 |
+
raises(ValueError, lambda: (tfm1 - tfm2)*tfm5)
|
| 895 |
+
|
| 896 |
+
# TFM in the arguments.
|
| 897 |
+
assert (MIMOParallel(tfm1, tfm2, evaluate=True) == MIMOParallel(tfm1, tfm2).doit()
|
| 898 |
+
== MIMOParallel(tfm1, tfm2).rewrite(TransferFunctionMatrix)
|
| 899 |
+
== TransferFunctionMatrix(((TransferFunction(-k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s),), \
|
| 900 |
+
(TransferFunction(-a0 + a1*s**2 + a2*s + k*(a0 + s), a0 + s, s),), (TransferFunction(-a2*s - p + (a2*p - s)* \
|
| 901 |
+
(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s),))))
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def test_Feedback_construction():
|
| 905 |
+
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
|
| 906 |
+
tf2 = TransferFunction(k, 1, s)
|
| 907 |
+
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
|
| 908 |
+
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
|
| 909 |
+
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
|
| 910 |
+
tf6 = TransferFunction(s - p, p + s, p)
|
| 911 |
+
|
| 912 |
+
f1 = Feedback(TransferFunction(1, 1, s), tf1*tf2*tf3)
|
| 913 |
+
assert f1.args == (TransferFunction(1, 1, s), Series(tf1, tf2, tf3), -1)
|
| 914 |
+
assert f1.sys1 == TransferFunction(1, 1, s)
|
| 915 |
+
assert f1.sys2 == Series(tf1, tf2, tf3)
|
| 916 |
+
assert f1.var == s
|
| 917 |
+
|
| 918 |
+
f2 = Feedback(tf1, tf2*tf3)
|
| 919 |
+
assert f2.args == (tf1, Series(tf2, tf3), -1)
|
| 920 |
+
assert f2.sys1 == tf1
|
| 921 |
+
assert f2.sys2 == Series(tf2, tf3)
|
| 922 |
+
assert f2.var == s
|
| 923 |
+
|
| 924 |
+
f3 = Feedback(tf1*tf2, tf5)
|
| 925 |
+
assert f3.args == (Series(tf1, tf2), tf5, -1)
|
| 926 |
+
assert f3.sys1 == Series(tf1, tf2)
|
| 927 |
+
|
| 928 |
+
f4 = Feedback(tf4, tf6)
|
| 929 |
+
assert f4.args == (tf4, tf6, -1)
|
| 930 |
+
assert f4.sys1 == tf4
|
| 931 |
+
assert f4.var == p
|
| 932 |
+
|
| 933 |
+
f5 = Feedback(tf5, TransferFunction(1, 1, s))
|
| 934 |
+
assert f5.args == (tf5, TransferFunction(1, 1, s), -1)
|
| 935 |
+
assert f5.var == s
|
| 936 |
+
assert f5 == Feedback(tf5) # When sys2 is not passed explicitly, it is assumed to be unit tf.
|
| 937 |
+
|
| 938 |
+
f6 = Feedback(TransferFunction(1, 1, p), tf4)
|
| 939 |
+
assert f6.args == (TransferFunction(1, 1, p), tf4, -1)
|
| 940 |
+
assert f6.var == p
|
| 941 |
+
|
| 942 |
+
f7 = -Feedback(tf4*tf6, TransferFunction(1, 1, p))
|
| 943 |
+
assert f7.args == (Series(TransferFunction(-1, 1, p), Series(tf4, tf6)), -TransferFunction(1, 1, p), -1)
|
| 944 |
+
assert f7.sys1 == Series(TransferFunction(-1, 1, p), Series(tf4, tf6))
|
| 945 |
+
|
| 946 |
+
# denominator can't be a Parallel instance
|
| 947 |
+
raises(TypeError, lambda: Feedback(tf1, tf2 + tf3))
|
| 948 |
+
raises(TypeError, lambda: Feedback(tf1, Matrix([1, 2, 3])))
|
| 949 |
+
raises(TypeError, lambda: Feedback(TransferFunction(1, 1, s), s - 1))
|
| 950 |
+
raises(TypeError, lambda: Feedback(1, 1))
|
| 951 |
+
# raises(ValueError, lambda: Feedback(TransferFunction(1, 1, s), TransferFunction(1, 1, s)))
|
| 952 |
+
raises(ValueError, lambda: Feedback(tf2, tf4*tf5))
|
| 953 |
+
raises(ValueError, lambda: Feedback(tf2, tf1, 1.5)) # `sign` can only be -1 or 1
|
| 954 |
+
raises(ValueError, lambda: Feedback(tf1, -tf1**-1)) # denominator can't be zero
|
| 955 |
+
raises(ValueError, lambda: Feedback(tf4, tf5)) # Both systems should use the same `var`
|
| 956 |
+
|
| 957 |
+
|
| 958 |
+
def test_Feedback_functions():
|
| 959 |
+
tf = TransferFunction(1, 1, s)
|
| 960 |
+
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
|
| 961 |
+
tf2 = TransferFunction(k, 1, s)
|
| 962 |
+
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
|
| 963 |
+
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
|
| 964 |
+
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
|
| 965 |
+
tf6 = TransferFunction(s - p, p + s, p)
|
| 966 |
+
|
| 967 |
+
assert (tf1*tf2*tf3 / tf3*tf5) == Series(tf1, tf2, tf3, pow(tf3, -1), tf5)
|
| 968 |
+
assert (tf1*tf2*tf3) / (tf3*tf5) == Series((tf1*tf2*tf3).doit(), pow((tf3*tf5).doit(),-1))
|
| 969 |
+
assert tf / (tf + tf1) == Feedback(tf, tf1)
|
| 970 |
+
assert tf / (tf + tf1*tf2*tf3) == Feedback(tf, tf1*tf2*tf3)
|
| 971 |
+
assert tf1 / (tf + tf1*tf2*tf3) == Feedback(tf1, tf2*tf3)
|
| 972 |
+
assert (tf1*tf2) / (tf + tf1*tf2) == Feedback(tf1*tf2, tf)
|
| 973 |
+
assert (tf1*tf2) / (tf + tf1*tf2*tf5) == Feedback(tf1*tf2, tf5)
|
| 974 |
+
assert (tf1*tf2) / (tf + tf1*tf2*tf5*tf3) in (Feedback(tf1*tf2, tf5*tf3), Feedback(tf1*tf2, tf3*tf5))
|
| 975 |
+
assert tf4 / (TransferFunction(1, 1, p) + tf4*tf6) == Feedback(tf4, tf6)
|
| 976 |
+
assert tf5 / (tf + tf5) == Feedback(tf5, tf)
|
| 977 |
+
|
| 978 |
+
raises(TypeError, lambda: tf1*tf2*tf3 / (1 + tf1*tf2*tf3))
|
| 979 |
+
raises(ValueError, lambda: tf2*tf3 / (tf + tf2*tf3*tf4))
|
| 980 |
+
|
| 981 |
+
assert Feedback(tf, tf1*tf2*tf3).doit() == \
|
| 982 |
+
TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), k*(a2*p - s) + \
|
| 983 |
+
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 984 |
+
assert Feedback(tf, tf1*tf2*tf3).sensitivity == \
|
| 985 |
+
1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
|
| 986 |
+
assert Feedback(tf1, tf2*tf3).doit() == \
|
| 987 |
+
TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (k*(a2*p - s) + \
|
| 988 |
+
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 989 |
+
assert Feedback(tf1, tf2*tf3).sensitivity == \
|
| 990 |
+
1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
|
| 991 |
+
assert Feedback(tf1*tf2, tf5).doit() == \
|
| 992 |
+
TransferFunction(k*(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
|
| 993 |
+
(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 994 |
+
assert Feedback(tf1*tf2, tf5, 1).sensitivity == \
|
| 995 |
+
1/(-k*(-a0 + a1*s**2 + a2*s)/((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
|
| 996 |
+
assert Feedback(tf4, tf6).doit() == \
|
| 997 |
+
TransferFunction(p*(p + s)*(a0*p + p**a1 - s), p*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
|
| 998 |
+
assert -Feedback(tf4*tf6, TransferFunction(1, 1, p)).doit() == \
|
| 999 |
+
TransferFunction(-p*(-p + s)*(p + s)*(a0*p + p**a1 - s), p*(p + s)*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
|
| 1000 |
+
assert Feedback(tf, tf).doit() == TransferFunction(1, 2, s)
|
| 1001 |
+
|
| 1002 |
+
assert Feedback(tf1, tf2*tf5).rewrite(TransferFunction) == \
|
| 1003 |
+
TransferFunction((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
|
| 1004 |
+
(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
|
| 1005 |
+
assert Feedback(TransferFunction(1, 1, p), tf4).rewrite(TransferFunction) == \
|
| 1006 |
+
TransferFunction(p, a0*p + p + p**a1 - s, p)
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
def test_Feedback_as_TransferFunction():
|
| 1010 |
+
# Solves issue https://github.com/sympy/sympy/issues/26161
|
| 1011 |
+
tf1 = TransferFunction(s+1, 1, s)
|
| 1012 |
+
tf2 = TransferFunction(s+2, 1, s)
|
| 1013 |
+
fd1 = Feedback(tf1, tf2, -1) # Negative Feedback system
|
| 1014 |
+
fd2 = Feedback(tf1, tf2, 1) # Positive Feedback system
|
| 1015 |
+
unit = TransferFunction(1, 1, s)
|
| 1016 |
+
|
| 1017 |
+
# Checking the type
|
| 1018 |
+
assert isinstance(fd1, TransferFunction)
|
| 1019 |
+
assert isinstance(fd1, Feedback)
|
| 1020 |
+
|
| 1021 |
+
# Testing the numerator and denominator
|
| 1022 |
+
assert fd1.num == tf1
|
| 1023 |
+
assert fd2.num == tf1
|
| 1024 |
+
assert fd1.den == Parallel(unit, Series(tf2, tf1))
|
| 1025 |
+
assert fd2.den == Parallel(unit, -Series(tf2, tf1))
|
| 1026 |
+
|
| 1027 |
+
# Testing the Series and Parallel Combination with Feedback and TransferFunction
|
| 1028 |
+
s1 = Series(tf1, fd1)
|
| 1029 |
+
p1 = Parallel(tf1, fd1)
|
| 1030 |
+
assert tf1 * fd1 == s1
|
| 1031 |
+
assert tf1 + fd1 == p1
|
| 1032 |
+
assert s1.doit() == TransferFunction((s + 1)**2, (s + 1)*(s + 2) + 1, s)
|
| 1033 |
+
assert p1.doit() == TransferFunction(s + (s + 1)*((s + 1)*(s + 2) + 1) + 1, (s + 1)*(s + 2) + 1, s)
|
| 1034 |
+
|
| 1035 |
+
# Testing the use of Feedback and TransferFunction with Feedback
|
| 1036 |
+
fd3 = Feedback(tf1*fd1, tf2, -1)
|
| 1037 |
+
assert fd3 == Feedback(Series(tf1, fd1), tf2)
|
| 1038 |
+
assert fd3.num == tf1 * fd1
|
| 1039 |
+
assert fd3.den == Parallel(unit, Series(tf2, Series(tf1, fd1)))
|
| 1040 |
+
|
| 1041 |
+
# Testing the use of Feedback and TransferFunction with TransferFunction
|
| 1042 |
+
tf3 = TransferFunction(tf1*fd1, tf2, s)
|
| 1043 |
+
assert tf3 == TransferFunction(Series(tf1, fd1), tf2, s)
|
| 1044 |
+
assert tf3.num == tf1*fd1
|
| 1045 |
+
|
| 1046 |
+
def test_issue_26161():
|
| 1047 |
+
# Issue https://github.com/sympy/sympy/issues/26161
|
| 1048 |
+
Ib, Is, m, h, l2, l1 = symbols('I_b, I_s, m, h, l2, l1',
|
| 1049 |
+
real=True, nonnegative=True)
|
| 1050 |
+
KD, KP, v = symbols('K_D, K_P, v', real=True)
|
| 1051 |
+
|
| 1052 |
+
tau1_sq = (Ib + m * h ** 2) / m / g / h
|
| 1053 |
+
tau2 = l2 / v
|
| 1054 |
+
tau3 = v / (l1 + l2)
|
| 1055 |
+
K = v ** 2 / g / (l1 + l2)
|
| 1056 |
+
|
| 1057 |
+
Gtheta = TransferFunction(-K * (tau2 * s + 1), tau1_sq * s ** 2 - 1, s)
|
| 1058 |
+
Gdelta = TransferFunction(1, Is * s ** 2 + c * s, s)
|
| 1059 |
+
Gpsi = TransferFunction(1, tau3 * s, s)
|
| 1060 |
+
Dcont = TransferFunction(KD * s, 1, s)
|
| 1061 |
+
PIcont = TransferFunction(KP, s, s)
|
| 1062 |
+
Gunity = TransferFunction(1, 1, s)
|
| 1063 |
+
|
| 1064 |
+
Ginner = Feedback(Dcont * Gdelta, Gtheta)
|
| 1065 |
+
Gouter = Feedback(PIcont * Ginner * Gpsi, Gunity)
|
| 1066 |
+
assert Gouter == Feedback(Series(PIcont, Series(Ginner, Gpsi)), Gunity)
|
| 1067 |
+
assert Gouter.num == Series(PIcont, Series(Ginner, Gpsi))
|
| 1068 |
+
assert Gouter.den == Parallel(Gunity, Series(Gunity, Series(PIcont, Series(Ginner, Gpsi))))
|
| 1069 |
+
expr = (KD*KP*g*s**3*v**2*(l1 + l2)*(Is*s**2 + c*s)**2*(-g*h*m + s**2*(Ib + h**2*m))*(-KD*g*h*m*s*v**2*(l2*s + v) + \
|
| 1070 |
+
g*v*(l1 + l2)*(Is*s**2 + c*s)*(-g*h*m + s**2*(Ib + h**2*m))))/((s**2*v*(Is*s**2 + c*s)*(-KD*g*h*m*s*v**2* \
|
| 1071 |
+
(l2*s + v) + g*v*(l1 + l2)*(Is*s**2 + c*s)*(-g*h*m + s**2*(Ib + h**2*m)))*(KD*KP*g*s*v*(l1 + l2)**2* \
|
| 1072 |
+
(Is*s**2 + c*s)*(-g*h*m + s**2*(Ib + h**2*m)) + s**2*v*(Is*s**2 + c*s)*(-KD*g*h*m*s*v**2*(l2*s + v) + \
|
| 1073 |
+
g*v*(l1 + l2)*(Is*s**2 + c*s)*(-g*h*m + s**2*(Ib + h**2*m))))/(l1 + l2)))
|
| 1074 |
+
|
| 1075 |
+
assert (Gouter.to_expr() - expr).simplify() == 0
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
def test_MIMOFeedback_construction():
|
| 1079 |
+
tf1 = TransferFunction(1, s, s)
|
| 1080 |
+
tf2 = TransferFunction(s, s**3 - 1, s)
|
| 1081 |
+
tf3 = TransferFunction(s, s + 1, s)
|
| 1082 |
+
tf4 = TransferFunction(s, s**2 + 1, s)
|
| 1083 |
+
|
| 1084 |
+
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
|
| 1085 |
+
tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
|
| 1086 |
+
tfm_3 = TransferFunctionMatrix([[tf3, tf4], [tf1, tf2]])
|
| 1087 |
+
|
| 1088 |
+
f1 = MIMOFeedback(tfm_1, tfm_2)
|
| 1089 |
+
assert f1.args == (tfm_1, tfm_2, -1)
|
| 1090 |
+
assert f1.sys1 == tfm_1
|
| 1091 |
+
assert f1.sys2 == tfm_2
|
| 1092 |
+
assert f1.var == s
|
| 1093 |
+
assert f1.sign == -1
|
| 1094 |
+
assert -(-f1) == f1
|
| 1095 |
+
|
| 1096 |
+
f2 = MIMOFeedback(tfm_2, tfm_1, 1)
|
| 1097 |
+
assert f2.args == (tfm_2, tfm_1, 1)
|
| 1098 |
+
assert f2.sys1 == tfm_2
|
| 1099 |
+
assert f2.sys2 == tfm_1
|
| 1100 |
+
assert f2.var == s
|
| 1101 |
+
assert f2.sign == 1
|
| 1102 |
+
|
| 1103 |
+
f3 = MIMOFeedback(tfm_1, MIMOSeries(tfm_3, tfm_2))
|
| 1104 |
+
assert f3.args == (tfm_1, MIMOSeries(tfm_3, tfm_2), -1)
|
| 1105 |
+
assert f3.sys1 == tfm_1
|
| 1106 |
+
assert f3.sys2 == MIMOSeries(tfm_3, tfm_2)
|
| 1107 |
+
assert f3.var == s
|
| 1108 |
+
assert f3.sign == -1
|
| 1109 |
+
|
| 1110 |
+
mat = Matrix([[1, 1/s], [0, 1]])
|
| 1111 |
+
sys1 = controller = TransferFunctionMatrix.from_Matrix(mat, s)
|
| 1112 |
+
f4 = MIMOFeedback(sys1, controller)
|
| 1113 |
+
assert f4.args == (sys1, controller, -1)
|
| 1114 |
+
assert f4.sys1 == f4.sys2 == sys1
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
def test_MIMOFeedback_errors():
|
| 1118 |
+
tf1 = TransferFunction(1, s, s)
|
| 1119 |
+
tf2 = TransferFunction(s, s**3 - 1, s)
|
| 1120 |
+
tf3 = TransferFunction(s, s - 1, s)
|
| 1121 |
+
tf4 = TransferFunction(s, s**2 + 1, s)
|
| 1122 |
+
tf5 = TransferFunction(1, 1, s)
|
| 1123 |
+
tf6 = TransferFunction(-1, s - 1, s)
|
| 1124 |
+
|
| 1125 |
+
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
|
| 1126 |
+
tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
|
| 1127 |
+
tfm_3 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
|
| 1128 |
+
tfm_4 = TransferFunctionMatrix([[tf1, tf5], [tf5, tf5]])
|
| 1129 |
+
tfm_5 = TransferFunctionMatrix([[-tf3, tf3], [tf3, tf6]])
|
| 1130 |
+
# tfm_4 is inverse of tfm_5. Therefore tfm_5*tfm_4 = I
|
| 1131 |
+
tfm_6 = TransferFunctionMatrix([[-tf3]])
|
| 1132 |
+
tfm_7 = TransferFunctionMatrix([[tf3, tf4]])
|
| 1133 |
+
|
| 1134 |
+
# Unsupported Types
|
| 1135 |
+
raises(TypeError, lambda: MIMOFeedback(tf1, tf2))
|
| 1136 |
+
raises(TypeError, lambda: MIMOFeedback(MIMOParallel(tfm_1, tfm_2), tfm_3))
|
| 1137 |
+
# Shape Errors
|
| 1138 |
+
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_6, 1))
|
| 1139 |
+
raises(ValueError, lambda: MIMOFeedback(tfm_7, tfm_7))
|
| 1140 |
+
# sign not 1/-1
|
| 1141 |
+
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_2, -2))
|
| 1142 |
+
# Non-Invertible Systems
|
| 1143 |
+
raises(ValueError, lambda: MIMOFeedback(tfm_5, tfm_4, 1))
|
| 1144 |
+
raises(ValueError, lambda: MIMOFeedback(tfm_4, -tfm_5))
|
| 1145 |
+
raises(ValueError, lambda: MIMOFeedback(tfm_3, tfm_3, 1))
|
| 1146 |
+
# Variable not same in both the systems
|
| 1147 |
+
tfm_8 = TransferFunctionMatrix.from_Matrix(eye(2), var=p)
|
| 1148 |
+
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_8, 1))
|
| 1149 |
+
|
| 1150 |
+
|
| 1151 |
+
def test_MIMOFeedback_functions():
|
| 1152 |
+
tf1 = TransferFunction(1, s, s)
|
| 1153 |
+
tf2 = TransferFunction(s, s - 1, s)
|
| 1154 |
+
tf3 = TransferFunction(1, 1, s)
|
| 1155 |
+
tf4 = TransferFunction(-1, s - 1, s)
|
| 1156 |
+
|
| 1157 |
+
tfm_1 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
|
| 1158 |
+
tfm_2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf3]])
|
| 1159 |
+
tfm_3 = TransferFunctionMatrix([[-tf2, tf2], [tf2, tf4]])
|
| 1160 |
+
tfm_4 = TransferFunctionMatrix([[tf1, tf2], [-tf2, tf1]])
|
| 1161 |
+
|
| 1162 |
+
# sensitivity, doit(), rewrite()
|
| 1163 |
+
F_1 = MIMOFeedback(tfm_2, tfm_3)
|
| 1164 |
+
F_2 = MIMOFeedback(tfm_2, MIMOSeries(tfm_4, -tfm_1), 1)
|
| 1165 |
+
|
| 1166 |
+
assert F_1.sensitivity == Matrix([[S.Half, 0], [0, S.Half]])
|
| 1167 |
+
assert F_2.sensitivity == Matrix([[(-2*s**4 + s**2)/(s**2 - s + 1),
|
| 1168 |
+
(2*s**3 - s**2)/(s**2 - s + 1)], [-s**2, s]])
|
| 1169 |
+
|
| 1170 |
+
assert F_1.doit() == \
|
| 1171 |
+
TransferFunctionMatrix(((TransferFunction(1, 2*s, s),
|
| 1172 |
+
TransferFunction(1, 2, s)), (TransferFunction(1, 2, s),
|
| 1173 |
+
TransferFunction(1, 2, s)))) == F_1.rewrite(TransferFunctionMatrix)
|
| 1174 |
+
assert F_2.doit(cancel=False, expand=True) == \
|
| 1175 |
+
TransferFunctionMatrix(((TransferFunction(-s**5 + 2*s**4 - 2*s**3 + s**2, s**5 - 2*s**4 + 3*s**3 - 2*s**2 + s, s),
|
| 1176 |
+
TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
|
| 1177 |
+
assert F_2.doit(cancel=False) == \
|
| 1178 |
+
TransferFunctionMatrix(((TransferFunction(s*(2*s**3 - s**2)*(s**2 - s + 1) + \
|
| 1179 |
+
(-2*s**4 + s**2)*(s**2 - s + 1), s*(s**2 - s + 1)**2, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
|
| 1180 |
+
(TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
|
| 1181 |
+
assert F_2.doit() == \
|
| 1182 |
+
TransferFunctionMatrix(((TransferFunction(s*(-2*s**2 + s*(2*s - 1) + 1), s**2 - s + 1, s),
|
| 1183 |
+
TransferFunction(-2*s**3*(s - 1), s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(s*(1 - s), 1, s))))
|
| 1184 |
+
assert F_2.doit(expand=True) == \
|
| 1185 |
+
TransferFunctionMatrix(((TransferFunction(-s**2 + s, s**2 - s + 1, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
|
| 1186 |
+
(TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
|
| 1187 |
+
|
| 1188 |
+
assert -(F_1.doit()) == (-F_1).doit() # First negating then calculating vs calculating then negating.
|
| 1189 |
+
|
| 1190 |
+
|
| 1191 |
+
def test_TransferFunctionMatrix_construction():
|
| 1192 |
+
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
|
| 1193 |
+
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
|
| 1194 |
+
|
| 1195 |
+
tfm3_ = TransferFunctionMatrix([[-TF3]])
|
| 1196 |
+
assert tfm3_.shape == (tfm3_.num_outputs, tfm3_.num_inputs) == (1, 1)
|
| 1197 |
+
assert tfm3_.args == Tuple(Tuple(Tuple(-TF3)))
|
| 1198 |
+
assert tfm3_.var == s
|
| 1199 |
+
|
| 1200 |
+
tfm5 = TransferFunctionMatrix([[TF1, -TF2], [TF3, tf5]])
|
| 1201 |
+
assert tfm5.shape == (tfm5.num_outputs, tfm5.num_inputs) == (2, 2)
|
| 1202 |
+
assert tfm5.args == Tuple(Tuple(Tuple(TF1, -TF2), Tuple(TF3, tf5)))
|
| 1203 |
+
assert tfm5.var == s
|
| 1204 |
+
|
| 1205 |
+
tfm7 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5], [-tf5, TF2]])
|
| 1206 |
+
assert tfm7.shape == (tfm7.num_outputs, tfm7.num_inputs) == (3, 2)
|
| 1207 |
+
assert tfm7.args == Tuple(Tuple(Tuple(TF1, TF2), Tuple(TF3, -tf5), Tuple(-tf5, TF2)))
|
| 1208 |
+
assert tfm7.var == s
|
| 1209 |
+
|
| 1210 |
+
# all transfer functions will use the same complex variable. tf4 uses 'p'.
|
| 1211 |
+
raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF2], [tf4]]))
|
| 1212 |
+
raises(ValueError, lambda: TransferFunctionMatrix([[TF1, tf4], [TF3, tf5]]))
|
| 1213 |
+
|
| 1214 |
+
# length of all the lists in the TFM should be equal.
|
| 1215 |
+
raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF3, tf5]]))
|
| 1216 |
+
raises(ValueError, lambda: TransferFunctionMatrix([[TF1, TF3], [tf5]]))
|
| 1217 |
+
|
| 1218 |
+
# lists should only support transfer functions in them.
|
| 1219 |
+
raises(TypeError, lambda: TransferFunctionMatrix([[TF1, TF2], [TF3, Matrix([1, 2])]]))
|
| 1220 |
+
raises(TypeError, lambda: TransferFunctionMatrix([[TF1, Matrix([1, 2])], [TF3, TF2]]))
|
| 1221 |
+
|
| 1222 |
+
# `arg` should strictly be nested list of TransferFunction
|
| 1223 |
+
raises(ValueError, lambda: TransferFunctionMatrix([TF1, TF2, tf5]))
|
| 1224 |
+
raises(ValueError, lambda: TransferFunctionMatrix([TF1]))
|
| 1225 |
+
|
| 1226 |
+
def test_TransferFunctionMatrix_functions():
|
| 1227 |
+
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
|
| 1228 |
+
|
| 1229 |
+
# Classmethod (from_matrix)
|
| 1230 |
+
|
| 1231 |
+
mat_1 = ImmutableMatrix([
|
| 1232 |
+
[s*(s + 1)*(s - 3)/(s**4 + 1), 2],
|
| 1233 |
+
[p, p*(s + 1)/(s*(s**1 + 1))]
|
| 1234 |
+
])
|
| 1235 |
+
mat_2 = ImmutableMatrix([[(2*s + 1)/(s**2 - 9)]])
|
| 1236 |
+
mat_3 = ImmutableMatrix([[1, 2], [3, 4]])
|
| 1237 |
+
assert TransferFunctionMatrix.from_Matrix(mat_1, s) == \
|
| 1238 |
+
TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)],
|
| 1239 |
+
[TransferFunction(p, 1, s), TransferFunction(p, s, s)]])
|
| 1240 |
+
assert TransferFunctionMatrix.from_Matrix(mat_2, s) == \
|
| 1241 |
+
TransferFunctionMatrix([[TransferFunction(2*s + 1, s**2 - 9, s)]])
|
| 1242 |
+
assert TransferFunctionMatrix.from_Matrix(mat_3, p) == \
|
| 1243 |
+
TransferFunctionMatrix([[TransferFunction(1, 1, p), TransferFunction(2, 1, p)],
|
| 1244 |
+
[TransferFunction(3, 1, p), TransferFunction(4, 1, p)]])
|
| 1245 |
+
|
| 1246 |
+
# Negating a TFM
|
| 1247 |
+
|
| 1248 |
+
tfm1 = TransferFunctionMatrix([[TF1], [TF2]])
|
| 1249 |
+
assert -tfm1 == TransferFunctionMatrix([[-TF1], [-TF2]])
|
| 1250 |
+
|
| 1251 |
+
tfm2 = TransferFunctionMatrix([[TF1, TF2, TF3], [tf5, -TF1, -TF3]])
|
| 1252 |
+
assert -tfm2 == TransferFunctionMatrix([[-TF1, -TF2, -TF3], [-tf5, TF1, TF3]])
|
| 1253 |
+
|
| 1254 |
+
# subs()
|
| 1255 |
+
|
| 1256 |
+
H_1 = TransferFunctionMatrix.from_Matrix(mat_1, s)
|
| 1257 |
+
H_2 = TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(s**2 - a), s)]])
|
| 1258 |
+
assert H_1.subs(p, 1) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
|
| 1259 |
+
assert H_1.subs({p: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
|
| 1260 |
+
assert H_1.subs({p: 1, s: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) # This should ignore `s` as it is `var`
|
| 1261 |
+
assert H_2.subs(p, 2) == TransferFunctionMatrix([[TransferFunction(2*a*s, k*s**2, s), TransferFunction(2*s, k*(-a + s**2), s)]])
|
| 1262 |
+
assert H_2.subs(k, 1) == TransferFunctionMatrix([[TransferFunction(a*p*s, s**2, s), TransferFunction(p*s, -a + s**2, s)]])
|
| 1263 |
+
assert H_2.subs(a, 0) == TransferFunctionMatrix([[TransferFunction(0, k*s**2, s), TransferFunction(p*s, k*s**2, s)]])
|
| 1264 |
+
assert H_2.subs({p: 1, k: 1, a: a0}) == TransferFunctionMatrix([[TransferFunction(a0*s, s**2, s), TransferFunction(s, -a0 + s**2, s)]])
|
| 1265 |
+
|
| 1266 |
+
# eval_frequency()
|
| 1267 |
+
assert H_2.eval_frequency(S(1)/2 + I) == Matrix([[2*a*p/(5*k) - 4*I*a*p/(5*k), I*p/(-a*k - 3*k/4 + I*k) + p/(-2*a*k - 3*k/2 + 2*I*k)]])
|
| 1268 |
+
|
| 1269 |
+
# transpose()
|
| 1270 |
+
|
| 1271 |
+
assert H_1.transpose() == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(p, 1, s)], [TransferFunction(2, 1, s), TransferFunction(p, s, s)]])
|
| 1272 |
+
assert H_2.transpose() == TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s)], [TransferFunction(p*s, k*(-a + s**2), s)]])
|
| 1273 |
+
assert H_1.transpose().transpose() == H_1
|
| 1274 |
+
assert H_2.transpose().transpose() == H_2
|
| 1275 |
+
|
| 1276 |
+
# elem_poles()
|
| 1277 |
+
|
| 1278 |
+
assert H_1.elem_poles() == [[[-sqrt(2)/2 - sqrt(2)*I/2, -sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2, sqrt(2)/2 + sqrt(2)*I/2], []],
|
| 1279 |
+
[[], [0]]]
|
| 1280 |
+
assert H_2.elem_poles() == [[[0, 0], [sqrt(a), -sqrt(a)]]]
|
| 1281 |
+
assert tfm2.elem_poles() == [[[wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [], [-p/a2]],
|
| 1282 |
+
[[-a0], [wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [-p/a2]]]
|
| 1283 |
+
|
| 1284 |
+
# elem_zeros()
|
| 1285 |
+
|
| 1286 |
+
assert H_1.elem_zeros() == [[[-1, 0, 3], []], [[], []]]
|
| 1287 |
+
assert H_2.elem_zeros() == [[[0], [0]]]
|
| 1288 |
+
assert tfm2.elem_zeros() == [[[], [], [a2*p]],
|
| 1289 |
+
[[-a2/(2*a1) - sqrt(4*a0*a1 + a2**2)/(2*a1), -a2/(2*a1) + sqrt(4*a0*a1 + a2**2)/(2*a1)], [], [a2*p]]]
|
| 1290 |
+
|
| 1291 |
+
# doit()
|
| 1292 |
+
|
| 1293 |
+
H_3 = TransferFunctionMatrix([[Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]])
|
| 1294 |
+
H_4 = TransferFunctionMatrix([[Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]])
|
| 1295 |
+
|
| 1296 |
+
assert H_3.doit() == TransferFunctionMatrix([[TransferFunction(s**2 - 2*s + 5, s*(s**3 - 3), s)]])
|
| 1297 |
+
assert H_4.doit() == TransferFunctionMatrix([[TransferFunction(1, 4*s**4 - s**2 - 2*s + 5, s)]])
|
| 1298 |
+
|
| 1299 |
+
# _flat()
|
| 1300 |
+
|
| 1301 |
+
assert H_1._flat() == [TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s), TransferFunction(p, 1, s), TransferFunction(p, s, s)]
|
| 1302 |
+
assert H_2._flat() == [TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(-a + s**2), s)]
|
| 1303 |
+
assert H_3._flat() == [Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]
|
| 1304 |
+
assert H_4._flat() == [Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]
|
| 1305 |
+
|
| 1306 |
+
# evalf()
|
| 1307 |
+
|
| 1308 |
+
assert H_1.evalf() == \
|
| 1309 |
+
TransferFunctionMatrix(((TransferFunction(s*(s - 3.0)*(s + 1.0), s**4 + 1.0, s), TransferFunction(2.0, 1, s)), (TransferFunction(1.0*p, 1, s), TransferFunction(p, s, s))))
|
| 1310 |
+
assert H_2.subs({a:3.141, p:2.88, k:2}).evalf() == \
|
| 1311 |
+
TransferFunctionMatrix(((TransferFunction(4.5230399999999999494093572138808667659759521484375, s, s),
|
| 1312 |
+
TransferFunction(2.87999999999999989341858963598497211933135986328125*s, 2.0*s**2 - 6.282000000000000028421709430404007434844970703125, s)),))
|
| 1313 |
+
|
| 1314 |
+
# simplify()
|
| 1315 |
+
|
| 1316 |
+
H_5 = TransferFunctionMatrix([[TransferFunction(s**5 + s**3 + s, s - s**2, s),
|
| 1317 |
+
TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)]])
|
| 1318 |
+
|
| 1319 |
+
assert H_5.simplify() == simplify(H_5) == \
|
| 1320 |
+
TransferFunctionMatrix(((TransferFunction(-s**4 - s**2 - 1, s - 1, s), TransferFunction(s + 3, s + 5, s)),))
|
| 1321 |
+
|
| 1322 |
+
# expand()
|
| 1323 |
+
|
| 1324 |
+
assert (H_1.expand()
|
| 1325 |
+
== TransferFunctionMatrix(((TransferFunction(s**3 - 2*s**2 - 3*s, s**4 + 1, s), TransferFunction(2, 1, s)),
|
| 1326 |
+
(TransferFunction(p, 1, s), TransferFunction(p, s, s)))))
|
| 1327 |
+
assert H_5.expand() == \
|
| 1328 |
+
TransferFunctionMatrix(((TransferFunction(s**5 + s**3 + s, -s**2 + s, s), TransferFunction(s**2 + 2*s - 3, s**2 + 4*s - 5, s)),))
|
| 1329 |
+
|
| 1330 |
+
def test_TransferFunction_gbt():
|
| 1331 |
+
# simple transfer function, e.g. ohms law
|
| 1332 |
+
tf = TransferFunction(1, a*s+b, s)
|
| 1333 |
+
numZ, denZ = gbt(tf, T, 0.5)
|
| 1334 |
+
# discretized transfer function with coefs from tf.gbt()
|
| 1335 |
+
tf_test_bilinear = TransferFunction(s * numZ[0] + numZ[1], s * denZ[0] + denZ[1], s)
|
| 1336 |
+
# corresponding tf with manually calculated coefs
|
| 1337 |
+
tf_test_manual = TransferFunction(s * T/(2*(a + b*T/2)) + T/(2*(a + b*T/2)), s + (-a + b*T/2)/(a + b*T/2), s)
|
| 1338 |
+
|
| 1339 |
+
assert S.Zero == (tf_test_bilinear.simplify()-tf_test_manual.simplify()).simplify().num
|
| 1340 |
+
|
| 1341 |
+
tf = TransferFunction(1, a*s+b, s)
|
| 1342 |
+
numZ, denZ = gbt(tf, T, 0)
|
| 1343 |
+
# discretized transfer function with coefs from tf.gbt()
|
| 1344 |
+
tf_test_forward = TransferFunction(numZ[0], s*denZ[0]+denZ[1], s)
|
| 1345 |
+
# corresponding tf with manually calculated coefs
|
| 1346 |
+
tf_test_manual = TransferFunction(T/a, s + (-a + b*T)/a, s)
|
| 1347 |
+
|
| 1348 |
+
assert S.Zero == (tf_test_forward.simplify()-tf_test_manual.simplify()).simplify().num
|
| 1349 |
+
|
| 1350 |
+
tf = TransferFunction(1, a*s+b, s)
|
| 1351 |
+
numZ, denZ = gbt(tf, T, 1)
|
| 1352 |
+
# discretized transfer function with coefs from tf.gbt()
|
| 1353 |
+
tf_test_backward = TransferFunction(s*numZ[0], s*denZ[0]+denZ[1], s)
|
| 1354 |
+
# corresponding tf with manually calculated coefs
|
| 1355 |
+
tf_test_manual = TransferFunction(s * T/(a + b*T), s - a/(a + b*T), s)
|
| 1356 |
+
|
| 1357 |
+
assert S.Zero == (tf_test_backward.simplify()-tf_test_manual.simplify()).simplify().num
|
| 1358 |
+
|
| 1359 |
+
tf = TransferFunction(1, a*s+b, s)
|
| 1360 |
+
numZ, denZ = gbt(tf, T, 0.3)
|
| 1361 |
+
# discretized transfer function with coefs from tf.gbt()
|
| 1362 |
+
tf_test_gbt = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s)
|
| 1363 |
+
# corresponding tf with manually calculated coefs
|
| 1364 |
+
tf_test_manual = TransferFunction(s*3*T/(10*(a + 3*b*T/10)) + 7*T/(10*(a + 3*b*T/10)), s + (-a + 7*b*T/10)/(a + 3*b*T/10), s)
|
| 1365 |
+
|
| 1366 |
+
assert S.Zero == (tf_test_gbt.simplify()-tf_test_manual.simplify()).simplify().num
|
| 1367 |
+
|
| 1368 |
+
def test_TransferFunction_bilinear():
|
| 1369 |
+
# simple transfer function, e.g. ohms law
|
| 1370 |
+
tf = TransferFunction(1, a*s+b, s)
|
| 1371 |
+
numZ, denZ = bilinear(tf, T)
|
| 1372 |
+
# discretized transfer function with coefs from tf.bilinear()
|
| 1373 |
+
tf_test_bilinear = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s)
|
| 1374 |
+
# corresponding tf with manually calculated coefs
|
| 1375 |
+
tf_test_manual = TransferFunction(s * T/(2*(a + b*T/2)) + T/(2*(a + b*T/2)), s + (-a + b*T/2)/(a + b*T/2), s)
|
| 1376 |
+
|
| 1377 |
+
assert S.Zero == (tf_test_bilinear.simplify()-tf_test_manual.simplify()).simplify().num
|
| 1378 |
+
|
| 1379 |
+
def test_TransferFunction_forward_diff():
|
| 1380 |
+
# simple transfer function, e.g. ohms law
|
| 1381 |
+
tf = TransferFunction(1, a*s+b, s)
|
| 1382 |
+
numZ, denZ = forward_diff(tf, T)
|
| 1383 |
+
# discretized transfer function with coefs from tf.forward_diff()
|
| 1384 |
+
tf_test_forward = TransferFunction(numZ[0], s*denZ[0]+denZ[1], s)
|
| 1385 |
+
# corresponding tf with manually calculated coefs
|
| 1386 |
+
tf_test_manual = TransferFunction(T/a, s + (-a + b*T)/a, s)
|
| 1387 |
+
|
| 1388 |
+
assert S.Zero == (tf_test_forward.simplify()-tf_test_manual.simplify()).simplify().num
|
| 1389 |
+
|
| 1390 |
+
def test_TransferFunction_backward_diff():
|
| 1391 |
+
# simple transfer function, e.g. ohms law
|
| 1392 |
+
tf = TransferFunction(1, a*s+b, s)
|
| 1393 |
+
numZ, denZ = backward_diff(tf, T)
|
| 1394 |
+
# discretized transfer function with coefs from tf.backward_diff()
|
| 1395 |
+
tf_test_backward = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s)
|
| 1396 |
+
# corresponding tf with manually calculated coefs
|
| 1397 |
+
tf_test_manual = TransferFunction(s * T/(a + b*T), s - a/(a + b*T), s)
|
| 1398 |
+
|
| 1399 |
+
assert S.Zero == (tf_test_backward.simplify()-tf_test_manual.simplify()).simplify().num
|
| 1400 |
+
|
| 1401 |
+
def test_TransferFunction_phase_margin():
|
| 1402 |
+
# Test for phase margin
|
| 1403 |
+
tf1 = TransferFunction(10, p**3 + 1, p)
|
| 1404 |
+
tf2 = TransferFunction(s**2, 10, s)
|
| 1405 |
+
tf3 = TransferFunction(1, a*s+b, s)
|
| 1406 |
+
tf4 = TransferFunction((s + 1)*exp(s/tau), s**2 + 2, s)
|
| 1407 |
+
tf_m = TransferFunctionMatrix([[tf2],[tf3]])
|
| 1408 |
+
|
| 1409 |
+
assert phase_margin(tf1) == -180 + 180*atan(3*sqrt(11))/pi
|
| 1410 |
+
assert phase_margin(tf2) == 0
|
| 1411 |
+
|
| 1412 |
+
raises(NotImplementedError, lambda: phase_margin(tf4))
|
| 1413 |
+
raises(ValueError, lambda: phase_margin(tf3))
|
| 1414 |
+
raises(ValueError, lambda: phase_margin(MIMOSeries(tf_m)))
|
| 1415 |
+
|
| 1416 |
+
def test_TransferFunction_gain_margin():
|
| 1417 |
+
# Test for gain margin
|
| 1418 |
+
tf1 = TransferFunction(s**2, 5*(s+1)*(s-5)*(s-10), s)
|
| 1419 |
+
tf2 = TransferFunction(s**2 + 2*s + 1, 1, s)
|
| 1420 |
+
tf3 = TransferFunction(1, a*s+b, s)
|
| 1421 |
+
tf4 = TransferFunction((s + 1)*exp(s/tau), s**2 + 2, s)
|
| 1422 |
+
tf_m = TransferFunctionMatrix([[tf2],[tf3]])
|
| 1423 |
+
|
| 1424 |
+
assert gain_margin(tf1) == -20*log(S(7)/540)/log(10)
|
| 1425 |
+
assert gain_margin(tf2) == oo
|
| 1426 |
+
|
| 1427 |
+
raises(NotImplementedError, lambda: gain_margin(tf4))
|
| 1428 |
+
raises(ValueError, lambda: gain_margin(tf3))
|
| 1429 |
+
raises(ValueError, lambda: gain_margin(MIMOSeries(tf_m)))
|
| 1430 |
+
|
| 1431 |
+
|
| 1432 |
+
def test_StateSpace_construction():
|
| 1433 |
+
# using different numbers for a SISO system.
|
| 1434 |
+
A1 = Matrix([[0, 1], [1, 0]])
|
| 1435 |
+
B1 = Matrix([1, 0])
|
| 1436 |
+
C1 = Matrix([[0, 1]])
|
| 1437 |
+
D1 = Matrix([0])
|
| 1438 |
+
ss1 = StateSpace(A1, B1, C1, D1)
|
| 1439 |
+
|
| 1440 |
+
assert ss1.state_matrix == Matrix([[0, 1], [1, 0]])
|
| 1441 |
+
assert ss1.input_matrix == Matrix([1, 0])
|
| 1442 |
+
assert ss1.output_matrix == Matrix([[0, 1]])
|
| 1443 |
+
assert ss1.feedforward_matrix == Matrix([0])
|
| 1444 |
+
assert ss1.args == (Matrix([[0, 1], [1, 0]]), Matrix([[1], [0]]), Matrix([[0, 1]]), Matrix([[0]]))
|
| 1445 |
+
|
| 1446 |
+
# using different symbols for a SISO system.
|
| 1447 |
+
ss2 = StateSpace(Matrix([a0]), Matrix([a1]),
|
| 1448 |
+
Matrix([a2]), Matrix([a3]))
|
| 1449 |
+
|
| 1450 |
+
assert ss2.state_matrix == Matrix([[a0]])
|
| 1451 |
+
assert ss2.input_matrix == Matrix([[a1]])
|
| 1452 |
+
assert ss2.output_matrix == Matrix([[a2]])
|
| 1453 |
+
assert ss2.feedforward_matrix == Matrix([[a3]])
|
| 1454 |
+
assert ss2.args == (Matrix([[a0]]), Matrix([[a1]]), Matrix([[a2]]), Matrix([[a3]]))
|
| 1455 |
+
|
| 1456 |
+
# using different numbers for a MIMO system.
|
| 1457 |
+
ss3 = StateSpace(Matrix([[-1.5, -2], [1, 0]]),
|
| 1458 |
+
Matrix([[0.5, 0], [0, 1]]),
|
| 1459 |
+
Matrix([[0, 1], [0, 2]]),
|
| 1460 |
+
Matrix([[2, 2], [1, 1]]))
|
| 1461 |
+
|
| 1462 |
+
assert ss3.state_matrix == Matrix([[-1.5, -2], [1, 0]])
|
| 1463 |
+
assert ss3.input_matrix == Matrix([[0.5, 0], [0, 1]])
|
| 1464 |
+
assert ss3.output_matrix == Matrix([[0, 1], [0, 2]])
|
| 1465 |
+
assert ss3.feedforward_matrix == Matrix([[2, 2], [1, 1]])
|
| 1466 |
+
assert ss3.args == (Matrix([[-1.5, -2],
|
| 1467 |
+
[1, 0]]),
|
| 1468 |
+
Matrix([[0.5, 0],
|
| 1469 |
+
[0, 1]]),
|
| 1470 |
+
Matrix([[0, 1],
|
| 1471 |
+
[0, 2]]),
|
| 1472 |
+
Matrix([[2, 2],
|
| 1473 |
+
[1, 1]]))
|
| 1474 |
+
|
| 1475 |
+
# using different symbols for a MIMO system.
|
| 1476 |
+
A4 = Matrix([[a0, a1], [a2, a3]])
|
| 1477 |
+
B4 = Matrix([[b0, b1], [b2, b3]])
|
| 1478 |
+
C4 = Matrix([[c0, c1], [c2, c3]])
|
| 1479 |
+
D4 = Matrix([[d0, d1], [d2, d3]])
|
| 1480 |
+
ss4 = StateSpace(A4, B4, C4, D4)
|
| 1481 |
+
|
| 1482 |
+
assert ss4.state_matrix == Matrix([[a0, a1], [a2, a3]])
|
| 1483 |
+
assert ss4.input_matrix == Matrix([[b0, b1], [b2, b3]])
|
| 1484 |
+
assert ss4.output_matrix == Matrix([[c0, c1], [c2, c3]])
|
| 1485 |
+
assert ss4.feedforward_matrix == Matrix([[d0, d1], [d2, d3]])
|
| 1486 |
+
assert ss4.args == (Matrix([[a0, a1],
|
| 1487 |
+
[a2, a3]]),
|
| 1488 |
+
Matrix([[b0, b1],
|
| 1489 |
+
[b2, b3]]),
|
| 1490 |
+
Matrix([[c0, c1],
|
| 1491 |
+
[c2, c3]]),
|
| 1492 |
+
Matrix([[d0, d1],
|
| 1493 |
+
[d2, d3]]))
|
| 1494 |
+
|
| 1495 |
+
# using less matrices. Rest will be filled with a minimum of zeros.
|
| 1496 |
+
ss5 = StateSpace()
|
| 1497 |
+
assert ss5.args == (Matrix([[0]]), Matrix([[0]]), Matrix([[0]]), Matrix([[0]]))
|
| 1498 |
+
|
| 1499 |
+
A6 = Matrix([[0, 1], [1, 0]])
|
| 1500 |
+
B6 = Matrix([1, 1])
|
| 1501 |
+
ss6 = StateSpace(A6, B6)
|
| 1502 |
+
|
| 1503 |
+
assert ss6.state_matrix == Matrix([[0, 1], [1, 0]])
|
| 1504 |
+
assert ss6.input_matrix == Matrix([1, 1])
|
| 1505 |
+
assert ss6.output_matrix == Matrix([[0, 0]])
|
| 1506 |
+
assert ss6.feedforward_matrix == Matrix([[0]])
|
| 1507 |
+
assert ss6.args == (Matrix([[0, 1],
|
| 1508 |
+
[1, 0]]),
|
| 1509 |
+
Matrix([[1],
|
| 1510 |
+
[1]]),
|
| 1511 |
+
Matrix([[0, 0]]),
|
| 1512 |
+
Matrix([[0]]))
|
| 1513 |
+
|
| 1514 |
+
# Check if the system is SISO or MIMO.
|
| 1515 |
+
# If system is not SISO, then it is definitely MIMO.
|
| 1516 |
+
|
| 1517 |
+
assert ss1.is_SISO == True
|
| 1518 |
+
assert ss2.is_SISO == True
|
| 1519 |
+
assert ss3.is_SISO == False
|
| 1520 |
+
assert ss4.is_SISO == False
|
| 1521 |
+
assert ss5.is_SISO == True
|
| 1522 |
+
assert ss6.is_SISO == True
|
| 1523 |
+
|
| 1524 |
+
# ShapeError if matrices do not fit.
|
| 1525 |
+
raises(ShapeError, lambda: StateSpace(Matrix([s, (s+1)**2]), Matrix([s+1]),
|
| 1526 |
+
Matrix([s**2 - 1]), Matrix([2*s])))
|
| 1527 |
+
raises(ShapeError, lambda: StateSpace(Matrix([s]), Matrix([s+1, s**3 + 1]),
|
| 1528 |
+
Matrix([s**2 - 1]), Matrix([2*s])))
|
| 1529 |
+
raises(ShapeError, lambda: StateSpace(Matrix([s]), Matrix([s+1]),
|
| 1530 |
+
Matrix([[s**2 - 1], [s**2 + 2*s + 1]]), Matrix([2*s])))
|
| 1531 |
+
raises(ShapeError, lambda: StateSpace(Matrix([[-s, -s], [s, 0]]),
|
| 1532 |
+
Matrix([[s/2, 0], [0, s]]),
|
| 1533 |
+
Matrix([[0, s]]),
|
| 1534 |
+
Matrix([[2*s, 2*s], [s, s]])))
|
| 1535 |
+
|
| 1536 |
+
# TypeError if arguments are not sympy matrices.
|
| 1537 |
+
raises(TypeError, lambda: StateSpace(s**2, s+1, 2*s, 1))
|
| 1538 |
+
raises(TypeError, lambda: StateSpace(Matrix([2, 0.5]), Matrix([-1]),
|
| 1539 |
+
Matrix([1]), 0))
|
| 1540 |
+
def test_StateSpace_add():
|
| 1541 |
+
A1 = Matrix([[4, 1],[2, -3]])
|
| 1542 |
+
B1 = Matrix([[5, 2],[-3, -3]])
|
| 1543 |
+
C1 = Matrix([[2, -4],[0, 1]])
|
| 1544 |
+
D1 = Matrix([[3, 2],[1, -1]])
|
| 1545 |
+
ss1 = StateSpace(A1, B1, C1, D1)
|
| 1546 |
+
|
| 1547 |
+
A2 = Matrix([[-3, 4, 2],[-1, -3, 0],[2, 5, 3]])
|
| 1548 |
+
B2 = Matrix([[1, 4],[-3, -3],[-2, 1]])
|
| 1549 |
+
C2 = Matrix([[4, 2, -3],[1, 4, 3]])
|
| 1550 |
+
D2 = Matrix([[-2, 4],[0, 1]])
|
| 1551 |
+
ss2 = StateSpace(A2, B2, C2, D2)
|
| 1552 |
+
ss3 = StateSpace()
|
| 1553 |
+
ss4 = StateSpace(Matrix([1]), Matrix([2]), Matrix([3]), Matrix([4]))
|
| 1554 |
+
|
| 1555 |
+
expected_add = \
|
| 1556 |
+
StateSpace(
|
| 1557 |
+
Matrix([
|
| 1558 |
+
[4, 1, 0, 0, 0],
|
| 1559 |
+
[2, -3, 0, 0, 0],
|
| 1560 |
+
[0, 0, -3, 4, 2],
|
| 1561 |
+
[0, 0, -1, -3, 0],
|
| 1562 |
+
[0, 0, 2, 5, 3]]),
|
| 1563 |
+
Matrix([
|
| 1564 |
+
[ 5, 2],
|
| 1565 |
+
[-3, -3],
|
| 1566 |
+
[ 1, 4],
|
| 1567 |
+
[-3, -3],
|
| 1568 |
+
[-2, 1]]),
|
| 1569 |
+
Matrix([
|
| 1570 |
+
[2, -4, 4, 2, -3],
|
| 1571 |
+
[0, 1, 1, 4, 3]]),
|
| 1572 |
+
Matrix([
|
| 1573 |
+
[1, 6],
|
| 1574 |
+
[1, 0]]))
|
| 1575 |
+
|
| 1576 |
+
expected_mul = \
|
| 1577 |
+
StateSpace(
|
| 1578 |
+
Matrix([
|
| 1579 |
+
[ -3, 4, 2, 0, 0],
|
| 1580 |
+
[ -1, -3, 0, 0, 0],
|
| 1581 |
+
[ 2, 5, 3, 0, 0],
|
| 1582 |
+
[ 22, 18, -9, 4, 1],
|
| 1583 |
+
[-15, -18, 0, 2, -3]]),
|
| 1584 |
+
Matrix([
|
| 1585 |
+
[ 1, 4],
|
| 1586 |
+
[ -3, -3],
|
| 1587 |
+
[ -2, 1],
|
| 1588 |
+
[-10, 22],
|
| 1589 |
+
[ 6, -15]]),
|
| 1590 |
+
Matrix([
|
| 1591 |
+
[14, 14, -3, 2, -4],
|
| 1592 |
+
[ 3, -2, -6, 0, 1]]),
|
| 1593 |
+
Matrix([
|
| 1594 |
+
[-6, 14],
|
| 1595 |
+
[-2, 3]]))
|
| 1596 |
+
|
| 1597 |
+
assert ss1 + ss2 == expected_add
|
| 1598 |
+
assert ss1*ss2 == expected_mul
|
| 1599 |
+
assert ss3 + 1/2 == StateSpace(Matrix([[0]]), Matrix([[0]]), Matrix([[0]]), Matrix([[0.5]]))
|
| 1600 |
+
assert ss4*1.5 == StateSpace(Matrix([[1]]), Matrix([[2]]), Matrix([[4.5]]), Matrix([[6.0]]))
|
| 1601 |
+
assert 1.5*ss4 == StateSpace(Matrix([[1]]), Matrix([[3.0]]), Matrix([[3]]), Matrix([[6.0]]))
|
| 1602 |
+
raises(ShapeError, lambda: ss1 + ss3)
|
| 1603 |
+
raises(ShapeError, lambda: ss2*ss4)
|
| 1604 |
+
|
| 1605 |
+
def test_StateSpace_negation():
|
| 1606 |
+
A = Matrix([[a0, a1], [a2, a3]])
|
| 1607 |
+
B = Matrix([[b0, b1], [b2, b3]])
|
| 1608 |
+
C = Matrix([[c0, c1], [c1, c2], [c2, c3]])
|
| 1609 |
+
D = Matrix([[d0, d1], [d1, d2], [d2, d3]])
|
| 1610 |
+
SS = StateSpace(A, B, C, D)
|
| 1611 |
+
SS_neg = -SS
|
| 1612 |
+
|
| 1613 |
+
state_mat = Matrix([[-1, 1], [1, -1]])
|
| 1614 |
+
input_mat = Matrix([1, -1])
|
| 1615 |
+
output_mat = Matrix([[-1, 1]])
|
| 1616 |
+
feedforward_mat = Matrix([1])
|
| 1617 |
+
system = StateSpace(state_mat, input_mat, output_mat, feedforward_mat)
|
| 1618 |
+
|
| 1619 |
+
assert SS_neg == \
|
| 1620 |
+
StateSpace(Matrix([[a0, a1],
|
| 1621 |
+
[a2, a3]]),
|
| 1622 |
+
Matrix([[b0, b1],
|
| 1623 |
+
[b2, b3]]),
|
| 1624 |
+
Matrix([[-c0, -c1],
|
| 1625 |
+
[-c1, -c2],
|
| 1626 |
+
[-c2, -c3]]),
|
| 1627 |
+
Matrix([[-d0, -d1],
|
| 1628 |
+
[-d1, -d2],
|
| 1629 |
+
[-d2, -d3]]))
|
| 1630 |
+
assert -system == \
|
| 1631 |
+
StateSpace(Matrix([[-1, 1],
|
| 1632 |
+
[ 1, -1]]),
|
| 1633 |
+
Matrix([[ 1],[-1]]),
|
| 1634 |
+
Matrix([[1, -1]]),
|
| 1635 |
+
Matrix([[-1]]))
|
| 1636 |
+
assert -SS_neg == SS
|
| 1637 |
+
assert -(-(-(-system))) == system
|
| 1638 |
+
|
| 1639 |
+
def test_SymPy_substitution_functions():
|
| 1640 |
+
# subs
|
| 1641 |
+
ss1 = StateSpace(Matrix([s]), Matrix([(s + 1)**2]), Matrix([s**2 - 1]), Matrix([2*s]))
|
| 1642 |
+
ss2 = StateSpace(Matrix([s + p]), Matrix([(s + 1)*(p - 1)]), Matrix([p**3 - s**3]), Matrix([s - p]))
|
| 1643 |
+
|
| 1644 |
+
assert ss1.subs({s:5}) == StateSpace(Matrix([[5]]), Matrix([[36]]), Matrix([[24]]), Matrix([[10]]))
|
| 1645 |
+
assert ss2.subs({p:1}) == StateSpace(Matrix([[s + 1]]), Matrix([[0]]), Matrix([[1 - s**3]]), Matrix([[s - 1]]))
|
| 1646 |
+
|
| 1647 |
+
# xreplace
|
| 1648 |
+
assert ss1.xreplace({s:p}) == \
|
| 1649 |
+
StateSpace(Matrix([[p]]), Matrix([[(p + 1)**2]]), Matrix([[p**2 - 1]]), Matrix([[2*p]]))
|
| 1650 |
+
assert ss2.xreplace({s:a, p:b}) == \
|
| 1651 |
+
StateSpace(Matrix([[a + b]]), Matrix([[(a + 1)*(b - 1)]]), Matrix([[-a**3 + b**3]]), Matrix([[a - b]]))
|
| 1652 |
+
|
| 1653 |
+
# evalf
|
| 1654 |
+
p1 = a1*s + a0
|
| 1655 |
+
p2 = b2*s**2 + b1*s + b0
|
| 1656 |
+
G = StateSpace(Matrix([p1]), Matrix([p2]))
|
| 1657 |
+
expect = StateSpace(Matrix([[2*s + 1]]), Matrix([[5*s**2 + 4*s + 3]]), Matrix([[0]]), Matrix([[0]]))
|
| 1658 |
+
expect_ = StateSpace(Matrix([[2.0*s + 1.0]]), Matrix([[5.0*s**2 + 4.0*s + 3.0]]), Matrix([[0]]), Matrix([[0]]))
|
| 1659 |
+
assert G.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect
|
| 1660 |
+
assert G.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect_
|
| 1661 |
+
assert expect.evalf() == expect_
|
| 1662 |
+
|
| 1663 |
+
def test_conversion():
|
| 1664 |
+
# StateSpace to TransferFunction for SISO
|
| 1665 |
+
A1 = Matrix([[-5, -1], [3, -1]])
|
| 1666 |
+
B1 = Matrix([2, 5])
|
| 1667 |
+
C1 = Matrix([[1, 2]])
|
| 1668 |
+
D1 = Matrix([0])
|
| 1669 |
+
H1 = StateSpace(A1, B1, C1, D1)
|
| 1670 |
+
tm1 = H1.rewrite(TransferFunction)
|
| 1671 |
+
tm2 = (-H1).rewrite(TransferFunction)
|
| 1672 |
+
|
| 1673 |
+
tf1 = tm1[0][0]
|
| 1674 |
+
tf2 = tm2[0][0]
|
| 1675 |
+
|
| 1676 |
+
assert tf1 == TransferFunction(12*s + 59, s**2 + 6*s + 8, s)
|
| 1677 |
+
assert tf2.num == -tf1.num
|
| 1678 |
+
assert tf2.den == tf1.den
|
| 1679 |
+
|
| 1680 |
+
# StateSpace to TransferFunction for MIMO
|
| 1681 |
+
A2 = Matrix([[-1.5, -2, 3], [1, 0, 1], [2, 1, 1]])
|
| 1682 |
+
B2 = Matrix([[0.5, 0, 1], [0, 1, 2], [2, 2, 3]])
|
| 1683 |
+
C2 = Matrix([[0, 1, 0], [0, 2, 1], [1, 0, 2]])
|
| 1684 |
+
D2 = Matrix([[2, 2, 0], [1, 1, 1], [3, 2, 1]])
|
| 1685 |
+
H2 = StateSpace(A2, B2, C2, D2)
|
| 1686 |
+
tm3 = H2.rewrite(TransferFunction)
|
| 1687 |
+
|
| 1688 |
+
# outputs for input i obtained at Index i-1. Consider input 1
|
| 1689 |
+
assert tm3[0][0] == TransferFunction(2.0*s**3 + 1.0*s**2 - 10.5*s + 4.5, 1.0*s**3 + 0.5*s**2 - 6.5*s - 2.5, s)
|
| 1690 |
+
assert tm3[0][1] == TransferFunction(2.0*s**3 + 2.0*s**2 - 10.5*s - 3.5, 1.0*s**3 + 0.5*s**2 - 6.5*s - 2.5, s)
|
| 1691 |
+
assert tm3[0][2] == TransferFunction(2.0*s**2 + 5.0*s - 0.5, 1.0*s**3 + 0.5*s**2 - 6.5*s - 2.5, s)
|
| 1692 |
+
|
| 1693 |
+
# TransferFunction to StateSpace
|
| 1694 |
+
SS = TF1.rewrite(StateSpace)
|
| 1695 |
+
assert SS == \
|
| 1696 |
+
StateSpace(Matrix([[ 0, 1],
|
| 1697 |
+
[-wn**2, -2*wn*zeta]]),
|
| 1698 |
+
Matrix([[0],
|
| 1699 |
+
[1]]),
|
| 1700 |
+
Matrix([[1, 0]]),
|
| 1701 |
+
Matrix([[0]]))
|
| 1702 |
+
assert SS.rewrite(TransferFunction)[0][0] == TF1
|
| 1703 |
+
|
| 1704 |
+
# Transfer function has to be proper
|
| 1705 |
+
raises(ValueError, lambda: TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s).rewrite(StateSpace))
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
def test_StateSpace_functions():
|
| 1709 |
+
# https://in.mathworks.com/help/control/ref/statespacemodel.obsv.html
|
| 1710 |
+
|
| 1711 |
+
A_mat = Matrix([[-1.5, -2], [1, 0]])
|
| 1712 |
+
B_mat = Matrix([0.5, 0])
|
| 1713 |
+
C_mat = Matrix([[0, 1]])
|
| 1714 |
+
D_mat = Matrix([1])
|
| 1715 |
+
SS1 = StateSpace(A_mat, B_mat, C_mat, D_mat)
|
| 1716 |
+
SS2 = StateSpace(Matrix([[1, 1], [4, -2]]),Matrix([[0, 1], [0, 2]]),Matrix([[-1, 1], [1, -1]]))
|
| 1717 |
+
SS3 = StateSpace(Matrix([[1, 1], [4, -2]]),Matrix([[1, -1], [1, -1]]))
|
| 1718 |
+
|
| 1719 |
+
# Observability
|
| 1720 |
+
assert SS1.is_observable() == True
|
| 1721 |
+
assert SS2.is_observable() == False
|
| 1722 |
+
assert SS1.observability_matrix() == Matrix([[0, 1], [1, 0]])
|
| 1723 |
+
assert SS2.observability_matrix() == Matrix([[-1, 1], [ 1, -1], [ 3, -3], [-3, 3]])
|
| 1724 |
+
assert SS1.observable_subspace() == [Matrix([[0], [1]]), Matrix([[1], [0]])]
|
| 1725 |
+
assert SS2.observable_subspace() == [Matrix([[-1], [ 1], [ 3], [-3]])]
|
| 1726 |
+
|
| 1727 |
+
# Controllability
|
| 1728 |
+
assert SS1.is_controllable() == True
|
| 1729 |
+
assert SS3.is_controllable() == False
|
| 1730 |
+
assert SS1.controllability_matrix() == Matrix([[0.5, -0.75], [ 0, 0.5]])
|
| 1731 |
+
assert SS3.controllability_matrix() == Matrix([[1, -1, 2, -2], [1, -1, 2, -2]])
|
| 1732 |
+
assert SS1.controllable_subspace() == [Matrix([[0.5], [ 0]]), Matrix([[-0.75], [ 0.5]])]
|
| 1733 |
+
assert SS3.controllable_subspace() == [Matrix([[1], [1]])]
|
| 1734 |
+
|
| 1735 |
+
# Append
|
| 1736 |
+
A1 = Matrix([[0, 1], [1, 0]])
|
| 1737 |
+
B1 = Matrix([[0], [1]])
|
| 1738 |
+
C1 = Matrix([[0, 1]])
|
| 1739 |
+
D1 = Matrix([[0]])
|
| 1740 |
+
ss1 = StateSpace(A1, B1, C1, D1)
|
| 1741 |
+
ss2 = StateSpace(Matrix([[1, 0], [0, 1]]), Matrix([[1], [0]]), Matrix([[1, 0]]), Matrix([[1]]))
|
| 1742 |
+
ss3 = ss1.append(ss2)
|
| 1743 |
+
|
| 1744 |
+
assert ss3.num_states == ss1.num_states + ss2.num_states
|
| 1745 |
+
assert ss3.num_inputs == ss1.num_inputs + ss2.num_inputs
|
| 1746 |
+
assert ss3.num_outputs == ss1.num_outputs + ss2.num_outputs
|
| 1747 |
+
assert ss3.state_matrix == Matrix([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
|
| 1748 |
+
assert ss3.input_matrix == Matrix([[0, 0], [1, 0], [0, 1], [0, 0]])
|
| 1749 |
+
assert ss3.output_matrix == Matrix([[0, 1, 0, 0], [0, 0, 1, 0]])
|
| 1750 |
+
assert ss3.feedforward_matrix == Matrix([[0, 0], [0, 1]])
|
wemm/lib/python3.10/site-packages/sympy/physics/optics/gaussopt.py
ADDED
|
@@ -0,0 +1,923 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gaussian optics.
|
| 3 |
+
|
| 4 |
+
The module implements:
|
| 5 |
+
|
| 6 |
+
- Ray transfer matrices for geometrical and gaussian optics.
|
| 7 |
+
|
| 8 |
+
See RayTransferMatrix, GeometricRay and BeamParameter
|
| 9 |
+
|
| 10 |
+
- Conjugation relations for geometrical and gaussian optics.
|
| 11 |
+
|
| 12 |
+
See geometric_conj*, gauss_conj and conjugate_gauss_beams
|
| 13 |
+
|
| 14 |
+
The conventions for the distances are as follows:
|
| 15 |
+
|
| 16 |
+
focal distance
|
| 17 |
+
positive for convergent lenses
|
| 18 |
+
object distance
|
| 19 |
+
positive for real objects
|
| 20 |
+
image distance
|
| 21 |
+
positive for real images
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
'RayTransferMatrix',
|
| 26 |
+
'FreeSpace',
|
| 27 |
+
'FlatRefraction',
|
| 28 |
+
'CurvedRefraction',
|
| 29 |
+
'FlatMirror',
|
| 30 |
+
'CurvedMirror',
|
| 31 |
+
'ThinLens',
|
| 32 |
+
'GeometricRay',
|
| 33 |
+
'BeamParameter',
|
| 34 |
+
'waist2rayleigh',
|
| 35 |
+
'rayleigh2waist',
|
| 36 |
+
'geometric_conj_ab',
|
| 37 |
+
'geometric_conj_af',
|
| 38 |
+
'geometric_conj_bf',
|
| 39 |
+
'gaussian_conj',
|
| 40 |
+
'conjugate_gauss_beams',
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
from sympy.core.expr import Expr
|
| 45 |
+
from sympy.core.numbers import (I, pi)
|
| 46 |
+
from sympy.core.sympify import sympify
|
| 47 |
+
from sympy.functions.elementary.complexes import (im, re)
|
| 48 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 49 |
+
from sympy.functions.elementary.trigonometric import atan2
|
| 50 |
+
from sympy.matrices.dense import Matrix, MutableDenseMatrix
|
| 51 |
+
from sympy.polys.rationaltools import together
|
| 52 |
+
from sympy.utilities.misc import filldedent
|
| 53 |
+
|
| 54 |
+
###
|
| 55 |
+
# A, B, C, D matrices
|
| 56 |
+
###
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class RayTransferMatrix(MutableDenseMatrix):
|
| 60 |
+
"""
|
| 61 |
+
Base class for a Ray Transfer Matrix.
|
| 62 |
+
|
| 63 |
+
It should be used if there is not already a more specific subclass mentioned
|
| 64 |
+
in See Also.
|
| 65 |
+
|
| 66 |
+
Parameters
|
| 67 |
+
==========
|
| 68 |
+
|
| 69 |
+
parameters :
|
| 70 |
+
A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D]))
|
| 71 |
+
|
| 72 |
+
Examples
|
| 73 |
+
========
|
| 74 |
+
|
| 75 |
+
>>> from sympy.physics.optics import RayTransferMatrix, ThinLens
|
| 76 |
+
>>> from sympy import Symbol, Matrix
|
| 77 |
+
|
| 78 |
+
>>> mat = RayTransferMatrix(1, 2, 3, 4)
|
| 79 |
+
>>> mat
|
| 80 |
+
Matrix([
|
| 81 |
+
[1, 2],
|
| 82 |
+
[3, 4]])
|
| 83 |
+
|
| 84 |
+
>>> RayTransferMatrix(Matrix([[1, 2], [3, 4]]))
|
| 85 |
+
Matrix([
|
| 86 |
+
[1, 2],
|
| 87 |
+
[3, 4]])
|
| 88 |
+
|
| 89 |
+
>>> mat.A
|
| 90 |
+
1
|
| 91 |
+
|
| 92 |
+
>>> f = Symbol('f')
|
| 93 |
+
>>> lens = ThinLens(f)
|
| 94 |
+
>>> lens
|
| 95 |
+
Matrix([
|
| 96 |
+
[ 1, 0],
|
| 97 |
+
[-1/f, 1]])
|
| 98 |
+
|
| 99 |
+
>>> lens.C
|
| 100 |
+
-1/f
|
| 101 |
+
|
| 102 |
+
See Also
|
| 103 |
+
========
|
| 104 |
+
|
| 105 |
+
GeometricRay, BeamParameter,
|
| 106 |
+
FreeSpace, FlatRefraction, CurvedRefraction,
|
| 107 |
+
FlatMirror, CurvedMirror, ThinLens
|
| 108 |
+
|
| 109 |
+
References
|
| 110 |
+
==========
|
| 111 |
+
|
| 112 |
+
.. [1] https://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
def __new__(cls, *args):
|
| 116 |
+
|
| 117 |
+
if len(args) == 4:
|
| 118 |
+
temp = ((args[0], args[1]), (args[2], args[3]))
|
| 119 |
+
elif len(args) == 1 \
|
| 120 |
+
and isinstance(args[0], Matrix) \
|
| 121 |
+
and args[0].shape == (2, 2):
|
| 122 |
+
temp = args[0]
|
| 123 |
+
else:
|
| 124 |
+
raise ValueError(filldedent('''
|
| 125 |
+
Expecting 2x2 Matrix or the 4 elements of
|
| 126 |
+
the Matrix but got %s''' % str(args)))
|
| 127 |
+
return Matrix.__new__(cls, temp)
|
| 128 |
+
|
| 129 |
+
def __mul__(self, other):
|
| 130 |
+
if isinstance(other, RayTransferMatrix):
|
| 131 |
+
return RayTransferMatrix(Matrix(self)*Matrix(other))
|
| 132 |
+
elif isinstance(other, GeometricRay):
|
| 133 |
+
return GeometricRay(Matrix(self)*Matrix(other))
|
| 134 |
+
elif isinstance(other, BeamParameter):
|
| 135 |
+
temp = Matrix(self)*Matrix(((other.q,), (1,)))
|
| 136 |
+
q = (temp[0]/temp[1]).expand(complex=True)
|
| 137 |
+
return BeamParameter(other.wavelen,
|
| 138 |
+
together(re(q)),
|
| 139 |
+
z_r=together(im(q)))
|
| 140 |
+
else:
|
| 141 |
+
return Matrix.__mul__(self, other)
|
| 142 |
+
|
| 143 |
+
@property
|
| 144 |
+
def A(self):
|
| 145 |
+
"""
|
| 146 |
+
The A parameter of the Matrix.
|
| 147 |
+
|
| 148 |
+
Examples
|
| 149 |
+
========
|
| 150 |
+
|
| 151 |
+
>>> from sympy.physics.optics import RayTransferMatrix
|
| 152 |
+
>>> mat = RayTransferMatrix(1, 2, 3, 4)
|
| 153 |
+
>>> mat.A
|
| 154 |
+
1
|
| 155 |
+
"""
|
| 156 |
+
return self[0, 0]
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def B(self):
|
| 160 |
+
"""
|
| 161 |
+
The B parameter of the Matrix.
|
| 162 |
+
|
| 163 |
+
Examples
|
| 164 |
+
========
|
| 165 |
+
|
| 166 |
+
>>> from sympy.physics.optics import RayTransferMatrix
|
| 167 |
+
>>> mat = RayTransferMatrix(1, 2, 3, 4)
|
| 168 |
+
>>> mat.B
|
| 169 |
+
2
|
| 170 |
+
"""
|
| 171 |
+
return self[0, 1]
|
| 172 |
+
|
| 173 |
+
@property
|
| 174 |
+
def C(self):
|
| 175 |
+
"""
|
| 176 |
+
The C parameter of the Matrix.
|
| 177 |
+
|
| 178 |
+
Examples
|
| 179 |
+
========
|
| 180 |
+
|
| 181 |
+
>>> from sympy.physics.optics import RayTransferMatrix
|
| 182 |
+
>>> mat = RayTransferMatrix(1, 2, 3, 4)
|
| 183 |
+
>>> mat.C
|
| 184 |
+
3
|
| 185 |
+
"""
|
| 186 |
+
return self[1, 0]
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def D(self):
|
| 190 |
+
"""
|
| 191 |
+
The D parameter of the Matrix.
|
| 192 |
+
|
| 193 |
+
Examples
|
| 194 |
+
========
|
| 195 |
+
|
| 196 |
+
>>> from sympy.physics.optics import RayTransferMatrix
|
| 197 |
+
>>> mat = RayTransferMatrix(1, 2, 3, 4)
|
| 198 |
+
>>> mat.D
|
| 199 |
+
4
|
| 200 |
+
"""
|
| 201 |
+
return self[1, 1]
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class FreeSpace(RayTransferMatrix):
|
| 205 |
+
"""
|
| 206 |
+
Ray Transfer Matrix for free space.
|
| 207 |
+
|
| 208 |
+
Parameters
|
| 209 |
+
==========
|
| 210 |
+
|
| 211 |
+
distance
|
| 212 |
+
|
| 213 |
+
See Also
|
| 214 |
+
========
|
| 215 |
+
|
| 216 |
+
RayTransferMatrix
|
| 217 |
+
|
| 218 |
+
Examples
|
| 219 |
+
========
|
| 220 |
+
|
| 221 |
+
>>> from sympy.physics.optics import FreeSpace
|
| 222 |
+
>>> from sympy import symbols
|
| 223 |
+
>>> d = symbols('d')
|
| 224 |
+
>>> FreeSpace(d)
|
| 225 |
+
Matrix([
|
| 226 |
+
[1, d],
|
| 227 |
+
[0, 1]])
|
| 228 |
+
"""
|
| 229 |
+
def __new__(cls, d):
|
| 230 |
+
return RayTransferMatrix.__new__(cls, 1, d, 0, 1)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class FlatRefraction(RayTransferMatrix):
|
| 234 |
+
"""
|
| 235 |
+
Ray Transfer Matrix for refraction.
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
==========
|
| 239 |
+
|
| 240 |
+
n1 :
|
| 241 |
+
Refractive index of one medium.
|
| 242 |
+
n2 :
|
| 243 |
+
Refractive index of other medium.
|
| 244 |
+
|
| 245 |
+
See Also
|
| 246 |
+
========
|
| 247 |
+
|
| 248 |
+
RayTransferMatrix
|
| 249 |
+
|
| 250 |
+
Examples
|
| 251 |
+
========
|
| 252 |
+
|
| 253 |
+
>>> from sympy.physics.optics import FlatRefraction
|
| 254 |
+
>>> from sympy import symbols
|
| 255 |
+
>>> n1, n2 = symbols('n1 n2')
|
| 256 |
+
>>> FlatRefraction(n1, n2)
|
| 257 |
+
Matrix([
|
| 258 |
+
[1, 0],
|
| 259 |
+
[0, n1/n2]])
|
| 260 |
+
"""
|
| 261 |
+
def __new__(cls, n1, n2):
|
| 262 |
+
n1, n2 = map(sympify, (n1, n2))
|
| 263 |
+
return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class CurvedRefraction(RayTransferMatrix):
|
| 267 |
+
"""
|
| 268 |
+
Ray Transfer Matrix for refraction on curved interface.
|
| 269 |
+
|
| 270 |
+
Parameters
|
| 271 |
+
==========
|
| 272 |
+
|
| 273 |
+
R :
|
| 274 |
+
Radius of curvature (positive for concave).
|
| 275 |
+
n1 :
|
| 276 |
+
Refractive index of one medium.
|
| 277 |
+
n2 :
|
| 278 |
+
Refractive index of other medium.
|
| 279 |
+
|
| 280 |
+
See Also
|
| 281 |
+
========
|
| 282 |
+
|
| 283 |
+
RayTransferMatrix
|
| 284 |
+
|
| 285 |
+
Examples
|
| 286 |
+
========
|
| 287 |
+
|
| 288 |
+
>>> from sympy.physics.optics import CurvedRefraction
|
| 289 |
+
>>> from sympy import symbols
|
| 290 |
+
>>> R, n1, n2 = symbols('R n1 n2')
|
| 291 |
+
>>> CurvedRefraction(R, n1, n2)
|
| 292 |
+
Matrix([
|
| 293 |
+
[ 1, 0],
|
| 294 |
+
[(n1 - n2)/(R*n2), n1/n2]])
|
| 295 |
+
"""
|
| 296 |
+
def __new__(cls, R, n1, n2):
|
| 297 |
+
R, n1, n2 = map(sympify, (R, n1, n2))
|
| 298 |
+
return RayTransferMatrix.__new__(cls, 1, 0, (n1 - n2)/R/n2, n1/n2)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class FlatMirror(RayTransferMatrix):
|
| 302 |
+
"""
|
| 303 |
+
Ray Transfer Matrix for reflection.
|
| 304 |
+
|
| 305 |
+
See Also
|
| 306 |
+
========
|
| 307 |
+
|
| 308 |
+
RayTransferMatrix
|
| 309 |
+
|
| 310 |
+
Examples
|
| 311 |
+
========
|
| 312 |
+
|
| 313 |
+
>>> from sympy.physics.optics import FlatMirror
|
| 314 |
+
>>> FlatMirror()
|
| 315 |
+
Matrix([
|
| 316 |
+
[1, 0],
|
| 317 |
+
[0, 1]])
|
| 318 |
+
"""
|
| 319 |
+
def __new__(cls):
|
| 320 |
+
return RayTransferMatrix.__new__(cls, 1, 0, 0, 1)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class CurvedMirror(RayTransferMatrix):
|
| 324 |
+
"""
|
| 325 |
+
Ray Transfer Matrix for reflection from curved surface.
|
| 326 |
+
|
| 327 |
+
Parameters
|
| 328 |
+
==========
|
| 329 |
+
|
| 330 |
+
R : radius of curvature (positive for concave)
|
| 331 |
+
|
| 332 |
+
See Also
|
| 333 |
+
========
|
| 334 |
+
|
| 335 |
+
RayTransferMatrix
|
| 336 |
+
|
| 337 |
+
Examples
|
| 338 |
+
========
|
| 339 |
+
|
| 340 |
+
>>> from sympy.physics.optics import CurvedMirror
|
| 341 |
+
>>> from sympy import symbols
|
| 342 |
+
>>> R = symbols('R')
|
| 343 |
+
>>> CurvedMirror(R)
|
| 344 |
+
Matrix([
|
| 345 |
+
[ 1, 0],
|
| 346 |
+
[-2/R, 1]])
|
| 347 |
+
"""
|
| 348 |
+
def __new__(cls, R):
|
| 349 |
+
R = sympify(R)
|
| 350 |
+
return RayTransferMatrix.__new__(cls, 1, 0, -2/R, 1)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class ThinLens(RayTransferMatrix):
|
| 354 |
+
"""
|
| 355 |
+
Ray Transfer Matrix for a thin lens.
|
| 356 |
+
|
| 357 |
+
Parameters
|
| 358 |
+
==========
|
| 359 |
+
|
| 360 |
+
f :
|
| 361 |
+
The focal distance.
|
| 362 |
+
|
| 363 |
+
See Also
|
| 364 |
+
========
|
| 365 |
+
|
| 366 |
+
RayTransferMatrix
|
| 367 |
+
|
| 368 |
+
Examples
|
| 369 |
+
========
|
| 370 |
+
|
| 371 |
+
>>> from sympy.physics.optics import ThinLens
|
| 372 |
+
>>> from sympy import symbols
|
| 373 |
+
>>> f = symbols('f')
|
| 374 |
+
>>> ThinLens(f)
|
| 375 |
+
Matrix([
|
| 376 |
+
[ 1, 0],
|
| 377 |
+
[-1/f, 1]])
|
| 378 |
+
"""
|
| 379 |
+
def __new__(cls, f):
|
| 380 |
+
f = sympify(f)
|
| 381 |
+
return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
###
|
| 385 |
+
# Representation for geometric ray
|
| 386 |
+
###
|
| 387 |
+
|
| 388 |
+
class GeometricRay(MutableDenseMatrix):
|
| 389 |
+
"""
|
| 390 |
+
Representation for a geometric ray in the Ray Transfer Matrix formalism.
|
| 391 |
+
|
| 392 |
+
Parameters
|
| 393 |
+
==========
|
| 394 |
+
|
| 395 |
+
h : height, and
|
| 396 |
+
angle : angle, or
|
| 397 |
+
matrix : a 2x1 matrix (Matrix(2, 1, [height, angle]))
|
| 398 |
+
|
| 399 |
+
Examples
|
| 400 |
+
========
|
| 401 |
+
|
| 402 |
+
>>> from sympy.physics.optics import GeometricRay, FreeSpace
|
| 403 |
+
>>> from sympy import symbols, Matrix
|
| 404 |
+
>>> d, h, angle = symbols('d, h, angle')
|
| 405 |
+
|
| 406 |
+
>>> GeometricRay(h, angle)
|
| 407 |
+
Matrix([
|
| 408 |
+
[ h],
|
| 409 |
+
[angle]])
|
| 410 |
+
|
| 411 |
+
>>> FreeSpace(d)*GeometricRay(h, angle)
|
| 412 |
+
Matrix([
|
| 413 |
+
[angle*d + h],
|
| 414 |
+
[ angle]])
|
| 415 |
+
|
| 416 |
+
>>> GeometricRay( Matrix( ((h,), (angle,)) ) )
|
| 417 |
+
Matrix([
|
| 418 |
+
[ h],
|
| 419 |
+
[angle]])
|
| 420 |
+
|
| 421 |
+
See Also
|
| 422 |
+
========
|
| 423 |
+
|
| 424 |
+
RayTransferMatrix
|
| 425 |
+
|
| 426 |
+
"""
|
| 427 |
+
|
| 428 |
+
def __new__(cls, *args):
|
| 429 |
+
if len(args) == 1 and isinstance(args[0], Matrix) \
|
| 430 |
+
and args[0].shape == (2, 1):
|
| 431 |
+
temp = args[0]
|
| 432 |
+
elif len(args) == 2:
|
| 433 |
+
temp = ((args[0],), (args[1],))
|
| 434 |
+
else:
|
| 435 |
+
raise ValueError(filldedent('''
|
| 436 |
+
Expecting 2x1 Matrix or the 2 elements of
|
| 437 |
+
the Matrix but got %s''' % str(args)))
|
| 438 |
+
return Matrix.__new__(cls, temp)
|
| 439 |
+
|
| 440 |
+
@property
|
| 441 |
+
def height(self):
|
| 442 |
+
"""
|
| 443 |
+
The distance from the optical axis.
|
| 444 |
+
|
| 445 |
+
Examples
|
| 446 |
+
========
|
| 447 |
+
|
| 448 |
+
>>> from sympy.physics.optics import GeometricRay
|
| 449 |
+
>>> from sympy import symbols
|
| 450 |
+
>>> h, angle = symbols('h, angle')
|
| 451 |
+
>>> gRay = GeometricRay(h, angle)
|
| 452 |
+
>>> gRay.height
|
| 453 |
+
h
|
| 454 |
+
"""
|
| 455 |
+
return self[0]
|
| 456 |
+
|
| 457 |
+
@property
|
| 458 |
+
def angle(self):
|
| 459 |
+
"""
|
| 460 |
+
The angle with the optical axis.
|
| 461 |
+
|
| 462 |
+
Examples
|
| 463 |
+
========
|
| 464 |
+
|
| 465 |
+
>>> from sympy.physics.optics import GeometricRay
|
| 466 |
+
>>> from sympy import symbols
|
| 467 |
+
>>> h, angle = symbols('h, angle')
|
| 468 |
+
>>> gRay = GeometricRay(h, angle)
|
| 469 |
+
>>> gRay.angle
|
| 470 |
+
angle
|
| 471 |
+
"""
|
| 472 |
+
return self[1]
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
###
|
| 476 |
+
# Representation for gauss beam
|
| 477 |
+
###
|
| 478 |
+
|
| 479 |
+
class BeamParameter(Expr):
|
| 480 |
+
"""
|
| 481 |
+
Representation for a gaussian ray in the Ray Transfer Matrix formalism.
|
| 482 |
+
|
| 483 |
+
Parameters
|
| 484 |
+
==========
|
| 485 |
+
|
| 486 |
+
wavelen : the wavelength,
|
| 487 |
+
z : the distance to waist, and
|
| 488 |
+
w : the waist, or
|
| 489 |
+
z_r : the rayleigh range.
|
| 490 |
+
n : the refractive index of medium.
|
| 491 |
+
|
| 492 |
+
Examples
|
| 493 |
+
========
|
| 494 |
+
|
| 495 |
+
>>> from sympy.physics.optics import BeamParameter
|
| 496 |
+
>>> p = BeamParameter(530e-9, 1, w=1e-3)
|
| 497 |
+
>>> p.q
|
| 498 |
+
1 + 1.88679245283019*I*pi
|
| 499 |
+
|
| 500 |
+
>>> p.q.n()
|
| 501 |
+
1.0 + 5.92753330865999*I
|
| 502 |
+
>>> p.w_0.n()
|
| 503 |
+
0.00100000000000000
|
| 504 |
+
>>> p.z_r.n()
|
| 505 |
+
5.92753330865999
|
| 506 |
+
|
| 507 |
+
>>> from sympy.physics.optics import FreeSpace
|
| 508 |
+
>>> fs = FreeSpace(10)
|
| 509 |
+
>>> p1 = fs*p
|
| 510 |
+
>>> p.w.n()
|
| 511 |
+
0.00101413072159615
|
| 512 |
+
>>> p1.w.n()
|
| 513 |
+
0.00210803120913829
|
| 514 |
+
|
| 515 |
+
See Also
|
| 516 |
+
========
|
| 517 |
+
|
| 518 |
+
RayTransferMatrix
|
| 519 |
+
|
| 520 |
+
References
|
| 521 |
+
==========
|
| 522 |
+
|
| 523 |
+
.. [1] https://en.wikipedia.org/wiki/Complex_beam_parameter
|
| 524 |
+
.. [2] https://en.wikipedia.org/wiki/Gaussian_beam
|
| 525 |
+
"""
|
| 526 |
+
#TODO A class Complex may be implemented. The BeamParameter may
|
| 527 |
+
# subclass it. See:
|
| 528 |
+
# https://groups.google.com/d/topic/sympy/7XkU07NRBEs/discussion
|
| 529 |
+
|
| 530 |
+
def __new__(cls, wavelen, z, z_r=None, w=None, n=1):
|
| 531 |
+
wavelen = sympify(wavelen)
|
| 532 |
+
z = sympify(z)
|
| 533 |
+
n = sympify(n)
|
| 534 |
+
|
| 535 |
+
if z_r is not None and w is None:
|
| 536 |
+
z_r = sympify(z_r)
|
| 537 |
+
elif w is not None and z_r is None:
|
| 538 |
+
z_r = waist2rayleigh(sympify(w), wavelen, n)
|
| 539 |
+
elif z_r is None and w is None:
|
| 540 |
+
raise ValueError('Must specify one of w and z_r.')
|
| 541 |
+
|
| 542 |
+
return Expr.__new__(cls, wavelen, z, z_r, n)
|
| 543 |
+
|
| 544 |
+
@property
|
| 545 |
+
def wavelen(self):
|
| 546 |
+
return self.args[0]
|
| 547 |
+
|
| 548 |
+
@property
|
| 549 |
+
def z(self):
|
| 550 |
+
return self.args[1]
|
| 551 |
+
|
| 552 |
+
@property
|
| 553 |
+
def z_r(self):
|
| 554 |
+
return self.args[2]
|
| 555 |
+
|
| 556 |
+
@property
|
| 557 |
+
def n(self):
|
| 558 |
+
return self.args[3]
|
| 559 |
+
|
| 560 |
+
@property
|
| 561 |
+
def q(self):
|
| 562 |
+
"""
|
| 563 |
+
The complex parameter representing the beam.
|
| 564 |
+
|
| 565 |
+
Examples
|
| 566 |
+
========
|
| 567 |
+
|
| 568 |
+
>>> from sympy.physics.optics import BeamParameter
|
| 569 |
+
>>> p = BeamParameter(530e-9, 1, w=1e-3)
|
| 570 |
+
>>> p.q
|
| 571 |
+
1 + 1.88679245283019*I*pi
|
| 572 |
+
"""
|
| 573 |
+
return self.z + I*self.z_r
|
| 574 |
+
|
| 575 |
+
@property
|
| 576 |
+
def radius(self):
|
| 577 |
+
"""
|
| 578 |
+
The radius of curvature of the phase front.
|
| 579 |
+
|
| 580 |
+
Examples
|
| 581 |
+
========
|
| 582 |
+
|
| 583 |
+
>>> from sympy.physics.optics import BeamParameter
|
| 584 |
+
>>> p = BeamParameter(530e-9, 1, w=1e-3)
|
| 585 |
+
>>> p.radius
|
| 586 |
+
1 + 3.55998576005696*pi**2
|
| 587 |
+
"""
|
| 588 |
+
return self.z*(1 + (self.z_r/self.z)**2)
|
| 589 |
+
|
| 590 |
+
@property
|
| 591 |
+
def w(self):
|
| 592 |
+
"""
|
| 593 |
+
The radius of the beam w(z), at any position z along the beam.
|
| 594 |
+
The beam radius at `1/e^2` intensity (axial value).
|
| 595 |
+
|
| 596 |
+
See Also
|
| 597 |
+
========
|
| 598 |
+
|
| 599 |
+
w_0 :
|
| 600 |
+
The minimal radius of beam.
|
| 601 |
+
|
| 602 |
+
Examples
|
| 603 |
+
========
|
| 604 |
+
|
| 605 |
+
>>> from sympy.physics.optics import BeamParameter
|
| 606 |
+
>>> p = BeamParameter(530e-9, 1, w=1e-3)
|
| 607 |
+
>>> p.w
|
| 608 |
+
0.001*sqrt(0.2809/pi**2 + 1)
|
| 609 |
+
"""
|
| 610 |
+
return self.w_0*sqrt(1 + (self.z/self.z_r)**2)
|
| 611 |
+
|
| 612 |
+
@property
|
| 613 |
+
def w_0(self):
|
| 614 |
+
"""
|
| 615 |
+
The minimal radius of beam at `1/e^2` intensity (peak value).
|
| 616 |
+
|
| 617 |
+
See Also
|
| 618 |
+
========
|
| 619 |
+
|
| 620 |
+
w : the beam radius at `1/e^2` intensity (axial value).
|
| 621 |
+
|
| 622 |
+
Examples
|
| 623 |
+
========
|
| 624 |
+
|
| 625 |
+
>>> from sympy.physics.optics import BeamParameter
|
| 626 |
+
>>> p = BeamParameter(530e-9, 1, w=1e-3)
|
| 627 |
+
>>> p.w_0
|
| 628 |
+
0.00100000000000000
|
| 629 |
+
"""
|
| 630 |
+
return sqrt(self.z_r/(pi*self.n)*self.wavelen)
|
| 631 |
+
|
| 632 |
+
@property
|
| 633 |
+
def divergence(self):
|
| 634 |
+
"""
|
| 635 |
+
Half of the total angular spread.
|
| 636 |
+
|
| 637 |
+
Examples
|
| 638 |
+
========
|
| 639 |
+
|
| 640 |
+
>>> from sympy.physics.optics import BeamParameter
|
| 641 |
+
>>> p = BeamParameter(530e-9, 1, w=1e-3)
|
| 642 |
+
>>> p.divergence
|
| 643 |
+
0.00053/pi
|
| 644 |
+
"""
|
| 645 |
+
return self.wavelen/pi/self.w_0
|
| 646 |
+
|
| 647 |
+
@property
|
| 648 |
+
def gouy(self):
|
| 649 |
+
"""
|
| 650 |
+
The Gouy phase.
|
| 651 |
+
|
| 652 |
+
Examples
|
| 653 |
+
========
|
| 654 |
+
|
| 655 |
+
>>> from sympy.physics.optics import BeamParameter
|
| 656 |
+
>>> p = BeamParameter(530e-9, 1, w=1e-3)
|
| 657 |
+
>>> p.gouy
|
| 658 |
+
atan(0.53/pi)
|
| 659 |
+
"""
|
| 660 |
+
return atan2(self.z, self.z_r)
|
| 661 |
+
|
| 662 |
+
@property
|
| 663 |
+
def waist_approximation_limit(self):
|
| 664 |
+
"""
|
| 665 |
+
The minimal waist for which the gauss beam approximation is valid.
|
| 666 |
+
|
| 667 |
+
Explanation
|
| 668 |
+
===========
|
| 669 |
+
|
| 670 |
+
The gauss beam is a solution to the paraxial equation. For curvatures
|
| 671 |
+
that are too great it is not a valid approximation.
|
| 672 |
+
|
| 673 |
+
Examples
|
| 674 |
+
========
|
| 675 |
+
|
| 676 |
+
>>> from sympy.physics.optics import BeamParameter
|
| 677 |
+
>>> p = BeamParameter(530e-9, 1, w=1e-3)
|
| 678 |
+
>>> p.waist_approximation_limit
|
| 679 |
+
1.06e-6/pi
|
| 680 |
+
"""
|
| 681 |
+
return 2*self.wavelen/pi
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
###
|
| 685 |
+
# Utilities
|
| 686 |
+
###
|
| 687 |
+
|
| 688 |
+
def waist2rayleigh(w, wavelen, n=1):
|
| 689 |
+
"""
|
| 690 |
+
Calculate the rayleigh range from the waist of a gaussian beam.
|
| 691 |
+
|
| 692 |
+
See Also
|
| 693 |
+
========
|
| 694 |
+
|
| 695 |
+
rayleigh2waist, BeamParameter
|
| 696 |
+
|
| 697 |
+
Examples
|
| 698 |
+
========
|
| 699 |
+
|
| 700 |
+
>>> from sympy.physics.optics import waist2rayleigh
|
| 701 |
+
>>> from sympy import symbols
|
| 702 |
+
>>> w, wavelen = symbols('w wavelen')
|
| 703 |
+
>>> waist2rayleigh(w, wavelen)
|
| 704 |
+
pi*w**2/wavelen
|
| 705 |
+
"""
|
| 706 |
+
w, wavelen = map(sympify, (w, wavelen))
|
| 707 |
+
return w**2*n*pi/wavelen
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def rayleigh2waist(z_r, wavelen):
|
| 711 |
+
"""Calculate the waist from the rayleigh range of a gaussian beam.
|
| 712 |
+
|
| 713 |
+
See Also
|
| 714 |
+
========
|
| 715 |
+
|
| 716 |
+
waist2rayleigh, BeamParameter
|
| 717 |
+
|
| 718 |
+
Examples
|
| 719 |
+
========
|
| 720 |
+
|
| 721 |
+
>>> from sympy.physics.optics import rayleigh2waist
|
| 722 |
+
>>> from sympy import symbols
|
| 723 |
+
>>> z_r, wavelen = symbols('z_r wavelen')
|
| 724 |
+
>>> rayleigh2waist(z_r, wavelen)
|
| 725 |
+
sqrt(wavelen*z_r)/sqrt(pi)
|
| 726 |
+
"""
|
| 727 |
+
z_r, wavelen = map(sympify, (z_r, wavelen))
|
| 728 |
+
return sqrt(z_r/pi*wavelen)
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def geometric_conj_ab(a, b):
|
| 732 |
+
"""
|
| 733 |
+
Conjugation relation for geometrical beams under paraxial conditions.
|
| 734 |
+
|
| 735 |
+
Explanation
|
| 736 |
+
===========
|
| 737 |
+
|
| 738 |
+
Takes the distances to the optical element and returns the needed
|
| 739 |
+
focal distance.
|
| 740 |
+
|
| 741 |
+
See Also
|
| 742 |
+
========
|
| 743 |
+
|
| 744 |
+
geometric_conj_af, geometric_conj_bf
|
| 745 |
+
|
| 746 |
+
Examples
|
| 747 |
+
========
|
| 748 |
+
|
| 749 |
+
>>> from sympy.physics.optics import geometric_conj_ab
|
| 750 |
+
>>> from sympy import symbols
|
| 751 |
+
>>> a, b = symbols('a b')
|
| 752 |
+
>>> geometric_conj_ab(a, b)
|
| 753 |
+
a*b/(a + b)
|
| 754 |
+
"""
|
| 755 |
+
a, b = map(sympify, (a, b))
|
| 756 |
+
if a.is_infinite or b.is_infinite:
|
| 757 |
+
return a if b.is_infinite else b
|
| 758 |
+
else:
|
| 759 |
+
return a*b/(a + b)
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def geometric_conj_af(a, f):
|
| 763 |
+
"""
|
| 764 |
+
Conjugation relation for geometrical beams under paraxial conditions.
|
| 765 |
+
|
| 766 |
+
Explanation
|
| 767 |
+
===========
|
| 768 |
+
|
| 769 |
+
Takes the object distance (for geometric_conj_af) or the image distance
|
| 770 |
+
(for geometric_conj_bf) to the optical element and the focal distance.
|
| 771 |
+
Then it returns the other distance needed for conjugation.
|
| 772 |
+
|
| 773 |
+
See Also
|
| 774 |
+
========
|
| 775 |
+
|
| 776 |
+
geometric_conj_ab
|
| 777 |
+
|
| 778 |
+
Examples
|
| 779 |
+
========
|
| 780 |
+
|
| 781 |
+
>>> from sympy.physics.optics.gaussopt import geometric_conj_af, geometric_conj_bf
|
| 782 |
+
>>> from sympy import symbols
|
| 783 |
+
>>> a, b, f = symbols('a b f')
|
| 784 |
+
>>> geometric_conj_af(a, f)
|
| 785 |
+
a*f/(a - f)
|
| 786 |
+
>>> geometric_conj_bf(b, f)
|
| 787 |
+
b*f/(b - f)
|
| 788 |
+
"""
|
| 789 |
+
a, f = map(sympify, (a, f))
|
| 790 |
+
return -geometric_conj_ab(a, -f)
|
| 791 |
+
|
| 792 |
+
geometric_conj_bf = geometric_conj_af
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def gaussian_conj(s_in, z_r_in, f):
|
| 796 |
+
"""
|
| 797 |
+
Conjugation relation for gaussian beams.
|
| 798 |
+
|
| 799 |
+
Parameters
|
| 800 |
+
==========
|
| 801 |
+
|
| 802 |
+
s_in :
|
| 803 |
+
The distance to optical element from the waist.
|
| 804 |
+
z_r_in :
|
| 805 |
+
The rayleigh range of the incident beam.
|
| 806 |
+
f :
|
| 807 |
+
The focal length of the optical element.
|
| 808 |
+
|
| 809 |
+
Returns
|
| 810 |
+
=======
|
| 811 |
+
|
| 812 |
+
a tuple containing (s_out, z_r_out, m)
|
| 813 |
+
s_out :
|
| 814 |
+
The distance between the new waist and the optical element.
|
| 815 |
+
z_r_out :
|
| 816 |
+
The rayleigh range of the emergent beam.
|
| 817 |
+
m :
|
| 818 |
+
The ration between the new and the old waists.
|
| 819 |
+
|
| 820 |
+
Examples
|
| 821 |
+
========
|
| 822 |
+
|
| 823 |
+
>>> from sympy.physics.optics import gaussian_conj
|
| 824 |
+
>>> from sympy import symbols
|
| 825 |
+
>>> s_in, z_r_in, f = symbols('s_in z_r_in f')
|
| 826 |
+
|
| 827 |
+
>>> gaussian_conj(s_in, z_r_in, f)[0]
|
| 828 |
+
1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
|
| 829 |
+
|
| 830 |
+
>>> gaussian_conj(s_in, z_r_in, f)[1]
|
| 831 |
+
z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
|
| 832 |
+
|
| 833 |
+
>>> gaussian_conj(s_in, z_r_in, f)[2]
|
| 834 |
+
1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
|
| 835 |
+
"""
|
| 836 |
+
s_in, z_r_in, f = map(sympify, (s_in, z_r_in, f))
|
| 837 |
+
s_out = 1 / ( -1/(s_in + z_r_in**2/(s_in - f)) + 1/f )
|
| 838 |
+
m = 1/sqrt((1 - (s_in/f)**2) + (z_r_in/f)**2)
|
| 839 |
+
z_r_out = z_r_in / ((1 - (s_in/f)**2) + (z_r_in/f)**2)
|
| 840 |
+
return (s_out, z_r_out, m)
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
def conjugate_gauss_beams(wavelen, waist_in, waist_out, **kwargs):
|
| 844 |
+
"""
|
| 845 |
+
Find the optical setup conjugating the object/image waists.
|
| 846 |
+
|
| 847 |
+
Parameters
|
| 848 |
+
==========
|
| 849 |
+
|
| 850 |
+
wavelen :
|
| 851 |
+
The wavelength of the beam.
|
| 852 |
+
waist_in and waist_out :
|
| 853 |
+
The waists to be conjugated.
|
| 854 |
+
f :
|
| 855 |
+
The focal distance of the element used in the conjugation.
|
| 856 |
+
|
| 857 |
+
Returns
|
| 858 |
+
=======
|
| 859 |
+
|
| 860 |
+
a tuple containing (s_in, s_out, f)
|
| 861 |
+
s_in :
|
| 862 |
+
The distance before the optical element.
|
| 863 |
+
s_out :
|
| 864 |
+
The distance after the optical element.
|
| 865 |
+
f :
|
| 866 |
+
The focal distance of the optical element.
|
| 867 |
+
|
| 868 |
+
Examples
|
| 869 |
+
========
|
| 870 |
+
|
| 871 |
+
>>> from sympy.physics.optics import conjugate_gauss_beams
|
| 872 |
+
>>> from sympy import symbols, factor
|
| 873 |
+
>>> l, w_i, w_o, f = symbols('l w_i w_o f')
|
| 874 |
+
|
| 875 |
+
>>> conjugate_gauss_beams(l, w_i, w_o, f=f)[0]
|
| 876 |
+
f*(1 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))
|
| 877 |
+
|
| 878 |
+
>>> factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1])
|
| 879 |
+
f*w_o**2*(w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 -
|
| 880 |
+
pi**2*w_i**4/(f**2*l**2)))/w_i**2
|
| 881 |
+
|
| 882 |
+
>>> conjugate_gauss_beams(l, w_i, w_o, f=f)[2]
|
| 883 |
+
f
|
| 884 |
+
"""
|
| 885 |
+
#TODO add the other possible arguments
|
| 886 |
+
wavelen, waist_in, waist_out = map(sympify, (wavelen, waist_in, waist_out))
|
| 887 |
+
m = waist_out / waist_in
|
| 888 |
+
z = waist2rayleigh(waist_in, wavelen)
|
| 889 |
+
if len(kwargs) != 1:
|
| 890 |
+
raise ValueError("The function expects only one named argument")
|
| 891 |
+
elif 'dist' in kwargs:
|
| 892 |
+
raise NotImplementedError(filldedent('''
|
| 893 |
+
Currently only focal length is supported as a parameter'''))
|
| 894 |
+
elif 'f' in kwargs:
|
| 895 |
+
f = sympify(kwargs['f'])
|
| 896 |
+
s_in = f * (1 - sqrt(1/m**2 - z**2/f**2))
|
| 897 |
+
s_out = gaussian_conj(s_in, z, f)[0]
|
| 898 |
+
elif 's_in' in kwargs:
|
| 899 |
+
raise NotImplementedError(filldedent('''
|
| 900 |
+
Currently only focal length is supported as a parameter'''))
|
| 901 |
+
else:
|
| 902 |
+
raise ValueError(filldedent('''
|
| 903 |
+
The functions expects the focal length as a named argument'''))
|
| 904 |
+
return (s_in, s_out, f)
|
| 905 |
+
|
| 906 |
+
#TODO
|
| 907 |
+
#def plot_beam():
|
| 908 |
+
# """Plot the beam radius as it propagates in space."""
|
| 909 |
+
# pass
|
| 910 |
+
|
| 911 |
+
#TODO
|
| 912 |
+
#def plot_beam_conjugation():
|
| 913 |
+
# """
|
| 914 |
+
# Plot the intersection of two beams.
|
| 915 |
+
#
|
| 916 |
+
# Represents the conjugation relation.
|
| 917 |
+
#
|
| 918 |
+
# See Also
|
| 919 |
+
# ========
|
| 920 |
+
#
|
| 921 |
+
# conjugate_gauss_beams
|
| 922 |
+
# """
|
| 923 |
+
# pass
|
wemm/lib/python3.10/site-packages/sympy/physics/optics/tests/test_waves.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import (Derivative, Function)
|
| 2 |
+
from sympy.core.numbers import (I, pi)
|
| 3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 5 |
+
from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
|
| 6 |
+
from sympy.simplify.simplify import simplify
|
| 7 |
+
from sympy.abc import epsilon, mu
|
| 8 |
+
from sympy.functions.elementary.exponential import exp
|
| 9 |
+
from sympy.physics.units import speed_of_light, m, s
|
| 10 |
+
from sympy.physics.optics import TWave
|
| 11 |
+
|
| 12 |
+
from sympy.testing.pytest import raises
|
| 13 |
+
|
| 14 |
+
c = speed_of_light.convert_to(m/s)
|
| 15 |
+
|
| 16 |
+
def test_twave():
|
| 17 |
+
A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
|
| 18 |
+
n = Symbol('n') # Refractive index
|
| 19 |
+
t = Symbol('t') # Time
|
| 20 |
+
x = Symbol('x') # Spatial variable
|
| 21 |
+
E = Function('E')
|
| 22 |
+
w1 = TWave(A1, f, phi1)
|
| 23 |
+
w2 = TWave(A2, f, phi2)
|
| 24 |
+
assert w1.amplitude == A1
|
| 25 |
+
assert w1.frequency == f
|
| 26 |
+
assert w1.phase == phi1
|
| 27 |
+
assert w1.wavelength == c/(f*n)
|
| 28 |
+
assert w1.time_period == 1/f
|
| 29 |
+
assert w1.angular_velocity == 2*pi*f
|
| 30 |
+
assert w1.wavenumber == 2*pi*f*n/c
|
| 31 |
+
assert w1.speed == c/n
|
| 32 |
+
|
| 33 |
+
w3 = w1 + w2
|
| 34 |
+
assert w3.amplitude == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
|
| 35 |
+
assert w3.frequency == f
|
| 36 |
+
assert w3.phase == atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
|
| 37 |
+
assert w3.wavelength == c/(f*n)
|
| 38 |
+
assert w3.time_period == 1/f
|
| 39 |
+
assert w3.angular_velocity == 2*pi*f
|
| 40 |
+
assert w3.wavenumber == 2*pi*f*n/c
|
| 41 |
+
assert w3.speed == c/n
|
| 42 |
+
assert simplify(w3.rewrite(sin) - w2.rewrite(sin) - w1.rewrite(sin)) == 0
|
| 43 |
+
assert w3.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
|
| 44 |
+
assert w3.rewrite(cos) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
|
| 45 |
+
+ A2**2)*cos(pi*f*n*x*s/(149896229*m) - 2*pi*f*t + atan2(A1*sin(phi1)
|
| 46 |
+
+ A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)))
|
| 47 |
+
assert w3.rewrite(exp) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
|
| 48 |
+
+ A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1)
|
| 49 |
+
+ A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)))
|
| 50 |
+
|
| 51 |
+
w4 = TWave(A1, None, 0, 1/f)
|
| 52 |
+
assert w4.frequency == f
|
| 53 |
+
|
| 54 |
+
w5 = w1 - w2
|
| 55 |
+
assert w5.amplitude == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2) + A2**2)
|
| 56 |
+
assert w5.frequency == f
|
| 57 |
+
assert w5.phase == atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1) - A2*cos(phi2))
|
| 58 |
+
assert w5.wavelength == c/(f*n)
|
| 59 |
+
assert w5.time_period == 1/f
|
| 60 |
+
assert w5.angular_velocity == 2*pi*f
|
| 61 |
+
assert w5.wavenumber == 2*pi*f*n/c
|
| 62 |
+
assert w5.speed == c/n
|
| 63 |
+
assert simplify(w5.rewrite(sin) - w1.rewrite(sin) + w2.rewrite(sin)) == 0
|
| 64 |
+
assert w5.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
|
| 65 |
+
assert w5.rewrite(cos) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2)
|
| 66 |
+
+ A2**2)*cos(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1)
|
| 67 |
+
- A2*cos(phi2)) + pi*s*f*n*x/(149896229*m))
|
| 68 |
+
assert w5.rewrite(exp) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2)
|
| 69 |
+
+ A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1)
|
| 70 |
+
- A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)))
|
| 71 |
+
|
| 72 |
+
w6 = 2*w1
|
| 73 |
+
assert w6.amplitude == 2*A1
|
| 74 |
+
assert w6.frequency == f
|
| 75 |
+
assert w6.phase == phi1
|
| 76 |
+
w7 = -w6
|
| 77 |
+
assert w7.amplitude == -2*A1
|
| 78 |
+
assert w7.frequency == f
|
| 79 |
+
assert w7.phase == phi1
|
| 80 |
+
|
| 81 |
+
raises(ValueError, lambda:TWave(A1))
|
| 82 |
+
raises(ValueError, lambda:TWave(A1, f, phi1, t))
|
wemm/lib/python3.10/site-packages/sympy/physics/optics/utils.py
ADDED
|
@@ -0,0 +1,698 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
**Contains**
|
| 3 |
+
|
| 4 |
+
* refraction_angle
|
| 5 |
+
* fresnel_coefficients
|
| 6 |
+
* deviation
|
| 7 |
+
* brewster_angle
|
| 8 |
+
* critical_angle
|
| 9 |
+
* lens_makers_formula
|
| 10 |
+
* mirror_formula
|
| 11 |
+
* lens_formula
|
| 12 |
+
* hyperfocal_distance
|
| 13 |
+
* transverse_magnification
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
__all__ = ['refraction_angle',
|
| 17 |
+
'deviation',
|
| 18 |
+
'fresnel_coefficients',
|
| 19 |
+
'brewster_angle',
|
| 20 |
+
'critical_angle',
|
| 21 |
+
'lens_makers_formula',
|
| 22 |
+
'mirror_formula',
|
| 23 |
+
'lens_formula',
|
| 24 |
+
'hyperfocal_distance',
|
| 25 |
+
'transverse_magnification'
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
from sympy.core.numbers import (Float, I, oo, pi, zoo)
|
| 29 |
+
from sympy.core.singleton import S
|
| 30 |
+
from sympy.core.symbol import Symbol
|
| 31 |
+
from sympy.core.sympify import sympify
|
| 32 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 33 |
+
from sympy.functions.elementary.trigonometric import (acos, asin, atan2, cos, sin, tan)
|
| 34 |
+
from sympy.matrices.dense import Matrix
|
| 35 |
+
from sympy.polys.polytools import cancel
|
| 36 |
+
from sympy.series.limits import Limit
|
| 37 |
+
from sympy.geometry.line import Ray3D
|
| 38 |
+
from sympy.geometry.util import intersection
|
| 39 |
+
from sympy.geometry.plane import Plane
|
| 40 |
+
from sympy.utilities.iterables import is_sequence
|
| 41 |
+
from .medium import Medium
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def refractive_index_of_medium(medium):
|
| 45 |
+
"""
|
| 46 |
+
Helper function that returns refractive index, given a medium
|
| 47 |
+
"""
|
| 48 |
+
if isinstance(medium, Medium):
|
| 49 |
+
n = medium.refractive_index
|
| 50 |
+
else:
|
| 51 |
+
n = sympify(medium)
|
| 52 |
+
return n
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
|
| 56 |
+
"""
|
| 57 |
+
This function calculates transmitted vector after refraction at planar
|
| 58 |
+
surface. ``medium1`` and ``medium2`` can be ``Medium`` or any sympifiable object.
|
| 59 |
+
If ``incident`` is a number then treated as angle of incidence (in radians)
|
| 60 |
+
in which case refraction angle is returned.
|
| 61 |
+
|
| 62 |
+
If ``incident`` is an object of `Ray3D`, `normal` also has to be an instance
|
| 63 |
+
of `Ray3D` in order to get the output as a `Ray3D`. Please note that if
|
| 64 |
+
plane of separation is not provided and normal is an instance of `Ray3D`,
|
| 65 |
+
``normal`` will be assumed to be intersecting incident ray at the plane of
|
| 66 |
+
separation. This will not be the case when `normal` is a `Matrix` or
|
| 67 |
+
any other sequence.
|
| 68 |
+
If ``incident`` is an instance of `Ray3D` and `plane` has not been provided
|
| 69 |
+
and ``normal`` is not `Ray3D`, output will be a `Matrix`.
|
| 70 |
+
|
| 71 |
+
Parameters
|
| 72 |
+
==========
|
| 73 |
+
|
| 74 |
+
incident : Matrix, Ray3D, sequence or a number
|
| 75 |
+
Incident vector or angle of incidence
|
| 76 |
+
medium1 : sympy.physics.optics.medium.Medium or sympifiable
|
| 77 |
+
Medium 1 or its refractive index
|
| 78 |
+
medium2 : sympy.physics.optics.medium.Medium or sympifiable
|
| 79 |
+
Medium 2 or its refractive index
|
| 80 |
+
normal : Matrix, Ray3D, or sequence
|
| 81 |
+
Normal vector
|
| 82 |
+
plane : Plane
|
| 83 |
+
Plane of separation of the two media.
|
| 84 |
+
|
| 85 |
+
Returns
|
| 86 |
+
=======
|
| 87 |
+
|
| 88 |
+
Returns an angle of refraction or a refracted ray depending on inputs.
|
| 89 |
+
|
| 90 |
+
Examples
|
| 91 |
+
========
|
| 92 |
+
|
| 93 |
+
>>> from sympy.physics.optics import refraction_angle
|
| 94 |
+
>>> from sympy.geometry import Point3D, Ray3D, Plane
|
| 95 |
+
>>> from sympy.matrices import Matrix
|
| 96 |
+
>>> from sympy import symbols, pi
|
| 97 |
+
>>> n = Matrix([0, 0, 1])
|
| 98 |
+
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
|
| 99 |
+
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
|
| 100 |
+
>>> refraction_angle(r1, 1, 1, n)
|
| 101 |
+
Matrix([
|
| 102 |
+
[ 1],
|
| 103 |
+
[ 1],
|
| 104 |
+
[-1]])
|
| 105 |
+
>>> refraction_angle(r1, 1, 1, plane=P)
|
| 106 |
+
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
|
| 107 |
+
|
| 108 |
+
With different index of refraction of the two media
|
| 109 |
+
|
| 110 |
+
>>> n1, n2 = symbols('n1, n2')
|
| 111 |
+
>>> refraction_angle(r1, n1, n2, n)
|
| 112 |
+
Matrix([
|
| 113 |
+
[ n1/n2],
|
| 114 |
+
[ n1/n2],
|
| 115 |
+
[-sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)]])
|
| 116 |
+
>>> refraction_angle(r1, n1, n2, plane=P)
|
| 117 |
+
Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
|
| 118 |
+
>>> round(refraction_angle(pi/6, 1.2, 1.5), 5)
|
| 119 |
+
0.41152
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
n1 = refractive_index_of_medium(medium1)
|
| 123 |
+
n2 = refractive_index_of_medium(medium2)
|
| 124 |
+
|
| 125 |
+
# check if an incidence angle was supplied instead of a ray
|
| 126 |
+
try:
|
| 127 |
+
angle_of_incidence = float(incident)
|
| 128 |
+
except TypeError:
|
| 129 |
+
angle_of_incidence = None
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
critical_angle_ = critical_angle(medium1, medium2)
|
| 133 |
+
except (ValueError, TypeError):
|
| 134 |
+
critical_angle_ = None
|
| 135 |
+
|
| 136 |
+
if angle_of_incidence is not None:
|
| 137 |
+
if normal is not None or plane is not None:
|
| 138 |
+
raise ValueError('Normal/plane not allowed if incident is an angle')
|
| 139 |
+
|
| 140 |
+
if not 0.0 <= angle_of_incidence < pi*0.5:
|
| 141 |
+
raise ValueError('Angle of incidence not in range [0:pi/2)')
|
| 142 |
+
|
| 143 |
+
if critical_angle_ and angle_of_incidence > critical_angle_:
|
| 144 |
+
raise ValueError('Ray undergoes total internal reflection')
|
| 145 |
+
return asin(n1*sin(angle_of_incidence)/n2)
|
| 146 |
+
|
| 147 |
+
# Treat the incident as ray below
|
| 148 |
+
# A flag to check whether to return Ray3D or not
|
| 149 |
+
return_ray = False
|
| 150 |
+
|
| 151 |
+
if plane is not None and normal is not None:
|
| 152 |
+
raise ValueError("Either plane or normal is acceptable.")
|
| 153 |
+
|
| 154 |
+
if not isinstance(incident, Matrix):
|
| 155 |
+
if is_sequence(incident):
|
| 156 |
+
_incident = Matrix(incident)
|
| 157 |
+
elif isinstance(incident, Ray3D):
|
| 158 |
+
_incident = Matrix(incident.direction_ratio)
|
| 159 |
+
else:
|
| 160 |
+
raise TypeError(
|
| 161 |
+
"incident should be a Matrix, Ray3D, or sequence")
|
| 162 |
+
else:
|
| 163 |
+
_incident = incident
|
| 164 |
+
|
| 165 |
+
# If plane is provided, get direction ratios of the normal
|
| 166 |
+
# to the plane from the plane else go with `normal` param.
|
| 167 |
+
if plane is not None:
|
| 168 |
+
if not isinstance(plane, Plane):
|
| 169 |
+
raise TypeError("plane should be an instance of geometry.plane.Plane")
|
| 170 |
+
# If we have the plane, we can get the intersection
|
| 171 |
+
# point of incident ray and the plane and thus return
|
| 172 |
+
# an instance of Ray3D.
|
| 173 |
+
if isinstance(incident, Ray3D):
|
| 174 |
+
return_ray = True
|
| 175 |
+
intersection_pt = plane.intersection(incident)[0]
|
| 176 |
+
_normal = Matrix(plane.normal_vector)
|
| 177 |
+
else:
|
| 178 |
+
if not isinstance(normal, Matrix):
|
| 179 |
+
if is_sequence(normal):
|
| 180 |
+
_normal = Matrix(normal)
|
| 181 |
+
elif isinstance(normal, Ray3D):
|
| 182 |
+
_normal = Matrix(normal.direction_ratio)
|
| 183 |
+
if isinstance(incident, Ray3D):
|
| 184 |
+
intersection_pt = intersection(incident, normal)
|
| 185 |
+
if len(intersection_pt) == 0:
|
| 186 |
+
raise ValueError(
|
| 187 |
+
"Normal isn't concurrent with the incident ray.")
|
| 188 |
+
else:
|
| 189 |
+
return_ray = True
|
| 190 |
+
intersection_pt = intersection_pt[0]
|
| 191 |
+
else:
|
| 192 |
+
raise TypeError(
|
| 193 |
+
"Normal should be a Matrix, Ray3D, or sequence")
|
| 194 |
+
else:
|
| 195 |
+
_normal = normal
|
| 196 |
+
|
| 197 |
+
eta = n1/n2 # Relative index of refraction
|
| 198 |
+
# Calculating magnitude of the vectors
|
| 199 |
+
mag_incident = sqrt(sum(i**2 for i in _incident))
|
| 200 |
+
mag_normal = sqrt(sum(i**2 for i in _normal))
|
| 201 |
+
# Converting vectors to unit vectors by dividing
|
| 202 |
+
# them with their magnitudes
|
| 203 |
+
_incident /= mag_incident
|
| 204 |
+
_normal /= mag_normal
|
| 205 |
+
c1 = -_incident.dot(_normal) # cos(angle_of_incidence)
|
| 206 |
+
cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
|
| 207 |
+
if cs2.is_negative: # This is the case of total internal reflection(TIR).
|
| 208 |
+
return S.Zero
|
| 209 |
+
drs = eta*_incident + (eta*c1 - sqrt(cs2))*_normal
|
| 210 |
+
# Multiplying unit vector by its magnitude
|
| 211 |
+
drs = drs*mag_incident
|
| 212 |
+
if not return_ray:
|
| 213 |
+
return drs
|
| 214 |
+
else:
|
| 215 |
+
return Ray3D(intersection_pt, direction_ratio=drs)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def fresnel_coefficients(angle_of_incidence, medium1, medium2):
|
| 219 |
+
"""
|
| 220 |
+
This function uses Fresnel equations to calculate reflection and
|
| 221 |
+
transmission coefficients. Those are obtained for both polarisations
|
| 222 |
+
when the electric field vector is in the plane of incidence (labelled 'p')
|
| 223 |
+
and when the electric field vector is perpendicular to the plane of
|
| 224 |
+
incidence (labelled 's'). There are four real coefficients unless the
|
| 225 |
+
incident ray reflects in total internal in which case there are two complex
|
| 226 |
+
ones. Angle of incidence is the angle between the incident ray and the
|
| 227 |
+
surface normal. ``medium1`` and ``medium2`` can be ``Medium`` or any
|
| 228 |
+
sympifiable object.
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
==========
|
| 232 |
+
|
| 233 |
+
angle_of_incidence : sympifiable
|
| 234 |
+
|
| 235 |
+
medium1 : Medium or sympifiable
|
| 236 |
+
Medium 1 or its refractive index
|
| 237 |
+
|
| 238 |
+
medium2 : Medium or sympifiable
|
| 239 |
+
Medium 2 or its refractive index
|
| 240 |
+
|
| 241 |
+
Returns
|
| 242 |
+
=======
|
| 243 |
+
|
| 244 |
+
Returns a list with four real Fresnel coefficients:
|
| 245 |
+
[reflection p (TM), reflection s (TE),
|
| 246 |
+
transmission p (TM), transmission s (TE)]
|
| 247 |
+
If the ray is undergoes total internal reflection then returns a
|
| 248 |
+
list of two complex Fresnel coefficients:
|
| 249 |
+
[reflection p (TM), reflection s (TE)]
|
| 250 |
+
|
| 251 |
+
Examples
|
| 252 |
+
========
|
| 253 |
+
|
| 254 |
+
>>> from sympy.physics.optics import fresnel_coefficients
|
| 255 |
+
>>> fresnel_coefficients(0.3, 1, 2)
|
| 256 |
+
[0.317843553417859, -0.348645229818821,
|
| 257 |
+
0.658921776708929, 0.651354770181179]
|
| 258 |
+
>>> fresnel_coefficients(0.6, 2, 1)
|
| 259 |
+
[-0.235625382192159 - 0.971843958291041*I,
|
| 260 |
+
0.816477005968898 - 0.577377951366403*I]
|
| 261 |
+
|
| 262 |
+
References
|
| 263 |
+
==========
|
| 264 |
+
|
| 265 |
+
.. [1] https://en.wikipedia.org/wiki/Fresnel_equations
|
| 266 |
+
"""
|
| 267 |
+
if not 0 <= 2*angle_of_incidence < pi:
|
| 268 |
+
raise ValueError('Angle of incidence not in range [0:pi/2)')
|
| 269 |
+
|
| 270 |
+
n1 = refractive_index_of_medium(medium1)
|
| 271 |
+
n2 = refractive_index_of_medium(medium2)
|
| 272 |
+
|
| 273 |
+
angle_of_refraction = asin(n1*sin(angle_of_incidence)/n2)
|
| 274 |
+
try:
|
| 275 |
+
angle_of_total_internal_reflection_onset = critical_angle(n1, n2)
|
| 276 |
+
except ValueError:
|
| 277 |
+
angle_of_total_internal_reflection_onset = None
|
| 278 |
+
|
| 279 |
+
if angle_of_total_internal_reflection_onset is None or\
|
| 280 |
+
angle_of_total_internal_reflection_onset > angle_of_incidence:
|
| 281 |
+
R_s = -sin(angle_of_incidence - angle_of_refraction)\
|
| 282 |
+
/sin(angle_of_incidence + angle_of_refraction)
|
| 283 |
+
R_p = tan(angle_of_incidence - angle_of_refraction)\
|
| 284 |
+
/tan(angle_of_incidence + angle_of_refraction)
|
| 285 |
+
T_s = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
|
| 286 |
+
/sin(angle_of_incidence + angle_of_refraction)
|
| 287 |
+
T_p = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
|
| 288 |
+
/(sin(angle_of_incidence + angle_of_refraction)\
|
| 289 |
+
*cos(angle_of_incidence - angle_of_refraction))
|
| 290 |
+
return [R_p, R_s, T_p, T_s]
|
| 291 |
+
else:
|
| 292 |
+
n = n2/n1
|
| 293 |
+
R_s = cancel((cos(angle_of_incidence)-\
|
| 294 |
+
I*sqrt(sin(angle_of_incidence)**2 - n**2))\
|
| 295 |
+
/(cos(angle_of_incidence)+\
|
| 296 |
+
I*sqrt(sin(angle_of_incidence)**2 - n**2)))
|
| 297 |
+
R_p = cancel((n**2*cos(angle_of_incidence)-\
|
| 298 |
+
I*sqrt(sin(angle_of_incidence)**2 - n**2))\
|
| 299 |
+
/(n**2*cos(angle_of_incidence)+\
|
| 300 |
+
I*sqrt(sin(angle_of_incidence)**2 - n**2)))
|
| 301 |
+
return [R_p, R_s]
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def deviation(incident, medium1, medium2, normal=None, plane=None):
|
| 305 |
+
"""
|
| 306 |
+
This function calculates the angle of deviation of a ray
|
| 307 |
+
due to refraction at planar surface.
|
| 308 |
+
|
| 309 |
+
Parameters
|
| 310 |
+
==========
|
| 311 |
+
|
| 312 |
+
incident : Matrix, Ray3D, sequence or float
|
| 313 |
+
Incident vector or angle of incidence
|
| 314 |
+
medium1 : sympy.physics.optics.medium.Medium or sympifiable
|
| 315 |
+
Medium 1 or its refractive index
|
| 316 |
+
medium2 : sympy.physics.optics.medium.Medium or sympifiable
|
| 317 |
+
Medium 2 or its refractive index
|
| 318 |
+
normal : Matrix, Ray3D, or sequence
|
| 319 |
+
Normal vector
|
| 320 |
+
plane : Plane
|
| 321 |
+
Plane of separation of the two media.
|
| 322 |
+
|
| 323 |
+
Returns angular deviation between incident and refracted rays
|
| 324 |
+
|
| 325 |
+
Examples
|
| 326 |
+
========
|
| 327 |
+
|
| 328 |
+
>>> from sympy.physics.optics import deviation
|
| 329 |
+
>>> from sympy.geometry import Point3D, Ray3D, Plane
|
| 330 |
+
>>> from sympy.matrices import Matrix
|
| 331 |
+
>>> from sympy import symbols
|
| 332 |
+
>>> n1, n2 = symbols('n1, n2')
|
| 333 |
+
>>> n = Matrix([0, 0, 1])
|
| 334 |
+
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
|
| 335 |
+
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
|
| 336 |
+
>>> deviation(r1, 1, 1, n)
|
| 337 |
+
0
|
| 338 |
+
>>> deviation(r1, n1, n2, plane=P)
|
| 339 |
+
-acos(-sqrt(-2*n1**2/(3*n2**2) + 1)) + acos(-sqrt(3)/3)
|
| 340 |
+
>>> round(deviation(0.1, 1.2, 1.5), 5)
|
| 341 |
+
-0.02005
|
| 342 |
+
"""
|
| 343 |
+
refracted = refraction_angle(incident,
|
| 344 |
+
medium1,
|
| 345 |
+
medium2,
|
| 346 |
+
normal=normal,
|
| 347 |
+
plane=plane)
|
| 348 |
+
try:
|
| 349 |
+
angle_of_incidence = Float(incident)
|
| 350 |
+
except TypeError:
|
| 351 |
+
angle_of_incidence = None
|
| 352 |
+
|
| 353 |
+
if angle_of_incidence is not None:
|
| 354 |
+
return float(refracted) - angle_of_incidence
|
| 355 |
+
|
| 356 |
+
if refracted != 0:
|
| 357 |
+
if isinstance(refracted, Ray3D):
|
| 358 |
+
refracted = Matrix(refracted.direction_ratio)
|
| 359 |
+
|
| 360 |
+
if not isinstance(incident, Matrix):
|
| 361 |
+
if is_sequence(incident):
|
| 362 |
+
_incident = Matrix(incident)
|
| 363 |
+
elif isinstance(incident, Ray3D):
|
| 364 |
+
_incident = Matrix(incident.direction_ratio)
|
| 365 |
+
else:
|
| 366 |
+
raise TypeError(
|
| 367 |
+
"incident should be a Matrix, Ray3D, or sequence")
|
| 368 |
+
else:
|
| 369 |
+
_incident = incident
|
| 370 |
+
|
| 371 |
+
if plane is None:
|
| 372 |
+
if not isinstance(normal, Matrix):
|
| 373 |
+
if is_sequence(normal):
|
| 374 |
+
_normal = Matrix(normal)
|
| 375 |
+
elif isinstance(normal, Ray3D):
|
| 376 |
+
_normal = Matrix(normal.direction_ratio)
|
| 377 |
+
else:
|
| 378 |
+
raise TypeError(
|
| 379 |
+
"normal should be a Matrix, Ray3D, or sequence")
|
| 380 |
+
else:
|
| 381 |
+
_normal = normal
|
| 382 |
+
else:
|
| 383 |
+
_normal = Matrix(plane.normal_vector)
|
| 384 |
+
|
| 385 |
+
mag_incident = sqrt(sum(i**2 for i in _incident))
|
| 386 |
+
mag_normal = sqrt(sum(i**2 for i in _normal))
|
| 387 |
+
mag_refracted = sqrt(sum(i**2 for i in refracted))
|
| 388 |
+
_incident /= mag_incident
|
| 389 |
+
_normal /= mag_normal
|
| 390 |
+
refracted /= mag_refracted
|
| 391 |
+
i = acos(_incident.dot(_normal))
|
| 392 |
+
r = acos(refracted.dot(_normal))
|
| 393 |
+
return i - r
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def brewster_angle(medium1, medium2):
|
| 397 |
+
"""
|
| 398 |
+
This function calculates the Brewster's angle of incidence to Medium 2 from
|
| 399 |
+
Medium 1 in radians.
|
| 400 |
+
|
| 401 |
+
Parameters
|
| 402 |
+
==========
|
| 403 |
+
|
| 404 |
+
medium 1 : Medium or sympifiable
|
| 405 |
+
Refractive index of Medium 1
|
| 406 |
+
medium 2 : Medium or sympifiable
|
| 407 |
+
Refractive index of Medium 1
|
| 408 |
+
|
| 409 |
+
Examples
|
| 410 |
+
========
|
| 411 |
+
|
| 412 |
+
>>> from sympy.physics.optics import brewster_angle
|
| 413 |
+
>>> brewster_angle(1, 1.33)
|
| 414 |
+
0.926093295503462
|
| 415 |
+
|
| 416 |
+
"""
|
| 417 |
+
|
| 418 |
+
n1 = refractive_index_of_medium(medium1)
|
| 419 |
+
n2 = refractive_index_of_medium(medium2)
|
| 420 |
+
|
| 421 |
+
return atan2(n2, n1)
|
| 422 |
+
|
| 423 |
+
def critical_angle(medium1, medium2):
|
| 424 |
+
"""
|
| 425 |
+
This function calculates the critical angle of incidence (marking the onset
|
| 426 |
+
of total internal) to Medium 2 from Medium 1 in radians.
|
| 427 |
+
|
| 428 |
+
Parameters
|
| 429 |
+
==========
|
| 430 |
+
|
| 431 |
+
medium 1 : Medium or sympifiable
|
| 432 |
+
Refractive index of Medium 1.
|
| 433 |
+
medium 2 : Medium or sympifiable
|
| 434 |
+
Refractive index of Medium 1.
|
| 435 |
+
|
| 436 |
+
Examples
|
| 437 |
+
========
|
| 438 |
+
|
| 439 |
+
>>> from sympy.physics.optics import critical_angle
|
| 440 |
+
>>> critical_angle(1.33, 1)
|
| 441 |
+
0.850908514477849
|
| 442 |
+
|
| 443 |
+
"""
|
| 444 |
+
|
| 445 |
+
n1 = refractive_index_of_medium(medium1)
|
| 446 |
+
n2 = refractive_index_of_medium(medium2)
|
| 447 |
+
|
| 448 |
+
if n2 > n1:
|
| 449 |
+
raise ValueError('Total internal reflection impossible for n1 < n2')
|
| 450 |
+
else:
|
| 451 |
+
return asin(n2/n1)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def lens_makers_formula(n_lens, n_surr, r1, r2, d=0):
|
| 456 |
+
"""
|
| 457 |
+
This function calculates focal length of a lens.
|
| 458 |
+
It follows cartesian sign convention.
|
| 459 |
+
|
| 460 |
+
Parameters
|
| 461 |
+
==========
|
| 462 |
+
|
| 463 |
+
n_lens : Medium or sympifiable
|
| 464 |
+
Index of refraction of lens.
|
| 465 |
+
n_surr : Medium or sympifiable
|
| 466 |
+
Index of reflection of surrounding.
|
| 467 |
+
r1 : sympifiable
|
| 468 |
+
Radius of curvature of first surface.
|
| 469 |
+
r2 : sympifiable
|
| 470 |
+
Radius of curvature of second surface.
|
| 471 |
+
d : sympifiable, optional
|
| 472 |
+
Thickness of lens, default value is 0.
|
| 473 |
+
|
| 474 |
+
Examples
|
| 475 |
+
========
|
| 476 |
+
|
| 477 |
+
>>> from sympy.physics.optics import lens_makers_formula
|
| 478 |
+
>>> from sympy import S
|
| 479 |
+
>>> lens_makers_formula(1.33, 1, 10, -10)
|
| 480 |
+
15.1515151515151
|
| 481 |
+
>>> lens_makers_formula(1.2, 1, 10, S.Infinity)
|
| 482 |
+
50.0000000000000
|
| 483 |
+
>>> lens_makers_formula(1.33, 1, 10, -10, d=1)
|
| 484 |
+
15.3418463277618
|
| 485 |
+
|
| 486 |
+
"""
|
| 487 |
+
|
| 488 |
+
if isinstance(n_lens, Medium):
|
| 489 |
+
n_lens = n_lens.refractive_index
|
| 490 |
+
else:
|
| 491 |
+
n_lens = sympify(n_lens)
|
| 492 |
+
if isinstance(n_surr, Medium):
|
| 493 |
+
n_surr = n_surr.refractive_index
|
| 494 |
+
else:
|
| 495 |
+
n_surr = sympify(n_surr)
|
| 496 |
+
d = sympify(d)
|
| 497 |
+
|
| 498 |
+
focal_length = 1/((n_lens - n_surr) / n_surr*(1/r1 - 1/r2 + (((n_lens - n_surr) * d) / (n_lens * r1 * r2))))
|
| 499 |
+
|
| 500 |
+
if focal_length == zoo:
|
| 501 |
+
return S.Infinity
|
| 502 |
+
return focal_length
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def mirror_formula(focal_length=None, u=None, v=None):
|
| 506 |
+
"""
|
| 507 |
+
This function provides one of the three parameters
|
| 508 |
+
when two of them are supplied.
|
| 509 |
+
This is valid only for paraxial rays.
|
| 510 |
+
|
| 511 |
+
Parameters
|
| 512 |
+
==========
|
| 513 |
+
|
| 514 |
+
focal_length : sympifiable
|
| 515 |
+
Focal length of the mirror.
|
| 516 |
+
u : sympifiable
|
| 517 |
+
Distance of object from the pole on
|
| 518 |
+
the principal axis.
|
| 519 |
+
v : sympifiable
|
| 520 |
+
Distance of the image from the pole
|
| 521 |
+
on the principal axis.
|
| 522 |
+
|
| 523 |
+
Examples
|
| 524 |
+
========
|
| 525 |
+
|
| 526 |
+
>>> from sympy.physics.optics import mirror_formula
|
| 527 |
+
>>> from sympy.abc import f, u, v
|
| 528 |
+
>>> mirror_formula(focal_length=f, u=u)
|
| 529 |
+
f*u/(-f + u)
|
| 530 |
+
>>> mirror_formula(focal_length=f, v=v)
|
| 531 |
+
f*v/(-f + v)
|
| 532 |
+
>>> mirror_formula(u=u, v=v)
|
| 533 |
+
u*v/(u + v)
|
| 534 |
+
|
| 535 |
+
"""
|
| 536 |
+
if focal_length and u and v:
|
| 537 |
+
raise ValueError("Please provide only two parameters")
|
| 538 |
+
|
| 539 |
+
focal_length = sympify(focal_length)
|
| 540 |
+
u = sympify(u)
|
| 541 |
+
v = sympify(v)
|
| 542 |
+
if u is oo:
|
| 543 |
+
_u = Symbol('u')
|
| 544 |
+
if v is oo:
|
| 545 |
+
_v = Symbol('v')
|
| 546 |
+
if focal_length is oo:
|
| 547 |
+
_f = Symbol('f')
|
| 548 |
+
if focal_length is None:
|
| 549 |
+
if u is oo and v is oo:
|
| 550 |
+
return Limit(Limit(_v*_u/(_v + _u), _u, oo), _v, oo).doit()
|
| 551 |
+
if u is oo:
|
| 552 |
+
return Limit(v*_u/(v + _u), _u, oo).doit()
|
| 553 |
+
if v is oo:
|
| 554 |
+
return Limit(_v*u/(_v + u), _v, oo).doit()
|
| 555 |
+
return v*u/(v + u)
|
| 556 |
+
if u is None:
|
| 557 |
+
if v is oo and focal_length is oo:
|
| 558 |
+
return Limit(Limit(_v*_f/(_v - _f), _v, oo), _f, oo).doit()
|
| 559 |
+
if v is oo:
|
| 560 |
+
return Limit(_v*focal_length/(_v - focal_length), _v, oo).doit()
|
| 561 |
+
if focal_length is oo:
|
| 562 |
+
return Limit(v*_f/(v - _f), _f, oo).doit()
|
| 563 |
+
return v*focal_length/(v - focal_length)
|
| 564 |
+
if v is None:
|
| 565 |
+
if u is oo and focal_length is oo:
|
| 566 |
+
return Limit(Limit(_u*_f/(_u - _f), _u, oo), _f, oo).doit()
|
| 567 |
+
if u is oo:
|
| 568 |
+
return Limit(_u*focal_length/(_u - focal_length), _u, oo).doit()
|
| 569 |
+
if focal_length is oo:
|
| 570 |
+
return Limit(u*_f/(u - _f), _f, oo).doit()
|
| 571 |
+
return u*focal_length/(u - focal_length)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def lens_formula(focal_length=None, u=None, v=None):
|
| 575 |
+
"""
|
| 576 |
+
This function provides one of the three parameters
|
| 577 |
+
when two of them are supplied.
|
| 578 |
+
This is valid only for paraxial rays.
|
| 579 |
+
|
| 580 |
+
Parameters
|
| 581 |
+
==========
|
| 582 |
+
|
| 583 |
+
focal_length : sympifiable
|
| 584 |
+
Focal length of the mirror.
|
| 585 |
+
u : sympifiable
|
| 586 |
+
Distance of object from the optical center on
|
| 587 |
+
the principal axis.
|
| 588 |
+
v : sympifiable
|
| 589 |
+
Distance of the image from the optical center
|
| 590 |
+
on the principal axis.
|
| 591 |
+
|
| 592 |
+
Examples
|
| 593 |
+
========
|
| 594 |
+
|
| 595 |
+
>>> from sympy.physics.optics import lens_formula
|
| 596 |
+
>>> from sympy.abc import f, u, v
|
| 597 |
+
>>> lens_formula(focal_length=f, u=u)
|
| 598 |
+
f*u/(f + u)
|
| 599 |
+
>>> lens_formula(focal_length=f, v=v)
|
| 600 |
+
f*v/(f - v)
|
| 601 |
+
>>> lens_formula(u=u, v=v)
|
| 602 |
+
u*v/(u - v)
|
| 603 |
+
|
| 604 |
+
"""
|
| 605 |
+
if focal_length and u and v:
|
| 606 |
+
raise ValueError("Please provide only two parameters")
|
| 607 |
+
|
| 608 |
+
focal_length = sympify(focal_length)
|
| 609 |
+
u = sympify(u)
|
| 610 |
+
v = sympify(v)
|
| 611 |
+
if u is oo:
|
| 612 |
+
_u = Symbol('u')
|
| 613 |
+
if v is oo:
|
| 614 |
+
_v = Symbol('v')
|
| 615 |
+
if focal_length is oo:
|
| 616 |
+
_f = Symbol('f')
|
| 617 |
+
if focal_length is None:
|
| 618 |
+
if u is oo and v is oo:
|
| 619 |
+
return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit()
|
| 620 |
+
if u is oo:
|
| 621 |
+
return Limit(v*_u/(_u - v), _u, oo).doit()
|
| 622 |
+
if v is oo:
|
| 623 |
+
return Limit(_v*u/(u - _v), _v, oo).doit()
|
| 624 |
+
return v*u/(u - v)
|
| 625 |
+
if u is None:
|
| 626 |
+
if v is oo and focal_length is oo:
|
| 627 |
+
return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit()
|
| 628 |
+
if v is oo:
|
| 629 |
+
return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit()
|
| 630 |
+
if focal_length is oo:
|
| 631 |
+
return Limit(v*_f/(_f - v), _f, oo).doit()
|
| 632 |
+
return v*focal_length/(focal_length - v)
|
| 633 |
+
if v is None:
|
| 634 |
+
if u is oo and focal_length is oo:
|
| 635 |
+
return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit()
|
| 636 |
+
if u is oo:
|
| 637 |
+
return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit()
|
| 638 |
+
if focal_length is oo:
|
| 639 |
+
return Limit(u*_f/(u + _f), _f, oo).doit()
|
| 640 |
+
return u*focal_length/(u + focal_length)
|
| 641 |
+
|
| 642 |
+
def hyperfocal_distance(f, N, c):
|
| 643 |
+
"""
|
| 644 |
+
|
| 645 |
+
Parameters
|
| 646 |
+
==========
|
| 647 |
+
|
| 648 |
+
f: sympifiable
|
| 649 |
+
Focal length of a given lens.
|
| 650 |
+
|
| 651 |
+
N: sympifiable
|
| 652 |
+
F-number of a given lens.
|
| 653 |
+
|
| 654 |
+
c: sympifiable
|
| 655 |
+
Circle of Confusion (CoC) of a given image format.
|
| 656 |
+
|
| 657 |
+
Example
|
| 658 |
+
=======
|
| 659 |
+
|
| 660 |
+
>>> from sympy.physics.optics import hyperfocal_distance
|
| 661 |
+
>>> round(hyperfocal_distance(f = 0.5, N = 8, c = 0.0033), 2)
|
| 662 |
+
9.47
|
| 663 |
+
"""
|
| 664 |
+
|
| 665 |
+
f = sympify(f)
|
| 666 |
+
N = sympify(N)
|
| 667 |
+
c = sympify(c)
|
| 668 |
+
|
| 669 |
+
return (1/(N * c))*(f**2)
|
| 670 |
+
|
| 671 |
+
def transverse_magnification(si, so):
|
| 672 |
+
"""
|
| 673 |
+
|
| 674 |
+
Calculates the transverse magnification upon reflection in a mirror,
|
| 675 |
+
which is the ratio of the image size to the object size.
|
| 676 |
+
|
| 677 |
+
Parameters
|
| 678 |
+
==========
|
| 679 |
+
|
| 680 |
+
so: sympifiable
|
| 681 |
+
Lens-object distance.
|
| 682 |
+
|
| 683 |
+
si: sympifiable
|
| 684 |
+
Lens-image distance.
|
| 685 |
+
|
| 686 |
+
Example
|
| 687 |
+
=======
|
| 688 |
+
|
| 689 |
+
>>> from sympy.physics.optics import transverse_magnification
|
| 690 |
+
>>> transverse_magnification(30, 15)
|
| 691 |
+
-2
|
| 692 |
+
|
| 693 |
+
"""
|
| 694 |
+
|
| 695 |
+
si = sympify(si)
|
| 696 |
+
so = sympify(so)
|
| 697 |
+
|
| 698 |
+
return (-(si/so))
|
wemm/lib/python3.10/site-packages/sympy/physics/optics/waves.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module has all the classes and functions related to waves in optics.
|
| 3 |
+
|
| 4 |
+
**Contains**
|
| 5 |
+
|
| 6 |
+
* TWave
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
__all__ = ['TWave']
|
| 10 |
+
|
| 11 |
+
from sympy.core.basic import Basic
|
| 12 |
+
from sympy.core.expr import Expr
|
| 13 |
+
from sympy.core.function import Derivative, Function
|
| 14 |
+
from sympy.core.numbers import (Number, pi, I)
|
| 15 |
+
from sympy.core.singleton import S
|
| 16 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 17 |
+
from sympy.core.sympify import _sympify, sympify
|
| 18 |
+
from sympy.functions.elementary.exponential import exp
|
| 19 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 20 |
+
from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
|
| 21 |
+
from sympy.physics.units import speed_of_light, meter, second
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
c = speed_of_light.convert_to(meter/second)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TWave(Expr):
|
| 28 |
+
|
| 29 |
+
r"""
|
| 30 |
+
This is a simple transverse sine wave travelling in a one-dimensional space.
|
| 31 |
+
Basic properties are required at the time of creation of the object,
|
| 32 |
+
but they can be changed later with respective methods provided.
|
| 33 |
+
|
| 34 |
+
Explanation
|
| 35 |
+
===========
|
| 36 |
+
|
| 37 |
+
It is represented as :math:`A \times cos(k*x - \omega \times t + \phi )`,
|
| 38 |
+
where :math:`A` is the amplitude, :math:`\omega` is the angular frequency,
|
| 39 |
+
:math:`k` is the wavenumber (spatial frequency), :math:`x` is a spatial variable
|
| 40 |
+
to represent the position on the dimension on which the wave propagates,
|
| 41 |
+
and :math:`\phi` is the phase angle of the wave.
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
Arguments
|
| 45 |
+
=========
|
| 46 |
+
|
| 47 |
+
amplitude : Sympifyable
|
| 48 |
+
Amplitude of the wave.
|
| 49 |
+
frequency : Sympifyable
|
| 50 |
+
Frequency of the wave.
|
| 51 |
+
phase : Sympifyable
|
| 52 |
+
Phase angle of the wave.
|
| 53 |
+
time_period : Sympifyable
|
| 54 |
+
Time period of the wave.
|
| 55 |
+
n : Sympifyable
|
| 56 |
+
Refractive index of the medium.
|
| 57 |
+
|
| 58 |
+
Raises
|
| 59 |
+
=======
|
| 60 |
+
|
| 61 |
+
ValueError : When neither frequency nor time period is provided
|
| 62 |
+
or they are not consistent.
|
| 63 |
+
TypeError : When anything other than TWave objects is added.
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
Examples
|
| 67 |
+
========
|
| 68 |
+
|
| 69 |
+
>>> from sympy import symbols
|
| 70 |
+
>>> from sympy.physics.optics import TWave
|
| 71 |
+
>>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
|
| 72 |
+
>>> w1 = TWave(A1, f, phi1)
|
| 73 |
+
>>> w2 = TWave(A2, f, phi2)
|
| 74 |
+
>>> w3 = w1 + w2 # Superposition of two waves
|
| 75 |
+
>>> w3
|
| 76 |
+
TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f,
|
| 77 |
+
atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)), 1/f, n)
|
| 78 |
+
>>> w3.amplitude
|
| 79 |
+
sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
|
| 80 |
+
>>> w3.phase
|
| 81 |
+
atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
|
| 82 |
+
>>> w3.speed
|
| 83 |
+
299792458*meter/(second*n)
|
| 84 |
+
>>> w3.angular_velocity
|
| 85 |
+
2*pi*f
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __new__(
|
| 90 |
+
cls,
|
| 91 |
+
amplitude,
|
| 92 |
+
frequency=None,
|
| 93 |
+
phase=S.Zero,
|
| 94 |
+
time_period=None,
|
| 95 |
+
n=Symbol('n')):
|
| 96 |
+
if time_period is not None:
|
| 97 |
+
time_period = _sympify(time_period)
|
| 98 |
+
_frequency = S.One/time_period
|
| 99 |
+
if frequency is not None:
|
| 100 |
+
frequency = _sympify(frequency)
|
| 101 |
+
_time_period = S.One/frequency
|
| 102 |
+
if time_period is not None:
|
| 103 |
+
if frequency != S.One/time_period:
|
| 104 |
+
raise ValueError("frequency and time_period should be consistent.")
|
| 105 |
+
if frequency is None and time_period is None:
|
| 106 |
+
raise ValueError("Either frequency or time period is needed.")
|
| 107 |
+
if frequency is None:
|
| 108 |
+
frequency = _frequency
|
| 109 |
+
if time_period is None:
|
| 110 |
+
time_period = _time_period
|
| 111 |
+
|
| 112 |
+
amplitude = _sympify(amplitude)
|
| 113 |
+
phase = _sympify(phase)
|
| 114 |
+
n = sympify(n)
|
| 115 |
+
obj = Basic.__new__(cls, amplitude, frequency, phase, time_period, n)
|
| 116 |
+
return obj
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def amplitude(self):
|
| 120 |
+
"""
|
| 121 |
+
Returns the amplitude of the wave.
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
========
|
| 125 |
+
|
| 126 |
+
>>> from sympy import symbols
|
| 127 |
+
>>> from sympy.physics.optics import TWave
|
| 128 |
+
>>> A, phi, f = symbols('A, phi, f')
|
| 129 |
+
>>> w = TWave(A, f, phi)
|
| 130 |
+
>>> w.amplitude
|
| 131 |
+
A
|
| 132 |
+
"""
|
| 133 |
+
return self.args[0]
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def frequency(self):
|
| 137 |
+
"""
|
| 138 |
+
Returns the frequency of the wave,
|
| 139 |
+
in cycles per second.
|
| 140 |
+
|
| 141 |
+
Examples
|
| 142 |
+
========
|
| 143 |
+
|
| 144 |
+
>>> from sympy import symbols
|
| 145 |
+
>>> from sympy.physics.optics import TWave
|
| 146 |
+
>>> A, phi, f = symbols('A, phi, f')
|
| 147 |
+
>>> w = TWave(A, f, phi)
|
| 148 |
+
>>> w.frequency
|
| 149 |
+
f
|
| 150 |
+
"""
|
| 151 |
+
return self.args[1]
|
| 152 |
+
|
| 153 |
+
@property
|
| 154 |
+
def phase(self):
|
| 155 |
+
"""
|
| 156 |
+
Returns the phase angle of the wave,
|
| 157 |
+
in radians.
|
| 158 |
+
|
| 159 |
+
Examples
|
| 160 |
+
========
|
| 161 |
+
|
| 162 |
+
>>> from sympy import symbols
|
| 163 |
+
>>> from sympy.physics.optics import TWave
|
| 164 |
+
>>> A, phi, f = symbols('A, phi, f')
|
| 165 |
+
>>> w = TWave(A, f, phi)
|
| 166 |
+
>>> w.phase
|
| 167 |
+
phi
|
| 168 |
+
"""
|
| 169 |
+
return self.args[2]
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def time_period(self):
|
| 173 |
+
"""
|
| 174 |
+
Returns the temporal period of the wave,
|
| 175 |
+
in seconds per cycle.
|
| 176 |
+
|
| 177 |
+
Examples
|
| 178 |
+
========
|
| 179 |
+
|
| 180 |
+
>>> from sympy import symbols
|
| 181 |
+
>>> from sympy.physics.optics import TWave
|
| 182 |
+
>>> A, phi, f = symbols('A, phi, f')
|
| 183 |
+
>>> w = TWave(A, f, phi)
|
| 184 |
+
>>> w.time_period
|
| 185 |
+
1/f
|
| 186 |
+
"""
|
| 187 |
+
return self.args[3]
|
| 188 |
+
|
| 189 |
+
@property
|
| 190 |
+
def n(self):
|
| 191 |
+
"""
|
| 192 |
+
Returns the refractive index of the medium
|
| 193 |
+
"""
|
| 194 |
+
return self.args[4]
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def wavelength(self):
|
| 198 |
+
"""
|
| 199 |
+
Returns the wavelength (spatial period) of the wave,
|
| 200 |
+
in meters per cycle.
|
| 201 |
+
It depends on the medium of the wave.
|
| 202 |
+
|
| 203 |
+
Examples
|
| 204 |
+
========
|
| 205 |
+
|
| 206 |
+
>>> from sympy import symbols
|
| 207 |
+
>>> from sympy.physics.optics import TWave
|
| 208 |
+
>>> A, phi, f = symbols('A, phi, f')
|
| 209 |
+
>>> w = TWave(A, f, phi)
|
| 210 |
+
>>> w.wavelength
|
| 211 |
+
299792458*meter/(second*f*n)
|
| 212 |
+
"""
|
| 213 |
+
return c/(self.frequency*self.n)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def speed(self):
|
| 218 |
+
"""
|
| 219 |
+
Returns the propagation speed of the wave,
|
| 220 |
+
in meters per second.
|
| 221 |
+
It is dependent on the propagation medium.
|
| 222 |
+
|
| 223 |
+
Examples
|
| 224 |
+
========
|
| 225 |
+
|
| 226 |
+
>>> from sympy import symbols
|
| 227 |
+
>>> from sympy.physics.optics import TWave
|
| 228 |
+
>>> A, phi, f = symbols('A, phi, f')
|
| 229 |
+
>>> w = TWave(A, f, phi)
|
| 230 |
+
>>> w.speed
|
| 231 |
+
299792458*meter/(second*n)
|
| 232 |
+
"""
|
| 233 |
+
return self.wavelength*self.frequency
|
| 234 |
+
|
| 235 |
+
@property
|
| 236 |
+
def angular_velocity(self):
|
| 237 |
+
"""
|
| 238 |
+
Returns the angular velocity of the wave,
|
| 239 |
+
in radians per second.
|
| 240 |
+
|
| 241 |
+
Examples
|
| 242 |
+
========
|
| 243 |
+
|
| 244 |
+
>>> from sympy import symbols
|
| 245 |
+
>>> from sympy.physics.optics import TWave
|
| 246 |
+
>>> A, phi, f = symbols('A, phi, f')
|
| 247 |
+
>>> w = TWave(A, f, phi)
|
| 248 |
+
>>> w.angular_velocity
|
| 249 |
+
2*pi*f
|
| 250 |
+
"""
|
| 251 |
+
return 2*pi*self.frequency
|
| 252 |
+
|
| 253 |
+
@property
|
| 254 |
+
def wavenumber(self):
|
| 255 |
+
"""
|
| 256 |
+
Returns the wavenumber of the wave,
|
| 257 |
+
in radians per meter.
|
| 258 |
+
|
| 259 |
+
Examples
|
| 260 |
+
========
|
| 261 |
+
|
| 262 |
+
>>> from sympy import symbols
|
| 263 |
+
>>> from sympy.physics.optics import TWave
|
| 264 |
+
>>> A, phi, f = symbols('A, phi, f')
|
| 265 |
+
>>> w = TWave(A, f, phi)
|
| 266 |
+
>>> w.wavenumber
|
| 267 |
+
pi*second*f*n/(149896229*meter)
|
| 268 |
+
"""
|
| 269 |
+
return 2*pi/self.wavelength
|
| 270 |
+
|
| 271 |
+
def __str__(self):
|
| 272 |
+
"""String representation of a TWave."""
|
| 273 |
+
from sympy.printing import sstr
|
| 274 |
+
return type(self).__name__ + sstr(self.args)
|
| 275 |
+
|
| 276 |
+
__repr__ = __str__
|
| 277 |
+
|
| 278 |
+
def __add__(self, other):
|
| 279 |
+
"""
|
| 280 |
+
Addition of two waves will result in their superposition.
|
| 281 |
+
The type of interference will depend on their phase angles.
|
| 282 |
+
"""
|
| 283 |
+
if isinstance(other, TWave):
|
| 284 |
+
if self.frequency == other.frequency and self.wavelength == other.wavelength:
|
| 285 |
+
return TWave(sqrt(self.amplitude**2 + other.amplitude**2 + 2 *
|
| 286 |
+
self.amplitude*other.amplitude*cos(
|
| 287 |
+
self.phase - other.phase)),
|
| 288 |
+
self.frequency,
|
| 289 |
+
atan2(self.amplitude*sin(self.phase)
|
| 290 |
+
+ other.amplitude*sin(other.phase),
|
| 291 |
+
self.amplitude*cos(self.phase)
|
| 292 |
+
+ other.amplitude*cos(other.phase))
|
| 293 |
+
)
|
| 294 |
+
else:
|
| 295 |
+
raise NotImplementedError("Interference of waves with different frequencies"
|
| 296 |
+
" has not been implemented.")
|
| 297 |
+
else:
|
| 298 |
+
raise TypeError(type(other).__name__ + " and TWave objects cannot be added.")
|
| 299 |
+
|
| 300 |
+
def __mul__(self, other):
|
| 301 |
+
"""
|
| 302 |
+
Multiplying a wave by a scalar rescales the amplitude of the wave.
|
| 303 |
+
"""
|
| 304 |
+
other = sympify(other)
|
| 305 |
+
if isinstance(other, Number):
|
| 306 |
+
return TWave(self.amplitude*other, *self.args[1:])
|
| 307 |
+
else:
|
| 308 |
+
raise TypeError(type(other).__name__ + " and TWave objects cannot be multiplied.")
|
| 309 |
+
|
| 310 |
+
def __sub__(self, other):
|
| 311 |
+
return self.__add__(-1*other)
|
| 312 |
+
|
| 313 |
+
def __neg__(self):
|
| 314 |
+
return self.__mul__(-1)
|
| 315 |
+
|
| 316 |
+
def __radd__(self, other):
|
| 317 |
+
return self.__add__(other)
|
| 318 |
+
|
| 319 |
+
def __rmul__(self, other):
|
| 320 |
+
return self.__mul__(other)
|
| 321 |
+
|
| 322 |
+
def __rsub__(self, other):
|
| 323 |
+
return (-self).__radd__(other)
|
| 324 |
+
|
| 325 |
+
def _eval_rewrite_as_sin(self, *args, **kwargs):
|
| 326 |
+
return self.amplitude*sin(self.wavenumber*Symbol('x')
|
| 327 |
+
- self.angular_velocity*Symbol('t') + self.phase + pi/2, evaluate=False)
|
| 328 |
+
|
| 329 |
+
def _eval_rewrite_as_cos(self, *args, **kwargs):
|
| 330 |
+
return self.amplitude*cos(self.wavenumber*Symbol('x')
|
| 331 |
+
- self.angular_velocity*Symbol('t') + self.phase)
|
| 332 |
+
|
| 333 |
+
def _eval_rewrite_as_pde(self, *args, **kwargs):
|
| 334 |
+
mu, epsilon, x, t = symbols('mu, epsilon, x, t')
|
| 335 |
+
E = Function('E')
|
| 336 |
+
return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
|
| 337 |
+
|
| 338 |
+
def _eval_rewrite_as_exp(self, *args, **kwargs):
|
| 339 |
+
return self.amplitude*exp(I*(self.wavenumber*Symbol('x')
|
| 340 |
+
- self.angular_velocity*Symbol('t') + self.phase))
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/boson.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bosonic quantum operators."""
|
| 2 |
+
|
| 3 |
+
from sympy.core.mul import Mul
|
| 4 |
+
from sympy.core.numbers import Integer
|
| 5 |
+
from sympy.core.singleton import S
|
| 6 |
+
from sympy.functions.elementary.complexes import conjugate
|
| 7 |
+
from sympy.functions.elementary.exponential import exp
|
| 8 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 9 |
+
from sympy.physics.quantum import Operator
|
| 10 |
+
from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra, IdentityOperator
|
| 11 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
'BosonOp',
|
| 16 |
+
'BosonFockKet',
|
| 17 |
+
'BosonFockBra',
|
| 18 |
+
'BosonCoherentKet',
|
| 19 |
+
'BosonCoherentBra'
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class BosonOp(Operator):
|
| 24 |
+
"""A bosonic operator that satisfies [a, Dagger(a)] == 1.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
==========
|
| 28 |
+
|
| 29 |
+
name : str
|
| 30 |
+
A string that labels the bosonic mode.
|
| 31 |
+
|
| 32 |
+
annihilation : bool
|
| 33 |
+
A bool that indicates if the bosonic operator is an annihilation (True,
|
| 34 |
+
default value) or creation operator (False)
|
| 35 |
+
|
| 36 |
+
Examples
|
| 37 |
+
========
|
| 38 |
+
|
| 39 |
+
>>> from sympy.physics.quantum import Dagger, Commutator
|
| 40 |
+
>>> from sympy.physics.quantum.boson import BosonOp
|
| 41 |
+
>>> a = BosonOp("a")
|
| 42 |
+
>>> Commutator(a, Dagger(a)).doit()
|
| 43 |
+
1
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def name(self):
|
| 48 |
+
return self.args[0]
|
| 49 |
+
|
| 50 |
+
@property
|
| 51 |
+
def is_annihilation(self):
|
| 52 |
+
return bool(self.args[1])
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def default_args(self):
|
| 56 |
+
return ("a", True)
|
| 57 |
+
|
| 58 |
+
def __new__(cls, *args, **hints):
|
| 59 |
+
if not len(args) in [1, 2]:
|
| 60 |
+
raise ValueError('1 or 2 parameters expected, got %s' % args)
|
| 61 |
+
|
| 62 |
+
if len(args) == 1:
|
| 63 |
+
args = (args[0], S.One)
|
| 64 |
+
|
| 65 |
+
if len(args) == 2:
|
| 66 |
+
args = (args[0], Integer(args[1]))
|
| 67 |
+
|
| 68 |
+
return Operator.__new__(cls, *args)
|
| 69 |
+
|
| 70 |
+
def _eval_commutator_BosonOp(self, other, **hints):
|
| 71 |
+
if self.name == other.name:
|
| 72 |
+
# [a^\dagger, a] = -1
|
| 73 |
+
if not self.is_annihilation and other.is_annihilation:
|
| 74 |
+
return S.NegativeOne
|
| 75 |
+
|
| 76 |
+
elif 'independent' in hints and hints['independent']:
|
| 77 |
+
# [a, b] = 0
|
| 78 |
+
return S.Zero
|
| 79 |
+
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
def _eval_commutator_FermionOp(self, other, **hints):
|
| 83 |
+
return S.Zero
|
| 84 |
+
|
| 85 |
+
def _eval_anticommutator_BosonOp(self, other, **hints):
|
| 86 |
+
if 'independent' in hints and hints['independent']:
|
| 87 |
+
# {a, b} = 2 * a * b, because [a, b] = 0
|
| 88 |
+
return 2 * self * other
|
| 89 |
+
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
def _eval_adjoint(self):
|
| 93 |
+
return BosonOp(str(self.name), not self.is_annihilation)
|
| 94 |
+
|
| 95 |
+
def __mul__(self, other):
|
| 96 |
+
|
| 97 |
+
if other == IdentityOperator(2):
|
| 98 |
+
return self
|
| 99 |
+
|
| 100 |
+
if isinstance(other, Mul):
|
| 101 |
+
args1 = tuple(arg for arg in other.args if arg.is_commutative)
|
| 102 |
+
args2 = tuple(arg for arg in other.args if not arg.is_commutative)
|
| 103 |
+
x = self
|
| 104 |
+
for y in args2:
|
| 105 |
+
x = x * y
|
| 106 |
+
return Mul(*args1) * x
|
| 107 |
+
|
| 108 |
+
return Mul(self, other)
|
| 109 |
+
|
| 110 |
+
def _print_contents_latex(self, printer, *args):
|
| 111 |
+
if self.is_annihilation:
|
| 112 |
+
return r'{%s}' % str(self.name)
|
| 113 |
+
else:
|
| 114 |
+
return r'{{%s}^\dagger}' % str(self.name)
|
| 115 |
+
|
| 116 |
+
def _print_contents(self, printer, *args):
|
| 117 |
+
if self.is_annihilation:
|
| 118 |
+
return r'%s' % str(self.name)
|
| 119 |
+
else:
|
| 120 |
+
return r'Dagger(%s)' % str(self.name)
|
| 121 |
+
|
| 122 |
+
def _print_contents_pretty(self, printer, *args):
|
| 123 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
| 124 |
+
pform = printer._print(self.args[0], *args)
|
| 125 |
+
if self.is_annihilation:
|
| 126 |
+
return pform
|
| 127 |
+
else:
|
| 128 |
+
return pform**prettyForm('\N{DAGGER}')
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class BosonFockKet(Ket):
|
| 132 |
+
"""Fock state ket for a bosonic mode.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
==========
|
| 136 |
+
|
| 137 |
+
n : Number
|
| 138 |
+
The Fock state number.
|
| 139 |
+
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
def __new__(cls, n):
|
| 143 |
+
return Ket.__new__(cls, n)
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def n(self):
|
| 147 |
+
return self.label[0]
|
| 148 |
+
|
| 149 |
+
@classmethod
|
| 150 |
+
def dual_class(self):
|
| 151 |
+
return BosonFockBra
|
| 152 |
+
|
| 153 |
+
@classmethod
|
| 154 |
+
def _eval_hilbert_space(cls, label):
|
| 155 |
+
return FockSpace()
|
| 156 |
+
|
| 157 |
+
def _eval_innerproduct_BosonFockBra(self, bra, **hints):
|
| 158 |
+
return KroneckerDelta(self.n, bra.n)
|
| 159 |
+
|
| 160 |
+
def _apply_from_right_to_BosonOp(self, op, **options):
|
| 161 |
+
if op.is_annihilation:
|
| 162 |
+
return sqrt(self.n) * BosonFockKet(self.n - 1)
|
| 163 |
+
else:
|
| 164 |
+
return sqrt(self.n + 1) * BosonFockKet(self.n + 1)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class BosonFockBra(Bra):
|
| 168 |
+
"""Fock state bra for a bosonic mode.
|
| 169 |
+
|
| 170 |
+
Parameters
|
| 171 |
+
==========
|
| 172 |
+
|
| 173 |
+
n : Number
|
| 174 |
+
The Fock state number.
|
| 175 |
+
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
def __new__(cls, n):
|
| 179 |
+
return Bra.__new__(cls, n)
|
| 180 |
+
|
| 181 |
+
@property
|
| 182 |
+
def n(self):
|
| 183 |
+
return self.label[0]
|
| 184 |
+
|
| 185 |
+
@classmethod
|
| 186 |
+
def dual_class(self):
|
| 187 |
+
return BosonFockKet
|
| 188 |
+
|
| 189 |
+
@classmethod
|
| 190 |
+
def _eval_hilbert_space(cls, label):
|
| 191 |
+
return FockSpace()
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class BosonCoherentKet(Ket):
|
| 195 |
+
"""Coherent state ket for a bosonic mode.
|
| 196 |
+
|
| 197 |
+
Parameters
|
| 198 |
+
==========
|
| 199 |
+
|
| 200 |
+
alpha : Number, Symbol
|
| 201 |
+
The complex amplitude of the coherent state.
|
| 202 |
+
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
def __new__(cls, alpha):
|
| 206 |
+
return Ket.__new__(cls, alpha)
|
| 207 |
+
|
| 208 |
+
@property
|
| 209 |
+
def alpha(self):
|
| 210 |
+
return self.label[0]
|
| 211 |
+
|
| 212 |
+
@classmethod
|
| 213 |
+
def dual_class(self):
|
| 214 |
+
return BosonCoherentBra
|
| 215 |
+
|
| 216 |
+
@classmethod
|
| 217 |
+
def _eval_hilbert_space(cls, label):
|
| 218 |
+
return HilbertSpace()
|
| 219 |
+
|
| 220 |
+
def _eval_innerproduct_BosonCoherentBra(self, bra, **hints):
|
| 221 |
+
if self.alpha == bra.alpha:
|
| 222 |
+
return S.One
|
| 223 |
+
else:
|
| 224 |
+
return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2)
|
| 225 |
+
|
| 226 |
+
def _apply_from_right_to_BosonOp(self, op, **options):
|
| 227 |
+
if op.is_annihilation:
|
| 228 |
+
return self.alpha * self
|
| 229 |
+
else:
|
| 230 |
+
return None
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class BosonCoherentBra(Bra):
|
| 234 |
+
"""Coherent state bra for a bosonic mode.
|
| 235 |
+
|
| 236 |
+
Parameters
|
| 237 |
+
==========
|
| 238 |
+
|
| 239 |
+
alpha : Number, Symbol
|
| 240 |
+
The complex amplitude of the coherent state.
|
| 241 |
+
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
def __new__(cls, alpha):
|
| 245 |
+
return Bra.__new__(cls, alpha)
|
| 246 |
+
|
| 247 |
+
@property
|
| 248 |
+
def alpha(self):
|
| 249 |
+
return self.label[0]
|
| 250 |
+
|
| 251 |
+
@classmethod
|
| 252 |
+
def dual_class(self):
|
| 253 |
+
return BosonCoherentKet
|
| 254 |
+
|
| 255 |
+
def _apply_operator_BosonOp(self, op, **options):
|
| 256 |
+
if not op.is_annihilation:
|
| 257 |
+
return self.alpha * self
|
| 258 |
+
else:
|
| 259 |
+
return None
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py
ADDED
|
@@ -0,0 +1,239 @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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The commutator: [A,B] = A*B - B*A."""
|
| 2 |
+
|
| 3 |
+
from sympy.core.add import Add
|
| 4 |
+
from sympy.core.expr import Expr
|
| 5 |
+
from sympy.core.mul import Mul
|
| 6 |
+
from sympy.core.power import Pow
|
| 7 |
+
from sympy.core.singleton import S
|
| 8 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
| 9 |
+
|
| 10 |
+
from sympy.physics.quantum.dagger import Dagger
|
| 11 |
+
from sympy.physics.quantum.operator import Operator
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
'Commutator'
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
#-----------------------------------------------------------------------------
|
| 19 |
+
# Commutator
|
| 20 |
+
#-----------------------------------------------------------------------------
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Commutator(Expr):
|
| 24 |
+
"""The standard commutator, in an unevaluated state.
|
| 25 |
+
|
| 26 |
+
Explanation
|
| 27 |
+
===========
|
| 28 |
+
|
| 29 |
+
Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
|
| 30 |
+
class returns the commutator in an unevaluated form. To evaluate the
|
| 31 |
+
commutator, use the ``.doit()`` method.
|
| 32 |
+
|
| 33 |
+
Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
|
| 34 |
+
arguments of the commutator are put into canonical order using ``__cmp__``.
|
| 35 |
+
If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
|
| 36 |
+
|
| 37 |
+
Parameters
|
| 38 |
+
==========
|
| 39 |
+
|
| 40 |
+
A : Expr
|
| 41 |
+
The first argument of the commutator [A,B].
|
| 42 |
+
B : Expr
|
| 43 |
+
The second argument of the commutator [A,B].
|
| 44 |
+
|
| 45 |
+
Examples
|
| 46 |
+
========
|
| 47 |
+
|
| 48 |
+
>>> from sympy.physics.quantum import Commutator, Dagger, Operator
|
| 49 |
+
>>> from sympy.abc import x, y
|
| 50 |
+
>>> A = Operator('A')
|
| 51 |
+
>>> B = Operator('B')
|
| 52 |
+
>>> C = Operator('C')
|
| 53 |
+
|
| 54 |
+
Create a commutator and use ``.doit()`` to evaluate it:
|
| 55 |
+
|
| 56 |
+
>>> comm = Commutator(A, B)
|
| 57 |
+
>>> comm
|
| 58 |
+
[A,B]
|
| 59 |
+
>>> comm.doit()
|
| 60 |
+
A*B - B*A
|
| 61 |
+
|
| 62 |
+
The commutator orders it arguments in canonical order:
|
| 63 |
+
|
| 64 |
+
>>> comm = Commutator(B, A); comm
|
| 65 |
+
-[A,B]
|
| 66 |
+
|
| 67 |
+
Commutative constants are factored out:
|
| 68 |
+
|
| 69 |
+
>>> Commutator(3*x*A, x*y*B)
|
| 70 |
+
3*x**2*y*[A,B]
|
| 71 |
+
|
| 72 |
+
Using ``.expand(commutator=True)``, the standard commutator expansion rules
|
| 73 |
+
can be applied:
|
| 74 |
+
|
| 75 |
+
>>> Commutator(A+B, C).expand(commutator=True)
|
| 76 |
+
[A,C] + [B,C]
|
| 77 |
+
>>> Commutator(A, B+C).expand(commutator=True)
|
| 78 |
+
[A,B] + [A,C]
|
| 79 |
+
>>> Commutator(A*B, C).expand(commutator=True)
|
| 80 |
+
[A,C]*B + A*[B,C]
|
| 81 |
+
>>> Commutator(A, B*C).expand(commutator=True)
|
| 82 |
+
[A,B]*C + B*[A,C]
|
| 83 |
+
|
| 84 |
+
Adjoint operations applied to the commutator are properly applied to the
|
| 85 |
+
arguments:
|
| 86 |
+
|
| 87 |
+
>>> Dagger(Commutator(A, B))
|
| 88 |
+
-[Dagger(A),Dagger(B)]
|
| 89 |
+
|
| 90 |
+
References
|
| 91 |
+
==========
|
| 92 |
+
|
| 93 |
+
.. [1] https://en.wikipedia.org/wiki/Commutator
|
| 94 |
+
"""
|
| 95 |
+
is_commutative = False
|
| 96 |
+
|
| 97 |
+
def __new__(cls, A, B):
|
| 98 |
+
r = cls.eval(A, B)
|
| 99 |
+
if r is not None:
|
| 100 |
+
return r
|
| 101 |
+
obj = Expr.__new__(cls, A, B)
|
| 102 |
+
return obj
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def eval(cls, a, b):
|
| 106 |
+
if not (a and b):
|
| 107 |
+
return S.Zero
|
| 108 |
+
if a == b:
|
| 109 |
+
return S.Zero
|
| 110 |
+
if a.is_commutative or b.is_commutative:
|
| 111 |
+
return S.Zero
|
| 112 |
+
|
| 113 |
+
# [xA,yB] -> xy*[A,B]
|
| 114 |
+
ca, nca = a.args_cnc()
|
| 115 |
+
cb, ncb = b.args_cnc()
|
| 116 |
+
c_part = ca + cb
|
| 117 |
+
if c_part:
|
| 118 |
+
return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
|
| 119 |
+
|
| 120 |
+
# Canonical ordering of arguments
|
| 121 |
+
# The Commutator [A, B] is in canonical form if A < B.
|
| 122 |
+
if a.compare(b) == 1:
|
| 123 |
+
return S.NegativeOne*cls(b, a)
|
| 124 |
+
|
| 125 |
+
def _expand_pow(self, A, B, sign):
|
| 126 |
+
exp = A.exp
|
| 127 |
+
if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
|
| 128 |
+
# nothing to do
|
| 129 |
+
return self
|
| 130 |
+
base = A.base
|
| 131 |
+
if exp.is_negative:
|
| 132 |
+
base = A.base**-1
|
| 133 |
+
exp = -exp
|
| 134 |
+
comm = Commutator(base, B).expand(commutator=True)
|
| 135 |
+
|
| 136 |
+
result = base**(exp - 1) * comm
|
| 137 |
+
for i in range(1, exp):
|
| 138 |
+
result += base**(exp - 1 - i) * comm * base**i
|
| 139 |
+
return sign*result.expand()
|
| 140 |
+
|
| 141 |
+
def _eval_expand_commutator(self, **hints):
|
| 142 |
+
A = self.args[0]
|
| 143 |
+
B = self.args[1]
|
| 144 |
+
|
| 145 |
+
if isinstance(A, Add):
|
| 146 |
+
# [A + B, C] -> [A, C] + [B, C]
|
| 147 |
+
sargs = []
|
| 148 |
+
for term in A.args:
|
| 149 |
+
comm = Commutator(term, B)
|
| 150 |
+
if isinstance(comm, Commutator):
|
| 151 |
+
comm = comm._eval_expand_commutator()
|
| 152 |
+
sargs.append(comm)
|
| 153 |
+
return Add(*sargs)
|
| 154 |
+
elif isinstance(B, Add):
|
| 155 |
+
# [A, B + C] -> [A, B] + [A, C]
|
| 156 |
+
sargs = []
|
| 157 |
+
for term in B.args:
|
| 158 |
+
comm = Commutator(A, term)
|
| 159 |
+
if isinstance(comm, Commutator):
|
| 160 |
+
comm = comm._eval_expand_commutator()
|
| 161 |
+
sargs.append(comm)
|
| 162 |
+
return Add(*sargs)
|
| 163 |
+
elif isinstance(A, Mul):
|
| 164 |
+
# [A*B, C] -> A*[B, C] + [A, C]*B
|
| 165 |
+
a = A.args[0]
|
| 166 |
+
b = Mul(*A.args[1:])
|
| 167 |
+
c = B
|
| 168 |
+
comm1 = Commutator(b, c)
|
| 169 |
+
comm2 = Commutator(a, c)
|
| 170 |
+
if isinstance(comm1, Commutator):
|
| 171 |
+
comm1 = comm1._eval_expand_commutator()
|
| 172 |
+
if isinstance(comm2, Commutator):
|
| 173 |
+
comm2 = comm2._eval_expand_commutator()
|
| 174 |
+
first = Mul(a, comm1)
|
| 175 |
+
second = Mul(comm2, b)
|
| 176 |
+
return Add(first, second)
|
| 177 |
+
elif isinstance(B, Mul):
|
| 178 |
+
# [A, B*C] -> [A, B]*C + B*[A, C]
|
| 179 |
+
a = A
|
| 180 |
+
b = B.args[0]
|
| 181 |
+
c = Mul(*B.args[1:])
|
| 182 |
+
comm1 = Commutator(a, b)
|
| 183 |
+
comm2 = Commutator(a, c)
|
| 184 |
+
if isinstance(comm1, Commutator):
|
| 185 |
+
comm1 = comm1._eval_expand_commutator()
|
| 186 |
+
if isinstance(comm2, Commutator):
|
| 187 |
+
comm2 = comm2._eval_expand_commutator()
|
| 188 |
+
first = Mul(comm1, c)
|
| 189 |
+
second = Mul(b, comm2)
|
| 190 |
+
return Add(first, second)
|
| 191 |
+
elif isinstance(A, Pow):
|
| 192 |
+
# [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
|
| 193 |
+
return self._expand_pow(A, B, 1)
|
| 194 |
+
elif isinstance(B, Pow):
|
| 195 |
+
# [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
|
| 196 |
+
return self._expand_pow(B, A, -1)
|
| 197 |
+
|
| 198 |
+
# No changes, so return self
|
| 199 |
+
return self
|
| 200 |
+
|
| 201 |
+
def doit(self, **hints):
|
| 202 |
+
""" Evaluate commutator """
|
| 203 |
+
A = self.args[0]
|
| 204 |
+
B = self.args[1]
|
| 205 |
+
if isinstance(A, Operator) and isinstance(B, Operator):
|
| 206 |
+
try:
|
| 207 |
+
comm = A._eval_commutator(B, **hints)
|
| 208 |
+
except NotImplementedError:
|
| 209 |
+
try:
|
| 210 |
+
comm = -1*B._eval_commutator(A, **hints)
|
| 211 |
+
except NotImplementedError:
|
| 212 |
+
comm = None
|
| 213 |
+
if comm is not None:
|
| 214 |
+
return comm.doit(**hints)
|
| 215 |
+
return (A*B - B*A).doit(**hints)
|
| 216 |
+
|
| 217 |
+
def _eval_adjoint(self):
|
| 218 |
+
return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
|
| 219 |
+
|
| 220 |
+
def _sympyrepr(self, printer, *args):
|
| 221 |
+
return "%s(%s,%s)" % (
|
| 222 |
+
self.__class__.__name__, printer._print(
|
| 223 |
+
self.args[0]), printer._print(self.args[1])
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
def _sympystr(self, printer, *args):
|
| 227 |
+
return "[%s,%s]" % (
|
| 228 |
+
printer._print(self.args[0]), printer._print(self.args[1]))
|
| 229 |
+
|
| 230 |
+
def _pretty(self, printer, *args):
|
| 231 |
+
pform = printer._print(self.args[0], *args)
|
| 232 |
+
pform = prettyForm(*pform.right(prettyForm(',')))
|
| 233 |
+
pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
|
| 234 |
+
pform = prettyForm(*pform.parens(left='[', right=']'))
|
| 235 |
+
return pform
|
| 236 |
+
|
| 237 |
+
def _latex(self, printer, *args):
|
| 238 |
+
return "\\left[%s,%s\\right]" % tuple([
|
| 239 |
+
printer._print(arg, *args) for arg in self.args])
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/gate.py
ADDED
|
@@ -0,0 +1,1309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""An implementation of gates that act on qubits.
|
| 2 |
+
|
| 3 |
+
Gates are unitary operators that act on the space of qubits.
|
| 4 |
+
|
| 5 |
+
Medium Term Todo:
|
| 6 |
+
|
| 7 |
+
* Optimize Gate._apply_operators_Qubit to remove the creation of many
|
| 8 |
+
intermediate Qubit objects.
|
| 9 |
+
* Add commutation relationships to all operators and use this in gate_sort.
|
| 10 |
+
* Fix gate_sort and gate_simp.
|
| 11 |
+
* Get multi-target UGates plotting properly.
|
| 12 |
+
* Get UGate to work with either sympy/numpy matrices and output either
|
| 13 |
+
format. This should also use the matrix slots.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from itertools import chain
|
| 17 |
+
import random
|
| 18 |
+
|
| 19 |
+
from sympy.core.add import Add
|
| 20 |
+
from sympy.core.containers import Tuple
|
| 21 |
+
from sympy.core.mul import Mul
|
| 22 |
+
from sympy.core.numbers import (I, Integer)
|
| 23 |
+
from sympy.core.power import Pow
|
| 24 |
+
from sympy.core.numbers import Number
|
| 25 |
+
from sympy.core.singleton import S as _S
|
| 26 |
+
from sympy.core.sorting import default_sort_key
|
| 27 |
+
from sympy.core.sympify import _sympify
|
| 28 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 29 |
+
from sympy.printing.pretty.stringpict import prettyForm, stringPict
|
| 30 |
+
|
| 31 |
+
from sympy.physics.quantum.anticommutator import AntiCommutator
|
| 32 |
+
from sympy.physics.quantum.commutator import Commutator
|
| 33 |
+
from sympy.physics.quantum.qexpr import QuantumError
|
| 34 |
+
from sympy.physics.quantum.hilbert import ComplexSpace
|
| 35 |
+
from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
|
| 36 |
+
HermitianOperator)
|
| 37 |
+
from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
|
| 38 |
+
from sympy.physics.quantum.matrixcache import matrix_cache
|
| 39 |
+
|
| 40 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 41 |
+
|
| 42 |
+
from sympy.utilities.iterables import is_sequence
|
| 43 |
+
|
| 44 |
+
__all__ = [
|
| 45 |
+
'Gate',
|
| 46 |
+
'CGate',
|
| 47 |
+
'UGate',
|
| 48 |
+
'OneQubitGate',
|
| 49 |
+
'TwoQubitGate',
|
| 50 |
+
'IdentityGate',
|
| 51 |
+
'HadamardGate',
|
| 52 |
+
'XGate',
|
| 53 |
+
'YGate',
|
| 54 |
+
'ZGate',
|
| 55 |
+
'TGate',
|
| 56 |
+
'PhaseGate',
|
| 57 |
+
'SwapGate',
|
| 58 |
+
'CNotGate',
|
| 59 |
+
# Aliased gate names
|
| 60 |
+
'CNOT',
|
| 61 |
+
'SWAP',
|
| 62 |
+
'H',
|
| 63 |
+
'X',
|
| 64 |
+
'Y',
|
| 65 |
+
'Z',
|
| 66 |
+
'T',
|
| 67 |
+
'S',
|
| 68 |
+
'Phase',
|
| 69 |
+
'normalized',
|
| 70 |
+
'gate_sort',
|
| 71 |
+
'gate_simp',
|
| 72 |
+
'random_circuit',
|
| 73 |
+
'CPHASE',
|
| 74 |
+
'CGateS',
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
#-----------------------------------------------------------------------------
|
| 78 |
+
# Gate Super-Classes
|
| 79 |
+
#-----------------------------------------------------------------------------
|
| 80 |
+
|
| 81 |
+
_normalized = True
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _max(*args, **kwargs):
|
| 85 |
+
if "key" not in kwargs:
|
| 86 |
+
kwargs["key"] = default_sort_key
|
| 87 |
+
return max(*args, **kwargs)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _min(*args, **kwargs):
|
| 91 |
+
if "key" not in kwargs:
|
| 92 |
+
kwargs["key"] = default_sort_key
|
| 93 |
+
return min(*args, **kwargs)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def normalized(normalize):
|
| 97 |
+
r"""Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`.
|
| 98 |
+
|
| 99 |
+
This is a global setting that can be used to simplify the look of various
|
| 100 |
+
expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate.
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
normalize : bool
|
| 105 |
+
Should the Hadamard gate include the `1/\sqrt{2}` normalization factor?
|
| 106 |
+
When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the
|
| 107 |
+
Hadamard gate will not have this factor.
|
| 108 |
+
"""
|
| 109 |
+
global _normalized
|
| 110 |
+
_normalized = normalize
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _validate_targets_controls(tandc):
|
| 114 |
+
tandc = list(tandc)
|
| 115 |
+
# Check for integers
|
| 116 |
+
for bit in tandc:
|
| 117 |
+
if not bit.is_Integer and not bit.is_Symbol:
|
| 118 |
+
raise TypeError('Integer expected, got: %r' % tandc[bit])
|
| 119 |
+
# Detect duplicates
|
| 120 |
+
if len(set(tandc)) != len(tandc):
|
| 121 |
+
raise QuantumError(
|
| 122 |
+
'Target/control qubits in a gate cannot be duplicated'
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Gate(UnitaryOperator):
|
| 127 |
+
"""Non-controlled unitary gate operator that acts on qubits.
|
| 128 |
+
|
| 129 |
+
This is a general abstract gate that needs to be subclassed to do anything
|
| 130 |
+
useful.
|
| 131 |
+
|
| 132 |
+
Parameters
|
| 133 |
+
----------
|
| 134 |
+
label : tuple, int
|
| 135 |
+
A list of the target qubits (as ints) that the gate will apply to.
|
| 136 |
+
|
| 137 |
+
Examples
|
| 138 |
+
========
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
_label_separator = ','
|
| 144 |
+
|
| 145 |
+
gate_name = 'G'
|
| 146 |
+
gate_name_latex = 'G'
|
| 147 |
+
|
| 148 |
+
#-------------------------------------------------------------------------
|
| 149 |
+
# Initialization/creation
|
| 150 |
+
#-------------------------------------------------------------------------
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def _eval_args(cls, args):
|
| 154 |
+
args = Tuple(*UnitaryOperator._eval_args(args))
|
| 155 |
+
_validate_targets_controls(args)
|
| 156 |
+
return args
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def _eval_hilbert_space(cls, args):
|
| 160 |
+
"""This returns the smallest possible Hilbert space."""
|
| 161 |
+
return ComplexSpace(2)**(_max(args) + 1)
|
| 162 |
+
|
| 163 |
+
#-------------------------------------------------------------------------
|
| 164 |
+
# Properties
|
| 165 |
+
#-------------------------------------------------------------------------
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def nqubits(self):
|
| 169 |
+
"""The total number of qubits this gate acts on.
|
| 170 |
+
|
| 171 |
+
For controlled gate subclasses this includes both target and control
|
| 172 |
+
qubits, so that, for examples the CNOT gate acts on 2 qubits.
|
| 173 |
+
"""
|
| 174 |
+
return len(self.targets)
|
| 175 |
+
|
| 176 |
+
@property
|
| 177 |
+
def min_qubits(self):
|
| 178 |
+
"""The minimum number of qubits this gate needs to act on."""
|
| 179 |
+
return _max(self.targets) + 1
|
| 180 |
+
|
| 181 |
+
@property
|
| 182 |
+
def targets(self):
|
| 183 |
+
"""A tuple of target qubits."""
|
| 184 |
+
return self.label
|
| 185 |
+
|
| 186 |
+
@property
|
| 187 |
+
def gate_name_plot(self):
|
| 188 |
+
return r'$%s$' % self.gate_name_latex
|
| 189 |
+
|
| 190 |
+
#-------------------------------------------------------------------------
|
| 191 |
+
# Gate methods
|
| 192 |
+
#-------------------------------------------------------------------------
|
| 193 |
+
|
| 194 |
+
def get_target_matrix(self, format='sympy'):
|
| 195 |
+
"""The matrix representation of the target part of the gate.
|
| 196 |
+
|
| 197 |
+
Parameters
|
| 198 |
+
----------
|
| 199 |
+
format : str
|
| 200 |
+
The format string ('sympy','numpy', etc.)
|
| 201 |
+
"""
|
| 202 |
+
raise NotImplementedError(
|
| 203 |
+
'get_target_matrix is not implemented in Gate.')
|
| 204 |
+
|
| 205 |
+
#-------------------------------------------------------------------------
|
| 206 |
+
# Apply
|
| 207 |
+
#-------------------------------------------------------------------------
|
| 208 |
+
|
| 209 |
+
def _apply_operator_IntQubit(self, qubits, **options):
|
| 210 |
+
"""Redirect an apply from IntQubit to Qubit"""
|
| 211 |
+
return self._apply_operator_Qubit(qubits, **options)
|
| 212 |
+
|
| 213 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
| 214 |
+
"""Apply this gate to a Qubit."""
|
| 215 |
+
|
| 216 |
+
# Check number of qubits this gate acts on.
|
| 217 |
+
if qubits.nqubits < self.min_qubits:
|
| 218 |
+
raise QuantumError(
|
| 219 |
+
'Gate needs a minimum of %r qubits to act on, got: %r' %
|
| 220 |
+
(self.min_qubits, qubits.nqubits)
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# If the controls are not met, just return
|
| 224 |
+
if isinstance(self, CGate):
|
| 225 |
+
if not self.eval_controls(qubits):
|
| 226 |
+
return qubits
|
| 227 |
+
|
| 228 |
+
targets = self.targets
|
| 229 |
+
target_matrix = self.get_target_matrix(format='sympy')
|
| 230 |
+
|
| 231 |
+
# Find which column of the target matrix this applies to.
|
| 232 |
+
column_index = 0
|
| 233 |
+
n = 1
|
| 234 |
+
for target in targets:
|
| 235 |
+
column_index += n*qubits[target]
|
| 236 |
+
n = n << 1
|
| 237 |
+
column = target_matrix[:, int(column_index)]
|
| 238 |
+
|
| 239 |
+
# Now apply each column element to the qubit.
|
| 240 |
+
result = 0
|
| 241 |
+
for index in range(column.rows):
|
| 242 |
+
# TODO: This can be optimized to reduce the number of Qubit
|
| 243 |
+
# creations. We should simply manipulate the raw list of qubit
|
| 244 |
+
# values and then build the new Qubit object once.
|
| 245 |
+
# Make a copy of the incoming qubits.
|
| 246 |
+
new_qubit = qubits.__class__(*qubits.args)
|
| 247 |
+
# Flip the bits that need to be flipped.
|
| 248 |
+
for bit, target in enumerate(targets):
|
| 249 |
+
if new_qubit[target] != (index >> bit) & 1:
|
| 250 |
+
new_qubit = new_qubit.flip(target)
|
| 251 |
+
# The value in that row and column times the flipped-bit qubit
|
| 252 |
+
# is the result for that part.
|
| 253 |
+
result += column[index]*new_qubit
|
| 254 |
+
return result
|
| 255 |
+
|
| 256 |
+
#-------------------------------------------------------------------------
|
| 257 |
+
# Represent
|
| 258 |
+
#-------------------------------------------------------------------------
|
| 259 |
+
|
| 260 |
+
def _represent_default_basis(self, **options):
|
| 261 |
+
return self._represent_ZGate(None, **options)
|
| 262 |
+
|
| 263 |
+
def _represent_ZGate(self, basis, **options):
|
| 264 |
+
format = options.get('format', 'sympy')
|
| 265 |
+
nqubits = options.get('nqubits', 0)
|
| 266 |
+
if nqubits == 0:
|
| 267 |
+
raise QuantumError(
|
| 268 |
+
'The number of qubits must be given as nqubits.')
|
| 269 |
+
|
| 270 |
+
# Make sure we have enough qubits for the gate.
|
| 271 |
+
if nqubits < self.min_qubits:
|
| 272 |
+
raise QuantumError(
|
| 273 |
+
'The number of qubits %r is too small for the gate.' % nqubits
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
target_matrix = self.get_target_matrix(format)
|
| 277 |
+
targets = self.targets
|
| 278 |
+
if isinstance(self, CGate):
|
| 279 |
+
controls = self.controls
|
| 280 |
+
else:
|
| 281 |
+
controls = []
|
| 282 |
+
m = represent_zbasis(
|
| 283 |
+
controls, targets, target_matrix, nqubits, format
|
| 284 |
+
)
|
| 285 |
+
return m
|
| 286 |
+
|
| 287 |
+
#-------------------------------------------------------------------------
|
| 288 |
+
# Print methods
|
| 289 |
+
#-------------------------------------------------------------------------
|
| 290 |
+
|
| 291 |
+
def _sympystr(self, printer, *args):
|
| 292 |
+
label = self._print_label(printer, *args)
|
| 293 |
+
return '%s(%s)' % (self.gate_name, label)
|
| 294 |
+
|
| 295 |
+
def _pretty(self, printer, *args):
|
| 296 |
+
a = stringPict(self.gate_name)
|
| 297 |
+
b = self._print_label_pretty(printer, *args)
|
| 298 |
+
return self._print_subscript_pretty(a, b)
|
| 299 |
+
|
| 300 |
+
def _latex(self, printer, *args):
|
| 301 |
+
label = self._print_label(printer, *args)
|
| 302 |
+
return '%s_{%s}' % (self.gate_name_latex, label)
|
| 303 |
+
|
| 304 |
+
def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
|
| 305 |
+
raise NotImplementedError('plot_gate is not implemented.')
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class CGate(Gate):
|
| 309 |
+
"""A general unitary gate with control qubits.
|
| 310 |
+
|
| 311 |
+
A general control gate applies a target gate to a set of targets if all
|
| 312 |
+
of the control qubits have a particular values (set by
|
| 313 |
+
``CGate.control_value``).
|
| 314 |
+
|
| 315 |
+
Parameters
|
| 316 |
+
----------
|
| 317 |
+
label : tuple
|
| 318 |
+
The label in this case has the form (controls, gate), where controls
|
| 319 |
+
is a tuple/list of control qubits (as ints) and gate is a ``Gate``
|
| 320 |
+
instance that is the target operator.
|
| 321 |
+
|
| 322 |
+
Examples
|
| 323 |
+
========
|
| 324 |
+
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
gate_name = 'C'
|
| 328 |
+
gate_name_latex = 'C'
|
| 329 |
+
|
| 330 |
+
# The values this class controls for.
|
| 331 |
+
control_value = _S.One
|
| 332 |
+
|
| 333 |
+
simplify_cgate = False
|
| 334 |
+
|
| 335 |
+
#-------------------------------------------------------------------------
|
| 336 |
+
# Initialization
|
| 337 |
+
#-------------------------------------------------------------------------
|
| 338 |
+
|
| 339 |
+
@classmethod
|
| 340 |
+
def _eval_args(cls, args):
|
| 341 |
+
# _eval_args has the right logic for the controls argument.
|
| 342 |
+
controls = args[0]
|
| 343 |
+
gate = args[1]
|
| 344 |
+
if not is_sequence(controls):
|
| 345 |
+
controls = (controls,)
|
| 346 |
+
controls = UnitaryOperator._eval_args(controls)
|
| 347 |
+
_validate_targets_controls(chain(controls, gate.targets))
|
| 348 |
+
return (Tuple(*controls), gate)
|
| 349 |
+
|
| 350 |
+
@classmethod
|
| 351 |
+
def _eval_hilbert_space(cls, args):
|
| 352 |
+
"""This returns the smallest possible Hilbert space."""
|
| 353 |
+
return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
|
| 354 |
+
|
| 355 |
+
#-------------------------------------------------------------------------
|
| 356 |
+
# Properties
|
| 357 |
+
#-------------------------------------------------------------------------
|
| 358 |
+
|
| 359 |
+
@property
|
| 360 |
+
def nqubits(self):
|
| 361 |
+
"""The total number of qubits this gate acts on.
|
| 362 |
+
|
| 363 |
+
For controlled gate subclasses this includes both target and control
|
| 364 |
+
qubits, so that, for examples the CNOT gate acts on 2 qubits.
|
| 365 |
+
"""
|
| 366 |
+
return len(self.targets) + len(self.controls)
|
| 367 |
+
|
| 368 |
+
@property
|
| 369 |
+
def min_qubits(self):
|
| 370 |
+
"""The minimum number of qubits this gate needs to act on."""
|
| 371 |
+
return _max(_max(self.controls), _max(self.targets)) + 1
|
| 372 |
+
|
| 373 |
+
@property
|
| 374 |
+
def targets(self):
|
| 375 |
+
"""A tuple of target qubits."""
|
| 376 |
+
return self.gate.targets
|
| 377 |
+
|
| 378 |
+
@property
|
| 379 |
+
def controls(self):
|
| 380 |
+
"""A tuple of control qubits."""
|
| 381 |
+
return tuple(self.label[0])
|
| 382 |
+
|
| 383 |
+
@property
|
| 384 |
+
def gate(self):
|
| 385 |
+
"""The non-controlled gate that will be applied to the targets."""
|
| 386 |
+
return self.label[1]
|
| 387 |
+
|
| 388 |
+
#-------------------------------------------------------------------------
|
| 389 |
+
# Gate methods
|
| 390 |
+
#-------------------------------------------------------------------------
|
| 391 |
+
|
| 392 |
+
def get_target_matrix(self, format='sympy'):
|
| 393 |
+
return self.gate.get_target_matrix(format)
|
| 394 |
+
|
| 395 |
+
def eval_controls(self, qubit):
|
| 396 |
+
"""Return True/False to indicate if the controls are satisfied."""
|
| 397 |
+
return all(qubit[bit] == self.control_value for bit in self.controls)
|
| 398 |
+
|
| 399 |
+
def decompose(self, **options):
|
| 400 |
+
"""Decompose the controlled gate into CNOT and single qubits gates."""
|
| 401 |
+
if len(self.controls) == 1:
|
| 402 |
+
c = self.controls[0]
|
| 403 |
+
t = self.gate.targets[0]
|
| 404 |
+
if isinstance(self.gate, YGate):
|
| 405 |
+
g1 = PhaseGate(t)
|
| 406 |
+
g2 = CNotGate(c, t)
|
| 407 |
+
g3 = PhaseGate(t)
|
| 408 |
+
g4 = ZGate(t)
|
| 409 |
+
return g1*g2*g3*g4
|
| 410 |
+
if isinstance(self.gate, ZGate):
|
| 411 |
+
g1 = HadamardGate(t)
|
| 412 |
+
g2 = CNotGate(c, t)
|
| 413 |
+
g3 = HadamardGate(t)
|
| 414 |
+
return g1*g2*g3
|
| 415 |
+
else:
|
| 416 |
+
return self
|
| 417 |
+
|
| 418 |
+
#-------------------------------------------------------------------------
|
| 419 |
+
# Print methods
|
| 420 |
+
#-------------------------------------------------------------------------
|
| 421 |
+
|
| 422 |
+
def _print_label(self, printer, *args):
|
| 423 |
+
controls = self._print_sequence(self.controls, ',', printer, *args)
|
| 424 |
+
gate = printer._print(self.gate, *args)
|
| 425 |
+
return '(%s),%s' % (controls, gate)
|
| 426 |
+
|
| 427 |
+
def _pretty(self, printer, *args):
|
| 428 |
+
controls = self._print_sequence_pretty(
|
| 429 |
+
self.controls, ',', printer, *args)
|
| 430 |
+
gate = printer._print(self.gate)
|
| 431 |
+
gate_name = stringPict(self.gate_name)
|
| 432 |
+
first = self._print_subscript_pretty(gate_name, controls)
|
| 433 |
+
gate = self._print_parens_pretty(gate)
|
| 434 |
+
final = prettyForm(*first.right(gate))
|
| 435 |
+
return final
|
| 436 |
+
|
| 437 |
+
def _latex(self, printer, *args):
|
| 438 |
+
controls = self._print_sequence(self.controls, ',', printer, *args)
|
| 439 |
+
gate = printer._print(self.gate, *args)
|
| 440 |
+
return r'%s_{%s}{\left(%s\right)}' % \
|
| 441 |
+
(self.gate_name_latex, controls, gate)
|
| 442 |
+
|
| 443 |
+
def plot_gate(self, circ_plot, gate_idx):
|
| 444 |
+
"""
|
| 445 |
+
Plot the controlled gate. If *simplify_cgate* is true, simplify
|
| 446 |
+
C-X and C-Z gates into their more familiar forms.
|
| 447 |
+
"""
|
| 448 |
+
min_wire = int(_min(chain(self.controls, self.targets)))
|
| 449 |
+
max_wire = int(_max(chain(self.controls, self.targets)))
|
| 450 |
+
circ_plot.control_line(gate_idx, min_wire, max_wire)
|
| 451 |
+
for c in self.controls:
|
| 452 |
+
circ_plot.control_point(gate_idx, int(c))
|
| 453 |
+
if self.simplify_cgate:
|
| 454 |
+
if self.gate.gate_name == 'X':
|
| 455 |
+
self.gate.plot_gate_plus(circ_plot, gate_idx)
|
| 456 |
+
elif self.gate.gate_name == 'Z':
|
| 457 |
+
circ_plot.control_point(gate_idx, self.targets[0])
|
| 458 |
+
else:
|
| 459 |
+
self.gate.plot_gate(circ_plot, gate_idx)
|
| 460 |
+
else:
|
| 461 |
+
self.gate.plot_gate(circ_plot, gate_idx)
|
| 462 |
+
|
| 463 |
+
#-------------------------------------------------------------------------
|
| 464 |
+
# Miscellaneous
|
| 465 |
+
#-------------------------------------------------------------------------
|
| 466 |
+
|
| 467 |
+
def _eval_dagger(self):
|
| 468 |
+
if isinstance(self.gate, HermitianOperator):
|
| 469 |
+
return self
|
| 470 |
+
else:
|
| 471 |
+
return Gate._eval_dagger(self)
|
| 472 |
+
|
| 473 |
+
def _eval_inverse(self):
|
| 474 |
+
if isinstance(self.gate, HermitianOperator):
|
| 475 |
+
return self
|
| 476 |
+
else:
|
| 477 |
+
return Gate._eval_inverse(self)
|
| 478 |
+
|
| 479 |
+
def _eval_power(self, exp):
|
| 480 |
+
if isinstance(self.gate, HermitianOperator):
|
| 481 |
+
if exp == -1:
|
| 482 |
+
return Gate._eval_power(self, exp)
|
| 483 |
+
elif abs(exp) % 2 == 0:
|
| 484 |
+
return self*(Gate._eval_inverse(self))
|
| 485 |
+
else:
|
| 486 |
+
return self
|
| 487 |
+
else:
|
| 488 |
+
return Gate._eval_power(self, exp)
|
| 489 |
+
|
| 490 |
+
class CGateS(CGate):
|
| 491 |
+
"""Version of CGate that allows gate simplifications.
|
| 492 |
+
I.e. cnot looks like an oplus, cphase has dots, etc.
|
| 493 |
+
"""
|
| 494 |
+
simplify_cgate=True
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
class UGate(Gate):
|
| 498 |
+
"""General gate specified by a set of targets and a target matrix.
|
| 499 |
+
|
| 500 |
+
Parameters
|
| 501 |
+
----------
|
| 502 |
+
label : tuple
|
| 503 |
+
A tuple of the form (targets, U), where targets is a tuple of the
|
| 504 |
+
target qubits and U is a unitary matrix with dimension of
|
| 505 |
+
len(targets).
|
| 506 |
+
"""
|
| 507 |
+
gate_name = 'U'
|
| 508 |
+
gate_name_latex = 'U'
|
| 509 |
+
|
| 510 |
+
#-------------------------------------------------------------------------
|
| 511 |
+
# Initialization
|
| 512 |
+
#-------------------------------------------------------------------------
|
| 513 |
+
|
| 514 |
+
@classmethod
|
| 515 |
+
def _eval_args(cls, args):
|
| 516 |
+
targets = args[0]
|
| 517 |
+
if not is_sequence(targets):
|
| 518 |
+
targets = (targets,)
|
| 519 |
+
targets = Gate._eval_args(targets)
|
| 520 |
+
_validate_targets_controls(targets)
|
| 521 |
+
mat = args[1]
|
| 522 |
+
if not isinstance(mat, MatrixBase):
|
| 523 |
+
raise TypeError('Matrix expected, got: %r' % mat)
|
| 524 |
+
#make sure this matrix is of a Basic type
|
| 525 |
+
mat = _sympify(mat)
|
| 526 |
+
dim = 2**len(targets)
|
| 527 |
+
if not all(dim == shape for shape in mat.shape):
|
| 528 |
+
raise IndexError(
|
| 529 |
+
'Number of targets must match the matrix size: %r %r' %
|
| 530 |
+
(targets, mat)
|
| 531 |
+
)
|
| 532 |
+
return (targets, mat)
|
| 533 |
+
|
| 534 |
+
@classmethod
|
| 535 |
+
def _eval_hilbert_space(cls, args):
|
| 536 |
+
"""This returns the smallest possible Hilbert space."""
|
| 537 |
+
return ComplexSpace(2)**(_max(args[0]) + 1)
|
| 538 |
+
|
| 539 |
+
#-------------------------------------------------------------------------
|
| 540 |
+
# Properties
|
| 541 |
+
#-------------------------------------------------------------------------
|
| 542 |
+
|
| 543 |
+
@property
|
| 544 |
+
def targets(self):
|
| 545 |
+
"""A tuple of target qubits."""
|
| 546 |
+
return tuple(self.label[0])
|
| 547 |
+
|
| 548 |
+
#-------------------------------------------------------------------------
|
| 549 |
+
# Gate methods
|
| 550 |
+
#-------------------------------------------------------------------------
|
| 551 |
+
|
| 552 |
+
def get_target_matrix(self, format='sympy'):
|
| 553 |
+
"""The matrix rep. of the target part of the gate.
|
| 554 |
+
|
| 555 |
+
Parameters
|
| 556 |
+
----------
|
| 557 |
+
format : str
|
| 558 |
+
The format string ('sympy','numpy', etc.)
|
| 559 |
+
"""
|
| 560 |
+
return self.label[1]
|
| 561 |
+
|
| 562 |
+
#-------------------------------------------------------------------------
|
| 563 |
+
# Print methods
|
| 564 |
+
#-------------------------------------------------------------------------
|
| 565 |
+
def _pretty(self, printer, *args):
|
| 566 |
+
targets = self._print_sequence_pretty(
|
| 567 |
+
self.targets, ',', printer, *args)
|
| 568 |
+
gate_name = stringPict(self.gate_name)
|
| 569 |
+
return self._print_subscript_pretty(gate_name, targets)
|
| 570 |
+
|
| 571 |
+
def _latex(self, printer, *args):
|
| 572 |
+
targets = self._print_sequence(self.targets, ',', printer, *args)
|
| 573 |
+
return r'%s_{%s}' % (self.gate_name_latex, targets)
|
| 574 |
+
|
| 575 |
+
def plot_gate(self, circ_plot, gate_idx):
|
| 576 |
+
circ_plot.one_qubit_box(
|
| 577 |
+
self.gate_name_plot,
|
| 578 |
+
gate_idx, int(self.targets[0])
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
class OneQubitGate(Gate):
|
| 583 |
+
"""A single qubit unitary gate base class."""
|
| 584 |
+
|
| 585 |
+
nqubits = _S.One
|
| 586 |
+
|
| 587 |
+
def plot_gate(self, circ_plot, gate_idx):
|
| 588 |
+
circ_plot.one_qubit_box(
|
| 589 |
+
self.gate_name_plot,
|
| 590 |
+
gate_idx, int(self.targets[0])
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
def _eval_commutator(self, other, **hints):
|
| 594 |
+
if isinstance(other, OneQubitGate):
|
| 595 |
+
if self.targets != other.targets or self.__class__ == other.__class__:
|
| 596 |
+
return _S.Zero
|
| 597 |
+
return Operator._eval_commutator(self, other, **hints)
|
| 598 |
+
|
| 599 |
+
def _eval_anticommutator(self, other, **hints):
|
| 600 |
+
if isinstance(other, OneQubitGate):
|
| 601 |
+
if self.targets != other.targets or self.__class__ == other.__class__:
|
| 602 |
+
return Integer(2)*self*other
|
| 603 |
+
return Operator._eval_anticommutator(self, other, **hints)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
class TwoQubitGate(Gate):
|
| 607 |
+
"""A two qubit unitary gate base class."""
|
| 608 |
+
|
| 609 |
+
nqubits = Integer(2)
|
| 610 |
+
|
| 611 |
+
#-----------------------------------------------------------------------------
|
| 612 |
+
# Single Qubit Gates
|
| 613 |
+
#-----------------------------------------------------------------------------
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
class IdentityGate(OneQubitGate):
|
| 617 |
+
"""The single qubit identity gate.
|
| 618 |
+
|
| 619 |
+
Parameters
|
| 620 |
+
----------
|
| 621 |
+
target : int
|
| 622 |
+
The target qubit this gate will apply to.
|
| 623 |
+
|
| 624 |
+
Examples
|
| 625 |
+
========
|
| 626 |
+
|
| 627 |
+
"""
|
| 628 |
+
is_hermitian = True
|
| 629 |
+
gate_name = '1'
|
| 630 |
+
gate_name_latex = '1'
|
| 631 |
+
|
| 632 |
+
# Short cut version of gate._apply_operator_Qubit
|
| 633 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
| 634 |
+
# Check number of qubits this gate acts on (see gate._apply_operator_Qubit)
|
| 635 |
+
if qubits.nqubits < self.min_qubits:
|
| 636 |
+
raise QuantumError(
|
| 637 |
+
'Gate needs a minimum of %r qubits to act on, got: %r' %
|
| 638 |
+
(self.min_qubits, qubits.nqubits)
|
| 639 |
+
)
|
| 640 |
+
return qubits # no computation required for IdentityGate
|
| 641 |
+
|
| 642 |
+
def get_target_matrix(self, format='sympy'):
|
| 643 |
+
return matrix_cache.get_matrix('eye2', format)
|
| 644 |
+
|
| 645 |
+
def _eval_commutator(self, other, **hints):
|
| 646 |
+
return _S.Zero
|
| 647 |
+
|
| 648 |
+
def _eval_anticommutator(self, other, **hints):
|
| 649 |
+
return Integer(2)*other
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
class HadamardGate(HermitianOperator, OneQubitGate):
|
| 653 |
+
"""The single qubit Hadamard gate.
|
| 654 |
+
|
| 655 |
+
Parameters
|
| 656 |
+
----------
|
| 657 |
+
target : int
|
| 658 |
+
The target qubit this gate will apply to.
|
| 659 |
+
|
| 660 |
+
Examples
|
| 661 |
+
========
|
| 662 |
+
|
| 663 |
+
>>> from sympy import sqrt
|
| 664 |
+
>>> from sympy.physics.quantum.qubit import Qubit
|
| 665 |
+
>>> from sympy.physics.quantum.gate import HadamardGate
|
| 666 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
| 667 |
+
>>> qapply(HadamardGate(0)*Qubit('1'))
|
| 668 |
+
sqrt(2)*|0>/2 - sqrt(2)*|1>/2
|
| 669 |
+
>>> # Hadamard on bell state, applied on 2 qubits.
|
| 670 |
+
>>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
|
| 671 |
+
>>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
|
| 672 |
+
sqrt(2)*|00>/2 + sqrt(2)*|11>/2
|
| 673 |
+
|
| 674 |
+
"""
|
| 675 |
+
gate_name = 'H'
|
| 676 |
+
gate_name_latex = 'H'
|
| 677 |
+
|
| 678 |
+
def get_target_matrix(self, format='sympy'):
|
| 679 |
+
if _normalized:
|
| 680 |
+
return matrix_cache.get_matrix('H', format)
|
| 681 |
+
else:
|
| 682 |
+
return matrix_cache.get_matrix('Hsqrt2', format)
|
| 683 |
+
|
| 684 |
+
def _eval_commutator_XGate(self, other, **hints):
|
| 685 |
+
return I*sqrt(2)*YGate(self.targets[0])
|
| 686 |
+
|
| 687 |
+
def _eval_commutator_YGate(self, other, **hints):
|
| 688 |
+
return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
|
| 689 |
+
|
| 690 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
| 691 |
+
return -I*sqrt(2)*YGate(self.targets[0])
|
| 692 |
+
|
| 693 |
+
def _eval_anticommutator_XGate(self, other, **hints):
|
| 694 |
+
return sqrt(2)*IdentityGate(self.targets[0])
|
| 695 |
+
|
| 696 |
+
def _eval_anticommutator_YGate(self, other, **hints):
|
| 697 |
+
return _S.Zero
|
| 698 |
+
|
| 699 |
+
def _eval_anticommutator_ZGate(self, other, **hints):
|
| 700 |
+
return sqrt(2)*IdentityGate(self.targets[0])
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class XGate(HermitianOperator, OneQubitGate):
|
| 704 |
+
"""The single qubit X, or NOT, gate.
|
| 705 |
+
|
| 706 |
+
Parameters
|
| 707 |
+
----------
|
| 708 |
+
target : int
|
| 709 |
+
The target qubit this gate will apply to.
|
| 710 |
+
|
| 711 |
+
Examples
|
| 712 |
+
========
|
| 713 |
+
|
| 714 |
+
"""
|
| 715 |
+
gate_name = 'X'
|
| 716 |
+
gate_name_latex = 'X'
|
| 717 |
+
|
| 718 |
+
def get_target_matrix(self, format='sympy'):
|
| 719 |
+
return matrix_cache.get_matrix('X', format)
|
| 720 |
+
|
| 721 |
+
def plot_gate(self, circ_plot, gate_idx):
|
| 722 |
+
OneQubitGate.plot_gate(self,circ_plot,gate_idx)
|
| 723 |
+
|
| 724 |
+
def plot_gate_plus(self, circ_plot, gate_idx):
|
| 725 |
+
circ_plot.not_point(
|
| 726 |
+
gate_idx, int(self.label[0])
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
def _eval_commutator_YGate(self, other, **hints):
|
| 730 |
+
return Integer(2)*I*ZGate(self.targets[0])
|
| 731 |
+
|
| 732 |
+
def _eval_anticommutator_XGate(self, other, **hints):
|
| 733 |
+
return Integer(2)*IdentityGate(self.targets[0])
|
| 734 |
+
|
| 735 |
+
def _eval_anticommutator_YGate(self, other, **hints):
|
| 736 |
+
return _S.Zero
|
| 737 |
+
|
| 738 |
+
def _eval_anticommutator_ZGate(self, other, **hints):
|
| 739 |
+
return _S.Zero
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
class YGate(HermitianOperator, OneQubitGate):
|
| 743 |
+
"""The single qubit Y gate.
|
| 744 |
+
|
| 745 |
+
Parameters
|
| 746 |
+
----------
|
| 747 |
+
target : int
|
| 748 |
+
The target qubit this gate will apply to.
|
| 749 |
+
|
| 750 |
+
Examples
|
| 751 |
+
========
|
| 752 |
+
|
| 753 |
+
"""
|
| 754 |
+
gate_name = 'Y'
|
| 755 |
+
gate_name_latex = 'Y'
|
| 756 |
+
|
| 757 |
+
def get_target_matrix(self, format='sympy'):
|
| 758 |
+
return matrix_cache.get_matrix('Y', format)
|
| 759 |
+
|
| 760 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
| 761 |
+
return Integer(2)*I*XGate(self.targets[0])
|
| 762 |
+
|
| 763 |
+
def _eval_anticommutator_YGate(self, other, **hints):
|
| 764 |
+
return Integer(2)*IdentityGate(self.targets[0])
|
| 765 |
+
|
| 766 |
+
def _eval_anticommutator_ZGate(self, other, **hints):
|
| 767 |
+
return _S.Zero
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
class ZGate(HermitianOperator, OneQubitGate):
|
| 771 |
+
"""The single qubit Z gate.
|
| 772 |
+
|
| 773 |
+
Parameters
|
| 774 |
+
----------
|
| 775 |
+
target : int
|
| 776 |
+
The target qubit this gate will apply to.
|
| 777 |
+
|
| 778 |
+
Examples
|
| 779 |
+
========
|
| 780 |
+
|
| 781 |
+
"""
|
| 782 |
+
gate_name = 'Z'
|
| 783 |
+
gate_name_latex = 'Z'
|
| 784 |
+
|
| 785 |
+
def get_target_matrix(self, format='sympy'):
|
| 786 |
+
return matrix_cache.get_matrix('Z', format)
|
| 787 |
+
|
| 788 |
+
def _eval_commutator_XGate(self, other, **hints):
|
| 789 |
+
return Integer(2)*I*YGate(self.targets[0])
|
| 790 |
+
|
| 791 |
+
def _eval_anticommutator_YGate(self, other, **hints):
|
| 792 |
+
return _S.Zero
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
class PhaseGate(OneQubitGate):
|
| 796 |
+
"""The single qubit phase, or S, gate.
|
| 797 |
+
|
| 798 |
+
This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
|
| 799 |
+
does nothing if the state is ``|0>``.
|
| 800 |
+
|
| 801 |
+
Parameters
|
| 802 |
+
----------
|
| 803 |
+
target : int
|
| 804 |
+
The target qubit this gate will apply to.
|
| 805 |
+
|
| 806 |
+
Examples
|
| 807 |
+
========
|
| 808 |
+
|
| 809 |
+
"""
|
| 810 |
+
is_hermitian = False
|
| 811 |
+
gate_name = 'S'
|
| 812 |
+
gate_name_latex = 'S'
|
| 813 |
+
|
| 814 |
+
def get_target_matrix(self, format='sympy'):
|
| 815 |
+
return matrix_cache.get_matrix('S', format)
|
| 816 |
+
|
| 817 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
| 818 |
+
return _S.Zero
|
| 819 |
+
|
| 820 |
+
def _eval_commutator_TGate(self, other, **hints):
|
| 821 |
+
return _S.Zero
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
class TGate(OneQubitGate):
|
| 825 |
+
"""The single qubit pi/8 gate.
|
| 826 |
+
|
| 827 |
+
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
|
| 828 |
+
does nothing if the state is ``|0>``.
|
| 829 |
+
|
| 830 |
+
Parameters
|
| 831 |
+
----------
|
| 832 |
+
target : int
|
| 833 |
+
The target qubit this gate will apply to.
|
| 834 |
+
|
| 835 |
+
Examples
|
| 836 |
+
========
|
| 837 |
+
|
| 838 |
+
"""
|
| 839 |
+
is_hermitian = False
|
| 840 |
+
gate_name = 'T'
|
| 841 |
+
gate_name_latex = 'T'
|
| 842 |
+
|
| 843 |
+
def get_target_matrix(self, format='sympy'):
|
| 844 |
+
return matrix_cache.get_matrix('T', format)
|
| 845 |
+
|
| 846 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
| 847 |
+
return _S.Zero
|
| 848 |
+
|
| 849 |
+
def _eval_commutator_PhaseGate(self, other, **hints):
|
| 850 |
+
return _S.Zero
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
# Aliases for gate names.
|
| 854 |
+
H = HadamardGate
|
| 855 |
+
X = XGate
|
| 856 |
+
Y = YGate
|
| 857 |
+
Z = ZGate
|
| 858 |
+
T = TGate
|
| 859 |
+
Phase = S = PhaseGate
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
#-----------------------------------------------------------------------------
|
| 863 |
+
# 2 Qubit Gates
|
| 864 |
+
#-----------------------------------------------------------------------------
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
class CNotGate(HermitianOperator, CGate, TwoQubitGate):
|
| 868 |
+
"""Two qubit controlled-NOT.
|
| 869 |
+
|
| 870 |
+
This gate performs the NOT or X gate on the target qubit if the control
|
| 871 |
+
qubits all have the value 1.
|
| 872 |
+
|
| 873 |
+
Parameters
|
| 874 |
+
----------
|
| 875 |
+
label : tuple
|
| 876 |
+
A tuple of the form (control, target).
|
| 877 |
+
|
| 878 |
+
Examples
|
| 879 |
+
========
|
| 880 |
+
|
| 881 |
+
>>> from sympy.physics.quantum.gate import CNOT
|
| 882 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
| 883 |
+
>>> from sympy.physics.quantum.qubit import Qubit
|
| 884 |
+
>>> c = CNOT(1,0)
|
| 885 |
+
>>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
|
| 886 |
+
|11>
|
| 887 |
+
|
| 888 |
+
"""
|
| 889 |
+
gate_name = 'CNOT'
|
| 890 |
+
gate_name_latex = r'\text{CNOT}'
|
| 891 |
+
simplify_cgate = True
|
| 892 |
+
|
| 893 |
+
#-------------------------------------------------------------------------
|
| 894 |
+
# Initialization
|
| 895 |
+
#-------------------------------------------------------------------------
|
| 896 |
+
|
| 897 |
+
@classmethod
|
| 898 |
+
def _eval_args(cls, args):
|
| 899 |
+
args = Gate._eval_args(args)
|
| 900 |
+
return args
|
| 901 |
+
|
| 902 |
+
@classmethod
|
| 903 |
+
def _eval_hilbert_space(cls, args):
|
| 904 |
+
"""This returns the smallest possible Hilbert space."""
|
| 905 |
+
return ComplexSpace(2)**(_max(args) + 1)
|
| 906 |
+
|
| 907 |
+
#-------------------------------------------------------------------------
|
| 908 |
+
# Properties
|
| 909 |
+
#-------------------------------------------------------------------------
|
| 910 |
+
|
| 911 |
+
@property
|
| 912 |
+
def min_qubits(self):
|
| 913 |
+
"""The minimum number of qubits this gate needs to act on."""
|
| 914 |
+
return _max(self.label) + 1
|
| 915 |
+
|
| 916 |
+
@property
|
| 917 |
+
def targets(self):
|
| 918 |
+
"""A tuple of target qubits."""
|
| 919 |
+
return (self.label[1],)
|
| 920 |
+
|
| 921 |
+
@property
|
| 922 |
+
def controls(self):
|
| 923 |
+
"""A tuple of control qubits."""
|
| 924 |
+
return (self.label[0],)
|
| 925 |
+
|
| 926 |
+
@property
|
| 927 |
+
def gate(self):
|
| 928 |
+
"""The non-controlled gate that will be applied to the targets."""
|
| 929 |
+
return XGate(self.label[1])
|
| 930 |
+
|
| 931 |
+
#-------------------------------------------------------------------------
|
| 932 |
+
# Properties
|
| 933 |
+
#-------------------------------------------------------------------------
|
| 934 |
+
|
| 935 |
+
# The default printing of Gate works better than those of CGate, so we
|
| 936 |
+
# go around the overridden methods in CGate.
|
| 937 |
+
|
| 938 |
+
def _print_label(self, printer, *args):
|
| 939 |
+
return Gate._print_label(self, printer, *args)
|
| 940 |
+
|
| 941 |
+
def _pretty(self, printer, *args):
|
| 942 |
+
return Gate._pretty(self, printer, *args)
|
| 943 |
+
|
| 944 |
+
def _latex(self, printer, *args):
|
| 945 |
+
return Gate._latex(self, printer, *args)
|
| 946 |
+
|
| 947 |
+
#-------------------------------------------------------------------------
|
| 948 |
+
# Commutator/AntiCommutator
|
| 949 |
+
#-------------------------------------------------------------------------
|
| 950 |
+
|
| 951 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
| 952 |
+
"""[CNOT(i, j), Z(i)] == 0."""
|
| 953 |
+
if self.controls[0] == other.targets[0]:
|
| 954 |
+
return _S.Zero
|
| 955 |
+
else:
|
| 956 |
+
raise NotImplementedError('Commutator not implemented: %r' % other)
|
| 957 |
+
|
| 958 |
+
def _eval_commutator_TGate(self, other, **hints):
|
| 959 |
+
"""[CNOT(i, j), T(i)] == 0."""
|
| 960 |
+
return self._eval_commutator_ZGate(other, **hints)
|
| 961 |
+
|
| 962 |
+
def _eval_commutator_PhaseGate(self, other, **hints):
|
| 963 |
+
"""[CNOT(i, j), S(i)] == 0."""
|
| 964 |
+
return self._eval_commutator_ZGate(other, **hints)
|
| 965 |
+
|
| 966 |
+
def _eval_commutator_XGate(self, other, **hints):
|
| 967 |
+
"""[CNOT(i, j), X(j)] == 0."""
|
| 968 |
+
if self.targets[0] == other.targets[0]:
|
| 969 |
+
return _S.Zero
|
| 970 |
+
else:
|
| 971 |
+
raise NotImplementedError('Commutator not implemented: %r' % other)
|
| 972 |
+
|
| 973 |
+
def _eval_commutator_CNotGate(self, other, **hints):
|
| 974 |
+
"""[CNOT(i, j), CNOT(i,k)] == 0."""
|
| 975 |
+
if self.controls[0] == other.controls[0]:
|
| 976 |
+
return _S.Zero
|
| 977 |
+
else:
|
| 978 |
+
raise NotImplementedError('Commutator not implemented: %r' % other)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
class SwapGate(TwoQubitGate):
|
| 982 |
+
"""Two qubit SWAP gate.
|
| 983 |
+
|
| 984 |
+
This gate swap the values of the two qubits.
|
| 985 |
+
|
| 986 |
+
Parameters
|
| 987 |
+
----------
|
| 988 |
+
label : tuple
|
| 989 |
+
A tuple of the form (target1, target2).
|
| 990 |
+
|
| 991 |
+
Examples
|
| 992 |
+
========
|
| 993 |
+
|
| 994 |
+
"""
|
| 995 |
+
is_hermitian = True
|
| 996 |
+
gate_name = 'SWAP'
|
| 997 |
+
gate_name_latex = r'\text{SWAP}'
|
| 998 |
+
|
| 999 |
+
def get_target_matrix(self, format='sympy'):
|
| 1000 |
+
return matrix_cache.get_matrix('SWAP', format)
|
| 1001 |
+
|
| 1002 |
+
def decompose(self, **options):
|
| 1003 |
+
"""Decompose the SWAP gate into CNOT gates."""
|
| 1004 |
+
i, j = self.targets[0], self.targets[1]
|
| 1005 |
+
g1 = CNotGate(i, j)
|
| 1006 |
+
g2 = CNotGate(j, i)
|
| 1007 |
+
return g1*g2*g1
|
| 1008 |
+
|
| 1009 |
+
def plot_gate(self, circ_plot, gate_idx):
|
| 1010 |
+
min_wire = int(_min(self.targets))
|
| 1011 |
+
max_wire = int(_max(self.targets))
|
| 1012 |
+
circ_plot.control_line(gate_idx, min_wire, max_wire)
|
| 1013 |
+
circ_plot.swap_point(gate_idx, min_wire)
|
| 1014 |
+
circ_plot.swap_point(gate_idx, max_wire)
|
| 1015 |
+
|
| 1016 |
+
def _represent_ZGate(self, basis, **options):
|
| 1017 |
+
"""Represent the SWAP gate in the computational basis.
|
| 1018 |
+
|
| 1019 |
+
The following representation is used to compute this:
|
| 1020 |
+
|
| 1021 |
+
SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
|
| 1022 |
+
"""
|
| 1023 |
+
format = options.get('format', 'sympy')
|
| 1024 |
+
targets = [int(t) for t in self.targets]
|
| 1025 |
+
min_target = _min(targets)
|
| 1026 |
+
max_target = _max(targets)
|
| 1027 |
+
nqubits = options.get('nqubits', self.min_qubits)
|
| 1028 |
+
|
| 1029 |
+
op01 = matrix_cache.get_matrix('op01', format)
|
| 1030 |
+
op10 = matrix_cache.get_matrix('op10', format)
|
| 1031 |
+
op11 = matrix_cache.get_matrix('op11', format)
|
| 1032 |
+
op00 = matrix_cache.get_matrix('op00', format)
|
| 1033 |
+
eye2 = matrix_cache.get_matrix('eye2', format)
|
| 1034 |
+
|
| 1035 |
+
result = None
|
| 1036 |
+
for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
|
| 1037 |
+
product = nqubits*[eye2]
|
| 1038 |
+
product[nqubits - min_target - 1] = i
|
| 1039 |
+
product[nqubits - max_target - 1] = j
|
| 1040 |
+
new_result = matrix_tensor_product(*product)
|
| 1041 |
+
if result is None:
|
| 1042 |
+
result = new_result
|
| 1043 |
+
else:
|
| 1044 |
+
result = result + new_result
|
| 1045 |
+
|
| 1046 |
+
return result
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
# Aliases for gate names.
|
| 1050 |
+
CNOT = CNotGate
|
| 1051 |
+
SWAP = SwapGate
|
| 1052 |
+
def CPHASE(a,b): return CGateS((a,),Z(b))
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
#-----------------------------------------------------------------------------
|
| 1056 |
+
# Represent
|
| 1057 |
+
#-----------------------------------------------------------------------------
|
| 1058 |
+
|
| 1059 |
+
|
| 1060 |
+
def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
|
| 1061 |
+
"""Represent a gate with controls, targets and target_matrix.
|
| 1062 |
+
|
| 1063 |
+
This function does the low-level work of representing gates as matrices
|
| 1064 |
+
in the standard computational basis (ZGate). Currently, we support two
|
| 1065 |
+
main cases:
|
| 1066 |
+
|
| 1067 |
+
1. One target qubit and no control qubits.
|
| 1068 |
+
2. One target qubits and multiple control qubits.
|
| 1069 |
+
|
| 1070 |
+
For the base of multiple controls, we use the following expression [1]:
|
| 1071 |
+
|
| 1072 |
+
1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
|
| 1073 |
+
|
| 1074 |
+
Parameters
|
| 1075 |
+
----------
|
| 1076 |
+
controls : list, tuple
|
| 1077 |
+
A sequence of control qubits.
|
| 1078 |
+
targets : list, tuple
|
| 1079 |
+
A sequence of target qubits.
|
| 1080 |
+
target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
|
| 1081 |
+
The matrix form of the transformation to be performed on the target
|
| 1082 |
+
qubits. The format of this matrix must match that passed into
|
| 1083 |
+
the `format` argument.
|
| 1084 |
+
nqubits : int
|
| 1085 |
+
The total number of qubits used for the representation.
|
| 1086 |
+
format : str
|
| 1087 |
+
The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
|
| 1088 |
+
|
| 1089 |
+
Examples
|
| 1090 |
+
========
|
| 1091 |
+
|
| 1092 |
+
References
|
| 1093 |
+
----------
|
| 1094 |
+
[1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
|
| 1095 |
+
"""
|
| 1096 |
+
controls = [int(x) for x in controls]
|
| 1097 |
+
targets = [int(x) for x in targets]
|
| 1098 |
+
nqubits = int(nqubits)
|
| 1099 |
+
|
| 1100 |
+
# This checks for the format as well.
|
| 1101 |
+
op11 = matrix_cache.get_matrix('op11', format)
|
| 1102 |
+
eye2 = matrix_cache.get_matrix('eye2', format)
|
| 1103 |
+
|
| 1104 |
+
# Plain single qubit case
|
| 1105 |
+
if len(controls) == 0 and len(targets) == 1:
|
| 1106 |
+
product = []
|
| 1107 |
+
bit = targets[0]
|
| 1108 |
+
# Fill product with [I1,Gate,I2] such that the unitaries,
|
| 1109 |
+
# I, cause the gate to be applied to the correct Qubit
|
| 1110 |
+
if bit != nqubits - 1:
|
| 1111 |
+
product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
|
| 1112 |
+
product.append(target_matrix)
|
| 1113 |
+
if bit != 0:
|
| 1114 |
+
product.append(matrix_eye(2**bit, format=format))
|
| 1115 |
+
return matrix_tensor_product(*product)
|
| 1116 |
+
|
| 1117 |
+
# Single target, multiple controls.
|
| 1118 |
+
elif len(targets) == 1 and len(controls) >= 1:
|
| 1119 |
+
target = targets[0]
|
| 1120 |
+
|
| 1121 |
+
# Build the non-trivial part.
|
| 1122 |
+
product2 = []
|
| 1123 |
+
for i in range(nqubits):
|
| 1124 |
+
product2.append(matrix_eye(2, format=format))
|
| 1125 |
+
for control in controls:
|
| 1126 |
+
product2[nqubits - 1 - control] = op11
|
| 1127 |
+
product2[nqubits - 1 - target] = target_matrix - eye2
|
| 1128 |
+
|
| 1129 |
+
return matrix_eye(2**nqubits, format=format) + \
|
| 1130 |
+
matrix_tensor_product(*product2)
|
| 1131 |
+
|
| 1132 |
+
# Multi-target, multi-control is not yet implemented.
|
| 1133 |
+
else:
|
| 1134 |
+
raise NotImplementedError(
|
| 1135 |
+
'The representation of multi-target, multi-control gates '
|
| 1136 |
+
'is not implemented.'
|
| 1137 |
+
)
|
| 1138 |
+
|
| 1139 |
+
|
| 1140 |
+
#-----------------------------------------------------------------------------
|
| 1141 |
+
# Gate manipulation functions.
|
| 1142 |
+
#-----------------------------------------------------------------------------
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
def gate_simp(circuit):
|
| 1146 |
+
"""Simplifies gates symbolically
|
| 1147 |
+
|
| 1148 |
+
It first sorts gates using gate_sort. It then applies basic
|
| 1149 |
+
simplification rules to the circuit, e.g., XGate**2 = Identity
|
| 1150 |
+
"""
|
| 1151 |
+
|
| 1152 |
+
# Bubble sort out gates that commute.
|
| 1153 |
+
circuit = gate_sort(circuit)
|
| 1154 |
+
|
| 1155 |
+
# Do simplifications by subing a simplification into the first element
|
| 1156 |
+
# which can be simplified. We recursively call gate_simp with new circuit
|
| 1157 |
+
# as input more simplifications exist.
|
| 1158 |
+
if isinstance(circuit, Add):
|
| 1159 |
+
return sum(gate_simp(t) for t in circuit.args)
|
| 1160 |
+
elif isinstance(circuit, Mul):
|
| 1161 |
+
circuit_args = circuit.args
|
| 1162 |
+
elif isinstance(circuit, Pow):
|
| 1163 |
+
b, e = circuit.as_base_exp()
|
| 1164 |
+
circuit_args = (gate_simp(b)**e,)
|
| 1165 |
+
else:
|
| 1166 |
+
return circuit
|
| 1167 |
+
|
| 1168 |
+
# Iterate through each element in circuit, simplify if possible.
|
| 1169 |
+
for i in range(len(circuit_args)):
|
| 1170 |
+
# H,X,Y or Z squared is 1.
|
| 1171 |
+
# T**2 = S, S**2 = Z
|
| 1172 |
+
if isinstance(circuit_args[i], Pow):
|
| 1173 |
+
if isinstance(circuit_args[i].base,
|
| 1174 |
+
(HadamardGate, XGate, YGate, ZGate)) \
|
| 1175 |
+
and isinstance(circuit_args[i].exp, Number):
|
| 1176 |
+
# Build a new circuit taking replacing the
|
| 1177 |
+
# H,X,Y,Z squared with one.
|
| 1178 |
+
newargs = (circuit_args[:i] +
|
| 1179 |
+
(circuit_args[i].base**(circuit_args[i].exp % 2),) +
|
| 1180 |
+
circuit_args[i + 1:])
|
| 1181 |
+
# Recursively simplify the new circuit.
|
| 1182 |
+
circuit = gate_simp(Mul(*newargs))
|
| 1183 |
+
break
|
| 1184 |
+
elif isinstance(circuit_args[i].base, PhaseGate):
|
| 1185 |
+
# Build a new circuit taking old circuit but splicing
|
| 1186 |
+
# in simplification.
|
| 1187 |
+
newargs = circuit_args[:i]
|
| 1188 |
+
# Replace PhaseGate**2 with ZGate.
|
| 1189 |
+
newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
|
| 1190 |
+
(Integer(circuit_args[i].exp/2)), circuit_args[i].base**
|
| 1191 |
+
(circuit_args[i].exp % 2))
|
| 1192 |
+
# Append the last elements.
|
| 1193 |
+
newargs = newargs + circuit_args[i + 1:]
|
| 1194 |
+
# Recursively simplify the new circuit.
|
| 1195 |
+
circuit = gate_simp(Mul(*newargs))
|
| 1196 |
+
break
|
| 1197 |
+
elif isinstance(circuit_args[i].base, TGate):
|
| 1198 |
+
# Build a new circuit taking all the old elements.
|
| 1199 |
+
newargs = circuit_args[:i]
|
| 1200 |
+
|
| 1201 |
+
# Put an Phasegate in place of any TGate**2.
|
| 1202 |
+
newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
|
| 1203 |
+
Integer(circuit_args[i].exp/2), circuit_args[i].base**
|
| 1204 |
+
(circuit_args[i].exp % 2))
|
| 1205 |
+
|
| 1206 |
+
# Append the last elements.
|
| 1207 |
+
newargs = newargs + circuit_args[i + 1:]
|
| 1208 |
+
# Recursively simplify the new circuit.
|
| 1209 |
+
circuit = gate_simp(Mul(*newargs))
|
| 1210 |
+
break
|
| 1211 |
+
return circuit
|
| 1212 |
+
|
| 1213 |
+
|
| 1214 |
+
def gate_sort(circuit):
|
| 1215 |
+
"""Sorts the gates while keeping track of commutation relations
|
| 1216 |
+
|
| 1217 |
+
This function uses a bubble sort to rearrange the order of gate
|
| 1218 |
+
application. Keeps track of Quantum computations special commutation
|
| 1219 |
+
relations (e.g. things that apply to the same Qubit do not commute with
|
| 1220 |
+
each other)
|
| 1221 |
+
|
| 1222 |
+
circuit is the Mul of gates that are to be sorted.
|
| 1223 |
+
"""
|
| 1224 |
+
# Make sure we have an Add or Mul.
|
| 1225 |
+
if isinstance(circuit, Add):
|
| 1226 |
+
return sum(gate_sort(t) for t in circuit.args)
|
| 1227 |
+
if isinstance(circuit, Pow):
|
| 1228 |
+
return gate_sort(circuit.base)**circuit.exp
|
| 1229 |
+
elif isinstance(circuit, Gate):
|
| 1230 |
+
return circuit
|
| 1231 |
+
if not isinstance(circuit, Mul):
|
| 1232 |
+
return circuit
|
| 1233 |
+
|
| 1234 |
+
changes = True
|
| 1235 |
+
while changes:
|
| 1236 |
+
changes = False
|
| 1237 |
+
circ_array = circuit.args
|
| 1238 |
+
for i in range(len(circ_array) - 1):
|
| 1239 |
+
# Go through each element and switch ones that are in wrong order
|
| 1240 |
+
if isinstance(circ_array[i], (Gate, Pow)) and \
|
| 1241 |
+
isinstance(circ_array[i + 1], (Gate, Pow)):
|
| 1242 |
+
# If we have a Pow object, look at only the base
|
| 1243 |
+
first_base, first_exp = circ_array[i].as_base_exp()
|
| 1244 |
+
second_base, second_exp = circ_array[i + 1].as_base_exp()
|
| 1245 |
+
|
| 1246 |
+
# Use SymPy's hash based sorting. This is not mathematical
|
| 1247 |
+
# sorting, but is rather based on comparing hashes of objects.
|
| 1248 |
+
# See Basic.compare for details.
|
| 1249 |
+
if first_base.compare(second_base) > 0:
|
| 1250 |
+
if Commutator(first_base, second_base).doit() == 0:
|
| 1251 |
+
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
|
| 1252 |
+
(circuit.args[i],) + circuit.args[i + 2:])
|
| 1253 |
+
circuit = Mul(*new_args)
|
| 1254 |
+
changes = True
|
| 1255 |
+
break
|
| 1256 |
+
if AntiCommutator(first_base, second_base).doit() == 0:
|
| 1257 |
+
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
|
| 1258 |
+
(circuit.args[i],) + circuit.args[i + 2:])
|
| 1259 |
+
sign = _S.NegativeOne**(first_exp*second_exp)
|
| 1260 |
+
circuit = sign*Mul(*new_args)
|
| 1261 |
+
changes = True
|
| 1262 |
+
break
|
| 1263 |
+
return circuit
|
| 1264 |
+
|
| 1265 |
+
|
| 1266 |
+
#-----------------------------------------------------------------------------
|
| 1267 |
+
# Utility functions
|
| 1268 |
+
#-----------------------------------------------------------------------------
|
| 1269 |
+
|
| 1270 |
+
|
| 1271 |
+
def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
|
| 1272 |
+
"""Return a random circuit of ngates and nqubits.
|
| 1273 |
+
|
| 1274 |
+
This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
|
| 1275 |
+
gates.
|
| 1276 |
+
|
| 1277 |
+
Parameters
|
| 1278 |
+
----------
|
| 1279 |
+
ngates : int
|
| 1280 |
+
The number of gates in the circuit.
|
| 1281 |
+
nqubits : int
|
| 1282 |
+
The number of qubits in the circuit.
|
| 1283 |
+
gate_space : tuple
|
| 1284 |
+
A tuple of the gate classes that will be used in the circuit.
|
| 1285 |
+
Repeating gate classes multiple times in this tuple will increase
|
| 1286 |
+
the frequency they appear in the random circuit.
|
| 1287 |
+
"""
|
| 1288 |
+
qubit_space = range(nqubits)
|
| 1289 |
+
result = []
|
| 1290 |
+
for i in range(ngates):
|
| 1291 |
+
g = random.choice(gate_space)
|
| 1292 |
+
if g == CNotGate or g == SwapGate:
|
| 1293 |
+
qubits = random.sample(qubit_space, 2)
|
| 1294 |
+
g = g(*qubits)
|
| 1295 |
+
else:
|
| 1296 |
+
qubit = random.choice(qubit_space)
|
| 1297 |
+
g = g(qubit)
|
| 1298 |
+
result.append(g)
|
| 1299 |
+
return Mul(*result)
|
| 1300 |
+
|
| 1301 |
+
|
| 1302 |
+
def zx_basis_transform(self, format='sympy'):
|
| 1303 |
+
"""Transformation matrix from Z to X basis."""
|
| 1304 |
+
return matrix_cache.get_matrix('ZX', format)
|
| 1305 |
+
|
| 1306 |
+
|
| 1307 |
+
def zy_basis_transform(self, format='sympy'):
|
| 1308 |
+
"""Transformation matrix from Z to Y basis."""
|
| 1309 |
+
return matrix_cache.get_matrix('ZY', format)
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/grover.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grover's algorithm and helper functions.
|
| 2 |
+
|
| 3 |
+
Todo:
|
| 4 |
+
|
| 5 |
+
* W gate construction (or perhaps -W gate based on Mermin's book)
|
| 6 |
+
* Generalize the algorithm for an unknown function that returns 1 on multiple
|
| 7 |
+
qubit states, not just one.
|
| 8 |
+
* Implement _represent_ZGate in OracleGate
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from sympy.core.numbers import pi
|
| 12 |
+
from sympy.core.sympify import sympify
|
| 13 |
+
from sympy.core.basic import Atom
|
| 14 |
+
from sympy.functions.elementary.integers import floor
|
| 15 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 16 |
+
from sympy.matrices.dense import eye
|
| 17 |
+
from sympy.core.numbers import NegativeOne
|
| 18 |
+
from sympy.physics.quantum.qapply import qapply
|
| 19 |
+
from sympy.physics.quantum.qexpr import QuantumError
|
| 20 |
+
from sympy.physics.quantum.hilbert import ComplexSpace
|
| 21 |
+
from sympy.physics.quantum.operator import UnitaryOperator
|
| 22 |
+
from sympy.physics.quantum.gate import Gate
|
| 23 |
+
from sympy.physics.quantum.qubit import IntQubit
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
'OracleGate',
|
| 27 |
+
'WGate',
|
| 28 |
+
'superposition_basis',
|
| 29 |
+
'grover_iteration',
|
| 30 |
+
'apply_grover'
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def superposition_basis(nqubits):
|
| 35 |
+
"""Creates an equal superposition of the computational basis.
|
| 36 |
+
|
| 37 |
+
Parameters
|
| 38 |
+
==========
|
| 39 |
+
|
| 40 |
+
nqubits : int
|
| 41 |
+
The number of qubits.
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
=======
|
| 45 |
+
|
| 46 |
+
state : Qubit
|
| 47 |
+
An equal superposition of the computational basis with nqubits.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
========
|
| 51 |
+
|
| 52 |
+
Create an equal superposition of 2 qubits::
|
| 53 |
+
|
| 54 |
+
>>> from sympy.physics.quantum.grover import superposition_basis
|
| 55 |
+
>>> superposition_basis(2)
|
| 56 |
+
|0>/2 + |1>/2 + |2>/2 + |3>/2
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
amp = 1/sqrt(2**nqubits)
|
| 60 |
+
return sum(amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits))
|
| 61 |
+
|
| 62 |
+
class OracleGateFunction(Atom):
|
| 63 |
+
"""Wrapper for python functions used in `OracleGate`s"""
|
| 64 |
+
|
| 65 |
+
def __new__(cls, function):
|
| 66 |
+
if not callable(function):
|
| 67 |
+
raise TypeError('Callable expected, got: %r' % function)
|
| 68 |
+
obj = Atom.__new__(cls)
|
| 69 |
+
obj.function = function
|
| 70 |
+
return obj
|
| 71 |
+
|
| 72 |
+
def _hashable_content(self):
|
| 73 |
+
return type(self), self.function
|
| 74 |
+
|
| 75 |
+
def __call__(self, *args):
|
| 76 |
+
return self.function(*args)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class OracleGate(Gate):
|
| 80 |
+
"""A black box gate.
|
| 81 |
+
|
| 82 |
+
The gate marks the desired qubits of an unknown function by flipping
|
| 83 |
+
the sign of the qubits. The unknown function returns true when it
|
| 84 |
+
finds its desired qubits and false otherwise.
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
==========
|
| 88 |
+
|
| 89 |
+
qubits : int
|
| 90 |
+
Number of qubits.
|
| 91 |
+
|
| 92 |
+
oracle : callable
|
| 93 |
+
A callable function that returns a boolean on a computational basis.
|
| 94 |
+
|
| 95 |
+
Examples
|
| 96 |
+
========
|
| 97 |
+
|
| 98 |
+
Apply an Oracle gate that flips the sign of ``|2>`` on different qubits::
|
| 99 |
+
|
| 100 |
+
>>> from sympy.physics.quantum.qubit import IntQubit
|
| 101 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
| 102 |
+
>>> from sympy.physics.quantum.grover import OracleGate
|
| 103 |
+
>>> f = lambda qubits: qubits == IntQubit(2)
|
| 104 |
+
>>> v = OracleGate(2, f)
|
| 105 |
+
>>> qapply(v*IntQubit(2))
|
| 106 |
+
-|2>
|
| 107 |
+
>>> qapply(v*IntQubit(3))
|
| 108 |
+
|3>
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
gate_name = 'V'
|
| 112 |
+
gate_name_latex = 'V'
|
| 113 |
+
|
| 114 |
+
#-------------------------------------------------------------------------
|
| 115 |
+
# Initialization/creation
|
| 116 |
+
#-------------------------------------------------------------------------
|
| 117 |
+
|
| 118 |
+
@classmethod
|
| 119 |
+
def _eval_args(cls, args):
|
| 120 |
+
if len(args) != 2:
|
| 121 |
+
raise QuantumError(
|
| 122 |
+
'Insufficient/excessive arguments to Oracle. Please ' +
|
| 123 |
+
'supply the number of qubits and an unknown function.'
|
| 124 |
+
)
|
| 125 |
+
sub_args = (args[0],)
|
| 126 |
+
sub_args = UnitaryOperator._eval_args(sub_args)
|
| 127 |
+
if not sub_args[0].is_Integer:
|
| 128 |
+
raise TypeError('Integer expected, got: %r' % sub_args[0])
|
| 129 |
+
|
| 130 |
+
function = args[1]
|
| 131 |
+
if not isinstance(function, OracleGateFunction):
|
| 132 |
+
function = OracleGateFunction(function)
|
| 133 |
+
|
| 134 |
+
return (sub_args[0], function)
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def _eval_hilbert_space(cls, args):
|
| 138 |
+
"""This returns the smallest possible Hilbert space."""
|
| 139 |
+
return ComplexSpace(2)**args[0]
|
| 140 |
+
|
| 141 |
+
#-------------------------------------------------------------------------
|
| 142 |
+
# Properties
|
| 143 |
+
#-------------------------------------------------------------------------
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def search_function(self):
|
| 147 |
+
"""The unknown function that helps find the sought after qubits."""
|
| 148 |
+
return self.label[1]
|
| 149 |
+
|
| 150 |
+
@property
|
| 151 |
+
def targets(self):
|
| 152 |
+
"""A tuple of target qubits."""
|
| 153 |
+
return sympify(tuple(range(self.args[0])))
|
| 154 |
+
|
| 155 |
+
#-------------------------------------------------------------------------
|
| 156 |
+
# Apply
|
| 157 |
+
#-------------------------------------------------------------------------
|
| 158 |
+
|
| 159 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
| 160 |
+
"""Apply this operator to a Qubit subclass.
|
| 161 |
+
|
| 162 |
+
Parameters
|
| 163 |
+
==========
|
| 164 |
+
|
| 165 |
+
qubits : Qubit
|
| 166 |
+
The qubit subclass to apply this operator to.
|
| 167 |
+
|
| 168 |
+
Returns
|
| 169 |
+
=======
|
| 170 |
+
|
| 171 |
+
state : Expr
|
| 172 |
+
The resulting quantum state.
|
| 173 |
+
"""
|
| 174 |
+
if qubits.nqubits != self.nqubits:
|
| 175 |
+
raise QuantumError(
|
| 176 |
+
'OracleGate operates on %r qubits, got: %r'
|
| 177 |
+
% (self.nqubits, qubits.nqubits)
|
| 178 |
+
)
|
| 179 |
+
# If function returns 1 on qubits
|
| 180 |
+
# return the negative of the qubits (flip the sign)
|
| 181 |
+
if self.search_function(qubits):
|
| 182 |
+
return -qubits
|
| 183 |
+
else:
|
| 184 |
+
return qubits
|
| 185 |
+
|
| 186 |
+
#-------------------------------------------------------------------------
|
| 187 |
+
# Represent
|
| 188 |
+
#-------------------------------------------------------------------------
|
| 189 |
+
|
| 190 |
+
def _represent_ZGate(self, basis, **options):
|
| 191 |
+
"""
|
| 192 |
+
Represent the OracleGate in the computational basis.
|
| 193 |
+
"""
|
| 194 |
+
nbasis = 2**self.nqubits # compute it only once
|
| 195 |
+
matrixOracle = eye(nbasis)
|
| 196 |
+
# Flip the sign given the output of the oracle function
|
| 197 |
+
for i in range(nbasis):
|
| 198 |
+
if self.search_function(IntQubit(i, nqubits=self.nqubits)):
|
| 199 |
+
matrixOracle[i, i] = NegativeOne()
|
| 200 |
+
return matrixOracle
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class WGate(Gate):
|
| 204 |
+
"""General n qubit W Gate in Grover's algorithm.
|
| 205 |
+
|
| 206 |
+
The gate performs the operation ``2|phi><phi| - 1`` on some qubits.
|
| 207 |
+
``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)``
|
| 208 |
+
|
| 209 |
+
Parameters
|
| 210 |
+
==========
|
| 211 |
+
|
| 212 |
+
nqubits : int
|
| 213 |
+
The number of qubits to operate on
|
| 214 |
+
|
| 215 |
+
"""
|
| 216 |
+
|
| 217 |
+
gate_name = 'W'
|
| 218 |
+
gate_name_latex = 'W'
|
| 219 |
+
|
| 220 |
+
@classmethod
|
| 221 |
+
def _eval_args(cls, args):
|
| 222 |
+
if len(args) != 1:
|
| 223 |
+
raise QuantumError(
|
| 224 |
+
'Insufficient/excessive arguments to W gate. Please ' +
|
| 225 |
+
'supply the number of qubits to operate on.'
|
| 226 |
+
)
|
| 227 |
+
args = UnitaryOperator._eval_args(args)
|
| 228 |
+
if not args[0].is_Integer:
|
| 229 |
+
raise TypeError('Integer expected, got: %r' % args[0])
|
| 230 |
+
return args
|
| 231 |
+
|
| 232 |
+
#-------------------------------------------------------------------------
|
| 233 |
+
# Properties
|
| 234 |
+
#-------------------------------------------------------------------------
|
| 235 |
+
|
| 236 |
+
@property
|
| 237 |
+
def targets(self):
|
| 238 |
+
return sympify(tuple(reversed(range(self.args[0]))))
|
| 239 |
+
|
| 240 |
+
#-------------------------------------------------------------------------
|
| 241 |
+
# Apply
|
| 242 |
+
#-------------------------------------------------------------------------
|
| 243 |
+
|
| 244 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
| 245 |
+
"""
|
| 246 |
+
qubits: a set of qubits (Qubit)
|
| 247 |
+
Returns: quantum object (quantum expression - QExpr)
|
| 248 |
+
"""
|
| 249 |
+
if qubits.nqubits != self.nqubits:
|
| 250 |
+
raise QuantumError(
|
| 251 |
+
'WGate operates on %r qubits, got: %r'
|
| 252 |
+
% (self.nqubits, qubits.nqubits)
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result
|
| 256 |
+
# Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis
|
| 257 |
+
# state and phi is the superposition of basis states (see function
|
| 258 |
+
# create_computational_basis above)
|
| 259 |
+
basis_states = superposition_basis(self.nqubits)
|
| 260 |
+
change_to_basis = (2/sqrt(2**self.nqubits))*basis_states
|
| 261 |
+
return change_to_basis - qubits
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def grover_iteration(qstate, oracle):
|
| 265 |
+
"""Applies one application of the Oracle and W Gate, WV.
|
| 266 |
+
|
| 267 |
+
Parameters
|
| 268 |
+
==========
|
| 269 |
+
|
| 270 |
+
qstate : Qubit
|
| 271 |
+
A superposition of qubits.
|
| 272 |
+
oracle : OracleGate
|
| 273 |
+
The black box operator that flips the sign of the desired basis qubits.
|
| 274 |
+
|
| 275 |
+
Returns
|
| 276 |
+
=======
|
| 277 |
+
|
| 278 |
+
Qubit : The qubits after applying the Oracle and W gate.
|
| 279 |
+
|
| 280 |
+
Examples
|
| 281 |
+
========
|
| 282 |
+
|
| 283 |
+
Perform one iteration of grover's algorithm to see a phase change::
|
| 284 |
+
|
| 285 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
| 286 |
+
>>> from sympy.physics.quantum.qubit import IntQubit
|
| 287 |
+
>>> from sympy.physics.quantum.grover import OracleGate
|
| 288 |
+
>>> from sympy.physics.quantum.grover import superposition_basis
|
| 289 |
+
>>> from sympy.physics.quantum.grover import grover_iteration
|
| 290 |
+
>>> numqubits = 2
|
| 291 |
+
>>> basis_states = superposition_basis(numqubits)
|
| 292 |
+
>>> f = lambda qubits: qubits == IntQubit(2)
|
| 293 |
+
>>> v = OracleGate(numqubits, f)
|
| 294 |
+
>>> qapply(grover_iteration(basis_states, v))
|
| 295 |
+
|2>
|
| 296 |
+
|
| 297 |
+
"""
|
| 298 |
+
wgate = WGate(oracle.nqubits)
|
| 299 |
+
return wgate*oracle*qstate
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def apply_grover(oracle, nqubits, iterations=None):
|
| 303 |
+
"""Applies grover's algorithm.
|
| 304 |
+
|
| 305 |
+
Parameters
|
| 306 |
+
==========
|
| 307 |
+
|
| 308 |
+
oracle : callable
|
| 309 |
+
The unknown callable function that returns true when applied to the
|
| 310 |
+
desired qubits and false otherwise.
|
| 311 |
+
|
| 312 |
+
Returns
|
| 313 |
+
=======
|
| 314 |
+
|
| 315 |
+
state : Expr
|
| 316 |
+
The resulting state after Grover's algorithm has been iterated.
|
| 317 |
+
|
| 318 |
+
Examples
|
| 319 |
+
========
|
| 320 |
+
|
| 321 |
+
Apply grover's algorithm to an even superposition of 2 qubits::
|
| 322 |
+
|
| 323 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
| 324 |
+
>>> from sympy.physics.quantum.qubit import IntQubit
|
| 325 |
+
>>> from sympy.physics.quantum.grover import apply_grover
|
| 326 |
+
>>> f = lambda qubits: qubits == IntQubit(2)
|
| 327 |
+
>>> qapply(apply_grover(f, 2))
|
| 328 |
+
|2>
|
| 329 |
+
|
| 330 |
+
"""
|
| 331 |
+
if nqubits <= 0:
|
| 332 |
+
raise QuantumError(
|
| 333 |
+
'Grover\'s algorithm needs nqubits > 0, received %r qubits'
|
| 334 |
+
% nqubits
|
| 335 |
+
)
|
| 336 |
+
if iterations is None:
|
| 337 |
+
iterations = floor(sqrt(2**nqubits)*(pi/4))
|
| 338 |
+
|
| 339 |
+
v = OracleGate(nqubits, oracle)
|
| 340 |
+
iterated = superposition_basis(nqubits)
|
| 341 |
+
for iter in range(iterations):
|
| 342 |
+
iterated = grover_iteration(iterated, v)
|
| 343 |
+
iterated = qapply(iterated)
|
| 344 |
+
|
| 345 |
+
return iterated
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hilbert spaces for quantum mechanics.
|
| 2 |
+
|
| 3 |
+
Authors:
|
| 4 |
+
* Brian Granger
|
| 5 |
+
* Matt Curry
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from functools import reduce
|
| 9 |
+
|
| 10 |
+
from sympy.core.basic import Basic
|
| 11 |
+
from sympy.core.singleton import S
|
| 12 |
+
from sympy.core.sympify import sympify
|
| 13 |
+
from sympy.sets.sets import Interval
|
| 14 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
| 15 |
+
from sympy.physics.quantum.qexpr import QuantumError
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
'HilbertSpaceError',
|
| 20 |
+
'HilbertSpace',
|
| 21 |
+
'TensorProductHilbertSpace',
|
| 22 |
+
'TensorPowerHilbertSpace',
|
| 23 |
+
'DirectSumHilbertSpace',
|
| 24 |
+
'ComplexSpace',
|
| 25 |
+
'L2',
|
| 26 |
+
'FockSpace'
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
#-----------------------------------------------------------------------------
|
| 30 |
+
# Main objects
|
| 31 |
+
#-----------------------------------------------------------------------------
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class HilbertSpaceError(QuantumError):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
#-----------------------------------------------------------------------------
|
| 38 |
+
# Main objects
|
| 39 |
+
#-----------------------------------------------------------------------------
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class HilbertSpace(Basic):
|
| 43 |
+
"""An abstract Hilbert space for quantum mechanics.
|
| 44 |
+
|
| 45 |
+
In short, a Hilbert space is an abstract vector space that is complete
|
| 46 |
+
with inner products defined [1]_.
|
| 47 |
+
|
| 48 |
+
Examples
|
| 49 |
+
========
|
| 50 |
+
|
| 51 |
+
>>> from sympy.physics.quantum.hilbert import HilbertSpace
|
| 52 |
+
>>> hs = HilbertSpace()
|
| 53 |
+
>>> hs
|
| 54 |
+
H
|
| 55 |
+
|
| 56 |
+
References
|
| 57 |
+
==========
|
| 58 |
+
|
| 59 |
+
.. [1] https://en.wikipedia.org/wiki/Hilbert_space
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __new__(cls):
|
| 63 |
+
obj = Basic.__new__(cls)
|
| 64 |
+
return obj
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
def dimension(self):
|
| 68 |
+
"""Return the Hilbert dimension of the space."""
|
| 69 |
+
raise NotImplementedError('This Hilbert space has no dimension.')
|
| 70 |
+
|
| 71 |
+
def __add__(self, other):
|
| 72 |
+
return DirectSumHilbertSpace(self, other)
|
| 73 |
+
|
| 74 |
+
def __radd__(self, other):
|
| 75 |
+
return DirectSumHilbertSpace(other, self)
|
| 76 |
+
|
| 77 |
+
def __mul__(self, other):
|
| 78 |
+
return TensorProductHilbertSpace(self, other)
|
| 79 |
+
|
| 80 |
+
def __rmul__(self, other):
|
| 81 |
+
return TensorProductHilbertSpace(other, self)
|
| 82 |
+
|
| 83 |
+
def __pow__(self, other, mod=None):
|
| 84 |
+
if mod is not None:
|
| 85 |
+
raise ValueError('The third argument to __pow__ is not supported \
|
| 86 |
+
for Hilbert spaces.')
|
| 87 |
+
return TensorPowerHilbertSpace(self, other)
|
| 88 |
+
|
| 89 |
+
def __contains__(self, other):
|
| 90 |
+
"""Is the operator or state in this Hilbert space.
|
| 91 |
+
|
| 92 |
+
This is checked by comparing the classes of the Hilbert spaces, not
|
| 93 |
+
the instances. This is to allow Hilbert Spaces with symbolic
|
| 94 |
+
dimensions.
|
| 95 |
+
"""
|
| 96 |
+
if other.hilbert_space.__class__ == self.__class__:
|
| 97 |
+
return True
|
| 98 |
+
else:
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
def _sympystr(self, printer, *args):
|
| 102 |
+
return 'H'
|
| 103 |
+
|
| 104 |
+
def _pretty(self, printer, *args):
|
| 105 |
+
ustr = '\N{LATIN CAPITAL LETTER H}'
|
| 106 |
+
return prettyForm(ustr)
|
| 107 |
+
|
| 108 |
+
def _latex(self, printer, *args):
|
| 109 |
+
return r'\mathcal{H}'
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class ComplexSpace(HilbertSpace):
|
| 113 |
+
"""Finite dimensional Hilbert space of complex vectors.
|
| 114 |
+
|
| 115 |
+
The elements of this Hilbert space are n-dimensional complex valued
|
| 116 |
+
vectors with the usual inner product that takes the complex conjugate
|
| 117 |
+
of the vector on the right.
|
| 118 |
+
|
| 119 |
+
A classic example of this type of Hilbert space is spin-1/2, which is
|
| 120 |
+
``ComplexSpace(2)``. Generalizing to spin-s, the space is
|
| 121 |
+
``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the
|
| 122 |
+
direct product space ``ComplexSpace(2)**N``.
|
| 123 |
+
|
| 124 |
+
Examples
|
| 125 |
+
========
|
| 126 |
+
|
| 127 |
+
>>> from sympy import symbols
|
| 128 |
+
>>> from sympy.physics.quantum.hilbert import ComplexSpace
|
| 129 |
+
>>> c1 = ComplexSpace(2)
|
| 130 |
+
>>> c1
|
| 131 |
+
C(2)
|
| 132 |
+
>>> c1.dimension
|
| 133 |
+
2
|
| 134 |
+
|
| 135 |
+
>>> n = symbols('n')
|
| 136 |
+
>>> c2 = ComplexSpace(n)
|
| 137 |
+
>>> c2
|
| 138 |
+
C(n)
|
| 139 |
+
>>> c2.dimension
|
| 140 |
+
n
|
| 141 |
+
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
def __new__(cls, dimension):
|
| 145 |
+
dimension = sympify(dimension)
|
| 146 |
+
r = cls.eval(dimension)
|
| 147 |
+
if isinstance(r, Basic):
|
| 148 |
+
return r
|
| 149 |
+
obj = Basic.__new__(cls, dimension)
|
| 150 |
+
return obj
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def eval(cls, dimension):
|
| 154 |
+
if len(dimension.atoms()) == 1:
|
| 155 |
+
if not (dimension.is_Integer and dimension > 0 or dimension is S.Infinity
|
| 156 |
+
or dimension.is_Symbol):
|
| 157 |
+
raise TypeError('The dimension of a ComplexSpace can only'
|
| 158 |
+
'be a positive integer, oo, or a Symbol: %r'
|
| 159 |
+
% dimension)
|
| 160 |
+
else:
|
| 161 |
+
for dim in dimension.atoms():
|
| 162 |
+
if not (dim.is_Integer or dim is S.Infinity or dim.is_Symbol):
|
| 163 |
+
raise TypeError('The dimension of a ComplexSpace can only'
|
| 164 |
+
' contain integers, oo, or a Symbol: %r'
|
| 165 |
+
% dim)
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def dimension(self):
|
| 169 |
+
return self.args[0]
|
| 170 |
+
|
| 171 |
+
def _sympyrepr(self, printer, *args):
|
| 172 |
+
return "%s(%s)" % (self.__class__.__name__,
|
| 173 |
+
printer._print(self.dimension, *args))
|
| 174 |
+
|
| 175 |
+
def _sympystr(self, printer, *args):
|
| 176 |
+
return "C(%s)" % printer._print(self.dimension, *args)
|
| 177 |
+
|
| 178 |
+
def _pretty(self, printer, *args):
|
| 179 |
+
ustr = '\N{LATIN CAPITAL LETTER C}'
|
| 180 |
+
pform_exp = printer._print(self.dimension, *args)
|
| 181 |
+
pform_base = prettyForm(ustr)
|
| 182 |
+
return pform_base**pform_exp
|
| 183 |
+
|
| 184 |
+
def _latex(self, printer, *args):
|
| 185 |
+
return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class L2(HilbertSpace):
|
| 189 |
+
"""The Hilbert space of square integrable functions on an interval.
|
| 190 |
+
|
| 191 |
+
An L2 object takes in a single SymPy Interval argument which represents
|
| 192 |
+
the interval its functions (vectors) are defined on.
|
| 193 |
+
|
| 194 |
+
Examples
|
| 195 |
+
========
|
| 196 |
+
|
| 197 |
+
>>> from sympy import Interval, oo
|
| 198 |
+
>>> from sympy.physics.quantum.hilbert import L2
|
| 199 |
+
>>> hs = L2(Interval(0,oo))
|
| 200 |
+
>>> hs
|
| 201 |
+
L2(Interval(0, oo))
|
| 202 |
+
>>> hs.dimension
|
| 203 |
+
oo
|
| 204 |
+
>>> hs.interval
|
| 205 |
+
Interval(0, oo)
|
| 206 |
+
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
def __new__(cls, interval):
|
| 210 |
+
if not isinstance(interval, Interval):
|
| 211 |
+
raise TypeError('L2 interval must be an Interval instance: %r'
|
| 212 |
+
% interval)
|
| 213 |
+
obj = Basic.__new__(cls, interval)
|
| 214 |
+
return obj
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def dimension(self):
|
| 218 |
+
return S.Infinity
|
| 219 |
+
|
| 220 |
+
@property
|
| 221 |
+
def interval(self):
|
| 222 |
+
return self.args[0]
|
| 223 |
+
|
| 224 |
+
def _sympyrepr(self, printer, *args):
|
| 225 |
+
return "L2(%s)" % printer._print(self.interval, *args)
|
| 226 |
+
|
| 227 |
+
def _sympystr(self, printer, *args):
|
| 228 |
+
return "L2(%s)" % printer._print(self.interval, *args)
|
| 229 |
+
|
| 230 |
+
def _pretty(self, printer, *args):
|
| 231 |
+
pform_exp = prettyForm('2')
|
| 232 |
+
pform_base = prettyForm('L')
|
| 233 |
+
return pform_base**pform_exp
|
| 234 |
+
|
| 235 |
+
def _latex(self, printer, *args):
|
| 236 |
+
interval = printer._print(self.interval, *args)
|
| 237 |
+
return r'{\mathcal{L}^2}\left( %s \right)' % interval
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class FockSpace(HilbertSpace):
|
| 241 |
+
"""The Hilbert space for second quantization.
|
| 242 |
+
|
| 243 |
+
Technically, this Hilbert space is a infinite direct sum of direct
|
| 244 |
+
products of single particle Hilbert spaces [1]_. This is a mess, so we have
|
| 245 |
+
a class to represent it directly.
|
| 246 |
+
|
| 247 |
+
Examples
|
| 248 |
+
========
|
| 249 |
+
|
| 250 |
+
>>> from sympy.physics.quantum.hilbert import FockSpace
|
| 251 |
+
>>> hs = FockSpace()
|
| 252 |
+
>>> hs
|
| 253 |
+
F
|
| 254 |
+
>>> hs.dimension
|
| 255 |
+
oo
|
| 256 |
+
|
| 257 |
+
References
|
| 258 |
+
==========
|
| 259 |
+
|
| 260 |
+
.. [1] https://en.wikipedia.org/wiki/Fock_space
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
def __new__(cls):
|
| 264 |
+
obj = Basic.__new__(cls)
|
| 265 |
+
return obj
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def dimension(self):
|
| 269 |
+
return S.Infinity
|
| 270 |
+
|
| 271 |
+
def _sympyrepr(self, printer, *args):
|
| 272 |
+
return "FockSpace()"
|
| 273 |
+
|
| 274 |
+
def _sympystr(self, printer, *args):
|
| 275 |
+
return "F"
|
| 276 |
+
|
| 277 |
+
def _pretty(self, printer, *args):
|
| 278 |
+
ustr = '\N{LATIN CAPITAL LETTER F}'
|
| 279 |
+
return prettyForm(ustr)
|
| 280 |
+
|
| 281 |
+
def _latex(self, printer, *args):
|
| 282 |
+
return r'\mathcal{F}'
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class TensorProductHilbertSpace(HilbertSpace):
|
| 286 |
+
"""A tensor product of Hilbert spaces [1]_.
|
| 287 |
+
|
| 288 |
+
The tensor product between Hilbert spaces is represented by the
|
| 289 |
+
operator ``*`` Products of the same Hilbert space will be combined into
|
| 290 |
+
tensor powers.
|
| 291 |
+
|
| 292 |
+
A ``TensorProductHilbertSpace`` object takes in an arbitrary number of
|
| 293 |
+
``HilbertSpace`` objects as its arguments. In addition, multiplication of
|
| 294 |
+
``HilbertSpace`` objects will automatically return this tensor product
|
| 295 |
+
object.
|
| 296 |
+
|
| 297 |
+
Examples
|
| 298 |
+
========
|
| 299 |
+
|
| 300 |
+
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
|
| 301 |
+
>>> from sympy import symbols
|
| 302 |
+
|
| 303 |
+
>>> c = ComplexSpace(2)
|
| 304 |
+
>>> f = FockSpace()
|
| 305 |
+
>>> hs = c*f
|
| 306 |
+
>>> hs
|
| 307 |
+
C(2)*F
|
| 308 |
+
>>> hs.dimension
|
| 309 |
+
oo
|
| 310 |
+
>>> hs.spaces
|
| 311 |
+
(C(2), F)
|
| 312 |
+
|
| 313 |
+
>>> c1 = ComplexSpace(2)
|
| 314 |
+
>>> n = symbols('n')
|
| 315 |
+
>>> c2 = ComplexSpace(n)
|
| 316 |
+
>>> hs = c1*c2
|
| 317 |
+
>>> hs
|
| 318 |
+
C(2)*C(n)
|
| 319 |
+
>>> hs.dimension
|
| 320 |
+
2*n
|
| 321 |
+
|
| 322 |
+
References
|
| 323 |
+
==========
|
| 324 |
+
|
| 325 |
+
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
|
| 326 |
+
"""
|
| 327 |
+
|
| 328 |
+
def __new__(cls, *args):
|
| 329 |
+
r = cls.eval(args)
|
| 330 |
+
if isinstance(r, Basic):
|
| 331 |
+
return r
|
| 332 |
+
obj = Basic.__new__(cls, *args)
|
| 333 |
+
return obj
|
| 334 |
+
|
| 335 |
+
@classmethod
|
| 336 |
+
def eval(cls, args):
|
| 337 |
+
"""Evaluates the direct product."""
|
| 338 |
+
new_args = []
|
| 339 |
+
recall = False
|
| 340 |
+
#flatten arguments
|
| 341 |
+
for arg in args:
|
| 342 |
+
if isinstance(arg, TensorProductHilbertSpace):
|
| 343 |
+
new_args.extend(arg.args)
|
| 344 |
+
recall = True
|
| 345 |
+
elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)):
|
| 346 |
+
new_args.append(arg)
|
| 347 |
+
else:
|
| 348 |
+
raise TypeError('Hilbert spaces can only be multiplied by \
|
| 349 |
+
other Hilbert spaces: %r' % arg)
|
| 350 |
+
#combine like arguments into direct powers
|
| 351 |
+
comb_args = []
|
| 352 |
+
prev_arg = None
|
| 353 |
+
for new_arg in new_args:
|
| 354 |
+
if prev_arg is not None:
|
| 355 |
+
if isinstance(new_arg, TensorPowerHilbertSpace) and \
|
| 356 |
+
isinstance(prev_arg, TensorPowerHilbertSpace) and \
|
| 357 |
+
new_arg.base == prev_arg.base:
|
| 358 |
+
prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp)
|
| 359 |
+
elif isinstance(new_arg, TensorPowerHilbertSpace) and \
|
| 360 |
+
new_arg.base == prev_arg:
|
| 361 |
+
prev_arg = prev_arg**(new_arg.exp + 1)
|
| 362 |
+
elif isinstance(prev_arg, TensorPowerHilbertSpace) and \
|
| 363 |
+
new_arg == prev_arg.base:
|
| 364 |
+
prev_arg = new_arg**(prev_arg.exp + 1)
|
| 365 |
+
elif new_arg == prev_arg:
|
| 366 |
+
prev_arg = new_arg**2
|
| 367 |
+
else:
|
| 368 |
+
comb_args.append(prev_arg)
|
| 369 |
+
prev_arg = new_arg
|
| 370 |
+
elif prev_arg is None:
|
| 371 |
+
prev_arg = new_arg
|
| 372 |
+
comb_args.append(prev_arg)
|
| 373 |
+
if recall:
|
| 374 |
+
return TensorProductHilbertSpace(*comb_args)
|
| 375 |
+
elif len(comb_args) == 1:
|
| 376 |
+
return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp)
|
| 377 |
+
else:
|
| 378 |
+
return None
|
| 379 |
+
|
| 380 |
+
@property
|
| 381 |
+
def dimension(self):
|
| 382 |
+
arg_list = [arg.dimension for arg in self.args]
|
| 383 |
+
if S.Infinity in arg_list:
|
| 384 |
+
return S.Infinity
|
| 385 |
+
else:
|
| 386 |
+
return reduce(lambda x, y: x*y, arg_list)
|
| 387 |
+
|
| 388 |
+
@property
|
| 389 |
+
def spaces(self):
|
| 390 |
+
"""A tuple of the Hilbert spaces in this tensor product."""
|
| 391 |
+
return self.args
|
| 392 |
+
|
| 393 |
+
def _spaces_printer(self, printer, *args):
|
| 394 |
+
spaces_strs = []
|
| 395 |
+
for arg in self.args:
|
| 396 |
+
s = printer._print(arg, *args)
|
| 397 |
+
if isinstance(arg, DirectSumHilbertSpace):
|
| 398 |
+
s = '(%s)' % s
|
| 399 |
+
spaces_strs.append(s)
|
| 400 |
+
return spaces_strs
|
| 401 |
+
|
| 402 |
+
def _sympyrepr(self, printer, *args):
|
| 403 |
+
spaces_reprs = self._spaces_printer(printer, *args)
|
| 404 |
+
return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs)
|
| 405 |
+
|
| 406 |
+
def _sympystr(self, printer, *args):
|
| 407 |
+
spaces_strs = self._spaces_printer(printer, *args)
|
| 408 |
+
return '*'.join(spaces_strs)
|
| 409 |
+
|
| 410 |
+
def _pretty(self, printer, *args):
|
| 411 |
+
length = len(self.args)
|
| 412 |
+
pform = printer._print('', *args)
|
| 413 |
+
for i in range(length):
|
| 414 |
+
next_pform = printer._print(self.args[i], *args)
|
| 415 |
+
if isinstance(self.args[i], (DirectSumHilbertSpace,
|
| 416 |
+
TensorProductHilbertSpace)):
|
| 417 |
+
next_pform = prettyForm(
|
| 418 |
+
*next_pform.parens(left='(', right=')')
|
| 419 |
+
)
|
| 420 |
+
pform = prettyForm(*pform.right(next_pform))
|
| 421 |
+
if i != length - 1:
|
| 422 |
+
if printer._use_unicode:
|
| 423 |
+
pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
|
| 424 |
+
else:
|
| 425 |
+
pform = prettyForm(*pform.right(' x '))
|
| 426 |
+
return pform
|
| 427 |
+
|
| 428 |
+
def _latex(self, printer, *args):
|
| 429 |
+
length = len(self.args)
|
| 430 |
+
s = ''
|
| 431 |
+
for i in range(length):
|
| 432 |
+
arg_s = printer._print(self.args[i], *args)
|
| 433 |
+
if isinstance(self.args[i], (DirectSumHilbertSpace,
|
| 434 |
+
TensorProductHilbertSpace)):
|
| 435 |
+
arg_s = r'\left(%s\right)' % arg_s
|
| 436 |
+
s = s + arg_s
|
| 437 |
+
if i != length - 1:
|
| 438 |
+
s = s + r'\otimes '
|
| 439 |
+
return s
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class DirectSumHilbertSpace(HilbertSpace):
|
| 443 |
+
"""A direct sum of Hilbert spaces [1]_.
|
| 444 |
+
|
| 445 |
+
This class uses the ``+`` operator to represent direct sums between
|
| 446 |
+
different Hilbert spaces.
|
| 447 |
+
|
| 448 |
+
A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
|
| 449 |
+
``HilbertSpace`` objects as its arguments. Also, addition of
|
| 450 |
+
``HilbertSpace`` objects will automatically return a direct sum object.
|
| 451 |
+
|
| 452 |
+
Examples
|
| 453 |
+
========
|
| 454 |
+
|
| 455 |
+
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
|
| 456 |
+
|
| 457 |
+
>>> c = ComplexSpace(2)
|
| 458 |
+
>>> f = FockSpace()
|
| 459 |
+
>>> hs = c+f
|
| 460 |
+
>>> hs
|
| 461 |
+
C(2)+F
|
| 462 |
+
>>> hs.dimension
|
| 463 |
+
oo
|
| 464 |
+
>>> list(hs.spaces)
|
| 465 |
+
[C(2), F]
|
| 466 |
+
|
| 467 |
+
References
|
| 468 |
+
==========
|
| 469 |
+
|
| 470 |
+
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums
|
| 471 |
+
"""
|
| 472 |
+
def __new__(cls, *args):
|
| 473 |
+
r = cls.eval(args)
|
| 474 |
+
if isinstance(r, Basic):
|
| 475 |
+
return r
|
| 476 |
+
obj = Basic.__new__(cls, *args)
|
| 477 |
+
return obj
|
| 478 |
+
|
| 479 |
+
@classmethod
|
| 480 |
+
def eval(cls, args):
|
| 481 |
+
"""Evaluates the direct product."""
|
| 482 |
+
new_args = []
|
| 483 |
+
recall = False
|
| 484 |
+
#flatten arguments
|
| 485 |
+
for arg in args:
|
| 486 |
+
if isinstance(arg, DirectSumHilbertSpace):
|
| 487 |
+
new_args.extend(arg.args)
|
| 488 |
+
recall = True
|
| 489 |
+
elif isinstance(arg, HilbertSpace):
|
| 490 |
+
new_args.append(arg)
|
| 491 |
+
else:
|
| 492 |
+
raise TypeError('Hilbert spaces can only be summed with other \
|
| 493 |
+
Hilbert spaces: %r' % arg)
|
| 494 |
+
if recall:
|
| 495 |
+
return DirectSumHilbertSpace(*new_args)
|
| 496 |
+
else:
|
| 497 |
+
return None
|
| 498 |
+
|
| 499 |
+
@property
|
| 500 |
+
def dimension(self):
|
| 501 |
+
arg_list = [arg.dimension for arg in self.args]
|
| 502 |
+
if S.Infinity in arg_list:
|
| 503 |
+
return S.Infinity
|
| 504 |
+
else:
|
| 505 |
+
return reduce(lambda x, y: x + y, arg_list)
|
| 506 |
+
|
| 507 |
+
@property
|
| 508 |
+
def spaces(self):
|
| 509 |
+
"""A tuple of the Hilbert spaces in this direct sum."""
|
| 510 |
+
return self.args
|
| 511 |
+
|
| 512 |
+
def _sympyrepr(self, printer, *args):
|
| 513 |
+
spaces_reprs = [printer._print(arg, *args) for arg in self.args]
|
| 514 |
+
return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs)
|
| 515 |
+
|
| 516 |
+
def _sympystr(self, printer, *args):
|
| 517 |
+
spaces_strs = [printer._print(arg, *args) for arg in self.args]
|
| 518 |
+
return '+'.join(spaces_strs)
|
| 519 |
+
|
| 520 |
+
def _pretty(self, printer, *args):
|
| 521 |
+
length = len(self.args)
|
| 522 |
+
pform = printer._print('', *args)
|
| 523 |
+
for i in range(length):
|
| 524 |
+
next_pform = printer._print(self.args[i], *args)
|
| 525 |
+
if isinstance(self.args[i], (DirectSumHilbertSpace,
|
| 526 |
+
TensorProductHilbertSpace)):
|
| 527 |
+
next_pform = prettyForm(
|
| 528 |
+
*next_pform.parens(left='(', right=')')
|
| 529 |
+
)
|
| 530 |
+
pform = prettyForm(*pform.right(next_pform))
|
| 531 |
+
if i != length - 1:
|
| 532 |
+
if printer._use_unicode:
|
| 533 |
+
pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} '))
|
| 534 |
+
else:
|
| 535 |
+
pform = prettyForm(*pform.right(' + '))
|
| 536 |
+
return pform
|
| 537 |
+
|
| 538 |
+
def _latex(self, printer, *args):
|
| 539 |
+
length = len(self.args)
|
| 540 |
+
s = ''
|
| 541 |
+
for i in range(length):
|
| 542 |
+
arg_s = printer._print(self.args[i], *args)
|
| 543 |
+
if isinstance(self.args[i], (DirectSumHilbertSpace,
|
| 544 |
+
TensorProductHilbertSpace)):
|
| 545 |
+
arg_s = r'\left(%s\right)' % arg_s
|
| 546 |
+
s = s + arg_s
|
| 547 |
+
if i != length - 1:
|
| 548 |
+
s = s + r'\oplus '
|
| 549 |
+
return s
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class TensorPowerHilbertSpace(HilbertSpace):
|
| 553 |
+
"""An exponentiated Hilbert space [1]_.
|
| 554 |
+
|
| 555 |
+
Tensor powers (repeated tensor products) are represented by the
|
| 556 |
+
operator ``**`` Identical Hilbert spaces that are multiplied together
|
| 557 |
+
will be automatically combined into a single tensor power object.
|
| 558 |
+
|
| 559 |
+
Any Hilbert space, product, or sum may be raised to a tensor power. The
|
| 560 |
+
``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
|
| 561 |
+
tensor power (number).
|
| 562 |
+
|
| 563 |
+
Examples
|
| 564 |
+
========
|
| 565 |
+
|
| 566 |
+
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
|
| 567 |
+
>>> from sympy import symbols
|
| 568 |
+
|
| 569 |
+
>>> n = symbols('n')
|
| 570 |
+
>>> c = ComplexSpace(2)
|
| 571 |
+
>>> hs = c**n
|
| 572 |
+
>>> hs
|
| 573 |
+
C(2)**n
|
| 574 |
+
>>> hs.dimension
|
| 575 |
+
2**n
|
| 576 |
+
|
| 577 |
+
>>> c = ComplexSpace(2)
|
| 578 |
+
>>> c*c
|
| 579 |
+
C(2)**2
|
| 580 |
+
>>> f = FockSpace()
|
| 581 |
+
>>> c*f*f
|
| 582 |
+
C(2)*F**2
|
| 583 |
+
|
| 584 |
+
References
|
| 585 |
+
==========
|
| 586 |
+
|
| 587 |
+
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
|
| 588 |
+
"""
|
| 589 |
+
|
| 590 |
+
def __new__(cls, *args):
|
| 591 |
+
r = cls.eval(args)
|
| 592 |
+
if isinstance(r, Basic):
|
| 593 |
+
return r
|
| 594 |
+
return Basic.__new__(cls, *r)
|
| 595 |
+
|
| 596 |
+
@classmethod
|
| 597 |
+
def eval(cls, args):
|
| 598 |
+
new_args = args[0], sympify(args[1])
|
| 599 |
+
exp = new_args[1]
|
| 600 |
+
#simplify hs**1 -> hs
|
| 601 |
+
if exp is S.One:
|
| 602 |
+
return args[0]
|
| 603 |
+
#simplify hs**0 -> 1
|
| 604 |
+
if exp is S.Zero:
|
| 605 |
+
return S.One
|
| 606 |
+
#check (and allow) for hs**(x+42+y...) case
|
| 607 |
+
if len(exp.atoms()) == 1:
|
| 608 |
+
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
|
| 609 |
+
raise ValueError('Hilbert spaces can only be raised to \
|
| 610 |
+
positive integers or Symbols: %r' % exp)
|
| 611 |
+
else:
|
| 612 |
+
for power in exp.atoms():
|
| 613 |
+
if not (power.is_Integer or power.is_Symbol):
|
| 614 |
+
raise ValueError('Tensor powers can only contain integers \
|
| 615 |
+
or Symbols: %r' % power)
|
| 616 |
+
return new_args
|
| 617 |
+
|
| 618 |
+
@property
|
| 619 |
+
def base(self):
|
| 620 |
+
return self.args[0]
|
| 621 |
+
|
| 622 |
+
@property
|
| 623 |
+
def exp(self):
|
| 624 |
+
return self.args[1]
|
| 625 |
+
|
| 626 |
+
@property
|
| 627 |
+
def dimension(self):
|
| 628 |
+
if self.base.dimension is S.Infinity:
|
| 629 |
+
return S.Infinity
|
| 630 |
+
else:
|
| 631 |
+
return self.base.dimension**self.exp
|
| 632 |
+
|
| 633 |
+
def _sympyrepr(self, printer, *args):
|
| 634 |
+
return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
|
| 635 |
+
*args), printer._print(self.exp, *args))
|
| 636 |
+
|
| 637 |
+
def _sympystr(self, printer, *args):
|
| 638 |
+
return "%s**%s" % (printer._print(self.base, *args),
|
| 639 |
+
printer._print(self.exp, *args))
|
| 640 |
+
|
| 641 |
+
def _pretty(self, printer, *args):
|
| 642 |
+
pform_exp = printer._print(self.exp, *args)
|
| 643 |
+
if printer._use_unicode:
|
| 644 |
+
pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
|
| 645 |
+
else:
|
| 646 |
+
pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
|
| 647 |
+
pform_base = printer._print(self.base, *args)
|
| 648 |
+
return pform_base**pform_exp
|
| 649 |
+
|
| 650 |
+
def _latex(self, printer, *args):
|
| 651 |
+
base = printer._print(self.base, *args)
|
| 652 |
+
exp = printer._print(self.exp, *args)
|
| 653 |
+
return r'{%s}^{\otimes %s}' % (base, exp)
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py
ADDED
|
@@ -0,0 +1,853 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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import import_module
|
| 5 |
+
from sympy.core.basic import Basic
|
| 6 |
+
from sympy.core.mul import Mul
|
| 7 |
+
from sympy.core.numbers import Number, equal_valued
|
| 8 |
+
from sympy.core.power import Pow
|
| 9 |
+
from sympy.core.singleton import S
|
| 10 |
+
from sympy.physics.quantum.represent import represent
|
| 11 |
+
from sympy.physics.quantum.dagger import Dagger
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
# Public interfaces
|
| 15 |
+
'generate_gate_rules',
|
| 16 |
+
'generate_equivalent_ids',
|
| 17 |
+
'GateIdentity',
|
| 18 |
+
'bfs_identity_search',
|
| 19 |
+
'random_identity_search',
|
| 20 |
+
|
| 21 |
+
# "Private" functions
|
| 22 |
+
'is_scalar_sparse_matrix',
|
| 23 |
+
'is_scalar_nonsparse_matrix',
|
| 24 |
+
'is_degenerate',
|
| 25 |
+
'is_reducible',
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
np = import_module('numpy')
|
| 29 |
+
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11):
|
| 33 |
+
"""Checks if a given scipy.sparse matrix is a scalar matrix.
|
| 34 |
+
|
| 35 |
+
A scalar matrix is such that B = bI, where B is the scalar
|
| 36 |
+
matrix, b is some scalar multiple, and I is the identity
|
| 37 |
+
matrix. A scalar matrix would have only the element b along
|
| 38 |
+
it's main diagonal and zeroes elsewhere.
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
==========
|
| 42 |
+
|
| 43 |
+
circuit : Gate tuple
|
| 44 |
+
Sequence of quantum gates representing a quantum circuit
|
| 45 |
+
nqubits : int
|
| 46 |
+
Number of qubits in the circuit
|
| 47 |
+
identity_only : bool
|
| 48 |
+
Check for only identity matrices
|
| 49 |
+
eps : number
|
| 50 |
+
The tolerance value for zeroing out elements in the matrix.
|
| 51 |
+
Values in the range [-eps, +eps] will be changed to a zero.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
if not np or not scipy:
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
matrix = represent(Mul(*circuit), nqubits=nqubits,
|
| 58 |
+
format='scipy.sparse')
|
| 59 |
+
|
| 60 |
+
# In some cases, represent returns a 1D scalar value in place
|
| 61 |
+
# of a multi-dimensional scalar matrix
|
| 62 |
+
if (isinstance(matrix, int)):
|
| 63 |
+
return matrix == 1 if identity_only else True
|
| 64 |
+
|
| 65 |
+
# If represent returns a matrix, check if the matrix is diagonal
|
| 66 |
+
# and if every item along the diagonal is the same
|
| 67 |
+
else:
|
| 68 |
+
# Due to floating pointing operations, must zero out
|
| 69 |
+
# elements that are "very" small in the dense matrix
|
| 70 |
+
# See parameter for default value.
|
| 71 |
+
|
| 72 |
+
# Get the ndarray version of the dense matrix
|
| 73 |
+
dense_matrix = matrix.todense().getA()
|
| 74 |
+
# Since complex values can't be compared, must split
|
| 75 |
+
# the matrix into real and imaginary components
|
| 76 |
+
# Find the real values in between -eps and eps
|
| 77 |
+
bool_real = np.logical_and(dense_matrix.real > -eps,
|
| 78 |
+
dense_matrix.real < eps)
|
| 79 |
+
# Find the imaginary values between -eps and eps
|
| 80 |
+
bool_imag = np.logical_and(dense_matrix.imag > -eps,
|
| 81 |
+
dense_matrix.imag < eps)
|
| 82 |
+
# Replaces values between -eps and eps with 0
|
| 83 |
+
corrected_real = np.where(bool_real, 0.0, dense_matrix.real)
|
| 84 |
+
corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag)
|
| 85 |
+
# Convert the matrix with real values into imaginary values
|
| 86 |
+
corrected_imag = corrected_imag * complex(1j)
|
| 87 |
+
# Recombine the real and imaginary components
|
| 88 |
+
corrected_dense = corrected_real + corrected_imag
|
| 89 |
+
|
| 90 |
+
# Check if it's diagonal
|
| 91 |
+
row_indices = corrected_dense.nonzero()[0]
|
| 92 |
+
col_indices = corrected_dense.nonzero()[1]
|
| 93 |
+
# Check if the rows indices and columns indices are the same
|
| 94 |
+
# If they match, then matrix only contains elements along diagonal
|
| 95 |
+
bool_indices = row_indices == col_indices
|
| 96 |
+
is_diagonal = bool_indices.all()
|
| 97 |
+
|
| 98 |
+
first_element = corrected_dense[0][0]
|
| 99 |
+
# If the first element is a zero, then can't rescale matrix
|
| 100 |
+
# and definitely not diagonal
|
| 101 |
+
if (first_element == 0.0 + 0.0j):
|
| 102 |
+
return False
|
| 103 |
+
|
| 104 |
+
# The dimensions of the dense matrix should still
|
| 105 |
+
# be 2^nqubits if there are elements all along the
|
| 106 |
+
# the main diagonal
|
| 107 |
+
trace_of_corrected = (corrected_dense/first_element).trace()
|
| 108 |
+
expected_trace = pow(2, nqubits)
|
| 109 |
+
has_correct_trace = trace_of_corrected == expected_trace
|
| 110 |
+
|
| 111 |
+
# If only looking for identity matrices
|
| 112 |
+
# first element must be a 1
|
| 113 |
+
real_is_one = abs(first_element.real - 1.0) < eps
|
| 114 |
+
imag_is_zero = abs(first_element.imag) < eps
|
| 115 |
+
is_one = real_is_one and imag_is_zero
|
| 116 |
+
is_identity = is_one if identity_only else True
|
| 117 |
+
return bool(is_diagonal and has_correct_trace and is_identity)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None):
|
| 121 |
+
"""Checks if a given circuit, in matrix form, is equivalent to
|
| 122 |
+
a scalar value.
|
| 123 |
+
|
| 124 |
+
Parameters
|
| 125 |
+
==========
|
| 126 |
+
|
| 127 |
+
circuit : Gate tuple
|
| 128 |
+
Sequence of quantum gates representing a quantum circuit
|
| 129 |
+
nqubits : int
|
| 130 |
+
Number of qubits in the circuit
|
| 131 |
+
identity_only : bool
|
| 132 |
+
Check for only identity matrices
|
| 133 |
+
eps : number
|
| 134 |
+
This argument is ignored. It is just for signature compatibility with
|
| 135 |
+
is_scalar_sparse_matrix.
|
| 136 |
+
|
| 137 |
+
Note: Used in situations when is_scalar_sparse_matrix has bugs
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
matrix = represent(Mul(*circuit), nqubits=nqubits)
|
| 141 |
+
|
| 142 |
+
# In some cases, represent returns a 1D scalar value in place
|
| 143 |
+
# of a multi-dimensional scalar matrix
|
| 144 |
+
if (isinstance(matrix, Number)):
|
| 145 |
+
return matrix == 1 if identity_only else True
|
| 146 |
+
|
| 147 |
+
# If represent returns a matrix, check if the matrix is diagonal
|
| 148 |
+
# and if every item along the diagonal is the same
|
| 149 |
+
else:
|
| 150 |
+
# Added up the diagonal elements
|
| 151 |
+
matrix_trace = matrix.trace()
|
| 152 |
+
# Divide the trace by the first element in the matrix
|
| 153 |
+
# if matrix is not required to be the identity matrix
|
| 154 |
+
adjusted_matrix_trace = (matrix_trace/matrix[0]
|
| 155 |
+
if not identity_only
|
| 156 |
+
else matrix_trace)
|
| 157 |
+
|
| 158 |
+
is_identity = equal_valued(matrix[0], 1) if identity_only else True
|
| 159 |
+
|
| 160 |
+
has_correct_trace = adjusted_matrix_trace == pow(2, nqubits)
|
| 161 |
+
|
| 162 |
+
# The matrix is scalar if it's diagonal and the adjusted trace
|
| 163 |
+
# value is equal to 2^nqubits
|
| 164 |
+
return bool(
|
| 165 |
+
matrix.is_diagonal() and has_correct_trace and is_identity)
|
| 166 |
+
|
| 167 |
+
if np and scipy:
|
| 168 |
+
is_scalar_matrix = is_scalar_sparse_matrix
|
| 169 |
+
else:
|
| 170 |
+
is_scalar_matrix = is_scalar_nonsparse_matrix
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _get_min_qubits(a_gate):
|
| 174 |
+
if isinstance(a_gate, Pow):
|
| 175 |
+
return a_gate.base.min_qubits
|
| 176 |
+
else:
|
| 177 |
+
return a_gate.min_qubits
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def ll_op(left, right):
|
| 181 |
+
"""Perform a LL operation.
|
| 182 |
+
|
| 183 |
+
A LL operation multiplies both left and right circuits
|
| 184 |
+
with the dagger of the left circuit's leftmost gate, and
|
| 185 |
+
the dagger is multiplied on the left side of both circuits.
|
| 186 |
+
|
| 187 |
+
If a LL is possible, it returns the new gate rule as a
|
| 188 |
+
2-tuple (LHS, RHS), where LHS is the left circuit and
|
| 189 |
+
and RHS is the right circuit of the new rule.
|
| 190 |
+
If a LL is not possible, None is returned.
|
| 191 |
+
|
| 192 |
+
Parameters
|
| 193 |
+
==========
|
| 194 |
+
|
| 195 |
+
left : Gate tuple
|
| 196 |
+
The left circuit of a gate rule expression.
|
| 197 |
+
right : Gate tuple
|
| 198 |
+
The right circuit of a gate rule expression.
|
| 199 |
+
|
| 200 |
+
Examples
|
| 201 |
+
========
|
| 202 |
+
|
| 203 |
+
Generate a new gate rule using a LL operation:
|
| 204 |
+
|
| 205 |
+
>>> from sympy.physics.quantum.identitysearch import ll_op
|
| 206 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 207 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 208 |
+
>>> ll_op((x, y, z), ())
|
| 209 |
+
((Y(0), Z(0)), (X(0),))
|
| 210 |
+
|
| 211 |
+
>>> ll_op((y, z), (x,))
|
| 212 |
+
((Z(0),), (Y(0), X(0)))
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
if (len(left) > 0):
|
| 216 |
+
ll_gate = left[0]
|
| 217 |
+
ll_gate_is_unitary = is_scalar_matrix(
|
| 218 |
+
(Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True)
|
| 219 |
+
|
| 220 |
+
if (len(left) > 0 and ll_gate_is_unitary):
|
| 221 |
+
# Get the new left side w/o the leftmost gate
|
| 222 |
+
new_left = left[1:len(left)]
|
| 223 |
+
# Add the leftmost gate to the left position on the right side
|
| 224 |
+
new_right = (Dagger(ll_gate),) + right
|
| 225 |
+
# Return the new gate rule
|
| 226 |
+
return (new_left, new_right)
|
| 227 |
+
|
| 228 |
+
return None
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def lr_op(left, right):
|
| 232 |
+
"""Perform a LR operation.
|
| 233 |
+
|
| 234 |
+
A LR operation multiplies both left and right circuits
|
| 235 |
+
with the dagger of the left circuit's rightmost gate, and
|
| 236 |
+
the dagger is multiplied on the right side of both circuits.
|
| 237 |
+
|
| 238 |
+
If a LR is possible, it returns the new gate rule as a
|
| 239 |
+
2-tuple (LHS, RHS), where LHS is the left circuit and
|
| 240 |
+
and RHS is the right circuit of the new rule.
|
| 241 |
+
If a LR is not possible, None is returned.
|
| 242 |
+
|
| 243 |
+
Parameters
|
| 244 |
+
==========
|
| 245 |
+
|
| 246 |
+
left : Gate tuple
|
| 247 |
+
The left circuit of a gate rule expression.
|
| 248 |
+
right : Gate tuple
|
| 249 |
+
The right circuit of a gate rule expression.
|
| 250 |
+
|
| 251 |
+
Examples
|
| 252 |
+
========
|
| 253 |
+
|
| 254 |
+
Generate a new gate rule using a LR operation:
|
| 255 |
+
|
| 256 |
+
>>> from sympy.physics.quantum.identitysearch import lr_op
|
| 257 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 258 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 259 |
+
>>> lr_op((x, y, z), ())
|
| 260 |
+
((X(0), Y(0)), (Z(0),))
|
| 261 |
+
|
| 262 |
+
>>> lr_op((x, y), (z,))
|
| 263 |
+
((X(0),), (Z(0), Y(0)))
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
if (len(left) > 0):
|
| 267 |
+
lr_gate = left[len(left) - 1]
|
| 268 |
+
lr_gate_is_unitary = is_scalar_matrix(
|
| 269 |
+
(Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True)
|
| 270 |
+
|
| 271 |
+
if (len(left) > 0 and lr_gate_is_unitary):
|
| 272 |
+
# Get the new left side w/o the rightmost gate
|
| 273 |
+
new_left = left[0:len(left) - 1]
|
| 274 |
+
# Add the rightmost gate to the right position on the right side
|
| 275 |
+
new_right = right + (Dagger(lr_gate),)
|
| 276 |
+
# Return the new gate rule
|
| 277 |
+
return (new_left, new_right)
|
| 278 |
+
|
| 279 |
+
return None
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def rl_op(left, right):
|
| 283 |
+
"""Perform a RL operation.
|
| 284 |
+
|
| 285 |
+
A RL operation multiplies both left and right circuits
|
| 286 |
+
with the dagger of the right circuit's leftmost gate, and
|
| 287 |
+
the dagger is multiplied on the left side of both circuits.
|
| 288 |
+
|
| 289 |
+
If a RL is possible, it returns the new gate rule as a
|
| 290 |
+
2-tuple (LHS, RHS), where LHS is the left circuit and
|
| 291 |
+
and RHS is the right circuit of the new rule.
|
| 292 |
+
If a RL is not possible, None is returned.
|
| 293 |
+
|
| 294 |
+
Parameters
|
| 295 |
+
==========
|
| 296 |
+
|
| 297 |
+
left : Gate tuple
|
| 298 |
+
The left circuit of a gate rule expression.
|
| 299 |
+
right : Gate tuple
|
| 300 |
+
The right circuit of a gate rule expression.
|
| 301 |
+
|
| 302 |
+
Examples
|
| 303 |
+
========
|
| 304 |
+
|
| 305 |
+
Generate a new gate rule using a RL operation:
|
| 306 |
+
|
| 307 |
+
>>> from sympy.physics.quantum.identitysearch import rl_op
|
| 308 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 309 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 310 |
+
>>> rl_op((x,), (y, z))
|
| 311 |
+
((Y(0), X(0)), (Z(0),))
|
| 312 |
+
|
| 313 |
+
>>> rl_op((x, y), (z,))
|
| 314 |
+
((Z(0), X(0), Y(0)), ())
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
if (len(right) > 0):
|
| 318 |
+
rl_gate = right[0]
|
| 319 |
+
rl_gate_is_unitary = is_scalar_matrix(
|
| 320 |
+
(Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
|
| 321 |
+
|
| 322 |
+
if (len(right) > 0 and rl_gate_is_unitary):
|
| 323 |
+
# Get the new right side w/o the leftmost gate
|
| 324 |
+
new_right = right[1:len(right)]
|
| 325 |
+
# Add the leftmost gate to the left position on the left side
|
| 326 |
+
new_left = (Dagger(rl_gate),) + left
|
| 327 |
+
# Return the new gate rule
|
| 328 |
+
return (new_left, new_right)
|
| 329 |
+
|
| 330 |
+
return None
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def rr_op(left, right):
|
| 334 |
+
"""Perform a RR operation.
|
| 335 |
+
|
| 336 |
+
A RR operation multiplies both left and right circuits
|
| 337 |
+
with the dagger of the right circuit's rightmost gate, and
|
| 338 |
+
the dagger is multiplied on the right side of both circuits.
|
| 339 |
+
|
| 340 |
+
If a RR is possible, it returns the new gate rule as a
|
| 341 |
+
2-tuple (LHS, RHS), where LHS is the left circuit and
|
| 342 |
+
and RHS is the right circuit of the new rule.
|
| 343 |
+
If a RR is not possible, None is returned.
|
| 344 |
+
|
| 345 |
+
Parameters
|
| 346 |
+
==========
|
| 347 |
+
|
| 348 |
+
left : Gate tuple
|
| 349 |
+
The left circuit of a gate rule expression.
|
| 350 |
+
right : Gate tuple
|
| 351 |
+
The right circuit of a gate rule expression.
|
| 352 |
+
|
| 353 |
+
Examples
|
| 354 |
+
========
|
| 355 |
+
|
| 356 |
+
Generate a new gate rule using a RR operation:
|
| 357 |
+
|
| 358 |
+
>>> from sympy.physics.quantum.identitysearch import rr_op
|
| 359 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 360 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 361 |
+
>>> rr_op((x, y), (z,))
|
| 362 |
+
((X(0), Y(0), Z(0)), ())
|
| 363 |
+
|
| 364 |
+
>>> rr_op((x,), (y, z))
|
| 365 |
+
((X(0), Z(0)), (Y(0),))
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
if (len(right) > 0):
|
| 369 |
+
rr_gate = right[len(right) - 1]
|
| 370 |
+
rr_gate_is_unitary = is_scalar_matrix(
|
| 371 |
+
(Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True)
|
| 372 |
+
|
| 373 |
+
if (len(right) > 0 and rr_gate_is_unitary):
|
| 374 |
+
# Get the new right side w/o the rightmost gate
|
| 375 |
+
new_right = right[0:len(right) - 1]
|
| 376 |
+
# Add the rightmost gate to the right position on the right side
|
| 377 |
+
new_left = left + (Dagger(rr_gate),)
|
| 378 |
+
# Return the new gate rule
|
| 379 |
+
return (new_left, new_right)
|
| 380 |
+
|
| 381 |
+
return None
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def generate_gate_rules(gate_seq, return_as_muls=False):
|
| 385 |
+
"""Returns a set of gate rules. Each gate rules is represented
|
| 386 |
+
as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary
|
| 387 |
+
scalar value.
|
| 388 |
+
|
| 389 |
+
This function uses the four operations (LL, LR, RL, RR)
|
| 390 |
+
to generate the gate rules.
|
| 391 |
+
|
| 392 |
+
A gate rule is an expression such as ABC = D or AB = CD, where
|
| 393 |
+
A, B, C, and D are gates. Each value on either side of the
|
| 394 |
+
equal sign represents a circuit. The four operations allow
|
| 395 |
+
one to find a set of equivalent circuits from a gate identity.
|
| 396 |
+
The letters denoting the operation tell the user what
|
| 397 |
+
activities to perform on each expression. The first letter
|
| 398 |
+
indicates which side of the equal sign to focus on. The
|
| 399 |
+
second letter indicates which gate to focus on given the
|
| 400 |
+
side. Once this information is determined, the inverse
|
| 401 |
+
of the gate is multiplied on both circuits to create a new
|
| 402 |
+
gate rule.
|
| 403 |
+
|
| 404 |
+
For example, given the identity, ABCD = 1, a LL operation
|
| 405 |
+
means look at the left value and multiply both left sides by the
|
| 406 |
+
inverse of the leftmost gate A. If A is Hermitian, the inverse
|
| 407 |
+
of A is still A. The resulting new rule is BCD = A.
|
| 408 |
+
|
| 409 |
+
The following is a summary of the four operations. Assume
|
| 410 |
+
that in the examples, all gates are Hermitian.
|
| 411 |
+
|
| 412 |
+
LL : left circuit, left multiply
|
| 413 |
+
ABCD = E -> AABCD = AE -> BCD = AE
|
| 414 |
+
LR : left circuit, right multiply
|
| 415 |
+
ABCD = E -> ABCDD = ED -> ABC = ED
|
| 416 |
+
RL : right circuit, left multiply
|
| 417 |
+
ABC = ED -> EABC = EED -> EABC = D
|
| 418 |
+
RR : right circuit, right multiply
|
| 419 |
+
AB = CD -> ABD = CDD -> ABD = C
|
| 420 |
+
|
| 421 |
+
The number of gate rules generated is n*(n+1), where n
|
| 422 |
+
is the number of gates in the sequence (unproven).
|
| 423 |
+
|
| 424 |
+
Parameters
|
| 425 |
+
==========
|
| 426 |
+
|
| 427 |
+
gate_seq : Gate tuple, Mul, or Number
|
| 428 |
+
A variable length tuple or Mul of Gates whose product is equal to
|
| 429 |
+
a scalar matrix
|
| 430 |
+
return_as_muls : bool
|
| 431 |
+
True to return a set of Muls; False to return a set of tuples
|
| 432 |
+
|
| 433 |
+
Examples
|
| 434 |
+
========
|
| 435 |
+
|
| 436 |
+
Find the gate rules of the current circuit using tuples:
|
| 437 |
+
|
| 438 |
+
>>> from sympy.physics.quantum.identitysearch import generate_gate_rules
|
| 439 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 440 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 441 |
+
>>> generate_gate_rules((x, x))
|
| 442 |
+
{((X(0),), (X(0),)), ((X(0), X(0)), ())}
|
| 443 |
+
|
| 444 |
+
>>> generate_gate_rules((x, y, z))
|
| 445 |
+
{((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
|
| 446 |
+
((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
|
| 447 |
+
((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
|
| 448 |
+
((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
|
| 449 |
+
((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
|
| 450 |
+
((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}
|
| 451 |
+
|
| 452 |
+
Find the gate rules of the current circuit using Muls:
|
| 453 |
+
|
| 454 |
+
>>> generate_gate_rules(x*x, return_as_muls=True)
|
| 455 |
+
{(1, 1)}
|
| 456 |
+
|
| 457 |
+
>>> generate_gate_rules(x*y*z, return_as_muls=True)
|
| 458 |
+
{(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
|
| 459 |
+
(1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
|
| 460 |
+
(Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
|
| 461 |
+
(X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
|
| 462 |
+
(Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
|
| 463 |
+
(Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
|
| 464 |
+
"""
|
| 465 |
+
|
| 466 |
+
if isinstance(gate_seq, Number):
|
| 467 |
+
if return_as_muls:
|
| 468 |
+
return {(S.One, S.One)}
|
| 469 |
+
else:
|
| 470 |
+
return {((), ())}
|
| 471 |
+
|
| 472 |
+
elif isinstance(gate_seq, Mul):
|
| 473 |
+
gate_seq = gate_seq.args
|
| 474 |
+
|
| 475 |
+
# Each item in queue is a 3-tuple:
|
| 476 |
+
# i) first item is the left side of an equality
|
| 477 |
+
# ii) second item is the right side of an equality
|
| 478 |
+
# iii) third item is the number of operations performed
|
| 479 |
+
# The argument, gate_seq, will start on the left side, and
|
| 480 |
+
# the right side will be empty, implying the presence of an
|
| 481 |
+
# identity.
|
| 482 |
+
queue = deque()
|
| 483 |
+
# A set of gate rules
|
| 484 |
+
rules = set()
|
| 485 |
+
# Maximum number of operations to perform
|
| 486 |
+
max_ops = len(gate_seq)
|
| 487 |
+
|
| 488 |
+
def process_new_rule(new_rule, ops):
|
| 489 |
+
if new_rule is not None:
|
| 490 |
+
new_left, new_right = new_rule
|
| 491 |
+
|
| 492 |
+
if new_rule not in rules and (new_right, new_left) not in rules:
|
| 493 |
+
rules.add(new_rule)
|
| 494 |
+
# If haven't reached the max limit on operations
|
| 495 |
+
if ops + 1 < max_ops:
|
| 496 |
+
queue.append(new_rule + (ops + 1,))
|
| 497 |
+
|
| 498 |
+
queue.append((gate_seq, (), 0))
|
| 499 |
+
rules.add((gate_seq, ()))
|
| 500 |
+
|
| 501 |
+
while len(queue) > 0:
|
| 502 |
+
left, right, ops = queue.popleft()
|
| 503 |
+
|
| 504 |
+
# Do a LL
|
| 505 |
+
new_rule = ll_op(left, right)
|
| 506 |
+
process_new_rule(new_rule, ops)
|
| 507 |
+
# Do a LR
|
| 508 |
+
new_rule = lr_op(left, right)
|
| 509 |
+
process_new_rule(new_rule, ops)
|
| 510 |
+
# Do a RL
|
| 511 |
+
new_rule = rl_op(left, right)
|
| 512 |
+
process_new_rule(new_rule, ops)
|
| 513 |
+
# Do a RR
|
| 514 |
+
new_rule = rr_op(left, right)
|
| 515 |
+
process_new_rule(new_rule, ops)
|
| 516 |
+
|
| 517 |
+
if return_as_muls:
|
| 518 |
+
# Convert each rule as tuples into a rule as muls
|
| 519 |
+
mul_rules = set()
|
| 520 |
+
for rule in rules:
|
| 521 |
+
left, right = rule
|
| 522 |
+
mul_rules.add((Mul(*left), Mul(*right)))
|
| 523 |
+
|
| 524 |
+
rules = mul_rules
|
| 525 |
+
|
| 526 |
+
return rules
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def generate_equivalent_ids(gate_seq, return_as_muls=False):
|
| 530 |
+
"""Returns a set of equivalent gate identities.
|
| 531 |
+
|
| 532 |
+
A gate identity is a quantum circuit such that the product
|
| 533 |
+
of the gates in the circuit is equal to a scalar value.
|
| 534 |
+
For example, XYZ = i, where X, Y, Z are the Pauli gates and
|
| 535 |
+
i is the imaginary value, is considered a gate identity.
|
| 536 |
+
|
| 537 |
+
This function uses the four operations (LL, LR, RL, RR)
|
| 538 |
+
to generate the gate rules and, subsequently, to locate equivalent
|
| 539 |
+
gate identities.
|
| 540 |
+
|
| 541 |
+
Note that all equivalent identities are reachable in n operations
|
| 542 |
+
from the starting gate identity, where n is the number of gates
|
| 543 |
+
in the sequence.
|
| 544 |
+
|
| 545 |
+
The max number of gate identities is 2n, where n is the number
|
| 546 |
+
of gates in the sequence (unproven).
|
| 547 |
+
|
| 548 |
+
Parameters
|
| 549 |
+
==========
|
| 550 |
+
|
| 551 |
+
gate_seq : Gate tuple, Mul, or Number
|
| 552 |
+
A variable length tuple or Mul of Gates whose product is equal to
|
| 553 |
+
a scalar matrix.
|
| 554 |
+
return_as_muls: bool
|
| 555 |
+
True to return as Muls; False to return as tuples
|
| 556 |
+
|
| 557 |
+
Examples
|
| 558 |
+
========
|
| 559 |
+
|
| 560 |
+
Find equivalent gate identities from the current circuit with tuples:
|
| 561 |
+
|
| 562 |
+
>>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
|
| 563 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 564 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 565 |
+
>>> generate_equivalent_ids((x, x))
|
| 566 |
+
{(X(0), X(0))}
|
| 567 |
+
|
| 568 |
+
>>> generate_equivalent_ids((x, y, z))
|
| 569 |
+
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
|
| 570 |
+
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
|
| 571 |
+
|
| 572 |
+
Find equivalent gate identities from the current circuit with Muls:
|
| 573 |
+
|
| 574 |
+
>>> generate_equivalent_ids(x*x, return_as_muls=True)
|
| 575 |
+
{1}
|
| 576 |
+
|
| 577 |
+
>>> generate_equivalent_ids(x*y*z, return_as_muls=True)
|
| 578 |
+
{X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
|
| 579 |
+
Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
|
| 580 |
+
"""
|
| 581 |
+
|
| 582 |
+
if isinstance(gate_seq, Number):
|
| 583 |
+
return {S.One}
|
| 584 |
+
elif isinstance(gate_seq, Mul):
|
| 585 |
+
gate_seq = gate_seq.args
|
| 586 |
+
|
| 587 |
+
# Filter through the gate rules and keep the rules
|
| 588 |
+
# with an empty tuple either on the left or right side
|
| 589 |
+
|
| 590 |
+
# A set of equivalent gate identities
|
| 591 |
+
eq_ids = set()
|
| 592 |
+
|
| 593 |
+
gate_rules = generate_gate_rules(gate_seq)
|
| 594 |
+
for rule in gate_rules:
|
| 595 |
+
l, r = rule
|
| 596 |
+
if l == ():
|
| 597 |
+
eq_ids.add(r)
|
| 598 |
+
elif r == ():
|
| 599 |
+
eq_ids.add(l)
|
| 600 |
+
|
| 601 |
+
if return_as_muls:
|
| 602 |
+
convert_to_mul = lambda id_seq: Mul(*id_seq)
|
| 603 |
+
eq_ids = set(map(convert_to_mul, eq_ids))
|
| 604 |
+
|
| 605 |
+
return eq_ids
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
class GateIdentity(Basic):
|
| 609 |
+
"""Wrapper class for circuits that reduce to a scalar value.
|
| 610 |
+
|
| 611 |
+
A gate identity is a quantum circuit such that the product
|
| 612 |
+
of the gates in the circuit is equal to a scalar value.
|
| 613 |
+
For example, XYZ = i, where X, Y, Z are the Pauli gates and
|
| 614 |
+
i is the imaginary value, is considered a gate identity.
|
| 615 |
+
|
| 616 |
+
Parameters
|
| 617 |
+
==========
|
| 618 |
+
|
| 619 |
+
args : Gate tuple
|
| 620 |
+
A variable length tuple of Gates that form an identity.
|
| 621 |
+
|
| 622 |
+
Examples
|
| 623 |
+
========
|
| 624 |
+
|
| 625 |
+
Create a GateIdentity and look at its attributes:
|
| 626 |
+
|
| 627 |
+
>>> from sympy.physics.quantum.identitysearch import GateIdentity
|
| 628 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 629 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 630 |
+
>>> an_identity = GateIdentity(x, y, z)
|
| 631 |
+
>>> an_identity.circuit
|
| 632 |
+
X(0)*Y(0)*Z(0)
|
| 633 |
+
|
| 634 |
+
>>> an_identity.equivalent_ids
|
| 635 |
+
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
|
| 636 |
+
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
|
| 637 |
+
"""
|
| 638 |
+
|
| 639 |
+
def __new__(cls, *args):
|
| 640 |
+
# args should be a tuple - a variable length argument list
|
| 641 |
+
obj = Basic.__new__(cls, *args)
|
| 642 |
+
obj._circuit = Mul(*args)
|
| 643 |
+
obj._rules = generate_gate_rules(args)
|
| 644 |
+
obj._eq_ids = generate_equivalent_ids(args)
|
| 645 |
+
|
| 646 |
+
return obj
|
| 647 |
+
|
| 648 |
+
@property
|
| 649 |
+
def circuit(self):
|
| 650 |
+
return self._circuit
|
| 651 |
+
|
| 652 |
+
@property
|
| 653 |
+
def gate_rules(self):
|
| 654 |
+
return self._rules
|
| 655 |
+
|
| 656 |
+
@property
|
| 657 |
+
def equivalent_ids(self):
|
| 658 |
+
return self._eq_ids
|
| 659 |
+
|
| 660 |
+
@property
|
| 661 |
+
def sequence(self):
|
| 662 |
+
return self.args
|
| 663 |
+
|
| 664 |
+
def __str__(self):
|
| 665 |
+
"""Returns the string of gates in a tuple."""
|
| 666 |
+
return str(self.circuit)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def is_degenerate(identity_set, gate_identity):
|
| 670 |
+
"""Checks if a gate identity is a permutation of another identity.
|
| 671 |
+
|
| 672 |
+
Parameters
|
| 673 |
+
==========
|
| 674 |
+
|
| 675 |
+
identity_set : set
|
| 676 |
+
A Python set with GateIdentity objects.
|
| 677 |
+
gate_identity : GateIdentity
|
| 678 |
+
The GateIdentity to check for existence in the set.
|
| 679 |
+
|
| 680 |
+
Examples
|
| 681 |
+
========
|
| 682 |
+
|
| 683 |
+
Check if the identity is a permutation of another identity:
|
| 684 |
+
|
| 685 |
+
>>> from sympy.physics.quantum.identitysearch import (
|
| 686 |
+
... GateIdentity, is_degenerate)
|
| 687 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 688 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 689 |
+
>>> an_identity = GateIdentity(x, y, z)
|
| 690 |
+
>>> id_set = {an_identity}
|
| 691 |
+
>>> another_id = (y, z, x)
|
| 692 |
+
>>> is_degenerate(id_set, another_id)
|
| 693 |
+
True
|
| 694 |
+
|
| 695 |
+
>>> another_id = (x, x)
|
| 696 |
+
>>> is_degenerate(id_set, another_id)
|
| 697 |
+
False
|
| 698 |
+
"""
|
| 699 |
+
|
| 700 |
+
# For now, just iteratively go through the set and check if the current
|
| 701 |
+
# gate_identity is a permutation of an identity in the set
|
| 702 |
+
for an_id in identity_set:
|
| 703 |
+
if (gate_identity in an_id.equivalent_ids):
|
| 704 |
+
return True
|
| 705 |
+
return False
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def is_reducible(circuit, nqubits, begin, end):
|
| 709 |
+
"""Determines if a circuit is reducible by checking
|
| 710 |
+
if its subcircuits are scalar values.
|
| 711 |
+
|
| 712 |
+
Parameters
|
| 713 |
+
==========
|
| 714 |
+
|
| 715 |
+
circuit : Gate tuple
|
| 716 |
+
A tuple of Gates representing a circuit. The circuit to check
|
| 717 |
+
if a gate identity is contained in a subcircuit.
|
| 718 |
+
nqubits : int
|
| 719 |
+
The number of qubits the circuit operates on.
|
| 720 |
+
begin : int
|
| 721 |
+
The leftmost gate in the circuit to include in a subcircuit.
|
| 722 |
+
end : int
|
| 723 |
+
The rightmost gate in the circuit to include in a subcircuit.
|
| 724 |
+
|
| 725 |
+
Examples
|
| 726 |
+
========
|
| 727 |
+
|
| 728 |
+
Check if the circuit can be reduced:
|
| 729 |
+
|
| 730 |
+
>>> from sympy.physics.quantum.identitysearch import is_reducible
|
| 731 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 732 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 733 |
+
>>> is_reducible((x, y, z), 1, 0, 3)
|
| 734 |
+
True
|
| 735 |
+
|
| 736 |
+
Check if an interval in the circuit can be reduced:
|
| 737 |
+
|
| 738 |
+
>>> is_reducible((x, y, z), 1, 1, 3)
|
| 739 |
+
False
|
| 740 |
+
|
| 741 |
+
>>> is_reducible((x, y, y), 1, 1, 3)
|
| 742 |
+
True
|
| 743 |
+
"""
|
| 744 |
+
|
| 745 |
+
current_circuit = ()
|
| 746 |
+
# Start from the gate at "end" and go down to almost the gate at "begin"
|
| 747 |
+
for ndx in reversed(range(begin, end)):
|
| 748 |
+
next_gate = circuit[ndx]
|
| 749 |
+
current_circuit = (next_gate,) + current_circuit
|
| 750 |
+
|
| 751 |
+
# If a circuit as a matrix is equivalent to a scalar value
|
| 752 |
+
if (is_scalar_matrix(current_circuit, nqubits, False)):
|
| 753 |
+
return True
|
| 754 |
+
|
| 755 |
+
return False
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
def bfs_identity_search(gate_list, nqubits, max_depth=None,
|
| 759 |
+
identity_only=False):
|
| 760 |
+
"""Constructs a set of gate identities from the list of possible gates.
|
| 761 |
+
|
| 762 |
+
Performs a breadth first search over the space of gate identities.
|
| 763 |
+
This allows the finding of the shortest gate identities first.
|
| 764 |
+
|
| 765 |
+
Parameters
|
| 766 |
+
==========
|
| 767 |
+
|
| 768 |
+
gate_list : list, Gate
|
| 769 |
+
A list of Gates from which to search for gate identities.
|
| 770 |
+
nqubits : int
|
| 771 |
+
The number of qubits the quantum circuit operates on.
|
| 772 |
+
max_depth : int
|
| 773 |
+
The longest quantum circuit to construct from gate_list.
|
| 774 |
+
identity_only : bool
|
| 775 |
+
True to search for gate identities that reduce to identity;
|
| 776 |
+
False to search for gate identities that reduce to a scalar.
|
| 777 |
+
|
| 778 |
+
Examples
|
| 779 |
+
========
|
| 780 |
+
|
| 781 |
+
Find a list of gate identities:
|
| 782 |
+
|
| 783 |
+
>>> from sympy.physics.quantum.identitysearch import bfs_identity_search
|
| 784 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
| 785 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
| 786 |
+
>>> bfs_identity_search([x], 1, max_depth=2)
|
| 787 |
+
{GateIdentity(X(0), X(0))}
|
| 788 |
+
|
| 789 |
+
>>> bfs_identity_search([x, y, z], 1)
|
| 790 |
+
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
|
| 791 |
+
GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}
|
| 792 |
+
|
| 793 |
+
Find a list of identities that only equal to 1:
|
| 794 |
+
|
| 795 |
+
>>> bfs_identity_search([x, y, z], 1, identity_only=True)
|
| 796 |
+
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
|
| 797 |
+
GateIdentity(Z(0), Z(0))}
|
| 798 |
+
"""
|
| 799 |
+
|
| 800 |
+
if max_depth is None or max_depth <= 0:
|
| 801 |
+
max_depth = len(gate_list)
|
| 802 |
+
|
| 803 |
+
id_only = identity_only
|
| 804 |
+
|
| 805 |
+
# Start with an empty sequence (implicitly contains an IdentityGate)
|
| 806 |
+
queue = deque([()])
|
| 807 |
+
|
| 808 |
+
# Create an empty set of gate identities
|
| 809 |
+
ids = set()
|
| 810 |
+
|
| 811 |
+
# Begin searching for gate identities in given space.
|
| 812 |
+
while (len(queue) > 0):
|
| 813 |
+
current_circuit = queue.popleft()
|
| 814 |
+
|
| 815 |
+
for next_gate in gate_list:
|
| 816 |
+
new_circuit = current_circuit + (next_gate,)
|
| 817 |
+
|
| 818 |
+
# Determines if a (strict) subcircuit is a scalar matrix
|
| 819 |
+
circuit_reducible = is_reducible(new_circuit, nqubits,
|
| 820 |
+
1, len(new_circuit))
|
| 821 |
+
|
| 822 |
+
# In many cases when the matrix is a scalar value,
|
| 823 |
+
# the evaluated matrix will actually be an integer
|
| 824 |
+
if (is_scalar_matrix(new_circuit, nqubits, id_only) and
|
| 825 |
+
not is_degenerate(ids, new_circuit) and
|
| 826 |
+
not circuit_reducible):
|
| 827 |
+
ids.add(GateIdentity(*new_circuit))
|
| 828 |
+
|
| 829 |
+
elif (len(new_circuit) < max_depth and
|
| 830 |
+
not circuit_reducible):
|
| 831 |
+
queue.append(new_circuit)
|
| 832 |
+
|
| 833 |
+
return ids
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def random_identity_search(gate_list, numgates, nqubits):
|
| 837 |
+
"""Randomly selects numgates from gate_list and checks if it is
|
| 838 |
+
a gate identity.
|
| 839 |
+
|
| 840 |
+
If the circuit is a gate identity, the circuit is returned;
|
| 841 |
+
Otherwise, None is returned.
|
| 842 |
+
"""
|
| 843 |
+
|
| 844 |
+
gate_size = len(gate_list)
|
| 845 |
+
circuit = ()
|
| 846 |
+
|
| 847 |
+
for i in range(numgates):
|
| 848 |
+
next_gate = gate_list[randint(0, gate_size - 1)]
|
| 849 |
+
circuit = circuit + (next_gate,)
|
| 850 |
+
|
| 851 |
+
is_scalar = is_scalar_matrix(circuit, nqubits, False)
|
| 852 |
+
|
| 853 |
+
return circuit if is_scalar else None
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/operator.py
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Quantum mechanical operators.
|
| 2 |
+
|
| 3 |
+
TODO:
|
| 4 |
+
|
| 5 |
+
* Fix early 0 in apply_operators.
|
| 6 |
+
* Debug and test apply_operators.
|
| 7 |
+
* Get cse working with classes in this file.
|
| 8 |
+
* Doctests and documentation of special methods for InnerProduct, Commutator,
|
| 9 |
+
AntiCommutator, represent, apply_operators.
|
| 10 |
+
"""
|
| 11 |
+
from typing import Optional
|
| 12 |
+
|
| 13 |
+
from sympy.core.add import Add
|
| 14 |
+
from sympy.core.expr import Expr
|
| 15 |
+
from sympy.core.function import (Derivative, expand)
|
| 16 |
+
from sympy.core.mul import Mul
|
| 17 |
+
from sympy.core.numbers import oo
|
| 18 |
+
from sympy.core.singleton import S
|
| 19 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
| 20 |
+
from sympy.physics.quantum.dagger import Dagger
|
| 21 |
+
from sympy.physics.quantum.qexpr import QExpr, dispatch_method
|
| 22 |
+
from sympy.matrices import eye
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
'Operator',
|
| 26 |
+
'HermitianOperator',
|
| 27 |
+
'UnitaryOperator',
|
| 28 |
+
'IdentityOperator',
|
| 29 |
+
'OuterProduct',
|
| 30 |
+
'DifferentialOperator'
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
#-----------------------------------------------------------------------------
|
| 34 |
+
# Operators and outer products
|
| 35 |
+
#-----------------------------------------------------------------------------
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Operator(QExpr):
|
| 39 |
+
"""Base class for non-commuting quantum operators.
|
| 40 |
+
|
| 41 |
+
An operator maps between quantum states [1]_. In quantum mechanics,
|
| 42 |
+
observables (including, but not limited to, measured physical values) are
|
| 43 |
+
represented as Hermitian operators [2]_.
|
| 44 |
+
|
| 45 |
+
Parameters
|
| 46 |
+
==========
|
| 47 |
+
|
| 48 |
+
args : tuple
|
| 49 |
+
The list of numbers or parameters that uniquely specify the
|
| 50 |
+
operator. For time-dependent operators, this will include the time.
|
| 51 |
+
|
| 52 |
+
Examples
|
| 53 |
+
========
|
| 54 |
+
|
| 55 |
+
Create an operator and examine its attributes::
|
| 56 |
+
|
| 57 |
+
>>> from sympy.physics.quantum import Operator
|
| 58 |
+
>>> from sympy import I
|
| 59 |
+
>>> A = Operator('A')
|
| 60 |
+
>>> A
|
| 61 |
+
A
|
| 62 |
+
>>> A.hilbert_space
|
| 63 |
+
H
|
| 64 |
+
>>> A.label
|
| 65 |
+
(A,)
|
| 66 |
+
>>> A.is_commutative
|
| 67 |
+
False
|
| 68 |
+
|
| 69 |
+
Create another operator and do some arithmetic operations::
|
| 70 |
+
|
| 71 |
+
>>> B = Operator('B')
|
| 72 |
+
>>> C = 2*A*A + I*B
|
| 73 |
+
>>> C
|
| 74 |
+
2*A**2 + I*B
|
| 75 |
+
|
| 76 |
+
Operators do not commute::
|
| 77 |
+
|
| 78 |
+
>>> A.is_commutative
|
| 79 |
+
False
|
| 80 |
+
>>> B.is_commutative
|
| 81 |
+
False
|
| 82 |
+
>>> A*B == B*A
|
| 83 |
+
False
|
| 84 |
+
|
| 85 |
+
Polymonials of operators respect the commutation properties::
|
| 86 |
+
|
| 87 |
+
>>> e = (A+B)**3
|
| 88 |
+
>>> e.expand()
|
| 89 |
+
A*B*A + A*B**2 + A**2*B + A**3 + B*A*B + B*A**2 + B**2*A + B**3
|
| 90 |
+
|
| 91 |
+
Operator inverses are handle symbolically::
|
| 92 |
+
|
| 93 |
+
>>> A.inv()
|
| 94 |
+
A**(-1)
|
| 95 |
+
>>> A*A.inv()
|
| 96 |
+
1
|
| 97 |
+
|
| 98 |
+
References
|
| 99 |
+
==========
|
| 100 |
+
|
| 101 |
+
.. [1] https://en.wikipedia.org/wiki/Operator_%28physics%29
|
| 102 |
+
.. [2] https://en.wikipedia.org/wiki/Observable
|
| 103 |
+
"""
|
| 104 |
+
is_hermitian: Optional[bool] = None
|
| 105 |
+
is_unitary: Optional[bool] = None
|
| 106 |
+
@classmethod
|
| 107 |
+
def default_args(self):
|
| 108 |
+
return ("O",)
|
| 109 |
+
|
| 110 |
+
#-------------------------------------------------------------------------
|
| 111 |
+
# Printing
|
| 112 |
+
#-------------------------------------------------------------------------
|
| 113 |
+
|
| 114 |
+
_label_separator = ','
|
| 115 |
+
|
| 116 |
+
def _print_operator_name(self, printer, *args):
|
| 117 |
+
return self.__class__.__name__
|
| 118 |
+
|
| 119 |
+
_print_operator_name_latex = _print_operator_name
|
| 120 |
+
|
| 121 |
+
def _print_operator_name_pretty(self, printer, *args):
|
| 122 |
+
return prettyForm(self.__class__.__name__)
|
| 123 |
+
|
| 124 |
+
def _print_contents(self, printer, *args):
|
| 125 |
+
if len(self.label) == 1:
|
| 126 |
+
return self._print_label(printer, *args)
|
| 127 |
+
else:
|
| 128 |
+
return '%s(%s)' % (
|
| 129 |
+
self._print_operator_name(printer, *args),
|
| 130 |
+
self._print_label(printer, *args)
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def _print_contents_pretty(self, printer, *args):
|
| 134 |
+
if len(self.label) == 1:
|
| 135 |
+
return self._print_label_pretty(printer, *args)
|
| 136 |
+
else:
|
| 137 |
+
pform = self._print_operator_name_pretty(printer, *args)
|
| 138 |
+
label_pform = self._print_label_pretty(printer, *args)
|
| 139 |
+
label_pform = prettyForm(
|
| 140 |
+
*label_pform.parens(left='(', right=')')
|
| 141 |
+
)
|
| 142 |
+
pform = prettyForm(*pform.right(label_pform))
|
| 143 |
+
return pform
|
| 144 |
+
|
| 145 |
+
def _print_contents_latex(self, printer, *args):
|
| 146 |
+
if len(self.label) == 1:
|
| 147 |
+
return self._print_label_latex(printer, *args)
|
| 148 |
+
else:
|
| 149 |
+
return r'%s\left(%s\right)' % (
|
| 150 |
+
self._print_operator_name_latex(printer, *args),
|
| 151 |
+
self._print_label_latex(printer, *args)
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
#-------------------------------------------------------------------------
|
| 155 |
+
# _eval_* methods
|
| 156 |
+
#-------------------------------------------------------------------------
|
| 157 |
+
|
| 158 |
+
def _eval_commutator(self, other, **options):
|
| 159 |
+
"""Evaluate [self, other] if known, return None if not known."""
|
| 160 |
+
return dispatch_method(self, '_eval_commutator', other, **options)
|
| 161 |
+
|
| 162 |
+
def _eval_anticommutator(self, other, **options):
|
| 163 |
+
"""Evaluate [self, other] if known."""
|
| 164 |
+
return dispatch_method(self, '_eval_anticommutator', other, **options)
|
| 165 |
+
|
| 166 |
+
#-------------------------------------------------------------------------
|
| 167 |
+
# Operator application
|
| 168 |
+
#-------------------------------------------------------------------------
|
| 169 |
+
|
| 170 |
+
def _apply_operator(self, ket, **options):
|
| 171 |
+
return dispatch_method(self, '_apply_operator', ket, **options)
|
| 172 |
+
|
| 173 |
+
def _apply_from_right_to(self, bra, **options):
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
+
def matrix_element(self, *args):
|
| 177 |
+
raise NotImplementedError('matrix_elements is not defined')
|
| 178 |
+
|
| 179 |
+
def inverse(self):
|
| 180 |
+
return self._eval_inverse()
|
| 181 |
+
|
| 182 |
+
inv = inverse
|
| 183 |
+
|
| 184 |
+
def _eval_inverse(self):
|
| 185 |
+
return self**(-1)
|
| 186 |
+
|
| 187 |
+
def __mul__(self, other):
|
| 188 |
+
|
| 189 |
+
if isinstance(other, IdentityOperator):
|
| 190 |
+
return self
|
| 191 |
+
|
| 192 |
+
return Mul(self, other)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class HermitianOperator(Operator):
|
| 196 |
+
"""A Hermitian operator that satisfies H == Dagger(H).
|
| 197 |
+
|
| 198 |
+
Parameters
|
| 199 |
+
==========
|
| 200 |
+
|
| 201 |
+
args : tuple
|
| 202 |
+
The list of numbers or parameters that uniquely specify the
|
| 203 |
+
operator. For time-dependent operators, this will include the time.
|
| 204 |
+
|
| 205 |
+
Examples
|
| 206 |
+
========
|
| 207 |
+
|
| 208 |
+
>>> from sympy.physics.quantum import Dagger, HermitianOperator
|
| 209 |
+
>>> H = HermitianOperator('H')
|
| 210 |
+
>>> Dagger(H)
|
| 211 |
+
H
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
is_hermitian = True
|
| 215 |
+
|
| 216 |
+
def _eval_inverse(self):
|
| 217 |
+
if isinstance(self, UnitaryOperator):
|
| 218 |
+
return self
|
| 219 |
+
else:
|
| 220 |
+
return Operator._eval_inverse(self)
|
| 221 |
+
|
| 222 |
+
def _eval_power(self, exp):
|
| 223 |
+
if isinstance(self, UnitaryOperator):
|
| 224 |
+
# so all eigenvalues of self are 1 or -1
|
| 225 |
+
if exp.is_even:
|
| 226 |
+
from sympy.core.singleton import S
|
| 227 |
+
return S.One # is identity, see Issue 24153.
|
| 228 |
+
elif exp.is_odd:
|
| 229 |
+
return self
|
| 230 |
+
# No simplification in all other cases
|
| 231 |
+
return Operator._eval_power(self, exp)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class UnitaryOperator(Operator):
|
| 235 |
+
"""A unitary operator that satisfies U*Dagger(U) == 1.
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
==========
|
| 239 |
+
|
| 240 |
+
args : tuple
|
| 241 |
+
The list of numbers or parameters that uniquely specify the
|
| 242 |
+
operator. For time-dependent operators, this will include the time.
|
| 243 |
+
|
| 244 |
+
Examples
|
| 245 |
+
========
|
| 246 |
+
|
| 247 |
+
>>> from sympy.physics.quantum import Dagger, UnitaryOperator
|
| 248 |
+
>>> U = UnitaryOperator('U')
|
| 249 |
+
>>> U*Dagger(U)
|
| 250 |
+
1
|
| 251 |
+
"""
|
| 252 |
+
is_unitary = True
|
| 253 |
+
def _eval_adjoint(self):
|
| 254 |
+
return self._eval_inverse()
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class IdentityOperator(Operator):
|
| 258 |
+
"""An identity operator I that satisfies op * I == I * op == op for any
|
| 259 |
+
operator op.
|
| 260 |
+
|
| 261 |
+
Parameters
|
| 262 |
+
==========
|
| 263 |
+
|
| 264 |
+
N : Integer
|
| 265 |
+
Optional parameter that specifies the dimension of the Hilbert space
|
| 266 |
+
of operator. This is used when generating a matrix representation.
|
| 267 |
+
|
| 268 |
+
Examples
|
| 269 |
+
========
|
| 270 |
+
|
| 271 |
+
>>> from sympy.physics.quantum import IdentityOperator
|
| 272 |
+
>>> IdentityOperator()
|
| 273 |
+
I
|
| 274 |
+
"""
|
| 275 |
+
is_hermitian = True
|
| 276 |
+
is_unitary = True
|
| 277 |
+
@property
|
| 278 |
+
def dimension(self):
|
| 279 |
+
return self.N
|
| 280 |
+
|
| 281 |
+
@classmethod
|
| 282 |
+
def default_args(self):
|
| 283 |
+
return (oo,)
|
| 284 |
+
|
| 285 |
+
def __init__(self, *args, **hints):
|
| 286 |
+
if not len(args) in (0, 1):
|
| 287 |
+
raise ValueError('0 or 1 parameters expected, got %s' % args)
|
| 288 |
+
|
| 289 |
+
self.N = args[0] if (len(args) == 1 and args[0]) else oo
|
| 290 |
+
|
| 291 |
+
def _eval_commutator(self, other, **hints):
|
| 292 |
+
return S.Zero
|
| 293 |
+
|
| 294 |
+
def _eval_anticommutator(self, other, **hints):
|
| 295 |
+
return 2 * other
|
| 296 |
+
|
| 297 |
+
def _eval_inverse(self):
|
| 298 |
+
return self
|
| 299 |
+
|
| 300 |
+
def _eval_adjoint(self):
|
| 301 |
+
return self
|
| 302 |
+
|
| 303 |
+
def _apply_operator(self, ket, **options):
|
| 304 |
+
return ket
|
| 305 |
+
|
| 306 |
+
def _apply_from_right_to(self, bra, **options):
|
| 307 |
+
return bra
|
| 308 |
+
|
| 309 |
+
def _eval_power(self, exp):
|
| 310 |
+
return self
|
| 311 |
+
|
| 312 |
+
def _print_contents(self, printer, *args):
|
| 313 |
+
return 'I'
|
| 314 |
+
|
| 315 |
+
def _print_contents_pretty(self, printer, *args):
|
| 316 |
+
return prettyForm('I')
|
| 317 |
+
|
| 318 |
+
def _print_contents_latex(self, printer, *args):
|
| 319 |
+
return r'{\mathcal{I}}'
|
| 320 |
+
|
| 321 |
+
def __mul__(self, other):
|
| 322 |
+
|
| 323 |
+
if isinstance(other, (Operator, Dagger)):
|
| 324 |
+
return other
|
| 325 |
+
|
| 326 |
+
return Mul(self, other)
|
| 327 |
+
|
| 328 |
+
def _represent_default_basis(self, **options):
|
| 329 |
+
if not self.N or self.N == oo:
|
| 330 |
+
raise NotImplementedError('Cannot represent infinite dimensional' +
|
| 331 |
+
' identity operator as a matrix')
|
| 332 |
+
|
| 333 |
+
format = options.get('format', 'sympy')
|
| 334 |
+
if format != 'sympy':
|
| 335 |
+
raise NotImplementedError('Representation in format ' +
|
| 336 |
+
'%s not implemented.' % format)
|
| 337 |
+
|
| 338 |
+
return eye(self.N)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class OuterProduct(Operator):
|
| 342 |
+
"""An unevaluated outer product between a ket and bra.
|
| 343 |
+
|
| 344 |
+
This constructs an outer product between any subclass of ``KetBase`` and
|
| 345 |
+
``BraBase`` as ``|a><b|``. An ``OuterProduct`` inherits from Operator as they act as
|
| 346 |
+
operators in quantum expressions. For reference see [1]_.
|
| 347 |
+
|
| 348 |
+
Parameters
|
| 349 |
+
==========
|
| 350 |
+
|
| 351 |
+
ket : KetBase
|
| 352 |
+
The ket on the left side of the outer product.
|
| 353 |
+
bar : BraBase
|
| 354 |
+
The bra on the right side of the outer product.
|
| 355 |
+
|
| 356 |
+
Examples
|
| 357 |
+
========
|
| 358 |
+
|
| 359 |
+
Create a simple outer product by hand and take its dagger::
|
| 360 |
+
|
| 361 |
+
>>> from sympy.physics.quantum import Ket, Bra, OuterProduct, Dagger
|
| 362 |
+
>>> from sympy.physics.quantum import Operator
|
| 363 |
+
|
| 364 |
+
>>> k = Ket('k')
|
| 365 |
+
>>> b = Bra('b')
|
| 366 |
+
>>> op = OuterProduct(k, b)
|
| 367 |
+
>>> op
|
| 368 |
+
|k><b|
|
| 369 |
+
>>> op.hilbert_space
|
| 370 |
+
H
|
| 371 |
+
>>> op.ket
|
| 372 |
+
|k>
|
| 373 |
+
>>> op.bra
|
| 374 |
+
<b|
|
| 375 |
+
>>> Dagger(op)
|
| 376 |
+
|b><k|
|
| 377 |
+
|
| 378 |
+
In simple products of kets and bras outer products will be automatically
|
| 379 |
+
identified and created::
|
| 380 |
+
|
| 381 |
+
>>> k*b
|
| 382 |
+
|k><b|
|
| 383 |
+
|
| 384 |
+
But in more complex expressions, outer products are not automatically
|
| 385 |
+
created::
|
| 386 |
+
|
| 387 |
+
>>> A = Operator('A')
|
| 388 |
+
>>> A*k*b
|
| 389 |
+
A*|k>*<b|
|
| 390 |
+
|
| 391 |
+
A user can force the creation of an outer product in a complex expression
|
| 392 |
+
by using parentheses to group the ket and bra::
|
| 393 |
+
|
| 394 |
+
>>> A*(k*b)
|
| 395 |
+
A*|k><b|
|
| 396 |
+
|
| 397 |
+
References
|
| 398 |
+
==========
|
| 399 |
+
|
| 400 |
+
.. [1] https://en.wikipedia.org/wiki/Outer_product
|
| 401 |
+
"""
|
| 402 |
+
is_commutative = False
|
| 403 |
+
|
| 404 |
+
def __new__(cls, *args, **old_assumptions):
|
| 405 |
+
from sympy.physics.quantum.state import KetBase, BraBase
|
| 406 |
+
|
| 407 |
+
if len(args) != 2:
|
| 408 |
+
raise ValueError('2 parameters expected, got %d' % len(args))
|
| 409 |
+
|
| 410 |
+
ket_expr = expand(args[0])
|
| 411 |
+
bra_expr = expand(args[1])
|
| 412 |
+
|
| 413 |
+
if (isinstance(ket_expr, (KetBase, Mul)) and
|
| 414 |
+
isinstance(bra_expr, (BraBase, Mul))):
|
| 415 |
+
ket_c, kets = ket_expr.args_cnc()
|
| 416 |
+
bra_c, bras = bra_expr.args_cnc()
|
| 417 |
+
|
| 418 |
+
if len(kets) != 1 or not isinstance(kets[0], KetBase):
|
| 419 |
+
raise TypeError('KetBase subclass expected'
|
| 420 |
+
', got: %r' % Mul(*kets))
|
| 421 |
+
|
| 422 |
+
if len(bras) != 1 or not isinstance(bras[0], BraBase):
|
| 423 |
+
raise TypeError('BraBase subclass expected'
|
| 424 |
+
', got: %r' % Mul(*bras))
|
| 425 |
+
|
| 426 |
+
if not kets[0].dual_class() == bras[0].__class__:
|
| 427 |
+
raise TypeError(
|
| 428 |
+
'ket and bra are not dual classes: %r, %r' %
|
| 429 |
+
(kets[0].__class__, bras[0].__class__)
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
# TODO: make sure the hilbert spaces of the bra and ket are
|
| 433 |
+
# compatible
|
| 434 |
+
obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions)
|
| 435 |
+
obj.hilbert_space = kets[0].hilbert_space
|
| 436 |
+
return Mul(*(ket_c + bra_c)) * obj
|
| 437 |
+
|
| 438 |
+
op_terms = []
|
| 439 |
+
if isinstance(ket_expr, Add) and isinstance(bra_expr, Add):
|
| 440 |
+
for ket_term in ket_expr.args:
|
| 441 |
+
for bra_term in bra_expr.args:
|
| 442 |
+
op_terms.append(OuterProduct(ket_term, bra_term,
|
| 443 |
+
**old_assumptions))
|
| 444 |
+
elif isinstance(ket_expr, Add):
|
| 445 |
+
for ket_term in ket_expr.args:
|
| 446 |
+
op_terms.append(OuterProduct(ket_term, bra_expr,
|
| 447 |
+
**old_assumptions))
|
| 448 |
+
elif isinstance(bra_expr, Add):
|
| 449 |
+
for bra_term in bra_expr.args:
|
| 450 |
+
op_terms.append(OuterProduct(ket_expr, bra_term,
|
| 451 |
+
**old_assumptions))
|
| 452 |
+
else:
|
| 453 |
+
raise TypeError(
|
| 454 |
+
'Expected ket and bra expression, got: %r, %r' %
|
| 455 |
+
(ket_expr, bra_expr)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
return Add(*op_terms)
|
| 459 |
+
|
| 460 |
+
@property
|
| 461 |
+
def ket(self):
|
| 462 |
+
"""Return the ket on the left side of the outer product."""
|
| 463 |
+
return self.args[0]
|
| 464 |
+
|
| 465 |
+
@property
|
| 466 |
+
def bra(self):
|
| 467 |
+
"""Return the bra on the right side of the outer product."""
|
| 468 |
+
return self.args[1]
|
| 469 |
+
|
| 470 |
+
def _eval_adjoint(self):
|
| 471 |
+
return OuterProduct(Dagger(self.bra), Dagger(self.ket))
|
| 472 |
+
|
| 473 |
+
def _sympystr(self, printer, *args):
|
| 474 |
+
return printer._print(self.ket) + printer._print(self.bra)
|
| 475 |
+
|
| 476 |
+
def _sympyrepr(self, printer, *args):
|
| 477 |
+
return '%s(%s,%s)' % (self.__class__.__name__,
|
| 478 |
+
printer._print(self.ket, *args), printer._print(self.bra, *args))
|
| 479 |
+
|
| 480 |
+
def _pretty(self, printer, *args):
|
| 481 |
+
pform = self.ket._pretty(printer, *args)
|
| 482 |
+
return prettyForm(*pform.right(self.bra._pretty(printer, *args)))
|
| 483 |
+
|
| 484 |
+
def _latex(self, printer, *args):
|
| 485 |
+
k = printer._print(self.ket, *args)
|
| 486 |
+
b = printer._print(self.bra, *args)
|
| 487 |
+
return k + b
|
| 488 |
+
|
| 489 |
+
def _represent(self, **options):
|
| 490 |
+
k = self.ket._represent(**options)
|
| 491 |
+
b = self.bra._represent(**options)
|
| 492 |
+
return k*b
|
| 493 |
+
|
| 494 |
+
def _eval_trace(self, **kwargs):
|
| 495 |
+
# TODO if operands are tensorproducts this may be will be handled
|
| 496 |
+
# differently.
|
| 497 |
+
|
| 498 |
+
return self.ket._eval_trace(self.bra, **kwargs)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
class DifferentialOperator(Operator):
|
| 502 |
+
"""An operator for representing the differential operator, i.e. d/dx
|
| 503 |
+
|
| 504 |
+
It is initialized by passing two arguments. The first is an arbitrary
|
| 505 |
+
expression that involves a function, such as ``Derivative(f(x), x)``. The
|
| 506 |
+
second is the function (e.g. ``f(x)``) which we are to replace with the
|
| 507 |
+
``Wavefunction`` that this ``DifferentialOperator`` is applied to.
|
| 508 |
+
|
| 509 |
+
Parameters
|
| 510 |
+
==========
|
| 511 |
+
|
| 512 |
+
expr : Expr
|
| 513 |
+
The arbitrary expression which the appropriate Wavefunction is to be
|
| 514 |
+
substituted into
|
| 515 |
+
|
| 516 |
+
func : Expr
|
| 517 |
+
A function (e.g. f(x)) which is to be replaced with the appropriate
|
| 518 |
+
Wavefunction when this DifferentialOperator is applied
|
| 519 |
+
|
| 520 |
+
Examples
|
| 521 |
+
========
|
| 522 |
+
|
| 523 |
+
You can define a completely arbitrary expression and specify where the
|
| 524 |
+
Wavefunction is to be substituted
|
| 525 |
+
|
| 526 |
+
>>> from sympy import Derivative, Function, Symbol
|
| 527 |
+
>>> from sympy.physics.quantum.operator import DifferentialOperator
|
| 528 |
+
>>> from sympy.physics.quantum.state import Wavefunction
|
| 529 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
| 530 |
+
>>> f = Function('f')
|
| 531 |
+
>>> x = Symbol('x')
|
| 532 |
+
>>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
|
| 533 |
+
>>> w = Wavefunction(x**2, x)
|
| 534 |
+
>>> d.function
|
| 535 |
+
f(x)
|
| 536 |
+
>>> d.variables
|
| 537 |
+
(x,)
|
| 538 |
+
>>> qapply(d*w)
|
| 539 |
+
Wavefunction(2, x)
|
| 540 |
+
|
| 541 |
+
"""
|
| 542 |
+
|
| 543 |
+
@property
|
| 544 |
+
def variables(self):
|
| 545 |
+
"""
|
| 546 |
+
Returns the variables with which the function in the specified
|
| 547 |
+
arbitrary expression is evaluated
|
| 548 |
+
|
| 549 |
+
Examples
|
| 550 |
+
========
|
| 551 |
+
|
| 552 |
+
>>> from sympy.physics.quantum.operator import DifferentialOperator
|
| 553 |
+
>>> from sympy import Symbol, Function, Derivative
|
| 554 |
+
>>> x = Symbol('x')
|
| 555 |
+
>>> f = Function('f')
|
| 556 |
+
>>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
|
| 557 |
+
>>> d.variables
|
| 558 |
+
(x,)
|
| 559 |
+
>>> y = Symbol('y')
|
| 560 |
+
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
|
| 561 |
+
... Derivative(f(x, y), y), f(x, y))
|
| 562 |
+
>>> d.variables
|
| 563 |
+
(x, y)
|
| 564 |
+
"""
|
| 565 |
+
|
| 566 |
+
return self.args[-1].args
|
| 567 |
+
|
| 568 |
+
@property
|
| 569 |
+
def function(self):
|
| 570 |
+
"""
|
| 571 |
+
Returns the function which is to be replaced with the Wavefunction
|
| 572 |
+
|
| 573 |
+
Examples
|
| 574 |
+
========
|
| 575 |
+
|
| 576 |
+
>>> from sympy.physics.quantum.operator import DifferentialOperator
|
| 577 |
+
>>> from sympy import Function, Symbol, Derivative
|
| 578 |
+
>>> x = Symbol('x')
|
| 579 |
+
>>> f = Function('f')
|
| 580 |
+
>>> d = DifferentialOperator(Derivative(f(x), x), f(x))
|
| 581 |
+
>>> d.function
|
| 582 |
+
f(x)
|
| 583 |
+
>>> y = Symbol('y')
|
| 584 |
+
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
|
| 585 |
+
... Derivative(f(x, y), y), f(x, y))
|
| 586 |
+
>>> d.function
|
| 587 |
+
f(x, y)
|
| 588 |
+
"""
|
| 589 |
+
|
| 590 |
+
return self.args[-1]
|
| 591 |
+
|
| 592 |
+
@property
|
| 593 |
+
def expr(self):
|
| 594 |
+
"""
|
| 595 |
+
Returns the arbitrary expression which is to have the Wavefunction
|
| 596 |
+
substituted into it
|
| 597 |
+
|
| 598 |
+
Examples
|
| 599 |
+
========
|
| 600 |
+
|
| 601 |
+
>>> from sympy.physics.quantum.operator import DifferentialOperator
|
| 602 |
+
>>> from sympy import Function, Symbol, Derivative
|
| 603 |
+
>>> x = Symbol('x')
|
| 604 |
+
>>> f = Function('f')
|
| 605 |
+
>>> d = DifferentialOperator(Derivative(f(x), x), f(x))
|
| 606 |
+
>>> d.expr
|
| 607 |
+
Derivative(f(x), x)
|
| 608 |
+
>>> y = Symbol('y')
|
| 609 |
+
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
|
| 610 |
+
... Derivative(f(x, y), y), f(x, y))
|
| 611 |
+
>>> d.expr
|
| 612 |
+
Derivative(f(x, y), x) + Derivative(f(x, y), y)
|
| 613 |
+
"""
|
| 614 |
+
|
| 615 |
+
return self.args[0]
|
| 616 |
+
|
| 617 |
+
@property
|
| 618 |
+
def free_symbols(self):
|
| 619 |
+
"""
|
| 620 |
+
Return the free symbols of the expression.
|
| 621 |
+
"""
|
| 622 |
+
|
| 623 |
+
return self.expr.free_symbols
|
| 624 |
+
|
| 625 |
+
def _apply_operator_Wavefunction(self, func, **options):
|
| 626 |
+
from sympy.physics.quantum.state import Wavefunction
|
| 627 |
+
var = self.variables
|
| 628 |
+
wf_vars = func.args[1:]
|
| 629 |
+
|
| 630 |
+
f = self.function
|
| 631 |
+
new_expr = self.expr.subs(f, func(*var))
|
| 632 |
+
new_expr = new_expr.doit()
|
| 633 |
+
|
| 634 |
+
return Wavefunction(new_expr, *wf_vars)
|
| 635 |
+
|
| 636 |
+
def _eval_derivative(self, symbol):
|
| 637 |
+
new_expr = Derivative(self.expr, symbol)
|
| 638 |
+
return DifferentialOperator(new_expr, self.args[-1])
|
| 639 |
+
|
| 640 |
+
#-------------------------------------------------------------------------
|
| 641 |
+
# Printing
|
| 642 |
+
#-------------------------------------------------------------------------
|
| 643 |
+
|
| 644 |
+
def _print(self, printer, *args):
|
| 645 |
+
return '%s(%s)' % (
|
| 646 |
+
self._print_operator_name(printer, *args),
|
| 647 |
+
self._print_label(printer, *args)
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
def _print_pretty(self, printer, *args):
|
| 651 |
+
pform = self._print_operator_name_pretty(printer, *args)
|
| 652 |
+
label_pform = self._print_label_pretty(printer, *args)
|
| 653 |
+
label_pform = prettyForm(
|
| 654 |
+
*label_pform.parens(left='(', right=')')
|
| 655 |
+
)
|
| 656 |
+
pform = prettyForm(*pform.right(label_pform))
|
| 657 |
+
return pform
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/shor.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shor's algorithm and helper functions.
|
| 2 |
+
|
| 3 |
+
Todo:
|
| 4 |
+
|
| 5 |
+
* Get the CMod gate working again using the new Gate API.
|
| 6 |
+
* Fix everything.
|
| 7 |
+
* Update docstrings and reformat.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import math
|
| 11 |
+
import random
|
| 12 |
+
|
| 13 |
+
from sympy.core.mul import Mul
|
| 14 |
+
from sympy.core.singleton import S
|
| 15 |
+
from sympy.functions.elementary.exponential import log
|
| 16 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 17 |
+
from sympy.core.intfunc import igcd
|
| 18 |
+
from sympy.ntheory import continued_fraction_periodic as continued_fraction
|
| 19 |
+
from sympy.utilities.iterables import variations
|
| 20 |
+
|
| 21 |
+
from sympy.physics.quantum.gate import Gate
|
| 22 |
+
from sympy.physics.quantum.qubit import Qubit, measure_partial_oneshot
|
| 23 |
+
from sympy.physics.quantum.qapply import qapply
|
| 24 |
+
from sympy.physics.quantum.qft import QFT
|
| 25 |
+
from sympy.physics.quantum.qexpr import QuantumError
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class OrderFindingException(QuantumError):
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class CMod(Gate):
|
| 33 |
+
"""A controlled mod gate.
|
| 34 |
+
|
| 35 |
+
This is black box controlled Mod function for use by shor's algorithm.
|
| 36 |
+
TODO: implement a decompose property that returns how to do this in terms
|
| 37 |
+
of elementary gates
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
@classmethod
|
| 41 |
+
def _eval_args(cls, args):
|
| 42 |
+
# t = args[0]
|
| 43 |
+
# a = args[1]
|
| 44 |
+
# N = args[2]
|
| 45 |
+
raise NotImplementedError('The CMod gate has not been completed.')
|
| 46 |
+
|
| 47 |
+
@property
|
| 48 |
+
def t(self):
|
| 49 |
+
"""Size of 1/2 input register. First 1/2 holds output."""
|
| 50 |
+
return self.label[0]
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def a(self):
|
| 54 |
+
"""Base of the controlled mod function."""
|
| 55 |
+
return self.label[1]
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def N(self):
|
| 59 |
+
"""N is the type of modular arithmetic we are doing."""
|
| 60 |
+
return self.label[2]
|
| 61 |
+
|
| 62 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
| 63 |
+
"""
|
| 64 |
+
This directly calculates the controlled mod of the second half of
|
| 65 |
+
the register and puts it in the second
|
| 66 |
+
This will look pretty when we get Tensor Symbolically working
|
| 67 |
+
"""
|
| 68 |
+
n = 1
|
| 69 |
+
k = 0
|
| 70 |
+
# Determine the value stored in high memory.
|
| 71 |
+
for i in range(self.t):
|
| 72 |
+
k += n*qubits[self.t + i]
|
| 73 |
+
n *= 2
|
| 74 |
+
|
| 75 |
+
# The value to go in low memory will be out.
|
| 76 |
+
out = int(self.a**k % self.N)
|
| 77 |
+
|
| 78 |
+
# Create array for new qbit-ket which will have high memory unaffected
|
| 79 |
+
outarray = list(qubits.args[0][:self.t])
|
| 80 |
+
|
| 81 |
+
# Place out in low memory
|
| 82 |
+
for i in reversed(range(self.t)):
|
| 83 |
+
outarray.append((out >> i) & 1)
|
| 84 |
+
|
| 85 |
+
return Qubit(*outarray)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def shor(N):
|
| 89 |
+
"""This function implements Shor's factoring algorithm on the Integer N
|
| 90 |
+
|
| 91 |
+
The algorithm starts by picking a random number (a) and seeing if it is
|
| 92 |
+
coprime with N. If it is not, then the gcd of the two numbers is a factor
|
| 93 |
+
and we are done. Otherwise, it begins the period_finding subroutine which
|
| 94 |
+
finds the period of a in modulo N arithmetic. This period, if even, can
|
| 95 |
+
be used to calculate factors by taking a**(r/2)-1 and a**(r/2)+1.
|
| 96 |
+
These values are returned.
|
| 97 |
+
"""
|
| 98 |
+
a = random.randrange(N - 2) + 2
|
| 99 |
+
if igcd(N, a) != 1:
|
| 100 |
+
return igcd(N, a)
|
| 101 |
+
r = period_find(a, N)
|
| 102 |
+
if r % 2 == 1:
|
| 103 |
+
shor(N)
|
| 104 |
+
answer = (igcd(a**(r/2) - 1, N), igcd(a**(r/2) + 1, N))
|
| 105 |
+
return answer
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def getr(x, y, N):
|
| 109 |
+
fraction = continued_fraction(x, y)
|
| 110 |
+
# Now convert into r
|
| 111 |
+
total = ratioize(fraction, N)
|
| 112 |
+
return total
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def ratioize(list, N):
|
| 116 |
+
if list[0] > N:
|
| 117 |
+
return S.Zero
|
| 118 |
+
if len(list) == 1:
|
| 119 |
+
return list[0]
|
| 120 |
+
return list[0] + ratioize(list[1:], N)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def period_find(a, N):
|
| 124 |
+
"""Finds the period of a in modulo N arithmetic
|
| 125 |
+
|
| 126 |
+
This is quantum part of Shor's algorithm. It takes two registers,
|
| 127 |
+
puts first in superposition of states with Hadamards so: ``|k>|0>``
|
| 128 |
+
with k being all possible choices. It then does a controlled mod and
|
| 129 |
+
a QFT to determine the order of a.
|
| 130 |
+
"""
|
| 131 |
+
epsilon = .5
|
| 132 |
+
# picks out t's such that maintains accuracy within epsilon
|
| 133 |
+
t = int(2*math.ceil(log(N, 2)))
|
| 134 |
+
# make the first half of register be 0's |000...000>
|
| 135 |
+
start = [0 for x in range(t)]
|
| 136 |
+
# Put second half into superposition of states so we have |1>x|0> + |2>x|0> + ... |k>x>|0> + ... + |2**n-1>x|0>
|
| 137 |
+
factor = 1/sqrt(2**t)
|
| 138 |
+
qubits = 0
|
| 139 |
+
for arr in variations(range(2), t, repetition=True):
|
| 140 |
+
qbitArray = list(arr) + start
|
| 141 |
+
qubits = qubits + Qubit(*qbitArray)
|
| 142 |
+
circuit = (factor*qubits).expand()
|
| 143 |
+
# Controlled second half of register so that we have:
|
| 144 |
+
# |1>x|a**1 %N> + |2>x|a**2 %N> + ... + |k>x|a**k %N >+ ... + |2**n-1=k>x|a**k % n>
|
| 145 |
+
circuit = CMod(t, a, N)*circuit
|
| 146 |
+
# will measure first half of register giving one of the a**k%N's
|
| 147 |
+
|
| 148 |
+
circuit = qapply(circuit)
|
| 149 |
+
for i in range(t):
|
| 150 |
+
circuit = measure_partial_oneshot(circuit, i)
|
| 151 |
+
# Now apply Inverse Quantum Fourier Transform on the second half of the register
|
| 152 |
+
|
| 153 |
+
circuit = qapply(QFT(t, t*2).decompose()*circuit, floatingPoint=True)
|
| 154 |
+
for i in range(t):
|
| 155 |
+
circuit = measure_partial_oneshot(circuit, i + t)
|
| 156 |
+
if isinstance(circuit, Qubit):
|
| 157 |
+
register = circuit
|
| 158 |
+
elif isinstance(circuit, Mul):
|
| 159 |
+
register = circuit.args[-1]
|
| 160 |
+
else:
|
| 161 |
+
register = circuit.args[-1].args[-1]
|
| 162 |
+
|
| 163 |
+
n = 1
|
| 164 |
+
answer = 0
|
| 165 |
+
for i in range(len(register)/2):
|
| 166 |
+
answer += n*register[i + t]
|
| 167 |
+
n = n << 1
|
| 168 |
+
if answer == 0:
|
| 169 |
+
raise OrderFindingException(
|
| 170 |
+
"Order finder returned 0. Happens with chance %f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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Quantum mechanical angular momemtum."""
|
| 2 |
+
|
| 3 |
+
from sympy.concrete.summations import Sum
|
| 4 |
+
from sympy.core.add import Add
|
| 5 |
+
from sympy.core.containers import Tuple
|
| 6 |
+
from sympy.core.expr import Expr
|
| 7 |
+
from sympy.core.numbers import int_valued
|
| 8 |
+
from sympy.core.mul import Mul
|
| 9 |
+
from sympy.core.numbers import (I, Integer, Rational, pi)
|
| 10 |
+
from sympy.core.singleton import S
|
| 11 |
+
from sympy.core.symbol import (Dummy, symbols)
|
| 12 |
+
from sympy.core.sympify import sympify
|
| 13 |
+
from sympy.functions.combinatorial.factorials import (binomial, factorial)
|
| 14 |
+
from sympy.functions.elementary.exponential import exp
|
| 15 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 16 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 17 |
+
from sympy.simplify.simplify import simplify
|
| 18 |
+
from sympy.matrices import zeros
|
| 19 |
+
from sympy.printing.pretty.stringpict import prettyForm, stringPict
|
| 20 |
+
from sympy.printing.pretty.pretty_symbology import pretty_symbol
|
| 21 |
+
|
| 22 |
+
from sympy.physics.quantum.qexpr import QExpr
|
| 23 |
+
from sympy.physics.quantum.operator import (HermitianOperator, Operator,
|
| 24 |
+
UnitaryOperator)
|
| 25 |
+
from sympy.physics.quantum.state import Bra, Ket, State
|
| 26 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
| 27 |
+
from sympy.physics.quantum.constants import hbar
|
| 28 |
+
from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace
|
| 29 |
+
from sympy.physics.quantum.tensorproduct import TensorProduct
|
| 30 |
+
from sympy.physics.quantum.cg import CG
|
| 31 |
+
from sympy.physics.quantum.qapply import qapply
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
__all__ = [
|
| 35 |
+
'm_values',
|
| 36 |
+
'Jplus',
|
| 37 |
+
'Jminus',
|
| 38 |
+
'Jx',
|
| 39 |
+
'Jy',
|
| 40 |
+
'Jz',
|
| 41 |
+
'J2',
|
| 42 |
+
'Rotation',
|
| 43 |
+
'WignerD',
|
| 44 |
+
'JxKet',
|
| 45 |
+
'JxBra',
|
| 46 |
+
'JyKet',
|
| 47 |
+
'JyBra',
|
| 48 |
+
'JzKet',
|
| 49 |
+
'JzBra',
|
| 50 |
+
'JzOp',
|
| 51 |
+
'J2Op',
|
| 52 |
+
'JxKetCoupled',
|
| 53 |
+
'JxBraCoupled',
|
| 54 |
+
'JyKetCoupled',
|
| 55 |
+
'JyBraCoupled',
|
| 56 |
+
'JzKetCoupled',
|
| 57 |
+
'JzBraCoupled',
|
| 58 |
+
'couple',
|
| 59 |
+
'uncouple'
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def m_values(j):
|
| 64 |
+
j = sympify(j)
|
| 65 |
+
size = 2*j + 1
|
| 66 |
+
if not size.is_Integer or not size > 0:
|
| 67 |
+
raise ValueError(
|
| 68 |
+
'Only integer or half-integer values allowed for j, got: : %r' % j
|
| 69 |
+
)
|
| 70 |
+
return size, [j - i for i in range(int(2*j + 1))]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
#-----------------------------------------------------------------------------
|
| 74 |
+
# Spin Operators
|
| 75 |
+
#-----------------------------------------------------------------------------
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class SpinOpBase:
|
| 79 |
+
"""Base class for spin operators."""
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def _eval_hilbert_space(cls, label):
|
| 83 |
+
# We consider all j values so our space is infinite.
|
| 84 |
+
return ComplexSpace(S.Infinity)
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def name(self):
|
| 88 |
+
return self.args[0]
|
| 89 |
+
|
| 90 |
+
def _print_contents(self, printer, *args):
|
| 91 |
+
return '%s%s' % (self.name, self._coord)
|
| 92 |
+
|
| 93 |
+
def _print_contents_pretty(self, printer, *args):
|
| 94 |
+
a = stringPict(str(self.name))
|
| 95 |
+
b = stringPict(self._coord)
|
| 96 |
+
return self._print_subscript_pretty(a, b)
|
| 97 |
+
|
| 98 |
+
def _print_contents_latex(self, printer, *args):
|
| 99 |
+
return r'%s_%s' % ((self.name, self._coord))
|
| 100 |
+
|
| 101 |
+
def _represent_base(self, basis, **options):
|
| 102 |
+
j = options.get('j', S.Half)
|
| 103 |
+
size, mvals = m_values(j)
|
| 104 |
+
result = zeros(size, size)
|
| 105 |
+
for p in range(size):
|
| 106 |
+
for q in range(size):
|
| 107 |
+
me = self.matrix_element(j, mvals[p], j, mvals[q])
|
| 108 |
+
result[p, q] = me
|
| 109 |
+
return result
|
| 110 |
+
|
| 111 |
+
def _apply_op(self, ket, orig_basis, **options):
|
| 112 |
+
state = ket.rewrite(self.basis)
|
| 113 |
+
# If the state has only one term
|
| 114 |
+
if isinstance(state, State):
|
| 115 |
+
ret = (hbar*state.m)*state
|
| 116 |
+
# state is a linear combination of states
|
| 117 |
+
elif isinstance(state, Sum):
|
| 118 |
+
ret = self._apply_operator_Sum(state, **options)
|
| 119 |
+
else:
|
| 120 |
+
ret = qapply(self*state)
|
| 121 |
+
if ret == self*state:
|
| 122 |
+
raise NotImplementedError
|
| 123 |
+
return ret.rewrite(orig_basis)
|
| 124 |
+
|
| 125 |
+
def _apply_operator_JxKet(self, ket, **options):
|
| 126 |
+
return self._apply_op(ket, 'Jx', **options)
|
| 127 |
+
|
| 128 |
+
def _apply_operator_JxKetCoupled(self, ket, **options):
|
| 129 |
+
return self._apply_op(ket, 'Jx', **options)
|
| 130 |
+
|
| 131 |
+
def _apply_operator_JyKet(self, ket, **options):
|
| 132 |
+
return self._apply_op(ket, 'Jy', **options)
|
| 133 |
+
|
| 134 |
+
def _apply_operator_JyKetCoupled(self, ket, **options):
|
| 135 |
+
return self._apply_op(ket, 'Jy', **options)
|
| 136 |
+
|
| 137 |
+
def _apply_operator_JzKet(self, ket, **options):
|
| 138 |
+
return self._apply_op(ket, 'Jz', **options)
|
| 139 |
+
|
| 140 |
+
def _apply_operator_JzKetCoupled(self, ket, **options):
|
| 141 |
+
return self._apply_op(ket, 'Jz', **options)
|
| 142 |
+
|
| 143 |
+
def _apply_operator_TensorProduct(self, tp, **options):
|
| 144 |
+
# Uncoupling operator is only easily found for coordinate basis spin operators
|
| 145 |
+
# TODO: add methods for uncoupling operators
|
| 146 |
+
if not isinstance(self, (JxOp, JyOp, JzOp)):
|
| 147 |
+
raise NotImplementedError
|
| 148 |
+
result = []
|
| 149 |
+
for n in range(len(tp.args)):
|
| 150 |
+
arg = []
|
| 151 |
+
arg.extend(tp.args[:n])
|
| 152 |
+
arg.append(self._apply_operator(tp.args[n]))
|
| 153 |
+
arg.extend(tp.args[n + 1:])
|
| 154 |
+
result.append(tp.__class__(*arg))
|
| 155 |
+
return Add(*result).expand()
|
| 156 |
+
|
| 157 |
+
# TODO: move this to qapply_Mul
|
| 158 |
+
def _apply_operator_Sum(self, s, **options):
|
| 159 |
+
new_func = qapply(self*s.function)
|
| 160 |
+
if new_func == self*s.function:
|
| 161 |
+
raise NotImplementedError
|
| 162 |
+
return Sum(new_func, *s.limits)
|
| 163 |
+
|
| 164 |
+
def _eval_trace(self, **options):
|
| 165 |
+
#TODO: use options to use different j values
|
| 166 |
+
#For now eval at default basis
|
| 167 |
+
|
| 168 |
+
# is it efficient to represent each time
|
| 169 |
+
# to do a trace?
|
| 170 |
+
return self._represent_default_basis().trace()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class JplusOp(SpinOpBase, Operator):
|
| 174 |
+
"""The J+ operator."""
|
| 175 |
+
|
| 176 |
+
_coord = '+'
|
| 177 |
+
|
| 178 |
+
basis = 'Jz'
|
| 179 |
+
|
| 180 |
+
def _eval_commutator_JminusOp(self, other):
|
| 181 |
+
return 2*hbar*JzOp(self.name)
|
| 182 |
+
|
| 183 |
+
def _apply_operator_JzKet(self, ket, **options):
|
| 184 |
+
j = ket.j
|
| 185 |
+
m = ket.m
|
| 186 |
+
if m.is_Number and j.is_Number:
|
| 187 |
+
if m >= j:
|
| 188 |
+
return S.Zero
|
| 189 |
+
return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One)
|
| 190 |
+
|
| 191 |
+
def _apply_operator_JzKetCoupled(self, ket, **options):
|
| 192 |
+
j = ket.j
|
| 193 |
+
m = ket.m
|
| 194 |
+
jn = ket.jn
|
| 195 |
+
coupling = ket.coupling
|
| 196 |
+
if m.is_Number and j.is_Number:
|
| 197 |
+
if m >= j:
|
| 198 |
+
return S.Zero
|
| 199 |
+
return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling)
|
| 200 |
+
|
| 201 |
+
def matrix_element(self, j, m, jp, mp):
|
| 202 |
+
result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One))
|
| 203 |
+
result *= KroneckerDelta(m, mp + 1)
|
| 204 |
+
result *= KroneckerDelta(j, jp)
|
| 205 |
+
return result
|
| 206 |
+
|
| 207 |
+
def _represent_default_basis(self, **options):
|
| 208 |
+
return self._represent_JzOp(None, **options)
|
| 209 |
+
|
| 210 |
+
def _represent_JzOp(self, basis, **options):
|
| 211 |
+
return self._represent_base(basis, **options)
|
| 212 |
+
|
| 213 |
+
def _eval_rewrite_as_xyz(self, *args, **kwargs):
|
| 214 |
+
return JxOp(args[0]) + I*JyOp(args[0])
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class JminusOp(SpinOpBase, Operator):
|
| 218 |
+
"""The J- operator."""
|
| 219 |
+
|
| 220 |
+
_coord = '-'
|
| 221 |
+
|
| 222 |
+
basis = 'Jz'
|
| 223 |
+
|
| 224 |
+
def _apply_operator_JzKet(self, ket, **options):
|
| 225 |
+
j = ket.j
|
| 226 |
+
m = ket.m
|
| 227 |
+
if m.is_Number and j.is_Number:
|
| 228 |
+
if m <= -j:
|
| 229 |
+
return S.Zero
|
| 230 |
+
return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One)
|
| 231 |
+
|
| 232 |
+
def _apply_operator_JzKetCoupled(self, ket, **options):
|
| 233 |
+
j = ket.j
|
| 234 |
+
m = ket.m
|
| 235 |
+
jn = ket.jn
|
| 236 |
+
coupling = ket.coupling
|
| 237 |
+
if m.is_Number and j.is_Number:
|
| 238 |
+
if m <= -j:
|
| 239 |
+
return S.Zero
|
| 240 |
+
return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling)
|
| 241 |
+
|
| 242 |
+
def matrix_element(self, j, m, jp, mp):
|
| 243 |
+
result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One))
|
| 244 |
+
result *= KroneckerDelta(m, mp - 1)
|
| 245 |
+
result *= KroneckerDelta(j, jp)
|
| 246 |
+
return result
|
| 247 |
+
|
| 248 |
+
def _represent_default_basis(self, **options):
|
| 249 |
+
return self._represent_JzOp(None, **options)
|
| 250 |
+
|
| 251 |
+
def _represent_JzOp(self, basis, **options):
|
| 252 |
+
return self._represent_base(basis, **options)
|
| 253 |
+
|
| 254 |
+
def _eval_rewrite_as_xyz(self, *args, **kwargs):
|
| 255 |
+
return JxOp(args[0]) - I*JyOp(args[0])
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class JxOp(SpinOpBase, HermitianOperator):
|
| 259 |
+
"""The Jx operator."""
|
| 260 |
+
|
| 261 |
+
_coord = 'x'
|
| 262 |
+
|
| 263 |
+
basis = 'Jx'
|
| 264 |
+
|
| 265 |
+
def _eval_commutator_JyOp(self, other):
|
| 266 |
+
return I*hbar*JzOp(self.name)
|
| 267 |
+
|
| 268 |
+
def _eval_commutator_JzOp(self, other):
|
| 269 |
+
return -I*hbar*JyOp(self.name)
|
| 270 |
+
|
| 271 |
+
def _apply_operator_JzKet(self, ket, **options):
|
| 272 |
+
jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
|
| 273 |
+
jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
|
| 274 |
+
return (jp + jm)/Integer(2)
|
| 275 |
+
|
| 276 |
+
def _apply_operator_JzKetCoupled(self, ket, **options):
|
| 277 |
+
jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
|
| 278 |
+
jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
|
| 279 |
+
return (jp + jm)/Integer(2)
|
| 280 |
+
|
| 281 |
+
def _represent_default_basis(self, **options):
|
| 282 |
+
return self._represent_JzOp(None, **options)
|
| 283 |
+
|
| 284 |
+
def _represent_JzOp(self, basis, **options):
|
| 285 |
+
jp = JplusOp(self.name)._represent_JzOp(basis, **options)
|
| 286 |
+
jm = JminusOp(self.name)._represent_JzOp(basis, **options)
|
| 287 |
+
return (jp + jm)/Integer(2)
|
| 288 |
+
|
| 289 |
+
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
|
| 290 |
+
return (JplusOp(args[0]) + JminusOp(args[0]))/2
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class JyOp(SpinOpBase, HermitianOperator):
|
| 294 |
+
"""The Jy operator."""
|
| 295 |
+
|
| 296 |
+
_coord = 'y'
|
| 297 |
+
|
| 298 |
+
basis = 'Jy'
|
| 299 |
+
|
| 300 |
+
def _eval_commutator_JzOp(self, other):
|
| 301 |
+
return I*hbar*JxOp(self.name)
|
| 302 |
+
|
| 303 |
+
def _eval_commutator_JxOp(self, other):
|
| 304 |
+
return -I*hbar*J2Op(self.name)
|
| 305 |
+
|
| 306 |
+
def _apply_operator_JzKet(self, ket, **options):
|
| 307 |
+
jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
|
| 308 |
+
jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
|
| 309 |
+
return (jp - jm)/(Integer(2)*I)
|
| 310 |
+
|
| 311 |
+
def _apply_operator_JzKetCoupled(self, ket, **options):
|
| 312 |
+
jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
|
| 313 |
+
jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
|
| 314 |
+
return (jp - jm)/(Integer(2)*I)
|
| 315 |
+
|
| 316 |
+
def _represent_default_basis(self, **options):
|
| 317 |
+
return self._represent_JzOp(None, **options)
|
| 318 |
+
|
| 319 |
+
def _represent_JzOp(self, basis, **options):
|
| 320 |
+
jp = JplusOp(self.name)._represent_JzOp(basis, **options)
|
| 321 |
+
jm = JminusOp(self.name)._represent_JzOp(basis, **options)
|
| 322 |
+
return (jp - jm)/(Integer(2)*I)
|
| 323 |
+
|
| 324 |
+
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
|
| 325 |
+
return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class JzOp(SpinOpBase, HermitianOperator):
|
| 329 |
+
"""The Jz operator."""
|
| 330 |
+
|
| 331 |
+
_coord = 'z'
|
| 332 |
+
|
| 333 |
+
basis = 'Jz'
|
| 334 |
+
|
| 335 |
+
def _eval_commutator_JxOp(self, other):
|
| 336 |
+
return I*hbar*JyOp(self.name)
|
| 337 |
+
|
| 338 |
+
def _eval_commutator_JyOp(self, other):
|
| 339 |
+
return -I*hbar*JxOp(self.name)
|
| 340 |
+
|
| 341 |
+
def _eval_commutator_JplusOp(self, other):
|
| 342 |
+
return hbar*JplusOp(self.name)
|
| 343 |
+
|
| 344 |
+
def _eval_commutator_JminusOp(self, other):
|
| 345 |
+
return -hbar*JminusOp(self.name)
|
| 346 |
+
|
| 347 |
+
def matrix_element(self, j, m, jp, mp):
|
| 348 |
+
result = hbar*mp
|
| 349 |
+
result *= KroneckerDelta(m, mp)
|
| 350 |
+
result *= KroneckerDelta(j, jp)
|
| 351 |
+
return result
|
| 352 |
+
|
| 353 |
+
def _represent_default_basis(self, **options):
|
| 354 |
+
return self._represent_JzOp(None, **options)
|
| 355 |
+
|
| 356 |
+
def _represent_JzOp(self, basis, **options):
|
| 357 |
+
return self._represent_base(basis, **options)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class J2Op(SpinOpBase, HermitianOperator):
|
| 361 |
+
"""The J^2 operator."""
|
| 362 |
+
|
| 363 |
+
_coord = '2'
|
| 364 |
+
|
| 365 |
+
def _eval_commutator_JxOp(self, other):
|
| 366 |
+
return S.Zero
|
| 367 |
+
|
| 368 |
+
def _eval_commutator_JyOp(self, other):
|
| 369 |
+
return S.Zero
|
| 370 |
+
|
| 371 |
+
def _eval_commutator_JzOp(self, other):
|
| 372 |
+
return S.Zero
|
| 373 |
+
|
| 374 |
+
def _eval_commutator_JplusOp(self, other):
|
| 375 |
+
return S.Zero
|
| 376 |
+
|
| 377 |
+
def _eval_commutator_JminusOp(self, other):
|
| 378 |
+
return S.Zero
|
| 379 |
+
|
| 380 |
+
def _apply_operator_JxKet(self, ket, **options):
|
| 381 |
+
j = ket.j
|
| 382 |
+
return hbar**2*j*(j + 1)*ket
|
| 383 |
+
|
| 384 |
+
def _apply_operator_JxKetCoupled(self, ket, **options):
|
| 385 |
+
j = ket.j
|
| 386 |
+
return hbar**2*j*(j + 1)*ket
|
| 387 |
+
|
| 388 |
+
def _apply_operator_JyKet(self, ket, **options):
|
| 389 |
+
j = ket.j
|
| 390 |
+
return hbar**2*j*(j + 1)*ket
|
| 391 |
+
|
| 392 |
+
def _apply_operator_JyKetCoupled(self, ket, **options):
|
| 393 |
+
j = ket.j
|
| 394 |
+
return hbar**2*j*(j + 1)*ket
|
| 395 |
+
|
| 396 |
+
def _apply_operator_JzKet(self, ket, **options):
|
| 397 |
+
j = ket.j
|
| 398 |
+
return hbar**2*j*(j + 1)*ket
|
| 399 |
+
|
| 400 |
+
def _apply_operator_JzKetCoupled(self, ket, **options):
|
| 401 |
+
j = ket.j
|
| 402 |
+
return hbar**2*j*(j + 1)*ket
|
| 403 |
+
|
| 404 |
+
def matrix_element(self, j, m, jp, mp):
|
| 405 |
+
result = (hbar**2)*j*(j + 1)
|
| 406 |
+
result *= KroneckerDelta(m, mp)
|
| 407 |
+
result *= KroneckerDelta(j, jp)
|
| 408 |
+
return result
|
| 409 |
+
|
| 410 |
+
def _represent_default_basis(self, **options):
|
| 411 |
+
return self._represent_JzOp(None, **options)
|
| 412 |
+
|
| 413 |
+
def _represent_JzOp(self, basis, **options):
|
| 414 |
+
return self._represent_base(basis, **options)
|
| 415 |
+
|
| 416 |
+
def _print_contents_pretty(self, printer, *args):
|
| 417 |
+
a = prettyForm(str(self.name))
|
| 418 |
+
b = prettyForm('2')
|
| 419 |
+
return a**b
|
| 420 |
+
|
| 421 |
+
def _print_contents_latex(self, printer, *args):
|
| 422 |
+
return r'%s^2' % str(self.name)
|
| 423 |
+
|
| 424 |
+
def _eval_rewrite_as_xyz(self, *args, **kwargs):
|
| 425 |
+
return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2
|
| 426 |
+
|
| 427 |
+
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
|
| 428 |
+
a = args[0]
|
| 429 |
+
return JzOp(a)**2 + \
|
| 430 |
+
S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class Rotation(UnitaryOperator):
|
| 434 |
+
"""Wigner D operator in terms of Euler angles.
|
| 435 |
+
|
| 436 |
+
Defines the rotation operator in terms of the Euler angles defined by
|
| 437 |
+
the z-y-z convention for a passive transformation. That is the coordinate
|
| 438 |
+
axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
|
| 439 |
+
this new coordinate system is rotated about the new y'-axis, giving new
|
| 440 |
+
x''-y''-z'' axes. Then this new coordinate system is rotated about the
|
| 441 |
+
z''-axis. Conventions follow those laid out in [1]_.
|
| 442 |
+
|
| 443 |
+
Parameters
|
| 444 |
+
==========
|
| 445 |
+
|
| 446 |
+
alpha : Number, Symbol
|
| 447 |
+
First Euler Angle
|
| 448 |
+
beta : Number, Symbol
|
| 449 |
+
Second Euler angle
|
| 450 |
+
gamma : Number, Symbol
|
| 451 |
+
Third Euler angle
|
| 452 |
+
|
| 453 |
+
Examples
|
| 454 |
+
========
|
| 455 |
+
|
| 456 |
+
A simple example rotation operator:
|
| 457 |
+
|
| 458 |
+
>>> from sympy import pi
|
| 459 |
+
>>> from sympy.physics.quantum.spin import Rotation
|
| 460 |
+
>>> Rotation(pi, 0, pi/2)
|
| 461 |
+
R(pi,0,pi/2)
|
| 462 |
+
|
| 463 |
+
With symbolic Euler angles and calculating the inverse rotation operator:
|
| 464 |
+
|
| 465 |
+
>>> from sympy import symbols
|
| 466 |
+
>>> a, b, c = symbols('a b c')
|
| 467 |
+
>>> Rotation(a, b, c)
|
| 468 |
+
R(a,b,c)
|
| 469 |
+
>>> Rotation(a, b, c).inverse()
|
| 470 |
+
R(-c,-b,-a)
|
| 471 |
+
|
| 472 |
+
See Also
|
| 473 |
+
========
|
| 474 |
+
|
| 475 |
+
WignerD: Symbolic Wigner-D function
|
| 476 |
+
D: Wigner-D function
|
| 477 |
+
d: Wigner small-d function
|
| 478 |
+
|
| 479 |
+
References
|
| 480 |
+
==========
|
| 481 |
+
|
| 482 |
+
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
@classmethod
|
| 486 |
+
def _eval_args(cls, args):
|
| 487 |
+
args = QExpr._eval_args(args)
|
| 488 |
+
if len(args) != 3:
|
| 489 |
+
raise ValueError('3 Euler angles required, got: %r' % args)
|
| 490 |
+
return args
|
| 491 |
+
|
| 492 |
+
@classmethod
|
| 493 |
+
def _eval_hilbert_space(cls, label):
|
| 494 |
+
# We consider all j values so our space is infinite.
|
| 495 |
+
return ComplexSpace(S.Infinity)
|
| 496 |
+
|
| 497 |
+
@property
|
| 498 |
+
def alpha(self):
|
| 499 |
+
return self.label[0]
|
| 500 |
+
|
| 501 |
+
@property
|
| 502 |
+
def beta(self):
|
| 503 |
+
return self.label[1]
|
| 504 |
+
|
| 505 |
+
@property
|
| 506 |
+
def gamma(self):
|
| 507 |
+
return self.label[2]
|
| 508 |
+
|
| 509 |
+
def _print_operator_name(self, printer, *args):
|
| 510 |
+
return 'R'
|
| 511 |
+
|
| 512 |
+
def _print_operator_name_pretty(self, printer, *args):
|
| 513 |
+
if printer._use_unicode:
|
| 514 |
+
return prettyForm('\N{SCRIPT CAPITAL R}' + ' ')
|
| 515 |
+
else:
|
| 516 |
+
return prettyForm("R ")
|
| 517 |
+
|
| 518 |
+
def _print_operator_name_latex(self, printer, *args):
|
| 519 |
+
return r'\mathcal{R}'
|
| 520 |
+
|
| 521 |
+
def _eval_inverse(self):
|
| 522 |
+
return Rotation(-self.gamma, -self.beta, -self.alpha)
|
| 523 |
+
|
| 524 |
+
@classmethod
|
| 525 |
+
def D(cls, j, m, mp, alpha, beta, gamma):
|
| 526 |
+
"""Wigner D-function.
|
| 527 |
+
|
| 528 |
+
Returns an instance of the WignerD class corresponding to the Wigner-D
|
| 529 |
+
function specified by the parameters.
|
| 530 |
+
|
| 531 |
+
Parameters
|
| 532 |
+
===========
|
| 533 |
+
|
| 534 |
+
j : Number
|
| 535 |
+
Total angular momentum
|
| 536 |
+
m : Number
|
| 537 |
+
Eigenvalue of angular momentum along axis after rotation
|
| 538 |
+
mp : Number
|
| 539 |
+
Eigenvalue of angular momentum along rotated axis
|
| 540 |
+
alpha : Number, Symbol
|
| 541 |
+
First Euler angle of rotation
|
| 542 |
+
beta : Number, Symbol
|
| 543 |
+
Second Euler angle of rotation
|
| 544 |
+
gamma : Number, Symbol
|
| 545 |
+
Third Euler angle of rotation
|
| 546 |
+
|
| 547 |
+
Examples
|
| 548 |
+
========
|
| 549 |
+
|
| 550 |
+
Return the Wigner-D matrix element for a defined rotation, both
|
| 551 |
+
numerical and symbolic:
|
| 552 |
+
|
| 553 |
+
>>> from sympy.physics.quantum.spin import Rotation
|
| 554 |
+
>>> from sympy import pi, symbols
|
| 555 |
+
>>> alpha, beta, gamma = symbols('alpha beta gamma')
|
| 556 |
+
>>> Rotation.D(1, 1, 0,pi, pi/2,-pi)
|
| 557 |
+
WignerD(1, 1, 0, pi, pi/2, -pi)
|
| 558 |
+
|
| 559 |
+
See Also
|
| 560 |
+
========
|
| 561 |
+
|
| 562 |
+
WignerD: Symbolic Wigner-D function
|
| 563 |
+
|
| 564 |
+
"""
|
| 565 |
+
return WignerD(j, m, mp, alpha, beta, gamma)
|
| 566 |
+
|
| 567 |
+
@classmethod
|
| 568 |
+
def d(cls, j, m, mp, beta):
|
| 569 |
+
"""Wigner small-d function.
|
| 570 |
+
|
| 571 |
+
Returns an instance of the WignerD class corresponding to the Wigner-D
|
| 572 |
+
function specified by the parameters with the alpha and gamma angles
|
| 573 |
+
given as 0.
|
| 574 |
+
|
| 575 |
+
Parameters
|
| 576 |
+
===========
|
| 577 |
+
|
| 578 |
+
j : Number
|
| 579 |
+
Total angular momentum
|
| 580 |
+
m : Number
|
| 581 |
+
Eigenvalue of angular momentum along axis after rotation
|
| 582 |
+
mp : Number
|
| 583 |
+
Eigenvalue of angular momentum along rotated axis
|
| 584 |
+
beta : Number, Symbol
|
| 585 |
+
Second Euler angle of rotation
|
| 586 |
+
|
| 587 |
+
Examples
|
| 588 |
+
========
|
| 589 |
+
|
| 590 |
+
Return the Wigner-D matrix element for a defined rotation, both
|
| 591 |
+
numerical and symbolic:
|
| 592 |
+
|
| 593 |
+
>>> from sympy.physics.quantum.spin import Rotation
|
| 594 |
+
>>> from sympy import pi, symbols
|
| 595 |
+
>>> beta = symbols('beta')
|
| 596 |
+
>>> Rotation.d(1, 1, 0, pi/2)
|
| 597 |
+
WignerD(1, 1, 0, 0, pi/2, 0)
|
| 598 |
+
|
| 599 |
+
See Also
|
| 600 |
+
========
|
| 601 |
+
|
| 602 |
+
WignerD: Symbolic Wigner-D function
|
| 603 |
+
|
| 604 |
+
"""
|
| 605 |
+
return WignerD(j, m, mp, 0, beta, 0)
|
| 606 |
+
|
| 607 |
+
def matrix_element(self, j, m, jp, mp):
|
| 608 |
+
result = self.__class__.D(
|
| 609 |
+
jp, m, mp, self.alpha, self.beta, self.gamma
|
| 610 |
+
)
|
| 611 |
+
result *= KroneckerDelta(j, jp)
|
| 612 |
+
return result
|
| 613 |
+
|
| 614 |
+
def _represent_base(self, basis, **options):
|
| 615 |
+
j = sympify(options.get('j', S.Half))
|
| 616 |
+
# TODO: move evaluation up to represent function/implement elsewhere
|
| 617 |
+
evaluate = sympify(options.get('doit'))
|
| 618 |
+
size, mvals = m_values(j)
|
| 619 |
+
result = zeros(size, size)
|
| 620 |
+
for p in range(size):
|
| 621 |
+
for q in range(size):
|
| 622 |
+
me = self.matrix_element(j, mvals[p], j, mvals[q])
|
| 623 |
+
if evaluate:
|
| 624 |
+
result[p, q] = me.doit()
|
| 625 |
+
else:
|
| 626 |
+
result[p, q] = me
|
| 627 |
+
return result
|
| 628 |
+
|
| 629 |
+
def _represent_default_basis(self, **options):
|
| 630 |
+
return self._represent_JzOp(None, **options)
|
| 631 |
+
|
| 632 |
+
def _represent_JzOp(self, basis, **options):
|
| 633 |
+
return self._represent_base(basis, **options)
|
| 634 |
+
|
| 635 |
+
def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options):
|
| 636 |
+
a = self.alpha
|
| 637 |
+
b = self.beta
|
| 638 |
+
g = self.gamma
|
| 639 |
+
j = ket.j
|
| 640 |
+
m = ket.m
|
| 641 |
+
if j.is_number:
|
| 642 |
+
s = []
|
| 643 |
+
size = m_values(j)
|
| 644 |
+
sz = size[1]
|
| 645 |
+
for mp in sz:
|
| 646 |
+
r = Rotation.D(j, m, mp, a, b, g)
|
| 647 |
+
z = r.doit()
|
| 648 |
+
s.append(z*state(j, mp))
|
| 649 |
+
return Add(*s)
|
| 650 |
+
else:
|
| 651 |
+
if dummy:
|
| 652 |
+
mp = Dummy('mp')
|
| 653 |
+
else:
|
| 654 |
+
mp = symbols('mp')
|
| 655 |
+
return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j))
|
| 656 |
+
|
| 657 |
+
def _apply_operator_JxKet(self, ket, **options):
|
| 658 |
+
return self._apply_operator_uncoupled(JxKet, ket, **options)
|
| 659 |
+
|
| 660 |
+
def _apply_operator_JyKet(self, ket, **options):
|
| 661 |
+
return self._apply_operator_uncoupled(JyKet, ket, **options)
|
| 662 |
+
|
| 663 |
+
def _apply_operator_JzKet(self, ket, **options):
|
| 664 |
+
return self._apply_operator_uncoupled(JzKet, ket, **options)
|
| 665 |
+
|
| 666 |
+
def _apply_operator_coupled(self, state, ket, *, dummy=True, **options):
|
| 667 |
+
a = self.alpha
|
| 668 |
+
b = self.beta
|
| 669 |
+
g = self.gamma
|
| 670 |
+
j = ket.j
|
| 671 |
+
m = ket.m
|
| 672 |
+
jn = ket.jn
|
| 673 |
+
coupling = ket.coupling
|
| 674 |
+
if j.is_number:
|
| 675 |
+
s = []
|
| 676 |
+
size = m_values(j)
|
| 677 |
+
sz = size[1]
|
| 678 |
+
for mp in sz:
|
| 679 |
+
r = Rotation.D(j, m, mp, a, b, g)
|
| 680 |
+
z = r.doit()
|
| 681 |
+
s.append(z*state(j, mp, jn, coupling))
|
| 682 |
+
return Add(*s)
|
| 683 |
+
else:
|
| 684 |
+
if dummy:
|
| 685 |
+
mp = Dummy('mp')
|
| 686 |
+
else:
|
| 687 |
+
mp = symbols('mp')
|
| 688 |
+
return Sum(Rotation.D(j, m, mp, a, b, g)*state(
|
| 689 |
+
j, mp, jn, coupling), (mp, -j, j))
|
| 690 |
+
|
| 691 |
+
def _apply_operator_JxKetCoupled(self, ket, **options):
|
| 692 |
+
return self._apply_operator_coupled(JxKetCoupled, ket, **options)
|
| 693 |
+
|
| 694 |
+
def _apply_operator_JyKetCoupled(self, ket, **options):
|
| 695 |
+
return self._apply_operator_coupled(JyKetCoupled, ket, **options)
|
| 696 |
+
|
| 697 |
+
def _apply_operator_JzKetCoupled(self, ket, **options):
|
| 698 |
+
return self._apply_operator_coupled(JzKetCoupled, ket, **options)
|
| 699 |
+
|
| 700 |
+
class WignerD(Expr):
|
| 701 |
+
r"""Wigner-D function
|
| 702 |
+
|
| 703 |
+
The Wigner D-function gives the matrix elements of the rotation
|
| 704 |
+
operator in the jm-representation. For the Euler angles `\alpha`,
|
| 705 |
+
`\beta`, `\gamma`, the D-function is defined such that:
|
| 706 |
+
|
| 707 |
+
.. math ::
|
| 708 |
+
<j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma)
|
| 709 |
+
|
| 710 |
+
Where the rotation operator is as defined by the Rotation class [1]_.
|
| 711 |
+
|
| 712 |
+
The Wigner D-function defined in this way gives:
|
| 713 |
+
|
| 714 |
+
.. math ::
|
| 715 |
+
D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
|
| 716 |
+
|
| 717 |
+
Where d is the Wigner small-d function, which is given by Rotation.d.
|
| 718 |
+
|
| 719 |
+
The Wigner small-d function gives the component of the Wigner
|
| 720 |
+
D-function that is determined by the second Euler angle. That is the
|
| 721 |
+
Wigner D-function is:
|
| 722 |
+
|
| 723 |
+
.. math ::
|
| 724 |
+
D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
|
| 725 |
+
|
| 726 |
+
Where d is the small-d function. The Wigner D-function is given by
|
| 727 |
+
Rotation.D.
|
| 728 |
+
|
| 729 |
+
Note that to evaluate the D-function, the j, m and mp parameters must
|
| 730 |
+
be integer or half integer numbers.
|
| 731 |
+
|
| 732 |
+
Parameters
|
| 733 |
+
==========
|
| 734 |
+
|
| 735 |
+
j : Number
|
| 736 |
+
Total angular momentum
|
| 737 |
+
m : Number
|
| 738 |
+
Eigenvalue of angular momentum along axis after rotation
|
| 739 |
+
mp : Number
|
| 740 |
+
Eigenvalue of angular momentum along rotated axis
|
| 741 |
+
alpha : Number, Symbol
|
| 742 |
+
First Euler angle of rotation
|
| 743 |
+
beta : Number, Symbol
|
| 744 |
+
Second Euler angle of rotation
|
| 745 |
+
gamma : Number, Symbol
|
| 746 |
+
Third Euler angle of rotation
|
| 747 |
+
|
| 748 |
+
Examples
|
| 749 |
+
========
|
| 750 |
+
|
| 751 |
+
Evaluate the Wigner-D matrix elements of a simple rotation:
|
| 752 |
+
|
| 753 |
+
>>> from sympy.physics.quantum.spin import Rotation
|
| 754 |
+
>>> from sympy import pi
|
| 755 |
+
>>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0)
|
| 756 |
+
>>> rot
|
| 757 |
+
WignerD(1, 1, 0, pi, pi/2, 0)
|
| 758 |
+
>>> rot.doit()
|
| 759 |
+
sqrt(2)/2
|
| 760 |
+
|
| 761 |
+
Evaluate the Wigner-d matrix elements of a simple rotation
|
| 762 |
+
|
| 763 |
+
>>> rot = Rotation.d(1, 1, 0, pi/2)
|
| 764 |
+
>>> rot
|
| 765 |
+
WignerD(1, 1, 0, 0, pi/2, 0)
|
| 766 |
+
>>> rot.doit()
|
| 767 |
+
-sqrt(2)/2
|
| 768 |
+
|
| 769 |
+
See Also
|
| 770 |
+
========
|
| 771 |
+
|
| 772 |
+
Rotation: Rotation operator
|
| 773 |
+
|
| 774 |
+
References
|
| 775 |
+
==========
|
| 776 |
+
|
| 777 |
+
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
|
| 778 |
+
"""
|
| 779 |
+
|
| 780 |
+
is_commutative = True
|
| 781 |
+
|
| 782 |
+
def __new__(cls, *args, **hints):
|
| 783 |
+
if not len(args) == 6:
|
| 784 |
+
raise ValueError('6 parameters expected, got %s' % args)
|
| 785 |
+
args = sympify(args)
|
| 786 |
+
evaluate = hints.get('evaluate', False)
|
| 787 |
+
if evaluate:
|
| 788 |
+
return Expr.__new__(cls, *args)._eval_wignerd()
|
| 789 |
+
return Expr.__new__(cls, *args)
|
| 790 |
+
|
| 791 |
+
@property
|
| 792 |
+
def j(self):
|
| 793 |
+
return self.args[0]
|
| 794 |
+
|
| 795 |
+
@property
|
| 796 |
+
def m(self):
|
| 797 |
+
return self.args[1]
|
| 798 |
+
|
| 799 |
+
@property
|
| 800 |
+
def mp(self):
|
| 801 |
+
return self.args[2]
|
| 802 |
+
|
| 803 |
+
@property
|
| 804 |
+
def alpha(self):
|
| 805 |
+
return self.args[3]
|
| 806 |
+
|
| 807 |
+
@property
|
| 808 |
+
def beta(self):
|
| 809 |
+
return self.args[4]
|
| 810 |
+
|
| 811 |
+
@property
|
| 812 |
+
def gamma(self):
|
| 813 |
+
return self.args[5]
|
| 814 |
+
|
| 815 |
+
def _latex(self, printer, *args):
|
| 816 |
+
if self.alpha == 0 and self.gamma == 0:
|
| 817 |
+
return r'd^{%s}_{%s,%s}\left(%s\right)' % \
|
| 818 |
+
(
|
| 819 |
+
printer._print(self.j), printer._print(
|
| 820 |
+
self.m), printer._print(self.mp),
|
| 821 |
+
printer._print(self.beta) )
|
| 822 |
+
return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \
|
| 823 |
+
(
|
| 824 |
+
printer._print(
|
| 825 |
+
self.j), printer._print(self.m), printer._print(self.mp),
|
| 826 |
+
printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) )
|
| 827 |
+
|
| 828 |
+
def _pretty(self, printer, *args):
|
| 829 |
+
top = printer._print(self.j)
|
| 830 |
+
|
| 831 |
+
bot = printer._print(self.m)
|
| 832 |
+
bot = prettyForm(*bot.right(','))
|
| 833 |
+
bot = prettyForm(*bot.right(printer._print(self.mp)))
|
| 834 |
+
|
| 835 |
+
pad = max(top.width(), bot.width())
|
| 836 |
+
top = prettyForm(*top.left(' '))
|
| 837 |
+
bot = prettyForm(*bot.left(' '))
|
| 838 |
+
if pad > top.width():
|
| 839 |
+
top = prettyForm(*top.right(' '*(pad - top.width())))
|
| 840 |
+
if pad > bot.width():
|
| 841 |
+
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
|
| 842 |
+
if self.alpha == 0 and self.gamma == 0:
|
| 843 |
+
args = printer._print(self.beta)
|
| 844 |
+
s = stringPict('d' + ' '*pad)
|
| 845 |
+
else:
|
| 846 |
+
args = printer._print(self.alpha)
|
| 847 |
+
args = prettyForm(*args.right(','))
|
| 848 |
+
args = prettyForm(*args.right(printer._print(self.beta)))
|
| 849 |
+
args = prettyForm(*args.right(','))
|
| 850 |
+
args = prettyForm(*args.right(printer._print(self.gamma)))
|
| 851 |
+
|
| 852 |
+
s = stringPict('D' + ' '*pad)
|
| 853 |
+
|
| 854 |
+
args = prettyForm(*args.parens())
|
| 855 |
+
s = prettyForm(*s.above(top))
|
| 856 |
+
s = prettyForm(*s.below(bot))
|
| 857 |
+
s = prettyForm(*s.right(args))
|
| 858 |
+
return s
|
| 859 |
+
|
| 860 |
+
def doit(self, **hints):
|
| 861 |
+
hints['evaluate'] = True
|
| 862 |
+
return WignerD(*self.args, **hints)
|
| 863 |
+
|
| 864 |
+
def _eval_wignerd(self):
|
| 865 |
+
j = self.j
|
| 866 |
+
m = self.m
|
| 867 |
+
mp = self.mp
|
| 868 |
+
alpha = self.alpha
|
| 869 |
+
beta = self.beta
|
| 870 |
+
gamma = self.gamma
|
| 871 |
+
if alpha == 0 and beta == 0 and gamma == 0:
|
| 872 |
+
return KroneckerDelta(m, mp)
|
| 873 |
+
if not j.is_number:
|
| 874 |
+
raise ValueError(
|
| 875 |
+
'j parameter must be numerical to evaluate, got %s' % j)
|
| 876 |
+
r = 0
|
| 877 |
+
if beta == pi/2:
|
| 878 |
+
# Varshalovich Equation (5), Section 4.16, page 113, setting
|
| 879 |
+
# alpha=gamma=0.
|
| 880 |
+
for k in range(2*j + 1):
|
| 881 |
+
if k > j + mp or k > j - m or k < mp - m:
|
| 882 |
+
continue
|
| 883 |
+
r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp)
|
| 884 |
+
r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) *
|
| 885 |
+
factorial(j - m) / (factorial(j + mp)*factorial(j - mp)))
|
| 886 |
+
else:
|
| 887 |
+
# Varshalovich Equation(5), Section 4.7.2, page 87, where we set
|
| 888 |
+
# beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
|
| 889 |
+
# then we use the Eq. (1), Section 4.4. page 79, to simplify:
|
| 890 |
+
# d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta)
|
| 891 |
+
# This happens to be almost the same as in Eq.(10), Section 4.16,
|
| 892 |
+
# except that we need to substitute -mp for mp.
|
| 893 |
+
size, mvals = m_values(j)
|
| 894 |
+
for mpp in mvals:
|
| 895 |
+
r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\
|
| 896 |
+
Rotation.d(j, mpp, -mp, pi/2).doit()
|
| 897 |
+
# Empirical normalization factor so results match Varshalovich
|
| 898 |
+
# Tables 4.3-4.12
|
| 899 |
+
# Note that this exact normalization does not follow from the
|
| 900 |
+
# above equations
|
| 901 |
+
r = r*I**(2*j - m - mp)*(-1)**(2*m)
|
| 902 |
+
# Finally, simplify the whole expression
|
| 903 |
+
r = simplify(r)
|
| 904 |
+
r *= exp(-I*m*alpha)*exp(-I*mp*gamma)
|
| 905 |
+
return r
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
Jx = JxOp('J')
|
| 909 |
+
Jy = JyOp('J')
|
| 910 |
+
Jz = JzOp('J')
|
| 911 |
+
J2 = J2Op('J')
|
| 912 |
+
Jplus = JplusOp('J')
|
| 913 |
+
Jminus = JminusOp('J')
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
#-----------------------------------------------------------------------------
|
| 917 |
+
# Spin States
|
| 918 |
+
#-----------------------------------------------------------------------------
|
| 919 |
+
|
| 920 |
+
|
| 921 |
+
class SpinState(State):
|
| 922 |
+
"""Base class for angular momentum states."""
|
| 923 |
+
|
| 924 |
+
_label_separator = ','
|
| 925 |
+
|
| 926 |
+
def __new__(cls, j, m):
|
| 927 |
+
j = sympify(j)
|
| 928 |
+
m = sympify(m)
|
| 929 |
+
if j.is_number:
|
| 930 |
+
if 2*j != int(2*j):
|
| 931 |
+
raise ValueError(
|
| 932 |
+
'j must be integer or half-integer, got: %s' % j)
|
| 933 |
+
if j < 0:
|
| 934 |
+
raise ValueError('j must be >= 0, got: %s' % j)
|
| 935 |
+
if m.is_number:
|
| 936 |
+
if 2*m != int(2*m):
|
| 937 |
+
raise ValueError(
|
| 938 |
+
'm must be integer or half-integer, got: %s' % m)
|
| 939 |
+
if j.is_number and m.is_number:
|
| 940 |
+
if abs(m) > j:
|
| 941 |
+
raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m))
|
| 942 |
+
if int(j - m) != j - m:
|
| 943 |
+
raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m))
|
| 944 |
+
return State.__new__(cls, j, m)
|
| 945 |
+
|
| 946 |
+
@property
|
| 947 |
+
def j(self):
|
| 948 |
+
return self.label[0]
|
| 949 |
+
|
| 950 |
+
@property
|
| 951 |
+
def m(self):
|
| 952 |
+
return self.label[1]
|
| 953 |
+
|
| 954 |
+
@classmethod
|
| 955 |
+
def _eval_hilbert_space(cls, label):
|
| 956 |
+
return ComplexSpace(2*label[0] + 1)
|
| 957 |
+
|
| 958 |
+
def _represent_base(self, **options):
|
| 959 |
+
j = self.j
|
| 960 |
+
m = self.m
|
| 961 |
+
alpha = sympify(options.get('alpha', 0))
|
| 962 |
+
beta = sympify(options.get('beta', 0))
|
| 963 |
+
gamma = sympify(options.get('gamma', 0))
|
| 964 |
+
size, mvals = m_values(j)
|
| 965 |
+
result = zeros(size, 1)
|
| 966 |
+
# breaks finding angles on L930
|
| 967 |
+
for p, mval in enumerate(mvals):
|
| 968 |
+
if m.is_number:
|
| 969 |
+
result[p, 0] = Rotation.D(
|
| 970 |
+
self.j, mval, self.m, alpha, beta, gamma).doit()
|
| 971 |
+
else:
|
| 972 |
+
result[p, 0] = Rotation.D(self.j, mval,
|
| 973 |
+
self.m, alpha, beta, gamma)
|
| 974 |
+
return result
|
| 975 |
+
|
| 976 |
+
def _eval_rewrite_as_Jx(self, *args, **options):
|
| 977 |
+
if isinstance(self, Bra):
|
| 978 |
+
return self._rewrite_basis(Jx, JxBra, **options)
|
| 979 |
+
return self._rewrite_basis(Jx, JxKet, **options)
|
| 980 |
+
|
| 981 |
+
def _eval_rewrite_as_Jy(self, *args, **options):
|
| 982 |
+
if isinstance(self, Bra):
|
| 983 |
+
return self._rewrite_basis(Jy, JyBra, **options)
|
| 984 |
+
return self._rewrite_basis(Jy, JyKet, **options)
|
| 985 |
+
|
| 986 |
+
def _eval_rewrite_as_Jz(self, *args, **options):
|
| 987 |
+
if isinstance(self, Bra):
|
| 988 |
+
return self._rewrite_basis(Jz, JzBra, **options)
|
| 989 |
+
return self._rewrite_basis(Jz, JzKet, **options)
|
| 990 |
+
|
| 991 |
+
def _rewrite_basis(self, basis, evect, **options):
|
| 992 |
+
from sympy.physics.quantum.represent import represent
|
| 993 |
+
j = self.j
|
| 994 |
+
args = self.args[2:]
|
| 995 |
+
if j.is_number:
|
| 996 |
+
if isinstance(self, CoupledSpinState):
|
| 997 |
+
if j == int(j):
|
| 998 |
+
start = j**2
|
| 999 |
+
else:
|
| 1000 |
+
start = (2*j - 1)*(2*j + 1)/4
|
| 1001 |
+
else:
|
| 1002 |
+
start = 0
|
| 1003 |
+
vect = represent(self, basis=basis, **options)
|
| 1004 |
+
result = Add(
|
| 1005 |
+
*[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)])
|
| 1006 |
+
if isinstance(self, CoupledSpinState) and options.get('coupled') is False:
|
| 1007 |
+
return uncouple(result)
|
| 1008 |
+
return result
|
| 1009 |
+
else:
|
| 1010 |
+
i = 0
|
| 1011 |
+
mi = symbols('mi')
|
| 1012 |
+
# make sure not to introduce a symbol already in the state
|
| 1013 |
+
while self.subs(mi, 0) != self:
|
| 1014 |
+
i += 1
|
| 1015 |
+
mi = symbols('mi%d' % i)
|
| 1016 |
+
break
|
| 1017 |
+
# TODO: better way to get angles of rotation
|
| 1018 |
+
if isinstance(self, CoupledSpinState):
|
| 1019 |
+
test_args = (0, mi, (0, 0))
|
| 1020 |
+
else:
|
| 1021 |
+
test_args = (0, mi)
|
| 1022 |
+
if isinstance(self, Ket):
|
| 1023 |
+
angles = represent(
|
| 1024 |
+
self.__class__(*test_args), basis=basis)[0].args[3:6]
|
| 1025 |
+
else:
|
| 1026 |
+
angles = represent(self.__class__(
|
| 1027 |
+
*test_args), basis=basis)[0].args[0].args[3:6]
|
| 1028 |
+
if angles == (0, 0, 0):
|
| 1029 |
+
return self
|
| 1030 |
+
else:
|
| 1031 |
+
state = evect(j, mi, *args)
|
| 1032 |
+
lt = Rotation.D(j, mi, self.m, *angles)
|
| 1033 |
+
return Sum(lt*state, (mi, -j, j))
|
| 1034 |
+
|
| 1035 |
+
def _eval_innerproduct_JxBra(self, bra, **hints):
|
| 1036 |
+
result = KroneckerDelta(self.j, bra.j)
|
| 1037 |
+
if bra.dual_class() is not self.__class__:
|
| 1038 |
+
result *= self._represent_JxOp(None)[bra.j - bra.m]
|
| 1039 |
+
else:
|
| 1040 |
+
result *= KroneckerDelta(
|
| 1041 |
+
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
|
| 1042 |
+
return result
|
| 1043 |
+
|
| 1044 |
+
def _eval_innerproduct_JyBra(self, bra, **hints):
|
| 1045 |
+
result = KroneckerDelta(self.j, bra.j)
|
| 1046 |
+
if bra.dual_class() is not self.__class__:
|
| 1047 |
+
result *= self._represent_JyOp(None)[bra.j - bra.m]
|
| 1048 |
+
else:
|
| 1049 |
+
result *= KroneckerDelta(
|
| 1050 |
+
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
|
| 1051 |
+
return result
|
| 1052 |
+
|
| 1053 |
+
def _eval_innerproduct_JzBra(self, bra, **hints):
|
| 1054 |
+
result = KroneckerDelta(self.j, bra.j)
|
| 1055 |
+
if bra.dual_class() is not self.__class__:
|
| 1056 |
+
result *= self._represent_JzOp(None)[bra.j - bra.m]
|
| 1057 |
+
else:
|
| 1058 |
+
result *= KroneckerDelta(
|
| 1059 |
+
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
|
| 1060 |
+
return result
|
| 1061 |
+
|
| 1062 |
+
def _eval_trace(self, bra, **hints):
|
| 1063 |
+
|
| 1064 |
+
# One way to implement this method is to assume the basis set k is
|
| 1065 |
+
# passed.
|
| 1066 |
+
# Then we can apply the discrete form of Trace formula here
|
| 1067 |
+
# Tr(|i><j| ) = \Sum_k <k|i><j|k>
|
| 1068 |
+
#then we do qapply() on each each inner product and sum over them.
|
| 1069 |
+
|
| 1070 |
+
# OR
|
| 1071 |
+
|
| 1072 |
+
# Inner product of |i><j| = Trace(Outer Product).
|
| 1073 |
+
# we could just use this unless there are cases when this is not true
|
| 1074 |
+
|
| 1075 |
+
return (bra*self).doit()
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
class JxKet(SpinState, Ket):
|
| 1079 |
+
"""Eigenket of Jx.
|
| 1080 |
+
|
| 1081 |
+
See JzKet for the usage of spin eigenstates.
|
| 1082 |
+
|
| 1083 |
+
See Also
|
| 1084 |
+
========
|
| 1085 |
+
|
| 1086 |
+
JzKet: Usage of spin states
|
| 1087 |
+
|
| 1088 |
+
"""
|
| 1089 |
+
|
| 1090 |
+
@classmethod
|
| 1091 |
+
def dual_class(self):
|
| 1092 |
+
return JxBra
|
| 1093 |
+
|
| 1094 |
+
@classmethod
|
| 1095 |
+
def coupled_class(self):
|
| 1096 |
+
return JxKetCoupled
|
| 1097 |
+
|
| 1098 |
+
def _represent_default_basis(self, **options):
|
| 1099 |
+
return self._represent_JxOp(None, **options)
|
| 1100 |
+
|
| 1101 |
+
def _represent_JxOp(self, basis, **options):
|
| 1102 |
+
return self._represent_base(**options)
|
| 1103 |
+
|
| 1104 |
+
def _represent_JyOp(self, basis, **options):
|
| 1105 |
+
return self._represent_base(alpha=pi*Rational(3, 2), **options)
|
| 1106 |
+
|
| 1107 |
+
def _represent_JzOp(self, basis, **options):
|
| 1108 |
+
return self._represent_base(beta=pi/2, **options)
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
class JxBra(SpinState, Bra):
|
| 1112 |
+
"""Eigenbra of Jx.
|
| 1113 |
+
|
| 1114 |
+
See JzKet for the usage of spin eigenstates.
|
| 1115 |
+
|
| 1116 |
+
See Also
|
| 1117 |
+
========
|
| 1118 |
+
|
| 1119 |
+
JzKet: Usage of spin states
|
| 1120 |
+
|
| 1121 |
+
"""
|
| 1122 |
+
|
| 1123 |
+
@classmethod
|
| 1124 |
+
def dual_class(self):
|
| 1125 |
+
return JxKet
|
| 1126 |
+
|
| 1127 |
+
@classmethod
|
| 1128 |
+
def coupled_class(self):
|
| 1129 |
+
return JxBraCoupled
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
class JyKet(SpinState, Ket):
|
| 1133 |
+
"""Eigenket of Jy.
|
| 1134 |
+
|
| 1135 |
+
See JzKet for the usage of spin eigenstates.
|
| 1136 |
+
|
| 1137 |
+
See Also
|
| 1138 |
+
========
|
| 1139 |
+
|
| 1140 |
+
JzKet: Usage of spin states
|
| 1141 |
+
|
| 1142 |
+
"""
|
| 1143 |
+
|
| 1144 |
+
@classmethod
|
| 1145 |
+
def dual_class(self):
|
| 1146 |
+
return JyBra
|
| 1147 |
+
|
| 1148 |
+
@classmethod
|
| 1149 |
+
def coupled_class(self):
|
| 1150 |
+
return JyKetCoupled
|
| 1151 |
+
|
| 1152 |
+
def _represent_default_basis(self, **options):
|
| 1153 |
+
return self._represent_JyOp(None, **options)
|
| 1154 |
+
|
| 1155 |
+
def _represent_JxOp(self, basis, **options):
|
| 1156 |
+
return self._represent_base(gamma=pi/2, **options)
|
| 1157 |
+
|
| 1158 |
+
def _represent_JyOp(self, basis, **options):
|
| 1159 |
+
return self._represent_base(**options)
|
| 1160 |
+
|
| 1161 |
+
def _represent_JzOp(self, basis, **options):
|
| 1162 |
+
return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
class JyBra(SpinState, Bra):
|
| 1166 |
+
"""Eigenbra of Jy.
|
| 1167 |
+
|
| 1168 |
+
See JzKet for the usage of spin eigenstates.
|
| 1169 |
+
|
| 1170 |
+
See Also
|
| 1171 |
+
========
|
| 1172 |
+
|
| 1173 |
+
JzKet: Usage of spin states
|
| 1174 |
+
|
| 1175 |
+
"""
|
| 1176 |
+
|
| 1177 |
+
@classmethod
|
| 1178 |
+
def dual_class(self):
|
| 1179 |
+
return JyKet
|
| 1180 |
+
|
| 1181 |
+
@classmethod
|
| 1182 |
+
def coupled_class(self):
|
| 1183 |
+
return JyBraCoupled
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
+
class JzKet(SpinState, Ket):
|
| 1187 |
+
"""Eigenket of Jz.
|
| 1188 |
+
|
| 1189 |
+
Spin state which is an eigenstate of the Jz operator. Uncoupled states,
|
| 1190 |
+
that is states representing the interaction of multiple separate spin
|
| 1191 |
+
states, are defined as a tensor product of states.
|
| 1192 |
+
|
| 1193 |
+
Parameters
|
| 1194 |
+
==========
|
| 1195 |
+
|
| 1196 |
+
j : Number, Symbol
|
| 1197 |
+
Total spin angular momentum
|
| 1198 |
+
m : Number, Symbol
|
| 1199 |
+
Eigenvalue of the Jz spin operator
|
| 1200 |
+
|
| 1201 |
+
Examples
|
| 1202 |
+
========
|
| 1203 |
+
|
| 1204 |
+
*Normal States:*
|
| 1205 |
+
|
| 1206 |
+
Defining simple spin states, both numerical and symbolic:
|
| 1207 |
+
|
| 1208 |
+
>>> from sympy.physics.quantum.spin import JzKet, JxKet
|
| 1209 |
+
>>> from sympy import symbols
|
| 1210 |
+
>>> JzKet(1, 0)
|
| 1211 |
+
|1,0>
|
| 1212 |
+
>>> j, m = symbols('j m')
|
| 1213 |
+
>>> JzKet(j, m)
|
| 1214 |
+
|j,m>
|
| 1215 |
+
|
| 1216 |
+
Rewriting the JzKet in terms of eigenkets of the Jx operator:
|
| 1217 |
+
Note: that the resulting eigenstates are JxKet's
|
| 1218 |
+
|
| 1219 |
+
>>> JzKet(1,1).rewrite("Jx")
|
| 1220 |
+
|1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2
|
| 1221 |
+
|
| 1222 |
+
Get the vector representation of a state in terms of the basis elements
|
| 1223 |
+
of the Jx operator:
|
| 1224 |
+
|
| 1225 |
+
>>> from sympy.physics.quantum.represent import represent
|
| 1226 |
+
>>> from sympy.physics.quantum.spin import Jx, Jz
|
| 1227 |
+
>>> represent(JzKet(1,-1), basis=Jx)
|
| 1228 |
+
Matrix([
|
| 1229 |
+
[ 1/2],
|
| 1230 |
+
[sqrt(2)/2],
|
| 1231 |
+
[ 1/2]])
|
| 1232 |
+
|
| 1233 |
+
Apply innerproducts between states:
|
| 1234 |
+
|
| 1235 |
+
>>> from sympy.physics.quantum.innerproduct import InnerProduct
|
| 1236 |
+
>>> from sympy.physics.quantum.spin import JxBra
|
| 1237 |
+
>>> i = InnerProduct(JxBra(1,1), JzKet(1,1))
|
| 1238 |
+
>>> i
|
| 1239 |
+
<1,1|1,1>
|
| 1240 |
+
>>> i.doit()
|
| 1241 |
+
1/2
|
| 1242 |
+
|
| 1243 |
+
*Uncoupled States:*
|
| 1244 |
+
|
| 1245 |
+
Define an uncoupled state as a TensorProduct between two Jz eigenkets:
|
| 1246 |
+
|
| 1247 |
+
>>> from sympy.physics.quantum.tensorproduct import TensorProduct
|
| 1248 |
+
>>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
|
| 1249 |
+
>>> TensorProduct(JzKet(1,0), JzKet(1,1))
|
| 1250 |
+
|1,0>x|1,1>
|
| 1251 |
+
>>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2))
|
| 1252 |
+
|j1,m1>x|j2,m2>
|
| 1253 |
+
|
| 1254 |
+
A TensorProduct can be rewritten, in which case the eigenstates that make
|
| 1255 |
+
up the tensor product is rewritten to the new basis:
|
| 1256 |
+
|
| 1257 |
+
>>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz')
|
| 1258 |
+
|1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2
|
| 1259 |
+
|
| 1260 |
+
The represent method for TensorProduct's gives the vector representation of
|
| 1261 |
+
the state. Note that the state in the product basis is the equivalent of the
|
| 1262 |
+
tensor product of the vector representation of the component eigenstates:
|
| 1263 |
+
|
| 1264 |
+
>>> represent(TensorProduct(JzKet(1,0),JzKet(1,1)))
|
| 1265 |
+
Matrix([
|
| 1266 |
+
[0],
|
| 1267 |
+
[0],
|
| 1268 |
+
[0],
|
| 1269 |
+
[1],
|
| 1270 |
+
[0],
|
| 1271 |
+
[0],
|
| 1272 |
+
[0],
|
| 1273 |
+
[0],
|
| 1274 |
+
[0]])
|
| 1275 |
+
>>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz)
|
| 1276 |
+
Matrix([
|
| 1277 |
+
[ 1/2],
|
| 1278 |
+
[sqrt(2)/2],
|
| 1279 |
+
[ 1/2],
|
| 1280 |
+
[ 0],
|
| 1281 |
+
[ 0],
|
| 1282 |
+
[ 0],
|
| 1283 |
+
[ 0],
|
| 1284 |
+
[ 0],
|
| 1285 |
+
[ 0]])
|
| 1286 |
+
|
| 1287 |
+
See Also
|
| 1288 |
+
========
|
| 1289 |
+
|
| 1290 |
+
JzKetCoupled: Coupled eigenstates
|
| 1291 |
+
sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states
|
| 1292 |
+
uncouple: Uncouples states given coupling parameters
|
| 1293 |
+
couple: Couples uncoupled states
|
| 1294 |
+
|
| 1295 |
+
"""
|
| 1296 |
+
|
| 1297 |
+
@classmethod
|
| 1298 |
+
def dual_class(self):
|
| 1299 |
+
return JzBra
|
| 1300 |
+
|
| 1301 |
+
@classmethod
|
| 1302 |
+
def coupled_class(self):
|
| 1303 |
+
return JzKetCoupled
|
| 1304 |
+
|
| 1305 |
+
def _represent_default_basis(self, **options):
|
| 1306 |
+
return self._represent_JzOp(None, **options)
|
| 1307 |
+
|
| 1308 |
+
def _represent_JxOp(self, basis, **options):
|
| 1309 |
+
return self._represent_base(beta=pi*Rational(3, 2), **options)
|
| 1310 |
+
|
| 1311 |
+
def _represent_JyOp(self, basis, **options):
|
| 1312 |
+
return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
|
| 1313 |
+
|
| 1314 |
+
def _represent_JzOp(self, basis, **options):
|
| 1315 |
+
return self._represent_base(**options)
|
| 1316 |
+
|
| 1317 |
+
|
| 1318 |
+
class JzBra(SpinState, Bra):
|
| 1319 |
+
"""Eigenbra of Jz.
|
| 1320 |
+
|
| 1321 |
+
See the JzKet for the usage of spin eigenstates.
|
| 1322 |
+
|
| 1323 |
+
See Also
|
| 1324 |
+
========
|
| 1325 |
+
|
| 1326 |
+
JzKet: Usage of spin states
|
| 1327 |
+
|
| 1328 |
+
"""
|
| 1329 |
+
|
| 1330 |
+
@classmethod
|
| 1331 |
+
def dual_class(self):
|
| 1332 |
+
return JzKet
|
| 1333 |
+
|
| 1334 |
+
@classmethod
|
| 1335 |
+
def coupled_class(self):
|
| 1336 |
+
return JzBraCoupled
|
| 1337 |
+
|
| 1338 |
+
|
| 1339 |
+
# Method used primarily to create coupled_n and coupled_jn by __new__ in
|
| 1340 |
+
# CoupledSpinState
|
| 1341 |
+
# This same method is also used by the uncouple method, and is separated from
|
| 1342 |
+
# the CoupledSpinState class to maintain consistency in defining coupling
|
| 1343 |
+
def _build_coupled(jcoupling, length):
|
| 1344 |
+
n_list = [ [n + 1] for n in range(length) ]
|
| 1345 |
+
coupled_jn = []
|
| 1346 |
+
coupled_n = []
|
| 1347 |
+
for n1, n2, j_new in jcoupling:
|
| 1348 |
+
coupled_jn.append(j_new)
|
| 1349 |
+
coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) )
|
| 1350 |
+
n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1])
|
| 1351 |
+
n_list[n_sort[0] - 1] = n_sort
|
| 1352 |
+
return coupled_n, coupled_jn
|
| 1353 |
+
|
| 1354 |
+
|
| 1355 |
+
class CoupledSpinState(SpinState):
|
| 1356 |
+
"""Base class for coupled angular momentum states."""
|
| 1357 |
+
|
| 1358 |
+
def __new__(cls, j, m, jn, *jcoupling):
|
| 1359 |
+
# Check j and m values using SpinState
|
| 1360 |
+
SpinState(j, m)
|
| 1361 |
+
# Build and check coupling scheme from arguments
|
| 1362 |
+
if len(jcoupling) == 0:
|
| 1363 |
+
# Use default coupling scheme
|
| 1364 |
+
jcoupling = []
|
| 1365 |
+
for n in range(2, len(jn)):
|
| 1366 |
+
jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) )
|
| 1367 |
+
jcoupling.append( (1, len(jn), j) )
|
| 1368 |
+
elif len(jcoupling) == 1:
|
| 1369 |
+
# Use specified coupling scheme
|
| 1370 |
+
jcoupling = jcoupling[0]
|
| 1371 |
+
else:
|
| 1372 |
+
raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) )
|
| 1373 |
+
# Check arguments have correct form
|
| 1374 |
+
if not isinstance(jn, (list, tuple, Tuple)):
|
| 1375 |
+
raise TypeError('jn must be Tuple, list or tuple, got %s' %
|
| 1376 |
+
jn.__class__.__name__)
|
| 1377 |
+
if not isinstance(jcoupling, (list, tuple, Tuple)):
|
| 1378 |
+
raise TypeError('jcoupling must be Tuple, list or tuple, got %s' %
|
| 1379 |
+
jcoupling.__class__.__name__)
|
| 1380 |
+
if not all(isinstance(term, (list, tuple, Tuple)) for term in jcoupling):
|
| 1381 |
+
raise TypeError(
|
| 1382 |
+
'All elements of jcoupling must be list, tuple or Tuple')
|
| 1383 |
+
if not len(jn) - 1 == len(jcoupling):
|
| 1384 |
+
raise ValueError('jcoupling must have length of %d, got %d' %
|
| 1385 |
+
(len(jn) - 1, len(jcoupling)))
|
| 1386 |
+
if not all(len(x) == 3 for x in jcoupling):
|
| 1387 |
+
raise ValueError('All elements of jcoupling must have length 3')
|
| 1388 |
+
# Build sympified args
|
| 1389 |
+
j = sympify(j)
|
| 1390 |
+
m = sympify(m)
|
| 1391 |
+
jn = Tuple( *[sympify(ji) for ji in jn] )
|
| 1392 |
+
jcoupling = Tuple( *[Tuple(sympify(
|
| 1393 |
+
n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] )
|
| 1394 |
+
# Check values in coupling scheme give physical state
|
| 1395 |
+
if any(2*ji != int(2*ji) for ji in jn if ji.is_number):
|
| 1396 |
+
raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn)
|
| 1397 |
+
if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling):
|
| 1398 |
+
raise ValueError('Indices in jcoupling must be integers')
|
| 1399 |
+
if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling):
|
| 1400 |
+
raise ValueError('Indices must be between 1 and the number of coupled spin spaces')
|
| 1401 |
+
if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number):
|
| 1402 |
+
raise ValueError('All coupled j values in coupling scheme must be integer or half-integer')
|
| 1403 |
+
coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn))
|
| 1404 |
+
jvals = list(jn)
|
| 1405 |
+
for n, (n1, n2) in enumerate(coupled_n):
|
| 1406 |
+
j1 = jvals[min(n1) - 1]
|
| 1407 |
+
j2 = jvals[min(n2) - 1]
|
| 1408 |
+
j3 = coupled_jn[n]
|
| 1409 |
+
if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number:
|
| 1410 |
+
if j1 + j2 < j3:
|
| 1411 |
+
raise ValueError('All couplings must have j1+j2 >= j3, '
|
| 1412 |
+
'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3))
|
| 1413 |
+
if abs(j1 - j2) > j3:
|
| 1414 |
+
raise ValueError("All couplings must have |j1+j2| <= j3, "
|
| 1415 |
+
"in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3))
|
| 1416 |
+
if int_valued(j1 + j2):
|
| 1417 |
+
pass
|
| 1418 |
+
jvals[min(n1 + n2) - 1] = j3
|
| 1419 |
+
if len(jcoupling) > 0 and jcoupling[-1][2] != j:
|
| 1420 |
+
raise ValueError('Last j value coupled together must be the final j of the state')
|
| 1421 |
+
# Return state
|
| 1422 |
+
return State.__new__(cls, j, m, jn, jcoupling)
|
| 1423 |
+
|
| 1424 |
+
def _print_label(self, printer, *args):
|
| 1425 |
+
label = [printer._print(self.j), printer._print(self.m)]
|
| 1426 |
+
for i, ji in enumerate(self.jn, start=1):
|
| 1427 |
+
label.append('j%d=%s' % (
|
| 1428 |
+
i, printer._print(ji)
|
| 1429 |
+
))
|
| 1430 |
+
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
|
| 1431 |
+
label.append('j(%s)=%s' % (
|
| 1432 |
+
','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn)
|
| 1433 |
+
))
|
| 1434 |
+
return ','.join(label)
|
| 1435 |
+
|
| 1436 |
+
def _print_label_pretty(self, printer, *args):
|
| 1437 |
+
label = [self.j, self.m]
|
| 1438 |
+
for i, ji in enumerate(self.jn, start=1):
|
| 1439 |
+
symb = 'j%d' % i
|
| 1440 |
+
symb = pretty_symbol(symb)
|
| 1441 |
+
symb = prettyForm(symb + '=')
|
| 1442 |
+
item = prettyForm(*symb.right(printer._print(ji)))
|
| 1443 |
+
label.append(item)
|
| 1444 |
+
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
|
| 1445 |
+
n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2))
|
| 1446 |
+
symb = prettyForm('j' + n + '=')
|
| 1447 |
+
item = prettyForm(*symb.right(printer._print(jn)))
|
| 1448 |
+
label.append(item)
|
| 1449 |
+
return self._print_sequence_pretty(
|
| 1450 |
+
label, self._label_separator, printer, *args
|
| 1451 |
+
)
|
| 1452 |
+
|
| 1453 |
+
def _print_label_latex(self, printer, *args):
|
| 1454 |
+
label = [
|
| 1455 |
+
printer._print(self.j, *args),
|
| 1456 |
+
printer._print(self.m, *args)
|
| 1457 |
+
]
|
| 1458 |
+
for i, ji in enumerate(self.jn, start=1):
|
| 1459 |
+
label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) )
|
| 1460 |
+
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
|
| 1461 |
+
n = ','.join(str(i) for i in sorted(n1 + n2))
|
| 1462 |
+
label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) )
|
| 1463 |
+
return self._label_separator.join(label)
|
| 1464 |
+
|
| 1465 |
+
@property
|
| 1466 |
+
def jn(self):
|
| 1467 |
+
return self.label[2]
|
| 1468 |
+
|
| 1469 |
+
@property
|
| 1470 |
+
def coupling(self):
|
| 1471 |
+
return self.label[3]
|
| 1472 |
+
|
| 1473 |
+
@property
|
| 1474 |
+
def coupled_jn(self):
|
| 1475 |
+
return _build_coupled(self.label[3], len(self.label[2]))[1]
|
| 1476 |
+
|
| 1477 |
+
@property
|
| 1478 |
+
def coupled_n(self):
|
| 1479 |
+
return _build_coupled(self.label[3], len(self.label[2]))[0]
|
| 1480 |
+
|
| 1481 |
+
@classmethod
|
| 1482 |
+
def _eval_hilbert_space(cls, label):
|
| 1483 |
+
j = Add(*label[2])
|
| 1484 |
+
if j.is_number:
|
| 1485 |
+
return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ])
|
| 1486 |
+
else:
|
| 1487 |
+
# TODO: Need hilbert space fix, see issue 5732
|
| 1488 |
+
# Desired behavior:
|
| 1489 |
+
#ji = symbols('ji')
|
| 1490 |
+
#ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j))
|
| 1491 |
+
# Temporary fix:
|
| 1492 |
+
return ComplexSpace(2*j + 1)
|
| 1493 |
+
|
| 1494 |
+
def _represent_coupled_base(self, **options):
|
| 1495 |
+
evect = self.uncoupled_class()
|
| 1496 |
+
if not self.j.is_number:
|
| 1497 |
+
raise ValueError(
|
| 1498 |
+
'State must not have symbolic j value to represent')
|
| 1499 |
+
if not self.hilbert_space.dimension.is_number:
|
| 1500 |
+
raise ValueError(
|
| 1501 |
+
'State must not have symbolic j values to represent')
|
| 1502 |
+
result = zeros(self.hilbert_space.dimension, 1)
|
| 1503 |
+
if self.j == int(self.j):
|
| 1504 |
+
start = self.j**2
|
| 1505 |
+
else:
|
| 1506 |
+
start = (2*self.j - 1)*(1 + 2*self.j)/4
|
| 1507 |
+
result[start:start + 2*self.j + 1, 0] = evect(
|
| 1508 |
+
self.j, self.m)._represent_base(**options)
|
| 1509 |
+
return result
|
| 1510 |
+
|
| 1511 |
+
def _eval_rewrite_as_Jx(self, *args, **options):
|
| 1512 |
+
if isinstance(self, Bra):
|
| 1513 |
+
return self._rewrite_basis(Jx, JxBraCoupled, **options)
|
| 1514 |
+
return self._rewrite_basis(Jx, JxKetCoupled, **options)
|
| 1515 |
+
|
| 1516 |
+
def _eval_rewrite_as_Jy(self, *args, **options):
|
| 1517 |
+
if isinstance(self, Bra):
|
| 1518 |
+
return self._rewrite_basis(Jy, JyBraCoupled, **options)
|
| 1519 |
+
return self._rewrite_basis(Jy, JyKetCoupled, **options)
|
| 1520 |
+
|
| 1521 |
+
def _eval_rewrite_as_Jz(self, *args, **options):
|
| 1522 |
+
if isinstance(self, Bra):
|
| 1523 |
+
return self._rewrite_basis(Jz, JzBraCoupled, **options)
|
| 1524 |
+
return self._rewrite_basis(Jz, JzKetCoupled, **options)
|
| 1525 |
+
|
| 1526 |
+
|
| 1527 |
+
class JxKetCoupled(CoupledSpinState, Ket):
|
| 1528 |
+
"""Coupled eigenket of Jx.
|
| 1529 |
+
|
| 1530 |
+
See JzKetCoupled for the usage of coupled spin eigenstates.
|
| 1531 |
+
|
| 1532 |
+
See Also
|
| 1533 |
+
========
|
| 1534 |
+
|
| 1535 |
+
JzKetCoupled: Usage of coupled spin states
|
| 1536 |
+
|
| 1537 |
+
"""
|
| 1538 |
+
|
| 1539 |
+
@classmethod
|
| 1540 |
+
def dual_class(self):
|
| 1541 |
+
return JxBraCoupled
|
| 1542 |
+
|
| 1543 |
+
@classmethod
|
| 1544 |
+
def uncoupled_class(self):
|
| 1545 |
+
return JxKet
|
| 1546 |
+
|
| 1547 |
+
def _represent_default_basis(self, **options):
|
| 1548 |
+
return self._represent_JzOp(None, **options)
|
| 1549 |
+
|
| 1550 |
+
def _represent_JxOp(self, basis, **options):
|
| 1551 |
+
return self._represent_coupled_base(**options)
|
| 1552 |
+
|
| 1553 |
+
def _represent_JyOp(self, basis, **options):
|
| 1554 |
+
return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options)
|
| 1555 |
+
|
| 1556 |
+
def _represent_JzOp(self, basis, **options):
|
| 1557 |
+
return self._represent_coupled_base(beta=pi/2, **options)
|
| 1558 |
+
|
| 1559 |
+
|
| 1560 |
+
class JxBraCoupled(CoupledSpinState, Bra):
|
| 1561 |
+
"""Coupled eigenbra of Jx.
|
| 1562 |
+
|
| 1563 |
+
See JzKetCoupled for the usage of coupled spin eigenstates.
|
| 1564 |
+
|
| 1565 |
+
See Also
|
| 1566 |
+
========
|
| 1567 |
+
|
| 1568 |
+
JzKetCoupled: Usage of coupled spin states
|
| 1569 |
+
|
| 1570 |
+
"""
|
| 1571 |
+
|
| 1572 |
+
@classmethod
|
| 1573 |
+
def dual_class(self):
|
| 1574 |
+
return JxKetCoupled
|
| 1575 |
+
|
| 1576 |
+
@classmethod
|
| 1577 |
+
def uncoupled_class(self):
|
| 1578 |
+
return JxBra
|
| 1579 |
+
|
| 1580 |
+
|
| 1581 |
+
class JyKetCoupled(CoupledSpinState, Ket):
|
| 1582 |
+
"""Coupled eigenket of Jy.
|
| 1583 |
+
|
| 1584 |
+
See JzKetCoupled for the usage of coupled spin eigenstates.
|
| 1585 |
+
|
| 1586 |
+
See Also
|
| 1587 |
+
========
|
| 1588 |
+
|
| 1589 |
+
JzKetCoupled: Usage of coupled spin states
|
| 1590 |
+
|
| 1591 |
+
"""
|
| 1592 |
+
|
| 1593 |
+
@classmethod
|
| 1594 |
+
def dual_class(self):
|
| 1595 |
+
return JyBraCoupled
|
| 1596 |
+
|
| 1597 |
+
@classmethod
|
| 1598 |
+
def uncoupled_class(self):
|
| 1599 |
+
return JyKet
|
| 1600 |
+
|
| 1601 |
+
def _represent_default_basis(self, **options):
|
| 1602 |
+
return self._represent_JzOp(None, **options)
|
| 1603 |
+
|
| 1604 |
+
def _represent_JxOp(self, basis, **options):
|
| 1605 |
+
return self._represent_coupled_base(gamma=pi/2, **options)
|
| 1606 |
+
|
| 1607 |
+
def _represent_JyOp(self, basis, **options):
|
| 1608 |
+
return self._represent_coupled_base(**options)
|
| 1609 |
+
|
| 1610 |
+
def _represent_JzOp(self, basis, **options):
|
| 1611 |
+
return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
|
| 1612 |
+
|
| 1613 |
+
|
| 1614 |
+
class JyBraCoupled(CoupledSpinState, Bra):
|
| 1615 |
+
"""Coupled eigenbra of Jy.
|
| 1616 |
+
|
| 1617 |
+
See JzKetCoupled for the usage of coupled spin eigenstates.
|
| 1618 |
+
|
| 1619 |
+
See Also
|
| 1620 |
+
========
|
| 1621 |
+
|
| 1622 |
+
JzKetCoupled: Usage of coupled spin states
|
| 1623 |
+
|
| 1624 |
+
"""
|
| 1625 |
+
|
| 1626 |
+
@classmethod
|
| 1627 |
+
def dual_class(self):
|
| 1628 |
+
return JyKetCoupled
|
| 1629 |
+
|
| 1630 |
+
@classmethod
|
| 1631 |
+
def uncoupled_class(self):
|
| 1632 |
+
return JyBra
|
| 1633 |
+
|
| 1634 |
+
|
| 1635 |
+
class JzKetCoupled(CoupledSpinState, Ket):
|
| 1636 |
+
r"""Coupled eigenket of Jz
|
| 1637 |
+
|
| 1638 |
+
Spin state that is an eigenket of Jz which represents the coupling of
|
| 1639 |
+
separate spin spaces.
|
| 1640 |
+
|
| 1641 |
+
The arguments for creating instances of JzKetCoupled are ``j``, ``m``,
|
| 1642 |
+
``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options
|
| 1643 |
+
are the total angular momentum quantum numbers, as used for normal states
|
| 1644 |
+
(e.g. JzKet).
|
| 1645 |
+
|
| 1646 |
+
The other required parameter in ``jn``, which is a tuple defining the `j_n`
|
| 1647 |
+
angular momentum quantum numbers of the product spaces. So for example, if
|
| 1648 |
+
a state represented the coupling of the product basis state
|
| 1649 |
+
`\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn``
|
| 1650 |
+
for this state would be ``(j1,j2)``.
|
| 1651 |
+
|
| 1652 |
+
The final option is ``jcoupling``, which is used to define how the spaces
|
| 1653 |
+
specified by ``jn`` are coupled, which includes both the order these spaces
|
| 1654 |
+
are coupled together and the quantum numbers that arise from these
|
| 1655 |
+
couplings. The ``jcoupling`` parameter itself is a list of lists, such that
|
| 1656 |
+
each of the sublists defines a single coupling between the spin spaces. If
|
| 1657 |
+
there are N coupled angular momentum spaces, that is ``jn`` has N elements,
|
| 1658 |
+
then there must be N-1 sublists. Each of these sublists making up the
|
| 1659 |
+
``jcoupling`` parameter have length 3. The first two elements are the
|
| 1660 |
+
indices of the product spaces that are considered to be coupled together.
|
| 1661 |
+
For example, if we want to couple `j_1` and `j_4`, the indices would be 1
|
| 1662 |
+
and 4. If a state has already been coupled, it is referenced by the
|
| 1663 |
+
smallest index that is coupled, so if `j_2` and `j_4` has already been
|
| 1664 |
+
coupled to some `j_{24}`, then this value can be coupled by referencing it
|
| 1665 |
+
with index 2. The final element of the sublist is the quantum number of the
|
| 1666 |
+
coupled state. So putting everything together, into a valid sublist for
|
| 1667 |
+
``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space
|
| 1668 |
+
with quantum number `j_{12}` with the value ``j12``, the sublist would be
|
| 1669 |
+
``(1,2,j12)``, N-1 of these sublists are used in the list for
|
| 1670 |
+
``jcoupling``.
|
| 1671 |
+
|
| 1672 |
+
Note the ``jcoupling`` parameter is optional, if it is not specified, the
|
| 1673 |
+
default coupling is taken. This default value is to coupled the spaces in
|
| 1674 |
+
order and take the quantum number of the coupling to be the maximum value.
|
| 1675 |
+
For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the
|
| 1676 |
+
default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then,
|
| 1677 |
+
`j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally
|
| 1678 |
+
`j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would
|
| 1679 |
+
correspond to this is:
|
| 1680 |
+
|
| 1681 |
+
``((1,2,j1+j2),(1,3,j1+j2+j3))``
|
| 1682 |
+
|
| 1683 |
+
Parameters
|
| 1684 |
+
==========
|
| 1685 |
+
|
| 1686 |
+
args : tuple
|
| 1687 |
+
The arguments that must be passed are ``j``, ``m``, ``jn``, and
|
| 1688 |
+
``jcoupling``. The ``j`` value is the total angular momentum. The ``m``
|
| 1689 |
+
value is the eigenvalue of the Jz spin operator. The ``jn`` list are
|
| 1690 |
+
the j values of argular momentum spaces coupled together. The
|
| 1691 |
+
``jcoupling`` parameter is an optional parameter defining how the spaces
|
| 1692 |
+
are coupled together. See the above description for how these coupling
|
| 1693 |
+
parameters are defined.
|
| 1694 |
+
|
| 1695 |
+
Examples
|
| 1696 |
+
========
|
| 1697 |
+
|
| 1698 |
+
Defining simple spin states, both numerical and symbolic:
|
| 1699 |
+
|
| 1700 |
+
>>> from sympy.physics.quantum.spin import JzKetCoupled
|
| 1701 |
+
>>> from sympy import symbols
|
| 1702 |
+
>>> JzKetCoupled(1, 0, (1, 1))
|
| 1703 |
+
|1,0,j1=1,j2=1>
|
| 1704 |
+
>>> j, m, j1, j2 = symbols('j m j1 j2')
|
| 1705 |
+
>>> JzKetCoupled(j, m, (j1, j2))
|
| 1706 |
+
|j,m,j1=j1,j2=j2>
|
| 1707 |
+
|
| 1708 |
+
Defining coupled spin states for more than 2 coupled spaces with various
|
| 1709 |
+
coupling parameters:
|
| 1710 |
+
|
| 1711 |
+
>>> JzKetCoupled(2, 1, (1, 1, 1))
|
| 1712 |
+
|2,1,j1=1,j2=1,j3=1,j(1,2)=2>
|
| 1713 |
+
>>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) )
|
| 1714 |
+
|2,1,j1=1,j2=1,j3=1,j(1,2)=2>
|
| 1715 |
+
>>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) )
|
| 1716 |
+
|2,1,j1=1,j2=1,j3=1,j(2,3)=1>
|
| 1717 |
+
|
| 1718 |
+
Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator:
|
| 1719 |
+
Note: that the resulting eigenstates are JxKetCoupled
|
| 1720 |
+
|
| 1721 |
+
>>> JzKetCoupled(1,1,(1,1)).rewrite("Jx")
|
| 1722 |
+
|1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2
|
| 1723 |
+
|
| 1724 |
+
The rewrite method can be used to convert a coupled state to an uncoupled
|
| 1725 |
+
state. This is done by passing coupled=False to the rewrite function:
|
| 1726 |
+
|
| 1727 |
+
>>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False)
|
| 1728 |
+
-sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2
|
| 1729 |
+
|
| 1730 |
+
Get the vector representation of a state in terms of the basis elements
|
| 1731 |
+
of the Jx operator:
|
| 1732 |
+
|
| 1733 |
+
>>> from sympy.physics.quantum.represent import represent
|
| 1734 |
+
>>> from sympy.physics.quantum.spin import Jx
|
| 1735 |
+
>>> from sympy import S
|
| 1736 |
+
>>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx)
|
| 1737 |
+
Matrix([
|
| 1738 |
+
[ 0],
|
| 1739 |
+
[ 1/2],
|
| 1740 |
+
[sqrt(2)/2],
|
| 1741 |
+
[ 1/2]])
|
| 1742 |
+
|
| 1743 |
+
See Also
|
| 1744 |
+
========
|
| 1745 |
+
|
| 1746 |
+
JzKet: Normal spin eigenstates
|
| 1747 |
+
uncouple: Uncoupling of coupling spin states
|
| 1748 |
+
couple: Coupling of uncoupled spin states
|
| 1749 |
+
|
| 1750 |
+
"""
|
| 1751 |
+
|
| 1752 |
+
@classmethod
|
| 1753 |
+
def dual_class(self):
|
| 1754 |
+
return JzBraCoupled
|
| 1755 |
+
|
| 1756 |
+
@classmethod
|
| 1757 |
+
def uncoupled_class(self):
|
| 1758 |
+
return JzKet
|
| 1759 |
+
|
| 1760 |
+
def _represent_default_basis(self, **options):
|
| 1761 |
+
return self._represent_JzOp(None, **options)
|
| 1762 |
+
|
| 1763 |
+
def _represent_JxOp(self, basis, **options):
|
| 1764 |
+
return self._represent_coupled_base(beta=pi*Rational(3, 2), **options)
|
| 1765 |
+
|
| 1766 |
+
def _represent_JyOp(self, basis, **options):
|
| 1767 |
+
return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
|
| 1768 |
+
|
| 1769 |
+
def _represent_JzOp(self, basis, **options):
|
| 1770 |
+
return self._represent_coupled_base(**options)
|
| 1771 |
+
|
| 1772 |
+
|
| 1773 |
+
class JzBraCoupled(CoupledSpinState, Bra):
|
| 1774 |
+
"""Coupled eigenbra of Jz.
|
| 1775 |
+
|
| 1776 |
+
See the JzKetCoupled for the usage of coupled spin eigenstates.
|
| 1777 |
+
|
| 1778 |
+
See Also
|
| 1779 |
+
========
|
| 1780 |
+
|
| 1781 |
+
JzKetCoupled: Usage of coupled spin states
|
| 1782 |
+
|
| 1783 |
+
"""
|
| 1784 |
+
|
| 1785 |
+
@classmethod
|
| 1786 |
+
def dual_class(self):
|
| 1787 |
+
return JzKetCoupled
|
| 1788 |
+
|
| 1789 |
+
@classmethod
|
| 1790 |
+
def uncoupled_class(self):
|
| 1791 |
+
return JzBra
|
| 1792 |
+
|
| 1793 |
+
#-----------------------------------------------------------------------------
|
| 1794 |
+
# Coupling/uncoupling
|
| 1795 |
+
#-----------------------------------------------------------------------------
|
| 1796 |
+
|
| 1797 |
+
|
| 1798 |
+
def couple(expr, jcoupling_list=None):
|
| 1799 |
+
""" Couple a tensor product of spin states
|
| 1800 |
+
|
| 1801 |
+
This function can be used to couple an uncoupled tensor product of spin
|
| 1802 |
+
states. All of the eigenstates to be coupled must be of the same class. It
|
| 1803 |
+
will return a linear combination of eigenstates that are subclasses of
|
| 1804 |
+
CoupledSpinState determined by Clebsch-Gordan angular momentum coupling
|
| 1805 |
+
coefficients.
|
| 1806 |
+
|
| 1807 |
+
Parameters
|
| 1808 |
+
==========
|
| 1809 |
+
|
| 1810 |
+
expr : Expr
|
| 1811 |
+
An expression involving TensorProducts of spin states to be coupled.
|
| 1812 |
+
Each state must be a subclass of SpinState and they all must be the
|
| 1813 |
+
same class.
|
| 1814 |
+
|
| 1815 |
+
jcoupling_list : list or tuple
|
| 1816 |
+
Elements of this list are sub-lists of length 2 specifying the order of
|
| 1817 |
+
the coupling of the spin spaces. The length of this must be N-1, where N
|
| 1818 |
+
is the number of states in the tensor product to be coupled. The
|
| 1819 |
+
elements of this sublist are the same as the first two elements of each
|
| 1820 |
+
sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this
|
| 1821 |
+
parameter is not specified, the default value is taken, which couples
|
| 1822 |
+
the first and second product basis spaces, then couples this new coupled
|
| 1823 |
+
space to the third product space, etc
|
| 1824 |
+
|
| 1825 |
+
Examples
|
| 1826 |
+
========
|
| 1827 |
+
|
| 1828 |
+
Couple a tensor product of numerical states for two spaces:
|
| 1829 |
+
|
| 1830 |
+
>>> from sympy.physics.quantum.spin import JzKet, couple
|
| 1831 |
+
>>> from sympy.physics.quantum.tensorproduct import TensorProduct
|
| 1832 |
+
>>> couple(TensorProduct(JzKet(1,0), JzKet(1,1)))
|
| 1833 |
+
-sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2
|
| 1834 |
+
|
| 1835 |
+
|
| 1836 |
+
Numerical coupling of three spaces using the default coupling method, i.e.
|
| 1837 |
+
first and second spaces couple, then this couples to the third space:
|
| 1838 |
+
|
| 1839 |
+
>>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)))
|
| 1840 |
+
sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3
|
| 1841 |
+
|
| 1842 |
+
Perform this same coupling, but we define the coupling to first couple
|
| 1843 |
+
the first and third spaces:
|
| 1844 |
+
|
| 1845 |
+
>>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) )
|
| 1846 |
+
sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3
|
| 1847 |
+
|
| 1848 |
+
Couple a tensor product of symbolic states:
|
| 1849 |
+
|
| 1850 |
+
>>> from sympy import symbols
|
| 1851 |
+
>>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
|
| 1852 |
+
>>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2)))
|
| 1853 |
+
Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2))
|
| 1854 |
+
|
| 1855 |
+
"""
|
| 1856 |
+
a = expr.atoms(TensorProduct)
|
| 1857 |
+
for tp in a:
|
| 1858 |
+
# Allow other tensor products to be in expression
|
| 1859 |
+
if not all(isinstance(state, SpinState) for state in tp.args):
|
| 1860 |
+
continue
|
| 1861 |
+
# If tensor product has all spin states, raise error for invalid tensor product state
|
| 1862 |
+
if not all(state.__class__ is tp.args[0].__class__ for state in tp.args):
|
| 1863 |
+
raise TypeError('All states must be the same basis')
|
| 1864 |
+
expr = expr.subs(tp, _couple(tp, jcoupling_list))
|
| 1865 |
+
return expr
|
| 1866 |
+
|
| 1867 |
+
|
| 1868 |
+
def _couple(tp, jcoupling_list):
|
| 1869 |
+
states = tp.args
|
| 1870 |
+
coupled_evect = states[0].coupled_class()
|
| 1871 |
+
|
| 1872 |
+
# Define default coupling if none is specified
|
| 1873 |
+
if jcoupling_list is None:
|
| 1874 |
+
jcoupling_list = []
|
| 1875 |
+
for n in range(1, len(states)):
|
| 1876 |
+
jcoupling_list.append( (1, n + 1) )
|
| 1877 |
+
|
| 1878 |
+
# Check jcoupling_list valid
|
| 1879 |
+
if not len(jcoupling_list) == len(states) - 1:
|
| 1880 |
+
raise TypeError('jcoupling_list must be length %d, got %d' %
|
| 1881 |
+
(len(states) - 1, len(jcoupling_list)))
|
| 1882 |
+
if not all( len(coupling) == 2 for coupling in jcoupling_list):
|
| 1883 |
+
raise ValueError('Each coupling must define 2 spaces')
|
| 1884 |
+
if any(n1 == n2 for n1, n2 in jcoupling_list):
|
| 1885 |
+
raise ValueError('Spin spaces cannot couple to themselves')
|
| 1886 |
+
if all(sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list):
|
| 1887 |
+
j_test = [0]*len(states)
|
| 1888 |
+
for n1, n2 in jcoupling_list:
|
| 1889 |
+
if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1:
|
| 1890 |
+
raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value')
|
| 1891 |
+
j_test[max(n1, n2) - 1] = -1
|
| 1892 |
+
|
| 1893 |
+
# j values of states to be coupled together
|
| 1894 |
+
jn = [state.j for state in states]
|
| 1895 |
+
mn = [state.m for state in states]
|
| 1896 |
+
|
| 1897 |
+
# Create coupling_list, which defines all the couplings between all
|
| 1898 |
+
# the spaces from jcoupling_list
|
| 1899 |
+
coupling_list = []
|
| 1900 |
+
n_list = [ [i + 1] for i in range(len(states)) ]
|
| 1901 |
+
for j_coupling in jcoupling_list:
|
| 1902 |
+
# Least n for all j_n which is coupled as first and second spaces
|
| 1903 |
+
n1, n2 = j_coupling
|
| 1904 |
+
# List of all n's coupled in first and second spaces
|
| 1905 |
+
j1_n = list(n_list[n1 - 1])
|
| 1906 |
+
j2_n = list(n_list[n2 - 1])
|
| 1907 |
+
coupling_list.append( (j1_n, j2_n) )
|
| 1908 |
+
# Set new j_n to be coupling of all j_n in both first and second spaces
|
| 1909 |
+
n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n)
|
| 1910 |
+
|
| 1911 |
+
if all(state.j.is_number and state.m.is_number for state in states):
|
| 1912 |
+
# Numerical coupling
|
| 1913 |
+
# Iterate over difference between maximum possible j value of each coupling and the actual value
|
| 1914 |
+
diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] +
|
| 1915 |
+
coupling[1] ] ) for coupling in coupling_list ]
|
| 1916 |
+
result = []
|
| 1917 |
+
for diff in range(diff_max[-1] + 1):
|
| 1918 |
+
# Determine available configurations
|
| 1919 |
+
n = len(coupling_list)
|
| 1920 |
+
tot = binomial(diff + n - 1, diff)
|
| 1921 |
+
|
| 1922 |
+
for config_num in range(tot):
|
| 1923 |
+
diff_list = _confignum_to_difflist(config_num, diff, n)
|
| 1924 |
+
|
| 1925 |
+
# Skip the configuration if non-physical
|
| 1926 |
+
# This is a lazy check for physical states given the loose restrictions of diff_max
|
| 1927 |
+
if any(d > m for d, m in zip(diff_list, diff_max)):
|
| 1928 |
+
continue
|
| 1929 |
+
|
| 1930 |
+
# Determine term
|
| 1931 |
+
cg_terms = []
|
| 1932 |
+
coupled_j = list(jn)
|
| 1933 |
+
jcoupling = []
|
| 1934 |
+
for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list):
|
| 1935 |
+
j1 = coupled_j[ min(j1_n) - 1 ]
|
| 1936 |
+
j2 = coupled_j[ min(j2_n) - 1 ]
|
| 1937 |
+
j3 = j1 + j2 - coupling_diff
|
| 1938 |
+
coupled_j[ min(j1_n + j2_n) - 1 ] = j3
|
| 1939 |
+
m1 = Add( *[ mn[x - 1] for x in j1_n] )
|
| 1940 |
+
m2 = Add( *[ mn[x - 1] for x in j2_n] )
|
| 1941 |
+
m3 = m1 + m2
|
| 1942 |
+
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
|
| 1943 |
+
jcoupling.append( (min(j1_n), min(j2_n), j3) )
|
| 1944 |
+
# Better checks that state is physical
|
| 1945 |
+
if any(abs(term[5]) > term[4] for term in cg_terms):
|
| 1946 |
+
continue
|
| 1947 |
+
if any(term[0] + term[2] < term[4] for term in cg_terms):
|
| 1948 |
+
continue
|
| 1949 |
+
if any(abs(term[0] - term[2]) > term[4] for term in cg_terms):
|
| 1950 |
+
continue
|
| 1951 |
+
coeff = Mul( *[ CG(*term).doit() for term in cg_terms] )
|
| 1952 |
+
state = coupled_evect(j3, m3, jn, jcoupling)
|
| 1953 |
+
result.append(coeff*state)
|
| 1954 |
+
return Add(*result)
|
| 1955 |
+
else:
|
| 1956 |
+
# Symbolic coupling
|
| 1957 |
+
cg_terms = []
|
| 1958 |
+
jcoupling = []
|
| 1959 |
+
sum_terms = []
|
| 1960 |
+
coupled_j = list(jn)
|
| 1961 |
+
for j1_n, j2_n in coupling_list:
|
| 1962 |
+
j1 = coupled_j[ min(j1_n) - 1 ]
|
| 1963 |
+
j2 = coupled_j[ min(j2_n) - 1 ]
|
| 1964 |
+
if len(j1_n + j2_n) == len(states):
|
| 1965 |
+
j3 = symbols('j')
|
| 1966 |
+
else:
|
| 1967 |
+
j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n])
|
| 1968 |
+
j3 = symbols(j3_name)
|
| 1969 |
+
coupled_j[ min(j1_n + j2_n) - 1 ] = j3
|
| 1970 |
+
m1 = Add( *[ mn[x - 1] for x in j1_n] )
|
| 1971 |
+
m2 = Add( *[ mn[x - 1] for x in j2_n] )
|
| 1972 |
+
m3 = m1 + m2
|
| 1973 |
+
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
|
| 1974 |
+
jcoupling.append( (min(j1_n), min(j2_n), j3) )
|
| 1975 |
+
sum_terms.append((j3, m3, j1 + j2))
|
| 1976 |
+
coeff = Mul( *[ CG(*term) for term in cg_terms] )
|
| 1977 |
+
state = coupled_evect(j3, m3, jn, jcoupling)
|
| 1978 |
+
return Sum(coeff*state, *sum_terms)
|
| 1979 |
+
|
| 1980 |
+
|
| 1981 |
+
def uncouple(expr, jn=None, jcoupling_list=None):
|
| 1982 |
+
""" Uncouple a coupled spin state
|
| 1983 |
+
|
| 1984 |
+
Gives the uncoupled representation of a coupled spin state. Arguments must
|
| 1985 |
+
be either a spin state that is a subclass of CoupledSpinState or a spin
|
| 1986 |
+
state that is a subclass of SpinState and an array giving the j values
|
| 1987 |
+
of the spaces that are to be coupled
|
| 1988 |
+
|
| 1989 |
+
Parameters
|
| 1990 |
+
==========
|
| 1991 |
+
|
| 1992 |
+
expr : Expr
|
| 1993 |
+
The expression containing states that are to be coupled. If the states
|
| 1994 |
+
are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters
|
| 1995 |
+
must be defined. If the states are a subclass of CoupledSpinState,
|
| 1996 |
+
``jn`` and ``jcoupling`` will be taken from the state.
|
| 1997 |
+
|
| 1998 |
+
jn : list or tuple
|
| 1999 |
+
The list of the j-values that are coupled. If state is a
|
| 2000 |
+
CoupledSpinState, this parameter is ignored. This must be defined if
|
| 2001 |
+
state is not a subclass of CoupledSpinState. The syntax of this
|
| 2002 |
+
parameter is the same as the ``jn`` parameter of JzKetCoupled.
|
| 2003 |
+
|
| 2004 |
+
jcoupling_list : list or tuple
|
| 2005 |
+
The list defining how the j-values are coupled together. If state is a
|
| 2006 |
+
CoupledSpinState, this parameter is ignored. This must be defined if
|
| 2007 |
+
state is not a subclass of CoupledSpinState. The syntax of this
|
| 2008 |
+
parameter is the same as the ``jcoupling`` parameter of JzKetCoupled.
|
| 2009 |
+
|
| 2010 |
+
Examples
|
| 2011 |
+
========
|
| 2012 |
+
|
| 2013 |
+
Uncouple a numerical state using a CoupledSpinState state:
|
| 2014 |
+
|
| 2015 |
+
>>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple
|
| 2016 |
+
>>> from sympy import S
|
| 2017 |
+
>>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)))
|
| 2018 |
+
sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
|
| 2019 |
+
|
| 2020 |
+
Perform the same calculation using a SpinState state:
|
| 2021 |
+
|
| 2022 |
+
>>> from sympy.physics.quantum.spin import JzKet
|
| 2023 |
+
>>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2))
|
| 2024 |
+
sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
|
| 2025 |
+
|
| 2026 |
+
Uncouple a numerical state of three coupled spaces using a CoupledSpinState state:
|
| 2027 |
+
|
| 2028 |
+
>>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) ))
|
| 2029 |
+
|1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
|
| 2030 |
+
|
| 2031 |
+
Perform the same calculation using a SpinState state:
|
| 2032 |
+
|
| 2033 |
+
>>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) )
|
| 2034 |
+
|1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
|
| 2035 |
+
|
| 2036 |
+
Uncouple a symbolic state using a CoupledSpinState state:
|
| 2037 |
+
|
| 2038 |
+
>>> from sympy import symbols
|
| 2039 |
+
>>> j,m,j1,j2 = symbols('j m j1 j2')
|
| 2040 |
+
>>> uncouple(JzKetCoupled(j, m, (j1, j2)))
|
| 2041 |
+
Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
|
| 2042 |
+
|
| 2043 |
+
Perform the same calculation using a SpinState state
|
| 2044 |
+
|
| 2045 |
+
>>> uncouple(JzKet(j, m), (j1, j2))
|
| 2046 |
+
Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
|
| 2047 |
+
|
| 2048 |
+
"""
|
| 2049 |
+
a = expr.atoms(SpinState)
|
| 2050 |
+
for state in a:
|
| 2051 |
+
expr = expr.subs(state, _uncouple(state, jn, jcoupling_list))
|
| 2052 |
+
return expr
|
| 2053 |
+
|
| 2054 |
+
|
| 2055 |
+
def _uncouple(state, jn, jcoupling_list):
|
| 2056 |
+
if isinstance(state, CoupledSpinState):
|
| 2057 |
+
jn = state.jn
|
| 2058 |
+
coupled_n = state.coupled_n
|
| 2059 |
+
coupled_jn = state.coupled_jn
|
| 2060 |
+
evect = state.uncoupled_class()
|
| 2061 |
+
elif isinstance(state, SpinState):
|
| 2062 |
+
if jn is None:
|
| 2063 |
+
raise ValueError("Must specify j-values for coupled state")
|
| 2064 |
+
if not isinstance(jn, (list, tuple)):
|
| 2065 |
+
raise TypeError("jn must be list or tuple")
|
| 2066 |
+
if jcoupling_list is None:
|
| 2067 |
+
# Use default
|
| 2068 |
+
jcoupling_list = []
|
| 2069 |
+
for i in range(1, len(jn)):
|
| 2070 |
+
jcoupling_list.append(
|
| 2071 |
+
(1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) )
|
| 2072 |
+
if not isinstance(jcoupling_list, (list, tuple)):
|
| 2073 |
+
raise TypeError("jcoupling must be a list or tuple")
|
| 2074 |
+
if not len(jcoupling_list) == len(jn) - 1:
|
| 2075 |
+
raise ValueError("Must specify 2 fewer coupling terms than the number of j values")
|
| 2076 |
+
coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn))
|
| 2077 |
+
evect = state.__class__
|
| 2078 |
+
else:
|
| 2079 |
+
raise TypeError("state must be a spin state")
|
| 2080 |
+
j = state.j
|
| 2081 |
+
m = state.m
|
| 2082 |
+
coupling_list = []
|
| 2083 |
+
j_list = list(jn)
|
| 2084 |
+
|
| 2085 |
+
# Create coupling, which defines all the couplings between all the spaces
|
| 2086 |
+
for j3, (n1, n2) in zip(coupled_jn, coupled_n):
|
| 2087 |
+
# j's which are coupled as first and second spaces
|
| 2088 |
+
j1 = j_list[n1[0] - 1]
|
| 2089 |
+
j2 = j_list[n2[0] - 1]
|
| 2090 |
+
# Build coupling list
|
| 2091 |
+
coupling_list.append( (n1, n2, j1, j2, j3) )
|
| 2092 |
+
# Set new value in j_list
|
| 2093 |
+
j_list[min(n1 + n2) - 1] = j3
|
| 2094 |
+
|
| 2095 |
+
if j.is_number and m.is_number:
|
| 2096 |
+
diff_max = [ 2*x for x in jn ]
|
| 2097 |
+
diff = Add(*jn) - m
|
| 2098 |
+
|
| 2099 |
+
n = len(jn)
|
| 2100 |
+
tot = binomial(diff + n - 1, diff)
|
| 2101 |
+
|
| 2102 |
+
result = []
|
| 2103 |
+
for config_num in range(tot):
|
| 2104 |
+
diff_list = _confignum_to_difflist(config_num, diff, n)
|
| 2105 |
+
if any(d > p for d, p in zip(diff_list, diff_max)):
|
| 2106 |
+
continue
|
| 2107 |
+
|
| 2108 |
+
cg_terms = []
|
| 2109 |
+
for coupling in coupling_list:
|
| 2110 |
+
j1_n, j2_n, j1, j2, j3 = coupling
|
| 2111 |
+
m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] )
|
| 2112 |
+
m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] )
|
| 2113 |
+
m3 = m1 + m2
|
| 2114 |
+
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
|
| 2115 |
+
coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] )
|
| 2116 |
+
state = TensorProduct(
|
| 2117 |
+
*[ evect(j, j - d) for j, d in zip(jn, diff_list) ] )
|
| 2118 |
+
result.append(coeff*state)
|
| 2119 |
+
return Add(*result)
|
| 2120 |
+
else:
|
| 2121 |
+
# Symbolic coupling
|
| 2122 |
+
m_str = "m1:%d" % (len(jn) + 1)
|
| 2123 |
+
mvals = symbols(m_str)
|
| 2124 |
+
cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]),
|
| 2125 |
+
j2, Add(*[mvals[n - 1] for n in j2_n]),
|
| 2126 |
+
j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ]
|
| 2127 |
+
cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]),
|
| 2128 |
+
j2, Add(*[mvals[n - 1] for n in j2_n]),
|
| 2129 |
+
j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ])
|
| 2130 |
+
cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms])
|
| 2131 |
+
sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ]
|
| 2132 |
+
state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] )
|
| 2133 |
+
return Sum(cg_coeff*state, *sum_terms)
|
| 2134 |
+
|
| 2135 |
+
|
| 2136 |
+
def _confignum_to_difflist(config_num, diff, list_len):
|
| 2137 |
+
# Determines configuration of diffs into list_len number of slots
|
| 2138 |
+
diff_list = []
|
| 2139 |
+
for n in range(list_len):
|
| 2140 |
+
prev_diff = diff
|
| 2141 |
+
# Number of spots after current one
|
| 2142 |
+
rem_spots = list_len - n - 1
|
| 2143 |
+
# Number of configurations of distributing diff among the remaining spots
|
| 2144 |
+
rem_configs = binomial(diff + rem_spots - 1, diff)
|
| 2145 |
+
while config_num >= rem_configs:
|
| 2146 |
+
config_num -= rem_configs
|
| 2147 |
+
diff -= 1
|
| 2148 |
+
rem_configs = binomial(diff + rem_spots - 1, diff)
|
| 2149 |
+
diff_list.append(prev_diff - diff)
|
| 2150 |
+
return diff_list
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_identitysearch.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.external import import_module
|
| 2 |
+
from sympy.core.mul import Mul
|
| 3 |
+
from sympy.core.numbers import Integer
|
| 4 |
+
from sympy.physics.quantum.dagger import Dagger
|
| 5 |
+
from sympy.physics.quantum.gate import (X, Y, Z, H, CNOT,
|
| 6 |
+
IdentityGate, CGate, PhaseGate, TGate)
|
| 7 |
+
from sympy.physics.quantum.identitysearch import (generate_gate_rules,
|
| 8 |
+
generate_equivalent_ids, GateIdentity, bfs_identity_search,
|
| 9 |
+
is_scalar_sparse_matrix,
|
| 10 |
+
is_scalar_nonsparse_matrix, is_degenerate, is_reducible)
|
| 11 |
+
from sympy.testing.pytest import skip
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def create_gate_sequence(qubit=0):
|
| 15 |
+
gates = (X(qubit), Y(qubit), Z(qubit), H(qubit))
|
| 16 |
+
return gates
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_generate_gate_rules_1():
|
| 20 |
+
# Test with tuples
|
| 21 |
+
(x, y, z, h) = create_gate_sequence()
|
| 22 |
+
ph = PhaseGate(0)
|
| 23 |
+
cgate_t = CGate(0, TGate(1))
|
| 24 |
+
|
| 25 |
+
assert generate_gate_rules((x,)) == {((x,), ())}
|
| 26 |
+
|
| 27 |
+
gate_rules = {((x, x), ()),
|
| 28 |
+
((x,), (x,))}
|
| 29 |
+
assert generate_gate_rules((x, x)) == gate_rules
|
| 30 |
+
|
| 31 |
+
gate_rules = {((x, y, x), ()),
|
| 32 |
+
((y, x, x), ()),
|
| 33 |
+
((x, x, y), ()),
|
| 34 |
+
((y, x), (x,)),
|
| 35 |
+
((x, y), (x,)),
|
| 36 |
+
((y,), (x, x))}
|
| 37 |
+
assert generate_gate_rules((x, y, x)) == gate_rules
|
| 38 |
+
|
| 39 |
+
gate_rules = {((x, y, z), ()), ((y, z, x), ()), ((z, x, y), ()),
|
| 40 |
+
((), (x, z, y)), ((), (y, x, z)), ((), (z, y, x)),
|
| 41 |
+
((x,), (z, y)), ((y, z), (x,)), ((y,), (x, z)),
|
| 42 |
+
((z, x), (y,)), ((z,), (y, x)), ((x, y), (z,))}
|
| 43 |
+
actual = generate_gate_rules((x, y, z))
|
| 44 |
+
assert actual == gate_rules
|
| 45 |
+
|
| 46 |
+
gate_rules = {
|
| 47 |
+
((), (h, z, y, x)), ((), (x, h, z, y)), ((), (y, x, h, z)),
|
| 48 |
+
((), (z, y, x, h)), ((h,), (z, y, x)), ((x,), (h, z, y)),
|
| 49 |
+
((y,), (x, h, z)), ((z,), (y, x, h)), ((h, x), (z, y)),
|
| 50 |
+
((x, y), (h, z)), ((y, z), (x, h)), ((z, h), (y, x)),
|
| 51 |
+
((h, x, y), (z,)), ((x, y, z), (h,)), ((y, z, h), (x,)),
|
| 52 |
+
((z, h, x), (y,)), ((h, x, y, z), ()), ((x, y, z, h), ()),
|
| 53 |
+
((y, z, h, x), ()), ((z, h, x, y), ())}
|
| 54 |
+
actual = generate_gate_rules((x, y, z, h))
|
| 55 |
+
assert actual == gate_rules
|
| 56 |
+
|
| 57 |
+
gate_rules = {((), (cgate_t**(-1), ph**(-1), x)),
|
| 58 |
+
((), (ph**(-1), x, cgate_t**(-1))),
|
| 59 |
+
((), (x, cgate_t**(-1), ph**(-1))),
|
| 60 |
+
((cgate_t,), (ph**(-1), x)),
|
| 61 |
+
((ph,), (x, cgate_t**(-1))),
|
| 62 |
+
((x,), (cgate_t**(-1), ph**(-1))),
|
| 63 |
+
((cgate_t, x), (ph**(-1),)),
|
| 64 |
+
((ph, cgate_t), (x,)),
|
| 65 |
+
((x, ph), (cgate_t**(-1),)),
|
| 66 |
+
((cgate_t, x, ph), ()),
|
| 67 |
+
((ph, cgate_t, x), ()),
|
| 68 |
+
((x, ph, cgate_t), ())}
|
| 69 |
+
actual = generate_gate_rules((x, ph, cgate_t))
|
| 70 |
+
assert actual == gate_rules
|
| 71 |
+
|
| 72 |
+
gate_rules = {(Integer(1), cgate_t**(-1)*ph**(-1)*x),
|
| 73 |
+
(Integer(1), ph**(-1)*x*cgate_t**(-1)),
|
| 74 |
+
(Integer(1), x*cgate_t**(-1)*ph**(-1)),
|
| 75 |
+
(cgate_t, ph**(-1)*x),
|
| 76 |
+
(ph, x*cgate_t**(-1)),
|
| 77 |
+
(x, cgate_t**(-1)*ph**(-1)),
|
| 78 |
+
(cgate_t*x, ph**(-1)),
|
| 79 |
+
(ph*cgate_t, x),
|
| 80 |
+
(x*ph, cgate_t**(-1)),
|
| 81 |
+
(cgate_t*x*ph, Integer(1)),
|
| 82 |
+
(ph*cgate_t*x, Integer(1)),
|
| 83 |
+
(x*ph*cgate_t, Integer(1))}
|
| 84 |
+
actual = generate_gate_rules((x, ph, cgate_t), return_as_muls=True)
|
| 85 |
+
assert actual == gate_rules
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_generate_gate_rules_2():
|
| 89 |
+
# Test with Muls
|
| 90 |
+
(x, y, z, h) = create_gate_sequence()
|
| 91 |
+
ph = PhaseGate(0)
|
| 92 |
+
cgate_t = CGate(0, TGate(1))
|
| 93 |
+
|
| 94 |
+
# Note: 1 (type int) is not the same as 1 (type One)
|
| 95 |
+
expected = {(x, Integer(1))}
|
| 96 |
+
assert generate_gate_rules((x,), return_as_muls=True) == expected
|
| 97 |
+
|
| 98 |
+
expected = {(Integer(1), Integer(1))}
|
| 99 |
+
assert generate_gate_rules(x*x, return_as_muls=True) == expected
|
| 100 |
+
|
| 101 |
+
expected = {((), ())}
|
| 102 |
+
assert generate_gate_rules(x*x, return_as_muls=False) == expected
|
| 103 |
+
|
| 104 |
+
gate_rules = {(x*y*x, Integer(1)),
|
| 105 |
+
(y, Integer(1)),
|
| 106 |
+
(y*x, x),
|
| 107 |
+
(x*y, x)}
|
| 108 |
+
assert generate_gate_rules(x*y*x, return_as_muls=True) == gate_rules
|
| 109 |
+
|
| 110 |
+
gate_rules = {(x*y*z, Integer(1)),
|
| 111 |
+
(y*z*x, Integer(1)),
|
| 112 |
+
(z*x*y, Integer(1)),
|
| 113 |
+
(Integer(1), x*z*y),
|
| 114 |
+
(Integer(1), y*x*z),
|
| 115 |
+
(Integer(1), z*y*x),
|
| 116 |
+
(x, z*y),
|
| 117 |
+
(y*z, x),
|
| 118 |
+
(y, x*z),
|
| 119 |
+
(z*x, y),
|
| 120 |
+
(z, y*x),
|
| 121 |
+
(x*y, z)}
|
| 122 |
+
actual = generate_gate_rules(x*y*z, return_as_muls=True)
|
| 123 |
+
assert actual == gate_rules
|
| 124 |
+
|
| 125 |
+
gate_rules = {(Integer(1), h*z*y*x),
|
| 126 |
+
(Integer(1), x*h*z*y),
|
| 127 |
+
(Integer(1), y*x*h*z),
|
| 128 |
+
(Integer(1), z*y*x*h),
|
| 129 |
+
(h, z*y*x), (x, h*z*y),
|
| 130 |
+
(y, x*h*z), (z, y*x*h),
|
| 131 |
+
(h*x, z*y), (z*h, y*x),
|
| 132 |
+
(x*y, h*z), (y*z, x*h),
|
| 133 |
+
(h*x*y, z), (x*y*z, h),
|
| 134 |
+
(y*z*h, x), (z*h*x, y),
|
| 135 |
+
(h*x*y*z, Integer(1)),
|
| 136 |
+
(x*y*z*h, Integer(1)),
|
| 137 |
+
(y*z*h*x, Integer(1)),
|
| 138 |
+
(z*h*x*y, Integer(1))}
|
| 139 |
+
actual = generate_gate_rules(x*y*z*h, return_as_muls=True)
|
| 140 |
+
assert actual == gate_rules
|
| 141 |
+
|
| 142 |
+
gate_rules = {(Integer(1), cgate_t**(-1)*ph**(-1)*x),
|
| 143 |
+
(Integer(1), ph**(-1)*x*cgate_t**(-1)),
|
| 144 |
+
(Integer(1), x*cgate_t**(-1)*ph**(-1)),
|
| 145 |
+
(cgate_t, ph**(-1)*x),
|
| 146 |
+
(ph, x*cgate_t**(-1)),
|
| 147 |
+
(x, cgate_t**(-1)*ph**(-1)),
|
| 148 |
+
(cgate_t*x, ph**(-1)),
|
| 149 |
+
(ph*cgate_t, x),
|
| 150 |
+
(x*ph, cgate_t**(-1)),
|
| 151 |
+
(cgate_t*x*ph, Integer(1)),
|
| 152 |
+
(ph*cgate_t*x, Integer(1)),
|
| 153 |
+
(x*ph*cgate_t, Integer(1))}
|
| 154 |
+
actual = generate_gate_rules(x*ph*cgate_t, return_as_muls=True)
|
| 155 |
+
assert actual == gate_rules
|
| 156 |
+
|
| 157 |
+
gate_rules = {((), (cgate_t**(-1), ph**(-1), x)),
|
| 158 |
+
((), (ph**(-1), x, cgate_t**(-1))),
|
| 159 |
+
((), (x, cgate_t**(-1), ph**(-1))),
|
| 160 |
+
((cgate_t,), (ph**(-1), x)),
|
| 161 |
+
((ph,), (x, cgate_t**(-1))),
|
| 162 |
+
((x,), (cgate_t**(-1), ph**(-1))),
|
| 163 |
+
((cgate_t, x), (ph**(-1),)),
|
| 164 |
+
((ph, cgate_t), (x,)),
|
| 165 |
+
((x, ph), (cgate_t**(-1),)),
|
| 166 |
+
((cgate_t, x, ph), ()),
|
| 167 |
+
((ph, cgate_t, x), ()),
|
| 168 |
+
((x, ph, cgate_t), ())}
|
| 169 |
+
actual = generate_gate_rules(x*ph*cgate_t)
|
| 170 |
+
assert actual == gate_rules
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_generate_equivalent_ids_1():
|
| 174 |
+
# Test with tuples
|
| 175 |
+
(x, y, z, h) = create_gate_sequence()
|
| 176 |
+
|
| 177 |
+
assert generate_equivalent_ids((x,)) == {(x,)}
|
| 178 |
+
assert generate_equivalent_ids((x, x)) == {(x, x)}
|
| 179 |
+
assert generate_equivalent_ids((x, y)) == {(x, y), (y, x)}
|
| 180 |
+
|
| 181 |
+
gate_seq = (x, y, z)
|
| 182 |
+
gate_ids = {(x, y, z), (y, z, x), (z, x, y), (z, y, x),
|
| 183 |
+
(y, x, z), (x, z, y)}
|
| 184 |
+
assert generate_equivalent_ids(gate_seq) == gate_ids
|
| 185 |
+
|
| 186 |
+
gate_ids = {Mul(x, y, z), Mul(y, z, x), Mul(z, x, y),
|
| 187 |
+
Mul(z, y, x), Mul(y, x, z), Mul(x, z, y)}
|
| 188 |
+
assert generate_equivalent_ids(gate_seq, return_as_muls=True) == gate_ids
|
| 189 |
+
|
| 190 |
+
gate_seq = (x, y, z, h)
|
| 191 |
+
gate_ids = {(x, y, z, h), (y, z, h, x),
|
| 192 |
+
(h, x, y, z), (h, z, y, x),
|
| 193 |
+
(z, y, x, h), (y, x, h, z),
|
| 194 |
+
(z, h, x, y), (x, h, z, y)}
|
| 195 |
+
assert generate_equivalent_ids(gate_seq) == gate_ids
|
| 196 |
+
|
| 197 |
+
gate_seq = (x, y, x, y)
|
| 198 |
+
gate_ids = {(x, y, x, y), (y, x, y, x)}
|
| 199 |
+
assert generate_equivalent_ids(gate_seq) == gate_ids
|
| 200 |
+
|
| 201 |
+
cgate_y = CGate((1,), y)
|
| 202 |
+
gate_seq = (y, cgate_y, y, cgate_y)
|
| 203 |
+
gate_ids = {(y, cgate_y, y, cgate_y), (cgate_y, y, cgate_y, y)}
|
| 204 |
+
assert generate_equivalent_ids(gate_seq) == gate_ids
|
| 205 |
+
|
| 206 |
+
cnot = CNOT(1, 0)
|
| 207 |
+
cgate_z = CGate((0,), Z(1))
|
| 208 |
+
gate_seq = (cnot, h, cgate_z, h)
|
| 209 |
+
gate_ids = {(cnot, h, cgate_z, h), (h, cgate_z, h, cnot),
|
| 210 |
+
(h, cnot, h, cgate_z), (cgate_z, h, cnot, h)}
|
| 211 |
+
assert generate_equivalent_ids(gate_seq) == gate_ids
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_generate_equivalent_ids_2():
|
| 215 |
+
# Test with Muls
|
| 216 |
+
(x, y, z, h) = create_gate_sequence()
|
| 217 |
+
|
| 218 |
+
assert generate_equivalent_ids((x,), return_as_muls=True) == {x}
|
| 219 |
+
|
| 220 |
+
gate_ids = {Integer(1)}
|
| 221 |
+
assert generate_equivalent_ids(x*x, return_as_muls=True) == gate_ids
|
| 222 |
+
|
| 223 |
+
gate_ids = {x*y, y*x}
|
| 224 |
+
assert generate_equivalent_ids(x*y, return_as_muls=True) == gate_ids
|
| 225 |
+
|
| 226 |
+
gate_ids = {(x, y), (y, x)}
|
| 227 |
+
assert generate_equivalent_ids(x*y) == gate_ids
|
| 228 |
+
|
| 229 |
+
circuit = Mul(*(x, y, z))
|
| 230 |
+
gate_ids = {x*y*z, y*z*x, z*x*y, z*y*x,
|
| 231 |
+
y*x*z, x*z*y}
|
| 232 |
+
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
|
| 233 |
+
|
| 234 |
+
circuit = Mul(*(x, y, z, h))
|
| 235 |
+
gate_ids = {x*y*z*h, y*z*h*x,
|
| 236 |
+
h*x*y*z, h*z*y*x,
|
| 237 |
+
z*y*x*h, y*x*h*z,
|
| 238 |
+
z*h*x*y, x*h*z*y}
|
| 239 |
+
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
|
| 240 |
+
|
| 241 |
+
circuit = Mul(*(x, y, x, y))
|
| 242 |
+
gate_ids = {x*y*x*y, y*x*y*x}
|
| 243 |
+
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
|
| 244 |
+
|
| 245 |
+
cgate_y = CGate((1,), y)
|
| 246 |
+
circuit = Mul(*(y, cgate_y, y, cgate_y))
|
| 247 |
+
gate_ids = {y*cgate_y*y*cgate_y, cgate_y*y*cgate_y*y}
|
| 248 |
+
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
|
| 249 |
+
|
| 250 |
+
cnot = CNOT(1, 0)
|
| 251 |
+
cgate_z = CGate((0,), Z(1))
|
| 252 |
+
circuit = Mul(*(cnot, h, cgate_z, h))
|
| 253 |
+
gate_ids = {cnot*h*cgate_z*h, h*cgate_z*h*cnot,
|
| 254 |
+
h*cnot*h*cgate_z, cgate_z*h*cnot*h}
|
| 255 |
+
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def test_is_scalar_nonsparse_matrix():
|
| 259 |
+
numqubits = 2
|
| 260 |
+
id_only = False
|
| 261 |
+
|
| 262 |
+
id_gate = (IdentityGate(1),)
|
| 263 |
+
actual = is_scalar_nonsparse_matrix(id_gate, numqubits, id_only)
|
| 264 |
+
assert actual is True
|
| 265 |
+
|
| 266 |
+
x0 = X(0)
|
| 267 |
+
xx_circuit = (x0, x0)
|
| 268 |
+
actual = is_scalar_nonsparse_matrix(xx_circuit, numqubits, id_only)
|
| 269 |
+
assert actual is True
|
| 270 |
+
|
| 271 |
+
x1 = X(1)
|
| 272 |
+
y1 = Y(1)
|
| 273 |
+
xy_circuit = (x1, y1)
|
| 274 |
+
actual = is_scalar_nonsparse_matrix(xy_circuit, numqubits, id_only)
|
| 275 |
+
assert actual is False
|
| 276 |
+
|
| 277 |
+
z1 = Z(1)
|
| 278 |
+
xyz_circuit = (x1, y1, z1)
|
| 279 |
+
actual = is_scalar_nonsparse_matrix(xyz_circuit, numqubits, id_only)
|
| 280 |
+
assert actual is True
|
| 281 |
+
|
| 282 |
+
cnot = CNOT(1, 0)
|
| 283 |
+
cnot_circuit = (cnot, cnot)
|
| 284 |
+
actual = is_scalar_nonsparse_matrix(cnot_circuit, numqubits, id_only)
|
| 285 |
+
assert actual is True
|
| 286 |
+
|
| 287 |
+
h = H(0)
|
| 288 |
+
hh_circuit = (h, h)
|
| 289 |
+
actual = is_scalar_nonsparse_matrix(hh_circuit, numqubits, id_only)
|
| 290 |
+
assert actual is True
|
| 291 |
+
|
| 292 |
+
h1 = H(1)
|
| 293 |
+
xhzh_circuit = (x1, h1, z1, h1)
|
| 294 |
+
actual = is_scalar_nonsparse_matrix(xhzh_circuit, numqubits, id_only)
|
| 295 |
+
assert actual is True
|
| 296 |
+
|
| 297 |
+
id_only = True
|
| 298 |
+
actual = is_scalar_nonsparse_matrix(xhzh_circuit, numqubits, id_only)
|
| 299 |
+
assert actual is True
|
| 300 |
+
actual = is_scalar_nonsparse_matrix(xyz_circuit, numqubits, id_only)
|
| 301 |
+
assert actual is False
|
| 302 |
+
actual = is_scalar_nonsparse_matrix(cnot_circuit, numqubits, id_only)
|
| 303 |
+
assert actual is True
|
| 304 |
+
actual = is_scalar_nonsparse_matrix(hh_circuit, numqubits, id_only)
|
| 305 |
+
assert actual is True
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def test_is_scalar_sparse_matrix():
|
| 309 |
+
np = import_module('numpy')
|
| 310 |
+
if not np:
|
| 311 |
+
skip("numpy not installed.")
|
| 312 |
+
|
| 313 |
+
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
|
| 314 |
+
if not scipy:
|
| 315 |
+
skip("scipy not installed.")
|
| 316 |
+
|
| 317 |
+
numqubits = 2
|
| 318 |
+
id_only = False
|
| 319 |
+
|
| 320 |
+
id_gate = (IdentityGate(1),)
|
| 321 |
+
assert is_scalar_sparse_matrix(id_gate, numqubits, id_only) is True
|
| 322 |
+
|
| 323 |
+
x0 = X(0)
|
| 324 |
+
xx_circuit = (x0, x0)
|
| 325 |
+
assert is_scalar_sparse_matrix(xx_circuit, numqubits, id_only) is True
|
| 326 |
+
|
| 327 |
+
x1 = X(1)
|
| 328 |
+
y1 = Y(1)
|
| 329 |
+
xy_circuit = (x1, y1)
|
| 330 |
+
assert is_scalar_sparse_matrix(xy_circuit, numqubits, id_only) is False
|
| 331 |
+
|
| 332 |
+
z1 = Z(1)
|
| 333 |
+
xyz_circuit = (x1, y1, z1)
|
| 334 |
+
assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is True
|
| 335 |
+
|
| 336 |
+
cnot = CNOT(1, 0)
|
| 337 |
+
cnot_circuit = (cnot, cnot)
|
| 338 |
+
assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True
|
| 339 |
+
|
| 340 |
+
h = H(0)
|
| 341 |
+
hh_circuit = (h, h)
|
| 342 |
+
assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True
|
| 343 |
+
|
| 344 |
+
# NOTE:
|
| 345 |
+
# The elements of the sparse matrix for the following circuit
|
| 346 |
+
# is actually 1.0000000000000002+0.0j.
|
| 347 |
+
h1 = H(1)
|
| 348 |
+
xhzh_circuit = (x1, h1, z1, h1)
|
| 349 |
+
assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True
|
| 350 |
+
|
| 351 |
+
id_only = True
|
| 352 |
+
assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True
|
| 353 |
+
assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is False
|
| 354 |
+
assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True
|
| 355 |
+
assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def test_is_degenerate():
|
| 359 |
+
(x, y, z, h) = create_gate_sequence()
|
| 360 |
+
|
| 361 |
+
gate_id = GateIdentity(x, y, z)
|
| 362 |
+
ids = {gate_id}
|
| 363 |
+
|
| 364 |
+
another_id = (z, y, x)
|
| 365 |
+
assert is_degenerate(ids, another_id) is True
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def test_is_reducible():
|
| 369 |
+
nqubits = 2
|
| 370 |
+
(x, y, z, h) = create_gate_sequence()
|
| 371 |
+
|
| 372 |
+
circuit = (x, y, y)
|
| 373 |
+
assert is_reducible(circuit, nqubits, 1, 3) is True
|
| 374 |
+
|
| 375 |
+
circuit = (x, y, x)
|
| 376 |
+
assert is_reducible(circuit, nqubits, 1, 3) is False
|
| 377 |
+
|
| 378 |
+
circuit = (x, y, y, x)
|
| 379 |
+
assert is_reducible(circuit, nqubits, 0, 4) is True
|
| 380 |
+
|
| 381 |
+
circuit = (x, y, y, x)
|
| 382 |
+
assert is_reducible(circuit, nqubits, 1, 3) is True
|
| 383 |
+
|
| 384 |
+
circuit = (x, y, z, y, y)
|
| 385 |
+
assert is_reducible(circuit, nqubits, 1, 5) is True
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def test_bfs_identity_search():
|
| 389 |
+
assert bfs_identity_search([], 1) == set()
|
| 390 |
+
|
| 391 |
+
(x, y, z, h) = create_gate_sequence()
|
| 392 |
+
|
| 393 |
+
gate_list = [x]
|
| 394 |
+
id_set = {GateIdentity(x, x)}
|
| 395 |
+
assert bfs_identity_search(gate_list, 1, max_depth=2) == id_set
|
| 396 |
+
|
| 397 |
+
# Set should not contain degenerate quantum circuits
|
| 398 |
+
gate_list = [x, y, z]
|
| 399 |
+
id_set = {GateIdentity(x, x),
|
| 400 |
+
GateIdentity(y, y),
|
| 401 |
+
GateIdentity(z, z),
|
| 402 |
+
GateIdentity(x, y, z)}
|
| 403 |
+
assert bfs_identity_search(gate_list, 1) == id_set
|
| 404 |
+
|
| 405 |
+
id_set = {GateIdentity(x, x),
|
| 406 |
+
GateIdentity(y, y),
|
| 407 |
+
GateIdentity(z, z),
|
| 408 |
+
GateIdentity(x, y, z),
|
| 409 |
+
GateIdentity(x, y, x, y),
|
| 410 |
+
GateIdentity(x, z, x, z),
|
| 411 |
+
GateIdentity(y, z, y, z)}
|
| 412 |
+
assert bfs_identity_search(gate_list, 1, max_depth=4) == id_set
|
| 413 |
+
assert bfs_identity_search(gate_list, 1, max_depth=5) == id_set
|
| 414 |
+
|
| 415 |
+
gate_list = [x, y, z, h]
|
| 416 |
+
id_set = {GateIdentity(x, x),
|
| 417 |
+
GateIdentity(y, y),
|
| 418 |
+
GateIdentity(z, z),
|
| 419 |
+
GateIdentity(h, h),
|
| 420 |
+
GateIdentity(x, y, z),
|
| 421 |
+
GateIdentity(x, y, x, y),
|
| 422 |
+
GateIdentity(x, z, x, z),
|
| 423 |
+
GateIdentity(x, h, z, h),
|
| 424 |
+
GateIdentity(y, z, y, z),
|
| 425 |
+
GateIdentity(y, h, y, h)}
|
| 426 |
+
assert bfs_identity_search(gate_list, 1) == id_set
|
| 427 |
+
|
| 428 |
+
id_set = {GateIdentity(x, x),
|
| 429 |
+
GateIdentity(y, y),
|
| 430 |
+
GateIdentity(z, z),
|
| 431 |
+
GateIdentity(h, h)}
|
| 432 |
+
assert id_set == bfs_identity_search(gate_list, 1, max_depth=3,
|
| 433 |
+
identity_only=True)
|
| 434 |
+
|
| 435 |
+
id_set = {GateIdentity(x, x),
|
| 436 |
+
GateIdentity(y, y),
|
| 437 |
+
GateIdentity(z, z),
|
| 438 |
+
GateIdentity(h, h),
|
| 439 |
+
GateIdentity(x, y, z),
|
| 440 |
+
GateIdentity(x, y, x, y),
|
| 441 |
+
GateIdentity(x, z, x, z),
|
| 442 |
+
GateIdentity(x, h, z, h),
|
| 443 |
+
GateIdentity(y, z, y, z),
|
| 444 |
+
GateIdentity(y, h, y, h),
|
| 445 |
+
GateIdentity(x, y, h, x, h),
|
| 446 |
+
GateIdentity(x, z, h, y, h),
|
| 447 |
+
GateIdentity(y, z, h, z, h)}
|
| 448 |
+
assert bfs_identity_search(gate_list, 1, max_depth=5) == id_set
|
| 449 |
+
|
| 450 |
+
id_set = {GateIdentity(x, x),
|
| 451 |
+
GateIdentity(y, y),
|
| 452 |
+
GateIdentity(z, z),
|
| 453 |
+
GateIdentity(h, h),
|
| 454 |
+
GateIdentity(x, h, z, h)}
|
| 455 |
+
assert id_set == bfs_identity_search(gate_list, 1, max_depth=4,
|
| 456 |
+
identity_only=True)
|
| 457 |
+
|
| 458 |
+
cnot = CNOT(1, 0)
|
| 459 |
+
gate_list = [x, cnot]
|
| 460 |
+
id_set = {GateIdentity(x, x),
|
| 461 |
+
GateIdentity(cnot, cnot),
|
| 462 |
+
GateIdentity(x, cnot, x, cnot)}
|
| 463 |
+
assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
|
| 464 |
+
|
| 465 |
+
cgate_x = CGate((1,), x)
|
| 466 |
+
gate_list = [x, cgate_x]
|
| 467 |
+
id_set = {GateIdentity(x, x),
|
| 468 |
+
GateIdentity(cgate_x, cgate_x),
|
| 469 |
+
GateIdentity(x, cgate_x, x, cgate_x)}
|
| 470 |
+
assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
|
| 471 |
+
|
| 472 |
+
cgate_z = CGate((0,), Z(1))
|
| 473 |
+
gate_list = [cnot, cgate_z, h]
|
| 474 |
+
id_set = {GateIdentity(h, h),
|
| 475 |
+
GateIdentity(cgate_z, cgate_z),
|
| 476 |
+
GateIdentity(cnot, cnot),
|
| 477 |
+
GateIdentity(cnot, h, cgate_z, h)}
|
| 478 |
+
assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
|
| 479 |
+
|
| 480 |
+
s = PhaseGate(0)
|
| 481 |
+
t = TGate(0)
|
| 482 |
+
gate_list = [s, t]
|
| 483 |
+
id_set = {GateIdentity(s, s, s, s)}
|
| 484 |
+
assert bfs_identity_search(gate_list, 1, max_depth=4) == id_set
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def test_bfs_identity_search_xfail():
|
| 488 |
+
s = PhaseGate(0)
|
| 489 |
+
t = TGate(0)
|
| 490 |
+
gate_list = [Dagger(s), t]
|
| 491 |
+
id_set = {GateIdentity(Dagger(s), t, t)}
|
| 492 |
+
assert bfs_identity_search(gate_list, 1, max_depth=3) == id_set
|
wemm/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_represent.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import (Float, I, Integer)
|
| 2 |
+
from sympy.matrices.dense import Matrix
|
| 3 |
+
from sympy.external import import_module
|
| 4 |
+
from sympy.testing.pytest import skip
|
| 5 |
+
|
| 6 |
+
from sympy.physics.quantum.dagger import Dagger
|
| 7 |
+
from sympy.physics.quantum.represent import (represent, rep_innerproduct,
|
| 8 |
+
rep_expectation, enumerate_states)
|
| 9 |
+
from sympy.physics.quantum.state import Bra, Ket
|
| 10 |
+
from sympy.physics.quantum.operator import Operator, OuterProduct
|
| 11 |
+
from sympy.physics.quantum.tensorproduct import TensorProduct
|
| 12 |
+
from sympy.physics.quantum.tensorproduct import matrix_tensor_product
|
| 13 |
+
from sympy.physics.quantum.commutator import Commutator
|
| 14 |
+
from sympy.physics.quantum.anticommutator import AntiCommutator
|
| 15 |
+
from sympy.physics.quantum.innerproduct import InnerProduct
|
| 16 |
+
from sympy.physics.quantum.matrixutils import (numpy_ndarray,
|
| 17 |
+
scipy_sparse_matrix, to_numpy,
|
| 18 |
+
to_scipy_sparse, to_sympy)
|
| 19 |
+
from sympy.physics.quantum.cartesian import XKet, XOp, XBra
|
| 20 |
+
from sympy.physics.quantum.qapply import qapply
|
| 21 |
+
from sympy.physics.quantum.operatorset import operators_to_state
|
| 22 |
+
from sympy.testing.pytest import raises
|
| 23 |
+
|
| 24 |
+
Amat = Matrix([[1, I], [-I, 1]])
|
| 25 |
+
Bmat = Matrix([[1, 2], [3, 4]])
|
| 26 |
+
Avec = Matrix([[1], [I]])
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class AKet(Ket):
|
| 30 |
+
|
| 31 |
+
@classmethod
|
| 32 |
+
def dual_class(self):
|
| 33 |
+
return ABra
|
| 34 |
+
|
| 35 |
+
def _represent_default_basis(self, **options):
|
| 36 |
+
return self._represent_AOp(None, **options)
|
| 37 |
+
|
| 38 |
+
def _represent_AOp(self, basis, **options):
|
| 39 |
+
return Avec
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class ABra(Bra):
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def dual_class(self):
|
| 46 |
+
return AKet
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class AOp(Operator):
|
| 50 |
+
|
| 51 |
+
def _represent_default_basis(self, **options):
|
| 52 |
+
return self._represent_AOp(None, **options)
|
| 53 |
+
|
| 54 |
+
def _represent_AOp(self, basis, **options):
|
| 55 |
+
return Amat
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class BOp(Operator):
|
| 59 |
+
|
| 60 |
+
def _represent_default_basis(self, **options):
|
| 61 |
+
return self._represent_AOp(None, **options)
|
| 62 |
+
|
| 63 |
+
def _represent_AOp(self, basis, **options):
|
| 64 |
+
return Bmat
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
k = AKet('a')
|
| 68 |
+
b = ABra('a')
|
| 69 |
+
A = AOp('A')
|
| 70 |
+
B = BOp('B')
|
| 71 |
+
|
| 72 |
+
_tests = [
|
| 73 |
+
# Bra
|
| 74 |
+
(b, Dagger(Avec)),
|
| 75 |
+
(Dagger(b), Avec),
|
| 76 |
+
# Ket
|
| 77 |
+
(k, Avec),
|
| 78 |
+
(Dagger(k), Dagger(Avec)),
|
| 79 |
+
# Operator
|
| 80 |
+
(A, Amat),
|
| 81 |
+
(Dagger(A), Dagger(Amat)),
|
| 82 |
+
# OuterProduct
|
| 83 |
+
(OuterProduct(k, b), Avec*Avec.H),
|
| 84 |
+
# TensorProduct
|
| 85 |
+
(TensorProduct(A, B), matrix_tensor_product(Amat, Bmat)),
|
| 86 |
+
# Pow
|
| 87 |
+
(A**2, Amat**2),
|
| 88 |
+
# Add/Mul
|
| 89 |
+
(A*B + 2*A, Amat*Bmat + 2*Amat),
|
| 90 |
+
# Commutator
|
| 91 |
+
(Commutator(A, B), Amat*Bmat - Bmat*Amat),
|
| 92 |
+
# AntiCommutator
|
| 93 |
+
(AntiCommutator(A, B), Amat*Bmat + Bmat*Amat),
|
| 94 |
+
# InnerProduct
|
| 95 |
+
(InnerProduct(b, k), (Avec.H*Avec)[0])
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_format_sympy():
|
| 100 |
+
for test in _tests:
|
| 101 |
+
lhs = represent(test[0], basis=A, format='sympy')
|
| 102 |
+
rhs = to_sympy(test[1])
|
| 103 |
+
assert lhs == rhs
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_scalar_sympy():
|
| 107 |
+
assert represent(Integer(1)) == Integer(1)
|
| 108 |
+
assert represent(Float(1.0)) == Float(1.0)
|
| 109 |
+
assert represent(1.0 + I) == 1.0 + I
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
np = import_module('numpy')
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_format_numpy():
|
| 116 |
+
if not np:
|
| 117 |
+
skip("numpy not installed.")
|
| 118 |
+
|
| 119 |
+
for test in _tests:
|
| 120 |
+
lhs = represent(test[0], basis=A, format='numpy')
|
| 121 |
+
rhs = to_numpy(test[1])
|
| 122 |
+
if isinstance(lhs, numpy_ndarray):
|
| 123 |
+
assert (lhs == rhs).all()
|
| 124 |
+
else:
|
| 125 |
+
assert lhs == rhs
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_scalar_numpy():
|
| 129 |
+
if not np:
|
| 130 |
+
skip("numpy not installed.")
|
| 131 |
+
|
| 132 |
+
assert represent(Integer(1), format='numpy') == 1
|
| 133 |
+
assert represent(Float(1.0), format='numpy') == 1.0
|
| 134 |
+
assert represent(1.0 + I, format='numpy') == 1.0 + 1.0j
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_format_scipy_sparse():
|
| 141 |
+
if not np:
|
| 142 |
+
skip("numpy not installed.")
|
| 143 |
+
if not scipy:
|
| 144 |
+
skip("scipy not installed.")
|
| 145 |
+
|
| 146 |
+
for test in _tests:
|
| 147 |
+
lhs = represent(test[0], basis=A, format='scipy.sparse')
|
| 148 |
+
rhs = to_scipy_sparse(test[1])
|
| 149 |
+
if isinstance(lhs, scipy_sparse_matrix):
|
| 150 |
+
assert np.linalg.norm((lhs - rhs).todense()) == 0.0
|
| 151 |
+
else:
|
| 152 |
+
assert lhs == rhs
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_scalar_scipy_sparse():
|
| 156 |
+
if not np:
|
| 157 |
+
skip("numpy not installed.")
|
| 158 |
+
if not scipy:
|
| 159 |
+
skip("scipy not installed.")
|
| 160 |
+
|
| 161 |
+
assert represent(Integer(1), format='scipy.sparse') == 1
|
| 162 |
+
assert represent(Float(1.0), format='scipy.sparse') == 1.0
|
| 163 |
+
assert represent(1.0 + I, format='scipy.sparse') == 1.0 + 1.0j
|
| 164 |
+
|
| 165 |
+
x_ket = XKet('x')
|
| 166 |
+
x_bra = XBra('x')
|
| 167 |
+
x_op = XOp('X')
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_innerprod_represent():
|
| 171 |
+
assert rep_innerproduct(x_ket) == InnerProduct(XBra("x_1"), x_ket).doit()
|
| 172 |
+
assert rep_innerproduct(x_bra) == InnerProduct(x_bra, XKet("x_1")).doit()
|
| 173 |
+
raises(TypeError, lambda: rep_innerproduct(x_op))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_operator_represent():
|
| 177 |
+
basis_kets = enumerate_states(operators_to_state(x_op), 1, 2)
|
| 178 |
+
assert rep_expectation(
|
| 179 |
+
x_op) == qapply(basis_kets[1].dual*x_op*basis_kets[0])
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_enumerate_states():
|
| 183 |
+
test = XKet("foo")
|
| 184 |
+
assert enumerate_states(test, 1, 1) == [XKet("foo_1")]
|
| 185 |
+
assert enumerate_states(
|
| 186 |
+
test, [1, 2, 4]) == [XKet("foo_1"), XKet("foo_2"), XKet("foo_4")]
|
wemm/lib/python3.10/site-packages/sympy/physics/tests/__init__.py
ADDED
|
File without changes
|
wemm/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc
ADDED
|
Binary file (8.28 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc
ADDED
|
Binary file (5.24 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc
ADDED
|
Binary file (1.61 kB). View file
|
|
|