Exemplo n.º 1
0
 def create_adjacency_matrix(self, data=None):
     r"""
     Returns a weighted adjacency matrix, in CSR format based on the
     product of weight values sharing an interface.
     """
     #
     if data is None:
         data = self.data_vector
     #
     weights = data[self._cell_interfaces[:, 0]]
     weights = 2*weights * data[self._cell_interfaces[:, 1]]
     #
     # clearing any zero-weighted connections
     indices = weights > 0
     interfaces = self._cell_interfaces[indices]
     weights = weights[indices]
     #
     # getting cell connectivity info
     row = interfaces[:, 0]
     col = interfaces[:, 1]
     #
     # append row & col to each other, and weights to itself
     row = sp.append(row, interfaces[:, 1])
     col = sp.append(col, interfaces[:, 0])
     weights = sp.append(weights, weights)
     #
     # Generate sparse adjacency matrix in 'coo' format and convert to csr
     num_blks = self.nx*self.nz
     matrix = sprs.coo_matrix((weights, (row, col)), (num_blks, num_blks))
     #
     return matrix.tocsr()
Exemplo n.º 2
0
def mix_prop_test():
    energyfile = "energies_0_K"
    vibfiles = ["0_thermo","1.54_thermo","1.3_thermo","2.3_thermo","1_thermo"]
    efile = open(energyfile,'r')
    efile.readline()
    comp = sp.array([])
    energy0 = sp.array([])
    for line in efile:
        comp = sp.append(comp,float(line.split()[0]))
        energy0 = sp.append(energy0,float(line.split()[1]))
    efile.close()
    phase = []
    for i in range(len(comp)):
        phase.append(Phase(comp[i],energy0[i],vibfiles[i]))
    vib_prop = []
    for i in range(len(phase)):
        vib_prop.append(phase[i].E_thermal)
    vib_mix_prop = binary_mixing_property(vib_prop,comp,2)

    # Text output of data
    for i in range(len(phase[0].T)):
        text = str(phase[0].T[i])
        for j in range(len(phase)):
            text += " "+str(vib_mix_prop[j,i])
        print text
    sys.exit()

    # Graphical output of data
    for i in range(len(phase)):
        plt.plot(phase[i].T,vib_mix_prop[i])
    plt.xlabel('T (K)')
    plt.ylabel('Delta E_vib (meV/cation)')
    plt.show()
Exemplo n.º 3
0
    def LatVsHeiArray(self):
        """        """

        self.altbins = arange(self.altlim[0], self.altlim[1] + self.altstp,
                              self.altstp)

        for _alt in self.altbins:

            if True:

                hwm14Obj = HWM14(alt=_alt,
                                 ap=self.ap,
                                 glatlim=self.glatlim,
                                 glatstp=self.glatstp,
                                 glon=self.glon,
                                 option=self.option,
                                 verbose=self.verbose,
                                 ut=self.ut)

            else:

                pass

            Uwind = reshape(hwm14Obj.Uwind, (len(hwm14Obj.Uwind), 1))
            Vwind = reshape(hwm14Obj.Vwind, (len(hwm14Obj.Vwind), 1))
            self.Uwind = Uwind if _alt == self.altlim[0] else append(
                self.Uwind, Uwind, axis=1)
            self.Vwind = Vwind if _alt == self.altlim[0] else append(
                self.Vwind, Vwind, axis=1)

        self.glatbins = hwm14Obj.glatbins

        self.Uwind = transpose(self.Uwind)
        self.Vwind = transpose(self.Vwind)
Exemplo n.º 4
0
def GP_train(x, y, cov_par, cov_func = None, cov_typ ='SE', \
             cov_fixed = None, prior = None, \
             MF = None, MF_par = None, MF_args = None, \
             MF_fixed = None):
    '''    
    Max likelihood optimization of GP hyper-parameters. Calls
    GP_negloglik. Takes care of merging / splitting the fixed /
    variable and cov / MF parameters
    '''
    if MF != None:
        merged_par = scipy.append(cov_par, MF_par)
        n_MF_par = len(MF_par)
        fixed = scipy.append(scipy.zeros(len(cov_par), 'bool'), \
                             scipy.zeros(n_MF_par, 'bool'))
        if (cov_fixed != None): fixed[0:-n_MF_par] = cov_fixed
        if (MF_fixed != None): fixed[-n_MF_par:] = MF_fixed
        if MF_args == None: MF_args = x[:]
    else:
        merged_par = cov_par[:]
        n_MF_par = 0
        fixed = scipy.zeros(len(cov_par), 'bool')
        if cov_fixed != None: fixed[:] = cov_fixed
    var_par_in = merged_par[fixed == False]
    fixed_par = merged_par[fixed == True]
    args = (x, y, cov_func, cov_typ, MF, n_MF_par, MF_args, fixed, \
            fixed_par, prior)
    var_par_out = \
        sop.fmin(GP_negloglik, var_par_in, args, disp = 0)
    par_out = scipy.copy(merged_par)
    par_out[fixed == False] = var_par_out
    par_out[fixed == True] = fixed_par
    if MF != None:
        return par_out[:-n_MF_par], par_out[-n_MF_par:]
    else:
        return par_out
Exemplo n.º 5
0
    def f(self,x,t):
        N = len(x)/2
        xdot = pl.array([])

        # modulus the x for periodicity.
        x[N:2*N]= x[N:2*N]%self.d
        # HERE ---->> 1Dify
        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive x interparticle force of j on i
                temp += self.qq*(x[N+i]-x[N+j])/(pl.sqrt((x[N+i]-x[N+j])**2)**3)
                # All of the forces coming from the 'same' paricle but from other 'cells' due to the
                # periodic contrains can be wraped up in a sum that converges to an aswer that can
                # be expressed in terms of polygamma functions (se pg 92 of notebook).
                temp += self.qq*(polygamma(1,(self.d+x[N+i]-x[N+j])/self.d)-polygamma(1,1.0-((x[N+i]-x[N+j])/self.d)))/(self.d**2)
            # EC x force on particle i
            for a in range(2):
                temp+=self.As[i]*pl.sin(x[N+i]-a*pl.pi)*pl.cos(t-a*pl.pi)/(pl.cosh(1.0)-pl.cos(x[N+i]-a*pl.pi)) 
            temp -= self.beta*x[i]
            xdot = pl.append(xdot,temp)

        for i in range(N):
            xdot = pl.append(xdot,x[i])

    
        return xdot
def calculate_difference(frames_energy):
    """calculate difference of energies
    
    Implementation following paper "A Highly Robust Audio Fingerprinting System"
    
    :math:`F(n,m)=1` if :math:`E(n,m)-E(n,m+1)-(E(n-1,m)-E(n-1,m+1))>0`
    
    :math:`F(n,m)=0` if :math:`E(n,m)-E(n,m+1)-(E(n-1,m)-E(n-1,m+1))\leq 0`
    
    :param frames_energy: frames of energys
    :type frames_energy: scipy.array
    :return: fingerint
    """
    log.debug('Fingerprinting: calculate_difference')

    # fingerprint vector
    fingerprint = scipy.array([], dtype=int)
    
    # first frame is defined as previous frame
    prev_frame = frames_energy[0]
    print str(len(frames_energy))
    del frames_energy[0]
    
    for n, frame in enumerate(frames_energy):
        # every energy of frequency bands until length-1
        for m in range(len(frame)-1):
            # calculate difference with formula from paper            
            if (frame[m]-frame[m+1]-(prev_frame[m]-prev_frame[m+1]) > 0):
                fingerprint = scipy.append(fingerprint, 1)
            else:
                fingerprint = scipy.append(fingerprint, 0)
            
        prev_frame = frame
        
    return fingerprint
Exemplo n.º 7
0
    def load_shapes(self, narrow_shape, wide_shape):

        self.signal_group = []

        for i in range(10):
            for j in range(10):

                signal = scipy.array([])

                for k in range(5):

                    if codes[i][k] == "n":
                        signal = scipy.append(signal, narrow_shape)
                    else:
                        signal = scipy.append(signal, wide_shape)

                    if codes[j][k] == "n":
                        signal = scipy.append(signal, scipy.zeros(len(narrow_shape)))
                    else:
                        signal = scipy.append(signal, scipy.zeros(len(wide_shape)))

                signal /= pnorm(signal)

                self.signal_group.append(signal)
                self.value_group.append(value_map(i, j))
Exemplo n.º 8
0
 def load_shapes( self, narrow_shape, wide_shape ):
     
     self.ref_signals = []
     
     for i in range(10):
         for j in range(10):
             
             signal = scipy.array([])
             
             for k in range(5):
                 
                 if ( codes[i][k] == 'n' ):
                     signal = scipy.append( signal, narrow_shape )
                 else:
                     signal = scipy.append( signal, wide_shape )
                 
                 if ( codes[j][k] == 'n' ):
                     signal = scipy.append( signal, scipy.zeros(len(narrow_shape)) )
                 else:
                     signal = scipy.append( signal, scipy.zeros(len(wide_shape)) ) 
             
             signal /= norm(signal);
             
             self.ref_signals.append( signal )
             self.ref_values.append( value_map(i,j) )
