示例#1
0
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
示例#2
0
 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
示例#3
0
    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
示例#4
0
def RREFscaled(mymat):
#    Pdb().set_trace()
    scalevect=scipy.amax(abs(mymat),1)
    scaledrows=[]
    for sf,row in zip(scalevect,mymat):
        row=row/sf
        scaledrows.append(row)
    scaledmat=scipy.vstack(scaledrows)
#    scaledmat=mymat
    nc=scipy.shape(scaledmat)[1]
    nr=scipy.shape(scaledmat)[0]
    for j in range(nr-1):
#        print('=====================')
#        print('j='+str(j))
        pivrow=scipy.argmax(abs(scaledmat[j:-1,j]))
        pivrow=pivrow+j
#        print('pivrow='+str(pivrow))
        if pivrow!=j:
            temprow=copy.copy(scaledmat[j,:])
            scaledmat[j,:]=scaledmat[pivrow,:]
            scaledmat[pivrow,:]=temprow
#        Pdb().set_trace()
        for i in range(j+1,nr):
#            print('i='+str(i))
            scaledmat[i,:]-=scaledmat[j,:]*(scaledmat[i,j]/scaledmat[j,j])
    return scaledmat, scalevect
示例#5
0
 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
示例#6
0
    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
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
示例#8
0
文件: IO.py 项目: TomTranter/OpenPNM
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
示例#9
0
  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
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
示例#11
0
    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")
示例#12
0
 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
示例#13
0
def PhaseMassageFilter(phin, N=2, Wn=0.1, jump=250,freqvect=[],chkind=0, fig=None):
    if fig is None:
       from pylab import figure
       fig = figure(fi)

    phun=colwise(phin)
    phout=zeros(shape(phun),'d')#+0.0j
    (b,a)=scipy.signal.butter(N,Wn)
    phfilt=scipy.signal.lfilter(b,a,phun,axis=0)
    for i in range(shape(phout)[1]):
        pherr=phun[:,i]-phfilt[:,i]
        phcor=map(pherrcomp,pherr)
        phout[:,i]=phun[:,i]+phcor
        if freqvect and i==chkind:
            fig.clear()
            ax1 = fig.add_subplot(2, 1, 1)
            ax1.semilogx(freqvect,phun[:,chkind])
            ax1.semilogx(freqvect,phfilt[:,chkind])
            ax1.semilogx(freqvect,phout[:,chkind])
            ax1.legend(['un','filt','out'],3)
            ax2 = fig.add_subplot(2, 1, 2)
            ax2.semilogx(freqvect,pherr)
            ax2.semilogx(freqvect,phcor)
            ax2.legend(['err','cor'],3)
    return phout
示例#14
0
    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)
示例#15
0
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
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
示例#17
0
def nonna_lsq(target, aux, idx=(), names=(), order=2):
	"""
	This function returns the coefficients of the least square prediction of the target
	signal, using the auxiliary signals and their powers, as specified by the order argument.
	
	Input arguments:
	target = target signal
	aux    = matrix of auxiliary signals
	idx    = boolean vector to select a subset of the data for the LSQ fit
	order  = order of the polynomial of aux signals to be used in the fit, default is 2
	names  = list of the auxiliary signal names
	
	Output:
	p      = list of coefficients
	X      = matrix of the signals used in the reconstruction
	cnames = list of the corresponding signals
	
	Note that the mean will be removed from the auxiliary signals. 
	"""
	# number of auxiliary channels
	naux = scipy.shape(aux[1])
	
	if len(names) == 0:
		# since the user didn't provide signal names, let's build some
		names = map(lambda x: 'S'+str(x), scipy.arange(naux)+1)
		
	if len(idx) == 0:
		# no index means use all
		idx = numpy.array(target, dtype=bool)
		idx[:] = True
	
	##### PREPARE CHANNELS FOR LSQ PREDICTION 

	# prepare channels and their squared values
	X = scipy.zeros((scipy.shape(aux)[0], order*scipy.shape(aux)[1]+1))
	cnames = []
	for i in range(scipy.shape(aux)[1]):
		for j in range(order):
			# add the (j+1)th power of the signal after removing the mean
			X[:,order*i+j] = numpy.power((aux[:,i] - scipy.mean(aux[idx,i])), j+1)
			# then remove the mean of the result
			X[:,order*i+j] = X[:,order*i+j] - scipy.mean(X[idx,order*i+j])
			# save the name, including the power
			if j==0:
				cnames.append(names[i])
			else:
				cnames.append(names[i]+'^'+str(j+1))
				
	# add a constant at the end of the list
	X[:,-1] = 1
	cnames.append('1')
	# convert to matrix object for simpler manipulation
	X = scipy.mat(X)
	
	##### best estimate of coefficients to minimize the squared error
	p = scipy.linalg.inv(X[idx,:].T * X[idx,:]) * X[idx,:].T * scipy.mat(target[idx]).T

	# return all the results
	return p, X, cnames
