当前位置: 首页>>代码示例>>Python>>正文


Python scipy.shape函数代码示例

本文整理汇总了Python中scipy.shape函数的典型用法代码示例。如果您正苦于以下问题:Python shape函数的具体用法?Python shape怎么用?Python shape使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了shape函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _generate_pores

    def _generate_pores(self):
        r"""
        Generate the pores (coordinates, numbering and types)
        """
        self._logger.info("generate_pores: Create specified number of pores")

        #Find non-zero elements in image
        template = self._template
        Np = np.sum(template > 0)
        #Add pores to data and ifo
        pind = np.arange(0, Np)
        self.set_pore_info(label='all', locations=pind)
        self.set_pore_data(prop='numbering', data=pind)  # Remove eventually

        
        img_ind = np.ravel_multi_index(sp.nonzero(template), dims=sp.shape(template), order='F')
        self.set_pore_data(prop='voxel_index', data=img_ind)

        #This voxel_to_pore map is messy but works
        temp = sp.prod(sp.shape(template))*sp.ones(np.prod(sp.shape(template),),dtype=sp.int32)
        temp[img_ind] = pind
        self._voxel_to_pore_map = temp

        coords = self._Lc*(0.5 + np.transpose(np.nonzero(template)))
        self.set_pore_data(prop='coords', data=coords)
        self._logger.debug("generate_pores: End of method")
开发者ID:AgustinPerez,项目名称:OpenPNM,代码行数:26,代码来源:__Template__.py

示例2: check_if_click_is_on_an_existing_point

def check_if_click_is_on_an_existing_point(mouse_x_coord,mouse_y_coord):
    # First, figure out how many points we have.
    # Each point is one row in the coords_array,
    # so we count the number of rows, which is dimension-0 for Python
    number_of_points = scipy.shape(coords_array)[0]    
    this_coord = scipy.array([[ mouse_x_coord, mouse_y_coord ]]) 
            # The double square brackets above give the this_coord array 
            # an explicit structure of having rows and also columns
    if number_of_points > 0:  
        # If there are some points, we want to calculate the distance
        # of the new mouse-click location from every existing point.
        # One way to do this is to make an array which is the same size
        # as coords_array, and which contains the mouse x,y-coords on every row.
        # Then we can subtract that xy_coord_matchng_matrix from coords_array
        ones_vec = scipy.ones((number_of_points,1))
        xy_coord_matching_matrix = scipy.dot(ones_vec,this_coord)
        distances_from_existing_points = (coords_array - xy_coord_matching_matrix)
        squared_distances_from_existing_points = distances_from_existing_points**2
        sum_sq_dists = scipy.sum(squared_distances_from_existing_points,axis=1) 
                   # The axis=1 means "sum over dimension 1", which is columns for Python          
        euclidean_dists = scipy.sqrt(sum_sq_dists)
        distance_threshold = 0.5
        within_threshold_points = scipy.nonzero(euclidean_dists < distance_threshold )
        num_within_threshold_points = scipy.shape(within_threshold_points)[1]
        if num_within_threshold_points > 0:
            # We only want one matching point.
            # It's possible that more than one might be within threshold.
            # So, we take the unique smallest distance
            point_to_be_deleted = scipy.argmin(euclidean_dists)
            return point_to_be_deleted
        else: # If there are zero points, then we are not deleting any 
            point_to_be_deleted = -1
            return point_to_be_deleted
开发者ID:eddienko,项目名称:SamPy,代码行数:33,代码来源:interactive_correlation_plot.py

示例3: full_obs

def full_obs(sys,poles):
    """Full order observer of the system sys

    Call:
    obs=full_obs(sys,poles)

    Parameters
    ----------
    sys : System in State Space form
    poles: desired observer poles

    Returns
    -------
    obs: ss
    Observer

    """
    if isinstance(sys, TransferFunction):
        "System must be in state space form"
        return
    a=mat(sys.A)
    b=mat(sys.B)
    c=mat(sys.C)
    d=mat(sys.D)
    poles=mat(poles)
    L=place(a.T,c.T,poles)
    L=mat(L).T
    Ao=a-L*c
    Bo=hstack((b-L*d,L))
    n=shape(Ao)
    m=shape(Bo)
    Co=eye(n[0],n[1])
    Do=zeros((n[0],m[1]))
    obs=ss(Ao,Bo,Co,Do,sys.Tsamp)
    return obs