Exemplo n.º 9
0
    def f(self,x,t):
        # x[N+i] is the position of i^th particle
        # x[i] is the velocity of i^th particle

        # This initilazation should be slightly faster than re-doing "len(x)"
        xdot = pl.array([])

        for i in range(self.N):
            # temp is to have a variable to keep adding terms of the "field" and the interactions to
            # so we can do things peicewise.  start with the field contribution
            temp = 0.0
            #print('1st temp:' + str(temp))
            for j in range(self.N):
                if i == j:
                    continue
                # interaction force of j on i
                temp += (self.I/(2.0*self.N))*pl.sin(x[self.N+i]-x[self.N+j])
            
            #print('2nd temp:' + str(temp))
            # What we have as temp is the second derivative of the position i.e v_dot -> so these
            # are the first in the array
            xdot = pl.append(xdot,temp)
            #print('xdot: ' + str(xdot))
        # The second in the array are just the first deriviative of the positions i.e v wich is what
        # were the first values in the input array.
        xdot = pl.append(xdot,x[:self.N])
        
        return xdot
Exemplo n.º 10
0
    def f(self,x,t):
        N = len(x)/2
        xdot = pl.array([])

        # modulus the x for periodicity.
        x[N:2*N]= x[N:2*N]%self.d
        # HERE ---->> 1Dify
        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive x interparticle force of j on i
                temp += self.qq*(x[N+i]-x[N+j])/(pl.sqrt((x[N+i]-x[N+j])**2)**3)
                # All of the forces coming from the 'same' paricle but from other 'cells' due to the
                # periodic contrains can be wraped up in a sum that converges to an aswer that can
                # be expressed in terms of polygamma functions (se pg 92 of notebook).
                # Note on the sign (xi-xj or xj-xi). Changing the sign of the xi-xj term (i.e. which
                # particle are we considering forces on) changes the direction of the force
                # apropriately.
                temp += self.qq*(polygamma(1,(self.d+x[N+i]-x[N+j])/self.d)-polygamma(1,1.0-((x[N+i]-x[N+j])/self.d)))/(self.d**2)
            # periodic force on particle i
            temp += self.As[i]*pl.sin(x[N+i])*pl.cos(t)
            temp -= self.beta*x[i]
            xdot = pl.append(xdot,temp)
        for i in range(N):
            xdot = pl.append(xdot,x[i])
        return xdot
Exemplo n.º 11
0
 def onclick(self, event):
     print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata)
     x=SP.append(self.x, event.xdata)
     self.y=SP.append(self.y, event.ydata)
     self.x= x[:,SP.newaxis]
     self.on_show()
     self.status_text.setText("New data point: x=%f, y=%f"%(event.xdata, event.ydata))
Exemplo n.º 12
0
    def f(self,x,t):
        # for now masses just = 1.0
        # the 4.0 only works for 2D
        N = len(x)/4
        xdot = pl.array([])
        # modulus the y component to keep periodicity right.
        x[3*N:4*N]= x[3*N:4*N]%self.yd
        # x too
        x[2*N:3*N]= x[2*N:3*N]%self.xd

        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive x interparticle force of j on i
                r_temp = pl.sqrt((x[2*N+i]-x[2*N+j])**2+(x[3*N+i]-x[3*N+j])**2)
                if r_temp < self.cutoff:
                    temp += (x[2*N+i]-x[2*N+j])/(r_temp)*24.0*(2.0/(r_temp**13) - 1.0/(r_temp**7))
                # if periodic in x we are going to need to include all the wrap around forces
                for gama in range(self.order):
                    r_temp = pl.sqrt((gama*self.xd-(x[2*N+i]-x[2*N+j]))**2+(x[3*N+i]-x[3*N+j])**2)
                    if r_temp < self.cutoff:
                        temp += -(gama*self.xd-(x[2*N+i]-x[2*N+j]))/(r_temp)*24.0*(2.0/(r_temp**13) - 1.0/(r_temp**7))

                    r_temp = pl.sqrt((gama*self.xd+(x[2*N+i]-x[2*N+j]))**2+(x[3*N+i]-x[3*N+j])**2)
                    if r_temp < self.cutoff:
                        temp += (gama*self.xd+(x[2*N+i]-x[2*N+j]))/(r_temp)*24.0*(2.0/(r_temp**13) - 1.0/(r_temp**7))
            #temp -= self.beta*x[i]
            xdot = pl.append(xdot,temp)
        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive y interparticle force of j on i
                r_temp = pl.sqrt((x[2*N+i]-x[2*N+j])**2+(x[3*N+i]-x[3*N+j])**2)
                if r_temp < self.cutoff:
                    temp += (x[3*N+i]-x[3*N+j])/r_temp*24.0*(2.0/(r_temp**13)-1.0/(r_temp**7)) 
                # force from same particle but in other direction becasue of periodic boundar
                # conditions
                for gama in range(self.order):
                    r_temp = pl.sqrt((x[2*N+i]-x[2*N+j])**2+(gama*self.yd-(x[3*N+i]-x[3*N+j]))**2)
                    if r_temp < self.cutoff:
                        temp += -(gama*self.yd-(x[3*N+i]-x[3*N+j]))/r_temp*24.0*(2.0/(r_temp**13)-1.0/(r_temp**7)) 

                    r_temp = pl.sqrt((x[2*N+i]-x[2*N+j])**2+(gama*self.yd+(x[3*N+i]-x[3*N+j]))**2)
                    if r_temp < self.cutoff:
                        temp += (gama*self.yd+(x[3*N+i]-x[3*N+j]))/r_temp*24.0*(2.0/(r_temp**13)-1.0/(r_temp**7)) 

                    #temp += -self.qq*(gama*self.yd-(x[3*N+i]-x[3*N+j]))/(pl.sqrt((gama*self.yd-(x[3*N+i]-x[3*N+j]))**2+(x[2*N+i]-x[2*N+j])**2)**3)
                    #temp += self.qq* (gama*self.yd+(x[3*N+i]-x[3*N+j]))/(pl.sqrt((gama*self.yd+(x[3*N+i]-x[3*N+j]))**2+(x[2*N+i]-x[2*N+j])**2)**3)
            #temp -= self.beta*x[N+i]
            xdot = pl.append(xdot,temp)
        for i in range(N):
            xdot = pl.append(xdot,x[i])
        for i in range(N):
            xdot = pl.append(xdot,x[N+i])

        return xdot
Exemplo n.º 13
0
    def update_step(self, input_signal=None, teaching_signal=None):
        """update the network with the given input and teach_output, input_signal and teaching_signal must be a column vector
        notice that input_signal is u(n+1) and output is output(n+1) 
        this step makes state(n) -> state(n+1)
        the x_history is a list of state's state_history , every item is a row vector like (100L,)"""

        if input_signal != None:
            assert input_signal.shape == (self.input_unit_amount, 1)
        if teaching_signal != None:
            assert teaching_signal.shape == (self.output_unit_amount, 1)

        if self.feedback_matrix != None and self.input_matrix != None:
            self.state = self.unit_type_ufunc(sp.dot(self.input_matrix, input_signal) + sp.dot(self.internal_matrix, self.state) + sp.dot(self.feedback_matrix, self.output))
            if teaching_signal == None:
                self.output = sp.dot(self.output_matrix, sp.append(input_signal.T,self.state.T).T)
            else:
                self.output = teaching_signal
        elif self.feedback_matrix != None:
            self.state = self.unit_type_ufunc(sp.dot(self.internal_matrix, self.state) + sp.dot(self.feedback_matrix, self.output))
            if teaching_signal == None:
                self.output = sp.dot(self.output_matrix, self.state)
            else:
                self.output = teaching_signal
        else:
            self.state = self.unit_type_ufunc(sp.dot(self.input_matrix, input_signal) + sp.dot(self.internal_matrix, self.state))
        if input_signal != None:
            self.state_history.append(sp.append(input_signal.T, self.state.T))
        else:
            self.state_history.append(self.state.reshape(-1))
        self.output_history.append(self.output)
Exemplo n.º 14
0
    def f(self,x,t):
        N = len(x)/2
        xdot = pl.array([])

        # modulus the x for periodicity.
        x[N:2*N]= x[N:2*N]%self.d
        # HERE ---->> 1Dify
        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive x interparticle force of j on i
                temp += self.qq*(x[N+i]-x[N+j])/(pl.sqrt((x[N+i]-x[N+j])**2)**3)

                # Add the forces from the two ancored charges
                # First one at x=0
                temp += self.qq*(x[N+i]-0.0)/(pl.sqrt((x[N+i]-0.0)**2)**3)
                # Second one at the other boundary i.e. self.d
                temp += self.qq*(x[N+i]-self.d)/(pl.sqrt((x[N+i]-self.d)**2)**3)

            # periodic force on particle i
            temp += self.As[i]*pl.sin(x[N+i])*pl.cos(t)
            temp -= self.beta*x[i]
            xdot = pl.append(xdot,temp)
        for i in range(N):
            xdot = pl.append(xdot,x[i])
        return xdot
