Example #1
0
def single_well_numerov_match(V0, dx, parity=1, overlapsize=5):
	"generate a candidate eigenfunction with given potential, assuming the potential well has a single allowed region bounded on both sides"
	assert len(V0) & 1, "Must have a grid with an odd number of points"
	vminchan=Numeric.argmin(V0) #position of bottom of well
	right_turn=Numeric.searchsorted(V0[vminchan:], 0.0)+vminchan #position of right-hand turning point

	#integrate from left end to right-hand turning point, at which point numerov method becomes unstable
	leftpsi=bare_numerov(V0[:right_turn], dx)
	#iterate backwards on right part to turning point, and flatten to normal array
	rightpsi= Numeric.array(bare_numerov(V0[right_turn-overlapsize:][::-1], dx)[::-1]) 
	
	#remember that since Numeric handles slices without copying, leftend and rightend also scale here
	slopeweight=Numeric.array(range(overlapsize),Numeric.Float)-overlapsize/2.0
	leftend=leftpsi[-overlapsize:]
	rightend=rightpsi[:overlapsize]
	
	scale=abs(Numeric.sum(leftend*rightend)/Numeric.sum(leftend**2)) #'least-squares' scale estimate
	#note that since leftend and rightend are Numeric slice references, modifying psi also changes them!
	rightpsi*=float(parity)/scale	
	error=Numeric.sum((leftend-rightend)*slopeweight) #average derivative
	psi0=Numeric.concatenate((leftpsi, rightpsi[overlapsize:]))

	psi2=psi0*psi0
	integral=psi2[0]+psi2[-1]+4.0*Numeric.sum(psi2[1:-1:2])+2.0*Numeric.sum(psi2[2:-2:2]) #use simpson's rule
	psimag=1.0/math.sqrt(integral*dx/3.0)
	
	return psi0*psimag, error*psimag
Example #2
0
 def recursive_remove_redundant_strains(self, cnd_entropy_matrix,
                                        cnd_entropy_sum_vector,
                                        no_of_strains_to_be_removed):
     strain_to_be_deleted_index_list = []
     if no_of_strains_to_be_removed > 0:
         strain_to_be_deleted = num.argmin(cnd_entropy_sum_vector)
         strain_to_be_deleted_index_list.append(strain_to_be_deleted)
         for i in range(cnd_entropy_sum_vector.shape[0]):  #remove
             cnd_entropy_sum_vector[i] -= cnd_entropy_matrix[
                 strain_to_be_deleted, i]
         cnd_entropy_sum_vector[
             strain_to_be_deleted] = cnd_entropy_matrix.shape[
                 0]  #set this deleted strain's cond entropy to maximum
         no_of_strains_to_be_removed -= 1
         if self.debug:
             print
             print 'strain_to_be_deleted:', strain_to_be_deleted
             print 'strain_to_be_deleted_index_list'
             print strain_to_be_deleted_index_list
             print 'cnd_entropy_sum_vector'
             print cnd_entropy_sum_vector
         strain_to_be_deleted_index_list += self.recursive_remove_redundant_strains(
             cnd_entropy_matrix, cnd_entropy_sum_vector,
             no_of_strains_to_be_removed)
     return strain_to_be_deleted_index_list