开发者ID:Southampton-Maritime-Robotics,项目名称:DelphinROSv3,代码行数:35,代码来源:yottalab.py

示例4: results

    def	results(self):
	""" This method computes the results as a dictionary """

	result = {}

	# here you can either use a perturbed fcc lattice or completely random positions        
        #positions=self.makeRandomPositions()
        positions = self.makePerturbedLattice()

        gradE = self.gradE(positions)
        force = self.getForce(positions)

        result['gradE'] = gradE
        result['force'] = force

        # what should the error tolerance be on this?
        error = abs((gradE+force)/force)

	max_error = error.max()
	
	# this is to identify where the max error is
	index1 = error.argmax()/scipy.shape(error)[1]  
	index2 = error.argmax()-scipy.shape(error)[1]*(index1)

        if (error > 10**(-8)).any(): # expected error according to numerical recipes
                result['Equal'] = False
        else:
                result['Equal'] = True

        result['errors'] = error
	result['max error'] = max_error
	result['max error location']=scipy.array([index1,index2])

        return result
开发者ID:alexalemi,项目名称:openkimtests,代码行数:34,代码来源:ForceTest.py

示例5: kalman_filter

def kalman_filter(b,
                  V,
                  Phi,
                  y,
                  X,
                 sigma,
                  Sigma,
                  switch = 0,
                  D = None,
                  d = None,
                  G = None,
                  a = None,
                  c = None):
    r"""
    
    .. math::
       :nowrap:

       \begin{eqnarray*}
       \beta_{t|t-1} = \Phi \: \beta_{t-1|t-1}\\
       V_{t|t-1} = \Phi  V_{t-1|t-1} \Phi ^T + \Sigma \\
       e_t = y_t -  X_t \beta_{t|t-1}\\
       K_t =  V_{t|t-1} X_t^T (\sigma + X_t V_{t|t-1} X_t )^{-1}\\
       \beta_{t|t} = \beta_{t|t-1} + K_t e_t\\
       V_{t|t} = (I - K_t X_t^T) V_{t|t-1}\\
       \end{eqnarray*}

    """

    n = scipy.shape(X)[1]
    beta = scipy.empty(scipy.shape(X))
    n = len(b)
    if D is None:
        D = scipy.ones((1, n))
    if d is None:
        d = scipy.matrix(1.)
    if G is None:
        G = scipy.identity(n)
    if a is None:
        a = scipy.zeros((n, 1))
    if c is None:
        c = scipy.ones((n, 1))
#        import code; code.interact(local=locals())
    (b, V) = kalman_predict(b, V, Phi, Sigma)
    for i in xrange(len(X)):
        beta[i] = scipy.array(b).T
        (b, V, e, K) = kalman_upd(b,
                                V,
                                y[i],
                                X[i],
                                sigma,
                                Sigma,
                                switch,
                                D,
                                d,
                                G,
                                a,
                                c)
        (b, V) = kalman_predict(b, V, Phi, Sigma)
    return beta
开发者ID:idaohang,项目名称:KF,代码行数:60,代码来源:libregression.py

示例6: __init__

    def __init__(self, params={}, **kwargs):
        """Initialize the AVSwThetaFB instance.  params should have
        the following keys:

        'ks'   - spring constant (required)
        'c'    - damper coeffiecent (defaults to 0)
        'Ka'   - actuator gain (defaults to 1)
        'Gc'   - proportional feedback gain (defaults to 1)
                 (Gc can be a transfer function modelled as a
                 ratio of polynomials when passed to FORTRAN.)
        'axis' - axis about which the actuator rotates (defaults to 1)
        'tau'  - first order pole of actuator."""
        if not params.has_key("Ka"):
            params["Ka"] = 1
        if not params.has_key("axis"):
            params["axis"] = 1
        if not params.has_key("c"):
            params["c"] = 0
        if not params.has_key("Gc"):
            params["Gc"] = 1
        if shape(params["Ka"]):
            params["Ka"] = params["Ka"][0]
        if params.has_key("tau"):
            if shape(params["tau"]):
                params["tau"] = params["tau"][0]
        TMMElementIHT.__init__(self, "avsthfb", params, **kwargs)
