def setData(self, *args): if len(args) == 3: self.locns, self.vals, self.sigs = args if len(locns) != len(vals) or len(vals) != len(sigs): raise DataError, 'Mismatch in lengths of arguments!' elif len(args) == 1: all = args[0] try: rows, cols = all.shape self.locns = all[:,0] self.vals = all[:,1] self.sigs = all[:,2] except AttributeError: # If *all* is not an array, treat it as a list. # Only the list format can handle >1-d locns using # a single setData argument. self.locns, self.vals, self.sigs = [], [], [] for row in all: self.locns.append(row[0]) self.vals.append(row[1]) self.sigs.append(row[2]) self.locns = array(self.locns) self.vals = array(self.vals) self.sigs = array(self.sigs) except: raise DataError, 'Bad data array format!' self.ndata = len(vals) if len(self.locns.shape) == 1: self.dimen = 1 elif len(self.locns.shape) ==2: self.dimen = self.locns.shape[1] else: raise DataError, 'Locations should be scalars or 1-d arrays!'
def setData(self, *args): if len(args) == 3: self.locns, self.vals, self.sigs = args if len(locns) != len(vals) or len(vals) != len(sigs): raise DataError, 'Mismatch in lengths of arguments!' elif len(args) == 1: all = args[0] try: rows, cols = all.shape self.locns = all[:, 0] self.vals = all[:, 1] self.sigs = all[:, 2] except AttributeError: # If *all* is not an array, treat it as a list. # Only the list format can handle >1-d locns using # a single setData argument. self.locns, self.vals, self.sigs = [], [], [] for row in all: self.locns.append(row[0]) self.vals.append(row[1]) self.sigs.append(row[2]) self.locns = array(self.locns) self.vals = array(self.vals) self.sigs = array(self.sigs) except: raise DataError, 'Bad data array format!' self.ndata = len(vals) if len(self.locns.shape) == 1: self.dimen = 1 elif len(self.locns.shape) == 2: self.dimen = self.locns.shape[1] else: raise DataError, 'Locations should be scalars or 1-d arrays!'
def add_shadow(image, shadow_offset, shadow_scale=None, ambience=None): """Return a copy of image with a shadow added. image - a surface with or without alpha or colorkey. shadow_offset - (dx, dy) amount, in pixel, to shift shadow center relative to image center. shadow_scale (optional) - amount by which to scale the shadow. defaults to 1.0 (no scaling). ambience (optional) - 0.0 to 1.0: Ambient light ratio. 0.0 gives a totally black shadow while 1.0 gives no shadow. Defaults to 0.0 . """ if (image.get_flags() & pygame.SRCALPHA or image.get_colorkey() is not None): shadow = make_shadow(image, ambience) if shadow_scale is not None: a = array(shadow.get_size(), float32) size = (a * shadow_scale).astype(int32) shadow = pygame.transform.smoothscale(shadow, size) else: size = (array(image.get_size(), float32) * shadow_scale).astype(int32) if shadow_scale is None: shadow_scale = 1.0 shadow = make_shadow_opaque(size, ambience, image.get_bitsize()) return place_shadow(image, shadow, shadow_offset)
def test_pairs_to_array(self): """pairs_to_array should match hand-calculated results""" p2a = pairs_to_array p1 = [0, 1, 0.5] p2 = [2, 3, 0.9] p3 = [1, 2, 0.6] pairs = [p1, p2, p3] self.assertEqual(p2a(pairs), \ array([[0,.5,0,0],[0,0,.6,0],[0,0,0,.9],[0,0,0,0]])) #try it without weights -- should assign 1 new_pairs = [[0,1],[2,3],[1,2]] self.assertEqual(p2a(new_pairs), \ array([[0,1,0,0],[0,0,1,0],[0,0,0,1],[0,0,0,0]])) #try it with explicit array size self.assertEqual(p2a(pairs, 5), \ array([[0,.5,0,0,0],[0,0,.6,0,0],[0,0,0,.9,0],[0,0,0,0,0],\ [0,0,0,0,0]])) #try it when we want to map the indices into gapped coords #we're effectively doing ABCD -> -A--BC-D- transform = array([1,4,5,7]) result = p2a(pairs, transform=transform) self.assertEqual(result.shape, (8,8)) exp = zeros((8,8), Float64) exp[1,4] = 0.5 exp[4,5] = 0.6 exp[5,7] = 0.9 self.assertEqual(result, exp) result = p2a(pairs, num_items=9, transform=transform) self.assertEqual(result.shape, (9,9)) exp = zeros((9,9), Float64) exp[1,4] = 0.5 exp[4,5] = 0.6 exp[5,7] = 0.9 self.assertEqual(result, exp)
def __call__(self,action=None): if action==None: self.angle = self.initial_angle self.velocity = self.initial_velocity return array((self.angle,self.velocity)) else: if type(action) == ArrayType: action = action[0] self.last_action = action # setup constants m = self.mass g = self.g l = self.length dt = self.delta_t # Gravitational torque T_g = m * g * l * cos(pi/2-self.angle) # action torque T_a = action # rotational acceleration is Torque divided by moment-of-inertia a = (T_g + T_a)/(m*l) # update velocity from acceleration (including friction) self.velocity += (a * dt) self.velocity -= self.velocity * self.friction # update angle from velocity self.angle += (self.velocity * dt)/2 return (array((normalize_angle(self.angle),self.velocity)),self.reward())
def __init__(self, *args, **kwargs): Visualiser.__init__(self, *args, **kwargs) fin = NetCDFFile(self.vis_source, 'r') self.xPoints = array(fin.variables['x'], Float) self.yPoints = array(fin.variables['y'], Float) self.quantityCache = {} fin.close()
def test_toOddsMatrix(self): """toOddsMatrix: should work on valid data or raise an error """ p = Profile(array([[.1,.3,.5,.1],[.25,.25,.25,.25],\ [.05,.8,.05,.1],[.7,.1,.1,.1],[.6,.15,.05,.2]]),\ Alphabet="ACTG") p_exp = Profile(array([[.4, 1.2, 2, .4],[1,1,1,1],[.2,3.2,.2,.4],\ [2.8,.4,.4,.4],[2.4,.6,.2,.8]]),Alphabet="ACTG") self.assertEqual(p.toOddsMatrix().Data,p_exp.Data) assert p.Alphabet is p.toOddsMatrix().Alphabet self.assertEqual(p.toOddsMatrix([.25,.25,.25,.25]).Data,p_exp.Data) #fails if symbol_freqs has wrong size self.assertRaises(ProfileError, p.toOddsMatrix,\ [.25,.25,.25,.25,.25,.25]) self.assertRaises(ProfileError, self.zero_entry.toOddsMatrix,\ [.1,.2,.3]) #works on empty profile self.assertEqual(self.empty.toOddsMatrix().Data.tolist(),[[]]) #works with different input self.assertEqual(self.zero_entry.toOddsMatrix().Data,\ array([[1.2,.8,0,2],[0,0,3.2,.8]])) self.assertFloatEqual(self.zero_entry.toOddsMatrix([.1,.2,.3,.4]).Data,\ array([[3,1,0,1.25],[0,0,2.667,.5]]),1e-3) #fails when one of the background frequencies is 0 self.assertRaises(ProfileError, self.zero_entry.toOddsMatrix,\ [.1,.2,.3,0])
def test__add_(self): """__add__: should not normalize input or output, just add""" p1 = Profile(array([[.3,.4,.1,0],[.1,.1,.1,.7]]),Alphabet="ABCD") p2 = Profile(array([[1,0,0,0],[1,0,0,1]]),Alphabet="ABCD") self.assertEqual((p1+p2).Data, array([[1.3,.4,.1,0],[1.1,.1,.1,1.7]])) self.assertRaises(ProfileError,self.empty.__add__, p1) self.assertEqual((self.empty + self.empty).Data.tolist(),[[]])
def test_score_profile(self): """score: should work correctly for Profile as input """ p1 = Profile(array([[1,0,0,0],[0,1,0,0],[0,0,.5,.5],[0,0,0,1],\ [.25,.25,.25,.25]]),"TCAG") p2 = Profile(array([[0,1,0,0],[.2,0,.8,0],[0,0,.5,.5],[1/3,1/3,0,1/3],\ [.25,.25,.25,.25]]),"TCAG") p3 = Profile(array([[1,0,0,0],[0,1,0,0],[0,0,0,1]]),"TCAG") p4 = Profile(array([[1,0,0,0],[0,1,0,0]]),"TCAG") p5 = Profile(array([[1,0,0,0],[0,1,0,0],[0,0,0,1]]),"AGTC") #works on normal valid data self.assertFloatEqual(self.score2.score(p1,offset=0),\ [.55,1.25,.45]) self.assertFloatEqual(self.score2.score(p2,offset=0), [1.49,1.043,.483],1e-3) #works with different offset self.assertFloatEqual(self.score2.score(p1,offset=1), [1.25,0.45]) self.assertFloatEqual(self.score2.score(p1,offset=2), [0.45]) #raises error on invalid offset self.assertRaises(ProfileError,self.score2.score,\ p1,offset=3) #works on profile of minimal length self.assertFloatEqual(self.score2.score(p3,offset=0), [0.6]) #raises error when profile is too short self.assertRaises(ProfileError, self.score2.score,p4,offset=0) #raises error on empty profile self.assertRaises(ProfileError,self.empty.score,p1) #raises error when character order doesn't match self.assertRaises(ProfileError,self.score2.score,p5)
def distance_to_closest(alignment, distance_method=hamming_distance): """Returns vector of distances to closest neighbor for each s in alignment alignment: Alignment object distance_method: function used to calculate the distance between two seqs Function returns the closest distances according to the RowOrder in the alignment example: Alignment({1:'ABCD',2:'ABCC',3:'CBDD',4:'ACAA'},RowOrder=[3,2,1,4]) [2,1,1,3] """ #change sequences into arrays for item in alignment: alignment[item] = array(alignment[item]) closest = [] for key in alignment.RowOrder: seq = alignment[key] dist = None for other_key in alignment.RowOrder: if key == other_key: continue d = distance_method(seq,alignment[other_key]) if dist: if d < dist: dist = d else: dist = d closest.append(dist) return array(closest)
def test4(): test = HMM(['a','b'],['s1','s2','s3'], array([[.3,.5],[.7,.5]]), array([[.5,0],[.5,.5],[0,.5]]), array([.9,.1])) print test.simulate(10) print test.simulate(10,1)
def runtest(t): tname = t.__doc__.split()[0] if tname in ['t0', 't1', 's0', 's1']: assert t(23) == '2' r = t('ab') assert r == 'a', ` r ` r = t(array('ab')) assert r == 'a', ` r ` r = t(array(77, '1')) assert r == 'M', ` r ` try: raise RuntimeError, ` t(array([77, 87])) ` except ValueError: pass try: raise RuntimeError, ` t(array(77)) ` except ValueError: pass elif tname in ['ts', 'ss']: assert t(23) == '23 ', ` t(23) ` assert t('123456789abcdef') == '123456789a' elif tname in ['t5', 's5']: assert t(23) == '23 ', ` t(23) ` assert t('ab') == 'ab ', ` t('ab') ` assert t('123456789abcdef') == '12345' else: raise NotImplementedError
def __init__(self, stacks, position): """ Pass a reference to the stacks object that holds all the blocks and the index of the initial stack of the block """ Block.__init__(self, stacks, position) self.box = box(pos=(position-(stacks.blockCount/2), 0, 0), size=(.9,.9,.9), color=color.blue) self.label = label(pos=array(self.box.pos) + array([0,0,1]), text=str(position), opacity=0, box=0, line=0)
def distance(self,other): """Calculates the distance between two BaseUsages. Distance is measured in three directions, CG-content, CU-content, and GU-content. """ return euclidean_distance(array(self.toCartesian()),\ array(other.toCartesian()))
def testAngleBetween(self): vector1 = array((1, 0, 0)) vector2 = array((0, 1, 0)) angle = angleBetween(vector1, vector2) assert angle == 90, "Fails sanity check" assert alltrue(vector1 == array((1, 0, 0))) and \ alltrue(vector2 == array((0, 1, 0))), \ "Arguments were modified (recurrence of bug ####)"
def test_unmasked_to_masked(self): """unmasked_to_masked should match hand-calculated results""" u2m = unmasked_to_masked self.assertEqual(u2m(self.m1), array([0,1,2,4])) self.assertEqual(u2m(self.m2), array([2,3])) self.assertEqual(u2m(self.m3), array([0,1])) self.assertEqual(u2m(self.m4), array([0,1])) self.assertEqual(u2m(self.m5), array([]))
def test_ungapped_to_gapped(self): """ungapped_to_gapped should match hand-calculated results""" u2g = ungapped_to_gapped self.assertEqual(u2g(self.s1, '-'), array([0,1,2,4])) self.assertEqual(u2g(self.s2, '-'), array([2,3])) self.assertEqual(u2g(self.s3, '-'), array([0,1])) self.assertEqual(u2g(self.s4, '-'), array([0,1])) self.assertEqual(u2g(self.s5, '-'), array([]))
def setUp(self): """setUp for all CenterOfMass tests""" self.simple = array([[1,1,1],[3,1,1],[2,3,2]]) self.simple_list = [[1,1,1],[3,1,1],[2,3,2]] self.more_weight = array([[1,1,3],[3,1,3],[2,3,50]]) self.square = array([[1,1,25],[3,1,25],[3,3,25],[1,3,25]]) self.square_odd = array([[1,1,25],[3,1,4],[3,3,25],[1,3,4]]) self.sec_weight = array([[1,25,1],[3,25,1],[3,25,3],[1,25,3]])
def test_center_of_mass_two_array(self): """center_of_mass_two_array should behave correctly""" com2 = center_of_mass_two_array coor = take(self.square_odd,(0,1),1) weights = take(self.square_odd,(2,),1) self.assertEqual(com2(coor,weights), array([2,2])) weights = weights.flat self.assertEqual(com2(coor,weights), array([2,2]))
def test_euclidean_distance(self): """euclidean_distance: should return dist between 2 vectors or matrices """ a = array([3,4]) b = array([8,5]) c = array([[2,3],[4,5]]) d = array([[1,5],[8,2]]) self.assertFloatEqual(euclidean_distance(a,b),sqrt(26)) self.assertFloatEqual(euclidean_distance(c,d),sqrt(30))
def hermite(x0, x1, v0, v1, t): a = array([1, t, t**2, t**3]) M = array([[1, 0, 0, 0], [1, 1, 1, 1], [0, 1, 0, 0], [0, 1, 2, 3]]) p = transpose([[x0, x1, v0, v1]]) return dot(dot(a, inverse(M)), p)
def optimize(self): """Optimize the objective function with respect to varying params.""" p, d = [], [] for param in self.varyingParams: p.append(param.getValue()) d.append(param.delta) p = array(p) d = identity(len(d)) * array(d,Float) return powell(self._objective, p, drxns=d)
def __init__(self, x, y=None, z=None): if y is None and z is None: # Array, list, tuple... if len(x)!=3: raise "Vector: x is not a list/tuple/array of 3 numbers" self._ar=array(x, 'd') else: # Three numbers self._ar=array((x, y, z), 'd')
def test_distance_matrix(self): """distance_matrix should obey RowOrder of alignment""" #RowOrder=None aln1_exp = array([[0,2,2],[2,0,1],[2,1,0]]) self.assertEqual(distance_matrix(self.aln1),aln1_exp) a = Alignment(self.aln1.copy()) a.RowOrder=[1,2,0] a_exp = array([[0,1,2],[1,0,2],[2,2,0]]) self.assertEqual(distance_matrix(a),a_exp)
def learn_batch(self,data): X = array([x for x,y in data]) Y = array([y for x,y in data]) if self.use_bias: X = join((X,ones((len(X),1))),axis=1) W,residuals,rank,s = linear_least_squares(X,Y) self.w = W
def learn_batch(self, data): X = array([x for x, y in data]) Y = array([y for x, y in data]) if self.use_bias: X = join((X, ones((len(X), 1))), axis=1) W, residuals, rank, s = linear_least_squares(X, Y) self.w = W
def get_trial_avg(trial_data,step=1): from Numeric import concatenate,array,transpose from plastk.utils import stats trial_data = get_trial_data(trial_data,step) indices = trial_data[0][:,0] data = array([x[:,1] for x in trial_data]) mean,var,stderr = stats(data) return transpose(array((indices, mean,stderr)))
def fingerprint(self, which_blocks='quartets', include_mean=True,\ normalize=True): """Returns fingerprint data for fingerprint plots. which_blocks: whether to include only the usual 4-codon quartets (the default), the split blocks only, or all blocks. include_mean: whether to include the mean (True). normalize: whether to normalize so that the quartets sum to 1 (True) """ if which_blocks == 'split': blocks = self.SplitBlocks elif which_blocks == 'quartets': blocks = self.SingleAABlocks elif which_blocks == 'all': blocks = self.Blocks else: raise "Got invalid option %s for which_blocks:\n" % which_blocks+\ " (valid options: 'split', 'quartets', 'all')." result = [] for b in blocks: #iterates over doublet string U, C, A, G = [self[b+i] for i in 'UCAG'] all = U+C+A+G if G+C: g_ratio = G/(G+C) else: g_ratio = 0.5 if A+U: a_ratio = A/(A+U) else: a_ratio=0.5 result.append([g_ratio, a_ratio, all]) result = array(result) if normalize: #make the shown bubbles sum to 1 sum_ = sum(result[:,-1]) if sum_: result[:,-1] /= sum_ if include_mean: #calculate mean from all codons third = self.positionalBases().Third U, C, A, G = [third[i] for i in 'UCAG'] if G+C: g_ratio = G/(G+C) else: g_ratio = 0.5 if A+U: a_ratio = A/(A+U) else: a_ratio=0.5 result = concatenate((result, array([[g_ratio,a_ratio,1]]))) return result
def setUp(self): self.tables = [('./data/1.dat', 'ASCII', Table(array([[1,2,3],[2,4,8],[3,9,27],[4,16,64]],'d')) ), ('./data/2.dat', 'ASCII', Table(array([[1,1,1],[2,2,2],[3,3,3]],'d')) ), ('./data/3.dat', 'ASCII', Table(array([[1,1,1],[2,2,2],[3,3,3]],'d')) ) ]
def test_columnUncertainty(self): """columnUncertainty: should handle full and empty profiles """ p = Profile(array([[.25,.5],[.25,.5],[.25,0],[.25,0]]),"AB") self.assertEqual(p.columnUncertainty(),[2,1]) #for empty cols nothing is returned as the uncertainty self.assertEqual(self.empty.columnUncertainty().tolist(),[]) p = Profile(array([[],[],[]]),"") self.assertEqual(p.columnUncertainty().tolist(),[]) #doesn't work on 1D array self.assertRaises(ProfileError,self.oned.columnUncertainty)
def test_reduce_normalization_error(self): """reduce: fails when input or output can't be normalized""" #Will raise errors when input data can't be normalized self.assertRaises(ProfileError,self.empty.reduce,self.empty,add) self.assertRaises(ProfileError,self.full.reduce,self.empty_row,add) #don't normalize input, but do normalize output #fails when one row adds up to zero p1 = Profile(array([[3,3],[4,4]]),"AB") p2 = Profile(array([[3,3],[-4,-4]]),"AB") self.assertRaises(ProfileError,p1.reduce,p2,add,False,True)
def makeArray(shape, typecode): if typecode == 'D': res = zeros(shape, typecode) res.imag = (rand(*shape) - 0.5) * 100 res.real = (rand(*shape) - 0.5) * 100 # XXX cheat for the small integer types to avoid overflows and hassles elif typecode in '1bw': res = array((rand(2,2)) * 10) else: res = array((rand(*shape) - 0.5) * 100).astype(typecode) return res
def grindPOD (xd) : helpMe('1', xd) helpMe('b', xd) helpMe('s', xd) helpMe('w', xd) v1 = helpMe('i', xd) helpMe('u', xd) helpMe('l', xd) # helpMe('l', xd) helpMe('f', xd) v2 = helpMe('d', xd) helpMe('F', xd) helpMe('D', xd) t = { } t["int_4"] = v1 t["real_4"] = v2 vv = { } vv["data"] = t sys.stdout.write("As normal:") pretty(vv) print print "As XML:" xd.XMLDumpKeyValue("top",vv) print # make sure we can put in lists a = [ ] a.append(v1); a.append(v2); v = { } v["data"] = a sys.stdout.write("As normal:") pretty(v) print print "As XML:" xd.XMLDumpKeyValue("top",v) print vvv = { 'top':{ 'int_4':[ array([1,2,3], 'i'), array([1.0,2.0,3.0], 'd') ] } } sys.stdout.write("As normal:") pretty(vvv) print pretty(vvv) print "As XML:" xd.XMLDumpValue(vvv) print
def test_hasValidAttributes(self): """hasValidAttributes: should work for different alphabets/char orders """ p = Profile(array([[1,2],[3,4]]),Alphabet="ABCD", CharOrder="BAC") #self.Data doesn't match len(CharOrder) self.assertEqual(p.hasValidAttributes(),False) p = Profile(array([[1,2],[3,4]]),Alphabet="ABCD", CharOrder="AX") #not all chars in CharOrder in Alphabet self.assertEqual(p.hasValidAttributes(),False) p = Profile(array([[1,2],[3,4]]),Alphabet="ABCD", CharOrder="CB") #should be fine self.assertEqual(p.hasValidAttributes(),True)
def test_rowUncertainty(self): """rowUncertainty: should handle full and empty profiles """ p = Profile(array([[.25,.25,.25,.25],[.5,.5,0,0]]),"ABCD") self.assertEqual(p.rowUncertainty(),[2,1]) #for empty rows 0 is returned as the uncertainty self.assertEqual(self.empty.rowUncertainty().tolist(),[]) p = Profile(array([[],[],[]]),"") self.assertEqual(p.rowUncertainty().tolist(),[]) #doesn't work on 1D array self.assertRaises(ProfileError,self.oned.rowUncertainty)
def test__score_indices(self): """_score_indices: should work on valid input""" self.assertEqual(self.score1._score_indices(array([0,1,1,3,0,3]),\ offset=0),[6,2,-3,0]) self.assertFloatEqual(self.score2._score_indices(\ array([3,1,2,0,2,2,3]), offset=0),[.3,1.4,.8,1.4,1.7]) self.assertFloatEqual(self.score2._score_indices(\ array([3,1,2,0,2,2,3]), offset=3),[1.4,1.7]) #Errors will be raised on invalid input. Errors are not handled #in this method. Validation of the input is done elsewhere self.assertRaises(IndexError,self.score2._score_indices,\ array([3,1,63,0,4,2,3]), offset=3)
def initsolver(self, tol=1e-8, hbsize=10000, dt=0.1, statescale=array([0.0])): ''' Sets the tolerance, buffer size, initial step size and a scaling parameter to help deal with states close to 0. Arguments: tol = 0.000005, hbsize = 1000, OBSOLETE: datasize = 1000, OBSOLETE: dout = 0.01, dt = 1.0, OBSOLETE: mindtx = 10.0**(-9), OBSOLETE: maxdtx = 100, statescale = array([0]). ''' # some simple checks if (hbsize == None): hbsize = 10000 if (hbsize <= 0): hbsize = 1 #if 0 or less, C code crashes if (dt == None): dt = 0.1 # check that the state scale is of the appropriate length if (self.PROB != None): if (len(statescale) < self.PROB[0]): tempstsc = zeros((self.PROB[0]), 'd') for i in range(len(statescale)): tempstsc[i] = statescale[i] statescale = tempstsc else: statescale = statescale[:self.PROB[0]] try: self.SOLVER = ( float(tol), int(hbsize), float(dt), # output and integration timesteps array(list(map(float, statescale)))) except: print( "DDE Error: Something is wrong: perhaps one of the supplied variables has the wrong type?" ) print("DDE Error: Solver initialisation failed!") return 0 # all went well self._set[1] = 1 return 1
def __init__(self, stacks, position): """ Pass a reference to the stacks object that holds all the blocks and the index of the initial stack of the block """ Block.__init__(self, stacks, position) self.box = box(pos=(position - (stacks.blockCount / 2), 0, 0), size=(.9, .9, .9), color=color.blue) self.label = label(pos=array(self.box.pos) + array([0, 0, 1]), text=str(position), opacity=0, box=0, line=0)
def arbitaryRotation(coord, angle, axis): """arbitaryRotation(coord, angle, vector) --> rotates point by angle around vector !!NB!! the axis is always through the origin!! must do offset first""" u, v, w = normalise(axis) oldCoord = array([coord[0], coord[1], coord[2]]) cth = cos(angle/180.*pi) sth = sin(angle/180.*pi) R = array([[cth + u**2*(1-cth), -w*sth+u*v*(1-cth), v*sth+u*w*(1-cth)], [ w*sth+u*v*(1-cth), cth+v**2*(1-cth), -u*sth+v*w*(1-cth)], [-v*sth+u*w*(1-cth), u*sth+v*w*(1-cth), cth+w**2*(1-cth)]]) newCoord = matrixmultiply(R,oldCoord) return [newCoord[0], newCoord[1], newCoord[2]]
def bezier2(x0, p1, p2, x1, t): a = array([1, t, t**2, t**3]) M = array([[1, 0, 0, 0], [1, 1, 1, 1], [0, 1, 0, 0], [0, 1, 2, 3]]) B = array([[1, 0, 0, 0], [0, 0, 0, 1], [-3, 3, 0, 0], [0, 0, -3, 3]]) p = transpose([[x0, p1, p2, x1]]) C = dot(inverse(M), B) return dot(dot(a, C), p)
def doit(): atoms = atom_array_of_part(part) ## elts = [atm.element.symbol for atm in atoms] elts = [atm.element.eltnum for atm in atoms] env.history.message( "%d element nums, first few are %r" % (len(elts), elts[:5] ) ) thing = array(elts) save_obj(thing, filename)
def delta_frame(self, n): """ return the delta frame with index n, as an appropriately-typed Numeric array """ bytes = self.filereader.delta_frame_bytes(n) ## older code: delta = A(unpack('bbb',file.read(3)))*0.01 # (with luck, reading the whole frame at once will be a nice speedup for fast-forwarding...) res = array(bytes, Int8) res.shape = (-1, 3) res = res * 0.01 #e it might be nice to move that multiply into caller (for speedup and error-reduction): #bruce 060110 comment: 0.01 is not represented exactly, so including it here might introduce cumulative # roundoff errors into callers who add up lots of delta frames! Let's estimate the size: assume 53 significant bits, # and typical values within 10^6 of 0, and need for 10^-3 precision, then we're using about 30 bits, # so an error in last bit, accumulating badly, still has say 1/4 * 2^23 = >> 10^6 steps to cause trouble... # and I think adding or subtracting this delta frame should reverse properly (same error gets added or removed), # except perhaps for special coord values that won't occur most times, so if true, what matters is movie length # rather than how often user plays it forwards and back. So I think we can tolerate this error for A7, at least, # and I think we can rule it out as a possible cause of bug 1297 (and an experiment also seems to rule that out). # [For the true cause, see 060111 comment in get_sim_posns.] # In the long run, we should fix this, though I never observed a problem. ####@@@@ ## if 0: #bruce 060111 debug code (two places), safe but could be removed when not needed (tiny bit slow) [bruce 060111] ###@@@ ## # maybe print deltas for one atom ## import runSim ## if runSim.debug_all_frames: ## ii = runSim.debug_all_frames_atom_index ## print "delta_frame %d[%d] is" % (n, ii), res[ii] return res
def corrcoef(*args): """ corrcoef(X) where X is a matrix returns a matrix of correlation coefficients for each row of X. corrcoef(x,y) where x and y are vectors returns the matrix or correlation coefficients for x and y. Numeric arrays can be real or complex The correlation matrix is defined from the covariance matrix C as r(i,j) = C[i,j] / (C[i,i]*C[j,j]) """ if len(args) == 2: X = transpose(array([args[0]] + [args[1]])) elif len(args == 1): X = args[0] else: raise RuntimeError, 'Only expecting 1 or 2 arguments' C = cov(X) d = resize(diagonal(C), (2, 1)) r = divide(C, sqrt(matrixmultiply(d, transpose(d))))[0, 1] try: return r.real except AttributeError: return r
def epsilon_greedy(self, sensation, applicable_actions): """ Given self.epsilon() and self.Q(), return a distribution over applicable_actions as an array where each element contains the a probability mass for the corresponding action. I.e. The action with the highest Q gets p = self.epsilon() and the others get the remainder of the mass, uniformly distributed. """ Q = array([self.Q(sensation, action) for action in applicable_actions]) # simple epsilon-greedy policy # get a vector with a 1 where each max element is, zero elsewhere mask = (Q == mmax(Q)) num_maxes = len(nonzero(mask)) num_others = len(mask) - num_maxes if num_others == 0: return mask e0 = self.epsilon() / num_maxes e1 = self.epsilon() / num_others result = zeros(len(mask)) + 0.0 putmask(result, mask, 1 - e0) putmask(result, mask == 0, e1) return result
def __call__(self, sensation, reward=None): if not is_terminal(sensation): sensation = tile_uniform_rfs( array(sensation) / self.tile_width, self.num_rfs, self.rf_width, self.num_tilings, self.num_features / self.num_rfs) return super(UniformTiledAgent, self).__call__(sensation, reward)
def convertToNumeric(self): """ Converts the internal data ( *self.data* ) to the *Numeric* array (if possible). Elements of array must be numerical or logical. Arrays can be stored and handeled more efficiently this way. Most of the code should be inependent of the type of storage of *self.data* , however, the way of soring the data can introduce some compatibility problems. Function return 1 if the conversion was successful, 0 otherwise. """ can_convert = 0 if self.type in [FLOAT_TYPE, INT_TYPE, LOGICAL_TYPE]: can_convert = 1 elif (type(self.type in (ListType, TupleType))) or isinstance( self.type, UserList): v = map(lambda x: x in [FLOAT_TYPE, INT_TYPE, LOGICAL_TYPE], self.type) if reduce(lambda x, y: x and y, v): can_convert = 1 if can_convert: try: from Numeric import array self.data = array(self.data) return 1 except ImportError: return 0 else: return 0
def collect_data(self,sensation,action,reward,next_sensation): from Numeric import array self.sensation = sensation self.action = action self.reward = reward self.next_sensation = next_sensation if self.caught_signal: import sys self.close() raise "Caught signal %d" % self.caught_signal epvars = self.episode_data.variables epvars['reward'][self.ep_count-1] += array((reward,),'f') epvars['length'][self.ep_count-1] += 1 if self.step_vars: stvars = self.step_data.variables for var,(fn,type,size) in self.step_vars.items(): stvars[var][self.step_count] = fn(self) if self.step_count % 10000 == 0: self.step_data.sync() if (self.checkpointing and self.step_count - self.last_ckpt_step >= self.steps_per_ckpt): self.ckpt_save() self.step_count += 1
def render(self): Actor.render(self) x, y, z = self.body.getPosition() R = self.body.getRotation() T = array((R[0], R[3], R[6], 0, R[1], R[4], R[7], 0, R[2], R[5], R[8], 0, x, y, z, 1), Float) glPushMatrix() glMultMatrixd(T.tolist()) sx, sy, sz = self.size glScale(sx, sy, sz) glDisable(GL_LIGHTING) glEnable(GL_BLEND) glBlendFunc(GL_ONE, GL_ONE) glFrontFace(GL_CW) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glColor3f(1, 1, 1) #glutSolidCube(1) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glEnable(GL_LIGHTING) glFrontFace(GL_CCW) glColor4f(*[abs(x) + .3 for x in self.body.getLinearVel() + (.5, )]) glScale(.97, .97, .97) #glutSolidCube(1) glDisable(GL_LIGHTING) glPopMatrix() glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def eval_formula(error, formula): global current_formula, t, last_time, start needed = int( min(rate * (time.time() - start + 1.5 * interval / 1000.0) - t, 3 * interval / 1000.0 * rate)) granularity = 1024 if needed % granularity != 0: needed += granularity - needed % granularity print time.time() - last_time, needed try: new_formula = shuntparse.parse(shuntparse.tokenize(formula.text)) new_formula.eval({'t': array(0)}) current_formula = new_formula except: _, exc, _ = sys.exc_info() error.text = repr(exc) else: error.text = '' try: rv = current_formula.eval({ 't': arange(t, t + needed) }).astype(UInt8).tostring() t += needed return rv except: if current_formula: error.text = str(sys.exc_info()[1]) return ''
def atom_array_of_part(part): "Return an Array of all atoms in the Part. Try to be linear time." res = [] for m in part.molecules: res.append( array(m.atlist) ) # concatenate might fail for chunks with exactly 1 atom -- fix later ####@@@@ return concatenate(res) ###k
def __init__(self, shp, ptlist, origin, selSense, **opts): """ ptlist is a list of 3d points describing a selection. origin is the center of view, and normal gives the direction of the line of light. Form a structure for telling whether arbitrary points fall inside the curve from the point of view. """ # bruce 041214 rewrote some of this method simple_shape_2d.__init__( self, shp, ptlist, origin, selSense, opts) # bounding rectangle, in integers (scaled 8 to the angstrom) ibbhi = array(map(int, ceil(8 * self.bboxhi)+2)) ibblo = array(map(int, floor(8 * self.bboxlo)-2)) bboxlo = self.bboxlo # draw the curve in these matrices and fill it # [bruce 041214 adds this comment: this might be correct but it's very # inefficient -- we should do it geometrically someday. #e] mat = zeros(ibbhi - ibblo) mat1 = zeros(ibbhi - ibblo) mat1[0,:] = 1 mat1[-1,:] = 1 mat1[:,0] = 1 mat1[:,-1] = 1 pt2d = self.pt2d pt0 = pt2d[0] for pt in pt2d[1:]: l = ceil(vlen(pt - pt0)*8) if l<0.01: continue v=(pt - pt0)/l for i in range(1 + int(l)): ij = 2 + array(map(int, floor((pt0 + v * i - bboxlo)*8))) mat[ij]=1 pt0 = pt mat1 += mat fill(mat1, array([1, 1]),1) mat1 -= mat #Which means boundary line is counted as inside the shape. # boolean raster of filled-in shape self.matrix = mat1 ## For any element inside the matrix, if it is 0, then it's inside. # where matrix[0, 0] is in x, y space self.matbase = ibblo # axes of the plane; only used for debugging self.x = self.right self.y = self.up self.z = self.normal
def unpickle(self): self._activation_fn = getattr(self, self.activation_function + '_activation') if hasattr(self, 'units'): # if the gng has a units attrib, it's the old version, # so convert it to the new version. self.weights = array([u.weights for u in self.units]) self.error = array([u.error for u in self.units]) self.dists = array([u.distance for u in self.units]) self.connections = [] for u in self.units: conn_dict = {} for k, v in u.connections.iteritems(): conn_dict[self.units.index(k)] = v self.connections.append(conn_dict) del self.units
def reindex(self): xa = self.xarray ya = array(self.series[-self.periods:]) try: slope, intercept, r, two_tail_prob, est_stderr = linregress(xa, ya) except (TypeError, ValueError, ZeroDivisionError): slope = 0.0 self.append(slope * self.scale)
def numpy_test(): try: from Numeric import array a = array((1., 2., 3.)) print "NumPy appears to work on your platform" except: print "Please install Numeric Python from http://numpy.sf.net" return
def MakeStrainMatrix(strainVector): """ Given the strain expressed as a vector, the so-called engineering strain, returns the matrix representation of the strain. """ return array( [[strainVector[0], 0.5 * strainVector[5], 0.5 * strainVector[4]], [0.5 * strainVector[5], strainVector[1], 0.5 * strainVector[3]], [0.5 * strainVector[4], 0.5 * strainVector[3], strainVector[2]]])
def find_in_radius(self,key,radius): if not self.db: return [],[] X = array([x for x,v in self.db]) dists = matrixnorm(key-X) close_enough = nonzero(dists <= radius) return ([self.db[i] for i in close_enough], [dists[i] for i in close_enough])