コード例 #1
0
ファイル: Actor.py プロジェクト: ml4ai/b3
 def vectors_to_Angle(self, aV1, aV2):
     mVect1 = pylab.matrix(aV1)
     mVect2 = pylab.matrix(aV2)
     nNorms = (pylab.norm(mVect1) * pylab.norm(mVect2))
     if nNorms == 0: return "-"
     nAngle = pylab.arccos(mVect1 * mVect2.T / nNorms)
     return float(nAngle)
コード例 #2
0
 def _bodyState2LidarState(self, bodyState):
     '''
     transform body 6-dim vector state to lidar matrix state
     return w_R_L(3*3 matrix), w_T_L(3*1 matrix)
     '''
     bodyState[3:] *= DEG2RAD
     roll = bodyState[3]
     pitch = bodyState[4]
     yaw = bodyState[5]
     w_R_b = pl.matrix(
         [[
             cos(pitch) * cos(yaw),
             -cos(roll) * sin(yaw) + sin(roll) * sin(pitch) * cos(yaw),
             sin(roll) * sin(yaw) + cos(roll) * sin(pitch) * cos(yaw)
         ],
          [
              cos(pitch) * sin(yaw),
              cos(roll) * cos(yaw) + sin(roll) * sin(pitch) * sin(yaw),
              -sin(roll) * cos(yaw) + cos(roll) * sin(pitch) * sin(yaw)
          ], [-sin(pitch),
              sin(roll) * cos(pitch),
              cos(roll) * cos(pitch)]])
     w_R_L = w_R_b * LidarFrame.b_R_L
     w_T_b = pl.matrix(bodyState[:3]).T
     w_T_L = w_T_b + w_R_b * LidarFrame.b_T_L
     return w_R_L, w_T_L
コード例 #3
0
ファイル: ss.py プロジェクト: syantek/sysid
    def dynamics(self, x, u, w):
        """
        Dynamics
        x(k+1) = A x(k) + B u(k) + w(k)

        E(ww^T) = Q

        Parameters
        ----------
        x : The current state.
        u : The current input.
        w : The current process noise.

        Return
        ------
        x(k+1) : The next state.

        """
        x = pl.matrix(x)
        u = pl.matrix(u)
        w = pl.matrix(w)
        assert x.shape[1] == 1
        assert u.shape[1] == 1
        assert w.shape[1] == 1
        return self.A*x + self.B*u + w
コード例 #4
0
ファイル: Individual_Attrs.py プロジェクト: ml4ai/b3
 def vectors_to_Angle(self, aV1, aV2):
     mVect1 = pylab.matrix(aV1);
     mVect2 = pylab.matrix(aV2);
     nNorms = (pylab.norm(mVect1)*pylab.norm(mVect2));
     if nNorms==0: return float('nan');
     nAngle = pylab.arccos(mVect1*mVect2.T/nNorms);
     return float(nAngle);
コード例 #5
0
    def WriteReactionsToHtml(self, S, rids, fluxes, cids, show_cids=True):
        self.thermo.pH = 7
        dG0_r = self.thermo.GetTransfromedReactionEnergies(S, cids)

        self.html_writer.write("<li>Reactions:</br><ul>\n")

        for r in range(S.shape[0]):
            self.html_writer.write('<li><a href=' +
                                   self.kegg.rid2link(rids[r]) +
                                   '>%s ' % rids[r] + '</a>')
            self.html_writer.write(
                '[x%g, &Delta;G<sub>r</sub>&deg; = %.1f] : ' %
                (fluxes[r], dG0_r[r, 0]))
            self.html_writer.write(
                self.kegg.vector_to_hypertext(S[r, :].flat,
                                              cids,
                                              show_cids=show_cids))
            self.html_writer.write('</li>\n')

        v_total = pylab.dot(pylab.matrix(fluxes), S).flat
        dG0_total = pylab.dot(pylab.matrix(fluxes), dG0_r)[0, 0]
        self.html_writer.write('<li><b>Total </b>')
        self.html_writer.write(
            '[&Delta;G<sub>r</sub>&deg; = %.1f kJ/mol] : \n' % dG0_total)
        self.html_writer.write(
            self.kegg.vector_to_hypertext(v_total, cids, show_cids=show_cids))
        self.html_writer.write("</li></ul></li>\n")
コード例 #6
0
ファイル: subspace.py プロジェクト: syantek/sysid
def project_perp(A):
    """
    Creates a projection matrix onto the space perpendicular to the
    rowspace of A.
    """
    A = pl.matrix(A)
    I = pl.matrix(pl.eye(A.shape[1]))
    P = project(A)
    return  I - P
コード例 #7
0
 def __init_prob_map(width,height,L):
     if type(L).__name__ == "list":
         _init = SimpleProbStrategy.__init_prob_map
         return reduce(__add__,[_init(width,height,l) for l in L])
     else:
         my_x = arange(1,width+1)
         my_y = arange(1,height+1)
         my_rows = matrix([minimum(L,minimum((width+1)-my_x, my_x))] * width)
         my_cols = matrix([minimum(L,minimum((height+1)-my_y,my_y))] * height).transpose()
         return my_rows + my_cols
コード例 #8
0
ファイル: icsd.py プロジェクト: Junji110/iCSD
 def calc_f_matrix(self):
     '''Calculate the F-matrix for cubic spline iCSD method'''
     el_len = self.coord_electrode.size
     z_js = pl.zeros(el_len+2)
     z_js[1:-1] = self.coord_electrode
     z_js[-1] = z_js[-2] + pl.diff(self.coord_electrode).mean()
     
     # Define integration matrixes
     f_mat0 = pl.matrix(pl.zeros((el_len, el_len+1)))
     f_mat1 = pl.matrix(pl.zeros((el_len, el_len+1)))
     f_mat2 = pl.matrix(pl.zeros((el_len, el_len+1)))
     f_mat3 = pl.matrix(pl.zeros((el_len, el_len+1)))
     
     # Calc. elements
     for j in xrange(el_len):
         for i in xrange(el_len):
             f_mat0[j, i] = si.quad(self.f_mat0, a=z_js[i], b=z_js[i+1], \
                 args=(z_js[j+1]), epsabs=self.tol)[0]
             f_mat1[j, i] = si.quad(self.f_mat1, a=z_js[i], b=z_js[i+1], \
                                args=(z_js[j+1], z_js[i]), \
                                     epsabs=self.tol)[0]
             f_mat2[j, i] = si.quad(self.f_mat2, a=z_js[i], b=z_js[i+1], \
                                args=(z_js[j+1], z_js[i]), \
                                     epsabs=self.tol)[0]
             f_mat3[j, i] = si.quad(self.f_mat3, a=z_js[i], b=z_js[i+1], \
                                args=(z_js[j+1], z_js[i]), \
                                     epsabs=self.tol)[0]
             # image technique if conductivity not constant:
             if self.cond != self.cond_top:    
                 f_mat0[j, i] = f_mat0[j, i] + (self.cond-self.cond_top) / \
                     (self.cond + self.cond_top) * \
                         si.quad(self.f_mat0, a=z_js[i], b=z_js[i+1], \
                             args=(-z_js[j+1]), \
                                 epsabs=self.tol)[0]
                 f_mat1[j, i] = f_mat1[j, i] + (self.cond-self.cond_top) / \
                     (self.cond + self.cond_top) * \
                         si.quad(self.f_mat1, a=z_js[i], b=z_js[i+1], \
                             args=(-z_js[j+1], z_js[i]), epsabs=self.tol)[0]
                 f_mat2[j, i] = f_mat2[j, i] + (self.cond-self.cond_top) / \
                     (self.cond + self.cond_top) * \
                         si.quad(self.f_mat2, a=z_js[i], b=z_js[i+1], \
                             args=(-z_js[j+1], z_js[i]), epsabs=self.tol)[0]
                 f_mat3[j, i] = f_mat3[j, i] + (self.cond-self.cond_top) / \
                     (self.cond + self.cond_top) * \
                         si.quad(self.f_mat3, a=z_js[i], b=z_js[i+1], \
                             args=(-z_js[j+1], z_js[i]), epsabs=self.tol)[0]
     
     e_mat0, e_mat1, e_mat2, e_mat3 = self.calc_e_matrices()
     
     # Calculate the F-matrix
     self.f_matrix = pl.matrix(pl.zeros((el_len+2, el_len+2)))
     self.f_matrix[1:-1, :] = f_mat0*e_mat0 + f_mat1*e_mat1 + \
                             f_mat2*e_mat2 + f_mat3*e_mat3
     self.f_matrix[0, 0] = 1
     self.f_matrix[-1, -1] = 1