Exemplo n.º 15
0
    def __init__(self, x, y, z, f, boundary = 'natural', dx=0, dy=0, dz=0, bounds_error=True, fill_value=scipy.nan):
        if dx != 0 or dy != 0 or dz != 0:
            raise NotImplementedError(
                "Trispline derivatives are not implemented, do not use tricubic "
                "interpolation if you need to compute magnetic fields!"
            )

        
        self._x = scipy.array(x,dtype=float)
        self._y = scipy.array(y,dtype=float)
        self._z = scipy.array(z,dtype=float)

        self._xlim = scipy.array((x.min(), x.max()))
        self._ylim = scipy.array((y.min(), y.max()))
        self._zlim = scipy.array((z.min(), z.max()))
        self.bounds_error = bounds_error
        self.fill_value = fill_value

        if f.shape != (self._x.size,self._y.size,self._z.size):
            raise ValueError("dimensions do not match f")
            
        if _tricub.ismonotonic(self._x) and _tricub.ismonotonic(self._y) and _tricub.ismonotonic(self._z):
            self._x = scipy.insert(self._x,0,2*self._x[0]-self._x[1])
            self._x = scipy.append(self._x,2*self._x[-1]-self._x[-2])
            self._y = scipy.insert(self._y,0,2*self._y[0]-self._y[1])
            self._y = scipy.append(self._y,2*self._y[-1]-self._y[-2])
            self._z = scipy.insert(self._z,0,2*self._z[0]-self._z[1])
            self._z = scipy.append(self._z,2*self._z[-1]-self._z[-2])

        
        self._f = scipy.zeros(scipy.array(f.shape)+(2,2,2))
        self._f[1:-1,1:-1,1:-1] = scipy.array(f) # place f in center, so that it is padded by unfilled values on all sides
        
        if boundary == 'clamped':
            # faces
            self._f[(0,-1),1:-1,1:-1] = f[(0,-1),:,:] 
            self._f[1:-1,(0,-1),1:-1] = f[:,(0,-1),:]
            self._f[1:-1,1:-1,(0,-1)] = f[:,:,(0,-1)]
            #verticies
            self._f[(0,0,-1,-1),(0,-1,0,-1),1:-1] = f[(0,0,-1,-1),(0,-1,0,-1),:] 
            self._f[(0,0,-1,-1),1:-1,(0,-1,0,-1)] = f[(0,0,-1,-1),:,(0,-1,0,-1)]
            self._f[1:-1,(0,0,-1,-1),(0,-1,0,-1)] = f[:,(0,0,-1,-1),(0,-1,0,-1)]
            #corners
            self._f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)] = f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)]
        elif boundary == 'natural':
            # faces
            self._f[(0,-1),1:-1,1:-1] = 2*f[(0,-1),:,:] - f[(1,-2),:,:]
            self._f[1:-1,(0,-1),1:-1] = 2*f[:,(0,-1),:] - f[:,(1,-2),:]
            self._f[1:-1,1:-1,(0,-1)] = 2*f[:,:,(0,-1)] - f[:,:,(1,-2)]
            #verticies
            self._f[(0,0,-1,-1),(0,-1,0,-1),1:-1] = 4*f[(0,0,-1,-1),(0,-1,0,-1),:] - f[(1,1,-2,-2),(0,-1,0,-1),:] - f[(0,0,-1,-1),(1,-2,1,-2),:] - f[(1,1,-2,-2),(1,-2,1,-2),:]
            self._f[(0,0,-1,-1),1:-1,(0,-1,0,-1)] = 4*f[(0,0,-1,-1),:,(0,-1,0,-1)] - f[(1,1,-2,-2),:,(0,-1,0,-1)] - f[(0,0,-1,-1),:,(1,-2,1,-2)] - f[(1,1,-2,-2),:,(1,-2,1,-2)]
            self._f[1:-1,(0,0,-1,-1),(0,-1,0,-1)] = 4*f[:,(0,0,-1,-1),(0,-1,0,-1)] - f[:,(1,1,-2,-2),(0,-1,0,-1)] - f[:,(0,0,-1,-1),(1,-2,1,-2)] - f[:,(1,1,-2,-2),(1,-2,1,-2)]
            #corners
            self._f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)] = 8*f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)] -f[(1,1,1,1,-2,-2,-2,-2),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)] -f[(0,0,0,0,-1,-1,-1,-1),(1,1,-2,-2,1,1,-2,-2),(0,-1,0,-1,0,-1,0,-1)] -f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(1,-2,1,-2,1,-2,1,-2)] -f[(1,1,1,1,-2,-2,-2,-2),(1,1,-2,-2,1,1,-2,-2),(0,-1,0,-1,0,-1,0,-1)] -f[(0,0,0,0,-1,-1,-1,-1),(1,1,-2,-2,1,1,-2,-2),(1,-2,1,-2,1,-2,1,-2)] -f[(1,1,1,1,-2,-2,-2,-2),(0,0,-1,-1,0,0,-1,-1),(1,-2,1,-2,1,-2,1,-2)] -f[(1,1,1,1,-2,-2,-2,-2),(1,1,-2,-2,1,1,-2,-2),(1,-2,1,-2,1,-2,1,-2)]

        self._regular = False
        if _tricub.isregular(self._x) and _tricub.isregular(self._y) and _tricub.isregular(self._z):
            self._regular = True
Exemplo n.º 16
0
    def __init__(self, x, y, z, f, boundary = 'natural', dx=0, dy=0, dz=0, bounds_error=True, fill_value=scipy.nan):
        if dx != 0 or dy != 0 or dz != 0:
            raise NotImplementedError(
                "Trispline derivatives are not implemented, do not use tricubic "
                "interpolation if you need to compute magnetic fields!"
            )

        
        self._x = scipy.array(x,dtype=float)
        self._y = scipy.array(y,dtype=float)
        self._z = scipy.array(z,dtype=float)

        self._xlim = scipy.array((x.min(), x.max()))
        self._ylim = scipy.array((y.min(), y.max()))
        self._zlim = scipy.array((z.min(), z.max()))
        self.bounds_error = bounds_error
        self.fill_value = fill_value

        if f.shape != (self._x.size,self._y.size,self._z.size):
            raise ValueError("dimensions do not match f")
            
        if _tricub.ismonotonic(self._x) and _tricub.ismonotonic(self._y) and _tricub.ismonotonic(self._z):
            self._x = scipy.insert(self._x,0,2*self._x[0]-self._x[1])
            self._x = scipy.append(self._x,2*self._x[-1]-self._x[-2])
            self._y = scipy.insert(self._y,0,2*self._y[0]-self._y[1])
            self._y = scipy.append(self._y,2*self._y[-1]-self._y[-2])
            self._z = scipy.insert(self._z,0,2*self._z[0]-self._z[1])
            self._z = scipy.append(self._z,2*self._z[-1]-self._z[-2])

        
        self._f = scipy.zeros(scipy.array(f.shape)+(2,2,2))
        self._f[1:-1,1:-1,1:-1] = scipy.array(f) # place f in center, so that it is padded by unfilled values on all sides
        
        if boundary == 'clamped':
            # faces
            self._f[(0,-1),1:-1,1:-1] = f[(0,-1),:,:] 
            self._f[1:-1,(0,-1),1:-1] = f[:,(0,-1),:]
            self._f[1:-1,1:-1,(0,-1)] = f[:,:,(0,-1)]
            #verticies
            self._f[(0,0,-1,-1),(0,-1,0,-1),1:-1] = f[(0,0,-1,-1),(0,-1,0,-1),:] 
            self._f[(0,0,-1,-1),1:-1,(0,-1,0,-1)] = f[(0,0,-1,-1),:,(0,-1,0,-1)]
            self._f[1:-1,(0,0,-1,-1),(0,-1,0,-1)] = f[:,(0,0,-1,-1),(0,-1,0,-1)]
            #corners
            self._f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)] = f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)]
        elif boundary == 'natural':
            # faces
            self._f[(0,-1),1:-1,1:-1] = 2*f[(0,-1),:,:] - f[(1,-2),:,:]
            self._f[1:-1,(0,-1),1:-1] = 2*f[:,(0,-1),:] - f[:,(1,-2),:]
            self._f[1:-1,1:-1,(0,-1)] = 2*f[:,:,(0,-1)] - f[:,:,(1,-2)]
            #verticies
            self._f[(0,0,-1,-1),(0,-1,0,-1),1:-1] = 4*f[(0,0,-1,-1),(0,-1,0,-1),:] - f[(1,1,-2,-2),(0,-1,0,-1),:] - f[(0,0,-1,-1),(1,-2,1,-2),:] - f[(1,1,-2,-2),(1,-2,1,-2),:]
            self._f[(0,0,-1,-1),1:-1,(0,-1,0,-1)] = 4*f[(0,0,-1,-1),:,(0,-1,0,-1)] - f[(1,1,-2,-2),:,(0,-1,0,-1)] - f[(0,0,-1,-1),:,(1,-2,1,-2)] - f[(1,1,-2,-2),:,(1,-2,1,-2)]
            self._f[1:-1,(0,0,-1,-1),(0,-1,0,-1)] = 4*f[:,(0,0,-1,-1),(0,-1,0,-1)] - f[:,(1,1,-2,-2),(0,-1,0,-1)] - f[:,(0,0,-1,-1),(1,-2,1,-2)] - f[:,(1,1,-2,-2),(1,-2,1,-2)]
            #corners
            self._f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)] = 8*f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)] -f[(1,1,1,1,-2,-2,-2,-2),(0,0,-1,-1,0,0,-1,-1),(0,-1,0,-1,0,-1,0,-1)] -f[(0,0,0,0,-1,-1,-1,-1),(1,1,-2,-2,1,1,-2,-2),(0,-1,0,-1,0,-1,0,-1)] -f[(0,0,0,0,-1,-1,-1,-1),(0,0,-1,-1,0,0,-1,-1),(1,-2,1,-2,1,-2,1,-2)] -f[(1,1,1,1,-2,-2,-2,-2),(1,1,-2,-2,1,1,-2,-2),(0,-1,0,-1,0,-1,0,-1)] -f[(0,0,0,0,-1,-1,-1,-1),(1,1,-2,-2,1,1,-2,-2),(1,-2,1,-2,1,-2,1,-2)] -f[(1,1,1,1,-2,-2,-2,-2),(0,0,-1,-1,0,0,-1,-1),(1,-2,1,-2,1,-2,1,-2)] -f[(1,1,1,1,-2,-2,-2,-2),(1,1,-2,-2,1,1,-2,-2),(1,-2,1,-2,1,-2,1,-2)]

        self._regular = False
        if _tricub.isregular(self._x) and _tricub.isregular(self._y) and _tricub.isregular(self._z):
            self._regular = True