Example #3
0
    def input_numpy_array_output_geotiff(
        self,
        attribute_values_in_2d_array,
        prototype_dataset=None,
        format="GTiff",
        output_directory=None,
        output_file_name=None,
    ):
        """
        This method accepts numpy array objects, x, y and attribute_values and converts them to a GeoTiff image.

        twoD_attribute_values - 2d attribute values, could be return value from Dataset.get_2d_attribute();
        prototype_dataset - prototype dataset that includes the same projection and goetransform info,
                            must be in a format that can be opened by gdal.Open();
        format - default "GTiff" for GeoTiff format, possible options "PNG" and any other formats GDAL support;
        output_directory and output_file_name indicate where to save the output,
                            if unspecified, save to current directory and use time stamp as file name (without file extension).
        """

        import Numeric as numeric
        import gdal.gdal as gdal
        import gdal.gdalnumeric as gdalnumeric

        driver = gdal.GetDriverByName(format)

        tdata = numeric.array(attribute_values_in_2d_array.tolist())
        tdata = numeric.transpose(tdata)

        min_val = min(numeric.argmin(tdata))
        if min_val >= 0:
            null_substitute = -1
        else:
            null_substitute = min_val + min_val * 10

        for i in range(len(tdata)):
            for j in range(len(tdata[i])):
                if tdata[i][j] == 999999:
                    tdata[i][j] = null_substitute

        if prototype_dataset is not None:
            imgds = gdalnumeric.OpenArray(tdata,
                                          prototype_ds=prototype_dataset)
        else:
            imgds = gdalnumeric.OpenArray(tdata)

        if output_directory is None:
            output_directory = "."
        elif not os.path.exists(output_directory):
            os.mkdir(output_directory)

        if output_file_name is None:
            output_file_name = strftime("%Y_%m_%d_%H_%M.",
                                        localtime()) + format.lower()

        sfilename = os.path.join(output_directory, output_file_name)
        #try:
        imgds = driver.CreateCopy(sfilename, imgds)
Example #4
0
 def testSort (self):
     "Test sort, argsort, argmax, argmin, searchsorted"
     s = (3,2,5,1,4,0)
     sm = [s, Numeric.array(s)[::-1]]
     se = Numeric.array(s)[0:0]
     assert_eq(Numeric.sort(s), self.a)
     assert len(Numeric.sort(se)) == 0
     assert_eq(Numeric.argsort(s), [5,3,1,0,4,2])
     assert len(Numeric.argsort(se)) == 0
     assert_eq(Numeric.sort(sm, axis = -1), [[0,1,2,3,4,5],[0,1,2,3,4,5]])
     assert_eq(Numeric.sort(sm, axis = 0), [[0,2,1,1,2,0],[3,4,5,5,4,3]])
     assert_eq(Numeric.searchsorted(Numeric.arange(10), (5,2)), [5,2])
     assert Numeric.argmax(s) == 2
     assert Numeric.argmin(s) == 5
     assert_eq(Numeric.argmax(sm, axis=-1), [2,3])
     assert_eq(Numeric.argmax(sm, axis=1), [2,3])
     assert_eq(Numeric.argmax(sm, axis=0), [0,1,0,1,0,1])
     assert_eq(Numeric.argmin(sm, axis=-1), [5,0])
     assert_eq(Numeric.argmin(sm, axis=1), [5,0])
    def input_numpy_array_output_geotiff(self, attribute_values_in_2d_array,
                                      prototype_dataset=None,
                                      format="GTiff",
                                      output_directory=None,
                                      output_file_name=None,
                                      ):
        """
        This method accepts numpy array objects, x, y and attribute_values and converts them to a GeoTiff image.

        twoD_attribute_values - 2d attribute values, could be return value from Dataset.get_2d_attribute();
        prototype_dataset - prototype dataset that includes the same projection and goetransform info,
                            must be in a format that can be opened by gdal.Open();
        format - default "GTiff" for GeoTiff format, possible options "PNG" and any other formats GDAL support;
        output_directory and output_file_name indicate where to save the output,
                            if unspecified, save to current directory and use time stamp as file name (without file extension).
        """

        import Numeric as numeric
        import gdal.gdal as gdal
        import gdal.gdalnumeric as gdalnumeric

        driver = gdal.GetDriverByName(format)

        tdata = numeric.array(attribute_values_in_2d_array.tolist())
        tdata = numeric.transpose(tdata)
        
        min_val = min(numeric.argmin(tdata))
        if min_val >= 0:
            null_substitute = -1
        else:
            null_substitute = min_val + min_val * 10
            
        for i in range(len(tdata)):
            for j in range(len(tdata[i])):
                if tdata[i][j] == 999999:
                    tdata[i][j] = null_substitute
        
        if prototype_dataset is not None:
            imgds = gdalnumeric.OpenArray(tdata, prototype_ds=prototype_dataset)
        else:
            imgds = gdalnumeric.OpenArray(tdata)

        if output_directory is None:
            output_directory = "."
        elif not os.path.exists(output_directory):
            os.mkdir(output_directory)

        if output_file_name is None:
            output_file_name = strftime("%Y_%m_%d_%H_%M.", localtime()) + format.lower()

        sfilename = os.path.join(output_directory, output_file_name)
        #try:
        imgds = driver.CreateCopy( sfilename, imgds )
