Ejemplo n.º 1
0
def Hamiltonian():
    H1 = E_0*diag(ones(q*L**2, complex))
    
    H2q = t1*diag(ones(q-1, complex), -1)
    H2xy= diag(ones(L*L, complex)).reshape(L**2,L**2)
    H2 = ln.kron(H2xy, H2q)

    
    H3q = diag([t2*exp(2*pi*k*1j/q) for k in range(q)])
    H3x = diag(ones(L, complex))
    H3y = diag(ones(L-1, complex), -1)
    H3xy = ln.kron(H3x, H3y)
    H3 = ln.kron(H3xy, H3q)

    H4q = zeros(q**2).reshape(q,q)
    H4q[0,q-1]= t1
    H4x = diag(ones(L-1, complex), -1)
    H4y = diag(ones(L, complex))
    H4xy = ln.kron(H4x, H4y)
    H4 = ln.kron(H4xy, H4q)

    H = H1+ H2 + H3+ H4

    H = H + array(matrix(H).getH())

    return H
Ejemplo n.º 2
0
def lz(L,S,I):
    gS=int(2*S+1)
    Si=identity(gS)
    Lz=jz(L)
    gI=int(2*I+1)
    Ii=identity(gI)
    lz=kron(kron(Lz,Si),Ii)
    return lz
Ejemplo n.º 3
0
def Iz(L,S,I):
    gS=int(2*S+1)
    gL=int(2*L+1)
    Si=identity(gS)
    Li=identity(gL)
    Iz_num=jz(I)
    Iz=kron(kron(Li,Si),Iz_num)
    return Iz
Ejemplo n.º 4
0
def sz(L,S,I):
    Sz=jz(S)
    gL=int(2*L+1)
    Li=identity(gL)
    gI=int(2*I+1)
    Ii=identity(gI)
    sz=kron(kron(Li,Sz),Ii)
    return sz
Ejemplo n.º 5
0
    def test_basic(self):

        a = kron(array([[1, 2], [3, 4]]), array([[1, 1, 1]]))
        assert_array_equal(a, array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]))

        m1 = array([[1, 2], [3, 4]])
        m2 = array([[10], [11]])
        a = kron(m1, m2)
        expected = array([[10, 20], [11, 22], [30, 40], [33, 44]])
        assert_array_equal(a, expected)
Ejemplo n.º 6
0
def fz(L,S,I):
    gS=int(2*S+1)
    Sz=jz(S)
    Si=identity(gS)
    gL=int(2*L+1)
    Lz=jz(L)
    Li=identity(gL)
    gJ=gL*gS
    Jz=kron(Lz,Si)+kron(Li,Sz)
    Ji=identity(gJ)
    gI=int(2*I+1)
    Iz=jz(I)
    Ii=identity(gI)
    Fz=kron(Jz,Ii)+kron(Ji,Iz)
    return Fz
Ejemplo n.º 7
0
	def test_expect(self):
		exp=expect(self.mps,self.ops)
		OP=self.ops[0]
		for i in range(1,6):
			OP=kron(OP,self.ops[i])
		exp2=self.ket.conjugate().transpose().dot(OP.dot(self.ket))
		print exp
		print exp2
Ejemplo n.º 8
0
def Hfs(L,S,I):
    """Provides the L dot S matrix (fine structure)"""
    gS=int(2*S+1) #number of mS values
    Sx=jx(S)
    Sy=jy(S)
    Sz=jz(S)
    Si=identity(gS)

    gL=int(2*L+1)
    Lx=jx(L)
    Ly=jy(L)
    Lz=jz(L)
    Li=identity(gL)

    gJ=gL*gS
    Jx=kron(Lx,Si)+kron(Li,Sx)
    Jy=kron(Ly,Si)+kron(Li,Sy)
    Jz=kron(Lz,Si)+kron(Li,Sz)
    J2=dot(Jx,Jx)+dot(Jy,Jy)+dot(Jz,Jz)

    gI=int(2*I+1)
    Ii=identity(gI)
    gF=gJ*gI
    Fi=identity(gF)
    Hfs=0.5*(kron(J2,Ii)-L*(L+1)*Fi-S*(S+1)*Fi) # fine structure in m_L,m_S,m_I basis
    return Hfs
Ejemplo n.º 9
0
 def kron(self,x,y):
     """
      Matrix Kroneker product between objects ``x`` and ``y``.
      Symbolically this is expressed as :math:`x \\otimes y`.
      
      Also, the bitwise or function has been redefined to now mean
      a Kronecker product.  For two operator objects ``x`` and
      ``y``, now ``x|y`` is their Kronecker product.
      """
     prod = operator( kron(x,y) )
     return prod
Ejemplo n.º 10
0
    def __init__(self, m, l, d, mu, tilde_mu, B, c_shape, c_vel):
        self.m = m
        self.l = l
        self.d = d
        self.mu = mu
        self.tilde_mu = tilde_mu
        self.B = B
        self.agents, self.edges = self.B.shape
        self.S1 = self.make_S1()
        self.S2 = self.make_S2()
        self.Av = self.make_Av()
        self.Aa = self.Av.dot(self.B.T).dot(self.Av)
        self.Bb = la.kron(self.B, np.eye(self.m))
        self.S1b = la.kron(self.S1, np.eye(self.m))
        self.S2b = la.kron(self.S2, np.eye(self.m))
        self.Avb = la.kron(self.Av, np.eye(self.m))
        self.Aab = la.kron(self.Aa, np.eye(self.m))
        self.Ed = np.zeros(self.edges)
        self.Ev = np.zeros(self.edges*self.m)

        self.c_shape = c_shape
        self.c_vel = c_vel
Ejemplo n.º 11
0
def Bbhfs(L,S,I):
    """Calculates electric quadrupole matrix.

    Calculates the part in square brakets from
    equation (8) in manual
    """
    gS=int(2*S+1)
    Sx=jx(S)
    Sy=jy(S)
    Sz=jz(S)
    Si=identity(gS)

    gL=int(2*L+1)
    Lx=jx(L)
    Ly=jy(L)
    Lz=jz(L)
    Li=identity(gL)

    gJ=gL*gS
    Jx=kron(Lx,Si)+kron(Li,Sx)
    Jy=kron(Ly,Si)+kron(Li,Sy)
    Jz=kron(Lz,Si)+kron(Li,Sz)

    gI=int(2*I+1)
    gF=gJ*gI
    Ix=jx(I)
    Iy=jy(I)
    Iz=jz(I)
    
    Fi=identity(gF)

    IdotJ=kron(Jx,Ix)+kron(Jy,Iy)+kron(Jz,Iz)
    IdotJ2=dot(IdotJ,IdotJ)

    if I != 0:
		Bbhfs=1./(6*I*(2*I-1))*(3*IdotJ2+3./2*IdotJ-I*(I+1)*15./4*Fi)
    else:
        Bbhfs = 0
    return Bbhfs
Ejemplo n.º 12
0
def hamilB(B0):
    '''
    Calculate hamiltonians for all 4 orientations for specific B field of the 
    P1 defec in diamond.
    creates hamiltonians of the form:
    H = alfa B @ S + A @ S @ I
    with @ the tensor inproduct operation. 
    input: B-field vector
    outputs: 4 hamiltonians
    '''

    # constants.
    pi = n.pi
    beta = 1  # Bohr magneton
    g = 1  # spectroscopic splitting factor
    alfa = 28.04
    angle = pi -2 * arcsin(1 / sqrt(3))  #109.5 degrees angle between tetrahedral bonds.

    # matrices.
    Sx, Sy, Sz = spinhalf()
    Ix, Iy, Iz = spin1()
    R1 = transpose(rot(angle, axis = 'y'))
    R2 = transpose(rot(pi * 2 / 3, axis = 'z') * rot(angle, axis = 'y'))
    R3 = transpose(rot(-pi * 2 / 3, axis = 'z') * rot(angle, axis = 'y'))

    B1_ = B0
    B2_ = R1 * B1_
    B3_ = R2 * B1_
    B4_ = R3 * B1_

    #hyperfine tensor
    A = matrix([[81.33], [81.33], [114.03]])
    
    # hyperfine interaction hamiltonian
    H_ASI = A.item(0) * la.kron(Sx, Ix) + A.item(1) * la.kron(Sy, Iy) + A.item(2) * la.kron(Sz, Iz)

    # hamiltonians work in electron spin half + nuclear spin 1 base, 6D
    H1 = alfa * la.kron((B1_.item(0) * Sx + B1_.item(1) * Sy + B1_.item(2) * Sz), eye(3)) + H_ASI 
    H2 = alfa * la.kron((B2_.item(0) * Sx + B2_.item(1) * Sy + B2_.item(2) * Sz), eye(3)) + H_ASI
    H3 = alfa * la.kron((B3_.item(0) * Sx + B3_.item(1) * Sy + B3_.item(2) * Sz), eye(3)) + H_ASI
    H4 = alfa * la.kron((B4_.item(0) * Sx + B4_.item(1) * Sy + B4_.item(2) * Sz), eye(3)) + H_ASI


    return H1, H2, H3, H4
Ejemplo n.º 13
0
from scipy.sparse import identity
from copy import deepcopy

from mps import MPS,ket2mps,overlap,expect
from dmrg import DMRGEngine
from testdmrg import lhgen,rhgen

ket=np.random.rand(2**4)
mps=ket2mps(ket,2,4,cano='mixed',div=2)
ket2=np.random.rand(2**4)
mps2=ket2mps(ket2,2,4,cano='mixed',div=2)

opl=[np.array([[0.5,0.],[0.,-0.5]]),np.array([[1.,0.],[0.,1.]]),np.array([[1.,0.],[0.,1.]]),np.array([[1.,0.],[0.,1.]])]
OP=deepcopy(opl[0])
for i in range(3):
	OP=kron(OP,np.array([[1.,0.],[0.,1.]]))

def test_tomps():
	dmrg=DMRGEngine(lhgen,rhgen)  
	dmrg.finite(mwarmup=10,mlist=[10])
	dmps=dmrg.tomps()
	return dmps

def test_shape(mps):
	for M in mps.Ms:
		print M.shape

def test_shift(mps):
	mps.shift(site=mps.L/2-1)
	test_shape(mps)
	test_cano(mps)
Ejemplo n.º 14
0
 def Hamiltonian_Matrix(self):
     
     self.hamiltonian = self.h0
     self.hamiltonian = la.kron(self.omegatot_1[0] * self.sx + self.omegatot_1[1] * self.sy + self.omegatot_1[2] * self.sz, self.iden2) + la.kron(self.iden2, self.omegatot_2[0] * self.sx + self.omegatot_2[1] * self.sy + self.omegatot_2[2] * self.sz)-2.0*(self.J_couple)*self.s1_s2
     
     return