示例#18
0
    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:]
    def __init__(self, x, y, axis=-1, makecopy=0, bounds_error=1,
                 fill_value=None):
        """Initialize a piecewise-constant interpolation class

        Description:
          x and y are arrays of values used to approximate some function f:
            y = f(x)
          This class returns a function whose call method uses piecewise-
          constant interpolation to find the value of new points.

        Inputs:
            x -- a 1d array of monotonically increasing real values.
                 x cannot include duplicate values. (otherwise f is
                 overspecified)
            y -- an nd array of real values.  y's length along the
                 interpolation axis must be equal to the length
                 of x.
            axis -- specifies the axis of y along which to 
                    interpolate. Interpolation defaults to the last
                    axis of y.  (default: -1)
            makecopy -- If 1, the class makes internal copies of x and y.
                    If 0, references to x and y are used. The default 
                    is to copy. (default: 0)
            bounds_error -- If 1, an error is thrown any time interpolation
                            is attempted on a value outside of the range
                            of x (where extrapolation is necessary).
                            If 0, out of bounds values are assigned the
                            NaN (#INF) value.  By default, an error is
                            raised, although this is prone to change.
                            (default: 1)
        """
        self.datapoints = (array(x, Float), array(y, Float))   # RHC -- for access from PyDSTool
        self.type = Float   # RHC -- for access from PyDSTool
        self.axis = axis
        self.makecopy = makecopy   # RHC -- renamed from copy to avoid nameclash
        self.bounds_error = bounds_error
        if fill_value is None:
            self.fill_value = NaN   # RHC -- was:   array(0.0) / array(0.0)
        else:
            self.fill_value = fill_value

        # Check that both x and y are at least 1 dimensional.
        if len(shape(x)) == 0 or len(shape(y)) == 0:
            raise ValueError, "x and y arrays must have at least one dimension."  
        # make a "view" of the y array that is rotated to the
        # interpolation axis.
        oriented_x = x
        oriented_y = swapaxes(y,self.interp_axis,axis)
        interp_axis = self.interp_axis
        len_x,len_y = shape(oriented_x)[interp_axis], \
                            shape(oriented_y)[interp_axis]
        if len_x != len_y:
            raise ValueError, "x and y arrays must be equal in length along "\
                              "interpolation axis."
        if len_x < 2 or len_y < 2:
            raise ValueError, "x and y arrays must have more than 1 entry"            
        self.x = array(oriented_x,copy=self.makecopy)
        self.y = array(oriented_y,copy=self.makecopy)
示例#20
0
 def test_save_and_load_networkx_no_phases(self):
     G = op.io.NetworkX.to_networkx(network=self.net)
     project = op.io.NetworkX.from_networkx(G)
     assert len(project) == 1
     net = project.network
     assert net.Np == 8
     assert net.Nt == 12
     assert sp.shape(net['pore.coords']) == (8, 3)
     assert sp.shape(net['throat.conns']) == (12, 2)
示例#21
0
 def test_load_networkx(self):
     fname = os.path.join(FIXTURE_DIR, 'test_load_yaml.yaml')
     net = io.NetworkX.load(filename=fname)
     assert net.Np == 9
     assert net.Nt == 12
     assert sp.shape(net['pore.coords']) == (9, 3)
     assert sp.shape(net['throat.conns']) == (12, 2)
     a = {'pore.area', 'pore.diameter', 'throat.length', 'throat.perimeter'}
     assert a.issubset(net.props())
示例#22
0
 def test_save_and_load_csv_no_phases(self):
     fname = os.path.join(TEMP_DIR, 'test_save_csv_1')
     io.CSV.save(network=self.net, filename=fname)
     assert os.path.isfile(fname+'.csv')
     net = io.CSV.load(fname+'.csv')
     assert net.Np == 27
     assert net.Nt == 54
     assert sp.shape(net['pore.coords']) == (27, 3)
     assert sp.shape(net['throat.conns']) == (54, 2)
示例#23
0
def augment_3_vector(v=array([0.0, 0.0, 0.0]), free=False):
    if free:
        freeval = 0.0
    else:
        freeval = 1.0
    assert shape(v) == (3,), "v argument must be 3-vector -- found " + str(shape(v))
    vaug = resize(v, (4,))
    vaug[3] = freeval
    return vaug
示例#24
0
    def update_graph(self):
        """Updates the graph with new X and Y"""
        # TODO: rewrite this routine, to get better performance

        # self.background = \
        # 	self.ui.mpl.canvas.ax.figure.canvas.copy_from_bbox(self.ui.mpl.canvas.ax.bbox)
        # save current plot variables
        if self.autoscale:
            self.Rescale()

        if self.background != None:
            # save initial x and y limits
            self.xl = self.ui.mpl.canvas.ax.get_xlim()
            self.yl = self.ui.mpl.canvas.ax.get_ylim()

            # clear the axes
        self.ui.mpl.canvas.ax.clear()
        # plot graph
        self.pltdata, = self.ui.mpl.canvas.ax.plot(
            self.tdata[:, 0], self.tdata[:, 1], self.color + "o", markersize=self.ui.mplhorizontalSlider.value()
        )

        if not hasattr(self, "line"):
            # creating line
            self.line, = self.ui.mpl.canvas.ax.plot([0, 0], [0, 0], "r--", animated=True)

        if not hasattr(self.ui, "rectab"):
            # creating rectangle
            self.rectab, = self.ui.mpl.canvas.ax.plot([0, 0], [0, 0], "r--", animated=True)
            self.rectbc, = self.ui.mpl.canvas.ax.plot([0, 0], [0, 0], "r--", animated=True)
            self.rectcd, = self.ui.mpl.canvas.ax.plot([0, 0], [0, 0], "r--", animated=True)
            self.rectda, = self.ui.mpl.canvas.ax.plot([0, 0], [0, 0], "r--", animated=True)
            # TODO: create a circle
            # enable grid
        self.ui.mpl.canvas.ax.grid(True)

        if self.background != None:
            # set x and y limits
            self.ui.mpl.canvas.ax.set_xlim(self.xl)
            self.ui.mpl.canvas.ax.set_ylim(self.yl)

        self.set_x_log(self.ui.xLogScale.isChecked(), redraw=False)
        self.set_y_log(self.ui.yLogScale.isChecked(), redraw=False)
        # force an image redraw
        self.ui.mpl.canvas.draw()

        # copy background
        self.background = self.ui.mpl.canvas.ax.figure.canvas.copy_from_bbox(self.ui.mpl.canvas.ax.bbox)
        # make edit buttons enabled

        self.ui.mplactionCut_by_line.setEnabled(self.background != None)
        self.ui.mplactionCut_by_rect.setEnabled(self.background != None)

        if np.shape(self.tdata) != self.tempShape:
            self.tempShape = np.shape(self.tdata)
            self.data_signal.emit()
