def clusters(self,L,min_L=1): from math import sqrt from frange import frange res = [] for y in frange(2,L+1.): for x in frange(y,L+1.): ll = sqrt(x*y) if (ll > (L-0.5) or abs(ll-(L-0.5))<1E-5) and (ll < L or abs(ll-L)<1E-5): res.append((int(x),int(y))) return res
def smartSweepInterval( ns2FileName, start, end, increment, args="", dropThreshold=0.10 ): """Similar to sweepInterval(), this function executes ns2 a number of times, each time passing it the specified data value. However, if the drop ratio ever exceeds dropThreshold, this function returns the data collected so far. This is useful if you are searching for the maximum sustainable throughput, or something similar.""" # We want to start from the LONGEST interval # which is the slowest sending rate if start < end: temp = end end = start start = temp increment = -increment assert( start > end ) assert( increment < 0 ) results = [] for interval in frange.frange( start, end, increment ): l = [ interval ] l.extend( executeAndParse( "ns %s %s %f" % ( ns2FileName, args, interval ) ) ) results.append( l ) if drops > dropThreshold: break return results
def test_slice_start_stop(): r = frange(0, 1, 10) print(list(r)) print("sliced [2:8] --", r[1:8]) print(list(r[2:8])) assert len(r[2:8]) == 6 assert list_close(r[2:8], list(r)[2:8])
def test_slice_stop(): r = frange(0, 1, 20) print(list(r)) print("sliced [:8] --", r[:8]) print(list(r[:8])) assert len(r[:8]) == 8 assert list_close(r[:8], list(r)[:8])
def test_frange_get_generator_nosteps(): """ Tests that for positive step size, with zero steps in interval, frange's returned generator matches arange's, which should be empty. """ np.testing.assert_allclose(list(frange(10, 0, 0.1).get_generator()), np.arange(10, 0, 0.1), rtol=1e-10) return None
def trapz(infun, a, b, *args, **kwargs): """ Compute the area under the curve defined by y = fun(x), for x between a and b :param fun: the function to evaluate :type fun: a function that takes a single parameter :param a: the start point for the integration :type a: a numeric value :param b: the end point for the integration :type b: a numeric value """ # curry the input function def fun(x): return infun(x, *args, **kwargs) # compute the range n = 100 # hard code that for now #vals = frange(a, b, n) #next(vals) # s = sum([fun(next(vals), *args, **kwargs) for i in range(n - 1)]) s = sum((fun(val) for val in frange(a, b, n)[1:-1])) s += (fun(a) + fun(b)) / 2 s *= (b - a) / n return s
def test_frange(): ''' tests the basics ''' r = frange(10, 20, 100) assert r[0] == 10.0 assert r[1] == 10.1 assert r[100] == 20.0
def test_frange_neg_index(): ''' tests the basics ''' r = frange(10, 20, 100) assert r[-1] == 20.0 assert r[-2] == 19.9 assert r[-101] == 10.0
def test_raise_zeroDivisionError(): """ Tests that when a zero step size is used frange raises a divide by zero error as numpy's arange function does. """ with pytest.raises(ZeroDivisionError): t = frange(1, 0, 0) return None
def __init__(self, Omega0, Gamma0, deltaGamma, mass, T0=300, q0=0, v0=0, alpha=0, beta=0, TimeTuple=[0, 100e-6], dt=1e-9, seed=None): """ Initialises the sde_solver instance. Parameters ---------- Omega0 : float Trapping frequency Gamma0 : float Enviromental damping - in radians/s - appears as (-Gamma*v) term in the SDE deltaGamma : float damping due to other effects (e.g. feedback cooling) - in radians/s - appears as (-deltaGamma*q**2*v)*dt term in the SDE mass : float mass of nanoparticle (in Kg) T0 : float, optional Temperature of the environment, defaults to 300 q0 : float, optional initial position, defaults to 0 v0 : float, optional intial velocity, defaults to 0 alpha : float prefactor multiplying the q**3 non-linearity term shows up as ([alpha*q]**3*dt) in the SDE beta : float prefactor multiplying the q**5 non-linearity term shows up as ([beta*q]**5*dt) in the SDE TimeTuple : tuple, optional tuple of start and stop time for simulation / solver dt : float, optional time interval for simulation / solver seed : float, optional random seed for generate_weiner_path, defaults to None i.e. no seeding of random numbers """ self.k_B = Boltzmann # J/K self.tArray = np.arange(0, 500e-6, dt) self.q0 = q0 self.v0 = v0 self.Omega0 = Omega0 self.Gamma0 = Gamma0 self.deltaGamma = deltaGamma self.mass = mass self.T0 = T0 self.alpha = alpha self.beta = beta self.TimeTuple = TimeTuple self.b_v = np.sqrt(2*self.Gamma0*self.k_B*self.T0/self.mass) # a constant self.dt = dt self.tArray = frange(TimeTuple[0], TimeTuple[1], dt) self.generate_weiner_path(seed) self.q = np.zeros(len(self.tArray)) # initialises position array, q self.v = np.zeros(len(self.tArray)) # initialises velocity array, v self.q[0] = self.q0 # sets initial position to q0 self.v[0] = self.v0 # sets initial position to v0 self.SqueezingPulseArray = np.ones(len(self.tArray)) # initialises squeezing pulse array such that there is no squeezing return None
def FloatingPoint(n, m, inc, d): fmt = "%%.%dg" % d["-d"] for i in frange(n, m, inc, include_end=d["-e"]): if i <= float(m): if d["-s"]: out(sig(i), "", nl=d["-n"]) else: out(fmt % i, "", nl=d["-n"]) if not d["-n"]: out()
def sweepInterval( ns2FileName, start, end, increment, args="", trimStart=5, trimEnd=5 ): """Execute ns2 a number of times with a range of parameters, and return the aggregate results from parseAggregateStatistics as a 2D list. The start, end, and increment parameters are passed to frange() to generate the sequence of values. The command executed is: ns <ns2FileName> <args> <dataValue>""" results = [] for interval in frange.frange( start, end, increment ): l = [ interval ] l.extend( executeAndParse( "ns %s %s %f" % ( ns2FileName, args, interval ), trimStart, trimEnd ) ) results.append( l ) return results
def main(): win = GraphWin('Sinusoid', 300, 300) win.setCoords(0, 0, win.width, win.height) # rect = Rectangle(Point(200, 90), Point(220, 100)) # rect.setFill("blue") # rect.draw(win) # # cir1 = Circle(Point(40, 100), 25) # cir1.setFill("yellow") # cir1.draw(win) # # cir2 = Circle(Point(150, 125), 25) # cir2.setFill("red") # cir2.draw(win) pt1 = Point(0, 150) pt1.draw(win) ln2 = Line(pt1, Point(300, 150)) ln2.draw(win) # x=[1,2,3,4,5,6,7,8,9,10] t = 0.05 amplitude = 10 for x in frange.frange(0,10,t/2): y = amplitude * math.sin((2*math.pi)*x) pt1.move(x, y) time.sleep(t/2) if pt1.getX() >= win.width: promptClose(win, win.getWidth() / 2, 20) break
def __init__(self, TimeTuple, SampleFreq, TrapFreqArray, Gamma0, mass, ConvFactorArray, NoiseStdDev, T0=300.0, deltaGammaArray=None, dt=1e-9, seed=None, NPerSegmentPSD=1000000): """ Parameters ---------- TimeTuple : tuple, optional tuple of start and stop time for simulation / solver SampleFreq : float Sample freq to downsample data to (Hz) TrapFreqArray : ndarray Array of trap frequencies of Z, X and Y motion (Hz). Gamma0 : float Damping due to the enviroment (radians/second) mass : float mass of the nanoparticle (kg) ConvFactorArray : ndarray Conversion factors to use to go from motion in nms to signal in volts for each degree of freedom NoiseStdDev : float std deviation of white noise applied to particle signal after generation from SDE solving. T0 : float, optional Temperature of the environment deltaGammaArray : ndarray, optional array containing the additional damping on each degree of freedom due to other effects (e.g. feedback cooling) dt : float, optional time step for SDE solver seed : float, optional random seed for generating the weiner paths for SDE solving defaults to None i.e. no seeding of random numbers sets the seed prior to initialising the SDE solvers such that the data is repeatable but that each solver uses different random numbers. No seed by default. NPerSegnmentPSD : int, optional number of points per segment to use in calculating the PSD """ self.q0 = 0.0 self.v0 = 0.0 self.TimeTuple = (TimeTuple[0], TimeTuple[1]) self.timeStart = TimeTuple[0] self.timeEnd = TimeTuple[1] self.SampleFreq = SampleFreq self.TrapFreqArray = _np.array(TrapFreqArray) self.Gamma0 = Gamma0 if deltaGammaArray == None: self.deltaGammaArray = _np.zeros_like(TrapFreqArray) else: if len(deltaGammaArray) != len(TrapFreqArray): raise ( "deltaGammaArray should be the same length as TrapFreqArray" ) self.deltaGammaArray = deltaGammaArray self.mass = mass self.ConvFactorArray = ConvFactorArray self.NoiseStdDev = NoiseStdDev self.T0 = T0 self.dt = dt self.seed = seed dtSample = 1 / SampleFreq self.DownSampleAmount = round(dtSample / dt) self.timeStep = dtSample / dt if _np.isclose(dtSample / dt, self.DownSampleAmount, atol=1e-6) == False: raise ValueError( "The sample rate {} has a time interval between samples of {}, this is not a multiple of the simualted time interval {}. dtSample/dt = {}" .format(SampleFreq, dtSample, dt, self.timeStep)) self.generate_simulated_data( ) # solves SDE for each frequency and eta value specified # along requested time interval self.time = frange(TimeTuple[0], TimeTuple[1], self.DownSampleAmount * dt) self.simtime = frange(TimeTuple[0], TimeTuple[1], dt) self.Noise = _np.random.normal(0, self.NoiseStdDev, len(self.time)) self.voltage = _np.copy(self.Noise) self.TrueSignals = [] for i, sdesolver in enumerate(self.sde_solvers): self.TrueSignals.append(_np.array([sdesolver.q, sdesolver.v])) self.voltage += ConvFactorArray[i] * sdesolver.q[::self. DownSampleAmount] self.TrueSignals = _np.array(self.TrueSignals) self.get_PSD(NPerSegmentPSD) del (self.sde_solvers) return None
def getAtDim(self, dim): dimMin = self.independentVarDimensionLimits[dim].dimMin dimMax = self.independentVarDimensionLimits[dim].dimMax return fr.frange(dimMin, dimMax, self.stepSize)
def test_full_slice(): r = frange(10, 20, 100) assert r == r[:]
def draw(self,randcol="false"): #find greatest common denominator of r and R using Euclidian algorithm: gcd = euclidianGCD(self.r, self.R) #number of periods is the reduced numerator of the fraction r/R numPeriods = self.r/gcd numPetals = self.R/gcd #calculate constants for graphing print('Periods: ', numPeriods) print('Petals: ', numPetals) k = float(self.r)/self.R l = float(self.d)/self.r print('k=',self.r, '/',self.R, '=',k,' l=',self.d,'/',self.r,'=',l) #use the custom-made frange function to make a list of angles of given increment angleIncrement = 0.01 #the smaller angleIncrement, the more data points ptsPeriod = math.ceil(2*math.pi/angleIncrement) print("Points per Period: ", ptsPeriod) #frange function is an alternative to range(). The last argument specifies a decimal step angles = frange(0, 2*math.pi*numPeriods, angleIncrement) xCoordinates = [] yCoordinates = [] #calculate all the (x,y) points corresponding to parameters in the "angles" list for theta in angles: thisX = self.R*((1-k)*math.cos(theta) + l*k*math.cos((1-k)/(k)*(theta))) thisY = self.R*((1-k)*math.sin(theta) + l*k*math.sin((1-k)/(k)*(theta))) xCoordinates.append(thisX) yCoordinates.append(thisY) print('Num data points: ', len(xCoordinates)) t = self.t #for brevity in future references to the turtle screen= t.getscreen() #same as above screen.bgcolor("black") #name the canvas window title = "Spirograph with R= " + str(self.R) + ", r = "+str(self.r) + ", and d = " +str(self.d) screen.title(title) #for the first point, just move the pen without leaving trace t.up() t.goto(xCoordinates[0], yCoordinates[0]) t.down() #speed up the drawing! update every 20 points. Change these parameters to vary speed screen.tracer(20) t.speed(6) if(randcol=="true"): randColors = True #if True, change up colors randomly with each period else: randColors = False t.color(self.color) sender=udp_client.SimpleUDPClient("127.0.0.1",4559) pointsCount = 0 for each in range(len(xCoordinates)): t.goto(xCoordinates[each], yCoordinates[each]) pointsCount = pointsCount + 1 #additonal section to export x.y coords using OSC message if (pointsCount % (numPetals*2) == 0): sender.send_message('/xcoord',xCoordinates[each]) if (pointsCount % (numPetals*4) ==0): sender.send_message('/ycoord',yCoordinates[each]) #end of additional section if (randColors): if (pointsCount % (ptsPeriod*4) == 0): red = random.random() green = random.random() blue = random.random() t.color(red, green, blue) t.hideturtle() print("Done drawing this curve") time.sleep(2) sender.send_message("/finished","done")
def test_zero_num_steps(): with pytest.raises(ValueError): assert list(frange(3, 10, 0)) == []
def test_frange_get_generator_negtaiveStepSize(): """ Tests that for negative step size frange's returned generator matches arange's """ np.testing.assert_allclose(list(frange(10, 0, -0.1).get_generator()), np.arange(10, 0, -0.1), rtol=1e-10) return None
def test_index_too_large(): r = frange(100, 200, 10) with pytest.raises(IndexError): r[11] with pytest.raises(IndexError): r[-12]
def test_slice_start_neg_end(): assert (list(frange( 0, 10, 10)[1:-1]) == [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
def test_slice_start(): r = frange(0, 1, 10) assert r[1:] == frange(0.1, 1, 9) assert r[2:] == frange(0.2, 1, 8)
def test_slice_start_neg_end2(): assert (list(frange(0, 10, 10)[2:-2]) == [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
def test_backwards(): list_close(frange(1, 0, 10), [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0])
def Fractions(n, m, inc, d): for i in frange(n, m, inc, impl=R, return_type=R, include_end=d["-e"]): out(i, "", nl=d["-n"]) if not d["-n"]: out()
def test_length(): assert len(frange(0, 100)) == 101
def test_length(): assert len(frange(0, 10, 0.1).get_array()) == 100 return None
y = [] z = [] m = [] r = [] Ntot = 0 for line in f: val = line.split() m.append(float(val[0]) * Msunh) x.append(float(val[1]) * Mpch) y.append(float(val[2]) * Mpch) z.append(float(val[3]) * Mpch) r.append(sqrt((x[Ntot] - xc) ** 2 + (y[Ntot] - yc) ** 2 + (z[Ntot] - zc) ** 2)) Ntot = Ntot + 1 print ("increase radius until relaxation time is simulation time") for rtmp in fr.frange(0.0, rvir, dr): # print "rtmp = ",rtmp # determine N,M M = 0.0 N = 0 for i in range(0, Ntot): if r[i] < rtmp: M = M + m[i] N = N + 1 if M <= 0.0: continue CL = log(rtmp / bmin) trelax = N * rtmp ** 1.5 / (8 * sqrt(G) * sqrt(M) * CL) if trelax > tsim:
def test_frange_get_array_postiveStepSize(): """ Tests that for positive step size frange's returned array matches arange's """ np.testing.assert_allclose(frange(0, 10, 0.1).get_array(), np.arange(0, 10, 0.1), rtol=1e-10) return None
#!/usr/bin/python # Generate absorbance data and save testing file for A->B import random from numpy import matrix, matlib import csv from frange import frange t_0 = matrix(frange(-1e-6, 0, 5e-11)).transpose() t_1 = matrix(frange(0, 1.9999500e-6, 5e-11)).transpose() k = [2.2e7, 3.124e7] # rate constant a_0 = 1e-3 # initial concentration of A a_1 = 2e-3 # initial concentration of C c = matlib.empty([t_1.size, 2]) c[:,0] = a_0 * matlib.exp(-k[0] * t_1) c[:,1] = a_1 * matlib.exp(-k[1] * t_1) # molar absorption of species A a = matlib.empty([2, 1]) a[0,0] = 1e3 a[1,0] = 1e3 y_1 = matlib.dot(c, a) y_1 = y_1.transpose().tolist()[0] y_1 = map(lambda y: y + (0.04 * random.random() - 0.02), y_1) t_0 = t_0.transpose().tolist()[0] t_1 = t_1.transpose().tolist()[0] fullLightVoltage = -0.0951192897786 y_1 = map(lambda y:fullLightVoltage*(10**-y), y_1)
def draw(self): #find greatest common denominator of r and R using Euclidian algorithm: gcd = euclidianGCD(self.r, self.R) #number of periods is the reduced numerator of the fraction r/R numPeriods = self.r/gcd numPetals = self.R/gcd #calculate constants for graphing print 'Periods: ', numPeriods print 'Petals: ', numPetals k = float(self.r)/self.R l = float(self.d)/self.r print 'k=',self.r, '/',self.R, '=',k,' l=',self.d,'/',self.r,'=',l #use the custom-made frange function to make a list of angles of given increment angleIncrement = 0.01 #the smaller angleIncrement, the more data points ptsPeriod = math.ceil(2*math.pi/angleIncrement) print "Points per Period: ", ptsPeriod #frange function is an alternative to range(). The last argument specifies a decimal step angles = frange(0, 2*math.pi*numPeriods, angleIncrement) xCoordinates = [] yCoordinates = [] #calculate all the (x,y) points corresponding to parameters in the "angles" list for theta in angles: thisX = self.R*((1-k)*math.cos(theta) + l*k*math.cos((1-k)/(k)*(theta))) thisY = self.R*((1-k)*math.sin(theta) + l*k*math.sin((1-k)/(k)*(theta))) xCoordinates.append(thisX) yCoordinates.append(thisY) print 'Num data points: ', len(xCoordinates) t = self.t #for brevity in future references to the turtle screen= t.getscreen() #same as above #name the canvas window title = "Spirograph with R= " + str(self.R) + ", r = "+str(self.r) + ", and d = " +str(self.d) screen.title(title) #for the first point, just move the pen without leaving trace t.up() t.goto(xCoordinates[0], yCoordinates[0]) t.down() #speed up the drawing! update every 20 points. Change these parameters to vary speed screen.tracer(20) t.speed(6) randColors = False #if True, change up colors randomly with each period t.color(self.color) pointsCount = 0 for each in range(len(xCoordinates)): t.goto(xCoordinates[each], yCoordinates[each]) pointsCount = pointsCount + 1 if (randColors): if (pointsCount % ptsPeriod == 0): red = random.random() green = random.random() blue = random.random() t.color(red, green, blue) print "Done drawing this curve" t.hideturtle()
def Integers(n, m, inc, d): for i in frange(n, m, inc, return_type=int, include_end=d["-e"]): if i <= int(m): out(i, "", nl=d["-n"]) if not d["-n"]: out()
def test_start_stop_same(): with pytest.raises(ValueError): assert list(frange(3, 3)) == []
#!/usr/bin/python from magnum import * from frange import frange from math import cos, sin, pi mesh = RectangularMesh((500,250,1), (5e-9, 5e-9, 20e-9)) Py = Material.Py(k_uni=5e2, axis1=(1,0,0)) world = World(mesh, Body("square", Py, Everywhere())) solver = create_solver(world, [StrayField, ExchangeField, AnisotropyField, ExternalField], log=True) # Create initial state solver.state.M = (8e5, 0, 0) # Perform hysteresis H_range = list(frange(+50e-3, -50e-3, -5e-3)) + list(frange(-50e-3, +50e-3, 5e-3)) for tmp in H_range: H = (tmp/MU0 * cos(pi/180), tmp/MU0 * sin(pi/180), 0) # in A/m print(H) solver.state.H_offs = H solver.relax(1.0)