def __init__(self, *args, **kwargs): name = 'ground' super().__init__(name) self.P_ground = quatrenion('Pg_%s' % self.name, format_as=r'{Pg_{%s}}' % self.name) self.normalized_pos_equation = sm.BlockMatrix( [[self.R], [self.P - self.P_ground]]) self.normalized_vel_equation = sm.BlockMatrix([[zero_matrix(3, 1)], [zero_matrix(4, 1)]]) self.normalized_acc_equation = sm.BlockMatrix([[zero_matrix(3, 1)], [zero_matrix(4, 1)]]) self.normalized_jacobian = sm.BlockMatrix( [[sm.Identity(3), zero_matrix(3, 4)], [zero_matrix(4, 3), sm.Identity(4)]])
def density_density_entangler_propagator(α, β, Λ, δ): """ β is the interaction strength: β \int n(x) n(y) exp(-Λ|x-y|) dx dy """ ϵ = sympy.symbols('e') b = sympy.Matrix(np.array([[0, 1], [0, 0]])) bd = b.T n = bd * b A = sympy.Identity(6) * (1 - ϵ * Λ) B = np.concatenate([ np.sqrt(1j * α) * sympy.sqrt(ϵ) * bd, np.sqrt(-1j * α) * sympy.sqrt(ϵ) * b, np.sqrt(2 * β) * n ], axis=0) C = np.concatenate([ np.sqrt(1j * α) * sympy.sqrt(ϵ) * bd, np.sqrt(-1j * α) * sympy.sqrt(ϵ) * b, np.sqrt(2 * β) * n ], axis=1) D = sympy.ZeroMatrix(2, 2) tmp1 = np.concatenate([sympy.Identity(2) + δ * D, np.sqrt(δ) * C], axis=1) tmp2 = np.concatenate([np.sqrt(δ) * B, A], axis=1) tmp = np.concatenate([tmp1, tmp2], axis=0) cmpo = np.transpose(np.reshape(tmp, (4, 2, 4, 2)), (0, 2, 1, 3)) #(M, M, dout, din) Gammas = [[None, None], [None, None]] for d1, d2 in itertools.product([0, 1], [0, 1]): M = cmpo.shape[0] tmp = np.zeros((M, M), dtype=np.complex128) if d1 != d2: cmpo_tmp = cmpo[:, :, d1, d2] for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].coeff('sqrt(e)')) elif (d1 == 0) and (d2 == 0): cmpo_tmp = cmpo[:, :, d1, d2] - sympy.Identity(M) for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].coeff('e')) elif (d1 == 1) and (d2 == 1): cmpo_tmp = cmpo[:, :, d1, d2] - sympy.Identity(M) for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].subs([('e', 0), ('sqrt(e)', 0)])) Gammas[d1][d2] = tmp return Gammas
def generate_transformation_matrix_2d(In_frame, origin, reference_frame, point): '''shamplessly modified version of pydy's 3D transfromation ! Generate a symbolic 2D transformation matrix, with respect to the reference frame and point. INPUTS: - In_frame : Inertial reference frame - reference_frame : A frame with respect to whicht transformation matrix is generated - Point : A point with respect to which transformation is generated ''' rotation_matrix = In_frame.dcm(reference_frame) rotation_matrix_2d = sm.Matrix([ rotation_matrix[i, j] for i in range(2) for j in range(2) ]).reshape(2, 2) trans_matrix = sm.Identity(3).as_mutable() trans_matrix[:2, :2] = rotation_matrix_2d # defining the vector from origin to the point point_vector = origin.pos_from(point) # calculating translation part of Transformation Matrix trans_matrix[2, 0] = point_vector.dot(reference_frame.x) trans_matrix[2, 1] = point_vector.dot(reference_frame.y) return trans_matrix
def generate_reduced_x_solutions(self) -> list[sp.Matrix]: nCampate = self.nCampate L, P, Q, EJ = self.generate_simbolic_variables() flex_rid, P_rid = self.generate_reduced_Flex_matrix_and_P_vector() # List of numeric values taken from Beam lenghts = self.beam.spans_lenght() ej = self.beam.spans_ej() # To solve the system for a generic Q=1 we have to subtistute values and then solve the systen for every span. # With Q values we have to subsistute them one at time and the must be other zero. # Example with the first span: Q1 = 1, Q2 = 0 , Q3 = 0, ... # Example with the second span: Q1 =0, Q2 = 1 , Q3 = 0, ... # To do this I'm using the Identidy matrix # Every x_solution_vector is added to a list list_of_reduced_x_solution_vectors = [] for n_span in range(nCampate): flex_sub = ( flex_rid.subs(zip(L, lenghts)) .subs(zip(EJ, ej)) .subs(zip(Q, np.array(sp.Identity(nCampate))[n_span])) ) P_sub = ( P_rid.subs(zip(L, lenghts)) .subs(zip(EJ, ej)) .subs(zip(Q, np.identity(nCampate)[n_span])) ) # solve the system: # --- maybe there is a more efificient way x = -flex_sub.inv() * P_sub list_of_reduced_x_solution_vectors.append(x) return list_of_reduced_x_solution_vectors
def _M_prod(self, i_tuple, l): M = self.M if self.bisim: prod = sympy.Identity(self.n) else: prod = np.eye(self.n) for i in range(l): prod = M[i_tuple[i]] @ prod return prod
def getPosterior(self): self.S = self.H * self.P1 * self.H.transpose() + self.R self.K_el = self.P1 * self.H.transpose() * self.S[0]**-1 self.K = sp.Matrix( sp.MatrixSymbol('K', self.K_el.shape[0], self.K_el.shape[1])) self.y_el = sp.Matrix([[self.z]]) - (self.H * self.x1) self.y = sp.Matrix( sp.MatrixSymbol('y', self.y_el.shape[0], self.y_el.shape[1])) self.x2 = self.x1 + self.K * self.y self.P2 = sp.Identity(self.P1.shape[0]).as_explicit( ) * self.P1 - self.K * self.H * self.P1
def __init__(self, name): self._name = name super().__init__(name) splited_name = name.split('.') self.id_name = ''.join(splited_name[-1]) self.prefix = '.'.join(splited_name[:-1]) self.prefix = (self.prefix + '.' if self.prefix != '' else self.prefix) format_ = (self.prefix, self.id_name) self.R = vector('%sR_%s' % format_, format_as=r'{%sR_{%s}}' % format_) self.P = quatrenion('%sP_%s' % format_, format_as=r'{%sP_{%s}}' % format_) self.Rd = vector('%sRd_%s' % format_, format_as=r'{%s\dot{R}_{%s}}' % format_) self.Pd = quatrenion('%sPd_%s' % format_, format_as=r'{%s\dot{P}_{%s}}' % format_) self.Rdd = vector('%sRdd_%s' % format_, format_as=r'{%s\ddot{R}_{%s}}' % format_) self.Pdd = quatrenion('%sPdd_%s' % format_, format_as=r'{%s\ddot{P}_{%s}}' % format_) self.A = A(self.P) self.G = G(self.P) self.E = E(self.P) self.normalized_pos_equation = (self.P.T * self.P) - sm.Identity(1) self.normalized_vel_equation = zero_matrix(1, 1) self.normalized_acc_equation = 2 * (self.Pd.T * self.Pd) self.normalized_jacobian = [zero_matrix(1, 3), 2 * self.P.T] self.m = sm.symbols('m_%s' % self.id_name) self.M = self.m * sm.Identity(3) self.Jbar = matrix_symbol('%sJbar_%s' % format_, 3, 3, r'{%s\bar{J}_{%s}}' % format_) self.J = 4 * G(self.P).T * self.Jbar * G(self.P)
def resample(input_field, output_field, interpolation_mode='linear'): """ Resample input_field with its coordinate system in terms of the coordinate system of output_field :param input_field: :param output_field: """ return generic_spatial_matrix_transform( input_field, output_field, sympy.Matrix(sympy.Identity(input_field.spatial_dimensions)), interpolation_mode=interpolation_mode)
def _construct_force_vector(self): dij = (self.Ri + self.ui - self.Rj - self.uj) dijd = (self.Rdi + self.Bui*self.Pdi - self.Rdj - self.Buj*self.Pdj) dij_bush_i = self.mi_bar.A.T * self.Ai.T * dij dijd_bush_i = self.mi_bar.A.T * self.Ai.T * dijd F_bush_i = (self.Kt*sm.Identity(3) * dij_bush_i) \ + (self.Ct*sm.Identity(3) * dijd_bush_i) self.Fi = self.Ai * self.mi_bar.A * -F_bush_i Ti_e = - 2*E(self.Pi).T * Skew(self.ui).T * self.Fi self._Qi = sm.BlockMatrix([[self.Fi], [Ti_e]]) dij_bush_j = self.mj_bar.A.T * self.Aj.T * dij dijd_bush_j = self.mj_bar.A.T * self.Aj.T * dijd F_bush_j = (self.Kt*sm.Identity(3) * dij_bush_j) \ + (self.Ct*sm.Identity(3) * dijd_bush_j) self.Fj = self.Aj * self.mj_bar.A * F_bush_j Tj_e = - 2*E(self.Pj).T * Skew(self.uj).T * self.Fj self._Qj = sm.BlockMatrix([[self.Fj], [Tj_e]])
def gen_sigmas(): """generate Pauli matrices. Usage:\n sp.Matrix(np.dot(vec, sigmas).reshape(2,2)) """ sigmas = [] for i in range(4): if (i == 0): sigma = sp.Identity(2).as_explicit() else: sigma = sp.ImmutableMatrix(msigma(i)) sigmas.append(sigma) return sigmas
def learn(self): """ :return: True iff a solution has been computed. Use get_solution() to retrieve it """ if self.iter > -1: self.solution = self._solve(min_sum=self._min_sum, max_sum=self._max_sum) log("learner %s" % self.solution) else: # correct solution of 6-dim [sp.diag(1, 0, 3, 3, 0, 2), sp.diag(0, 2, 0, 0, 1, 0)] self.solution = [ -sp.Identity(self.n), sp.zeros(self.n, self.n) ]#[+sp.Identity(self.n) for _ in range(len(self.P_sym))] res = self._valid_sol(self.solution) self.iter += 1 return res
def __init__(self, A, x, B, u, z, H): self.A = A self.x0 = x self.B = B self.u = u self.z = z self.H = H self.dkron = sp.Identity(A.shape[0]).as_explicit() self.Q = sp.Matrix(sp.MatrixSymbol('Q', A.shape[0], A.shape[1])) self.Q = sp.Matrix( [[self.Q[i, j] * self.dkron[i, j] for i in range(A.shape[0])] for j in range(A.shape[1])]) self.R = sp.Matrix([[sp.Symbol('R')]]) self.P0 = sp.Matrix(sp.MatrixSymbol('P_0', A.shape[0], A.shape[1]))
def learn(self): """ :return: True iff a solution has been computed. Use get_solution() to retrieve it """ if self.iter > -1: self.solution, self._has_timedout = self._solve( min_sum=self._min_sum, max_sum=self._max_sum) log("learner %s" % self.solution) else: self.solution = [ -sp.Identity(self.n) for _ in range(len(self.P_sym)) ] res = self._valid_sol(self.solution) self.iter += 1 return res
def gaussian(input_symbols, sigma=1): """gaussian :param input_symbols: Input symbols for each dimension :param sigma: Standard deviation or covariance matrix """ ndim = len(input_symbols) if not isinstance(sigma, sympy.Matrix): covariance_matrix = sympy.Matrix(sympy.Identity(ndim)) * sigma * sigma else: covariance_matrix = sigma x = sympy.Matrix(input_symbols) return sympy.sqrt(sympy.pi**ndim / covariance_matrix.det()) * \ sympy.exp((-x.transpose() @ covariance_matrix.inv() @ x)[0, 0])
def generate_projections(vol): import pycuda.autoinit # noqa from conebeam_projector import CudaProjector import pyconrad.config from pycuda.gpuarray import to_gpu, zeros pyconrad.config.set_reco_shape(vol.shape) pyconrad.config.center_volume() rotation = np.random.rand(3) * 2 * np.pi rotation_matrix = np.array( sympy.rot_axis1(rotation[0]) * sympy.rot_axis2(rotation[1]) * sympy.rot_axis3(rotation[2])) extended_rotation = sympy.Identity(4).as_explicit().as_mutable() extended_rotation[:3, :3] = rotation_matrix extended_rotation = np.array(extended_rotation) matrices = pyconrad.config.get_projection_matrices() idx = random.randint(0, len(matrices) - 1) my_matrix = matrices[idx] @ extended_rotation from edu.stanford.rsl.conrad.geometry import Projection from edu.stanford.rsl.conrad.numerics import SimpleMatrix pyconrad.config.get_geometry().setProjectionMatrix( idx, Projection(SimpleMatrix.from_numpy(my_matrix))) projector = CudaProjector() vol_gpu = to_gpu(vol) proj_gpu = zeros(pyconrad.config.get_sino_shape()[1:], np.float32) projector.forward_project_cuda_idx(vol_gpu, proj_gpu, idx) proj = proj_gpu.get() proj /= np.max(proj) detector_spacing = pyconrad.config.get_geometry().getPixelDimensionX() return proj, projector._projectionMatrices[idx], detector_spacing
def pos_level_equations(self): return sm.BlockMatrix([sm.Identity(1) * self._pos_level_equations[0]])
def acc_level_equations(self): return sm.BlockMatrix([ sm.Identity(1) * self._acc_level_equations[0] - sm.Identity(1) * self._acc_function ])
# Standard library imports import itertools # 3rd parties library imports import sympy as sm # Local application imports from .matrices import (reference_frame, vector, E, Skew, matrix_symbol) from .helpers import body_setter, name_setter # Commonly used variables I = sm.Identity(3) I1 = sm.Identity(1) class abstract_joint(object): r""" **Abstract Class** A class that acts as a base class for algebraic constraints equations. The class is used to construct spatial joints connecting body pairs as well as actuators that acts on joints or bodies. Parameters ---------- name : str Name of the joint instance. Should mimic a valid python variable name. body_i : body The 1st body isntance. Should be an instance of the `body` class. body_j : body The 2nd body isntance. Should be an instance of the `body` class.
import sympy as sp shape = 2 z = sp.MatrixSymbol('z', shape, 1) H = sp.MatrixSymbol('H', shape, shape) x = sp.MatrixSymbol('', shape, 1) R = sp.MatrixSymbol('R', shape, shape) x_bar = sp.MatrixSymbol('x_bar', shape, 1) P_bar = sp.MatrixSymbol('P_bar', shape, shape) I = sp.Identity(shape) z_bar = H * x_bar S = R + H * P_bar * H.T W = P_bar * H.T * S.inv() x_hat = x_bar + W * (z - H * x_bar) P_hat = (I - W * H) * P_bar
def euler_rotmat(order='xyz', frame='local', angles=None, unit='deg', str_symbols=None, showA=True, showN=True): """Euler rotation matrix given sequence, frame, and angles. This function calculates the algebraic rotation matrix (3x3) for a given sequence ('order' argument) of up to three elemental rotations of a given coordinate system ('frame' argument) around another coordinate system, the Euler (or Eulerian) angles [1]_. This function also calculates the numerical values of the rotation matrix when numerical values for the angles are inputed for each rotation axis. Use None as value if the rotation angle for the particular axis is unknown. The symbols for the angles are: alpha, beta, and gamma for the first, second, and third rotations, respectively. The matrix product is calulated from right to left and in the specified sequence for the Euler angles. The first letter will be the first rotation. The function will print and return the algebraic rotation matrix and the numerical rotation matrix if angles were inputed. Parameters ---------- order : string, optional (default = 'xyz') Sequence for the Euler angles, any combination of the letters x, y, and z with 1 to 3 letters is accepted to denote the elemental rotations. The first letter will be the first rotation. frame : string, optional (default = 'local') Coordinate system for which the rotations are calculated. Valid values are 'local' or 'global'. angles : list, array, or bool, optional (default = None) Numeric values of the rotation angles ordered as the 'order' parameter. Enter None for a rotation whith unknown value. unit : str, optional (default = 'deg') Unit of the input angles. str_symbols : list of strings, optional (default = None) New symbols for the angles, for instance, ['theta', 'phi', 'psi'] showA : bool, optional (default = True) True (1) displays the Algebraic rotation matrix in rich format. False (0) to not display. showN : bool, optional (default = True) True (1) displays the Numeric rotation matrix in rich format. False (0) to not display. Returns ------- R : Matrix Sympy object Rotation matrix (3x3) in algebraic format. Rn : Numpy array or Matrix Sympy object (only if angles are inputed) Numeric rotation matrix (if values for all angles were inputed) or a algebraic matrix with some of the algebraic angles substituted by the corresponding inputed numeric values. Notes ----- This code uses Sympy, the Python library for symbolic mathematics, to calculate the algebraic rotation matrix and shows this matrix in latex form possibly for using with the IPython Notebook, see [1]_. References ---------- .. [1] http://nbviewer.ipython.org/github/duartexyz/BMC/blob/master/Transformation3D.ipynb Examples -------- >>> # import function >>> from euler_rotmat import euler_rotmat >>> # Default options: xyz sequence, local frame and show matrix >>> R = euler_rotmat() >>> # XYZ sequence (around global (fixed) coordinate system) >>> R = euler_rotmat(frame='global') >>> # Enter numeric values for all angles and show both matrices >>> R, Rn = euler_rotmat(angles=[90, 90, 90]) >>> # show what is returned >>> euler_rotmat(angles=[90, 90, 90]) >>> # show only the rotation matrix for the elemental rotation at x axis >>> R = euler_rotmat(order='x') >>> # zxz sequence and numeric value for only one angle >>> R, Rn = euler_rotmat(order='zxz', angles=[None, 0, None]) >>> # input values in radians: >>> import numpy as np >>> R, Rn = euler_rotmat(order='zxz', angles=[None, np.pi, None], unit='rad') >>> # shows only the numeric matrix >>> R, Rn = euler_rotmat(order='zxz', angles=[90, 0, None], showA='False') >>> # Change the angles' symbols >>> R = euler_rotmat(order='zxz', str_symbols=['theta', 'phi', 'psi']) >>> # Negativate the angles' symbols >>> R = euler_rotmat(order='zxz', str_symbols=['-theta', '-phi', '-psi']) >>> # all algebraic matrices for all possible sequences for the local frame >>> s=['xyz','xzy','yzx','yxz','zxy','zyx','xyx','xzx','yzy','yxy','zxz','zyz'] >>> for seq in s: R = euler_rotmat(order=seq) >>> # all algebraic matrices for all possible sequences for the global frame >>> for seq in s: R = euler_rotmat(order=seq, frame='global') """ import numpy as np import sympy as sym try: from IPython.core.display import Math, display ipython = True except: ipython = False angles = np.asarray(np.atleast_1d(angles), dtype=np.float64) if ~np.isnan(angles).all(): if len(order) != angles.size: raise ValueError("Parameters 'order' and 'angles' (when " + "different from None) must have the same size.") x, y, z = sym.symbols('x, y, z') sig = [1, 1, 1] if str_symbols is None: a, b, g = sym.symbols('alpha, beta, gamma') else: s = str_symbols if s[0][0] == '-': s[0] = s[0][1:] sig[0] = -1 if s[1][0] == '-': s[1] = s[1][1:] sig[1] = -1 if s[2][0] == '-': s[2] = s[2][1:] sig[2] = -1 a, b, g = sym.symbols(s) var = {'x': x, 'y': y, 'z': z, 0: a, 1: b, 2: g} # Elemental rotation matrices for xyz (local) cos, sin = sym.cos, sym.sin Rx = sym.Matrix([[1, 0, 0], [0, cos(x), sin(x)], [0, -sin(x), cos(x)]]) Ry = sym.Matrix([[cos(y), 0, -sin(y)], [0, 1, 0], [sin(y), 0, cos(y)]]) Rz = sym.Matrix([[cos(z), sin(z), 0], [-sin(z), cos(z), 0], [0, 0, 1]]) if frame.lower() == 'global': Rs = {'x': Rx.T, 'y': Ry.T, 'z': Rz.T} order = order.upper() else: Rs = {'x': Rx, 'y': Ry, 'z': Rz} order = order.lower() R = Rn = sym.Matrix(sym.Identity(3)) str1 = r'\mathbf{R}_{%s}( ' % frame # last space needed for order='' #str2 = [r'\%s'%var[0], r'\%s'%var[1], r'\%s'%var[2]] str2 = [1, 1, 1] for i in range(len(order)): Ri = Rs[order[i].lower()].subs(var[order[i].lower()], sig[i] * var[i]) R = Ri * R if sig[i] > 0: str2[i] = '%s:%s' % (order[i], sym.latex(var[i])) else: str2[i] = '%s:-%s' % (order[i], sym.latex(var[i])) str1 = str1 + str2[i] + ',' if ~np.isnan(angles).all() and ~np.isnan(angles[i]): if unit[:3].lower() == 'deg': angles[i] = np.deg2rad(angles[i]) Rn = Ri.subs(var[i], angles[i]) * Rn #Rn = sym.lambdify(var[i], Ri, 'numpy')(angles[i]) * Rn str2[i] = str2[i] + '=%.0f^o' % np.around(np.rad2deg(angles[i]), 0) else: Rn = Ri * Rn Rn = sym.simplify(Rn) # for trigonometric relations try: # nsimplify only works if there are symbols Rn2 = sym.latex(sym.nsimplify(Rn, tolerance=1e-8).n(chop=True, prec=4)) except: Rn2 = sym.latex(Rn.n(chop=True, prec=4)) # there are no symbols, pass it as Numpy array Rn = np.asarray(Rn) if showA and ipython: display(Math(str1[:-1] + ') =' + sym.latex(R, mat_str='matrix'))) if showN and ~np.isnan(angles).all() and ipython: str2 = ',\;'.join(str2[:angles.size]) display(Math(r'\mathbf{R}_{%s}(%s)=%s' % (frame, str2, Rn2))) if np.isnan(angles).all(): return R else: return R, Rn
def constants_symbolic_expr(self): massmatrix = sm.Eq(self.M, self.m * sm.Identity(3)) return [massmatrix]
def o1_o2_o3_o4_gammas(o1, o2, o3, o4, γ, Λ, δ): """ γ is the interaction strength: γ \int_{w<x<y<z} ϕ(w)π(x)π(y)π(z) exp(-Λ|w-z|) dw dx dy dz """ ϵ = sympy.symbols('e') A = np.concatenate([ np.concatenate([ sympy.Identity(2) * (1 - ϵ * Λ), γ * sympy.sqrt(ϵ) * sympy.Matrix(o2), sympy.ZeroMatrix(2, 2) ], axis=1), np.concatenate([ sympy.ZeroMatrix(2, 2), sympy.Identity(2) * (1 - ϵ * Λ), γ * sympy.sqrt(ϵ) * sympy.Matrix(o3) ], axis=1), np.concatenate([ sympy.ZeroMatrix(2, 2), sympy.ZeroMatrix(2, 2), sympy.Identity(2) * (1 - ϵ * Λ) ], axis=1) ], axis=0) B = np.concatenate([ sympy.ZeroMatrix(2, 2), sympy.ZeroMatrix(2, 2), γ * sympy.sqrt(ϵ) * sympy.Matrix(o4) ], axis=0) C = np.concatenate([ γ * sympy.sqrt(ϵ) * sympy.Matrix(o1), sympy.ZeroMatrix(2, 2), sympy.ZeroMatrix(2, 2) ], axis=1) D = sympy.ZeroMatrix(2, 2) tmp1 = np.concatenate([sympy.Identity(2) + δ * D, np.sqrt(δ) * C], axis=1) tmp2 = np.concatenate([np.sqrt(δ) * B, A], axis=1) tmp = np.concatenate([tmp1, tmp2], axis=0) cmpo = np.transpose(np.reshape(tmp, (4, 2, 4, 2)), (0, 2, 1, 3)) #(M, M, dout, din) Gammas = [[None, None], [None, None]] for d1, d2 in itertools.product([0, 1], [0, 1]): M = cmpo.shape[0] tmp = np.zeros((M, M), dtype=np.complex128) if d1 != d2: cmpo_tmp = cmpo[:, :, d1, d2] for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].coeff('sqrt(e)')) elif (d1 == 0) and (d2 == 0): cmpo_tmp = cmpo[:, :, d1, d2] - sympy.Identity(M) for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].coeff('e')) elif (d1 == 1) and (d2 == 1): cmpo_tmp = cmpo[:, :, d1, d2] - sympy.Identity(M) for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].subs([('e', 0), ('sqrt(e)', 0)])) Gammas[d1][d2] = tmp return Gammas
from numpy.core.numeric import identity import sympy as sp from sympy.matrices.expressions.matexpr import Identity shape = 4 x_prev = sp.MatrixSymbol('X_{k-1}', shape, 1) P_prev = sp.MatrixSymbol('P_{k-1}', shape, shape) z_k = sp.MatrixSymbol('z_{k}', shape, 1) F = sp.MatrixSymbol('F', shape, shape) H = sp.MatrixSymbol('H', shape, shape) Q = sp.MatrixSymbol('Q', shape, shape) R = sp.MatrixSymbol('R', shape, shape) x_ateori = F*x_prev P_ateori = F*P_prev*F.T + Q z_ateori = H*x_ateori innovation = z_k - z_ateori S_k = H*P_ateori*H.T + R W_k = P_ateori*H.T*S_k.inv() # gain x_apost = x_ateori + W_k*innovation P_apost = (sp.Identity(shape) - W_k*H)*P_ateori
def free_boson_entangler_propagator(α, Λ, δ): """ Generate the mpo representation of the entangling evolution for a free scalar, massless boson the implemented operator is -1j*alpha/2\int dx dy exp(-Lambda*abs(x-y))*(psi(x)psi(y)-psidag(x)psidag(y)) for alpha =Lambda/4, this gives the cMERA evolution operator for the free Boson theory with a UV-cutoff=Lambda; The MPO is obtained from Gammas as 11 + dx * Gamma[0][0], sqrt(dx) Gamma[0][1] sqrt(dx) Gamma[1][0], 11 + Gamma[1][1] Parameters: ----------------- alpha: float or None the strength of the entangler; if None, alpha=cutoff/4 Lambda: float UV cutoff (see description above) delta: float or complex time step of the entangling evolution; use np.real(delta) == 0, np.imag(delta) > 0 for lorentzian evolution Returns: ----------------- Gamma: list of length 2 of list of length 2 of np.ndarray: the cMPO matrices of the entangling propagator, in column major ordering The index convention is: Gamma[a][b]: a is the outgoing physical index, b is the incoming physical index e.g. index a is contracted with the MPS: Q_out = kron(11,Gamma[0][0])+kron(Q_in,11)+kron(R_in,Gamma[0][1]) R_out = kron(11,Gamma[1][0])+kron(R_in, 11 + Gamma[1][1]) """ ϵ = sympy.symbols('e') b = sympy.Matrix(np.array([[0, 1], [0, 0]])) bd = b.T n = bd * b A = sympy.Identity(4) * (1 - ϵ * Λ) B = np.concatenate([ np.sqrt(1j * α) * sympy.sqrt(ϵ) * bd, np.sqrt(-1j * α) * sympy.sqrt(ϵ) * b ], axis=0) C = np.concatenate([ np.sqrt(1j * α) * sympy.sqrt(ϵ) * bd, np.sqrt(-1j * α) * sympy.sqrt(ϵ) * b ], axis=1) D = sympy.ZeroMatrix(2, 2) tmp1 = np.concatenate([sympy.Identity(2) + δ * D, np.sqrt(δ) * C], axis=1) tmp2 = np.concatenate([np.sqrt(δ) * B, A], axis=1) tmp = np.concatenate([tmp1, tmp2], axis=0) cmpo = np.transpose(np.reshape(tmp, (3, 2, 3, 2)), (0, 2, 1, 3)) #(M, M, dout, din) Gammas = [[None, None], [None, None]] for d1, d2 in itertools.product([0, 1], [0, 1]): M = cmpo.shape[0] tmp = np.zeros((M, M), dtype=np.complex128) if d1 != d2: cmpo_tmp = cmpo[:, :, d1, d2] for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].coeff('sqrt(e)')) elif (d1 == 0) and (d2 == 0): cmpo_tmp = cmpo[:, :, d1, d2] - sympy.Identity(M) for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].coeff('e')) elif (d1 == 1) and (d2 == 1): cmpo_tmp = cmpo[:, :, d1, d2] - sympy.Identity(M) for a1, a2 in itertools.product(range(M), range(M)): tmp[a1, a2] = complex(cmpo_tmp[a1, a2].subs([('e', 0), ('sqrt(e)', 0)])) Gammas[d1][d2] = tmp return Gammas