示例#25
0
def makeSquare(image):
	'''For images that aren't square, this funtion will identify the closest power of 2 
	to the smaller dimension and decide whether to crop or pad. If it needs to be padded, 
	this is done in harris.hs'''
 	dim = min(sp.shape(image)[0],sp.shape(image)[1])
	potential_crop = int(2**math.floor(math.log(dim,2)))
	if potential_crop**2 >= 0.9*sp.shape(image)[0]*sp.shape(image)[1]:
		return sp.misc.imresize(image,(potential_crop,potential_crop))

	return image
示例#26
0
 def generateScore(self, target, cut_num):
   fs = self.time_freq_fs = sp.shape(target)[1]  / self.duration
   noise_length = 60. / self.wavetempo * fs
   working = sp.copy(target)
   score = []
   while(sp.shape(working)[1] > noise_length):
     cutted, working = self.cutOutToChangingPoint(working)
     note = self.extractNote(cutted, cut_num)
     score.append(note)
   return score
示例#27
0
 def test_save_load_vtk_no_phases(self):
     fname = os.path.join(TEMP_DIR, 'test_save_vtk_1')
     io.VTK.save(network=self.net, filename=fname, legacy=True)
     assert os.path.isfile(fname+'.vtp')
     net = io.VTK.load(fname+'.vtp')
     assert net.Np == 27
     assert net.Nt == 54
     assert sp.shape(net['pore.coords']) == (27, 3)
     assert sp.shape(net['throat.conns']) == (54, 2)
     assert 'pore.'+self.net.name+'_diameter' in net.keys()
def prob_opt(data):
    k = sp.shape(data)[0]
    n = sp.shape(data)[1]
    max_arm = sp.argmax(data, axis=1)
    prob = sp.zeros(n)
    for i in xrange(0, n):
        this_max = max_arm == i
        prob[i] = this_max.sum() / float(k)
        
    return prob
示例#29
0
文件: vmc.py 项目: EPFL-LQM/gpvmc
def RenormalizeFactor(excfile,gsfile,channel=None,Nsamp=1,O=None,q=None):
    if not type(excfile)==list:
        excfile=[excfile]
    if not type(gsfile)==list:
        gsfile=[gsfile]
    exat=GetAttr(excfile[0])
    gsat=GetAttr(gsfile[0])
    L=exat['L']
    if q==None:
        q=sc.array([exat['qx'],exat['qy']])
    if 'phasex' in exat.keys():
        shift=sc.array([exat['phasex']/2.0,exat['phasey']/2.0])
    else:
        shift=sc.array([exat['phase_shift_x']/2.0,exat['phase_shift_y']/2.0])
    phi=exat['phi']
    neel=exat['neel']
    qx,qy,Sq=GetSq(gsfile)
    kx,ky=sf.fermisea(L,L,shift)
    qidx=ml.find((qx==q[0])*(qy==q[1]))
    if O==None:
        _,O,_,_=GetEigSys(excfile,Nsamp)
    pk=None
    sqq=None
    if channel==None:
        channel=exat['channel']
    if channel=='trans':
        pk=sc.squeeze(sf.phiktrans(kx,ky,q[0]/L,q[1]/L,[phi,neel]))
        sqq=sc.real(0.5*(Sq[0,1,qidx]+Sq[0,2,qidx]))
    elif channel=='long':
        pkup=sc.squeeze(sf.phiklong(kx,ky,q[0]/L,q[1]/L,1,[phi,neel]))
        pkdo=sc.squeeze(sf.phiklong(kx,ky,q[0]/L,q[1]/L,-1,[phi,neel]))
        if (q[0]/L==0.5 and q[1]/L==0.5) or (q[0]/L==0 and q[1]/L==0):
            pk=sc.zeros(2*sc.shape(pkup)[0]+1,complex)
        else:
            pk=sc.zeros(2*sc.shape(pkup)[0],complex)
        pk[0:2*sc.shape(pkup)[0]:2]=pkup
        pk[1:2*sc.shape(pkdo)[0]:2]=pkdo
        if (qx[0]/L==0.5 and q[1]/L==0.5) or (q[0]/L==0 and q[1]/L==0):
            if neel==0:
                pk[-1]=0
            else:
                pk[-1]=sum(neel/sf.omega(kx,ky,[phi,neel]))
        sqq=Sq[0,0,qidx]
    else:
        raise(InputFileError('In file \''+excfile+'\', channel=\''+str(channel)+'\'. Should be \'trans\' or \'long\''))
    sqe=sc.einsum('i,jik,k->j',sc.conj(pk),O,pk)
    out=sc.zeros(Nsamp)
    for n in range(Nsamp):
        if abs(sqq)<1e-6 or abs(sqe[n])<1e-6:
            warnings.warn('Probably ill-defined renormalization, returns 1 for sample {0} out of {1}'.format(n,Nsamp),UserWarning)
            out[n]=1
        else:
            out[n]=sc.real(sqq/sqe[n])
    return out
示例#30
0
 def test_save_and_load_csv_w_phases(self):
     fname = os.path.join(TEMP_DIR, 'test_save_csv_2')
     io.CSV.save(network=self.net, filename=fname, phases=self.phase)
     assert os.path.isfile(fname+'.csv')
     net = io.CSV.load(fname+'.csv')
     assert net.Np == 27
     assert net.Nt == 54
     assert sp.shape(net['pore.coords']) == (27, 3)
     assert sp.shape(net['throat.conns']) == (54, 2)
     assert [True for item in net.keys() if 'temperature' in item]
     assert [True for item in net.keys() if 'diffusive_conductance' in item]