コード例 #9
0
ファイル: ss.py プロジェクト: syantek/sysid
    def __init__(self, t, x, y, u):

        self.t = pl.matrix(t)
        self.x = pl.matrix(x)
        self.y = pl.matrix(y)
        self.u = pl.matrix(u)

        assert self.t.shape[0] == 1
        assert self.x.shape[0] < self.x.shape[1]
        assert self.y.shape[0] < self.y.shape[1]
        assert self.u.shape[0] < self.u.shape[1]
コード例 #10
0
ファイル: subspace.py プロジェクト: syantek/sysid
def block_hankel(data, f):
    """
    Create a block hankel matrix.
    f : number of rows
    """
    data = pl.matrix(data)
    assert len(data.shape) == 2
    n = data.shape[1] - f
    return pl.matrix(pl.hstack([
        pl.vstack([data[:, i+j] for i in range(f)])
        for j in range(n)]))
コード例 #11
0
ファイル: LidarBase.py プロジェクト: jianxingdong/Velodyne-3
 def _bodyState2LidarState(self, bodyState):
     '''
     transform body 6-dim vector state to lidar matrix state
     return w_R_L(3*3 matrix), w_T_L(3*1 matrix)
     '''
     bodyState[3:]*=DEG2RAD;
     roll=bodyState[3];pitch=bodyState[4];yaw=bodyState[5];
     w_R_b=pl.matrix([[ cos(pitch)*cos(yaw),-cos(roll)*sin(yaw)+sin(roll)*sin(pitch)*cos(yaw), sin(roll)*sin(yaw)+cos(roll)*sin(pitch)*cos(yaw)],
                      [ cos(pitch)*sin(yaw), cos(roll)*cos(yaw)+sin(roll)*sin(pitch)*sin(yaw),-sin(roll)*cos(yaw)+cos(roll)*sin(pitch)*sin(yaw)],
                      [-sin(pitch),           sin(roll)*cos(pitch),                                  cos(roll)*cos(pitch)]])
     w_R_L = w_R_b * LidarFrame.b_R_L 
     w_T_b = pl.matrix(bodyState[:3]).T
     w_T_L = w_T_b + w_R_b * LidarFrame.b_T_L
     return w_R_L, w_T_L
コード例 #12
0
ファイル: ss.py プロジェクト: syantek/sysid
    def simulate(self, f_u, x0, tf):
        """
        Simulate the system.

        Parameters
        ----------
        f_u: The input function  f_u(t, x, i)
        x0: The initial state.
        tf: The final time.

        Return
        ------
        data : A StateSpaceDataArray object.

        """
        #pylint: disable=too-many-locals, no-member
        x0 = pl.matrix(x0)
        assert x0.shape[1] == 1
        t = 0
        x = x0
        dt = self.dt
        data = StateSpaceDataList([], [], [], [])
        i = 0
        n_x = self.A.shape[0]
        n_y = self.C.shape[0]
        assert pl.matrix(f_u(0, x0, 0)).shape[1] == 1
        assert pl.matrix(f_u(0, x0, 0)).shape[0] == n_y

        # take square root of noise cov to prepare for noise sim
        if pl.norm(self.Q) > 0:
            sqrtQ = scipy.linalg.sqrtm(self.Q)
        else:
            sqrtQ = self.Q

        if pl.norm(self.R) > 0:
            sqrtR = scipy.linalg.sqrtm(self.R)
        else:
            sqrtR = self.R

        # main simulation loop
        while t + dt < tf:
            u = f_u(t, x, i)
            v = sqrtR.dot(pl.randn(n_y, 1))
            y = self.measurement(x, u, v)
            data.append(t, x, y, u)
            w = sqrtQ.dot(pl.randn(n_x, 1))
            x = self.dynamics(x, u, w)
            t += dt
            i += 1
        return data.to_StateSpaceDataArray()
コード例 #13
0
ファイル: feasibility.py プロジェクト: issfangks/milo-lab
def find_mtdf(S, dG0_f, c_range=(1e-6, 1e-2), T=default_T, bounds=None, log_stream=None):
    """
        Find a distribution of concentration that will satisfy the 'relaxed' thermodynamic constraints.
        The 'relaxation' means that there is a slack variable 'B' where all dG_r are constrained to be < B.
        Note that B can also be negative, which will happen when the pathway is feasible.
        MTDF (Maximal Thermodynamic Driving Force) is defined as the minimal B, note that it is a function of the concentration bounds.
    """
    Nr, Nc = S.shape
    
    # compute right hand-side vector - r,
    # i.e. the deltaG0' of the reactions divided by -RT
    if (S.shape[1] != dG0_f.shape[0]):
        raise Exception("The S matrix has %d columns, while the dG0_f vector has %d" % (S.shape[1], dG0_f.shape[0]))
    
    cpl = create_cplex(S, dG0_f, log_stream)
    add_thermodynamic_constraints(cpl, dG0_f, c_range=c_range, bounds=bounds)

    # Define the MTDF variable and use it relax the thermodynamic constraints on each reaction
    cpl.variables.add(names=["B"], lb=[-1e6], ub=[1e6])
    for r in xrange(Nr):
        cpl.linear_constraints.set_coefficients("r%d" % r, "B", -1)

    # Set 'B' as the objective
    cpl.objective.set_linear([("B", 1)])
    
    #cpl.write("../res/test_MTDF.lp", "lp")
    cpl.solve()
    if (cpl.solution.get_status() != cplex.callbacks.SolveCallback.status.optimal):
        raise LinProgNoSolutionException("")

    dG_f = pylab.matrix(cpl.solution.get_values(["c%d" % c for c in xrange(Nc)])).T
    concentrations = pylab.exp((dG_f-dG0_f)/(R*T))
    MTDF = cpl.solution.get_values(["B"])[0]

    return dG_f, concentrations, MTDF
コード例 #14
0
ファイル: LidarBase.py プロジェクト: jianxingdong/Velodyne-3
 def _transformPoints(self, points, w_R_old, w_T_old, w_R_new, w_T_new):
     '''
     transform lidar points from old state to new state
     Input:
     new/old R/L are both Lidar state
     
     points are n*3-dim array
     return n*3-dim array
     '''
     
     #verify rotation matrix
     #print pl.norm(w_R_old[0],2), pl.norm(w_R_old[1],2), pl.norm(w_R_old[2],2)
     #print pl.norm(w_R_new[0],2), pl.norm(w_R_new[1],2), pl.norm(w_R_new[2],2)
     
     new_R_old = w_R_new.T * w_R_old
     new_T_old = w_R_new.T * (w_T_old - w_T_new)
     
     #pdb.set_trace()
     
     #old points first transform to body frame
     old_P = pl.matrix(points).T
     new_P = new_R_old * old_P + new_T_old
     
     #print new_P.T
     #pdb.set_trace()
     
     return pl.array(new_P.T)