Ejemplo n.º 15
0
    def formation(self):
        '''
        formation control algorithm
        '''
        ready = True
        for rc in self.rotorcrafts:
            if not rc.initialized:
                if self.verbose:
                    print("Waiting for state of rotorcraft ", rc.id)
                    sys.stdout.flush()
                ready = False
            if rc.timeout > 0.5:
                if self.verbose:
                    print("The state msg of rotorcraft ", rc.id, " stopped")
                    sys.stdout.flush()
                ready = False
            if rc.initialized and 'geo_fence' in list(self.config.keys()):
                geo_fence = self.config['geo_fence']
                if not self.ignore_geo_fence:
                    if (rc.X[0] < geo_fence['x_min']
                            or rc.X[0] > geo_fence['x_max']
                            or rc.X[1] < geo_fence['y_min']
                            or rc.X[1] > geo_fence['y_max']
                            or rc.X[2] < geo_fence['z_min']
                            or rc.X[2] > geo_fence['z_max']):
                        if self.verbose:
                            print("The rotorcraft", rc.id,
                                  " is out of the fence (", rc.X, ", ",
                                  geo_fence, ")")
                            sys.stdout.flush()
                        ready = False

        if not ready:
            return

        dim = 2 * len(self.rotorcrafts)
        X = np.zeros(dim)
        V = np.zeros(dim)
        U = np.zeros(dim)

        i = 0
        for rc in self.rotorcrafts:
            X[i] = rc.X[0]
            X[i + 1] = rc.X[1]
            V[i] = rc.V[0]
            V[i + 1] = rc.V[1]
            i = i + 2

        Bb = la.kron(self.B, np.eye(2))
        Z = Bb.T.dot(X)
        Dz = rf.make_Dz(Z, 2)
        Dzt = rf.make_Dzt(Z, 2, 1)
        Dztstar = rf.make_Dztstar(self.d * self.scale, 2, 1)
        Zh = rf.make_Zh(Z, 2)
        E = rf.make_E(Z, self.d * self.scale, 2, 1)

        # Shape and motion control
        jmu_t1 = self.joystick.trans * self.t1[0, :]
        jtilde_mu_t1 = self.joystick.trans * self.t1[1, :]
        jmu_r1 = self.joystick.rot * self.r1[0, :]
        jtilde_mu_r1 = self.joystick.rot * self.r1[1, :]
        jmu_t2 = self.joystick.trans2 * self.t2[0, :]
        jtilde_mu_t2 = self.joystick.trans2 * self.t2[1, :]
        jmu_r2 = self.joystick.rot2 * self.r2[0, :]
        jtilde_mu_r2 = self.joystick.rot2 * self.r2[1, :]

        Avt1 = rf.make_Av(self.B, jmu_t1, jtilde_mu_t1)
        Avt1b = la.kron(Avt1, np.eye(2))
        Avr1 = rf.make_Av(self.B, jmu_r1, jtilde_mu_r1)
        Avr1b = la.kron(Avr1, np.eye(2))
        Avt2 = rf.make_Av(self.B, jmu_t2, jtilde_mu_t2)
        Avt2b = la.kron(Avt2, np.eye(2))
        Avr2 = rf.make_Av(self.B, jmu_r2, jtilde_mu_r2)
        Avr2b = la.kron(Avr2, np.eye(2))

        Avb = Avt1b + Avr1b + Avt2b + Avr2b
        Avr = Avr1 + Avr2

        if self.B.size == 2:
            Zhr = np.array([-Zh[1], Zh[0]])
            U = -self.k[1] * V - self.k[0] * Bb.dot(Dz).dot(Dzt).dot(
                E) + self.k[1] * (Avt1b.dot(Zh) + Avt2b.dot(Zhr)) + np.sign(
                    jmu_r1[0]) * la.kron(
                        Avr1.dot(Dztstar).dot(self.B.T).dot(Avr1),
                        np.eye(2)).dot(Zhr)
        else:
            U = -self.k[1] * V - self.k[0] * Bb.dot(Dz).dot(Dzt).dot(
                E) + self.k[1] * Avb.dot(Zh) + la.kron(
                    Avr.dot(Dztstar).dot(self.B.T).dot(Avr), np.eye(2)).dot(Zh)

        if self.verbose:
            #print "Positions: " + str(X).replace('[','').replace(']','')
            #print "Velocities: " + str(V).replace('[','').replace(']','')
            #print "Acceleration command: " + str(U).replace('[','').replace(']','')
            print("Error distances: " +
                  str(E).replace('[', '').replace(']', ''))
            sys.stdout.flush()

        i = 0
        for ac in self.rotorcrafts:
            msg = PprzMessage("datalink", "DESIRED_SETPOINT")
            msg['ac_id'] = ac.id
            msg['flag'] = 0  # full 3D not supported yet
            msg['ux'] = U[i]
            msg['uy'] = U[i + 1]
            msg['uz'] = self.altitude
            self._interface.send(msg)
            i = i + 2
Ejemplo n.º 16
0
def Hhfs(L, S, I):
    """Provides the I dot J matrix (magnetic dipole interaction)"""
    gS = int(2 * S + 1)
    Sx = jx(S)
    Sy = jy(S)
    Sz = jz(S)
    Si = identity(gS)

    gL = int(2 * L + 1)
    Lx = jx(L)
    Ly = jy(L)
    Lz = jz(L)
    Li = identity(gL)

    gJ = gL * gS
    Jx = kron(Lx, Si) + kron(Li, Sx)
    Jy = kron(Ly, Si) + kron(Li, Sy)
    Jz = kron(Lz, Si) + kron(Li, Sz)
    Ji = identity(gJ)
    J2 = dot(Jx, Jx) + dot(Jy, Jy) + dot(Jz, Jz)

    gI = int(2 * I + 1)
    gF = gJ * gI
    Ix = jx(I)
    Iy = jy(I)
    Iz = jz(I)
    Ii = identity(gI)
    Fx = kron(Jx, Ii) + kron(Ji, Ix)
    Fy = kron(Jy, Ii) + kron(Ji, Iy)
    Fz = kron(Jz, Ii) + kron(Ji, Iz)
    Fi = identity(gF)
    F2 = dot(Fx, Fx) + dot(Fy, Fy) + dot(Fz, Fz)
    Hhfs = 0.5 * (F2 - I * (I + 1) * Fi - kron(J2, Ii))
    return Hhfs
    def liouville(self):

        self.ltot = la.kron((-1j*self.hamiltonian-self.haberkorn),self.iden4) + la.kron(self.iden4,np.transpose(+1j*self.hamiltonian-self.haberkorn)) - self.kstd*(la.kron(self.pro_trip,np.transpose(self.pro_sing))+la.kron(self.pro_sing,np.transpose(self.pro_trip)))

        return
Ejemplo n.º 18
0
def tik_sep(B, PSF, center=None, alpha=None, BC=None):
    """TIK_SEP Tikhonov image deblurring using the Kronecker decomposition.

    X, alpha = tik_sep(B, PSF, center, alpha, BC)

  Compute restoration using a Kronecker product decomposition and a
  Tikhonov filter, with the identity matrix as the regularization operator.

  Input:
        B  Array containing blurred image.
      PSF  Array containing the point spread function.
   center  [row, col] = indices of center of PSF.
  
  Optional Inputs:
    alpha  Regularization parameter.
             Default parameter chosen by generalized cross validation.
       BC  String indicating boundary condition.
             ('zero', 'reflexive', or 'periodic')
           Default is 'zero'.

  Output:
        X  Array containing computed restoration.
    alpha  Regularization parameter used to construct restoration."""
    #
    # compute the center of the PSF if it is not provided
    #
    if center is None:
        center = array(PSF.shape) / 2

    #
    # if PSF is smaller than B, pad it to the same size as B
    #
    if PSF.size < B.size:
        PSF = padarray(PSF, array(B.shape) - array(PSF.shape),
                       direction='post')

    #
    # First compute the Kronecker product terms, Ar and Ac, where
    # the blurring matrix  A = kron(Ar, Ac).  
    # Note that if the PSF is not separable, this
    # step computes a Kronecker product approximation to A.
    #
    Ar, Ac = kronDecomp(PSF, center, BC)

    #
    # Compute SVD of the blurring matrix.
    #
    Ur, sr, Vr = svd(Ar)
    Uc, sc, Vc = svd(Ac)

    bhat = dot( dot(Uc.transpose(), B), Ur )
    bhat = bhat.flatten('f')
    s = kron(matrix(sr),matrix(sc))
    s = array(s.flatten('f'))

    #
    # If a regularization parameter is not given, use GCV to find one.
    #
    if alpha is None:
        alpha = gcv_tik(s, bhat)

    #
    # Compute the Tikhonov regularized solution.
    #
    D = abs(s)**2 + abs(alpha)**2
    bhat = s * bhat
    xhat = bhat / D
    xhat = reshape(xhat, shape(B))
    xhat = xhat.transpose()
    X = dot( dot(Vc.transpose(),xhat), Vr)

    return X, alpha
Ejemplo n.º 19
0
    def liouville(self):
        self.l_vibronic = self.kisc * (-0.5*(np.kron((self.pro_sing+self.t0_t0),self.iden4) + np.kron(self.iden4,np.transpose(self.pro_sing+self.t0_t0)))+np.kron(self.s_t0,np.transpose(self.t0_s))+np.kron(self.t0_s,np.transpose(self.s_t0))-0.5*(np.kron((self.pro_sing+self.tplus_tplus),self.iden4) + np.kron(self.iden4,np.transpose(self.pro_sing+self.tplus_tplus)))+np.kron(self.s_tplus,np.transpose(self.tplus_s))+np.kron(self.tplus_s,np.transpose(self.s_tplus))-0.5*(np.kron((self.pro_sing+self.tminus_tminus),self.iden4) + np.kron(self.iden4,np.transpose(self.pro_sing+self.tminus_tminus)))+np.kron(self.s_tminus,np.transpose(self.tminus_s))+np.kron(self.tminus_s,np.transpose(self.s_tminus)))
        
        self.ltot = la.kron((-1j*self.hamiltonian-self.haberkorn),self.iden4) + la.kron(self.iden4,np.transpose(+1j*self.hamiltonian-self.haberkorn)) - self.kstd*(la.kron(self.pro_trip,np.transpose(self.pro_sing))+la.kron(self.pro_sing,np.transpose(self.pro_trip))) + self.l_vibronic

        return
Ejemplo n.º 20
0
		def _Cry(sig_r, sig_s, sig_i, rho1, rho2, rho3, **kwargs):
			cov_FP = get_cov_FP2(sig_r, sig_s, sig_i, rho1, rho2, rho3) # 3x3
			v = cov_FP[1:3,0].reshape(-1, 1) # shape = (2,1)
			return linalg.kron(v, np.eye(self.N))
Ejemplo n.º 21
0
		def _Cyy(sig_r, sig_s, sig_i, rho1, rho2, rho3, **kwargs):
			cov_FP = get_cov_FP2(sig_r, sig_s, sig_i, rho1, rho2, rho3) # 3x3
			return linalg.kron(cov_FP[1:3,1:3], np.eye(self.N))
Ejemplo n.º 22
0
# Storage for cost
Jt = zeros((3, res))
# Storage for cost
th[:] = th_r[:]
# reset parameters

# Get noise and simulate system (generate training data)
W = Noise(dt, T, 1, 1, 3, pd, [], [s * dt], seed)
w_tmp = W.getNoise()[1]
w[:, :] = w_tmp[0:2, :]
v[:, :] = w_tmp[2, :]
x, y = S.sim([0, 0], u, w, v)

# Generalize Model for predictions, derivatives and history
M_t = generalize(M, p, DTCM('GF', p, s))[0]
D = kron(eye(p, p, 1), eye(2))

# Generalize in- and output signals;
u_t = zeros((p * M.nu, N))
x_t = zeros((p * M.nx, N))
y_t = zeros((p * M.ny, N))

# Generalized signals (predictions)
for i in range(0, p):
    u_t[M.nu * i:M.nu * (i + 1), 0:N - i] = u[:, i:N]
    x_t[M.nx * i:M.nx * (i + 1), 0:N - i] = x[:, i:N]
    y_t[M.ny * i:M.ny * (i + 1), 0:N - i] = y[:, i:N]

# Fetch Timer
Tim = Timer('Running cost estimates for case 5/16', 0, 3 * res, 3 * res)
Ejemplo n.º 23
0
def solvingStuffForPQRS(AA, BB, CC, DD, FF, GG, HH, JJ, KK, LL, MM, NN):
    """
    Solves for P,Q,R, and S in Uhlig's paper on DSGE models.

    P is found by solving the Matrix quadratic question.  Note that 
    solutions may not be unique. 
    Special Case:  FP^2+GP+H=0
    General Case:  ____________

    Q is found using Kronkier products.
    Special Case: FQN+(FP+G)Q+LN+M=0
    General Case: ___________________

    R,S are found only if Jump variables are included; otherwise, 
    they are returned as matrices of size 0 by ________.
    R = -inv(C)*(AP+B)
    S = -inv(C)*(AQ+D)

    Note: C is assumed to be of full rank and thus invertable
    Returns P,Q,R,S
    """
    q_eqns = sp.shape(FF)[0]
    m_states = sp.shape(FF)[1]
    l_equ = sp.shape(CC)[0]
    if l_equ == 0:
        n_endog = 0
    else:
        n_endog = sp.shape(CC)[1]

    k_exog = min(sp.shape(sp.mat(NN))[0], sp.shape(sp.mat(NN))[1])

    if l_equ == 0:
        PP, Diff = solve_P(FF, GG, HH)
        PP = sp.real(PP)
    else:
        Cinv = la.inv(CC)
        Fprime = FF - sp.dot(sp.dot(JJ, Cinv), AA)
        Gprime = -(sp.dot(sp.dot(JJ, Cinv), BB) - GG + sp.dot(sp.dot(KK, Cinv), AA))
        Hprime = -sp.dot(sp.dot(KK, Cinv), BB) + HH
        PP, Diff = solve_P(Fprime, Gprime, Hprime)
        PP = sp.real(PP)

    # solve for QRS
    if l_equ == 0:
        RR = sp.zeros((0, m_states))
        Left = FF
        Right = sp.dot(FF, PP) + GG
        VV = (la.kron(NN.T, Left)) + la.kron(sp.eye(k_exog), Right)
    else:
        RR = sp.dot(-Cinv, (sp.dot(AA, PP) + BB))
        Left = FF - sp.dot(sp.dot(JJ, Cinv), AA)
        Right = sp.dot(JJ, RR) + sp.dot(FF, PP) + G - sp.dot(sp.dot(KK, Cinv), AA)
        VV = (la.kron(NN.T, Left)) + la.kron(sp.eye(k_exog), Right)
    if False and (npla.matrix_rank(VV) < k_exog * (m_states + n_endog)):
        print ("Sorry but V is note invertible. Can't solve for Q and S")
    else:
        if l_equ == 0:
            Vector = (sp.dot(LL, NN) + MM).flatten()
            QQSS_vec = sp.dot(la.inv(VV), Vector)
            QQSS_vec = -QQSS_vec
        else:
            Vector = (sp.dot((sp.dot(sp.dot(JJ, Cinv), DD) - LL), NN) + sp.dot(sp.dot(KK, Cinv), DD) - MM).flatten()
            QQSS_vec = sp.dot(la.inv(VV), Vector)
            QQSS_vec = -QQSS_vec

        QQ = sp.reshape(QQSS_vec, (m_states, k_exog))

        if l_equ == 0:
            SS = sp.zeros((0, 2))
        else:
            SS = sp.dot(-Cinv, (sp.dot(AA, QQ) + DD))
    return PP, QQ, RR, SS