开发者ID:ryanGT,项目名称:research,代码行数:26,代码来源:__init__.py

示例7: convertToTimeAndFrequencyData

  def convertToTimeAndFrequencyData(self, grain, target):
    d = self.sample_duration
    length = max(sp.shape(sp.arange(1, sp.size(target) - sp.size(self.gabor[1]), d)))
    scale = sp.zeros((88, length))
    datacapsule = sp.zeros((sp.shape(self.gabor)[1], grain))

    # 行列を束ねて処理
    #   個々にgabor*datadataを計算すると時間がかかる
    #   一気にdatadataを束ねるとメモリ消費量が半端ない
    #   よってdatadataに定義された数だけ束ねて処理
    m = 0
    datasize = sp.size(target) - sp.size(self.gabor[1])

    for k in sp.arange(1, datasize+1, d*grain):
      capsule_pointer = 0
      endl = k+d*grain

      if endl > datasize:
        endl = k + datasize%(d*grain)

      for l in sp.arange(k, endl, d):
        datadata = target[l:l+sp.size(self.gabor[1])]
        datacapsule[:, capsule_pointer] = datadata
        capsule_pointer += 1

      try:
        scale[:, m:m+grain] = sp.absolute(
            sp.dot(self.gabor,datacapsule[:, :capsule_pointer]))
      except ValueError:
        pass
      m += grain
    
    self.time_freq = scale
开发者ID:mackee,项目名称:utakata,代码行数:33,代码来源:utakata_wave.py

示例8: autolim

 def autolim(self, myattr, freqvect, margin=0.1,db=0):
     if self.freqlim:
         ind1=thresh(freqvect,self.freqlim[0])
         ind2=thresh(freqvect,self.freqlim[1])
     else:
         ind1=0
         ind2=-1
     mymatrix=getattr(self,myattr)
     if len(shape(mymatrix))==1:
         submat=mymatrix[ind1:ind2]
     else:
         mymatrix=colwise(mymatrix)
         submat=mymatrix[ind1:ind2,:]
     if db:
         submat=20*log10(submat)
     # max and min need to be done columnwise
     # (maybe a Krauss matrix max)
     if len(shape(submat))==2:
         mymax=[]
         mymin=[]
         for q in range(shape(submat)[1]):
             mymax.append(max(submat[:,q]))
             mymin.append(min(submat[:,q]))
     else:
         mymax=max(submat)
         mymin=min(submat)
     if len(shape(mymax))>0:
         mymax=max(mymax)
         mymin=min(mymin)
     myspan=mymax-mymin
     mymargin=margin*myspan
     limout=[mymin-mymargin, mymax+mymargin]
     setattr(self,myattr+"lim",limout)
     return limout
开发者ID:ryanGT,项目名称:research,代码行数:34,代码来源:rwkbode.py

示例9: minreal

def minreal(sys):
    """Minimal representation for state space systems

    Usage
    =====
    [sysmin]=minreal[sys]

    Inputs
    ------

    sys: system in ss or tf form

    Outputs
    -------
    sysfin: system in state space form
    """
    a=mat(sys.A)
    b=mat(sys.B)
    c=mat(sys.C)
    d=mat(sys.D)
    nx=shape(a)[0]
    ni=shape(b)[1]
    no=shape(c)[0]

    out=tb03ad(nx,no,ni,a,b,c,d,'R')

    nr=out[3]
    A=out[0][:nr,:nr]
    B=out[1][:nr,:ni]
    C=out[2][:no,:nr]
    sysf=ss(A,B,C,sys.D,sys.Tsamp)
    return sysf
开发者ID:Jeet1994,项目名称:python-control-code,代码行数:32,代码来源:yottalab.py

示例10: dsimul