Example #6
0
def getDistance(V, X, mask):
    """
    d(V, X) = (1/|X|) Sum[i = 1 to |X|]{ min[j = 1 to |V|] {|| x_i - v_j||} }
    where x_i is in X and v_j is in V.  
    """
    min = []
    sum = 0
    for x in X:
        for v in V:
            min.append(euclideanDistance(x, v, mask))
        sum += min[Numeric.argmin(min)]
    return sum / len(X)
Example #7
0
File: ravq.py Project: is44c/Calico
def getDistance(V, X, mask):
    """
    d(V, X) = (1/|X|) Sum[i = 1 to |X|]{ min[j = 1 to |V|] {|| x_i - v_j||} }
    where x_i is in X and v_j is in V.  
    """
    min = []
    sum = 0
    for x in X:
        for v in V:
            min.append(euclideanDistance(x,v,mask))
        sum += min[Numeric.argmin(min)]
    return sum / len(X)
Example #8
0
    def findTransformationAsQuaternion(self, conf1, conf2 = None):
	if conf2 is None:
	    conf1, conf2 = conf2, conf1
        ref = conf1
        conf = conf2
        weights = self.universe().masses()
        weights = weights/self.mass()
        ref_cms = self.centerOfMass(ref).array
        pos = Numeric.zeros((3,), Numeric.Float)
        possq = 0.
        cross = Numeric.zeros((3, 3), Numeric.Float)
        for a in self.atomList():
            r = a.position(conf).array
            r_ref = a.position(ref).array-ref_cms
            w = weights[a]
            pos = pos + w*r
            possq = possq + w*Numeric.add.reduce(r*r) \
                          + w*Numeric.add.reduce(r_ref*r_ref)
            cross = cross + w*r[:, Numeric.NewAxis]*r_ref[Numeric.NewAxis, :]
        k = Numeric.zeros((4, 4), Numeric.Float)
        k[0, 0] = -cross[0, 0]-cross[1, 1]-cross[2, 2]
        k[0, 1] = cross[1, 2]-cross[2, 1]
        k[0, 2] = cross[2, 0]-cross[0, 2]
        k[0, 3] = cross[0, 1]-cross[1, 0]
        k[1, 1] = -cross[0, 0]+cross[1, 1]+cross[2, 2]
        k[1, 2] = -cross[0, 1]-cross[1, 0]
        k[1, 3] = -cross[0, 2]-cross[2, 0]
        k[2, 2] = cross[0, 0]-cross[1, 1]+cross[2, 2]
        k[2, 3] = -cross[1, 2]-cross[2, 1]
        k[3, 3] = cross[0, 0]+cross[1, 1]-cross[2, 2]
        for i in range(1, 4):
            for j in range(i):
                k[i, j] = k[j, i]
        k = 2.*k
        for i in range(4):
            k[i, i] = k[i, i] + possq - Numeric.add.reduce(pos*pos)
	import LinearAlgebra
	e, v = LinearAlgebra.eigenvectors(k)
	i = Numeric.argmin(e)
        v = v[i]
        if v[0] < 0: v = -v
	if e[i] <= 0.:
	    rms = 0.
	else:
	    rms = Numeric.sqrt(e[i])
        return Quaternion.Quaternion(v), Vector(ref_cms), \
               Vector(pos), rms