def read_mat_files(features_basename, labels_fname, camname_fname, actname_fname, partiname_fname):
    """docstring for read_mat_file"""
    
    print "reading features"
    tic = time.time()
    
    f = h5py.File(features_basename + '_part1.mat', 'r')
    ff = f["myData"]
    features1 = ff[:,0:N_1STCHUNK].T
    features2 = ff[:,N_1STCHUNK+1:N_2NDCHUNK].T
    features3 = ff[:,N_2NDCHUNK+1:].T
    features = sp.append(features1, features2,1)
    features = sp.append(features, features3,1)
#    features = sp.array(ff).T
    import ipdb; ipdb.set_trace()
    for nn in range(2,N_PARTS+1):
        f = h5py.File(features_basename + '_part' + str(nn)+ '.mat', 'r')
        import ipdb; ipdb.set_trace()
        ff = f["myData"]
        import ipdb; ipdb.set_trace()
        temp = sp.array(ff).T
        import ipdb; ipdb.set_trace()
        features = sp.append(features, temp,1)
        print nn
    
    print "time taken :", time.time() - tic, 'seconds'

    print "reading participant names"
    tic = time.time()
    partiNames = io.loadmat(partiname_fname)['myPartis']
    partiNames = sp.array([str(partiNames[i][0][0]) for i in xrange(partiNames.shape[0])])
    print "time taken :", time.time() - tic, 'seconds'

    print "reading labels"
    tic = time.time()
    labels = io.loadmat(labels_fname)['labels']
    labels = sp.array([str(labels[i][0][0]) for i in xrange(labels.shape[0])])
    print "time taken :", time.time() - tic, 'seconds'
    
    print "reading camera names"
    tic = time.time()
    camNames = io.loadmat(camname_fname)['myCams']
    camNames = sp.array([str(camNames[i][0][0]) for i in xrange(camNames.shape[0])])
    print "time taken :", time.time() - tic, 'seconds'

    
    print "reading action names"
    tic = time.time()
    actNames = io.loadmat(actname_fname)['myActs']
    actNames = sp.array([str(actNames[i][0][0]) for i in xrange(actNames.shape[0])])
    print "time taken :", time.time() - tic, 'seconds'
            


    # few sanity checks
    #assert(not features.isnan().any())
    #assert(not features.isinf().any())
    
    return features, labels, camNames, actNames, partiNames
Exemplo n.º 18
0
 def point_append(self, p, k):
     """
     Appends the lists of position and direction vectors with the position and the normalised direction vector.
     """
     mag_k = sp.sqrt(sp.dot(k, k))
     khat = k / mag_k
     self.poslist = sp.append(self.poslist, sp.array([p]), axis=0)
     self.dirlist = sp.append(self.dirlist, [khat], axis=0)
Exemplo n.º 19
0
 def onclick(self, event):
     print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
         event.button, event.x, event.y, event.xdata, event.ydata)
     x = SP.append(self.x, event.xdata)
     self.y = SP.append(self.y, event.ydata)
     self.x = x[:, SP.newaxis]
     self.on_show()
     self.status_text.setText("New data point: x=%f, y=%f" %
                              (event.xdata, event.ydata))
Exemplo n.º 20
0
def ConvolucionCircular(f,g):
    # condicion para igualar convolucion lineal con circular
    fog = len(f) + len(g) - 1 
    cerosX = fog - len(f)
    cerosY = fog - len(g)
    # agregando ceros
    f = np.array(sp.append(f,sp.zeros(cerosX)))
    g = np.array(sp.append(g,sp.zeros(cerosY)))
    return np.real(sp.ifft(sp.fft(f) * sp.fft(g)))
Exemplo n.º 21
0
def fitw(material, figurek):
    
#    source_path = os.path.join("measurementData","2a.json")
#    with open(source_path, "r") as ifile:
#        idata = json.load(ifile)
        
#    for k, material in enumerate(idata["materials"][:]):
        
#    label = material["label"]
#    print(label)
    
    w = sp.array(material["w_sorption"])
#    if type(material["w_sorption"]) == list:# and label == "D2":
    RH = sp.array(material["w_sorption_RH"])
    
    wmax = w[-1]
    #    146/(1+(-8e-8*R_water*T_ref*rho_w*sp.log(phi))**1.6)**0.375
    def fit_func(phi, a,b,c):
        return wmax / (1+(a*sp.log(phi))**b)**c 

    
    def to_min(parms):
        return (((w[:-1]-fit_func(RH[:-1], *parms))**2)**0.5).sum()
    try:
        popt, pcov = optimize.curve_fit(fit_func, 
                            RH[:], 
                            w[:],
                            [-2,
                             0.7,
                             2],
#                                [-67744.35379546453,
#                                 0.38825626197169383,
#                                 1.006448450321765]
                            )
    except RuntimeError:
        lb = [-1e4, 0,1]
        ub = [0, 1, 3]
        popt, fopt = pyswarm.pso(to_min, lb, ub,maxiter=1000 )
    
#        print(fopt)
    
    RHfit = sp.linspace(0,1,10000)
    wfit=fit_func(RHfit, *popt)
        
    RHfit = sp.append(RHfit, 1000)
    wfit = sp.append(wfit, (w[-1] - w[-2])/(RH[-1] - RH[-2])* (RHfit[-1] - RHfit[-2]) )
    
#    plt.figure(figurek)
#    plt.plot(RH[:], w[:], "d")
#    plt.plot(RHfit, wfit, "-")
#    plt.xlim(0,1.1)
#    plt.ylim(0,w.max()*1.3)
    
    
    return RHfit, wfit    
Exemplo n.º 22
0
 def matrix_rows(self):
     if self.node==None or self.Phi==None:
         raise NameError('DoF of point %(self.id)d has not been set.')
     
     cols = scipy.array([i*3 for i in self.nodes])
     data = scipy.array([phi for phi in self.Phi])
     
     cols = scipy.append(cols, 3*self.node)
     data = self.binding_weight*scipy.append(data, -1)
     
     return [[cols, data]], [0,1,2], None
Exemplo n.º 23
0
def AddPeople(space, ratio):
    init1 = sci.zeros(100)
    init2 = sci.ones(100)
    init3 = sci.append(init1, init2)
    init4 = sci.array([100] * ratio)
    initialize = sci.append(init3, init4)

    for i in range(1, rows - 1):
        for j in range(1, cols - 1):
            space[i, j] = sci.random.choice(initialize)

    return space
Exemplo n.º 24
0
            def matrix_rows(self):
                if self.node == None or self.Phi == None:
                    raise NameError(
                        'DoF of point %(self.id)d has not been set.')

                cols = scipy.array([i * 3 for i in self.nodes])
                data = scipy.array([phi for phi in self.Phi])

                cols = scipy.append(cols, 3 * self.node)
                data = self.binding_weight * scipy.append(data, -1)

                return [[cols, data]], [0, 1, 2], None
Exemplo n.º 25
0
	def readScatteringFactorFile(self, tablefile):
		flag_header = True
		for line in open(tablefile):
			if flag_header:
				flag_header = False
			else:
				cols = line.split()		
				self.array_energy_eV  = scipy.append(self.array_energy_eV, float(cols[0]))
				self.array_energy_keV = scipy.append(self.array_energy_keV, 0.001*float(cols[0]))
				self.array_f1         = scipy.append(self.array_f1, float(cols[1]))
				self.array_f2         = scipy.append(self.array_f2, float(cols[2]))
		self.interpolateScatteringFactor()