def dsimul(sys,u):
    """Simulate the discrete system sys
    Only for discrete systems!!!

    Call:
    y=dsimul(sys,u)

    Parameters
    ----------
    sys : Discrete System in State Space form
    u   : input vector
    Returns
    -------
    y: ndarray
    Simulation results

    """
    a=mat(sys.A)
    b=mat(sys.B)
    c=mat(sys.C)
    d=mat(sys.D)
    nx=shape(a)[0]
    ns=shape(u)[1]
    xk=zeros((nx,1))
    for i in arange(0,ns):
        uk=u[:,i]
        xk_1=a*xk+b*uk
        yk=c*xk+d*uk
        xk=xk_1
        if i==0:
            y=yk
        else:
            y=hstack((y,yk))
    y=array(y).T
    return y
开发者ID:Southampton-Maritime-Robotics,项目名称:DelphinROSv3,代码行数:35,代码来源:yottalab.py

示例11: GetMat

 def GetMat(self,s,sym=False):
     """Return the element transfer matrix for the
     TorsionalSpringDamper element.  If sym=True, 's' must be a
     symbolic string and a matrix of strings will be returned.
     Otherwise, 's' is a numeric value (probably complex) and the
     matrix returned will be complex."""
     N=self.maxsize
     if sym:
         myparams=self.symparams
     else:
         myparams=self.params
     k=myparams['k']
     c=myparams['c']
     springterm=1/(k[0]+c[0]*s)
     if sym:
         maxlen=len(springterm)+10
         matout=eye(N,dtype='f')
         matout=matout.astype('S%d'%maxlen)
     else:
         matout=eye(N,dtype='D')
     matout[1,2]=springterm
     if max(shape(k))>1 and self.maxsize>=8:
         matout[5,6]=1/(k[1]+c[1]*s)
     if max(shape(k))>2 and self.maxsize>=12:
         matout[9,10]=1/(k[2]+c[2]*s)
     return matout
开发者ID:ryanGT,项目名称:research,代码行数:26,代码来源:__init__.py

示例12: _update_network

def _update_network(network, net):
    # Infer Np and Nt from length of given prop arrays in file
    for element in ['pore', 'throat']:
        N = [_sp.shape(net[i])[0] for i in net.keys() if i.startswith(element)]
        if N:
            N = _sp.array(N)
            if _sp.all(N == N[0]):
                if (network._count(element) == N[0]) \
                        or (network._count(element) == 0):
                    network.update({element+'.all': _sp.ones((N[0],),
                                                             dtype=bool)})
                    net.pop(element+'.all', None)
                else:
                    raise Exception('Length of '+element+' data in file ' +
                                    'does not match network')
            else:
                raise Exception(element+' data in file have inconsistent ' +
                                'lengths')

    # Add data on dummy net to actual network
    for item in net.keys():
        # Try to infer array types and change if necessary
        # Chcek for booleans disguised and 1's and 0's
        num0s = _sp.sum(net[item] == 0)
        num1s = _sp.sum(net[item] == 1)
        if (num1s + num0s) == _sp.shape(net[item])[0]:
            net[item] = net[item].astype(bool)
        # Write data to network object
        if item not in network:
            network.update({item: net[item]})
        else:
            logger.warning('\''+item+'\' already present')
    return network
开发者ID:TomTranter,项目名称:OpenPNM,代码行数:33,代码来源:IO.py

示例13: num_neighbors

    def num_neighbors(self,pnums,labels=['all']):
        r"""
        Returns an ndarray containing the number of neigbhor pores for each 
        element in Pnums

        Parameters
        ----------
        pnums : array_like
            Pores whose neighbors are to be counted
        labels : list of string, optional
            The pore labels that should be included in the count

        Returns
        -------
        num_neighbors : 1D array with number of neighbors in each element, 
        useful for finding the number of neighbors of a certain type

        Examples
        --------
        >>> pn = OpenPNM.Network.TestNet()
        >>> Pnum = [0,1]
        >>> pn.num_neighbors(Pnum,flatten=False)
        array([3, 4], dtype=int8)
        >>> pn.num_neighbors(Pnum)
        7
        """
        #Convert string to list, if necessary
        if type(labels) == str: labels = [labels]

        #Count number of neighbors
        neighborPs = self.find_neighbor_pores(pnums,labels=labels,flatten=False)
        num = sp.zeros(sp.shape(neighborPs),dtype=sp.int8)
        for i in range(0,sp.shape(num)[0]):
            num[i] = sp.size(neighborPs[i])
        return num