Ejemplo n.º 24
0
    def formation(self):
        '''
        formation control algorithm
        '''
        ready = True
        for rc in self.rotorcrafts:
            if not rc.initialized:
                if self.verbose:
                    print("Waiting for state of rotorcraft ", rc.id)
                    sys.stdout.flush()
                ready = False
            if rc.timeout > 0.5:
                if self.verbose:
                    print("The state msg of rotorcraft ", rc.id, " stopped")
                    sys.stdout.flush()
                ready = False
            if rc.initialized and 'geo_fence' in self.config.keys():
                geo_fence = self.config['geo_fence']
                if not self.ignore_geo_fence:
                    if (rc.X[0] < geo_fence['x_min'] or rc.X[0] > geo_fence['x_max']
                            or rc.X[1] < geo_fence['y_min'] or rc.X[1] > geo_fence['y_max']
                            or rc.X[2] < geo_fence['z_min'] or rc.X[2] > geo_fence['z_max']):
                        if self.verbose:
                            print("The rotorcraft", rc.id, " is out of the fence (", rc.X, ", ", geo_fence, ")")
                            sys.stdout.flush()
                        ready = False

        if not ready:
            return

        dim = 2 * len(self.rotorcrafts)
        X = np.zeros(dim)
        V = np.zeros(dim)
        U = np.zeros(dim)

        i = 0
        for rc in self.rotorcrafts:
            X[i] = rc.X[0]
            X[i+1] = rc.X[1]
            V[i] = rc.V[0]
            V[i+1] = rc.V[1]
            i = i + 2


        Bb = la.kron(self.B, np.eye(2))
        Z = Bb.T.dot(X)
        Dz = rf.make_Dz(Z, 2)
        Dzt = rf.make_Dzt(Z, 2, 1)
        Dztstar = rf.make_Dztstar(self.d * self.scale, 2, 1)
        Zh = rf.make_Zh(Z, 2)
        E = rf.make_E(Z, self.d * self.scale, 2, 1)

        # Shape and motion control
        jmu_t1 = self.joystick.trans * self.t1[0,:]
        jtilde_mu_t1 = self.joystick.trans * self.t1[1,:]
        jmu_r1 = self.joystick.rot * self.r1[0,:]
        jtilde_mu_r1 = self.joystick.rot * self.r1[1,:]
        jmu_t2 = self.joystick.trans2 * self.t2[0,:]
        jtilde_mu_t2 = self.joystick.trans2 * self.t2[1,:]
        jmu_r2 = self.joystick.rot2 * self.r2[0,:]
        jtilde_mu_r2 = self.joystick.rot2 * self.r2[1,:]

        Avt1 = rf.make_Av(self.B, jmu_t1, jtilde_mu_t1)
        Avt1b = la.kron(Avt1, np.eye(2))
        Avr1 = rf.make_Av(self.B, jmu_r1, jtilde_mu_r1)
        Avr1b = la.kron(Avr1, np.eye(2))
        Avt2 = rf.make_Av(self.B, jmu_t2, jtilde_mu_t2)
        Avt2b = la.kron(Avt2, np.eye(2))
        Avr2 = rf.make_Av(self.B, jmu_r2, jtilde_mu_r2)
        Avr2b = la.kron(Avr2, np.eye(2))

        Avb = Avt1b + Avr1b + Avt2b + Avr2b
        Avr = Avr1 + Avr2

        if self.B.size == 2:
            Zhr = np.array([-Zh[1],Zh[0]])
            U = -self.k[1]*V - self.k[0]*Bb.dot(Dz).dot(Dzt).dot(E) + self.k[1]*(Avt1b.dot(Zh) + Avt2b.dot(Zhr)) + np.sign(jmu_r1[0])*la.kron(Avr1.dot(Dztstar).dot(self.B.T).dot(Avr1), np.eye(2)).dot(Zhr)
        else:
            U = -self.k[1]*V - self.k[0]*Bb.dot(Dz).dot(Dzt).dot(E) + self.k[1]*Avb.dot(Zh) + la.kron(Avr.dot(Dztstar).dot(self.B.T).dot(Avr), np.eye(2)).dot(Zh)

        if self.verbose:
            #print "Positions: " + str(X).replace('[','').replace(']','')
            #print "Velocities: " + str(V).replace('[','').replace(']','')
            #print "Acceleration command: " + str(U).replace('[','').replace(']','')
            print "Error distances: " + str(E).replace('[','').replace(']','')
            sys.stdout.flush()

        i = 0
        for ac in self.rotorcrafts:
            msg = PprzMessage("datalink", "DESIRED_SETPOINT")
            msg['ac_id'] = ac.id
            msg['flag'] = 0 # full 3D not supported yet
            msg['ux'] = U[i]
            msg['uy'] = U[i+1]
            msg['uz'] = self.altitude
            self._interface.send(msg)
            i = i+2
Ejemplo n.º 25
0
    def inference(self, kern, likelihood, mean_function = None,W=None, Y_metadata=None,precision = None):
        
        """
        Not sure about kronmagic yet
        """
        
        
        """
        Not sure about design of kern yet. 
        Needs to contain something like "is_toeplitz" per grid dimension
        and has to provide p different Kernel-matrices (p = #grid dimensions)
        
        
        
        
        ????? Do we even need partial grids for MSGP????? Probably not
        TO-DO: Incomplete grids:
                    The M-matrix is usually used to lift incomplete grid information
                    to a complete grid (y-values only for parts of the grid)
        """
        if not isinstance(likelihood,likelihoods.Gaussian):
            raise NotImplementedError("Not sure what todo if likelihood is non-gaussian")
        
        
        if kern.name != 'kern_grid':
            raise ValueError("kernel type has to be kern_grid")
            
        
        Z = kern.Z
        X = kern.X
        Y = kern.Y 
        W_x_z = kern.W_x_z

        kronmagic = False 
        
        if mean_function is None: 
            m = 0
        else:
            m = mean_function.f(X)
        
        if precision is None:
            precision = likelihood.gaussian_variance()
        

        p = len(Z) 
        n_grid = 1 
        n_data = np.shape(Y)[0]
        D=0
        for i in range(p):
            n_grid=n_grid*np.shape(Z[i])[0]
            D = D+np.shape(Z[i])[1]
        
        K  = kern.get_K_Z()

        is_toeplitz = kern.get_toeplitz_dims()
        #xe = np.dot(M,xe)
        #n=np.shape(xe)[1]
        for j in range(len(K)):
            if is_toeplitz[i] == True:
                K[j] = linalg.toeplitz(K[j])
                
        sn2 = np.exp(2*precision) 
        
        V = []
        E = []
    #with Timer() as t:
        for j in range(len(K)):
            if is_toeplitz[i] == True:
                V_j,E_j = msgp_linalg.eigr(linalg.toeplitz(K[j]))
            else:
                V_j,E_j = msgp_linalg.eigr(K[j])

            V.append(np.matrix(V_j))
            E.append(np.matrix(E_j))#
    #print("Runtime eigendecomposition: {}".format(t.secs))
        
        e = np.ones((1,1))
        for ii in range(len(E)):
              e = linalg.kron(np.matrix(np.diag(E[ii])).T,e) 
        e = np.ravel(e.astype(float))
        if kronmagic:
            """
            Problem: here we would need the eigendecomposition of the kernel
            matrices. We would need to get those from the kernels.
            
            """
            raise NotImplementedError
            #s = 1/(e+sn2)
            #order = range(1,N)
        else:

            sort_index = np.argsort(e)

            sort_index = sort_index[::-1]
            sort_index = np.ravel(sort_index)
            
            eord = e[sort_index]

            """
            if n<N: ##We dont need this here <- only for partial grid structure
                eord = np.vstack((eord,np.zeros((n-N),1)))
                order = np.vstack((order,range(N+1,n).T))
            """

            s = 1./((float(n_data)/float(n_grid))*eord[0:n_data]+sn2) 

           
           
        if kronmagic:
        ## infGrid.m line 61
            raise NotImplementedError
        else:
            
            kron_mvm_func = lambda x: msgp_linalg.mvm_K(x,K,sn2,W_x_z)
            shape_mvm = (n_data,n_data) ## To-Do: what is the shape of the mvm?
            L = lambda x: -msgp_linalg.solveMVM(x,kron_mvm_func,shape_mvm,cgtol = 1e-6,cgmit=1000) # ein - zuviel?
        
 
        alpha = -L(Y-m) 

        lda = -np.sum(np.log(s))
        #lda_exact = sum(np.log(np.diag(linalg.cholesky(W_x_z.dot(W_x_z.dot(msgp_linalg.kronmvm(K,np.eye(n_grid))).T).T+sn2*np.eye(n_data)))));
        #lda = lda_exact
        #log_marginal = np.dot((Y-m).T,alpha)/2 + n_data*np.log(2*np.pi)/2 + lda/2 
        #print("model fit: {}".format(np.dot((Y-m).T,alpha)/2))
        #print("complexity: {}".format(lda/2))
        #print("complexity exact: {}".format(lda_exact))
        log_marginal = (np.dot((Y-m).T,alpha)/2 + n_data*np.log(2*np.pi)/2 + lda/2) *(-1)
        #print(log_marginal)
            
        #print(alpha)
        #print(W_x_z.T)
        #print(np.max(K[0]))
        #alpha_pred = msgp_linalg.kronmvm(K,W_x_z.T.dot(alpha)) # we need the term K_Z_Z*W.T*alpha for the predictive mean
        
        """
        Calculate  the nu-term for predictive variance
        
        TO-DO: not sure if the K_tilde kronmvm is correct
        """    

        
    
        grad_dict = dict()
        grad_dict["V"] = V 
        grad_dict["E"] = E
        grad_dict["S"] = dict()
        grad_dict["S"]["s"] = s
        grad_dict["S"]["eord"] = eord
        grad_dict["S"]["sort_index"] = sort_index
        post = dict()
        post["alpha"] = alpha
        
        
        return post, log_marginal, grad_dict