示例#31
0
    def add_periodic_connections(self, pores1, pores2, apply_label='periodic'):
        r"""
        Accepts two sets of pores and connects them with new throats.  The
        connections are determined by pairing each pore in ``pores1`` with its
        nearest pore in ``pores2``.  For cubic Networks this will create
        pairings with pores directly across the domain from each other,
        assuming the input pores are 2D co-planar sets of pores.

        Parameters
        ----------
        pores_1 and pores_2 : array_like
            Lists of pores on the opposing faces which are to be linked to
            create periodicity.

        apply_label = string
            The label to apply to the newly created throats.  The default is
            'periodic'.

        Notes
        -----
        This method will raise an exception if the input pores do not create
        fully unique pairs.  Specifically, the length of pore_1 and pores_2
        must be the same AND each pore in pores_1 must pair up with one and
        only one pore in pores_2, and vice versa.  If these conditions are
        not met then periodicity cannot be acheived, and an exception is
        raised.

        """
        logger.debug('Creating periodic pores')
        if sp.shape(pores1)[0] != sp.shape(pores2)[0]:
            raise Exception('Unequal length inputs, periodicity not possible')
        p1 = self['pore.coords'][pores1]
        p2 = self['pore.coords'][pores2]
        dist_mat = sptl.distance_matrix(p1, p2)
        dist_min = sp.amin(dist_mat, axis=1, keepdims=True)
        [a, b] = sp.where(dist_mat == dist_min)
        pairs = sp.vstack([pores1[a], pores2[b]]).T
        # Confirm that each pore in each list is only paired up once
        temp_1 = sp.unique(pairs[:, 0])
        if sp.shape(temp_1) < sp.shape(pores1):
            raise Exception('Non-unique pairs found, periodicity not met')
        temp_2 = sp.unique(pairs[:, 1])
        if sp.shape(temp_2) < sp.shape(pores2):
            raise Exception('Non-unique pairs found, periodicity not met')
        # Add throats to the network for the periodic connections
        self.extend(throat_conns=pairs, labels=apply_label)
        # Create a list which pores are connected which
        self['pore.periodic_neighbor'] = sp.nan
        self['pore.periodic_neighbor'][pairs[:, 0]] = pairs[:, 1]
        self['pore.periodic_neighbor'][pairs[:, 1]] = pairs[:, 0]
        logger.info('Periodic boundary pores added successfully')
示例#32
0
def gaussians(x, x0, A, sig):
    #if sc.amax(abs(sc.imag(A)))/sc.amax(abs(sc.real(A)))>0.01:
    #    warnings.warn(\
    #'Gaussian amplitude has a sizable imaginary part\(max(|Im|)/max(|Re|)={0}, mean(abs(A))={1}).'\
    #        .format(sc.amax(abs(sc.imag(A)))/sc.amax(abs(sc.real(A))), sc.mean(abs(A))))
    x0 = sc.atleast_1d(x0)
    A = sc.atleast_1d(A)
    sig = sc.atleast_1d(sig)
    amp = A * sc.sqrt(1 / 2.0 / sc.pi) / sig
    [X, X0] = sc.meshgrid(x, x0)
    gg = None
    #if len(sc.shape(amp))==1:
    #    gg=sc.einsum('i,ij',amp,sc.exp(-0.5*(X-X0)**2/sc.tile(sig**2,(sc.shape(x)[0],1)).T))
    #elif len(sc.shape(amp))==2:
    #    gg=sc.einsum('ij,jk',amp,sc.exp(-0.5*(X-X0)**2/sc.tile(sig**2,(sc.shape(x)[0],1)).T))
    gg = sc.einsum(
        '...i,...ij->...j', amp,
        sc.exp(-0.5 * (X - X0)**2 / sc.tile(sig**2, (sc.shape(x)[0], 1)).T))
    return gg
示例#33
0
    def __init__(self,
                 edgelist_fname,
                 directed,
                 write_label_file=True,
                 columns=(0, 1, 2),
                 firsttime=None,
                 lasttime=None):
        list.__init__(self)
        self.first_day = firsttime
        self.last_day = lasttime
        self.fname = edgelist_fname
        self.cols = columns
        self.label_file = write_label_file
        self.is_directed = directed

        self.matricesCreation()
        if not self.is_directed:
            self.as_undirected()
        self.number_of_nodes = scipy.shape(self[0])[0]
示例#34
0
    def find_connected_pores(self, throats=[], flatten=False):
        r"""
        Return a list of pores connected to the given list of throats

        Parameters
        ----------
        throats : array_like
            List of throats numbers

        flatten : boolean, optional
            If flatten is True (default) a 1D array of unique pore numbers
            is returned. If flatten is False each location in the the returned
            array contains a sub-arras of neighboring pores for each input
            throat, in the order they were sent.

        Returns
        -------
        1D array (if flatten is True) or ndarray of arrays (if flatten is False)

        Examples
        --------
        >>> import OpenPNM
        >>> pn = OpenPNM.Network.TestNet()
        >>> pn.find_connected_pores(throats=[0,1])
        array([[0, 1],
               [0, 5]])
        >>> pn.find_connected_pores(throats=[0,1], flatten=True)
        array([0, 1, 5])

        Notes
        -----
        This method basically just looks into the pn['throat.conns'] array and
        retrieves the pores for each input throat.  The flatten option merely
        stacks the two columns and eliminate non-unique values.
        """
        Ts = self._parse_locations(throats)
        Ps = self['throat.conns'][Ts]
        if flatten:
            if sp.shape(Ps) == (0, 2):
                Ps = sp.array([], ndmin=1, dtype=int)
            else:
                Ps = sp.unique(sp.hstack(Ps))
        return Ps
示例#35
0
 def calculate_W_out(self, Y_target, N_x, beta, train_start_timestep,
                     train_end_timestep):
     # see Lukosevicius Practical ESN eqtn 11
     # Using ridge regression
     N_u = sp.shape(Y_target)[0]
     X = sp.vstack(
         (sp.ones((1, train_end_timestep - train_start_timestep)),
          Y_target[:, train_start_timestep:train_end_timestep],
          self.x[train_start_timestep:train_end_timestep].transpose()))
     # Ridge Regression
     W_out = sp.matmul(
         sp.array(Y_target[:, train_start_timestep + 1:train_end_timestep +
                           1]),
         sp.matmul(
             X.transpose(),
             sp.linalg.inv(
                 sp.matmul(X, X.transpose()) +
                 beta * sp.identity(1 + N_x + N_u))))
     self.W_out = W_out