Exemplo n.º 26
0
    def f(self,x,t):
        # the 4.0 only works for 2D
        N = len(x)/4
        xdot = pl.array([])
        # modulus the x component to keep periodicity right.
        x[2*N:3*N]= x[2*N:3*N]%self.diameter

        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive x interparticle force of j on i
                temp += self.qq*(x[2*N+i]-x[2*N+j])/(pl.sqrt((x[2*N+i]-x[2*N+j])**2+(x[3*N+i]-x[3*N+j])**2)**3)
                # force from same particle but in other direction becasue of periodic boundar
                # conditions
                temp += -self.qq*(self.diameter-(x[2*N+i]-x[2*N+j]))/(pl.sqrt((self.diameter-(x[2*N+i]-x[2*N+j]))**2+(x[3*N+i]-x[3*N+j])**2)**3)
                # could do this forever but for now just include one more of force going around in
                # same direction as first. draw a diagam if you need to
                temp += self.qq*(self.diameter+(x[2*N+i]-x[2*N+j]))/(pl.sqrt((self.diameter+(x[2*N+i]-x[2*N+j]))**2+(x[3*N+i]-x[3*N+j])**2)**3)
            # EC x force on particle i
            temp += self.A*(self.square_wave(t))*(-2*(pl.cosh(self.d-x[3*N+i]) + \
                pl.cosh(x[3*N+i]))*(pl.cos(x[2*N+i])**2 - \
                    pl.cosh(self.d-x[3*N+i])*pl.cosh(x[3*N+i]))*pl.sin(x[2*N+i]))/((pl.cos(x[2*N+i])\
                        - pl.cosh(self.d-x[3*N+i]))*(pl.cos(x[2*N+i]) + pl.cosh(self.d - \
                            x[3*N+i]))*(pl.cos(x[2*N+i]) - pl.cosh(x[3*N+i]))*(pl.cos(x[2*N+i]) + \
                                pl.cosh(x[3*N+i]))) - self.beta*x[i]
            xdot = pl.append(xdot,temp)
        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive y interparticle force of j on i
                temp += self.qq*(x[3*N+i]-x[3*N+j])/(pl.sqrt((x[2*N+i]-x[2*N+j])**2+(x[3*N+i]-x[3*N+j])**2)**3)
                # force from same particle but in other direction becasue of periodic boundar
                # conditions
                temp += self.qq*(x[3*N+i]-x[3*N+j])/(pl.sqrt((self.diameter-(x[2*N+i]-x[2*N+j]))**2+(x[3*N+i]-x[3*N+j])**2)**3)
            # EC y force on particle i
            temp += self.A*(self.square_wave(t))*(2*pl.cos(x[2*N+i])*(pl.sinh(self.d - x[3*N+i]) - \
                pl.sinh(x[3*N+i]))*(-pl.sin(x[2*N+i])**2 + pl.sinh(self.d - \
                    x[3*N+i])*pl.sinh(x[3*N+i])))/((pl.cos(x[2*N+i]) - pl.cosh(self.d - \
                        x[3*N+i]))*(pl.cos(x[2*N+i]) + pl.cosh(self.d - x[3*N+i]))*(pl.cos(x[2*N+i]) \
                            - pl.cosh(x[3*N+i]))*(pl.cos(x[2*N+i]) + \
                                pl.cosh(x[3*N+i])))-self.beta*x[N+i] 
            # quadropole restoring force to center of electric curtains
            temp += -self.quadA*(pl.cos(200.0*t)+0.1)*(x[3*N+i]-self.d/2.0)
            xdot = pl.append(xdot,temp)
        for i in range(N):
            xdot = pl.append(xdot,x[i]) 
        for i in range(N):
            xdot = pl.append(xdot,x[N+i])
        return xdot
Exemplo n.º 27
0
    def TOBEFIXED_build_k_coo_sub(self):
        import scipy
        import scipy.sparse as ss
        import alg3dpy.scipy_sparse as assparse
        #FIXME not considering pos to build the matrix!!!
        self.k_coo_sub = {}
        for sub in self.subcases.values():
            dim = 6*len( self.k_pos ) - \
                    len( self.index_to_delete[ sub.id ] )
            data = scipy.zeros(0, dtype='float64')
            row = scipy.zeros(0, dtype='int64')
            col = scipy.zeros(0, dtype='int64')
            for elem in self.elemdict.values():
                numg = len(elem.grids)
                for i in xrange(numg):
                    gi = elem.grids[i]
                    offseti = gi.k_offset[sub.id]
                    consi = set([])
                    if sub.id in gi.cons.keys():
                        consi = gi.cons[sub.id]
                    for j in xrange(numg):
                        gj = elem.grids[j]
                        offsetj = gj.k_offset[sub.id]
                        consj = set([])
                        if sub.id in gj.cons.keys():
                            consj = gj.cons[sub.id]
                        cons = consi | consj
                        index_to_delete = [(c - 1) for c in cons]
                        k_grid = assparse.in_sparse(elem.k, i * 6, i * 6 + 5,
                                                    j * 6, j * 6 + 5)

                        if len(index_to_delete) < 6:
                            k = k_grid
                            for d, r, c, in zip(k.data, k.row, k.col):
                                #FIXME remove the search below
                                if not r in index_to_delete:
                                    sub_r = 0
                                    for k in index_to_delete:
                                        if r > k:
                                            sub_r += 1
                                    if not c in index_to_delete:
                                        sub_c = 0
                                        for m in index_to_delete:
                                            if c > m:
                                                sub_c += 1
                                        newr = r + gi.pos * 6 - offseti - sub_r
                                        newc = c + gj.pos * 6 - offsetj - sub_c
                                        data = scipy.append(data, d)
                                        row = scipy.append(row, newr)
                                        col = scipy.append(col, newc)
            k_coo = ss.coo_matrix((data, (row, col)), shape=(dim, dim))
            self.k_coo_sub[sub.id] = k_coo
Exemplo n.º 28
0
def generate_dummy_data():
    xw1 = norm(loc=0.3, scale=.15).rvs(20)
    yw1 = norm(loc=0.3, scale=.15).rvs(20)

    xw2 = norm(loc=0.7, scale=.15).rvs(20)
    yw2 = norm(loc=0.7, scale=.15).rvs(20)

    xw3 = norm(loc=0.2, scale=.15).rvs(20)
    yw3 = norm(loc=0.8, scale=.15).rvs(20)

    x = scipy.append(scipy.append(xw1, xw2), xw3)
    y = scipy.append(scipy.append(yw1, yw2), yw3)
    return x, y
Exemplo n.º 29
0
 def set_cur_mzvalues_and_intensities(self, act_scan_number):
     self.set_cur_scan(act_scan_number)
     if self.is_profile_bool:
         if len(self.cur_scan.profile) != 0:
             self.cur_mzvals = self.cur_scan.profile[:, 0]
             self.cur_intensities = self.cur_scan.profile[:, 1]
     else:
         self.cur_mzvals = sp.array([])
         self.cur_intensities = sp.array([])
         for i in self.cur_scan.peaklist:
             self.cur_mzvals = sp.append(self.cur_mzvals, i.mz)
             self.cur_intensities = sp.append(self.cur_intensities,
                                              i.intensity)
def prob3():
    rate1, sig1 = wavfile.read('chopinw.wav')
    n = sig1.shape[0]
    rate2, sig2 = wavfile.read('balloon.wav')
    m = sig2.shape[0]
    sig1 = sp.append(sig1, sp.zeros((m, 2)))
    sig2 = sp.append(sig2, sp.zeros((n, 2)))
    f1 = sp.fft(sig1)
    f2 = sp.fft(sig2)
    out = sp.ifft((f1 * f2))
    out = sp.real(out)
    scaled = sp.int16(out / sp.absolute(out).max() * 32767)
    wavfile.write('test.wav', rate1, scaled)
Exemplo n.º 31
0
def prob3():
	rate1,sig1 = wavfile.read('chopinw.wav')
	n = sig1.shape[0]
	rate2,sig2 = wavfile.read('balloon.wav')
	m = sig2.shape[0]
	sig1 = sp.append(sig1,sp.zeros((m,2)))
	sig2 = sp.append(sig2,sp.zeros((n,2)))
	f1 = sp.fft(sig1)
	f2 = sp.fft(sig2)
	out = sp.ifft((f1*f2))
	out = sp.real(out)
	scaled = sp.int16(out/sp.absolute(out).max() * 32767)
	wavfile.write('test.wav',rate1,scaled)
Exemplo n.º 32
0
    def f(self,x,t):
        # for now masses just = 1.0
        # the 4.0 only works for 2D
        N = len(x)/4
        xdot = pl.array([])
        # modulus the y component to keep periodicity right.
        x[3*N:4*N]= x[3*N:4*N]%self.yd
        # x too
        if self.x_periodic:
            x[2*N:3*N]= x[2*N:3*N]%self.xd
        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive x interparticle force of j on i
                temp += self.qq*(x[2*N+i]-x[2*N+j])/(pl.sqrt((x[2*N+i]-x[2*N+j])**2+(x[3*N+i]-x[3*N+j])**2)**3)
                # if periodic in x we are going to need to include all the wrap around forces
                if self.x_periodic:
                    #repulsive y interparticle force of j on i
                    temp += self.qq*(x[2*N+i]-x[2*N+j])/(pl.sqrt((x[2*N+i]-x[2*N+j])**2+(x[3*N+i]-x[3*N+j])**2)**3)
                    for gama in range(self.order):
                        temp += -self.qq*(gama*self.xd-(x[2*N+i]-x[2*N+j]))/(pl.sqrt((gama*self.xd-(x[2*N+i]-x[2*N+j]))**2+(x[3*N+i]-x[3*N+j])**2)**3)
                        temp += self.qq* (gama*self.xd+(x[2*N+i]-x[2*N+j]))/(pl.sqrt((gama*self.xd+(x[2*N+i]-x[2*N+j]))**2+(x[3*N+i]-x[3*N+j])**2)**3)
            # EC x force on particle i
            # surface set to 1.0
            for a in range(2):
                temp+=self.As[i]*pl.sin(x[2*N+i]-a*pl.pi)*pl.cos(t-a*pl.pi)/(pl.cosh(1.0)-pl.cos(x[2*N+i]-a*pl.pi)) 
            temp -= self.beta*x[i]
            xdot = pl.append(xdot,temp)
        for i in range(N):
            temp = 0.0
            for j in range(N):
                if i == j:
                    continue
                #repulsive y interparticle force of j on i
                temp += self.qq*(x[3*N+i]-x[3*N+j])/(pl.sqrt((x[2*N+i]-x[2*N+j])**2+(x[3*N+i]-x[3*N+j])**2)**3)
                # force from same particle but in other direction becasue of periodic boundar
                # conditions
                for gama in range(self.order):
                    temp += -self.qq*(gama*self.yd-(x[3*N+i]-x[3*N+j]))/(pl.sqrt((gama*self.yd-(x[3*N+i]-x[3*N+j]))**2+(x[2*N+i]-x[2*N+j])**2)**3)
                    temp += self.qq* (gama*self.yd+(x[3*N+i]-x[3*N+j]))/(pl.sqrt((gama*self.yd+(x[3*N+i]-x[3*N+j]))**2+(x[2*N+i]-x[2*N+j])**2)**3)
            temp -= self.beta*x[N+i]
            xdot = pl.append(xdot,temp)
        for i in range(N):
            xdot = pl.append(xdot,x[i])
        for i in range(N):
            xdot = pl.append(xdot,x[N+i])

    
        return xdot