Ejemplo n.º 26
0
def __discretize(T, dt, method, PrewarpAt, q):
    """
    Actually, I think that presenting this topic as a numerical
    integration problem is confusing more than it explains. Most
    items here can be presented as conformal mappings and nobody
    needs to be limited to riemann sums of particular shape. As
    I found that scipy version of this, adopts Zhang SICON 2007
    parametrization which surprisingly fresh!

    Here I "generalized" to any rational function representation
    if you are into that mathematician lingo (see the 'fancy'
    ASCII art below). I used LFTs instead, for all real rational
    approx. mappings (for whoever wants to follow that rabbit).
    """

    m, n = T.shape[1], T.NumberOfStates

    if method == 'zoh':
        """
        Zero-order hold is not much useful for linear systems and
        in fact it should be discouraged since control problems
        don't have boundary conditions as in stongly nonlinear
        FEM simulations of CFDs so on. Most importantly it is not
        stability-invariant which defeats its purpose. But whatever



        This conversion is usually done via the expm() identity

            [A | B]   [ exp(A) | int(exp(A))*B ]   [ Ad | Bd ]
        expm[- - -] = [------------------------] = [---------]
            [0 | 0]   [   0    |       I       ]   [ C  | D  ]
        """

        M = np.r_[np.c_[T.a, T.b], np.zeros((m, m + n))]
        eM = expm(M * dt)
        Ad, Bd, Cd, Dd = eM[:n, :n], eM[:n, n:], T.c, T.d

    elif method == 'lft':
        """
        Here we form the following star product
                                      _
                       ---------       |
                       |  1    |       |
                    ---| --- I |<--    |
                    |  |  z    |  |    |
                    |  ---------  |    |
                    |             |    |> this is the lft of (1/s)*I
                    |   -------   |    |
                    --->|     |----    |
                        |  q  |        |
                    --->|     |----    |
                    |   -------   |   _|
                    |             |
                    |   -------   |
                    ----|     |<--|
                        |  T  |
                    <---|     |<---
                        -------

        Here q is whatever the rational mapping that links s to z in
        the following sense:

            1         1                    1        1
           --- = F_u(---,q) = q_22 + q_21 --- (I - --- q_11)⁻¹ q12
            s         z                    z        z

        where F_u denotes the upper linear fractional representation.

        As an example, for the usual discretization cases, the map is

                  [     I     |  sqrt(T)*I ]
              Q = [-----------|------------]
                  [ sqrt(T)*I |    T*α*I   ]

        with α defined as in Zhang 2007 SICON.

        α = 0   --> backward diff, (backward euler)
        α = 0.5 --> Tustin,
        α = 1   --> forward difference (forward euler)

        """

        # TODO: Check if interconnection is well-posed !!!!

        if q is None:
            raise ValueError('\"lft\" method requires an interconnection '
                             'matrix \"q" between s and z variables.')

        # Copy n times for n integrators
        q11, q12, q21, q22 = (kron(np.eye(n), x)
                              for x in matrix_slice(q, (-1, -1)))

        # Compute the star product
        ZAinv = solve(np.eye(n) - q22.dot(T.a), q21)
        AZinv = solve(np.eye(n) - T.a.dot(q22), T.b)

        Ad = q11 + q12.dot(T.a.dot(ZAinv))
        Bd = q12.dot(AZinv)
        Cd = T.c.dot(ZAinv)
        Dd = T.d + T.c.dot(q22.dot(AZinv))

    elif method in ('bilinear', 'tustin', 'trapezoidal'):
        if not PrewarpAt == 0.:
            if 1 / (2 * dt) < PrewarpAt:
                raise ValueError('Prewarping Frequency is beyond the Nyquist'
                                 ' rate. It has to satisfy 0 < w < 1/(2*Δt)'
                                 ' and Δt being the sampling period in '
                                 'seconds. Δt={0} is given, hence the max.'
                                 ' allowed is {1} Hz.'.format(
                                     dt, 1 / (2 * dt)))

            TwoTanw_Over_w = np.tan(
                2 * np.pi * PrewarpAt * dt / 2) / (2 * np.pi * PrewarpAt)
            q = np.array([[1, np.sqrt(2 * TwoTanw_Over_w)],
                          [np.sqrt(2 * TwoTanw_Over_w), TwoTanw_Over_w]])
        else:
            q = np.array([[1, np.sqrt(dt)], [np.sqrt(dt), dt / 2]])

        return __discretize(T, dt, "lft", 0., q)

    elif method in ('forward euler', 'forward difference',
                    'forward rectangular', '>>'):
        return __discretize(T,
                            dt,
                            "lft",
                            0,
                            q=np.array([[1, np.sqrt(dt)], [np.sqrt(dt), 0]]))

    elif method in ('backward euler', 'backward difference',
                    'backward rectangular', '<<'):
        return __discretize(T,
                            dt,
                            "lft",
                            0,
                            q=np.array([[1, np.sqrt(dt)], [np.sqrt(dt), dt]]))

    else:
        raise ValueError('I don\'t know that discretization method. But '
                         'I know {0} methods.'
                         ''.format(_KnownDiscretizationMethods))

    return Ad, Bd, Cd, Dd, dt
Ejemplo n.º 27
0
Archivo: hb.py Proyecto: pawsen/pyvib
    def periodic(self, f0, f_amp, fdofs):
        """Find periodic solution

        NR iteration to solve:
        # Solve h(z,ω)=A(ω)-b(z)=0 (ie find z that is root of this eq), eq. (21)
        # NR solution: (h_z is the derivative of h wrt z)
        # zⁱ⁺¹ = zⁱ - h(zⁱ,ω)/h_z(zⁱ,ω)
        # h_z = A(ω) - b_z(z) = A - Γ⁺ ∂f/∂x Γ
        # where the last exp. is in time domain. df/dx is thus available
        # analytical. See eq (30)

        Parameters
        ----------
        f0: float
            Forcing frequency in Hz
        f_amp: float
            Forcing amplitude

        """
        self.f0 = f0
        self.f_amp = f_amp
        self.fdofs = fdofs

        nu = self.nu
        NH = self.NH
        n = self.n
        nz = self.nz
        scale_x = self.scale_x
        scale_t = self.scale_t
        amp0 = self.amp0
        stability = self.stability
        tol_NR = self.tol_NR
        max_it_NR = self.max_it_NR

        w0 = f0 * 2*np.pi
        omega = w0*scale_t
        omega2 = omega / nu

        t = self.assemblet(omega2)
        nt = len(t)
        u, _ = sineForce(f_amp, omega=omega, t=t)
        force = toMDOF(u, n, fdofs)

        # Assemble A, describing the linear dynamics. eq (20)
        A = self.assembleA(omega2)

        # Form Q(t), eq (8). Q is orthogonal trigonometric basis(harmonic
        # terms) Then use Q to from the kron product Q(t) ⊗ Iₙ, eq (6)
        mat_func_form = np.empty((n*nt, nz))
        Q = np.empty((NH*2+1, 1))
        for i in range(nt):
            Q[0] = 1
            for ii in range(1, NH+1):
                Q[ii*2-1] = np.sin(omega * t[i]*ii)
                Q[ii*2] = np.cos(omega * t[i]*ii)

            # Stack the kron prod, so each block row is for time(i)
            mat_func_form[i*n:(i+1)*n, :] = kron(Q.T, np.eye(n))
        self.mat_func_form_sparse = csr_matrix(mat_func_form)

        if stability:
            hills = Hills(self)
            self.hills = hills

        # Initial guess for x. Here calculated by broadcasting. np.outer could
        # be used instead to calculate the outer product
        amp = np.ones(n)*amp0
        x_guess = amp[:, None] * np.sin(omega * t)/scale_x

        # Initial guess for z, z = Γ⁺x as given by eq (26). Γ is found as
        # Q(t)⊗Iₙ, eq 6
        # TODO use mat_func_form_sparse
        z_guess, *_ = lstsq(mat_func_form, x_guess.ravel())

        # Solve h(z,ω)=A(ω)-b(z)=0 (ie find z-root), eq. (21)
        print('Newton-Raphson iterative solution')

        Obj = 1
        it_NR = 1
        z = z_guess
        while (Obj > tol_NR) and (it_NR <= max_it_NR):
            H = self.state_sys(z, A, force)
            H_z = self.hjac(z, A)

            zsol, *_ = lstsq(H_z, H)
            z = z - zsol

            Obj = norm(H) / norm(z)
            print('It. {} - Convergence test: {:e} ({:e})'.
                  format(it_NR, Obj, tol_NR))
            it_NR = it_NR + 1

        if it_NR > max_it_NR:
            raise ValueError("Number of NR iterations exceeded {}."
                             " Change Harmonic Balance parameters".
                             format(max_it_NR))

        if stability:
            B = hills.stability(omega, H_z)
            B_tilde, stab = hills.reduc(B)
            self.stab_vec.append(stab)
            self.lamb_vec.append(B_tilde)

        # amplitude of hb components
        c, cnorm, phi = hb_components(scale_x*z, n, NH)
        x = hb_signal(omega, t, c, phi)
        xamp = np.max(x, axis=1)

        self.z_vec.append(z)
        self.xamp_vec.append(xamp)
        self.omega_vec.append(omega)

        if stability:
            return omega, z, stab, B
        else:
            return omega, z
Ejemplo n.º 28
0
# +
# set  inputs
m_X = array([[-0.5], [1]])  # expectation of target variable X
s2_X = array([[1, .1], [.1, .2]])  # covariance of target variable X

beta = array([[1], [1]])  # loadings

n_ = m_X.shape[0]  # target dimension
k_ = beta.shape[1]  # number of factors
i_n = eye(n_)
i_k = eye(k_)

km = zeros((k_ * n_, k_ * n_))  # commutation matrix
for n in range(n_):
    for k in range(k_):
        km = km + kron(i_k[:, [k]] @ i_n[:, [n]].T,
                       i_n[:, [n]] @ i_k[:, [k]].T)

# set inputs for quadratic programming problem
invsigma2 = np.diagflat(1 / diag(s2_X))
pos = beta.T @ invsigma2 @ s2_X
g = -pos.flatten()
q = kron(s2_X, beta.T @ invsigma2 @ beta)
q_, _ = q.shape

# linear constraints
v = array([[-1, 1]])
d_eq = kron(i_k, v @ s2_X) @ km
b_eq = zeros((k_**2, 1))

# compute extraction matrix
# options = optimoptions(('quadprog','MaxIter.T, 2000, .TAlgorithm','interior-point-convex'))
Ejemplo n.º 29
0
def PortfolioMomentsLogN(v_tnow, h, LogN_loc, LogN_disp):
    # This function computes the expectation, the standard deviation and the skewness
    # of a portfolio's P&L which is lognormally distributed.
    #  INPUTS
    #  v_tnow        : [vector] (n_ x 1)  current values of the instruments
    #  h             : [vector] (n_ x 1)  portfolio's holdings
    #  LogN_loc      : [vector] (n_ x 1)  location parameter of the instruments lognormal distribution at the horizon
    #  LogN_disp     : [vector] (n_ x n_) dispersion parameter of the instruments lognormal distribution at the horizon
    #  OPS
    #  muPL_h      : [scalar] expectation of the portfolio's P&L
    #  sdPL_h      : [scalar] standard deviation of the portfolio's P&L
    #  skPL_h      : [scalar] skewness of the portfolio's P&L

    # portfolio's P&L expectation
    muV_thor = exp(
        LogN_loc + 1 / 2 * diag(LogN_disp).reshape(-1, 1)
    )  # expectation of the portfolio's instruments at the horizon
    muPL = muV_thor - v_tnow  # expectation of one unit of the portfolio's P&L
    muPL_h = h.T @ muPL  # portfolio's P&L expectation

    n_ = v_tnow.shape[0]
    d = eye(n_)  # canonical basis
    noncent2ndPL = zeros((n_, n_))
    noncent3rdPL = zeros((n_ * n_ * n_, 1))
    cent2ndPL = zeros((n_, n_))
    cent3rdPL = zeros((n_ * n_ * n_, 1))
    i = 0

    for n in range(n_):
        for m in range(n_):
            omega_nm = d[:, n] + d[:, m]
            # second non-central moments
            noncent2ndV_thor_nm = exp(omega_nm.T @ LogN_loc + 1 / 2 *
                                      omega_nm.T @ LogN_disp @ omega_nm)
            noncent2ndPL[n, m] = noncent2ndV_thor_nm - muV_thor[n] * v_tnow[
                m] - muV_thor[m] * v_tnow[n] + v_tnow[m] * v_tnow[n]
            # second central moment
            cent2ndPL[n, m] = noncent2ndPL[n, m] - muPL[n] * muPL[m]
            for l in range(n_):

                omega_nl = d[:, n] + d[:, l]
                omega_ml = d[:, m] + d[:, l]
                omega_nml = d[:, n] + d[:, m] + d[:, l]
                # second non-central moments that enter in the third non-central moments formulas
                noncent2ndV_thor_nl = exp(omega_nl.T @ LogN_loc + 1 / 2 *
                                          omega_nl.T @ LogN_disp @ omega_nl)
                noncent2ndV_thor_ml = exp(omega_ml.T @ LogN_loc + 1 / 2 *
                                          omega_ml.T @ LogN_disp @ omega_ml)
                # third non-central moments
                noncent3rdV_thor_nml = exp(omega_nml.T @ LogN_loc + 1 / 2 *
                                           omega_nml.T @ LogN_disp @ omega_nml)
                noncent3rdPL[i] = noncent3rdV_thor_nml - noncent2ndV_thor_nm*v_tnow[l] - noncent2ndV_thor_nl*v_tnow[m]+\
                                  muV_thor[n]*v_tnow[m]*v_tnow[l] - noncent2ndV_thor_ml*v_tnow[n] +\
                                  muV_thor[m]*v_tnow[n]*v_tnow[l] + muV_thor[l]*v_tnow[n]*v_tnow[m] -\
                                  v_tnow[m]*v_tnow[n]*v_tnow[l]
                # third central moment
                cent3rdPL[i] = noncent3rdPL[i] - noncent2ndPL[n,m]*muPL[l] - noncent2ndPL[n,l]*muPL[m] -\
                               muPL[n]*noncent2ndPL[m,l] + 2*muPL[n]*muPL[m]*muPL[l]
                i = i + 1

    sdPL_h = sqrt(h.T @ cent2ndPL @ h)  # portfolio's P&L standard deviation
    dummy = kron(h, h) @ h.T
    vec_h = dummy.flatten()
    skPL_h = (vec_h.T @ cent3rdPL) / (sdPL_h**3)  # portfolio's P&L skewness

    return muPL_h, sdPL_h, skPL_h