Example #9
0
	def recursive_remove_redundant_strains(self, cnd_entropy_matrix, cnd_entropy_sum_vector, no_of_strains_to_be_removed):
		strain_to_be_deleted_index_list = []
		if no_of_strains_to_be_removed>0:
			strain_to_be_deleted = num.argmin(cnd_entropy_sum_vector)
			strain_to_be_deleted_index_list.append(strain_to_be_deleted)
			for i in range(cnd_entropy_sum_vector.shape[0]):	#remove 
				cnd_entropy_sum_vector[i] -= cnd_entropy_matrix[strain_to_be_deleted,i]
			cnd_entropy_sum_vector[strain_to_be_deleted] = cnd_entropy_matrix.shape[0]	#set this deleted strain's cond entropy to maximum
			no_of_strains_to_be_removed -= 1
			if self.debug:
				print
				print 'strain_to_be_deleted:', strain_to_be_deleted
				print 'strain_to_be_deleted_index_list'
				print strain_to_be_deleted_index_list
				print 'cnd_entropy_sum_vector'
				print cnd_entropy_sum_vector
			strain_to_be_deleted_index_list += self.recursive_remove_redundant_strains(cnd_entropy_matrix, cnd_entropy_sum_vector, no_of_strains_to_be_removed)
		return strain_to_be_deleted_index_list
Example #10
0
File: ravq.py Project: is44c/Calico
 def updateWinner(self):
     """
     Calculate the current winner based on which model vector is
     closest to the moving average.
     """
     min = []
     for m in self.models:
         min.append(euclideanDistance(m.vector, self.movingAverage, self.mask))
     if min == []:
         self.winner = 'No Winner'
     else:
         self.previousWinnerIndex= self.newWinnerIndex
         self.newWinnerIndex = Numeric.argmin(min)
         if self.previousWinnerIndex == self.newWinnerIndex:
             self.winnerCount += 1
         else:
             self.winnerCount = 0
         winner = self.models[self.newWinnerIndex]
         winner.counter += 1
         #if winner.maxSize != -1:
         winner.addItem(self.buffer[0])
         self.winner = winner.vector
Example #11
0
 def updateWinner(self):
     """
     Calculate the current winner based on which model vector is
     closest to the moving average.
     """
     min = []
     for m in self.models:
         min.append(
             euclideanDistance(m.vector, self.movingAverage, self.mask))
     if min == []:
         self.winner = 'No Winner'
     else:
         self.previousWinnerIndex = self.newWinnerIndex
         self.newWinnerIndex = Numeric.argmin(min)
         if self.previousWinnerIndex == self.newWinnerIndex:
             self.winnerCount += 1
         else:
             self.winnerCount = 0
         winner = self.models[self.newWinnerIndex]
         winner.counter += 1
         #if winner.maxSize != -1:
         winner.addItem(self.buffer[0])
         self.winner = winner.vector