Exemplo n.º 33
0
    def TOBEFIXED_build_k_coo_sub(self):
        import scipy
        import scipy.sparse as ss
        import alg3dpy.scipy_sparse as assparse
        #FIXME not considering pos to build the matrix!!!
        self.k_coo_sub = {}
        for sub in self.subcases.values():
            dim = 6*len( self.k_pos ) - \
                    len( self.index_to_delete[ sub.id ] )
            data = scipy.zeros(0, dtype='float64')
            row =  scipy.zeros(0, dtype='int64')
            col =  scipy.zeros(0, dtype='int64')
            for elem in self.elemdict.values():
                numg = len( elem.grids )
                for i in xrange( numg ):
                    gi = elem.grids[ i ]
                    offseti = gi.k_offset[ sub.id ]
                    consi = set( [] )
                    if sub.id in gi.cons.keys():
                        consi = gi.cons[ sub.id ]
                    for j in xrange( numg ):
                        gj = elem.grids[ j ]
                        offsetj = gj.k_offset[ sub.id ]
                        consj = set( [] )
                        if sub.id in gj.cons.keys():
                            consj = gj.cons[ sub.id ]
                        cons = consi | consj
                        index_to_delete = [ (c-1) for c in cons ]
                        k_grid = assparse.in_sparse(elem.k,i*6,i*6+5,j*6,j*6+5)

                        if len(index_to_delete) < 6:
                            k = k_grid
                            for d, r, c, in zip( k.data , k.row, k.col ):
                                #FIXME remove the search below
                                if not r in index_to_delete:
                                    sub_r = 0
                                    for k in index_to_delete:
                                        if r > k:
                                            sub_r += 1
                                    if not c in index_to_delete:
                                        sub_c = 0
                                        for m in index_to_delete:
                                            if c > m:
                                                sub_c += 1
                                        newr = r + gi.pos * 6 - offseti - sub_r
                                        newc = c + gj.pos * 6 - offsetj - sub_c
                                        data = scipy.append( data , d    )
                                        row  = scipy.append( row  , newr )
                                        col  = scipy.append( col  , newc )
            k_coo = ss.coo_matrix(( data, (row,col) ), shape=(dim,dim))
            self.k_coo_sub[sub.id] = k_coo
def createNormalizedDataSets():
    xw1 = norm(loc=0.3, scale=.15).rvs(20)
    yw1 = norm(loc=0.3, scale=.15).rvs(20)

    xw2 = norm(loc=0.7, scale=.15).rvs(20)
    yw2 = norm(loc=0.7, scale=.15).rvs(20)

    xw3 = norm(loc=0.2, scale=.15).rvs(20)
    yw3 = norm(loc=0.8, scale=.15).rvs(20)

    x = sp.append(sp.append(xw1, xw2), xw3)
    y = sp.append(sp.append(yw1, yw2), yw3)

    return x, y
Exemplo n.º 35
0
 def shift(self, items):
     """Shift all buffers up or down a defined number of items on offset axis.
     Negative values indicate backward shift."""
     if items == 0:
         return
     self.offset += items
     for buffername, _  in self.bufferlist:
         buf = getattr(self, buffername)
         assert abs(items) <= len(buf), "Cannot shift further than length of buffer."
         fill = zeros((abs(items), len(buf[0])))
         if items < 0:
             buf[:] = append(buf[-items:], fill, 0)
         else:
             buf[:] = append(fill ,buf[0:-items] , 0)
Exemplo n.º 36
0
def center_orbit(sol,N,Dim):
    how_much = 20
    #sol[:,N:(2*N)]=sol[:,N:(2*N)]%(2.0*sp.pi)

    print('looking for orbit for with smallest velocity amplitude. This only works for 1D systems')

    # make an array of the mean velocity squared values. The array will be orderd as the solution is
    # ordered
    mean_vel_arr = sp.array([])
    # we also need an array of mean_positions to figure out where these things are
    mean_pos_arr = sp.array([])
    count = 0
    while count < N:
        mean_vel_arr = sp.append(mean_vel_arr,(sol[(-len(sol)/how_much):,count]**2).mean())
        print('mean vel appended: ' +str((sol[(-len(sol)/how_much):,count]**2).mean()))

        # so this is a little trickey... 
        # We also need the standard deveation becuase if the paticle is oscilating at the boundary
        # so it is right around 0 AND 2pi then its mean position is pi. We can use the standard
        # deviation to tell weather or not it is actualy at pi or at the boundary. The standard
        # deveation should certinaly be less than pi/2 unless there is only 1 particle.
        cur_mean_pos = (sol[(-len(sol)/how_much):,N+count]).mean()
        cur_mean_std = (sol[(-len(sol)/how_much):,N+count]).std()
        if (cur_mean_std > 3.0):
            print('foud particle oscilating at boundary')
            print('standard deviation: ' +str(cur_mean_std))
            cur_mean_pos = 0.0
        mean_pos_arr = sp.append(mean_pos_arr,cur_mean_pos)
        print('mean pos appended: ' +str(cur_mean_pos))

        count+=1

    print('mean pos arr: ' +str(mean_pos_arr))
    print('mean vel arr: ' +str(mean_vel_arr))

    # which particle is the one with the smallest v^2 trajectory? the_one will be the index of this
    # particle
    the_one = sp.argmin(mean_vel_arr)
    print('orbit with smallest velocity amplitued: '+str(the_one))
    print('mean vel of the_one: ' +str(mean_vel_arr[the_one]))
    print('mean pos of the_one: ' +str(mean_pos_arr[the_one]))

    # Now we need to shift everything to get it into the center. 
    # there are a few ways to do this. We are going to try this one but it might not be the best one

    shift = sp.pi-mean_pos_arr[the_one]
    # now shift everything by the right amount
    sol[:,N:] = (sol[:,N:]+shift)%(2.0*sp.pi)

    return sol
Exemplo n.º 37
0
 def square_wave(self,input):
     if type(input)==float:
         if input%(2.0*pl.pi)<= pl.pi:
             output = 1.0
         if input%(2.0*pl.pi)> pl.pi:
             output = -1.0
     if (type(input)==pl.ndarray)or(type(input)==list):
         output = pl.array([])
         for i,j in enumerate(input):
             if j%(2.0*pl.pi)<= pl.pi:
                 output = pl.append(output,1.0)
             if j%(2.0*pl.pi)> pl.pi:
                 output = pl.append(output,-1.0)
         print('square wave output: ' + str(output)) 
     return output
Exemplo n.º 38
0
def position(xyzsource, xyzobserver):
    '''
    Calculates the norm and angle between a set of points
    '''
    S = np.array([])
    thetas = np.array([])
    for xyz in xyzsource:
        distance = np.linalg.norm(np.array(xyz) - np.array(xyzobserver))
        opposite = xyz[0] - xyzobserver[0]
        adjacent = xyz[1] - xyzobserver[1]
        angle = np.arctan2(opposite, adjacent)
        S = np.append(S, distance / 0.3048)
        thetas = np.append(thetas, angle)

    return S, thetas
Exemplo n.º 39
0
def generation_CommonRare(common, rare, annotation, h2_anno, h2_r, h2_c, pi):
    # first deal with NA in the genoytype matrix
    common = common.fillna(common.mean()).values
    rare = rare.fillna(rare.mean()).values
    rare = (rare - rare.mean()) / rare.std()
    common = (common - common.mean()) / common.std()
    geno = sp.hstack((rare, common))

    G = []
    R = rare.shape[1]
    N = common.shape[0]
    C = common.shape[1]
    ###real parameters
    # number of SNPs being causal
    p_causal = math.floor(pi * R)
    sigma_r = h2_r / p_causal
    sigma_b = h2_anno / (annotation.shape[1] - 1)

    b = sp.random.normal(0, math.sqrt(sigma_b), annotation.shape[1] - 1)
    # first determine random noise in the annotation layer
    anno_error = ((1 - h2_anno) / h2_anno) * annotation[:, 0:-1].dot(b).var()
    b = b / math.sqrt(anno_error)
    sigma_b = h2_anno / (annotation.shape[1] - 1) / anno_error

    # determine the intercept based on how many values larger than 0
    anno_noise = sp.random.normal(0, 1, R)
    anno_val = annotation[:, 0:-1].dot(b) + anno_noise
    anno_intercept = -sorted(anno_val, reverse=True)[p_causal]
    b = sp.append(b, anno_intercept)
    w = annotation.dot(b) + anno_noise

    gamma = sp.zeros(shape=R)
    beta_rare = sp.zeros(shape=R)
    gamma[w > 0] = 1
    beta_rare[w > 0] = sp.random.normal(0, math.sqrt(sigma_r), sum(w > 0))

    sigma_c = h2_c / C
    beta_common = sp.random.normal(0, math.sqrt(sigma_c), C)

    sigma_e = (1 - h2_c - h2_r) / (h2_c + h2_r) * (
        rare.dot(beta_rare) + common.dot(beta_common)).var()
    noise = sp.random.normal(0, math.sqrt(sigma_e), N)
    noise < -noise / noise.std() * math.sqrt(sigma_e)

    beta = sp.append(beta_rare, beta_common)
    G = geno.dot(beta) + noise

    return G, common, rare, gamma, beta, sigma_r, sigma_c, sigma_e, sigma_b, b, w