Ejemplo n.º 30
0
def tsvd_sep(B, PSF, center=None, tol=None, BC='zero'):
    """TSVD_SEP Truncated SVD image deblurring using Kronecker decomposition.

    X, tol = tsvd_sep(B, PSF, center, tol, BC)

  Compute restoration using a Kronecker product decomposition and
  a truncated SVD.

  Input:
        B  Array containing blurred image.
      PSF  Array containing the point spread function.
  
  Optional Inputs:
   center  [row, col] = indices of center of PSF.
      tol  Regularization parameter (truncation tolerance).
             Default parameter chosen by generalized cross validation.
       BC  String indicating boundary condition.
             ('zero', 'reflexive', or 'periodic'; default is 'zero'.)

  Output:
        X  Array containing computed restoration.
      tol  Regularization parameter used to construct restoration."""
    #
    # compute the center of the PSF if it is not provided
    #
    if center is None:
        center = array(PSF.shape) / 2

    #
    # if PSF is smaller than B, pad it to the same size as B
    #
    if PSF.size < B.size:
        PSF = padarray(PSF, array(B.shape) - array(PSF.shape),
                       direction='post')

    #
    # First compute the Kronecker product terms, Ar and Ac, where
    # A = kron(Ar, Ac).  Note that if the PSF is not separable, this
    # step computes a Kronecker product approximation to A.
    #
    Ar, Ac = kronDecomp(PSF, center, BC)

    #
    # Compute SVD of the blurring matrix.
    #
    Ur, sr, Vr = svd(Ar)
    Uc, sc, Vc = svd(Ac)

    bhat = dot( dot( Uc.transpose(), B ), Ur )
    bhat = bhat.flatten('f')
    s = kron(matrix(sr),matrix(sc))
    s = array(s.flatten('f'))
    
    #
    # If a regularization parameter is not given, use GCV to find one.
    #
    if tol is None:
        tol = gcv_tsvd( s, bhat.flatten('f') )

    #
    # Compute the TSVD regularized solution.
    #
    idx = where(abs(s) >= tol)
    Sfilt = zeros(shape(bhat),'d')
    Sfilt[idx] = 1 / s[idx]
    Bhat = reshape(bhat * Sfilt , shape(B))
    Bhat = Bhat.transpose()
    X = dot( dot(Vc.transpose(),Bhat), Vr )

    return X, tol
Ejemplo n.º 31
0
def Hhfs(L,S,I):
    """Provides the I dot J matrix (magnetic dipole interaction)"""
    gS=int(2*S+1)
    Sx=jx(S)
    Sy=jy(S)
    Sz=jz(S)
    Si=identity(gS)

    gL=int(2*L+1)
    Lx=jx(L)
    Ly=jy(L)
    Lz=jz(L)
    Li=identity(gL)

    gJ=gL*gS
    Jx=kron(Lx,Si)+kron(Li,Sx)
    Jy=kron(Ly,Si)+kron(Li,Sy)
    Jz=kron(Lz,Si)+kron(Li,Sz)
    Ji=identity(gJ)
    J2=dot(Jx,Jx)+dot(Jy,Jy)+dot(Jz,Jz)

    gI=int(2*I+1)
    gF=gJ*gI
    Ix=jx(I)
    Iy=jy(I)
    Iz=jz(I)
    Ii=identity(gI)
    Fx=kron(Jx,Ii)+kron(Ji,Ix)
    Fy=kron(Jy,Ii)+kron(Ji,Iy)
    Fz=kron(Jz,Ii)+kron(Ji,Iz)
    Fi=identity(gF)
    F2=dot(Fx,Fx)+dot(Fy,Fy)+dot(Fz,Fz)
    Hhfs=0.5*(F2-I*(I+1)*Fi-kron(J2,Ii))
    return Hhfs
Ejemplo n.º 32
0
def unbalance_emai(y,
                   xmat,
                   zmat,
                   kin,
                   init=None,
                   maxiter=30,
                   cc_par=1.0e-8,
                   cc_gra=1.0e-6,
                   em_weight_step=0.001):
    num_var_pos = 1
    for i in range(len(zmat)):
        num_var_pos += len(zmat[i])
    y_var = np.var(y) / num_var_pos
    num_record = y.shape[0]
    var_com = []
    eff_ind = [[0, xmat.shape[1]]]  # the index for all effects [start end]
    zmat_con_lst = []  # combined random matrix
    cov_dim = []  # the dim for covariance matrix
    vari = []
    varij = []
    varik = []
    i = 0
    for i in range(len(zmat)):
        temp = [eff_ind[i][-1]]
        zmat_con_lst.append(hstack(zmat[i]))
        cov_dim.append(len(zmat[i]))
        for j in range(len(zmat[i])):
            temp.append(temp[-1] + zmat[i][j].shape[1])
            for k in range(j + 1):
                vari.append(i + 1)
                varij.append(j + 1)
                varik.append(k + 1)
                if j == k:
                    var_com.append(y_var)
                else:
                    var_com.append(0.0)
        eff_ind.append(temp)
    var_com.append(y_var)
    vari.append(i + 2)
    varij.append(1)
    varik.append(1)
    if init is None:
        var_com = np.array(var_com)
    else:
        if len(var_com) != len(init):
            logging.info('ERROR: The length of initial variances should be' +
                         len(var_com))
            exit()
        else:
            var_com = np.array(init)
    var_com_update = np.array(var_com)
    logging.info('***prepare the MME**')
    zmat_con = hstack(zmat_con_lst)  # design matrix for random effects
    wmat = hstack([xmat, zmat_con])  # merged design matrix
    cmat_pure = np.dot(wmat.T, wmat)  # C matrix
    rhs_pure = wmat.T.dot(y)  # right hand
    # em weight vector
    if em_weight_step <= 0.0 or em_weight_step > 1.0:
        logging.info(
            'ERROR: The em weight step should be between 0 (not include) and 1 (include)'
        )
        exit()
    iter_count = 0
    cc_par_val = 1000.0
    cc_gra_val = 1000.0
    delta = 1000.0
    logging.info("initial variances: " +
                 ' '.join(np.array(var_com, dtype=str)))
    covi_mat = pre_covi_mat(cov_dim, var_com)
    if covi_mat is None:
        logging.inf(
            "ERROR: Initial variances is not positive define, please check!")
        exit()
    while iter_count < maxiter:
        iter_count += 1
        logging.info('***Start the iteration: ' + str(iter_count) + ' ***')
        logging.info("Prepare the coefficient matrix")
        cmat = (cmat_pure.multiply(1.0 / var_com[-1])).toarray()
        for i in range(len(cov_dim)):
            if isspmatrix(kin[i]):
                temp = sparse.kron(covi_mat[i], kin[i])
                temp = temp.toarray()
            else:
                temp = linalg.kron(covi_mat[i], kin[i])
            cmat[eff_ind[i + 1][0]:eff_ind[i + 1][-1], \
            eff_ind[i + 1][0]:eff_ind[i + 1][-1]] = \
                np.add(cmat[eff_ind[i + 1][0]:eff_ind[i + 1][-1], \
                       eff_ind[i + 1][0]:eff_ind[i + 1][-1]], temp)
        rhs_mat = np.divide(rhs_pure, var_com[-1])
        cmati = linalg.inv(cmat)
        eff = np.dot(cmati, rhs_mat)
        e = y - xmat.dot(eff[:eff_ind[0][1], :]) - zmat_con.dot(
            eff[eff_ind[0][1]:, :])
        # first-order derivative
        fd_mat = pre_fd_mat_x(cmati, kin, covi_mat, eff, eff_ind, e, cov_dim,
                              zmat_con_lst, wmat, num_record, var_com)
        # AI matrix
        ai_mat = pre_ai_mat(cmati, covi_mat, eff, eff_ind, e, cov_dim,
                            zmat_con_lst, wmat, var_com)
        # EM matrix
        em_mat = pre_em_mat(cov_dim, zmat_con_lst, num_record, var_com)
        # Increase em weight to guarantee variances positive
        gamma = -em_weight_step
        while gamma < 1.0:
            gamma = gamma + em_weight_step
            if gamma >= 1.0:
                gamma = 1.0
            wemai_mat = (1 - gamma) * ai_mat + gamma * em_mat
            delta = np.dot(linalg.inv(wemai_mat), fd_mat)
            var_com_update = var_com + delta
            covi_mat = pre_covi_mat(cov_dim, var_com_update)
            if covi_mat is not None:
                logging.info('EM weight value: ' + str(gamma))
                break
        logging.info('Updated variances: ' +
                     ' '.join(np.array(var_com_update, dtype=str)))
        if covi_mat is None:
            logging.info("ERROR: Updated variances is not positive define!")
            exit()
        # Convergence criteria
        cc_par_val = np.sum(pow(delta, 2)) / np.sum(pow(var_com_update, 2))
        cc_par_val = np.sqrt(cc_par_val)
        cc_gra_val = np.sqrt(np.sum(pow(fd_mat, 2))) / len(var_com)
        var_com = var_com_update.copy()
        logging.info("Change in parameters, Norm of gradient vector: " +
                     str(cc_par_val) + ', ' + str(cc_gra_val))
        if cc_par_val < cc_par and cc_gra_val < cc_gra:
            break
    if cc_par_val < cc_par and cc_gra_val < cc_gra:
        logging.info("Variances Converged")
    else:
        logging.info("Variances not Converged")
    var_pd = {'vari': vari, "varij": varij, "varik": varik, "var_val": var_com}
    var_pd = pd.DataFrame(var_pd,
                          columns=['vari', "varij", "varik", "var_val"])
    return var_pd
Ejemplo n.º 33
0
# ## Compute statistics of the joint distribution of X,Z

[m_XZ, s2_XZ] = FPmeancov(r_[X, Z], p)
s2_X = s2_XZ[:n_, :n_]
s_XZ = s2_XZ[:n_, n_:n_ + k_]
s2_Z = s2_XZ[n_:n_ + k_, n_:n_ + k_]

# ## Solve generalized regression LFM
# ## set inputs for quadratic programming problem

# +
d = np.diagflat(1 / diag(s2_X))
pos = d @ s_XZ
g = -pos.flatten()
q = kron(s2_Z, d)
q_, _ = q.shape

# set constraints
a_eq = ones((1, n_ * k_)) / (n_ * k_)
b_eq = array([[1]])
lb = 0.8 * ones((n_ * k_, 1))
ub = 1.2 * ones((n_ * k_, 1))

# compute optimal loadings
b = quadprog(q, g, a_eq, b_eq, lb, ub)
b = np.array(b)