コード例 #15
0
ファイル: test_subspace.py プロジェクト: jgoppert/sysid
    def test_subspace_det_algo1_siso(self):
        """
        Subspace deterministic algorithm (SISO).
        """
        ss1 = sysid.StateSpaceDiscreteLinear(
            A=0.9, B=0.5, C=1, D=0, Q=0.01, R=0.01, dt=0.1)

        pl.seed(1234)
        prbs1 = sysid.prbs(1000)
        def f_prbs(t, x, i):
            "input function"
            #pylint: disable=unused-argument, unused-variable
            return prbs1[i]

        tf = 10
        data = ss1.simulate(f_u=f_prbs, x0=pl.matrix(0), tf=tf)
        ss1_id = sysid.subspace_det_algo1(
            y=data.y, u=data.u,
            f=5, p=5, s_tol=1e-1, dt=ss1.dt)
        data_id = ss1_id.simulate(f_u=f_prbs, x0=0, tf=tf)
        nrms = sysid.subspace.nrms(data_id.y, data.y)
        self.assertGreater(nrms, 0.9)

        if ENABLE_PLOTTING:
            pl.plot(data_id.t.T, data_id.x.T, label='id')
            pl.plot(data.t.T, data.x.T, label='true')
            pl.legend()
            pl.grid()
コード例 #16
0
ファイル: IDE.py プロジェクト: mikedewar/BrainIDE
	def sigma_vectors(self,x,P):

		"""
		generates sigma vectors

		Arguments
		----------
		x : matrix
			state at time instant t
		P:  matrix
			state covariance matrix at time instant t

		Returns
		----------
		Chi : matrix
			matrix of sigma points
		"""
		State_covariance_cholesky=sp.linalg.cholesky(P).T
		State_covariance_cholesky_product=self.gamma_sigma_points*State_covariance_cholesky		
		chi_plus=[]
		chi_minus=[]
		for i in range(self.L):
			chi_plus.append(x+State_covariance_cholesky_product[:,i].reshape(self.L,1)) 
			chi_minus.append(x-State_covariance_cholesky_product[:,i].reshape(self.L,1)) 

		Chi=pb.hstack((x,pb.hstack((pb.hstack(chi_plus),pb.hstack(chi_minus))))) 
		return pb.matrix(Chi)