Exemplo n.º 40
0
    def __init__(self, body_model, body_controller, final_height, max_velocity,
                 acceleration):
        logger.info("New path.",
                    path_name="TrapezoidalSitStand",
                    final_height=final_height,
                    max_velocity=max_velocity,
                    acceleration=acceleration)

        self.model = body_model
        self.controller = body_controller
        self.final_foot_positions = self.model.getFootPositions()
        self.feet_path = []

        for i in range(NUM_LEGS):
            self.final_foot_positions[i][2] = final_height

        for i in range(NUM_LEGS):
            self.feet_path = append(
                self.feet_path,
                TrapezoidalFootMove(self.model.getLegs()[i],
                                    self.controller.getLimbControllers()[i],
                                    self.final_foot_positions[i], max_velocity,
                                    acceleration))

        self.done = False
def on_click():
    f = file.File(inFile1, mode='r')
    ptcloud = np.vstack((f.x, f.y, f.z)).transpose()
    f.close()

    # Centred the data
    ptcloud_centred = ptcloud - np.mean(ptcloud, 0)

    # Simulate an intensity information between 0 and 1
    ptcloud_centred = sc.append(ptcloud_centred,
                                np.zeros((ptcloud.shape[0], 1)),
                                axis=1)  # Ajout d'une ligne (axis=0)
    for i in range(ptcloud_centred.shape[0] - 1):
        ptcloud_centred[i, 3] = random.random()

    p = pcl.PointCloud_PointXYZI()
    p.from_array(np.array(ptcloud_centred, dtype=np.float32))

    visual = pcl_visualization.CloudViewing()
    visual.ShowGrayCloud(p)

    def check_was_stopped():
        visual.WasStopped()

        root.after(100, check_was_stopped)

    check_was_stopped()
def coordinates_to_voxel_idx(coords_xyz, masker):
	# transform to homogeneous coordinates
	coords_h_xyz = sp.append(coords_xyz, ones([1,coords_xyz.shape[1]]),axis=0)
	
	# apply inverse affine transformation to get homogeneous coordinates in voxel space
	inv_transf = sp.linalg.inv(masker.volume.get_affine())
	coords_h_voxel_space = inv_transf.dot(coords_h_xyz)
	coords_h_voxel_space = sp.rint(coords_h_voxel_space).astype(int)
	
	# remove homogeneous dimension
	coords_voxel_space = coords_h_voxel_space[0:-1,:]
	
	# convert coordinates to idcs in a flattened voxel space
	flattened_idcs = sp.ravel_multi_index(coords_voxel_space, masker.dims)
	
	# check if there is any study data for the flattened idcs
	voxel_idcs = sp.zeros((1,len(flattened_idcs)),dtype=int64)
	for i in range(0,len(flattened_idcs)):
		idcs = find(masker.in_mask == flattened_idcs[i])
		if len(idcs > 0):
			voxel_idcs[0,i] = find(masker.in_mask == flattened_idcs[i])
		else:
			voxel_idcs[0,i] = nan
			
	return voxel_idcs
Exemplo n.º 43
0
 def orbitVel(self, r, t, antiCW):  #legacy
     #velocity for a circular orbit around body at vector r
     #Anticlockwise is default, enter -1 for clockwise
     v = sp.sqrt(G * self.mass / mag(self.orbitPos(t), r)) #mag v=(GM/R)^0.5
     rHat = sp.append(unitV(self.orbitPos(t), r), 0) #make it 3D
     vHat = antiCW * sp.cross(zHat, rHat)[:2] #return to 2D
     return v * vHat
Exemplo n.º 44
0
    def get_scan_nums_in_orderd_array(self):
        if len(self.scan_number_array) == 0:
            count = 0
            #print self.scan_list
            for i in self.scan_list:
                self.act_scan_number_array = sp.append(
                    self.act_scan_number_array, i)
                self.scan_number_array = sp.append(self.scan_number_array,
                                                   count)
                #print("i['retentionTime']")
                #print(self.scan_list[i]['retentionTime'])
                self.rt_arr = sp.append(self.rt_arr,
                                        self.scan_list[i]['retentionTime'])
                count += 1

            self.rt_arr.sort()
Exemplo n.º 45
0
def plot_delta():     
    beta = 0.99
    N = 1000
    u = lambda c: sp.sqrt(c)
    W = sp.linspace(0,1,N)
    X, Y = sp.meshgrid(W,W)
    Wdiff = sp.transpose(X-Y)
    index = Wdiff <0
    Wdiff[index] = 0
    util_grid = u(Wdiff)
    util_grid[index] = -10**10
    
    Vprime = sp.zeros((N,1))
    delta = sp.ones(1)
    tol = 10**-9
    it = 0
    max_iter = 500
    
    while (delta[-1] >= tol) and (it < max_iter):
        V = Vprime
        it += 1;
        print(it)
        val = util_grid + beta*sp.transpose(V)
        Vprime = sp.amax(val, axis = 1)
        Vprime = Vprime.reshape((N,1))
        delta = sp.append(delta,sp.dot(sp.transpose(Vprime - V),Vprime-V))
        
    plt.figure()
    plt.plot(delta[1:])
    plt.ylabel(r'$\delta_k$')
    plt.xlabel('iteration')
    plt.savefig('convergence.pdf')
Exemplo n.º 46
0
def GP_plotpred(xpred, x, y, cov_par, cov_func = None, cov_typ = 'SE',
             MF = None, MF_par = None, MF_args = None, MF_args_pred = None, \
             WhiteNoise = False, plot_color = None):
    '''
    Wrapper for GP_predict that takes care of merging the
    covariance and mean function parameters, and (optionally) plots
    the predictive distribution (as well as returning it)
    '''
    if MF != None:
        merged_par = scipy.append(cov_par, MF_par)
        n_MF_par = len(MF_par)
    else:
        merged_par = cov_par[:]
        n_MF_par = 0
    fpred, fpred_err = GP_predict(merged_par, xpred, x, y, \
                                  cov_func = cov_func, cov_typ = cov_typ, \
                                  MF = MF, n_MF_par = n_MF_par, \
                                  MF_args = MF_args, MF_args_pred = MF_args_pred, \
                                  WhiteNoise = WhiteNoise)
    xpl = scipy.array(xpred[:,0]).flatten()
    if plot_color != None:
        pylab.fill_between(xpl, fpred + 2 * fpred_err, fpred - 2 * fpred_err, \
                           color = plot_color, alpha = 0.1)
        pylab.fill_between(xpl, fpred + fpred_err, fpred - fpred_err, \
                           color = plot_color, alpha = 0.1)
        pylab.plot(xpl, fpred, '-', color = plot_color)
    return fpred, fpred_err
Exemplo n.º 47
0
def heun(f, u0, T, h):

    t0 = T[0]
    te = T[1]

    # Anfangswert ggf. auf Zeilenvektor transformieren
    u0 = array(u0).flatten()

    tv = t0
    uv = u0.T

    # eigentliches Verfahren
    t = t0
    u = u0

    ttol = 1e-8 * h

    while t < te:
        tn = t + h
        if tn > te - ttol:
            tn = te
            h = tn - t

    # Euler-Schritt
        un = u + h / 2 * (f(u, t) + f(u + h * f(u, t), tn))

        t = tn
        u = un

        tv = append(tv, t)
        uv = vstack((uv, u))
    return (uv, tv)
Exemplo n.º 48
0
def main():
    import pcl
    # laspy librairy, read las file
    f = file.File('28XXX10000075-18.las', mode='r')
    # Store pointcloud in array
    ptcloud = np.vstack((f.x, f.y, f.z)).transpose()
    f.close()

    # cloud = pcl.load('./examples/pcldata/tutorials/table_scene_mug_stereo_textured.pcd')
    # ptcloud = cloud.to_list()

    # Centred the data
    ptcloud_centred = ptcloud - np.mean(ptcloud, 0)

    # Simulate an intensity information between 0 and 1
    ptcloud_centred = sc.append(ptcloud_centred,
                                np.zeros((ptcloud.shape[0], 1)),
                                axis=1)
    for i in range(ptcloud_centred.shape[0] - 1):
        ptcloud_centred[i, 3] = random.random()

    p = pcl.PointCloud_PointXYZI()
    p.from_array(np.array(ptcloud_centred, dtype=np.float32))

    # Visualization
    visual = pcl_visualization.CloudViewing()
    visual.ShowGrayCloud(p, b'cloud')

    v = True
    while v:
        v = not (visual.WasStopped())
Exemplo n.º 49
0
def unique_rows(array, index = None, counts = False):
    """Make array unique by rows"""

    if array.shape[0] == 0:
        if index == True:
            return (array, [])
        else:
            return (array)

    if len(array.shape) == 1:
        if index == True:
            return (array, [0])
        else:
            return array

    (array_s, s_idx) = sort_rows(array, True)
    tmp = [False]
    tmp.extend([sp.all(array_s[i-1, :] == array_s[i, :]) for i in range(1, array.shape[0])])
    k_idx = sp.where(~sp.array(tmp, dtype='bool'))[0]

    if index == True:
        if counts:
            uidx = s_idx[k_idx]
            dist = sp.append((uidx[1:] - uidx[:-1]), array.shape[0] - uidx[-1])
            return (array[s_idx[k_idx], :], s_idx[k_idx], dist)
        else:
            return (array[s_idx[k_idx], :], s_idx[k_idx])
    else:
        return array[s_idx[k_idx], :]