beta = reshape(b, (n_, k_), 'F')
alpha = m_XZ[:n_] - beta @ m_XZ[n_:n_ + k_]
# -
Ejemplo n.º 34
0
    def __init__(self, aniso_dipolar, g1_iso, g2_iso, aniso_g1, aniso_g2,
                 iso_h1, iso_h2, aniso_hyperfine_1, aniso_hyperfine_2,
                 spin_numbers_1, spin_numbers_2, field, J, ks, kt, temp, kstd):
        # declare constants and identities

        self.r_perp = 16.60409997886e-10
        self.r_parr = 4.9062966e-10

        self.prefact = 3.92904692e-03
        self.beta = 9.96973104e+01
        self.c = -4.92846450e-03

        #self.visc = 1.0e-3*(-0.00625*temp+2.425)
        self.visc = self.prefact * np.exp(self.beta / temp) + self.c

        self.convert = 1.76e8

        self.d_perp = self.convert * 1.38064852e-23 * temp / (8.0 * np.pi *
                                                              self.visc *
                                                              (self.r_perp**3))
        self.d_parr = self.convert * 1.38064852e-23 * temp / (8.0 * np.pi *
                                                              self.visc *
                                                              (self.r_parr**3))

        self.iden2 = np.eye(2)
        self.iden4 = np.eye(4)
        self.iden16 = np.eye(16)

        #declare matrices
        self.sx = np.array([[0, 0.5], [0.5, 0]])
        self.sy = np.array([[0, -0.5j], [0.5j, 0]])
        self.sz = np.array([[0.5, 0], [0, -0.5]])

        self.s1_x = la.kron(self.sx, self.iden2)
        self.s1_y = la.kron(self.sy, self.iden2)
        self.s1_z = la.kron(self.sz, self.iden2)

        self.s2_x = la.kron(self.iden2, self.sx)
        self.s2_y = la.kron(self.iden2, self.sy)
        self.s2_z = la.kron(self.iden2, self.sz)

        self.s1_s2 = la.kron(self.sx, self.sx) + la.kron(
            self.sy, self.sy) + la.kron(self.sz, self.sz)
        self.pro_trip = 0.75 * np.eye(4) + self.s1_s2
        self.pro_sing = 0.25 * np.eye(4) - self.s1_s2

        # Declare Liouvillian density operators

        self.p0_lou = 0.5 * (np.reshape(self.pro_sing, (16, 1)))
        self.pt_lou = np.reshape(self.pro_trip, (1, 16))
        self.ps_lou = np.reshape(self.pro_sing, (1, 16))

        #Declare Hamiltonian and Louivillian
        self.ltot = np.zeros([16, 16], dtype=complex)
        self.h0 = np.zeros([4, 4], dtype=complex)

        # Declare redfield and components
        self.redfield = np.zeros([16, 16], dtype=complex)
        self.B = np.zeros([16, 16], dtype=complex)

        # Tensor terms
        self.elec = np.zeros([5, 5, 4, 4], dtype=complex)
        self.uq = np.zeros([5, 4, 4], dtype=complex)

        # declare class variable

        self.aniso_g1 = aniso_g1
        self.aniso_g2 = aniso_g2
        self.g_mat = np.zeros([5], dtype=complex)
        self.g1_iso = g1_iso
        self.g2_iso = g2_iso

        self.hyperfine_1 = aniso_hyperfine_1
        self.h1_size = np.size(self.hyperfine_1[:, 0, 0])
        self.h1 = np.zeros([self.h1_size, 5], dtype=complex)
        self.iso_h1 = iso_h1

        self.hyperfine_2 = aniso_hyperfine_2
        self.h2_size = np.size(self.hyperfine_2[:, 0, 0])
        self.h2 = np.zeros([self.h2_size, 5], dtype=complex)
        self.iso_h2 = iso_h2

        self.dipolar = aniso_dipolar
        self.d_rank_2 = np.zeros([5], dtype=complex)

        self.ks = ks
        self.kt = kt

        self.kstd = kstd

        self.J_couple = J

        self.omega1 = [0.0, 0.0, field]
        self.omega2 = [0.0, 0.0, field]

        self.n1_nuclear_spins = self.h1_size
        self.n2_nuclear_spins = self.h2_size

        self.spin_numbers_1 = spin_numbers_1
        self.spin_numbers_2 = spin_numbers_2

        # Variables for sampling SW vectors
        self.angles1 = np.zeros([2, self.n1_nuclear_spins])
        self.angles2 = np.zeros([2, self.n2_nuclear_spins])

        self.nuc_vecs_1 = np.zeros([3, self.n1_nuclear_spins])
        self.nuc_vecs_2 = np.zeros([3, self.n2_nuclear_spins])

        self.omegatot_1 = np.zeros_like(self.omega1)
        self.omegatot_2 = np.zeros_like(self.omega2)

        self.vec_len_1 = np.sqrt(
            np.multiply(self.spin_numbers_1, (self.spin_numbers_1 + 1.0)))
        self.vec_len_2 = np.sqrt(
            np.multiply(self.spin_numbers_2, (self.spin_numbers_2 + 1.0)))

        # Haberkorn
        self.Haberkorn_Matrix()

        return
Ejemplo n.º 35
0
# ## Specify the constraint function with random parameters

# +
a = randn(m_, n_)
q = randn(m_, 1)

# set constant matrices for derivatives
i_n = eye(n_)
i_k = eye(k_)

matrix = namedtuple('matrix', 'hm km1 hm2')
matrix.hm = diag(i_n.flatten())
matrix.km1 = zeros((k_ * n_, k_ * n_**2))
matrix.hm2 = zeros((n_, n_**2))
for n in range(n_):
    matrix.hm2 = matrix.hm2 + kron(i_n[:, [n]].T, diagflat(i_n[:, [n]]))
    matrix.km1 = matrix.km1 + kron(kron(
        i_n[:, [n]].T, i_k), diagflat(i_n[:, [n]]))  # constraint function

v = lambda theta: SigNoConstrLRD(theta, a, q, n_, k_, matrix)[0]
v3 = lambda theta: SigNoConstrLRD(theta, a, q, n_, k_, matrix)[2]
# -

# ## Main computations

err = zeros((j_, 1))
for j in trange(j_, desc='Simulations'):  # Set random variables
    theta_ = randn(n_ + n_ * k_ + n_, 1)
    # Compute numerical Hessian
    for m in range(m_):
        g_m = lambda theta: SigNoConstrLRD(theta, a[[m], :], q[m], n_, k_)[0]
Ejemplo n.º 36
0
    x = np.linspace(min_x,max_x,N)
    y = np.sin(x)
    ddx = derivative_op(min_x,max_x,N)
    dy_dx = np.dot(ddx,y)
    x_mid = midpoint_op(N).dot( x )
    plt.plot( x_mid , dy_dx-np.cos(x_mid) , 'r-')
    plt.title('error')
    plt.show()
    return 0

#unit_test_derivative_op( *span_x)
#quit()

from scipy.linalg import kron

partial_x = kron( midpoint_op(Nt), derivative_op( *span_x ) )
partial_t = kron( derivative_op( *span_t ), midpoint_op(Nx) )

def unit_test_partial_t():
    x = np.linspace( *span_x )
    x_mid = midpoint_op(Nx).dot(x)
    t = np.linspace( *span_t )
    t_mid = midpoint_op(Nt).dot(t)
    #consider the function x*(t**2)
    f = np.kron( t**2 , x )
    df_dt_computed = np.dot( partial_t , f )
    df_dt_computed.resize( Nt-1,Nx-1)
    df_dt = np.kron( 2*t_mid , x_mid )
    df_dt.resize(Nt-1,Nx-1)
    plt.subplot(2,1,1)
    plt.imshow( df_dt )
Ejemplo n.º 37
0
gates = {'I': I, 'X': X, 'Y': Y, 'Z': Z, 'H': H, 'CNOT': CNOT, 'SWAP': SWAP}

N = 10
lim = 0.2
XX = 500

solution = [
    '0100010000', '0100000000', '0100000000', '0100000100', '0000100000',
    '0000000001', '0000010000', '0000000000', '0100000000', '0000000100',
    '0000100000', '0000000001'
]
solution = ['0100010000', '0100000000', '0000100000', '0000000001']

s001 = basis('0000000000')
IIX = kron(
    H, kron(H, kron(H, kron(H, kron(H, kron(H, kron(H, kron(H, kron(H,
                                                                    H)))))))))
A0, T0 = print_wf(IIX * s001)


def uncoupled(A0, T0, nbit):
    D = get_directions(nbit)
    C = []
    result = []
    for i in range(len(D)):
        C.append(0)
        for j in range(len(T0)):
            if T0[j] == D[i]:
                C[i] = (A0[j] / A0[0])**2
        result.append((1 / (1 + C[i]**2)))
        result.append((C[i]**2 / (1 + C[i]**2)))
    def __init__(self,aniso_dipolar,g1_iso,g2_iso,aniso_g1,aniso_g2,iso_h1,iso_h2,aniso_hyperfine_1,aniso_hyperfine_2,spin_numbers_1,spin_numbers_2,field,J,dj,ks,kt,exchange_rate,lamb,temp):
        # declare constants and identities
        self.r_perp = 16.65552296e-10       
        self.r_parr = 8.130217003e-10
        
        self.visc = 1.0e-3*(-0.00625*temp+2.425)
        
        self.convert = 1.0e3/1.76e-11

        self.d_perp = self.convert*1.38064852e-23*temp/(8.0*np.pi*self.visc*(self.r_perp**3))
        self.d_parr = self.convert*1.38064852e-23*temp/(8.0*np.pi*self.visc*(self.r_parr**3))
        
        
        
        self.iden2 = np.eye(2)
        self.iden4 = np.eye(4)
        self.iden16 = np.eye(16)
        
        #declare matrices
        self.sx = np.array([[0,0.5],[0.5,0]])
        self.sy = np.array([[0,-0.5j],[0.5j,0]])
        self.sz = np.array([[0.5,0],[0,-0.5]])
        
        self.s1_x = la.kron(self.sx,self.iden2)
        self.s1_y = la.kron(self.sy,self.iden2)
        self.s1_z = la.kron(self.sz,self.iden2)
        
        self.s2_x = la.kron(self.iden2,self.sx)
        self.s2_y = la.kron(self.iden2,self.sy)
        self.s2_z = la.kron(self.iden2,self.sz)
        
        self.s1_s2 = la.kron(self.sx,self.sx) + la.kron(self.sy,self.sy) + la.kron(self.sz,self.sz)
        self.pro_trip = 0.75 * np.eye(4) + self.s1_s2
        self.pro_sing = 0.25 * np.eye(4) - self.s1_s2
        
        # Declare Liouvillian density operators
        self.p0_lou = np.zeros([32,1],dtype = complex)
        self.pt_lou = np.zeros([1,32],dtype = complex)
        self.ps_lou = np.zeros([1,32],dtype = complex)
        
        self.lamb = lamb
        
        self.p0_lou[:16,:] = 0.5 * ((1.0-self.lamb)*np.reshape(self.pro_sing,(16,1))+(self.lamb/3.0)*np.reshape(self.pro_trip,(16,1))) 
        self.p0_lou[16:,:] = 0.5 * ((1.0-self.lamb)*np.reshape(self.pro_sing,(16,1))+(self.lamb/3.0)*np.reshape(self.pro_trip,(16,1)))  
        
        self.pt_lou[:,:16] = np.reshape(self.pro_trip,(1,16)) 
        self.pt_lou[:,16:] = np.reshape(self.pro_trip,(1,16))
        
        self.ps_lou[:,:16] = np.reshape(self.pro_sing,(1,16)) 
        self.ps_lou[:,16:] = np.reshape(self.pro_sing,(1,16))

        
        #Declare Hamiltonian and Louivillian
        self.ltot = np.zeros([32,32], dtype = complex)
        self.h0 = np.zeros([4,4], dtype = complex)
        
        # Declare redfield and components
        self.redfield = np.zeros([32,32], dtype = complex)
        self.B = np.zeros([32,32], dtype = complex)
        
        # Tensor terms
        self.elec = np.zeros([5,5,4,4],dtype = complex)
        self.uq = np.zeros([5,4,4],dtype = complex)
        
        # declare class variable
        
        self.aniso_g1 = aniso_g1
        self.aniso_g2 = aniso_g2
        self.g_mat = np.zeros([5],dtype = complex)
        self.g1_iso = g1_iso
        self.g2_iso = g2_iso
        
        self.hyperfine_1 = aniso_hyperfine_1
        self.h1_size = np.size(self.hyperfine_1[:,0,0])
        self.h1 = np.zeros([self.h1_size,5], dtype = complex)
        self.iso_h1 = iso_h1
        
        self.hyperfine_2 = aniso_hyperfine_2
        self.h2_size = np.size(self.hyperfine_2[:,0,0])
        self.h2 = np.zeros([self.h2_size,5], dtype = complex)
        self.iso_h2 = iso_h2
        
        self.dipolar = aniso_dipolar
        self.d_rank_2 = np.zeros([5],dtype = complex)
        
        self.ks = ks
        self.kt = kt
        
        self.J_couple = J
        self.del_J_couple = dj
        
        self.exchange_rate = exchange_rate
        
        self.omega1 = [0.0,0.0,field]
        self.omega2 = [0.0,0.0,field]
        
        self.n1_nuclear_spins = self.h1_size
        self.n2_nuclear_spins = self.h2_size
        
        self.spin_numbers_1 = spin_numbers_1
        self.spin_numbers_2 = spin_numbers_2
        
        # Variables for sampling SW vectors
        self.angles1 = np.zeros([2,self.n1_nuclear_spins])
        self.angles2 = np.zeros([2,self.n2_nuclear_spins])
        
        self.nuc_vecs_1 = np.zeros([3,self.n1_nuclear_spins])
        self.nuc_vecs_2 = np.zeros([3,self.n2_nuclear_spins])
        
        self.omegatot_1 = np.zeros_like(self.omega1)
        self.omegatot_2 = np.zeros_like(self.omega2)
        
        self.vec_len_1 = np.sqrt(np.multiply(self.spin_numbers_1,(self.spin_numbers_1+1.0)))
        self.vec_len_2 = np.sqrt(np.multiply(self.spin_numbers_2,(self.spin_numbers_2+1.0)))
        
        
        # Haberkorn
        self.Haberkorn_Matrix()
        
        return