示例#36
0
 def __setitem__(self, prop, value):
     if prop == 'throat.conns':
         if sp.shape(value)[1] != 2:
             logger.error('Wrong size for throat conns!')
         else:
             mask = value[:, 0] > value[:, 1]
             if mask.any():
                 logger.debug('The first column in (throat.conns) should be \
                               smaller than the second one.')
                 v1 = sp.copy(value[:, 0][mask])
                 v2 = sp.copy(value[:, 1][mask])
                 value[:, 0][mask] = v2
                 value[:, 1][mask] = v1
     for geom in self._geometries:
         if (prop in list(geom.keys())) and ('all' not in prop.split('.')):
             logger.error(prop + ' is already defined in at least one associated \
                          Geometry object')
             return
     super().__setitem__(prop, value)
def populations_plot(times, density_m, location):
    """
    Plot the populations of each state versus time in separate files.
    :param times: The times over which to plot the populations in microseconds.
    :param density_m: The density matrix at each time step.
    :param location: Directory where plots will be saved.
    :return: None.
    """
    for i in range(sp.shape(density_m)[1]):
        fig, ax = plt.subplots(nrows=1, ncols=1)
        ax.plot(times, abs(density_m[:, i, i]))
        ax.set_title(r"Population of State " + str(i + 1) + " v. Time")
        ax.set_xlabel(r"Time ($\mu$s)")
        ax.set_ylabel(r"$|\rho_{" + str(i + 1) + str(i + 1) + "}|$")
        ax.axhline(0, color='black')
        plt.savefig(location + "/State " + str(i + 1) + " population.png")
        plt.close()

    return None
示例#38
0
    def laplacian(self):
        """Computes hypergraph laplacian
        Delta=I-Theta,
        Theta=Dv^-1/2 H W De^-1 H^T Dv^-1/2
        
        Returns
        -------
        Delta: sparse matrix
            hypergraph laplacian
        """

        with Timer() as t_l:

            Theta = self.theta_matrix()
            Delta = spsp.eye(*sp.shape(Theta)) - Theta

        self.laplacian_timer = t_l.secs

        return Delta
    def _func(self,x,y):

        if shape(x)==():
                x=array([x])

        if self._log_log_interp is True:
            x=np.log10(x)
            y=np.log10(y)

        model = self.interp_func(x,y)
        #print('-->',x,y,model)
        model[model<self._zero]=self._zero

        if self._log_log_interp is True:
            return np.power(10., model)
        else:
            pass

        return model
示例#40
0
    def log_func(self,nu_log):
        
        x_shift=getattr(self,self.x_scale)
        y_shift=getattr(self,self.y_scale)
        if shape(nu_log)==():
                nu=array([nu_log])
        
        
        x_log=nu_log-x_shift

        model=ones(x_log.size)*-20.0 
            
        msk = x_log >self.nu_template.min() 
        msk*= x_log <self.nu_template.max()
            
        
        model[msk] = self.interp_func(x_log[msk])+y_shift
        
        return model
示例#41
0
def genEdgeCompMat(connComp, rows):
    numComps = sp.shape(connComp)[0]
    edgeCompMat = sp.zeros((numComps, 16))
    for i in xrange(numComps):
        comp = connComp[i].astype(sp.int32)
        r = comp % rows
        c = comp / rows + 1
        r[r == 0] = rows
        subs = sp.concatenate((r, c), axis=1) - 1

        r_cmin, cmin = subs[sp.argmin(c), :]
        rmin, c_rmin = subs[sp.argmin(r), :]
        r_cmax, cmax = subs[sp.argmax(c), :]
        rmax, c_rmax = subs[sp.argmax(r), :]

        edgeCompMat[i, :] = [
            r_cmin, -r_cmin, rmin, -rmin, r_cmax, -r_cmax, rmax, -rmax, cmin,
            -cmin, c_rmin, -c_rmin, cmax, -cmax, c_rmax, -c_rmax
        ]
    return edgeCompMat
def LU(A):
    # throw warning flag when the number is too small
    # (close to 0)
    ok = 1
    small = 1e-12

    n = scipy.shape(A)[0]
    U = copy.copy(A)
    L = scipy.identity(n)
    for j in range(1, n):
        for i in range(j + 1, n + 1):
            if abs(U[j - 1, j - 1]) < small:
                print("Near-zero pivot!")
                ok = 0
                break
            L[i - 1, j - 1] = U[i - 1, j - 1] / U[j - 1, j - 1]
            for k in range(j, n + 1):
                U[i - 1,
                  k - 1] = U[i - 1, k - 1] - L[i - 1, j - 1] * U[j - 1, k - 1]
    return L, U, ok
示例#43
0
def neighbor(network, geometry, throat_prop='', mode='min', **kwargs):
    r"""
    Adopt the minimum seed value from the neighboring throats
    """
    Ps = geometry.pores()
    data = geometry[throat_prop]
    neighborTs = network.find_neighbor_throats(pores=Ps,
                                               flatten=False,
                                               mode='intersection')
    values = _sp.ones((_sp.shape(Ps)[0], )) * _sp.nan
    if mode == 'min':
        for pore in Ps:
            values[pore] = _sp.amin(data[neighborTs[pore]])
    if mode == 'max':
        for pore in Ps:
            values[pore] = _sp.amax(data[neighborTs[pore]])
    if mode == 'mean':
        for pore in Ps:
            values[pore] = _sp.mean(data[neighborTs[pore]])
    return values