开发者ID:HaroldDay,项目名称:OpenPNM,代码行数:35,代码来源:__GenericNetwork__.py

示例14: getHDF5Description

 def getHDF5Description(self):
     u_shape = scipy.shape(self.u)
     lambd_shape = scipy.shape(self.lambd)
     class SystemSave(tables.IsDescription):
         u = tables.FloatCol(shape = u_shape)
         lambd = tables.FloatCol(shape = lambd_shape)
     return SystemSave
开发者ID:pvnuffel,项目名称:riskmodel,代码行数:7,代码来源:System.py

示例15: __init__

    def __init__(self, U, Y, statedim, reg=None):
        if size(shape(U)) == 1:
            U = reshape(U, (-1,1))
        if size(shape(Y)) == 1:
            Y = reshape(Y, (-1,1))
        if reg is None:
            reg = 0

        yDim = size(Y,1)
        uDim = size(U,1)

        self.output_size = size(Y,1) # placeholder

        # number of samples of past/future we'll mash together into a 'state'
        width = 1
        # total number of past/future pairings we get as a result
        K = size(U,0) - 2 * width + 1

        # build hankel matrices containing pasts and futures
        U_p = array([ravel(U[t : t + width]) for t in range(K)]).T
        U_f = array([ravel(U[t + width : t + 2 * width]) for t in range(K)]).T
        Y_p = array([ravel(Y[t : t + width]) for t in range(K)]).T
        Y_f = array([ravel(Y[t + width : t + 2 * width]) for t in range(K)]).T

        # solve the eigenvalue problem
        YfUfT = dot(Y_f, U_f.T)
        YfUpT = dot(Y_f, U_p.T)
        YfYpT = dot(Y_f, Y_p.T)
        UfUpT = dot(U_f, U_p.T)
        UfYpT = dot(U_f, Y_p.T)
        UpYpT = dot(U_p, Y_p.T)
        F = bmat([[None, YfUfT, YfUpT, YfYpT],
                  [YfUfT.T, None, UfUpT, UfYpT],
                  [YfUpT.T, UfUpT.T, None, UpYpT],
                  [YfYpT.T, UfYpT.T, UpYpT.T, None]])
        Ginv = bmat([[pinv(dot(Y_f,Y_f.T)), None, None, None],
                     [None, pinv(dot(U_f,U_f.T)), None, None],
                     [None, None, pinv(dot(U_p,U_p.T)), None],
                     [None, None, None, pinv(dot(Y_p,Y_p.T))]])
        F = F - eye(size(F, 0)) * reg

        # Take smallest eigenvalues
        _, W = eigs(Ginv.dot(F), k=statedim, which='SR')

        # State sequence is a weighted combination of the past
        W_U_p = W[ width * (yDim + uDim) : width * (yDim + uDim + uDim), :]
        W_Y_p = W[ width * (yDim + uDim + uDim):, :]
        X_hist = dot(W_U_p.T, U_p) + dot(W_Y_p.T, Y_p)

        # Regress; trim inputs to match the states we retrieved
        R = concatenate((X_hist[:, :-1], U[width:-width].T), 0)
        L = concatenate((X_hist[:, 1: ], Y[width:-width].T), 0)
        RRi = pinv(dot(R, R.T))
        RL  = dot(R, L.T)
        Sys = dot(RRi, RL).T
        self.A = Sys[:statedim, :statedim]
        self.B = Sys[:statedim, statedim:]
        self.C = Sys[statedim:, :statedim]
        self.D = Sys[statedim:, statedim:]
开发者ID:riscy,项目名称:mllm,代码行数:59,代码来源:system_identifier.py


注:本文中的scipy.shape函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。