Exemplo n.º 50
0
def clean(probs,
          deckSize,
          locked=[0, 1],
          maxNum=array([24, 60, 40, 30] + [10] * 10) * .7):
    if sum(probs) - sum(probs[locked]) == 0:
        return probs / sum(probs) if sum(probs) else array(probs)
    probs = probs / sum(probs)
    lockedProbs = probs[locked]
    probs *= deckSize
    probs = array([round(p) for p in probs])
    maxed = []
    maxedProbs = array([])
    for i in xrange(len(probs)):
        if probs[i] > maxNum[i] and i not in locked:
            maxed += [i]
            maxedProbs = append(maxedProbs, 1. * maxNum[i] / deckSize)
    if (sum(probs) - sum(probs[locked]) - sum(probs[maxed])) == 0:
        probs[locked] = lockedProbs
        probs[maxed] = maxedProbs
        return probs
    probs = probs / (sum(probs) - sum(probs[locked]) - sum(probs[maxed])) * (
        1 - sum(lockedProbs) - sum(maxedProbs))
    probs[locked] = lockedProbs
    probs[maxed] = maxedProbs
    if array([
            round(probs[i] * deckSize) > maxNum[i] for i in xrange(len(probs))
            if i not in locked
    ]).any():
        return clean(probs, deckSize, locked=locked + maxed)
    return probs
Exemplo n.º 51
0
def get_indices(code_country):
    indices_country = scipy.array(0)

    for i in code_country:
        tmp = c_shape_df[c_shape_df.COWCODE == i].index.tolist()
        indices_country = scipy.append(indices_country, tmp)
    return indices_country.reshape(len(indices_country), 1)
Exemplo n.º 52
0
def PathSPCA(A, k):
    M, N = A.shape
    # Loop through variables
    As = ((A * A).sum(axis=0))
    vmax = As.max()
    vp = As.argmax()
    subset = [vp]
    vars = []
    res = subset
    rhos = [(A[:, vp] * A[:, vp]).sum()]
    Stemp = array([rhos])
    for i in range(1, k):
        lev, v = la.eig(Stemp)
        vars.append(real(lev).max())
        vp = real(lev).argmax()
        x = dot(A[:, subset], v[:, vp])
        x = x / la.norm(x)
        seto = list(range(0, N))
        for j in subset:
            seto.remove(j)
        vals = dot(x.T, A[:, seto])
        vals = vals * vals
        rhos.append(vals.max())
        vpo = seto[vals.argmax()]
        Stemp = column_stack((Stemp, dot(A[:, subset].T, A[:, vpo])))
        vbuf = append(dot(A[:, vpo].T, A[:, subset]),
                      array([(A[:, vpo] * A[:, vpo]).sum()]))
        Stemp = row_stack((Stemp, vbuf))
        subset.append(vpo)
    lev, v = la.eig(Stemp)
    vars.append(real(lev).max())
    return vars, res, rhos
Exemplo n.º 53
0
def E_gliding(s_glide, V_glide, t=np.array([0]), E=np.array([0]), P_arr=np.array([0])):
    '''
    Calculates energy for gliding
    '''
    t_begin = t[-1]
    x = np.array([0])
    dt = 0.1
    
    while x[-1]<s_glide:
        
        x = np.append(x,x[-1]+V_glide*dt)
        E = np.append(E, E[-1]+E_sensors(dt))
        t = np.append(t,t[-1]+dt)
        P_arr = np.append(P_arr,25.25)
        
    return E, E[-1], t, t[-1]-t_begin, P_arr
Exemplo n.º 54
0
    def initialize(self, state, chain):
        params = {}
        for key in self.scan_range.keys():
            # Check for single range
            if len(self.scan_range[key]) == 2:
                params[key] = sp.rand() * (self.scan_range[key][1] - self.scan_range[key][0]) + self.scan_range[key][0]
            else:
                # calculate weights of sub_regions
                sub_size = sp.array([])
                # Determine weights of region
                for i in range(0, len(self.scan_range[key]), 2):
                    sub_size = sp.append(sub_size, self.scan_range[key][i + 1] - self.scan_range[key][i])
                    self.range_weight[key] = sub_size / float(sp.sum(sub_size))

                # sample region based on size
                i_sel = 2 * sp.searchsorted(sp.cumsum(self.range_weight[key]), sp.rand())
                # sample point
                params[key] = (
                    sp.rand() * (self.scan_range[key][i_sel + 1] - self.scan_range[key][i_sel])
                    + self.scan_range[key][i_sel]
                )

        # params=dict([(key,sp.rand()*(self.scan_range[key][1]-self.scan_range[key][0])+self.scan_range[key][0]) for key in self.scan_range.keys() if type(self.scan_range[key])==list])

        # Add constant parameters
        for key in self.constants.keys():
            params[key] = self.constants[key]

        for key in self.functions.keys():
            params[key] = self.functions[key](params)

        modelid = "%i%01i" % (self.rank, 0) + "%i" % chain.accepted

        return params, modelid
Exemplo n.º 55
0
def read_data(filename_, flag=True):
    """Reads the odometry and sensor readings from a file.
    
    Args:
        filename_: string containing file location
    
    Returns:
        output: A FburgData class which contains the odometry
        and/or sensor data
        
    Raises:
        NameError: incorrect filepath

    """
    output = {'sensor':[],'odometry':[]}
        
    data = scipy.genfromtxt(filename_, dtype='object')
    idx = scipy.squeeze(data[:,0] == 'ODOMETRY')
    for inp in data[idx,1:].astype(float):
        output['odometry'] += [{'r1':inp[0],
                                    't':inp[1],
                                    'r2':inp[2]}]

    idxarray = scipy.where(idx)
    idxarray = scipy.append(idxarray,[len(idx)])
    for i in xrange(len(idxarray) - 1):
        temp = []
        
        for j in scipy.arange(idxarray[i] + 1, idxarray[i + 1]):
            temp += [{'id':int(data[j,1]) - 1,
                      'range':float(data[j,2]),
                      'bearing':float(data[j,3])}]
                
        output['sensor'] += [temp]
    return output
Exemplo n.º 56
0
def nullSpaceBasis(A):
    """
    This funciton will find the basis of the null space of the matrix A.

    Inputs:
        A: The matrix you want the basis for
    Outputs:
        A numpy matrix containing the vectors as row vectors.

    Notes:
        If A is an empty matrix, an empty matrix is returned.

    """
    if A:
        U,s, Vh = la.svd(A)
        vecs = np.array([])
        toAppend = A.shape[1] -s.size
        s = sp.append(s,sp.zeros((1,toAppend)))
        for i in range(0,s.size):
            if s[i]==0:
                vecs = Vh[-toAppend:,:]
        if vecs.size ==0:
            vecs = sp.zeros((1,A.shape[1]))
        return sp.mat(vecs)
    else:
        return sp.zeros((0,0))
    def get_hand_props(self):
        """Initializes self.handarea [sqmeters], self.handrad [m], 
		self.handslope [-], and self.handstage [ft]"""
        # ************
        # This is the next big to-do item. Need to pass in hand_props file
        # (see details in 'mannings.py') and parse through with hand_props_idx
        # to collect data needed for querying mannings_n() on all xs discharges
        # for every stage-height for any given comid.
        # ************
        handc = self.hand_props.variables['COMID']
        handslope = self.hand_props.variables['Slope']  # So
        handstage = self.hand_props.variables[
            'StageHeight']  # h values for each Aw and Hr
        handarea = self.hand_props.variables['WetArea']  # Aw
        handrad = self.hand_props.variables['HydraulicRadius']  # Hr
        if handc[self.hand_props_idx] == self.comid:
            self.handarea = handarea[
                self.hand_props_idx] * 10.7639  # Convert sqm to sqft
            self.handrad = handrad[
                self.hand_props_idx] * 3.28084  # Convert m to ft
            self.handslope = handslope[self.hand_props_idx]  # unitless
        handstagenew = scipy.array([])
        for i in handstage:
            handstagenew = scipy.append(handstagenew, handstage)
        self.handstage = handstagenew
        self.handstage = self.handstage[:] * 3.28084  # Convert m to ft # cutoff - [:49]
        self.handstage = scipy.rint(
            self.handstage)  # Round to nearest int, to clean up conversion
Exemplo n.º 58
0
def plot_delta():     
    beta = 0.99
    N = 1000
    u = lambda c: sp.sqrt(c)
    W = sp.linspace(0,1,N)
    X, Y = sp.meshgrid(W,W)
    Wdiff = sp.transpose(X-Y)
    index = Wdiff <0
    Wdiff[index] = 0
    util_grid = u(Wdiff)
    util_grid[index] = -10**10
    
    Vprime = sp.zeros((N,1))
    delta = sp.ones(1)
    tol = 10**-9
    it = 0
    max_iter = 500
    
    while (delta[-1] >= tol) and (it < max_iter):
        V = Vprime
        it += 1;
        print(it)
        val = util_grid + beta*sp.transpose(V)
        Vprime = sp.amax(val, axis = 1)
        Vprime = Vprime.reshape((N,1))
        delta = sp.append(delta,sp.dot(sp.transpose(Vprime - V),Vprime-V))
        
    plt.figure()
    plt.plot(delta[1:])
    plt.ylabel(r'$\delta_k$')
    plt.xlabel('iteration')
    plt.savefig('convergence.pdf')