示例#44
0
def PlotSqw(filename,gsen,Nsamp=1,channel=None,\
            fig=None,width=0.1,shift=0,\
            V=None,O=None,E=None,S=None,w=None,
            gsspinfile=None, wavefile=None):
    if type(filename) == str:
        filename = [filename]
    attrs = GetAttr(filename[0])
    L = attrs['L']
    q = [float(attrs['qx'] / L), float(attrs['qy']) / L]
    if E == None:
        H, O, E, V = GetEigSys(filename,
                               Nsamp=Nsamp,
                               channel=channel,
                               gsfile=gsspinfile,
                               wavefile=wavefile)
    if S == None:
        S = GetSqAmpl(filename, Nsamp=Nsamp, channel=channel, V=V, O=O)
        if len(sc.shape(S)) == 4:
            S = S[:, 0, 0, :]
    if w == None:
        w = sc.arange(-0.5, 6, 0.01)
    sqw = sc.zeros((sc.shape(E)[0], sc.shape(w)[0]), dtype=S.dtype)
    ax = None
    for s in range(sc.shape(sqw)[0]):
        idx = ~sc.isnan(E[s, :])
        sqw[s] = sf.gaussians(w,
                              sc.squeeze(E[s, idx]) - gsen * L * L,
                              sc.squeeze(S[s, idx]),
                              sc.ones(sc.shape(E[s, idx])) * width)
    sqw += shift
    if fig is None:
        fig = pl.figure()
        ax = fig.gca()
    else:
        ax = fig.gca()
    #ax.hold(True)
    for s in range(sc.shape(sqw)[0]):
        ax.plot(w, sc.real(sqw[s, :]))
        ax.plot(E[s, :] - gsen * L * L,
                sc.squeeze(S[s, :]) * sc.sqrt(1 / 2.0 / sc.pi) / width, 'o')
    if Nsamp != 1:
        ax.plot(w, sc.sum(sqw, 0) / sc.shape(sqw)[0], 'k--', linewidth=3)
    ax.set_xlim((sc.amin(w), sc.amax(w)))
    return fig
示例#45
0
def trainLM(dW, W0, E):
    """
    Params : ``dW`` means ``dE/dW``, or ``J``\n
    ``W = Wt`` at current iteration\n
    ``E = Error`` at current iteration
    """
    J = np.reshape(dW, (1, np.size(dW)))
    #    J = dW.T
    W = np.reshape(W0, (np.size(W0), 1))
    #    W = W0

    mu = 1.0
    #    dW1 = la.pinv(J.T.dot(J) + mu*np.eye(np.size(J.T.dot(J), 0)))
    dW1 = la.pinv(J.dot(J.T) + mu)
    temp1 = J.T.dot(E)
    temp2 = dW1 * temp1
    temp3 = W - temp2
    W1 = np.reshape(temp3, np.shape(W0))
    #    W1 = temp3
    return W1
示例#46
0
    def draw_rviz_points(self,
                         points,
                         frame='narrow_stereo_optical_frame',
                         size=.005,
                         ns='points',
                         id=0,
                         duration=20.,
                         color=[0, 0, 1],
                         opaque=1.0,
                         pose_mat=None,
                         frame_locked=False):
        if pose_mat != None:
            (pos, quat) = mat_to_pos_and_quat(pose_mat)
            marker = self.create_marker(Marker.POINTS, [size, size, size],
                                        frame,
                                        ns,
                                        id,
                                        duration,
                                        color,
                                        opaque,
                                        pos,
                                        quat,
                                        frame_locked=frame_locked)
        else:
            marker = self.create_marker(Marker.POINTS, [size, size, size],
                                        frame,
                                        ns,
                                        id,
                                        duration,
                                        color,
                                        opaque,
                                        frame_locked=frame_locked)

        for point_ind in range(scipy.shape(points)[1]):
            new_point = Point()
            new_point.x = points[0, point_ind]
            new_point.y = points[1, point_ind]
            new_point.z = points[2, point_ind]
            marker.points.append(new_point)

        self.marker_pub.publish(marker)
示例#47
0
文件: maths.py 项目: xmzzaa/PyTom
def normalize2D(data, start=None, end=None, byRow=True):
    """
    normalize2D: normalize 2D data
    """
    from scipy import mean, std, shape
    row, col = shape(data)
    
    if byRow: # normalize by row
        if not start:
            start = 0
        if not end:
            end = row
        
        ndata = data[:start]
        for d in data[start:end]:
            m = mean(d)
            scale = std(d)
            ndata.append([(i-m)/scale for i in d])
        ndata.extend(data[end:])
    else: # normalize by column
        if not start:
            start = 0
        if not end:
            end = col
        
        ndata = []
        m = [0 for i in range(col)]
        scale = [1 for i in range(col)]
        
        for i in range(start, end):
            tmp = [d[i] for d in data]
            m[i] = mean(tmp)
            scale[i] = std(tmp)
        
        for d in data:
            nd = []
            for i in range(col):
                nd.append((d[i]-m[i])/scale[i])
            ndata.append(nd)
    
    return ndata
示例#48
0
    def remove_outliers(self, points):

        points_filtered = points[:]
        empty_space_width = .02
        check_percent = .02
        edge_width = .005

        #remove outliers in each dimension (x,y,z)
        for dim in range(3):

            #sort the points by their values in that dimension
            num_points = scipy.shape(points_filtered)[1]
            points_sorted = points_filtered[:, points_filtered[dim, :].argsort().tolist()[0]]

            #chop off the top points if they are more than empty_space_width away from the bounding box edge
            ind = int(math.floor(num_points*(1-check_percent)))
            if points_sorted[dim, -1] - points_sorted[dim, ind] > empty_space_width:
                
                #find the first point that isn't within edge_width of the point at ind, and lop off all points after
                searcharr = scipy.array(points_sorted[dim, :]).flatten()
                searchval = points_sorted[dim, ind] + edge_width
                thres_ind = scipy.searchsorted(searcharr, searchval)
                if thres_ind != 0 and thres_ind != len(searcharr):
                    points_filtered = points_sorted[:, 0:thres_ind] 
                    rospy.loginfo("chopped points off of dim %d, highest val = %5.3f, searchval = %5.3f"%(dim, points_sorted[dim, -1], searchval))
            else:
                points_filtered = points_sorted

            #do both sides for x and y
            if dim != 2:
                ind = int(math.floor(num_points*check_percent))
                if points_filtered[dim, ind] - points_filtered[dim, 0] > empty_space_width:
                    
                    #find the first point that isn't within edge_width of the point at ind, and lop off all points before
                    searcharr = scipy.array(points_sorted[dim, :]).flatten()
                    searchval = points_sorted[dim, ind] - edge_width
                    thres_ind = scipy.searchsorted(searcharr, searchval)
                    if thres_ind != 0 and thres_ind != len(searcharr):
                        points_filtered = points_filtered[:, thres_ind:-1]
                        rospy.loginfo("chopped points off of dim -%d, lowest val = %5.3f, searchval = %5.3f"%(dim, points_sorted[dim, 0], searchval))
        return points_filtered