コード例 #17
0
 def __init__(self,
              min_dist,
              max_dist,
              fov,
              dist_per_que,
              goal,
              threshold=0.2):
     """
     initialize queue to store sensed obstacles 
     goal is given from initial bearing (angle) and distance
     away from the bat
     max dist is max sensing dist and min dist is min sensing dist 
     """
     self.goal = goal  #format [angle, distance]
     num_queue = int(max_dist / dist_per_que) * 2 + 1
     #Going to initialize bat in the middle of the grid
     self.num_queue = num_queue
     self.mindist = min_dist
     self.maxdist = max_dist
     self.dist_pq = dist_per_que
     self.obst_queue = pylab.matrix(np.zeros((num_queue, num_queue)))
     self.path = []
     self.fov = fov
     self.goal_index = None
     self.real_goal = False
     self.threshold = threshold
     self.bat_tile = [(num_queue - 1) / 2, (num_queue - 1) / 2]
     self.bat_pos = [0, 0]
     """
コード例 #18
0
    def _transformPoints(self, points, w_R_old, w_T_old, w_R_new, w_T_new):
        '''
        transform lidar points from old state to new state
        Input:
        new/old R/L are both Lidar state
        
        points are n*3-dim array
        return n*3-dim array
        '''

        #verify rotation matrix
        #print pl.norm(w_R_old[0],2), pl.norm(w_R_old[1],2), pl.norm(w_R_old[2],2)
        #print pl.norm(w_R_new[0],2), pl.norm(w_R_new[1],2), pl.norm(w_R_new[2],2)

        new_R_old = w_R_new.T * w_R_old
        new_T_old = w_R_new.T * (w_T_old - w_T_new)

        #pdb.set_trace()

        #old points first transform to body frame
        old_P = pl.matrix(points).T
        new_P = new_R_old * old_P + new_T_old

        #print new_P.T
        #pdb.set_trace()

        return pl.array(new_P.T)
コード例 #19
0
ファイル: feasibility.py プロジェクト: issfangks/milo-lab
def find_pCr(S, dG0_f, c_mid=1e-3, ratio=3.0, T=default_T, bounds=None, log_stream=None):
    """
        Compute the feasibility of a given set of reactions
    
        input: S = stoichiometric matrix (reactions x compounds)
               dG0_f = deltaG0'-formation values for all compounds (in kJ/mol) (1 x compounds)
               c_mid = the default concentration
               ratio = the ratio between the distance of the upper bound from c_mid and the lower bound from c_mid (in logarithmic scale)
        
        output: (concentrations, margin)
    """
    Nc = S.shape[1]
    cpl = make_pCr_problem(S, dG0_f, c_mid, ratio, T, bounds, log_stream)
    
    # Objective: minimize the pC variable.
    cpl.objective.set_sense(cpl.objective.sense.minimize)
    cpl.objective.set_linear([("pC", 1)])

    #cpl.write("../res/test_PCR.lp", "lp")
    cpl.solve()
    if cpl.solution.get_status() != cplex.callbacks.SolveCallback.status.optimal:
        raise LinProgNoSolutionException("")
    dG_f = pylab.matrix(cpl.solution.get_values(["c%d" % c for c in xrange(Nc)])).T
    concentrations = pylab.exp((dG_f-dG0_f)/(R*T))
    pCr = cpl.solution.get_values(["pC"])[0]

    return dG_f, concentrations, pCr
コード例 #20
0
ファイル: log_matrix.py プロジェクト: issfangks/milo-lab
def log_inv(X): # inverts a 3x3 matrix given by the logscale values
    if (X.shape[0] != X.shape[1]):
        raise Exception("X is not a square matrix and cannot be inverted")
    
    if (X.shape[0] == 1):
        return matrix((-X[0,0]))
    
    ldet = log_det(X)
    if (ldet == nan):
        raise Exception("The determinant of X is 0, cannot calculate the inverse")
     
    if (X.shape[0] == 2): # X is a 2x2 matrix
        I = (-log_det(X)) * ones((2,2))
        I[0,0] += X[1,1]
        I[0,1] += X[0,1] + complex(0, pi)
        I[1,0] += X[1,0] + complex(0, pi)
        I[1,1] += X[0,0]
        return I
    
    if (X.shape[0] == 3): # X is a 3x3 matrix
        I = (-log_det(X)) * ones((3,3))
        I[0,0] += log_subt_exp(X[1,1]+X[2,2], X[1,2]+X[2,1])
        I[0,1] += log_subt_exp(X[0,2]+X[2,1], X[0,1]+X[2,2])
        I[0,2] += log_subt_exp(X[0,1]+X[1,2], X[0,2]+X[1,1])
        I[1,0] += log_subt_exp(X[2,0]+X[1,2], X[1,0]+X[2,2])
        I[1,1] += log_subt_exp(X[0,0]+X[2,2], X[0,2]+X[2,0])
        I[1,2] += log_subt_exp(X[0,2]+X[1,0], X[0,0]+X[1,2])
        I[2,0] += log_subt_exp(X[1,0]+X[2,1], X[2,0]+X[1,1])
        I[2,1] += log_subt_exp(X[2,0]+X[0,1], X[0,0]+X[2,1])
        I[2,2] += log_subt_exp(X[0,0]+X[1,1], X[0,1]+X[1,0])
        return I
    
    raise Exception("log_inv is only implemented for matrices of size < 4")
コード例 #21
0
def find_pCr(S,
             dG0_f,
             c_mid=1e-3,
             ratio=3.0,
             T=default_T,
             bounds=None,
             log_stream=None):
    """
        Compute the feasibility of a given set of reactions
    
        input: S = stoichiometric matrix (reactions x compounds)
               dG0_f = deltaG0'-formation values for all compounds (in kJ/mol) (1 x compounds)
               c_mid = the default concentration
               ratio = the ratio between the distance of the upper bound from c_mid and the lower bound from c_mid (in logarithmic scale)
        
        output: (concentrations, margin)
    """
    Nc = S.shape[1]
    cpl = make_pCr_problem(S, dG0_f, c_mid, ratio, T, bounds, log_stream)

    # Objective: minimize the pC variable.
    cpl.objective.set_sense(cpl.objective.sense.minimize)
    cpl.objective.set_linear([("pC", 1)])

    #cpl.write("../res/test_PCR.lp", "lp")
    cpl.solve()
    if cpl.solution.get_status(
    ) != cplex.callbacks.SolveCallback.status.optimal:
        raise LinProgNoSolutionException("")
    dG_f = pylab.matrix(
        cpl.solution.get_values(["c%d" % c for c in xrange(Nc)])).T
    concentrations = pylab.exp((dG_f - dG0_f) / (R * T))
    pCr = cpl.solution.get_values(["pC"])[0]

    return dG_f, concentrations, pCr
コード例 #22
0
 def _phase_map(self):
     self.dphi = (2*P.pi * self.nhop * P.arange(self.nfft/2+1)) / self.nfft
     A = P.diff(P.angle(self.STFT),1) # Complete Phase Map
     U = P.c_[P.angle(self.STFT[:,0]), A - P.matrix(self.dphi).T ]
     U = U - P.np.round(U/(2*P.pi))*2*P.pi
     self.dPhi = U
     return U
コード例 #23
0
def log_inv(X):  # inverts a 3x3 matrix given by the logscale values
    if (X.shape[0] != X.shape[1]):
        raise Exception("X is not a square matrix and cannot be inverted")

    if (X.shape[0] == 1):
        return matrix((-X[0, 0]))

    ldet = log_det(X)
    if (ldet == nan):
        raise Exception(
            "The determinant of X is 0, cannot calculate the inverse")

    if (X.shape[0] == 2):  # X is a 2x2 matrix
        I = (-log_det(X)) * ones((2, 2))
        I[0, 0] += X[1, 1]
        I[0, 1] += X[0, 1] + complex(0, pi)
        I[1, 0] += X[1, 0] + complex(0, pi)
        I[1, 1] += X[0, 0]
        return I

    if (X.shape[0] == 3):  # X is a 3x3 matrix
        I = (-log_det(X)) * ones((3, 3))
        I[0, 0] += log_subt_exp(X[1, 1] + X[2, 2], X[1, 2] + X[2, 1])
        I[0, 1] += log_subt_exp(X[0, 2] + X[2, 1], X[0, 1] + X[2, 2])
        I[0, 2] += log_subt_exp(X[0, 1] + X[1, 2], X[0, 2] + X[1, 1])
        I[1, 0] += log_subt_exp(X[2, 0] + X[1, 2], X[1, 0] + X[2, 2])
        I[1, 1] += log_subt_exp(X[0, 0] + X[2, 2], X[0, 2] + X[2, 0])
        I[1, 2] += log_subt_exp(X[0, 2] + X[1, 0], X[0, 0] + X[1, 2])
        I[2, 0] += log_subt_exp(X[1, 0] + X[2, 1], X[2, 0] + X[1, 1])
        I[2, 1] += log_subt_exp(X[2, 0] + X[0, 1], X[0, 0] + X[2, 1])
        I[2, 2] += log_subt_exp(X[0, 0] + X[1, 1], X[0, 1] + X[1, 0])
        return I

    raise Exception("log_inv is only implemented for matrices of size < 4")
コード例 #24
0
ファイル: LDS.py プロジェクト: mikedewar/pyLDS
	def __init__(self,A,B,C,Sw,Sv,x0,Pi0):
		
		ny, nx = C.shape
		nu = B.shape[1]	
		
		if type(A) is list:
			for Ai in A:
				assert Ai.shape == (nx, nx)
		else:
			assert A.shape == (nx, nx), A.shape
		assert B.shape == (nx, nu), B.shape
		assert Sw.shape == (nx, nx), Sw.shape
		assert Sv.shape == (ny, ny), Sv.shape
		assert x0.shape == (nx,1), x0.shape
		
		self.A = A
		self.B = B
		self.C = C
		self.Sw = Sw
		self.Sv = Sv
		self.ny = ny
		self.nx = nx
		self.nu = nu
		self.x0 = x0
		self.Pi0 = Pi0
		
		# initial condition
		# TODO - not sure about this as a prior covariance...
		self.P0 = 40000 * pb.matrix(pb.ones((self.nx,self.nx)))
		self.log = logging.getLogger('LDS')
		# check for stability
		self.is_stable()
		self.log.info('initialised state space model')
コード例 #25
0
ファイル: NF.py プロジェクト: mikedewar/BrainIDE
    def simulate(self, T):

        """Simulates the full neural field model

		Arguments
		----------

		T: ndarray
				simulation time instants
		Returns
		----------
		V: list of matrix
			each matrix is the neural field at a time instant

		Y: list of matrix
			each matrix is the observation vector corrupted with noise at a time instant
		"""

        Y = []
        V = []

        spatial_location_num = (len(self.field_space)) ** 2
        sim_field_space_len = len(self.field_space)

        # initial field
        v0 = self.Sigma_e_c * pb.matrix(np.random.randn(spatial_location_num, 1))
        v_membrane = pb.reshape(v0, (sim_field_space_len, sim_field_space_len))
        firing_rate = self.act_fun.fmax / (1.0 + pb.exp(self.act_fun.varsigma * (self.act_fun.v0 - v_membrane)))

        for t in T[1:]:

            v = self.Sigma_varepsilon_c * pb.matrix(np.random.randn(len(self.obs_locns), 1))
            w = pb.reshape(
                self.Sigma_e_c * pb.matrix(np.random.randn(spatial_location_num, 1)),
                (sim_field_space_len, sim_field_space_len),
            )

            print "simulation at time", t
            g = signal.fftconvolve(self.K, firing_rate, mode="same")
            g *= self.spacestep ** 2
            v_membrane = self.Ts * pb.matrix(g) + self.xi * v_membrane + w
            firing_rate = self.act_fun.fmax / (1.0 + pb.exp(self.act_fun.varsigma * (self.act_fun.v0 - v_membrane)))
            # Observation
            Y.append((self.spacestep ** 2) * (self.C * pb.reshape(v_membrane, (sim_field_space_len ** 2, 1))) + v)
            V.append(v_membrane)

        return V, Y
コード例 #26
0
ファイル: show.py プロジェクト: TheCharlatan/PHY125
 def Sun(self, year):
     """ Returns a row vector for the position of the sun relative to the surface of the earth
     Parameters
     ----------
     year: float
           Angle of the earth relative ot the sun depending on its rotation around the sun
     """
     return matrix([[1,0,0]]) * self.Rot_z(year)
コード例 #27
0
def load_data(directory, file_):
    # load the data matrix from the data file

    data = loadtxt(directory + "data/" + file_ + ".txt", unpack=True)
    if type(data[0]) is float64:  # check if the first column is a column
        data = array(transpose(matrix(data)))

    return data
コード例 #28
0
 def WriteReactionsToHtml(self, S, rids, fluxes, cids, show_cids=True):
     self.thermo.pH = 7
     dG0_r = self.thermo.GetTransfromedReactionEnergies(S, cids)
     
     self.html_writer.write("<li>Reactions:</br><ul>\n")
     
     for r in range(S.shape[0]):
         self.html_writer.write('<li><a href=' + self.kegg.rid2link(rids[r]) + '>%s ' % rids[r] + '</a>')
         self.html_writer.write('[x%g, &Delta;G<sub>r</sub>&deg; = %.1f] : ' % (fluxes[r], dG0_r[r, 0]))
         self.html_writer.write(self.kegg.vector_to_hypertext(S[r, :].flat, cids, show_cids=show_cids))
         self.html_writer.write('</li>\n')
     
     v_total = pylab.dot(pylab.matrix(fluxes), S).flat
     dG0_total = pylab.dot(pylab.matrix(fluxes), dG0_r)[0,0]
     self.html_writer.write('<li><b>Total </b>')
     self.html_writer.write('[&Delta;G<sub>r</sub>&deg; = %.1f kJ/mol] : \n' % dG0_total)
     self.html_writer.write(self.kegg.vector_to_hypertext(v_total, cids, show_cids=show_cids))
     self.html_writer.write("</li></ul></li>\n")
コード例 #29
0
ファイル: icsd.py プロジェクト: Junji110/iCSD
    def calc_e_matrices(self):
        '''Calculate the E-matrices used by cubic spline iCSD method'''
        el_len = self.coord_electrode.size
        ## expanding electrode grid
        z_js = pl.zeros(el_len+2)
        z_js[1:-1] = self.coord_electrode
        z_js[-1] = self.coord_electrode[-1] + \
            pl.diff(self.coord_electrode).mean()
        
        ## Define transformation matrices
        c_mat3 = pl.matrix(pl.zeros((el_len+1, el_len+1)))
        
        for i in xrange(el_len+1):
            for j in xrange(el_len+1):
                if i == j:
                    c_mat3[i, j] = 1./pl.diff(z_js)[i]

        # Get K-matrix
        k_matrix = self.calc_k_matrix()
        
        # Define matrixes for C to A transformation:
        # identity matrix except that it cuts off last element:
        tja = pl.matrix(pl.zeros((el_len+1, el_len+2)))
        # converting k_j to k_j+1 and cutting off last element:
        tjp1a = pl.matrix(pl.zeros((el_len+1, el_len+2))) 

        # C to A
        for i in xrange(el_len+1):
            for j in xrange(el_len+2):
                if i == j-1:
                    tjp1a[i, j] = 1
                elif i == j:
                    tja[i, j] = 1
        
        # Define spline coeffiscients
        e_mat0 = tja    
        e_mat1 = tja*k_matrix
        e_mat2 = 3 * c_mat3**2 * (tjp1a-tja) - c_mat3 * \
                (tjp1a + 2 * tja) * k_matrix
        e_mat3 = 2 * c_mat3**3 * (tja-tjp1a) + c_mat3**2 * \
                (tjp1a + tja) * k_matrix
        
        return e_mat0, e_mat1, e_mat2, e_mat3
コード例 #30
0
ファイル: show.py プロジェクト: TheCharlatan/PHY125
    def Rot_y(self,y):
        """ Returns rotation matrix in y direction

        Parameters
        ----------
        y: float
           Angle to rotate the matrix with
        """
        return matrix([[cos(y), 0, -sin(y)],
                       [     0, 1,       0],
                       [sin(y), 0,  cos(y)]])
コード例 #31
0
ファイル: show.py プロジェクト: TheCharlatan/PHY125
    def Rot_x(self,x):
        """ Returns rotation matrix in x direction

        Parameters
        ----------
        x: float
           Angle to rotate the matrix with
        """
        return matrix([[1,      0,      0],
                       [0, cos(x), sin(x)],
                       [0,-sin(x), cos(x)]])
コード例 #32
0
ファイル: show.py プロジェクト: TheCharlatan/PHY125
    def Rot_z(self,z):
        """ Returns rotation matrix in z direction

        Parameters
        ----------
        z: float
           Angle to rotate the matrix with
        """
        return matrix([[ cos(z), sin(z), 0],
                       [-sin(z), cos(z), 0],
                       [      0,      0, 1]])
コード例 #33
0
    def main(self):
        sums = pylab.matrix(pylab.zeros((self.M + 1, self.M + 1)))
        for n in range(len(self.xlist)):
            sums += self.phi(self.xlist[n]) * self.phi(self.xlist[n]).transpose()
        I = pylab.matrix(numpy.identity(self.M + 1))
        S_inv = self.ALPHA * I + self.BETA * sums
        S = S_inv.getI()

        xs = numpy.linspace(min(self.xlist), max(self.xlist), 500)
        means = []
        uppers = []
        lowers = []
        for x in xs:
            m = self.mean(x, S)[0, 0]
            s = numpy.sqrt(self.variance(x, S)[0, 0])
            u = m + s
            l = m - s
            means.append(m)
            uppers.append(u)
            lowers.append(l)
        return([xs, means, uppers, lowers])
コード例 #34
0
    def CalculateRates(self, times, levels):
        N = len(levels)
        t_mat = pylab.matrix(times).T

        # normalize the cell_count data by its minimum
        count_matrix = pylab.matrix(levels).T
        norm_counts = count_matrix - min(levels)
        c_mat = pylab.matrix(norm_counts)
        if c_mat[-1, 0] == 0:
            ge_zero = c_mat[pylab.find(c_mat > 0)]
            if ge_zero.any():
                c_mat[-1, 0] = min(ge_zero)

        for i in pylab.arange(N - 1, 0, -1):
            if c_mat[i - 1, 0] <= 0:
                c_mat[i - 1, 0] = c_mat[i, 0]

        c_mat = pylab.log(c_mat)

        res_mat = pylab.zeros(
            (N, 5))  # columns are: slope, offset, error, avg_value, max_value
        for i in xrange(N - self.window_size):
            i_range = range(i, i + self.window_size)
            x = pylab.hstack(
                [t_mat[i_range, 0],
                 pylab.ones((len(i_range), 1))])
            y = c_mat[i_range, 0]

            # Measurements in window must all be above the min.
            if min(pylab.exp(y)) < self.minimum_level:
                continue

            (a, residues) = pylab.lstsq(x, y)[0:2]
            res_mat[i, 0] = a[0]
            res_mat[i, 1] = a[1]
            res_mat[i, 2] = residues
            res_mat[i, 3] = pylab.mean(count_matrix[i_range, 0])
            res_mat[i, 4] = max(pylab.exp(y))

        return res_mat
コード例 #35
0
ファイル: IDE.py プロジェクト: mikedewar/BrainIDE
	def simulate(self,T):

		"""Simulates the nonlinear state space IDE

		Arguments
		----------

		T: ndarray
				simulation time instants
		Returns
		----------
		X: list of matrix
			each matrix is the state vector at a time instant

		Y: list of matrix
			each matrix is the observation vector corrupted with noise at a time instant
		"""
		Y = []		
		X = []		
		x=self.x0
		firing_rate_temp=x.T*self.Phi_values
 		firing_rate=pb.array(self.act_fun.fmax/(1.+pb.exp(self.act_fun.varsigma*(self.act_fun.v0-firing_rate_temp)))).T		

		print "iterating"
		for t in T[1:]:
			w = self.Sigma_e_c*pb.matrix(np.random.randn(self.nx,1))
			v = self.Sigma_varepsilon_c*pb.matrix(np.random.randn(len(self.obs_locns),1))
			print "simulation at time",t
			Gamma_inv_Psi_conv_Phi=pb.array(self.Gamma_inv_Psi_conv_Phi)
			g=pb.matrix(pb.dot(Gamma_inv_Psi_conv_Phi,firing_rate))
			g *=(self.spacestep**2)
			x=self.Ts*g+self.xi*x+w

			X.append(x)
			Y.append(self.C*x+v)
			firing_rate_temp=x.T*self.Phi_values
			firing_rate=pb.array(self.act_fun.fmax/(1.+pb.exp(self.act_fun.varsigma*(self.act_fun.v0-firing_rate_temp)))).T		

		return X,Y
コード例 #36
0
ファイル: growth.py プロジェクト: issfangks/milo-lab
    def CalculateGrowthInternal(self, times, levels):
        res_mat = self.CalculateRates(times, levels)
        max_i = self.FindMaximumGrowthRate(res_mat)        
        
        t_mat = pylab.matrix(times).T
        count_matrix = pylab.matrix(levels).T
        norm_counts = count_matrix - min(levels)

        abs_res_mat = pylab.array(res_mat)
        abs_res_mat[:,0] = pylab.absolute(res_mat[:,0])
        order = abs_res_mat[:,0].argsort(axis=0)
        stationary_indices = filter(lambda x: x >= max_i, order)
        stationary_indices = pylab.array(filter(lambda x: res_mat[x,3] > 0,
                                                stationary_indices))
        
        stationary_level = 0.0
        if stationary_indices.any():
            stationary_level = res_mat[stationary_indices[0], 3]
        
        
        pylab.hold(True)
        pylab.plot(times, norm_counts)
        pylab.plot(times, res_mat[:,0])
        pylab.plot([0, times.max()], [self.minimum_level, self.minimum_level], 'r--')
        pylab.plot([0, times.max()], [self.maximum_level, self.maximum_level], 'r--')
        i_range = range(max_i, max_i+self.window_size)
        
        x = pylab.hstack([t_mat[i_range, 0], pylab.ones((len(i_range), 1))])
        y = x * pylab.matrix(res_mat[max_i, 0:2]).T
        pylab.plot(x[:,0], pylab.exp(y), 'k:', linewidth=4)
                
        #pylab.plot([0, max(times)], [stationary_level, stationary_level], 'k-')
        
        pylab.yscale('log')
        pylab.legend(['OD', 'growth rate', 'threshold', 'fit'])
        #, 'stationary'])
        
        
        return res_mat[max_i, 0], stationary_level
コード例 #37
0
    def CalculateGrowthInternal(self, times, levels):
        res_mat = self.CalculateRates(times, levels)
        max_i = self.FindMaximumGrowthRate(res_mat)

        t_mat = pylab.matrix(times).T
        count_matrix = pylab.matrix(levels).T
        norm_counts = count_matrix - min(levels)

        abs_res_mat = pylab.array(res_mat)
        abs_res_mat[:, 0] = pylab.absolute(res_mat[:, 0])
        order = abs_res_mat[:, 0].argsort(axis=0)
        stationary_indices = filter(lambda x: x >= max_i, order)
        stationary_indices = pylab.array(
            filter(lambda x: res_mat[x, 3] > 0, stationary_indices))

        stationary_level = 0.0
        if stationary_indices.any():
            stationary_level = res_mat[stationary_indices[0], 3]

        pylab.hold(True)
        pylab.plot(times, norm_counts)
        pylab.plot(times, res_mat[:, 0])
        pylab.plot([0, times.max()], [self.minimum_level, self.minimum_level],
                   'r--')
        pylab.plot([0, times.max()], [self.maximum_level, self.maximum_level],
                   'r--')
        i_range = range(max_i, max_i + self.window_size)

        x = pylab.hstack([t_mat[i_range, 0], pylab.ones((len(i_range), 1))])
        y = x * pylab.matrix(res_mat[max_i, 0:2]).T
        pylab.plot(x[:, 0], pylab.exp(y), 'k:', linewidth=4)

        #pylab.plot([0, max(times)], [stationary_level, stationary_level], 'k-')

        pylab.yscale('log')
        pylab.legend(['OD', 'growth rate', 'threshold', 'fit'])
        #, 'stationary'])

        return res_mat[max_i, 0], stationary_level
コード例 #38
0
 def linearize(self, x0=None, u0=None):
     ss = self.linearize_symbolic()
     ss_eval = []
     ss_subs = {}
     ss_subs.update(self.p0)
     ss_subs.update(self.c0)
     if x0 is None:
         x0 = self.x.subs(self.x0)[:]
     if u0 is None:
         u0 = self.x.subs(self.u0)[:]
     for i in range(len(ss)):
         ss_eval += [pl.matrix(ss[i].subs(ss_subs)).astype(float)]
     return ss_eval
コード例 #39
0
ファイル: test_LDS.py プロジェクト: DaomingLyu/pyLDS
def setup():
    A = pb.matrix([[0.8, -0.4], [1, 0]])
    B = pb.matrix([[1, 0], [0, 1]])
    C = pb.matrix([[1, 0], [0, 1], [1, 1]])
    Q = 2.3 * pb.matrix(pb.eye(2))
    R = 0.2 * pb.matrix(pb.eye(3))
    x0 = pb.matrix([[1], [1]])
    return LDS.LDS(A, B, C, Q, R, x0)
コード例 #40
0
ファイル: test_LDS.py プロジェクト: mikedewar/pyLDS
def setup():
    A = pb.matrix([[0.8, -0.4], [1, 0]])
    B = pb.matrix([[1, 0], [0, 1]])
    C = pb.matrix([[1, 0], [0, 1], [1, 1]])
    Q = 2.3 * pb.matrix(pb.eye(2))
    R = 0.2 * pb.matrix(pb.eye(3))
    x0 = pb.matrix([[1], [1]])
    return LDS.LDS(A, B, C, Q, R, x0)
コード例 #41
0
def uncertainty_comparison():
    """
        Plots the uncertainty in the dG of each reaction in KEGG, against the RMSE of the predictions (compared to the NIST measurements).
        The x-value is a function of the number of substrates and number of products of each reaction (excluding H2O and H+).
        The y-value of each dot is calculated by the RMSE of the observation vs. estimation across all measurements of the same reaction.
    """
    limits = [(-5, -3), (-5, -2), (-6, -2)] # in log10 scale
    pylab.rcParams['text.usetex'] = True
    pylab.rcParams['legend.fontsize'] = 8
    pylab.rcParams['font.family'] = 'sans-serif'
    pylab.rcParams['font.size'] = 8
    pylab.rcParams['lines.linewidth'] = 0.4
    pylab.rcParams['lines.markersize'] = 3

    pylab.figure(figsize=(12,3.5))
    for i in range(len(limits)):
        (min_C, max_C) = limits[i]
        
        rid_to_nist_rowids = map_rid_to_nist_rowids()
        data_mat = []
        for (rid, rowids) in rid_to_nist_rowids.iteritems():
            reaction = gc.kegg.rid2reaction(rid)
            try:
                error_mat = []
                for rowid in rowids:
                    row = nist.data[rowid]
                    #evaluation = row[3] # A, B, C, D
                    dG0_est = [reaction.PredictReactionEnergy(predictor, pH=row.pH, I=row.I, T=row.T)
                               for predictor in [A, H]]
                    error_mat.append([(row.dG0_r - x) for x in dG0_est])
                error_mat = pylab.array(error_mat)
                rmse = pylab.sqrt(pylab.mean(error_mat**2, 0))
                (ddG_min, ddG_max) = calculate_uncertainty(reaction, min_C=10**min_C, max_C=10**max_C, T=300)
                data_mat.append([ddG_max - ddG_min, rmse[0], rmse[1], rmse[2]])
            except MissingCompoundFormationEnergy:
                continue
        
        data_mat = pylab.matrix(data_mat)
    
        pylab.subplot(1,len(limits),i+1)
        pylab.hold(True)
        pylab.plot(data_mat[:,0], data_mat[:,1:], '.')
        pylab.plot([0, 200], [0, 200], '--k')
        pylab.axis('scaled')
        pylab.xlabel(r"uncertainty in $\Delta_r G$ due to concentrations [kJ/mol]")
        if (i == 0):
            pylab.ylabel(r"RMSE of $\Delta_r G^\circ$ estimation [kJ/mol]")
        pylab.title(r"$10^{%g}M$ $<$ [c] $<$ $10^{%g}M$" % (min_C, max_C))
        pylab.legend(['Alberty', 'Hatzimanikatis', 'Rugged'], loc="upper left")

    pylab.savefig('../res/compare_uncertainty.pdf', format='pdf')
コード例 #42
0
def get_projection_transformed_point(src_x_values, src_y_values, dest_width,
                                     dest_height, target_point_x,
                                     target_point_y):
    sx1, sy1 = src_x_values[0], src_y_values[0]  # tl
    sx2, sy2 = src_x_values[1], src_y_values[1]  # bl
    sx3, sy3 = src_x_values[2], src_y_values[2]  # br
    sx4, sy4 = src_x_values[3], src_y_values[3]  # tr

    source_points_123 = pl.matrix([[sx1, sx2, sx3],
                                   [sy1, sy2, sy3],
                                   [1, 1, 1]])

    source_point_4 = [[sx4], [sy4], [1]]

    scale_to_source = pl.solve(source_points_123, source_point_4)

    l, m, t = [float(x) for x in scale_to_source]

    unit_to_source = pl.matrix([[l * sx1, m * sx2, t * sx3],
                                [l * sy1, m * sy2, t * sy3],
                                [l, m, t]])

    dx1, dy1 = 0, 0
    dx2, dy2 = 0, dest_height
    dx3, dy3 = dest_width, dest_height
    dx4, dy4 = dest_width, 0

    dest_points_123 = pl.matrix([[dx1, dx2, dx3],
                                 [dy1, dy2, dy3],
                                 [1, 1, 1]])

    dest_point_4 = pl.matrix([[dx4],
                              [dy4],
                              [1]])

    scale_to_dest = pl.solve(dest_points_123, dest_point_4)

    l, m, t = [float(x) for x in scale_to_dest]

    unit_to_dest = pl.matrix([[l * dx1, m * dx2, t * dx3],
                              [l * dy1, m * dy2, t * dy3],
                              [l, m, t]])

    source_to_unit = pl.inv(unit_to_source)

    source_to_dest = unit_to_dest @ source_to_unit

    x, y, z = [float(w) for w in (source_to_dest @ pl.matrix([
        [target_point_x],
        [target_point_y],
        [1]]))]

    x /= z
    y /= z

    y = target_point_y * 2 - y

    return x, y
コード例 #43
0
ファイル: test_LDS.py プロジェクト: DaomingLyu/pyLDS
def setup_nonstationary():
    T = 100
    A_ns = [pb.matrix([[0.8, -0.4], [1, 0]]) for t in range(T)]
    B = pb.matrix([[1, 0], [0, 1]])
    C = pb.matrix([[1, 0], [0, 1], [1, 1]])
    Q = 2.3 * pb.matrix(pb.eye(2))
    R = 0.2 * pb.matrix(pb.eye(3))
    x0 = pb.matrix([[1], [1]])
    return T, LDS.LDS(A_ns, B, C, Q, R, x0)
コード例 #44
0
ファイル: test_LDS.py プロジェクト: mikedewar/pyLDS
def setup_nonstationary():
    T = 100
    A_ns = [pb.matrix([[0.8, -0.4], [1, 0]]) for t in range(T)]
    B = pb.matrix([[1, 0], [0, 1]])
    C = pb.matrix([[1, 0], [0, 1], [1, 1]])
    Q = 2.3 * pb.matrix(pb.eye(2))
    R = 0.2 * pb.matrix(pb.eye(3))
    x0 = pb.matrix([[1], [1]])
    return T, LDS.LDS(A_ns, B, C, Q, R, x0)
コード例 #45
0
ファイル: ss.py プロジェクト: syantek/sysid
    def measurement(self, x, u, v):
        """
        Measurement.
        y(k) = C x(k) + D u(k) + v(k)

        E(vv^T) = R

        Parameters
        ----------
        x : The current state.
        u : The current input.
        v : The current measurement noise.

        Return
        ------
        y(k) : The current measurement
        """
        x = pl.matrix(x)
        u = pl.matrix(u)
        v = pl.matrix(v)
        assert x.shape[1] == 1
        assert u.shape[1] == 1
        assert v.shape[1] == 1
        return self.C*x + self.D*u + v
コード例 #46
0
ファイル: matrices.py プロジェクト: mGolos/OldCodeSamples
def adjointVectors(ksi):
    ''' Return the adjoint vectors of ksi where ksi is composed of m vector of size > 1
    '''
    from pylab import matrix, eye
    A = matrix(dot(ksi, ksi.T))
    A = A + 1e-1 * eye(A.shape[0])
    try:
        #A = matrix( dot(ksi, ksi.T) ).I
        A = A.I
    except:
        A = zeros(dot(ksi, ksi.T).shape)
        print(
            'Non inversible dot(ksi, ksi.T) building adjoint vectors where ksi are the patterns'
        )
    return dot(A, ksi)
コード例 #47
0
def get_heuristic(grid, start, end, threshold):
    """
    heuristic for A* search. Basically the matrix that stores the number of steps away 
    from the destination for each tile 
    """
    #generate heuristic
    grid_shape = grid.shape
    num_row = grid_shape[0]
    num_col = grid_shape[1]
    ref = pylab.matrix(grid)
    heuristic = pylab.matrix([[99 for col in range(num_col)]
                              for row in range(num_row)])
    notdone = True
    step = 1
    current = [end[:]]
    ref[end[0], end[1]] = 1
    heuristic[end[0], end[1]] = 0
    while notdone:
        if start in current:
            notdone = False
        else:
            new = []
            for tile in current:
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        ns = tile
                        a = ns[0] + i
                        b = ns[1] + j
                        if a >= 0 and a < num_row and b >= 0 and b < num_col:
                            if ref[a, b] < threshold:
                                heuristic[a, b] = step
                                ref[a, b] = 1
                                new.append([a, b])
            current = new
            step += 1
    return heuristic
コード例 #48
0
def take_matrix(matrix, list1, list2 = []):
    """
    taking a matrix from a bigger matrix 
    for example: a = Matrix([[1,2,3],[4,5,6],[7,8,9]])
    b = take_matrix(a, [0,2],[0,1]) 
    b = Matrix([[1,2],[7,8]])
    """
    matrix_dim = matrix.shape
    if list2 == []:
        list2 = list1
    if len(list1) > matrix_dim[0] or len(list2) > matrix_dim[1]:
        raise ValueError, "list invalid in take()"

    new = np.zeros((len(list1),len(list2)))
    for i in range(len(list1)):
        for j in range(len(list2)):
            new[i,j] = matrix[list1[i],list2[j]]
    return pylab.matrix(new)
コード例 #49
0
def find_mtdf(S,
              dG0_f,
              c_range=(1e-6, 1e-2),
              T=default_T,
              bounds=None,
              log_stream=None):
    """
        Find a distribution of concentration that will satisfy the 'relaxed' thermodynamic constraints.
        The 'relaxation' means that there is a slack variable 'B' where all dG_r are constrained to be < B.
        Note that B can also be negative, which will happen when the pathway is feasible.
        MTDF (Maximal Thermodynamic Driving Force) is defined as the minimal B, note that it is a function of the concentration bounds.
    """
    Nr, Nc = S.shape

    # compute right hand-side vector - r,
    # i.e. the deltaG0' of the reactions divided by -RT
    if (S.shape[1] != dG0_f.shape[0]):
        raise Exception(
            "The S matrix has %d columns, while the dG0_f vector has %d" %
            (S.shape[1], dG0_f.shape[0]))

    cpl = create_cplex(S, dG0_f, log_stream)
    add_thermodynamic_constraints(cpl, dG0_f, c_range=c_range, bounds=bounds)

    # Define the MTDF variable and use it relax the thermodynamic constraints on each reaction
    cpl.variables.add(names=["B"], lb=[-1e6], ub=[1e6])
    for r in xrange(Nr):
        cpl.linear_constraints.set_coefficients("r%d" % r, "B", -1)

    # Set 'B' as the objective
    cpl.objective.set_linear([("B", 1)])

    #cpl.write("../res/test_MTDF.lp", "lp")
    cpl.solve()
    if (cpl.solution.get_status() !=
            cplex.callbacks.SolveCallback.status.optimal):
        raise LinProgNoSolutionException("")

    dG_f = pylab.matrix(
        cpl.solution.get_values(["c%d" % c for c in xrange(Nc)])).T
    concentrations = pylab.exp((dG_f - dG0_f) / (R * T))
    MTDF = cpl.solution.get_values(["B"])[0]

    return dG_f, concentrations, MTDF
コード例 #50
0
    def motion_update(self, distance, direction, motion_certainty=0.98):
        """
        update the obstacle queue with motion using simple vectors
        Note the Bayesian Inference: 
        P(L=l|X=x, Z=z) = P(Z=z|X=x, L=l)*P(X=x|L=l)*P(L=l)
        where L is landmark position, X is bat position, and Z is measurement 
        motion update is just the P(X=x|L=l)*P(L=l)
        Note that P(L=l) is just the prior probability 
        """
        grid = pylab.matrix(self.obst_queue)
        grid_shape = grid.shape
        rad = math.radians(direction)
        bat_delta_x = math.cos(rad) * distance
        bat_delta_y = math.sin(rad) * distance
        self.bat_pos[0] += bat_delta_x
        self.bat_pos[1] += bat_delta_y
        self.bat_tile[0] = int(round(
            self.bat_pos[0] / self.dist_pq)) + (self.num_queue - 1) / 2
        self.bat_tile[1] = int(round(
            self.bat_pos[1] / self.dist_pq)) + (self.num_queue - 1) / 2
        num_row = grid_shape[0]
        num_col = grid_shape[1]
        spilldex = [[1, 0], [1, 1], [0, 1],
                    [-1, 1]]  #which direction the "spill" is
        dex = int((direction - 22.5) /
                  45) % 4  #kind of crude way to do motion uncertainty
        spill_dir = spilldex[dex]
        spill_prob = (1 - motion_certainty) / 2.
        filled_tiles = []
        for row in range(num_row):
            for col in range(num_col):
                if [row, col] not in filled_tiles:
                    val = self.obst_queue[row, col]
                    grid[row, col] = val * motion_certainty
                    filled_tiles.append([row, col])
                    for i in range(1):
                        try:
                            grid[row + spill_dir[0] * (-1)**i, col +
                                 spill_dir[1] * (-1)**i] += spill_prob * val
                        except IndexError:  #avoid out of range problems
                            pass

        return grid
コード例 #51
0
    def test_subspace_det_algo1_mimo(self):
        """
        Subspace deterministic algorithm (MIMO).
        """
        ss2 = sysid.StateSpaceDiscreteLinear(A=pl.matrix([[0, 0.1, 0.2],
                                                          [0.2, 0.3, 0.4],
                                                          [0.4, 0.3, 0.2]]),
                                             B=pl.matrix([[1, 0], [0, 1],
                                                          [0, -1]]),
                                             C=pl.matrix([[1, 0, 0], [0, 1,
                                                                      0]]),
                                             D=pl.matrix([[0, 0], [0, 0]]),
                                             Q=pl.diag([0.01, 0.01, 0.01]),
                                             R=pl.diag([0.01, 0.01]),
                                             dt=0.1)
        pl.seed(1234)
        prbs1 = sysid.prbs(1000)
        prbs2 = sysid.prbs(1000)

        def f_prbs_2d(t, x, i):
            "input function"
            #pylint: disable=unused-argument
            i = i % 1000
            return 2 * pl.matrix([prbs1[i] - 0.5, prbs2[i] - 0.5]).T

        tf = 8
        data = ss2.simulate(f_u=f_prbs_2d, x0=pl.matrix([0, 0, 0]).T, tf=tf)
        ss2_id = sysid.subspace_det_algo1(y=data.y,
                                          u=data.u,
                                          f=5,
                                          p=5,
                                          s_tol=0.1,
                                          dt=ss2.dt)
        data_id = ss2_id.simulate(f_u=f_prbs_2d,
                                  x0=pl.matrix(pl.zeros(ss2_id.A.shape[0])).T,
                                  tf=tf)
        nrms = sysid.nrms(data_id.y, data.y)
        self.assertGreater(nrms, 0.9)

        if ENABLE_PLOTTING:
            for i in range(2):
                pl.figure()
                pl.plot(data_id.t.T,
                        data_id.y[i, :].T,
                        label='$y_{:d}$ true'.format(i))
                pl.plot(data.t.T,
                        data.y[i, :].T,
                        label='$y_{:d}$ id'.format(i))
                pl.legend()
                pl.grid()
コード例 #52
0
def expand_matrix(matrix, dimx, dimy, list1, list2 = []):
    """
    expanding an old matrix to a new matrix 
    for example: a = Matrix([[1,2],[3,4]])
    b = expand_matrix(a, 3, 3, [0,2],[0,1]) 
    b = Matrix([[1,2,0],[0,0,0],[3,4,0]])
    the two lists tells you where to put the original 
    """
    matrix_dim = matrix.shape
    if list2 == []:
        list2 = list1
    if len(list1) > matrix_dim[0] or len(list2) > matrix_dim[1]:
        raise ValueError, "list invalid in expand()"

    new = np.zeros((dimx, dimy))
    
    for i in range(len(list1)):
        for j in range(len(list2)):
            new[list1[i], list2[j]] = matrix[i,j]
    return pylab.matrix(new)