Example #12
0
    def __init__(self, trajectory, object, first=0, last=None, skip=1,
                 reference = None):
        self.trajectory = trajectory
        universe = trajectory.universe
        if last is None: last = len(trajectory)
        first_conf = trajectory.configuration[first]
        offset = universe.contiguousObjectOffset([object], first_conf, 1)
        if reference is None:
            reference = first_conf
        reference = universe.contiguousObjectConfiguration([object],
                                                           reference)
        steps = (last-first+skip-1)/skip
        mass = object.mass()
        ref_cms = object.centerOfMass(reference)
        atoms = object.atomList()

        possq = Numeric.zeros((steps,), Numeric.Float)
        cross = Numeric.zeros((steps, 3, 3), Numeric.Float)
        rcms = Numeric.zeros((steps, 3), Numeric.Float)

        # cms of the CONTIGUOUS object made of CONTINUOUS atom trajectories 
        for a in atoms:
            r = trajectory.readParticleTrajectory(a, first, last, skip,
                                                  "box_coordinates").array
            w = a._mass/mass
            Numeric.add(rcms, w*r, rcms)
            if offset is not None:
                Numeric.add(rcms, w*offset[a].array, rcms)
        
        # relative coords of the CONTIGUOUS reference
        r_ref = Numeric.zeros((len(atoms), 3), Numeric.Float)
        for a in range(len(atoms)):
            r_ref[a] = atoms[a].position(reference).array - ref_cms.array

        # main loop: storing data needed to fill M matrix 
        for a in range(len(atoms)):
            r = trajectory.readParticleTrajectory(atoms[a],
                                                  first, last, skip,
                                                  "box_coordinates").array
            r = r - rcms # (a-b)**2 != a**2 - b**2
            if offset is not None:
                Numeric.add(r, offset[atoms[a]].array,r)
            trajectory._boxTransformation(r, r)
            w = atoms[a]._mass/mass
            Numeric.add(possq, w*Numeric.add.reduce(r*r, -1), possq)
            Numeric.add(possq, w*Numeric.add.reduce(r_ref[a]*r_ref[a],-1),
                        possq)
            Numeric.add(cross, w*r[:,:,Numeric.NewAxis]*r_ref[Numeric.NewAxis,
                                                              a,:],cross)
        self.trajectory._boxTransformation(rcms, rcms)

        # filling matrix M (formula no 40)
        k = Numeric.zeros((steps, 4, 4), Numeric.Float)
        k[:, 0, 0] = -cross[:, 0, 0]-cross[:, 1, 1]-cross[:, 2, 2]
        k[:, 0, 1] = cross[:, 1, 2]-cross[:, 2, 1]
        k[:, 0, 2] = cross[:, 2, 0]-cross[:, 0, 2]
        k[:, 0, 3] = cross[:, 0, 1]-cross[:, 1, 0]
        k[:, 1, 1] = -cross[:, 0, 0]+cross[:, 1, 1]+cross[:, 2, 2]
        k[:, 1, 2] = -cross[:, 0, 1]-cross[:, 1, 0]
        k[:, 1, 3] = -cross[:, 0, 2]-cross[:, 2, 0]
        k[:, 2, 2] = cross[:, 0, 0]-cross[:, 1, 1]+cross[:, 2, 2]
        k[:, 2, 3] = -cross[:, 1, 2]-cross[:, 2, 1]
        k[:, 3, 3] = cross[:, 0, 0]+cross[:, 1, 1]-cross[:, 2, 2]
        del cross
        for i in range(1, 4):
            for j in range(i):
                k[:, i, j] = k[:, j, i]
        Numeric.multiply(k, 2., k)
        for i in range(4):
            Numeric.add(k[:,i,i], possq, k[:,i,i])
        del possq

        quaternions = Numeric.zeros((steps, 4), Numeric.Float)
        fit = Numeric.zeros((steps,), Numeric.Float)
	import LinearAlgebra
        for i in range(steps):
            e, v = LinearAlgebra.eigenvectors(k[i])
            j = Numeric.argmin(e)
            if e[j] < 0.:
                fit[i] = 0.
            else:
                fit[i] = Numeric.sqrt(e[j])
            if v[j,0] < 0.: quaternions[i] = -v[j] # eliminate jumps
            else: quaternions[i] = v[j]
        self.fit = fit
        self.cms = rcms
        self.quaternions = quaternions