Ejemplo n.º 39
0
    for i in range(len(misalignments)):
        phi = misalignments[i]
        R = np.array([[np.cos(phi), -np.sin(phi)], [np.sin(phi), np.cos(phi)]])
        if i == 0:
            DR_2D = R
        else:
            DR_2D = la.block_diag(DR_2D, R)
    return DR_2D


misalignments = np.random.uniform(-0.17, 0.17, numAgents)

DR = build_DR_2D(misalignments)

# Kronecker products
Bb = la.kron(B, np.eye(m))
Lb = la.kron(L, np.eye(m))
Mb = la.kron(M, np.eye(m))
Lambdab = la.kron(Lambda, np.eye(m))
Dab = la.kron(Da, np.eye(m))

Dx = Dab.dot(DR)

# Initial conditions
p0 = np.random.uniform(-20, 20, numAgents * m)


# ODE(s)
def displacement_based(p, t, Lb, p_star):
    dpdt = -Lb.dot(p - p_star)
    return dpdt
Ejemplo n.º 40
0
def projection_shifts(A, E, Z, W, prev_shifts, shift_options):
    """Find further shift parameters for low-rank ADI iteration using
    Galerkin projection on spaces spanned by LR-ADI iterates.

    See [PK16]_, pp. 92-95.

    Parameters
    ----------
    A
        The |Operator| A from the corresponding Lyapunov equation.
    E
        The |Operator| E from the corresponding Lyapunov equation.
    Z
        A |VectorArray| representing the currently computed low-rank solution factor.
    W
        A |VectorArray| representing the currently computed low-rank residual factor.
    prev_shifts
        A |NumPy array| containing the set of all previously used shift parameters.
    shift_options
        The shift options to use (see :func:`lyap_solver_options`).

    Returns
    -------
    shifts
        A |NumPy array| containing a set of stable shift parameters.
    """
    u = shift_options['z_columns']
    L = prev_shifts.size
    r = len(W)
    d = L - u
    if d < 0:
        u = L
        d = 0
    if prev_shifts[-u].imag < 0:
        u = u + 1

    Vu = Z[-u * r:]  # last u matrices V added to solution factor Z

    if shift_options['implicit_subspace']:
        B = np.zeros((u, u))
        G = np.zeros((u, 1))
        Ir = np.eye(r)
        iC = np.where(np.imag(prev_shifts) > 0)[0]  # complex shifts indices (first shift of complex pair)
        iR = np.where(np.isreal(prev_shifts))[0]  # real shifts indices
        iC = iC[iC >= d]
        iR = iR[iR >= d]
        i = 0

        while i < u:
            rS = iR[iR < d + i]
            cS = iC[iC < d + i]
            rp = prev_shifts[d + i].real
            cp = prev_shifts[d + i].imag
            G[i, 0] = np.sqrt(-2 * rp)
            if cp == 0:
                B[i, i] = rp
                if rS.size > 0:
                    B[i, rS - d] = -2 * np.sqrt(rp*np.real(prev_shifts[rS]))
                if cS.size > 0:
                    B[i, cS - d] = -2 * np.sqrt(2*rp*np.real(prev_shifts[cS]))
                i = i + 1
            else:
                sri = np.sqrt(rp**2+cp**2)
                B[i: i + 2, i: i + 2] = [[2*rp, -sri], [sri, 0]]
                if rS.size > 0:
                    B[i, rS - d] = -2 * np.sqrt(2*rp*np.real(prev_shifts[rS]))
                if cS.size > 0:
                    B[i, cS - d] = -4 * np.sqrt(rp*np.real(prev_shifts[cS]))
                i = i + 2
        B = spla.kron(B, Ir)
        G = spla.kron(G, Ir)

        s, v = spla.svd(Vu.gramian(), full_matrices=False)[1:3]
        P = v.T.dot(np.diag(1. / np.sqrt(s)))
        Q = Vu.to_numpy().T.dot(P)

        E_V = E.apply(Vu).to_numpy().T
        T = Q.T.dot(E_V)
        Ap = Q.T.dot(W.to_numpy().T).dot(G.T).dot(P) + T.dot(B.dot(P))
        Ep = T.dot(P)
    else:
        Q = gram_schmidt(Vu, atol=0, rtol=0)
        Ap = A.apply2(Q, Q)
        Ep = E.apply2(Q, Q)

    shifts = spla.eigvals(Ap, Ep)
    shifts = shifts[np.real(shifts) < 0]
    if shifts.size == 0:
        return np.concatenate((prev_shifts, prev_shifts))
    else:
        return np.concatenate((prev_shifts, shifts))
Ejemplo n.º 41
0
print(x)

##
## Determinant
## ===========

det_a = linalg.det(a)

print(det_a)

##
## Kronecker product
## =================

kron = linalg.kron(a, a_inv)
print(kron)

##
## Others
## ======

# (1): tril
# ---

# Make a copy of a matrix with elements above the k-th diagonal zeroed.
# k == 0 is the main diagonal, k < 0 subdiagonal and k > 0 superdiagonal.
print(linalg.tril(kron))

print(linalg.tril(kron, k=-1))
print(linalg.tril(kron, k=1))
Ejemplo n.º 42
0
def solvingStuffForPQRS(AA, BB, CC, DD, FF, GG, HH, JJ, KK, LL, MM, NN):
    q_eqns = sp.shape(FF)[0]
    m_states = sp.shape(FF)[1]
    l_equ = sp.shape(CC)[0]
    n_endog = sp.shape(CC)[1]

	
    k_exog = min(sp.shape(sp.mat(NN))[0], sp.shape(sp.mat(NN))[1])


    if n_endog > 0 and npla.matrix_rank(CC)<n_endog:
        print('CC is not of rank n. Cannot solve. Quitting. Goodbye')
    else:
        if l_equ==0:
#            CC_plus = la.pinv(CC)
 #           CC_0 = nullSpaceBasis(CC.T)
            Psi_mat = FF
            Gamma_mat=- GG
            Theta_mat = -HH
            Xi_mat    = sp.vstack(( sp.hstack((Gamma_mat, Theta_mat)), sp.hstack((sp.eye(m_states), sp.zeros((m_states,m_states))))))
            Delta_mat = sp.vstack((sp.hstack((Psi_mat, sp.mat(sp.zeros((m_states,m_states))))), sp.hstack((sp.zeros((m_states,m_states)), sp.eye(m_states))))) 
        
        else:
            CC_plus = la.pinv(CC)
            CC_0 = nullSpaceBasis(CC.T)
            Psi_mat = sp.vstack((sp.zeros((l_equ - n_endog, m_states)), FF - sp.dot(sp.dot(JJ,CC_plus),AA)))
            if sp.size(CC_0) !=0:
                Gamma_mat = sp.vstack((sp.dot(CC_0,AA), sp.dot(sp.dot(JJ,CC_plus),BB) - GG + sp.dot(sp.dot(KK,CC_plus),AA) ))
                Theta_mat = sp.vstack((sp.dot(CC_0,AA), sp.dot(sp.dot(KK,CC_plus),BB) - HH))
            else:
                Gamma_mat = sp.dot(sp.dot(JJ,CC_plus),BB) - GG + sp.dot(sp.dot(KK,CC_plus),AA)
                Theta_mat = sp.dot(sp.dot(KK,CC_plus),BB) - HH
            Xi_mat    = sp.vstack(( sp.hstack((Gamma_mat, Theta_mat)), sp.hstack((sp.eye(m_states), sp.zeros((m_states,m_states))))))
            Delta_mat = sp.vstack((sp.hstack((Psi_mat, sp.mat(sp.zeros((m_states,m_states))))), sp.hstack((sp.zeros((m_states,m_states)), sp.eye(m_states)))))
        
        eVals, eVecs = la.eig(Xi_mat, Delta_mat)
        if npla.matrix_rank(eVecs)<m_states:
            print('Error: Xi is not diagonalizable, stopping')
        else:
            Xi_sortabs = sp.sort(abs(eVals))
            Xi_sortindex = sp.argsort(abs(eVals))
            Xi_sortedVec = sp.array([eVecs[:,i] for i in Xi_sortindex])
            Xi_sortval = Xi_sortabs
            Xi_select = np.arange(0,m_states)
            if sp.imag(Xi_sortedVec[m_states-1]).any():
                if (abs(Xi_sortval[m_states-1] - sp.conj(Xi_sortval[m_states])) <TOL):
                    drop_index = 1
                    while (abs(sp.imag(Xi_sortval[drop_index]))>TOL) and (drop_index < m_states):
                        drop_index+=1
                    if drop_index >= m_states:
                        print('There is an error. Too many complex eigenvalues. Quitting')
                    else:
                        print('droping the lowest real eigenvalue. Beware of sunspots')
                        Xi_select = np.array([np.arange(0,drop_index-1),np.arange(drop_index+1,m_states)])
            # Here Uhlig computes stuff if user chose "Manual roots" I am skipping it.
            if max(abs(Xi_sortval[Xi_select]))> 1 + TOL:
                print('It looks like we have unstable roots. This might not work')
            if abs(max(abs(Xi_sortval[Xi_select])) -1) < TOL:
                print('Check the model to make sure you have a unique steady state'\
                ,'we are having problems with convergence.')
            Lambda_mat = sp.diag(Xi_sortval[Xi_select])
            Omega_mat = sp.mat(sp.hstack((Xi_sortedVec[(m_states):(2*(m_states)),Xi_select])))
            print Omega_mat
            # Omega_mat = sp.reshape(Omega_mat,(Omega_mat.size**1/2,Omega_mat.size**1/2))
            if npla.matrix_rank(Omega_mat) < m_states:
                PP, Diff = solve_P(FF, GG, HH)
                PP = sp.real(PP)
                FFPP_plus_GG = sp.dot(FF,PP) + GG
                print FFPP_plus_GG
                print PP
                print("Omega matrix is not invertible, Can't solve for P")
            else:
                PP =  sp.dot(sp.dot(Omega_mat,Lambda_mat),la.inv(Omega_mat))
                PP_imag = sp.imag(PP)
                PP = sp.real(PP)
                if sum(sum(abs(PP_imag))) / sum(sum(abs(PP))) > .000001:
                    print("A lot of P is complex. We will continue with the real part and hope we don't lose too much information")
                    
        #The code below was from he Uhlig file cacl_qrs.m. I think for python it fits better here.
    if l_equ ==0:
        RR = sp.zeros((0,m_states))
        Bleh = (la.kron(sp.mat(NN.T), sp.mat(FF)))
        print Bleh
        #Don't you dare delete bleh and meh... They are the reason it works!!!
        Meh = la.kron(NN.T, FFPP_plus_GG)
		#100000000 strong for the matrices bleh and meh.  Click HERE to join
        print FFPP_plus_GG
        VV = Bleh + Meh