示例#49
0
def setBoundaries(u, room):
    [i, j] = sc.shape(u)
    if room == 2:
        u[0, :] = 40
        u[-1, :] = 5
        #u[0:int(i/2) + 1,0] = 15
        #u[int(i/2):,-1] = 15
        u[:, 0] = 15  #endast rum 2
        u[:, -1] = 15
        #hörn
        u[0, 0] = (40 + 15) / 2
        u[-1, 0] = (5 + 15) / 2
        u[-1, -1] = (5 + 15) / 2
        u[0, -1] = (40 + 15) / 2
    if room == 1:
        u[:, 0] = 40
        u[0, :] = 15
        u[-1, :] = 15
        #hörn
        u[0, 0] = (40 + 15) / 2
        u[-1, 0] = (40 + 15) / 2
示例#50
0
    def draw_rviz_points(self,
                         points,
                         frame='kinect_link',
                         size=.005,
                         ns='points',
                         id=0,
                         duration=20.,
                         color=[0, 0, 1],
                         opaque=1.0):
        marker = self.create_marker(Marker.POINTS, [size, size, size], frame,
                                    ns, id, duration, color, opaque)

        for point_ind in range(scipy.shape(points)[1]):
            new_point = Point()
            new_point.x = points[0, point_ind]
            new_point.y = points[1, point_ind]
            new_point.z = points[2, point_ind]
            marker.points.append(new_point)

        self.marker_pub.publish(marker)
        rospy.loginfo("published points")
示例#51
0
def benchmark_rect(n_pts=1000, sz=(1000, 1000)):
    "Draws a number of randomly-placed renctangles."
    width, height = sz
    pts = stats.norm.rvs(size=(n_pts, 2)) * array(sz) / 8. + array(sz) / 2.
    print(pts[5, :])
    print(shape(pts))

    gc = agg.GraphicsContextArray(sz)
    gc.set_fill_color((1.0, 0.0, 0.0, 0.1))
    gc.set_stroke_color((0.0, 1.0, 0.0, 0.6))
    t1 = time.clock()
    for x, y in pts:
        with gc:
            gc.translate_ctm(x, y)
            gc.rect(-2.5, -2.5, 5, 5)
            gc.draw_path()
    t2 = time.clock()
    gc.save("benchmark_rect.bmp")
    tot_time = t2 - t1
    print('rect count, tot,per shape:', n_pts, tot_time, tot_time / n_pts)
    return
示例#52
0
    def plot_porosity_profile(self, fig=None):
        r"""
        Return a porosity profile in all orthogonal directions by summing
        the voxel volumes in consectutive slices.
        """
        if hasattr(self, '_fibre_image') is False:
            logger.warning(
                'This method only works when a fibre image exists, ' +
                'please run make_fibre_image')
            return
        if self._fibre_image is None:
            self.make_fibre_image()
        l = sp.asarray(sp.shape(self._fibre_image))
        px = sp.zeros(l[0])
        py = sp.zeros(l[1])
        pz = sp.zeros(l[2])

        for x in sp.arange(l[0]):
            px[x] = sp.sum(self._fibre_image[x, :, :])
            px[x] /= sp.size(self._fibre_image[x, :, :])
        for y in sp.arange(l[1]):
            py[y] = sp.sum(self._fibre_image[:, y, :])
            py[y] /= sp.size(self._fibre_image[:, y, :])
        for z in sp.arange(l[2]):
            pz[z] = sp.sum(self._fibre_image[:, :, z])
            pz[z] /= sp.size(self._fibre_image[:, :, z])

        if fig is None:
            fig = plt.figure()
        ax = fig.gca()
        plots = []
        plots.append(plt.plot(sp.arange(l[0]) / l[0], px, 'r', label='x'))
        plots.append(plt.plot(sp.arange(l[1]) / l[1], py, 'g', label='y'))
        plots.append(plt.plot(sp.arange(l[2]) / l[2], pz, 'b', label='z'))
        plt.xlabel('Normalized Distance')
        plt.ylabel('Porosity')
        handles, labels = ax.get_legend_handles_labels()
        ax.legend(handles, labels, loc=1)
        plt.legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.)
        return fig
示例#53
0
 def asarray(self, values):
     r'''
     Retreive values as a rectangular array, rather than the OpenPNM list format
     
     Parameters
     ----------
     values : array_like
         The values from the network (in a list) to insert into the array
         
     Notes
     -----
     This method can break on networks that have had boundaries added.  It
     will usually work IF the list of values came only from 'internal' pores.
     '''
     if sp.shape(values)[0] > self.num_pores('internal'):
         raise Exception(
             'The received values are bigger than the original network')
     Ps = sp.array(self['pore.index'][self.pores('internal')], dtype=int)
     arr = sp.ones(self._shape) * sp.nan
     ind = sp.unravel_index(Ps, self._shape)
     arr[ind[0], ind[1], ind[2]] = values
     return arr
示例#54
0
def unique_list(input_list):
    r"""
    For a given list (of points) remove any duplicates
    """
    output_list = []
    if len(input_list) > 0:
        dim = _sp.shape(input_list)[1]
        for i in input_list:
            match = False
            for j in output_list:
                if dim == 3:
                    if i[0] == j[0] and i[1] == j[1] and i[2] == j[2]:
                        match = True
                elif dim == 2:
                    if i[0] == j[0] and i[1] == j[1]:
                        match = True
                elif dim == 1:
                    if i[0] == j[0]:
                        match = True
            if match is False:
                output_list.append(i)
    return output_list