Example #13
0
 else:
   x2=Numeric.take(var_list,inds2)
   y2=Numeric.take(var2_list,inds2)  
   g.itemlist.append(Gnuplot.Data(x2,y2,with='points 2 1',title='{/Symbol G}_{max}> %g'%ref_g))
 for i in range(len(matching)):
   if matching[i].data['num']==ref:
     ref_ind = i
     break
 minx = min(var_list)
 maxx = max(var_list)
 g('set xrange [%g:%g]'%(minx,maxx))
 if var_key=='epsVz' and var_key2=='Vz0':
   xl = Numeric.arange(minx-abs(minx)*2,maxx+abs(maxx)*2,.01)
   g.itemlist.append(Gnuplot.Data(xl,2./abs(xl),with='lines'))
   if wb==None:
     indmin=Numeric.argmin(matching[ref_ind].evals.imag)
     wb=matching[ref_ind].evals[indmin].real
   print wb
   data = matching[ref_ind].data
   g.itemlist.append(Gnuplot.Data(xl,abs(wb)/abs(data['k']*(1-xl*r0**2)),with='lines'))
 g.refresh()
 ttl = ''
 for tt1 in tt:
   ttl=ttl+'%s=%g, '%(tt1,matching[ref_ind].data[tt1])
 ttl = ttl[:-2]
 if notitle==False:
   g.title(ttl)#'V_z(r=a)=%g'%matching[0].Vz([matching[0].data['a']]))
 else:
   g('unset title')
 fn = 'plots/%d_%s_%s_stability_boundary.eps'%(min([mat.data['num'] for mat in matching]),var_key,var_key2)
 print 'Output to %s'%fn
      evec_num = int(round(evec_num+eimag/abs(eimag)))
    else:
      EV.imag = True
      del EV.sevecs  
    (y1,yl)  = EV.get_evec1(coord,evec_num,x)
    acoef = EV.get_EVrot(minr=minr,maxr=maxr)
    y2 = (acoef*y+1j*acoef*y1).real
    y3 = (acoef*y+1j*acoef*y1).imag
    #print acoef, y[-1],y1[-1],y2[-1],y3[-1]
    norm = EV.get_EVnorm()
    y2 = y2*norm
    y3 = y3*norm
    amp.append(1./((max(y2)+abs(min(y2)))/2.))
    try:
      x_zero = x[Numeric.nonzero(y2[1:]*y2[:-1]<0)[0]]
      ind = Numeric.argmin(Numeric.absolute(EV.grid-x_zero))
      zero.append(EV.grid[ind])
    except:
      zero.append(0)
    dr = Gnuplot.Data(x,y2,title='Re',with='lines 3')
    di =  Gnuplot.Data(x,y3,title='Im',with='lines 2')  
    inds = Numeric.nonzero((EV.grid>=minx)*(EV.grid<=maxx))
    dg = Gnuplot.Data(Numeric.take(EV.grid,inds),0*inds,with='points 1',title='Grid')
    d[-1]=[dg,dr,di]
    if 'nolegend' in sys.argv:
      for i in range(len(d[-1])):
        d[-1][i].set_option(title=None)
    EV.imag=False

fn = 'plots/%g_var_%s_evec%s_%dunstable.eps'%(num0,var_key,coord,unst_ind)
if 'xr' in sys.argv:
Example #15
0
                               d=d,
                               nomatch_keys=get_EV.get_numeric_nomatch_keys() +
                               [var_key, var_key2])
var_list = []
var2_list = []
min_eval = []
nums = []
for i in range(len(matching)):
    var_list.append(matching[i].data[var_key])
    var2_list.append(matching[i].data[var_key2])
    nums.append(matching[i].num)
    evals = matching[i].evals
    if 'neg' in sys.argv:
        inds = Numeric.nonzero(evals.real < 1e-5)
        evals = Numeric.take(evals, inds)
    ind = Numeric.argmin(evals.imag)
    min_eval.append(evals[ind].real)
print nums
for u2 in Numeric.sort(list(sets.Set(var2_list))):
    inds = Numeric.nonzero(Numeric.array(var2_list) == u2)
    v1 = Numeric.take(var_list, inds)
    ev1 = Numeric.take(min_eval, inds)
    d1 = matching[inds[0]]
    g.itemlist.append(
        Gnuplot.Data(v1, ev1, title='%s=%g' % (var_key2, d1.data[var_key2])))
    g.itemlist.append(
        Gnuplot.Data(v1,
                     d1.data['k'] *
                     Numeric.array([matching[j].Vz([r0])[0] for j in inds]) +
                     ev1[0] - d1.data['k'] * d1.Vz([r0]),
                     title='V_z(r=%g)' % r0))