#        VV = mparray2npfloat(VV)
        print VV, 'death'
		#VV = sp.kron(NN.T,FF)+sp.kron(sp.eye(k_exog),sp.dot(FF,PP)+GG) #sp.kron(NN.T,JJ)+sp.kron(sp.eye(k_exog),KK)))
    else:   
        RR = - sp.dot(CC_plus,(sp.dot(AA,PP)+BB))
        VV = sp.vstack((sp.hstack((sp.kron(eye(k_exog),AA), sp.kron(eye(k_exog),CC))),\
        sp.hstack((sp.kron(NN.T,FF)+sp.kron(sp.eye(k_exog),sp.dot(FF,PP)+sp.dot(JJ,RR)+GG), sp.kron(NN.T,JJ)+sp.kron(sp.eye(k_exog),KK)))))
        
    if  False and (npla.matrix_rank(VV) < k_exog*(m_states + n_endog)):
        print("Sorry but V is note invertible. Can't solve for Q and S")
    else:
        LLNN_plus_MM = sp.dot(sp.mat(LL.T),sp.mat(NN)) + sp.mat(MM.T)
        QQSS_vec = sp.dot(la.inv(sp.mat(VV)), sp.mat(LLNN_plus_MM))
        QQSS_vec = -QQSS_vec
        if max(abs(QQSS_vec)) == sp.inf:
            print("We have issues with Q and S. Entries are undefined. Probably because V is no inverible.")
        
        QQ = sp.reshape(QQSS_vec[0:m_states*k_exog],(m_states,k_exog))
        SS = sp.reshape(QQSS_vec[(m_states*k_exog):((m_states+n_endog)*k_exog)],(n_endog,k_exog))
        
        # The vstack and hstack's below are ugly, but safe. If you have issues with WW uncomment the first definition and comment out the second one.
        #WW = sp.vstack((\
        #sp.hstack((sp.eye(m_states), sp.zeros((m_states,k_exog)))),\
        #sp.hstack((sp.dot(RR,sp.pinv(PP)), (SS-sp.dot(sp.dot(RR,sp.pinv(PP)),QQ)))),\
        #sp.hstack((sp.zeros((k_exog,m_states)),sp.eye(k_exog)))))
        
        WW = sp.array([[sp.eye(m_states), sp.zeros((m_states,k_exog))],\
        [sp.dot(RR,la.pinv(PP)), (SS-sp.dot(sp.dot(RR,la.pinv(PP)),QQ))],\
        [sp.zeros((k_exog,m_states)),sp.eye(k_exog)]])
    return PP, QQ, RR, SS
    
#def solveQRS():
    #if l_equ ==0:
    #    RR = sp.zeros((0,m_states))
    #    VV = sp.hstack((sp.kron(NN.T,FF)+sp.kron(sp.eye(k_exog),sp.dot(FF,PP)+GG), sp.kron(NN.T,JJ)+sp.kron(sp.eye(k_exog),KK)))
    #else:   
    #    RR = - sp.dot(CC_plus,(sp.dot(AA,PP)+BB))
    #    VV = sp.vstack((sp.hstack((sp.kron(eye(k_exog),AA), sp.kron(eye(k_exog),CC))),\
    #    sp.hstack((sp.kron(NN.T,FF)+sp.kron(sp.eye(k_exog),sp.dot(FF,PP)+sp.dot(JJ,RR)+GG), sp.kron(NN.T,JJ)+sp.kron(sp.eye(k_exog),KK)))))
    #    
    #if (np.matrix_rank(VV) < k_exog*(m_states + n_endog)):
    #    print("Sorry but V is note invertible. Can't solve for Q and S")
    #else:
    #    LLNN_plus_MM = LL*NN + MM
    #    QQSS_vec = - sp.dot(la.inv(VV), sp.vstack((DD,LLNN_plus_MM )))
    #    if max(abs(QQSS_vec)) == sp.inf:
    #        print("We have issueswith Q and S. Entries are undefined. Probably because V is no inverible.")
    #    
    #    QQ = sp.reshape(QQSS_vec[0:m_states*k_exog],(m_states,k_exog))
    #    SS = sp.reshape(QQSS_vec[(m_states*k_exog+1):((m_states+n_endog)*k_endog)],(n_endog,k_endog))
    #    WW = sp.vstack((\
    #    sp.hstack((sp.eye(m_states), sp.zeros((m_states,k_exog)))),\
    #    sp.hstack((sp.dot(RR,sp.pinv(PP)), (SS-sp.dot(sp.dot(RR,sp.pinv(PP)),QQ)))),\
    #    sp.hstack((sp.zeros((k_exog,m_states)),sp.eye(k_exog)))))
    #    
        
    
Ejemplo n.º 43
0

if __name__ == "__main__":
    # Shape
    m = 2
    #ps = np.array([2,0,1,1,1,-1,0,1,0,-1,-1,1,-1,-1])
    ps = np.array([2, 0, 1, 1, 1, -1, 0, 1, 0, -1, -1, 1, -1, -1, -2, 0])
    numAgents = len(ps) / m
    #list_edges = ((1,2),(1,3),(1,4),(1,5),(2,4),(2,7),(3,5),(3,6),(4,5),(4,6),(5,7),(6,7))
    list_edges = ((1, 2), (1, 3), (1, 4), (1, 5), (2, 4), (2, 7), (3, 5),
                  (3, 6), (4, 5), (4, 6), (5, 7), (6, 8), (7, 8), (4, 8), (5,
                                                                           8))
    B = build_B(list_edges, numAgents)
    w = find_w_from_ps(ps, B, m)
    L = build_Laplacian(B, w)
    Bb = la.kron(B, np.eye(m))
    Lb = la.kron(L, np.eye(m))

    Mr = np.zeros_like(B)
    Mr[0, 0] = -0.5
    Mr[0, 1] = 0.5
    Mr[1, 0] = -1 / np.sqrt(2)
    Mr[2, 1] = 1 / np.sqrt(2)
    Mr[3, 4] = -1
    Mr[4, 6] = 1
    Mr[5, 11] = -1 / np.sqrt(2)
    Mr[6, 12] = 1 / np.sqrt(2)
    Mr[7, 11] = -0.5
    Mr[7, 12] = 0.5
    kr = 0.0
Ejemplo n.º 44
0
bend_loc = seg/2

voltage = 1

e0 = 8.854e-12
col = 1.602176565e-19

##digitize physical space
dl = line_len / seg

cl = np.cos(pi * bend_ang / 180)
sl = np.sin(pi * bend_ang / 180)

x_quad2 = linalg.toeplitz(np.arange(0, bend_loc) * dl)
xy_quad4 = linalg.toeplitz(np.arange(0, seg - bend_loc))
quad13 = kron(np.ones((bend_loc,1)), xy_quad4[0,:])
quad13 = quad13.reshape((bend_loc,seg - bend_loc))
y_quad13 = quad13 * sl*dl + sl*dl
x_quad13 = quad13 * cl*dl + cl*dl+ x_quad2[:,-1:]

x =  np.vstack( (np.hstack( (x_quad2,x_quad13) ), np.hstack((x_quad13.T,xy_quad4 * cl*dl) ) ) )

y =  np.vstack( (np.hstack( (np.zeros(np.shape(x_quad2)),y_quad13) ),np.hstack( (y_quad13.T,xy_quad4 * sl*dl) ) ))



##build coefficient matrix
coeff_mat = np.sqrt(x**2 + y**2)
coeff_mat =  2 * line_dia * dl / coeff_mat
coeff_mat[np.diag_indices(seg)] = 4 * pi * line_dia * np.log(dl / line_dia)
# coeff_mat[0,:] = 2 * line_dia * dl / opoint
Ejemplo n.º 45
0
def projection_shifts(A, E, Z, W, prev_shifts, shift_options):
    """Find further shift parameters for low-rank ADI iteration using
    Galerkin projection on spaces spanned by LR-ADI iterates.

    See [PK16]_, pp. 92-95.

    Parameters
    ----------
    A
        The |Operator| A from the corresponding Lyapunov equation.
    E
        The |Operator| E from the corresponding Lyapunov equation.
    Z
        A |VectorArray| representing the currently computed low-rank
        solution factor.
    W
        A |VectorArray| representing the currently computed low-rank
        residual factor.
    prev_shifts
        A |NumPy array| containing the set of all previously used shift
        parameters.
    shift_options
        The shift options to use (see :func:`lyap_lrcf_solver_options`).

    Returns
    -------
    shifts
        A |NumPy array| containing a set of stable shift parameters.
    """
    u = shift_options['z_columns']
    L = prev_shifts.size
    r = len(W)
    d = L - u
    if d < 0:
        u = L
        d = 0
    if prev_shifts[-u].imag < 0:
        u = u + 1

    Vu = Z[-u * r:]  # last u matrices V added to solution factor Z

    if shift_options['implicit_subspace']:
        B = np.zeros((u, u))
        G = np.zeros((u, 1))
        Ir = np.eye(r)
        iC = np.where(np.imag(prev_shifts) > 0)[
            0]  # complex shifts indices (first shift of complex pair)
        iR = np.where(np.isreal(prev_shifts))[0]  # real shifts indices
        iC = iC[iC >= d]
        iR = iR[iR >= d]
        i = 0

        while i < u:
            rS = iR[iR < d + i]
            cS = iC[iC < d + i]
            rp = prev_shifts[d + i].real
            cp = prev_shifts[d + i].imag
            G[i, 0] = np.sqrt(-2 * rp)
            if cp == 0:
                B[i, i] = rp
                if rS.size > 0:
                    B[i, rS - d] = -2 * np.sqrt(rp * np.real(prev_shifts[rS]))
                if cS.size > 0:
                    B[i,
                      cS - d] = -2 * np.sqrt(2 * rp * np.real(prev_shifts[cS]))
                i = i + 1
            else:
                sri = np.sqrt(rp**2 + cp**2)
                B[i:i + 2, i:i + 2] = [[2 * rp, -sri], [sri, 0]]
                if rS.size > 0:
                    B[i,
                      rS - d] = -2 * np.sqrt(2 * rp * np.real(prev_shifts[rS]))
                if cS.size > 0:
                    B[i, cS - d] = -4 * np.sqrt(rp * np.real(prev_shifts[cS]))
                i = i + 2
        B = spla.kron(B, Ir)
        G = spla.kron(G, Ir)

        s, v = spla.svd(Vu.gramian(), full_matrices=False)[1:3]
        P = v.T.dot(np.diag(1. / np.sqrt(s)))
        Q = Vu.lincomb(P.T)

        T = E.apply2(Q, Vu)
        Ap = Q.dot(W).dot(G.T).dot(P) + T.dot(B.dot(P))
        Ep = T.dot(P)
    else:
        Q = gram_schmidt(Vu, atol=0, rtol=0)
        Ap = A.apply2(Q, Q)
        Ep = E.apply2(Q, Q)

    shifts = spla.eigvals(Ap, Ep)
    shifts = shifts[shifts.real < 0]
    if shifts.size == 0:
        return np.concatenate((prev_shifts, prev_shifts))
    else:
        return np.concatenate((prev_shifts, shifts))
Ejemplo n.º 46
0
# +
mu_ = randn(n_, 1)  # expectation
c = randn(n_, n_)

invs2_ = c @ c.T  # inverse covariance

# set constant matrices for second derivatives
i_n = eye(n_)
i_k = eye(k_)

matrix = namedtuple('matrix', 'hm1 km')
matrix.hm1 = zeros((n_**2, n_))
matrix.km = zeros((k_ * n_, k_ * n_))

for k in range(k_):
    matrix.km = matrix.km + kron(kron(i_k[:, [k]], i_n), i_k[:, [k]].T)

for n in range(n_):
    matrix.hm1 = matrix.hm1 + kron(i_n[:, [n]], diagflat(
        i_n[:, [n]]))  # relative entropy

e = lambda theta: REnormLRD(theta, mu_, invs2_, n_, k_, matrix)[0]
e3 = lambda theta: REnormLRD(theta, mu_, invs2_, n_, k_, matrix)[2]
# -

# ## Main computations

err = zeros((j_, 1))
for j in trange(j_, desc='Simulations'):
    # Set random variables
    theta_ = randn(n_ + n_ * k_ + n_, 1)
Ejemplo n.º 47
0
#N for Walking times
N = 1000
#picture lim for y
lim = 0.18
#showing interval(ms)
timess = 40
#definition about the searching targets and basis
solution = ['10010100', '01000100', '01011110', '10100000', '11000000']
s001 = basis('00000000')
nbit = len(solution[0])
nspace = 2**nbit

#genearate Hilbert space
H_single_coin = H
for i in range(nbit - 1):
    H_single_coin = kron(H, H_single_coin)
A0, T0 = print_wf(H_single_coin * s001)

#geneate initial_states
Coin = []
for i in range(nspace):
    Coin.append([])
    for j in range(nbit):
        Coin[i].append(1 / np.sqrt(nbit * nspace))

Directions = get_directions(nbit)
Quantum = [Coin, Directions, T0]
print(Quantum)
results = []
results.append(get_Prob(Quantum))