示例#55
0
    def find_connecting_throat(self,P1,P2):
        r"""
        Return the throat number connecting pairs of pores

        Parameters
        ----------
        P1 , P2 : array_like
            The pore numbers whose throats are sought.  These can be vectors
            of pore numbers, but must be the same length

        Returns
        -------
        Tnum : list of list of int
            Returns throat number(s), or empty array if pores are not connected

        Examples
        --------
        >>> import OpenPNM
        >>> pn = OpenPNM.Network.TestNet()
        >>> pn.find_connecting_throat([0,1,2],[2,2,2])
        [[], [3], []]

        TODO: This now works on 'vector' inputs, but is not actually vectorized
        in the Numpy sense, so could be slow with large P1,P2 inputs
        """
        Ts1 = self.find_neighbor_throats(P1,flatten=False)
        Ts2 = self.find_neighbor_throats(P2,flatten=False)
        Ts = []
        if sp.shape(P1) == ():
            P1 = [P1]
            P2 = [P2]
        for row in range(0,len(P1)):
            if P1[row] == P2[row]:
                throat = []
            else:
                throat = sp.intersect1d(Ts1[row],Ts2[row]).tolist()
            Ts.insert(0,throat)
        Ts.reverse()
        return Ts
示例#56
0
    def __init__(self,
                 shape=None,
                 spacing=[1, 1, 1],
                 perturbation=0.1,
                 arrangement='SC',
                 **kwargs):
        if shape is not None:
            self._arr = np.atleast_3d(np.empty(shape))
        else:
            self._arr = np.atleast_3d(np.empty([3, 3, 3]))

        # Store original network shape
        self._shape = sp.shape(self._arr)
        # Store network spacing instead of calculating it
        self._spacing = sp.asarray(spacing)
        self._num_pores = np.prod(np.asarray(self._shape))
        self._domain_size = np.asarray(self._shape) * self._spacing
        self._perturbation = perturbation
        self._arrangement = arrangement
        super().__init__(num_pores=self._num_pores,
                         domain_size=self._domain_size,
                         **kwargs)
示例#57
0
def get_subscripts(network, shape, **kwargs):
    r'''
    Return the 3D subscripts (i,j,k) into the cubic network

    Parameters
    ----------
    shape : list
        The (i,j,k) shape of the network in number of pores in each direction

    '''
    if network.num_pores('internal') != _sp.prod(shape):
        print('Supplied shape does not match Network size, cannot proceed')
    else:
        template = _sp.atleast_3d(_sp.empty(shape))
        a = _sp.indices(_sp.shape(template))
        i = a[0].flatten()
        j = a[1].flatten()
        k = a[2].flatten()
        ind = _sp.vstack((i, j, k)).T
        vals = _sp.ones((network.Np, 3)) * _sp.nan
        vals[network.pores('internal')] = ind
        return vals
示例#58
0
    def predict(self, data):
        """ Predict samples on actual data.
        
        The result of this function is used for calculating the residuals.
        
        Parameters
        ----------
        data : array-like
            shape = [n_samples, n_channels, n_trials] or
            [n_samples, n_channels]
            Continuous or segmented data set.
            
        Returns
        -------
        predicted : shape = `data`.shape
            Data as predicted by the VAR model.
            
        Notes
        -----
        Residuals are obtained by r = x - var.predict(x)
        """
        data = sp.atleast_3d(data)
        (l, m, t) = data.shape

        p = int(sp.shape(self.coef)[1] / m)

        y = sp.zeros(data.shape)
        if t > l-p:  # which takes less loop iterations
            for k in range(1, p + 1):
                bp = self.coef[:, (k - 1)::p]
                for n in range(p, l):
                    y[n, :, :] += bp.dot(data[n - k, :, :])
        else:
            for k in range(1, p + 1):
                bp = self.coef[:, (k - 1)::p]
                for s in range(t):
                    y[p:, :, s] += data[(p - k):(l - k), :, s].dot(bp.T)

        return y
    def broadened_time_evolution(self):
        """
        Calculate the state of all the atoms in the inhomogeneous line at each of nt time steps of size dt.
        :return: The state of the system at each timestep averaged over the inhomogeneous line.
        """
        dim1, dim2 = sp.shape(self.sing_sim.system.initial_state)
        times = sp.linspace(0,
                            self.sing_sim.duration,
                            self.sing_sim.nt,
                            endpoint=False)
        time_dep_state = sp.zeros((self.sing_sim.nt, dim1, dim2),
                                  dtype=complex)
        for index_i, i in enumerate(self.detunings):
            self.sing_sim.reset_state()
            self.detune(i)
            t1 = time.time()
            time_dep_state = time_dep_state + self.sing_sim.time_evolution()
            print("Atom number =", index_i, "Detuning =",
                  round(i / 1e6, 4), "MHz", "Time elapsed =",
                  str(round(time.time() - t1, 4)), "seconds")

        return time_dep_state / self.n_atoms
示例#60
0
def benchmark_individual_symbols(n_pts=1000, sz=(1000, 1000)):
    "Draws some stars"
    width, height = sz
    pts = stats.norm.rvs(size=(n_pts, 2)) * array(sz) / 8.0 + array(sz) / 2.0
    print(pts[5, :])
    print(shape(pts))
    star_path = star_path_gen()

    gc = agg.GraphicsContextArray(sz)
    gc.set_fill_color((1.0, 0.0, 0.0, 0.1))
    gc.set_stroke_color((0.0, 1.0, 0.0, 0.6))
    t1 = time.clock()
    for x, y in pts:
        with gc:
            gc.translate_ctm(x, y)
            gc.add_path(star_path)
            gc.draw_path()
    t2 = time.clock()
    gc.save("benchmark_symbols1.bmp")
    tot_time = t2 - t1
    print('star count, tot,per shape:', n_pts, tot_time, tot_time / n_pts)
    return