def moving_average(y, window_length): """ Compute the moving average of y with specified window length. Args: y: an 1-d pylab array with length N, representing the y-coordinates of the N sample points window_length: an integer indicating the window length for computing moving average Returns: an 1-d pylab array with the same length as y storing moving average of y-coordinates of the N sample points """ i = 1 moving_avg = pylab.array([]) while i < window_length: moving_avg = pylab.append(moving_avg, pylab.array(sum(y[0:i])/i)) i += 1 for j in range(i, len(y)+1): moving_avg = pylab.append(moving_avg, pylab.array( sum(y[j-window_length:j] / window_length))) return moving_avg
def gen_cities_avg(climate, multi_cities, years): """ Compute the average annual temperature over multiple cities. Args: climate: instance of Climate multi_cities: the names of cities we want to average over (list of str) years: the range of years of the yearly averaged temperature (list of int) Returns: a pylab 1-d array of floats with length = len(years). Each element in this array corresponds to the average annual temperature over the given cities for a given year. """ year_dt = list() for year in years: city_dt = pylab.array([]) for city in multi_cities: city_dt = pylab.append( city_dt, climate.get_yearly_temp(city, year)) year_dt.append(sum(city_dt) / len(city_dt)) return pylab.array(year_dt)
def tempo_search(db, Key, tempo): """ :: Static tempo-invariant search Returns search results for query resampled over a range of tempos. """ if not db.configCheck(): print("Failed configCheck in query spec.") print(db.configQuery) return None prop = 1. / tempo # the proportion of original samples required for new tempo qconf = db.configQuery.copy() X = db.retrieve_datum(Key) P = db.retrieve_datum(Key, powers=True) X_m = pylab.mat(X.mean(0)) X_resamp = pylab.array( adb.resample_vector(X - pylab.mat(pylab.ones(X.shape[0])).T * X_m, prop)) X_resamp += pylab.mat(pylab.ones(X_resamp.shape[0])).T * X_m P_resamp = pylab.array(adb.resample_vector(P, prop)) seqStart = int(pylab.around(qconf['seqStart'] * prop)) qconf['seqStart'] = seqStart seqLength = int(pylab.around(qconf['seqLength'] * prop)) qconf['seqLength'] = seqLength tmpconf = db.configQuery db.configQuery = qconf res = db.query_data(featData=X_resamp, powerData=P_resamp) res_resorted = adb.sort_search_result(res.rawData) db.configQuery = tmpconf return res_resorted
def fitting(x,y,f,p0,c0,yerr='none',qval='none'): if yerr=='none': yerr=y*0+y/y global func func=f npar=len(p0) func=def_func(npar,c0) print 'fitting with funcion: ', func print 'no of parameters: ', len(p0) # plsq = leastsq(residuals, p0, args=(y,x,yerr), col_deriv=1, maxfev=20000) if 'duri' in func: plsq= leastsq(residuals_duri_global, p0, args=(y,x,yerr,qval), col_deriv=0, ftol=1e-4, maxfev=2000000) else: plsq = leastsq(residuals, p0, args=(y,x,yerr), col_deriv=0, maxfev=20000) if npar==1: final_par = array([plsq[0]]) else: final_par = plsq[0] if 'duri' in func: yfit=0*y for i,q in enumerate(qval): q=float(q) yfit[i,:]=pyl.array(peval_duri_global(x,final_par,q),typecode='d') else: yfit=pyl.array(peval(x,final_par),typecode='d') return yfit, final_par, func
def tryFits1(fName): distances, heights = getTrajectoryData(fName) distances = pylab.array(distances) * 36 totHeights = pylab.array([0] * len(distances)) for h in heights: totHeights = totHeights + pylab.array(h) pylab.title('Trajectory of Projectile (Mean of 4 Trials)') pylab.xlabel('Inches from Launch Point') pylab.ylabel('Inches Above Launch Point') meanHeights = totHeights / float(len(heights)) pylab.plot(distances, meanHeights, 'bo') a, b = pylab.polyfit(distances, meanHeights, 1) altitudes = a * distances + b pylab.plot(distances, altitudes, 'r', label='Linear Fit' + ', R2 = ' + str(round(rSquare(meanHeights, altitudes), 4))) a, b, c = pylab.polyfit(distances, meanHeights, 2) altitudes = a * (distances**2) + b * distances + c pylab.plot(distances, altitudes, 'g', label='Quadratic Fit' + ', R2 = ' + str(round(rSquare(meanHeights, altitudes), 4))) pylab.legend()
def infer(model): print('start test!') label_np = array(Image.open('./data/test/Labels/672.png')) label = Variable(torch.from_numpy(label_np)) img = Image.open('./data/test/Images/672.png') img_n = array(img) img_np = np.resize(img_n, (480, 480, 3)) outputs = model( Variable(torch.from_numpy(img_np[np.newaxis, :].transpose(0, 3, 1, 2)).float(), volatile=True).cuda()) # print outputs.size() outputs = outputs.squeeze() print outputs predict = reverse_one_hot(outputs) print predict label = label.squeeze() print label fig, ax = plt.subplots(1, 3) ax[0].imshow(img_np, cmap='gray') ax[1].imshow(predict) ax[2].imshow(label) plt.show() return 0
def sol_tov(rho_center): rmin = dr rmax = 20000.0 r = pylab.arange(rmin, rmax + dr, dr) m = pylab.zeros_like(r) P = pylab.zeros_like(r) m[0] = (4.0 / 3.0) * pi * rho_center * r[0]**3 P[0] = eos(rho_center) y = pylab.array([P[0], m[0]]) i = 0 while P[i] > 0.0 and i < len(r) - 1: y = rk4(tov, y, r[i], dr) P[i + 1] = y[0] m[i + 1] = y[1] i = i + 1 rho = pylab.array(list(map(lambda p: inv_eos(p), P))) m, r, rho, P = m[:i], r[:i], rho[:i], P[:i] # Give restriction for region if isentropic: # Consider the isentropic case # We use conventional finite differencing to handle this case drhodr = get_dfdr(rho, dr) rprime = (r[-1] - r)[::-1] # Inward integration variable # Specific internal energy from thermo identities u_integrand = (-P * drhodr / (rho**2))[::-1] # Interpolation integrand_interpol = iterp1d(rprime, u_integrand, kind='cubic') urhs = lambda u, rprime: integrand_interpol(rprime) u = np.zeros_like(r) for i in range(0, len(rprime) - 1): u[i + 1] = rk4(urhs, u[i], rprime[i], dr) # Using RK4 to integrate u = u[::-1] # Reverse u else: u = np.zeros_like(r) return m, m[-1] / Msun, r, rho, P, u # Return the mass and radius of star
def imextents(self, im, buffer=1.): """ extents in pixel space - buffer in units of inner ap radius """ ca = self.imcoords(im, reg="ap") c1 = self.imcoords(im, reg="bg1") # outer bg if self.type == "circle": dr = ca[2] xra = c1[0] + (dr * buffer + c1[2]) * pl.array([-1, 1]) yra = c1[1] + (dr * buffer + c1[2]) * pl.array([-1, 1]) elif self.type == "polygon": dx = minmax(ca[0, :]) dy = minmax(ca[1, :]) ctr = [mean(dx), mean(dy)] dx = dx[1] - dx[0] dy = dy[1] - dy[0] dr = 0.5 * max(dx, dy) xra = minmax(c1[0, :]) + dr * buffer * pl.array([-1, 1]) yra = minmax(c1[1, :]) + dr * buffer * pl.array([-1, 1]) xra[0] = pl.floor(xra[0]) + 1 yra[0] = pl.floor(yra[0]) + 1 xra[1] = pl.ceil(xra[1]) + 1 yra[1] = pl.ceil(yra[1]) + 1 if xra[0] < 0: xra[0] = 0 if yra[0] < 0: yra[0] = 0 s = im.shape - pl.array([1, 1]) # remember, transposed y,x if xra[1] > s[1]: xra[1] = s[1] if yra[1] > s[0]: yra[1] = s[0] return int(xra[0]), int(yra[0]), int(xra[1]), int(yra[1])
def updateParticules(self, X, Y, T, freq=10): """ rajouter une ligne dans le groupe de particules""" l0 = self.getObjFromType('particules') lignes = l0.object d = l0.getData() if d == None: data = [] else: data = d * 1 t = self.getObjFromType('partTime') if t != None: txt = t.object * 1 else: txt = [] p, = pl.plot(pl.array(X), pl.array(Y), 'r') lignes.append(p) obj = GraphicObject('particules', lignes, True, None) data.append([X, Y, T]) obj.setData(data) self.addGraphicObject(obj) if freq > 0: tx, ty, tt = X[0::freq], Y[0::freq], T[0::freq] for i in range(len(tx)): a = str(tt[i]) b = a.split('.') ln = max(4, len(b[0])) txt.append(pl.text(tx[i], ty[i], a[:ln], fontsize='8')) obj = GraphicObject('partTime', txt, False, None) self.addGraphicObject(obj) self.gui_repaint() # bug matplotlib v2.6 for direct draw!!! self.draw()
def setbgcoords(self): if self.type == None: raise Exception("region type=None - has it been set?") if self.type == "circle": if len(self.coords) != 3: raise Exception( "region coords should be ctr_ra, ctr_dec, rad_arcsec - the coord array has unexpected length %d" % len(self.coords)) self.bg0coords = pl.array(self.coords) self.bg1coords = pl.array(self.coords) # set larger radii for annulus self.bg0coords[2] = self.coords[2] * self.bgfact[0] self.bg1coords[2] = self.coords[2] * self.bgfact[1] elif self.type == "polygon": n = self.coords.shape[1] self.coords = pl.array(self.coords) ctr = [self.coords[:, 0].mean(), self.coords[:, 1].mean()] x = self.coords[:, 0] - ctr[0] y = self.coords[:, 1] - ctr[1] r = pl.sqrt(x**2 + y**2) th = pl.arctan2(y, x) ct = pl.cos(th) st = pl.sin(th) # inner and outer background regions b = self.bgfact self.bg0coords = pl.array([r * b[0] * ct, r * b[0] * st]).T + ctr self.bg1coords = pl.array([r * b[1] * ct, r * b[1] * st]).T + ctr else: raise Exception("unknown region type %s" % self.type)
def _make_log_freq_map(self): """ :: For the given ncoef (bands-per-octave) and nfft, calculate the center frequencies and bandwidths of linear and log-scaled frequency axes for a constant-Q transform. """ fp = self.feature_params bpo = float(self.nbpo) # Bands per octave self._fftN = float(self.nfft) hi_edge = float(self.hi) lo_edge = float(self.lo) f_ratio = 2.0**(1.0 / bpo) # Constant-Q bandwidth self._cqtN = float(P.floor(P.log(hi_edge / lo_edge) / P.log(f_ratio))) self._dctN = self._cqtN self._outN = float(self.nfft / 2 + 1) if self._cqtN < 1: print("warning: cqtN not positive definite") mxnorm = P.empty(self._cqtN) # Normalization coefficients fftfrqs = self._fftfrqs #P.array([i * self.sample_rate / float(self._fftN) for i in P.arange(self._outN)]) logfrqs = P.array([ lo_edge * P.exp(P.log(2.0) * i / bpo) for i in P.arange(self._cqtN) ]) logfbws = P.array([ max(logfrqs[i] * (f_ratio - 1.0), self.sample_rate / float(self._fftN)) for i in P.arange(self._cqtN) ]) #self._fftfrqs = fftfrqs self._logfrqs = logfrqs self._logfbws = logfbws self._make_cqt()
def test_r_squared(self): # basic case: # actual values [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # estimated values [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] y = pylab.array(range(10)) est = pylab.array([5] * 10) r_sq = ps5.r_squared(y, est) self.assertIsInstance(r_sq, float, "r_squared should return a float") rounded = round(r_sq, 6) self.assertEquals(rounded, -0.030303) # another basic case: # actual values [0, 1, 2, 3, 4, 5, 6, 7, 8] # estimated values [0, 2, 4, 6, 8, 10, 12, 14, 16] est = pylab.array(range(0, 20, 2)) r_sq = ps5.r_squared(y, est) self.assertIsInstance(r_sq, float, "r_squared should return a float") rounded = round(r_sq, 6) self.assertEquals(rounded, -2.454545) # case where actual = estimated, so R^2=1 r_sq = ps5.r_squared(y, y) self.assertIsInstance(r_sq, float, "r_squared should return a float") self.assertEquals(r_sq, 1.0)
def __init__(self, bins = 10, rnge = (0,100), temp_file = 'temp.txt', do_histograms = True, do_coincidences = False): """ Thread constructor :arg temp_file: Name of the temporary file :arg do_histogram: :arg bins: :arg rnge: :arg do_coincidences: Generate an additional histogram with the coincidences t2-t1 """ threading.Thread.__init__(self) self.bins = bins self.rnge = rnge self.data = [pl.array([]),pl.array([])] self.hist = [generateHist([], self.bins, rnge= self.rnge), generateHist([], self.bins, rnge= self.rnge)] self.n_starts = 0 if temp_file != None: self.temp_file = open(temp_file,'w') else: self.temp_file = None self.do_coincidences = do_coincidences self.do_histograms = do_histograms if do_coincidences: self.rnge_c = (self.rnge[0] - self.rnge[1], self.rnge[1] - self.rnge[0]) self.hist_c = generateHist([], 2*self.bins, rnge= self.rnge_c)
def plotstuff(cell, electrode): figure = mlab.figure(size=(800,800)) l_list = [] for sec in neuron.h.allsec(): idx = cell.get_idx_section(sec.name()) j = 0 for seg in sec: i = idx[j] x = pl.array([cell.xstart[i],cell.xend[i]]) y = pl.array([cell.ystart[i],cell.yend[i]]) z = pl.array([cell.zstart[i],cell.zend[i]]) s = pl.array([seg.v, seg.v]) l = mlab.plot3d(x, y, z, s, colormap = 'Spectral', tube_radius=cell.diam[i], representation='surface', vmin=-70, vmax=10) l_list.append(l) print j j += 1 t0 = time() ipdb.set_trace() #ms = l_list[0].mlab_source while time()-t0 < 10: for l in l_list: ms = l.mlab_source s = pl.rand()*80 -70 scalars = pl.array([s, s]) ms.set(scalars = scalars)
def __init__(self, contact_area_percent=50.0): ###################################### # begin: parameters to be specified self.contact_area_percent = contact_area_percent # resistor that is in series with the taxel (Ohms) self.r1 = 47.0 # total voltage across the taxel and r1, which are in serise (Volts) self.vtot = 5.0 # the maximum resistance of the taxel when no pressure is applied (Ohms) self.rtax_max = 50.0 # the minimum force that will be applied to the taxel (Newtons) self.fz_min = 0.0 # the maximum force that will be applied to the taxel (Newtons) self.fz_max = 45.0 # the number of bits for the analog to digital conversion self.adc_bits = 10 # the pressure sensitive area of the taxel (meters^2) self.taxel_area = 0.04 * 0.04 # pressure that results in minimum resistance after which # further pressure does not result in a reduction in the # signal, since the sensor is saturated (Pascals = N/m^2) self.pressure_max = self.fz_max / (0.4 * self.taxel_area) # hack to specify the minimum resistance of the taxel, which # is associated with the maximum pressure. for now, it's # specified as a percentage of the maximum resistance, which # is associated with 0 applied pressure (no contact) self.r_min_percent_of_r_no_contact = 0.001 # # end ###################################### self.r_no_contact = self.taxel_area * self.rtax_max self.r_min = self.r_no_contact * (self.r_min_percent_of_r_no_contact / 100.0) self.fz_array = pl.arange(self.fz_min, self.fz_max, 0.001) # N self.adc_range = pow(2.0, self.adc_bits) self.volts_per_adc_unit = self.vtot / self.adc_range # V self.contact_area = self.taxel_area * ( self.contact_area_percent / 100.0) # m^2 self.no_contact_area = self.taxel_area - self.contact_area # m^2 self.pressure_array = pl.array( [f / self.contact_area for f in self.fz_array]) # Pascals = N/m^2 self.rtax_array = pl.array([self.rtax(f) for f in self.pressure_array]) self.vdigi_array = pl.array( [self.output_voltage(r) for r in self.rtax_array]) self.vdigi_max = self.output_voltage(self.rtax_max) self.adc_bias = self.vdigi_max / self.volts_per_adc_unit self.adc_array = self.vdigi_array / self.volts_per_adc_unit self.adc_plot = self.adc_bias - self.adc_array
def histogram(arguments): data = list(map(float, sys.stdin.readlines())) data_min = min(data) data_avg = pylab.average(pylab.array(data)) data_max = max(data) data_std = pylab.std(pylab.array(data)) data = filter( lambda n: data_avg + arguments.n * data_std > (n**2)**0.5, data) pyplot.hist(list(data), bins=arguments.bins) pyplot.suptitle(arguments.suptitle) if arguments.title is None: pyplot.title('min|avg|max|std = {0:0.2f}|{1:0.2f}|{2:0.2f}|{3:0.2f}' .format(data_min, data_avg, data_max, data_std)) else: pyplot.title(arguments.title) pyplot.xlabel(arguments.xlabel) pyplot.ylabel(arguments.ylabel) pyplot.grid() pyplot.savefig(path(arguments))
def updateParticules(self, X, Y, T, freq=10): """ rajouter une ligne dans le groupe de particules""" l0 = self.getObjFromType("particules") lignes = l0.object d = l0.getData() if d == None: data = [] else: data = d * 1 t = self.getObjFromType("partTime") if t != None: txt = t.object * 1 else: txt = [] p, = pl.plot(pl.array(X), pl.array(Y), "r") lignes.append(p) obj = GraphicObject("particules", lignes, True, None) data.append([X, Y, T]) obj.setData(data) self.addGraphicObject(obj) if freq > 0: tx, ty, tt = X[0::freq], Y[0::freq], T[0::freq] for i in range(len(tx)): a = str(tt[i]) b = a.split(".") ln = max(4, len(b[0])) txt.append(pl.text(tx[i], ty[i], a[:ln], fontsize="8")) obj = GraphicObject("partTime", txt, False, None) self.addGraphicObject(obj) self.gui_repaint() # bug matplotlib v2.6 for direct draw!!! self.draw()
def gen_std_devs(climate, multi_cities, years): """ For each year in years, compute the standard deviation over the averaged yearly temperatures for each city in multi_cities. Args: climate: instance of Climate multi_cities: the names of cities we want to use in our std dev calculation (list of str) years: the range of years to calculate standard deviation for (list of int) Returns: a pylab 1-d array of floats with length = len(years). Each element in this array corresponds to the standard deviation of the average annual city temperatures for the given cities in a given year. """ result = [] for year in years: city_temps = [] national_temp = [] for city in multi_cities: #Get a list of arrays, each array is all the daily temps of the year for each city city_temps.append(climate.get_yearly_temp(city, year)) #turn the list of arrays into a numpy array city_temps = np.array(city_temps) #go over the 2d array and get an array of temperatures for that day, add the standard deviation to national_temp for day in range(len(city_temps[0])): daily_temps = city_temps[:, day] national_temp.append(pylab.array(daily_temps).mean()) result.append(np.std(national_temp)) return pylab.array(result)
def moving_average(y, window_length): """ Compute the moving average of y with specified window length. Args: y: an 1-d pylab array with length N, representing the y-coordinates of the N sample points window_length: an integer indicating the window length for computing moving average Returns: an 1-d pylab array with the same length as y storing moving average of y-coordinates of the N sample points """ result = [] for i in range(len(y)): start_index = i - window_length + 1 if start_index < 0: result.append( #Get mean from start of array till i pylab.array(y[:i + 1]).mean()) else: result.append( #Get mean from start_index to i pylab.array(y[start_index:i + 1]).mean()) return pylab.array(result)
def main(data_files1, data_files2, err, B=0.5003991, l=2e-2, w=1e-2, outfile=None): mu_H = lambda V_5, V_1: V_5 * l / ( V_1 * B * w) mu_He = lambda V_5, V_1, V_5e, V_1e: pylab.sqrt(\ ( (l / ( V_1 * B * w)) * V_5e )**2 +\ ( (V_5 / ( V_1 * B * w)) * 1e-4 )**2 +\ ( (V_5 * l / ( V_1 * B * w)) * 1e-4 )**2 +\ ( (V_5 * l / ( V_1**2 * B * w)) * V_1e )**2 +\ ( (V_5 * l / ( V_1 * B**2 * w)) * 2e-8 )**2 +\ ( (V_5 * l / ( V_1 * B * w**2)) * 1e-4 )**2) x5, x1, V5, V1, N5, N1 = [], [], [], [], [], [] for df in data_files1: databox = spinmob.data.load(df) x, V, N = interpolate(databox) x5 += x V5 += V N5 += N for df in data_files2: databox = spinmob.data.load(df) x, V, N = interpolate(databox) x1 += x V1 += V N1 += N min_len = min([len(x5), len(x1)]) xs = pylab.array(x5[:min_len]) V5, V1 = pylab.array(V5[:min_len]), pylab.array(V1[:min_len]) N5, N1 = pylab.array(N5[:min_len]), pylab.array(N1[:min_len]) e5, e1 = err / pylab.sqrt(N5), err / pylab.sqrt(N1) ys, es = mu_H(V5, V1), mu_He(V5, V1, e5, e1) make_fig(xs, ys, es, outfile)
def plot_net(self, style: str): total_pd = [self.paid[0]] for i in range(1, len(self.paid)): total_pd.append(total_pd[-1] + self.paid[i]) equity = pylab.array([self.loan] * len(self.owed)) equity = equity - pylab.array(self.owed) net = pylab.array(total_pd) - equity pylab.plot(net, style, label=self.legend)
def plotNet(self, style): totPd = [self.paid[0]] for i in range(1, len(self.paid)): totPd.append(totPd[-1] + self.paid[i]) equityAcquired = pylab.array([self.loan] * len(self.outstanding)) equityAcquired = equityAcquired - pylab.array(self.outstanding) net = pylab.array(totPd) - equityAcquired pylab.plot(net, style, label=self.legend)
def plot_data(input): masses, distances = get_data(input) masses = pylab.array(masses) distances = pylab.array(distances) forces = masses * 9.81 pylab.plot(forces, distances, 'bo', label='Measured displacements') pylab.xlabel('|Force|(Newtons)') pylab.ylabel('Distance(meters')
def getAntLocations(configuration='D'): """Return location information for each antenna in array. Arguments: Takes configuration as argument (choose from 'A', 'C', 'D'). Returns: Tuple of arrays containing antenna diameters (m), names, and x, y, and z locations (m). """ # Raw antenna locations in C configuration vx = [41.1100006, 134.110001, 268.309998, 439.410004, 644.210022, 880.309998, 1147.10999, 1442.41003, 1765.41003, -36.7900009, -121.690002, -244.789993, -401.190002, -588.48999, -804.690002, -1048.48999, -1318.48999, -1613.98999, -4.38999987,-11.29, -22.7900009, -37.6899986, -55.3899994, -75.8899994, -99.0899963, -124.690002, -152.690002] vy = [3.51999998, -39.8300018, -102.480003, -182.149994, -277.589996, -387.839996, -512.119995, -649.76001, -800.450012, -2.58999991, -59.9099998, -142.889999, -248.410004, -374.690002, -520.599976, -685, -867.099976, -1066.42004, 77.1500015, 156.910004, 287.980011, 457.429993, 660.409973, 894.700012, 1158.82996, 1451.43005, 1771.48999] vz = [0.25, -0.439999998, -1.46000004, -3.77999997, -5.9000001, -7.28999996, -8.48999977, -10.5, -9.56000042, 0.25, -0.699999988, -1.79999995, -3.28999996, -4.78999996, -6.48999977, -9.17000008, -12.5299997, -15.3699999, 1.25999999, 2.42000008, 4.23000002, 6.65999985, 9.5, 12.7700005, 16.6800003, 21.2299995, 26.3299999] d = [25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0] # Get scaling factor for antenna locations based on configuration if(configuration=='D'): scale = 3.0 else: if(configuration=='A'): scale = 1.0/9.0 else: scale = 1.0 print 'Using VLA C-array coords' # Move antennas into desired configuration nn = len(vx) x = (vx - (sum(pl.array(vx))/(nn)))/scale y = (vy - (sum(pl.array(vy))/(nn)))/scale z = (vz - (sum(pl.array(vz))/(nn)))/scale # Label the antenna an=[] for i in range(0,nn): an.append("VLA"+str(i)) return d,an,x,y,z
def plotData(fileName): xVals, yVals = getData(fileName) xVals = pylab.array(xVals) yVals = pylab.array(yVals) xVals = xVals * 9.81 # convert mass to force (F = mg) pylab.plot(xVals, yVals, 'bo', label='Measured displacements') pylab.title('Measured Displacement of Spring') pylab.xlabel('Force (Newtons)') pylab.ylabel('Distance (meters)')
def __init__(self, contact_area_percent=50.0): ###################################### # begin: parameters to be specified self.contact_area_percent = contact_area_percent # resistor that is in series with the taxel (Ohms) self.r1 = 47.0 # total voltage across the taxel and r1, which are in serise (Volts) self.vtot = 5.0 # the maximum resistance of the taxel when no pressure is applied (Ohms) self.rtax_max = 50.0 # the minimum force that will be applied to the taxel (Newtons) self.fz_min = 0.0 # the maximum force that will be applied to the taxel (Newtons) self.fz_max = 45.0 # the number of bits for the analog to digital conversion self.adc_bits = 10 # the pressure sensitive area of the taxel (meters^2) self.taxel_area = 0.04 * 0.04 # pressure that results in minimum resistance after which # further pressure does not result in a reduction in the # signal, since the sensor is saturated (Pascals = N/m^2) self.pressure_max = self.fz_max/(0.4 * self.taxel_area) # hack to specify the minimum resistance of the taxel, which # is associated with the maximum pressure. for now, it's # specified as a percentage of the maximum resistance, which # is associated with 0 applied pressure (no contact) self.r_min_percent_of_r_no_contact = 0.001 # # end ###################################### self.r_no_contact = self.taxel_area * self.rtax_max self.r_min = self.r_no_contact * (self.r_min_percent_of_r_no_contact/100.0) self.fz_array = pl.arange(self.fz_min, self.fz_max, 0.001) # N self.adc_range = pow(2.0, self.adc_bits) self.volts_per_adc_unit = self.vtot/self.adc_range # V self.contact_area = self.taxel_area * (self.contact_area_percent/100.0) # m^2 self.no_contact_area = self.taxel_area - self.contact_area # m^2 self.pressure_array = pl.array([f/self.contact_area for f in self.fz_array]) # Pascals = N/m^2 self.rtax_array = pl.array([self.rtax(f) for f in self.pressure_array]) self.vdigi_array = pl.array([self.output_voltage(r) for r in self.rtax_array]) self.vdigi_max = self.output_voltage(self.rtax_max) self.adc_bias = self.vdigi_max/self.volts_per_adc_unit self.adc_array = self.vdigi_array/self.volts_per_adc_unit self.adc_plot = self.adc_bias - self.adc_array
def plotData(inputFile): masses, distances = getData(inputFile) masses = pylab.array(masses) distances = pylab.array(distances) forces = masses * 9.81 pylab.plot(forces, distances, 'bo', label='Measured displacements') pylab.title('Measured Displacement of Spring') pylab.xlabel('|Force| (Newtons)') pylab.ylabel('Distance (meters)') pylab.show()
def get_ind_under_point(self, event): 'get the index of the vertex under point if within epsilon tolerance' x, y = self.lx, self.ly d = sqrt((pl.array(x) - event.xdata)**2 + (pl.array(y) - event.ydata)**2) indseq = nonzero(equal(d, amin(d))) ind = indseq[0] if len(ind) > 1: ind = ind[0] if d[ind] >= self.epsilon: ind = None return ind
def makeMSFrame(dirname,msname,ra0,dec0,nchan): msstokes='RR LL'; feedtype='perfect R L'; ## Directory for the MS if(not os.path.exists(dirname)): cmd = 'mkdir ' + dirname; os.system(cmd); vx = [41.1100006, -34.110001, -268.309998, 439.410004, -444.210022] vy = [3.51999998, 129.8300018, +102.480003, -182.149994, -277.589996] vz = [0.25, -0.439999998, -1.46000004, -3.77999997, -5.9000001] d = [25.0, 25.0, 25.0, 25.0, 25.0] an = ['VLA1','VLA2','VLA3','VLA4','VLA5']; nn = len(vx)*2.0; x = 0.5*(vx - (sum(pl.array(vx))/(nn))); y = 0.5*(vy - (sum(pl.array(vy))/(nn))); z = 0.5*(vz - (sum(pl.array(vz))/(nn))); #### This call will get locations for all 27 vla antennas. #d, an, x, y, z = getAntLocations() obspos = me.observatory('EVLA'); #obspos = me.position('ITRF', '-0.0m', '0.0m', '3553971.510m'); ## Make MS Frame sm.open(ms=msname); sm.setconfig(telescopename='EVLA',x=x.tolist(),y=y.tolist(),z=z.tolist(),dishdiameter=d, mount=['alt-az'], antname=an, coordsystem='local',referencelocation=obspos); sm.setspwindow(spwname="CBand",freq="6.0GHz",deltafreq='500MHz', freqresolution='2MHz',nchannels=nchan,stokes=msstokes); sm.setfeed(mode=feedtype,pol=['']); sm.setfield( sourcename="fake",sourcedirection=me.direction(rf='J2000',v0=ra0,v1=dec0) ); sm.setlimits(shadowlimit=0.01, elevationlimit='10deg'); sm.setauto(autocorrwt=0.0); sm.settimes(integrationtime='1800s', usehourangle=True, referencetime=me.epoch('UTC','2013/05/10/00:00:00')); # Every 30 minutes, from -3h to +3h ostep = 0.5 for loop in pl.arange(-3.0,+3.0,ostep): starttime = loop stoptime = starttime + ostep print starttime, stoptime for ch in range(0,nchan): sm.observe(sourcename="fake",spwname='CBand', starttime=str(starttime)+'h', stoptime=str(stoptime)+'h'); sm.close(); listobs(vis=msname) return d
def get_ind_under_point(self, event): "get the index of the vertex under point if within epsilon tolerance" x, y = self.lx, self.ly d = sqrt((pl.array(x) - event.xdata) ** 2 + (pl.array(y) - event.ydata) ** 2) indseq = nonzero(equal(d, amin(d))) ind = indseq[0] if len(ind) > 1: ind = ind[0] if d[ind] >= self.epsilon: ind = None return ind
def plotNet(self, style): """ Plot an approxmation to the total cost of the mortgage over time by plotting the cash expended minus the equity acquired by paying off part of the loan""" totPd = [self.paid[0]] for i in range(1, len(self.paid)): totPd.append(totPd[-1] + self.paid[i]) equityAcquired = pylab.array([self.loan] * len(self.owed)) equityAcquired = equityAcquired - pylab.array(self.owed) net = pylab.array(totPd) - equityAcquired pylab.plot(net, style, label=self.legend)
def cubic_bezier(pts, t): """ Get points in a cubic bezier. """ p0, p1, p2, p3 = pts p0 = pylab.array(p0) p1 = pylab.array(p1) p2 = pylab.array(p2) p3 = pylab.array(p3) return p0 * (1 - t)**3 + 3 * t * p1 * (1 - t) ** 2 + \ 3 * t**2 * (1 - t) * p2 + t**3 * p3
def test_rmse(self): y = [1, 2, 3, 4, 5, 6, 7, 8, 9] estimate = [1, 4, 9, 16, 25, 36, 49, 64, 81] result = ps5.rmse(pylab.array(y), pylab.array(estimate)) correct = 35.8515457593 self.assertTrue(math.isclose(correct, result), "RMSE value incorrect") y = [1, 1, 1, 1, 1, 1, 1, 1, 1] estimate = [1, 4, 9, 16, 25, 36, 49, 64, 81] result = ps5.rmse(pylab.array(y), pylab.array(estimate)) correct = 40.513372278 self.assertTrue(math.isclose(correct, result), "RMSE value incorrect")
def fit_power(Ts, Rs, Rerr, pguess): 'Fit a power function to the data' Rs, Rerr = pylab.array(Rs), pylab.array(Rerr) model, ps = 'a * (x-x0)**(3/2)', 'a,x0' # Make intelligent guesses for the parameters a, x0 = pguess # Create a spinmob fitter fitter = spinmob.data.fitter(model, ps) fitter.set_data(Ts, Rs, Rerr) fitter.set(a=a, x0=x0) # Set guesses # Fit. fitter.fit() return fitter
def getData(fname): f = open(fname, 'r') X = [] Y = [] f.readline() # ignore header for line in f: # if line[0] == '#': # continue line = line[:-1] elems = line.rsplit(' ') X.append(float(elems[0])) Y.append(float(elems[1])) return plt.array(X), plt.array(Y)
def setpoly(self, coordarr): """ ra1,de1,ra2,de2... in decimal degrees """ self.type = "polygon" n = len(coordarr) / 2 c = pl.array(coordarr) xi = 2 * pl.array(range(n)) yi = xi + 1 self.coords = pl.array([c[xi], c[yi]]).T # TODO checks on coordarr - at least check if its even # TODO do we need to close the poly to make other things work? self.setbgcoords()
def fit_exp(Ts, Rs, Rerr, eguess): 'Fit an exponential function to the data' Rs, Rerr = pylab.array(Rs), pylab.array(Rerr) model, ps = 'a * exp(b / x)', 'a,b' # Make intelligent guesses for the parameters a, b = eguess b = pylab.log(Rs[0]/Rs[1]) / ( Rs[-1] - Rs[0] ) # Create a spinmob fitter fitter = spinmob.data.fitter(model, ps) fitter.set_data(Ts, Rs, Rerr) fitter.set(a=a, b=b) # Set guesses # Fit. fitter.fit() return fitter
def infer(model): print 'ok' label_np = array(Image.open('./data/test/Labels/10.png')) #label_np = cv2.cvtColor(label_np, cv2.COLOR_BGR2GRAY) img = Image.open('./data/test/Images/10.png') img_n = array(img) img_np = np.resize(img_n, (224, 224, 3)) #image = f.convert('RGB') #img_cuda= input_transform(image).cuda() print img_np.shape outputs = model( Variable(torch.from_numpy(img_np[np.newaxis, :].transpose(0, 3, 1, 2)).float(), volatile=True).cuda()) interp = nn.UpsamplingBilinear2d(size=(224, 224)) outputs = interp(outputs[3]).cpu().data[0].numpy() outputs = outputs[:, :img_np.shape[0], :img_np.shape[1]] print outputs.shape # outputs = np.array(outputs) # outputs = torch.from_numpy(outputs) # print outputs.shape outputs = outputs.transpose(1, 2, 0) outputs = np.argmax(outputs, axis=2) print outputs.shape mask = np.array(outputs) print type(mask) #sa=Image.fromarray(mask) #sa.save('1.png') cv2.imwrite('tuandao_10.png', mask * 120) #mask=array(outputs).argmax(axis=0) print('mask', mask.shape) print mask.max() print(label_np.shape) #a=(mask==label_np)*1 #same=a.sum() #acc=same/250000.0 #print acc # acc.dtype='float32' # print acc/(500*500) #print(label_np.max()) fig, ax = plt.subplots(1, 3) ax[0].imshow(img_np, cmap='gray') ax[1].imshow(mask) ax[2].imshow(label_np) plt.show() return 0
def fitData(fileName): xVals, yVals = getData(fileName) xVals = pylab.array(xVals) yVals = pylab.array(yVals) xVals = xVals * 9.81 # convert mass to force (F = mg) pylab.plot(xVals, yVals, 'bo', label='Measured points') pylab.title('Measured Displacement of Spring') pylab.xlabel('Force (Newtons)') pylab.ylabel('Distance (meters)') a, b = pylab.polyfit(xVals, yVals, 1) # fit y = ax + b # use line equation to graph predicted values estYVals = a * xVals + b k = 1 / a pylab.plot(xVals, estYVals, label='Linear fit, k = ' + str(round(k, 5))) pylab.legend(loc='best')
def RealtimePloter(arg): global values #current x axis (cxa) is the length of values from max length to length-100 cxa = range(len(values)-100,len(values),1) Stock1[0].set_data(cxa,pylab.array(values[-100:])) ax.axis([min(cxa),max(cxa),high,low]) manager.canvas.draw()
def splitfit(Ts, Rs, es, a, b, c, d, pguess, eguess, outfile=None): ## Split the data in two parts x1, x2, y1, y2, e1, e2 = [], [], [], [], [], [] for T, R, pe, ee in zip(Ts, Rs, es[0], es[1]): if a < T < b: x1.append(T) y1.append(abs(R)) e1.append(pe) elif c < T < d: x2.append(T) y2.append(abs(R)) e2.append(ee) ## Fit one part with the exponential fit1 = fit_power(x1, y1, e1, pguess) ## Fit one part with the polynomial fit2 = fit_exp(x2, y2, e2, eguess) res1 = fit1.results[0] res2 = fit2.results[0] fct1 = lambda x: res1[0] * (x - res1[1]) fct2 = lambda x: res2[0] * pylab.exp(res2[1]/x) Rs = pylab.array(Rs) Ges = [[[e/R**2] for R, e in zip(Rs, es[i])] for i in range(2)] pylab.clf() make_fig(Ts, Rs, Ges, a, b, c, d, fct1, fct2, outfile) return fit1, fit2
def buildCityPoints(fName, scaling): cityNames, featureList = readCityData(fName, scaling) points = [] for i in range(len(cityNames)): point = City(cityNames[i], pylab.array(featureList[i])) points.append(point) return points
def new_york_annual_temps(Climate): """ Takes in a instance of a climate object and plots model of a city's annual temperature trend over training period. """ #Get temperature for Jan 10th in New York city = "NEW YORK" new_york_temps = [] #Make training interval into pylab.array() to use as x values #Only convert to array once nothing else is needed to be added (otherwise have to copy all array everytime) x = pylab.array(TRAINING_INTERVAL) for year in x: #For every year get the mean temperature new_york_temps.append(Climate.get_yearly_temp(city, year).mean()) y = pylab.array(new_york_temps) model = generate_models(x, y, [1]) evaluate_models_on_training(x, y, model)
def to_scale_sound(self, tuning, f0=440., num_harmonics=6, dur=0.5, sr=44100.): """ :: Realize given tuning system as a scale, starting at frequency f0=440., using num_harmonics=6 complex tones with duration dur=0.5 seconds, and default sample rate sr=44100Hz. """ p = default_signal_params() p['num_harmonics'] = num_harmonics p['sr'] = sr p['num_points'] = int(round(dur * sr)) p.pop('f0') x = [] num_samples = p['num_points'] ramp = pylab.r_[pylab.array(pylab.linspace(0, 1, 100)), pylab.linspace(1, 0, num_samples - 100)] for rat in tuning: x = pylab.r_[x, ramp * harmonics(f0=f0 * rat, **p)] return x
def scaleFeatures(vals): """Assumes vals is a sequence of numbers""" result = pylab.array(vals) mean = sum(result) / float(len(result)) result -= mean sd = stdDev(result) result /= sd return result
def testfunction(data): # N-D Gaussian or N-D Runge Function N, sd = data.shape f = ones((N,1)) for i in range(sd): #f = f*array([exp(-15*(data[:,i]-0.5)**2)]).T f = f*array([1./(1+(5*data[:,i])**2)]).T return f
def main(data_files, a, b, c, d, pguess, eguess, perr=1, eerr=1, outfile=None): xs, ys, es, Ns = [], [], [], [] for df in data_files: databox = spinmob.data.load(df) x, y, e, N = databox[:4] xs += list(x) ys += [abs(i) for i in y] es += list(e) Ns += list(N) xs, ys, es, Ns = pylab.array(xs), pylab.array(ys), pylab.array(es), pylab.array(Ns) pes, ees = perr / pylab.sqrt(Ns), eerr / pylab.sqrt(Ns) if 'current' in databox.hkeys: current = databox.h('current') else: current = 0.001 # A databox.h(current=current) Rs = ys / current Rerrs = pes / current, ees / current fits = splitfit(xs, Rs, Rerrs, a, b, c, d, pguess, eguess, outfile) return fits
def main(data_files, a, b, c, d, pguess, eguess, perr=1, eerr=1, I=0.001, B=0.5003991, sample_thickness=1e-3, outfile=None): R_H = lambda V_H: V_H*sample_thickness / (I*B) # Vm/AT R_He = lambda V_H, V_He: pylab.sqrt(\ ( sample_thickness/(I*B) * V_He )**2 + \ ( V_H / (I*B) * 1e-4 )**2 + \ ( V_H * sample_thickness / (B**2 * I) * 2e-8 )**2 ) xs, ys, es, Ns = [], [], [], [] for df in data_files: databox = spinmob.data.load(df) x, y, e, N = databox[:4] xs += list(x) ys += [R_H(i) for i in y] es += [R_He(i, j) for i, j in zip(y, e)] Ns += list(N) xs, ys, es, Ns = pylab.array(xs), pylab.array(ys), pylab.array(es), pylab.array(Ns) pes, ees = perr / pylab.sqrt(Ns), eerr / pylab.sqrt(Ns) fits = splitfit(xs, ys, (pes, ees), a, b, c, d, pguess, eguess, outfile) return fits
def pruning_plot(costs, figname, max_cost=None): if max_cost == None: max_cost = max(costs) assert max_cost in costs costs = PP.array(costs) costs /= float(max_cost) assert 1 in costs PP.plot(range(len(costs)), costs) PP.xlabel('time steps') PP.ylabel('proportion of edges in use') PP.savefig(figname + '.png', format='png')
def getAntLocations(configuration='D'): vx = [41.1100006, 134.110001, 268.309998, 439.410004, 644.210022, 880.309998, 1147.10999, 1442.41003, 1765.41003, -36.7900009, -121.690002, -244.789993, -401.190002, -588.48999, -804.690002, -1048.48999, -1318.48999, -1613.98999, -4.38999987,-11.29, -22.7900009, -37.6899986, -55.3899994, -75.8899994, -99.0899963, -124.690002, -152.690002]; vy = [3.51999998, -39.8300018, -102.480003, -182.149994, -277.589996, -387.839996, -512.119995, -649.76001, -800.450012, -2.58999991, -59.9099998, -142.889999, -248.410004, -374.690002, -520.599976, -685, -867.099976, -1066.42004, 77.1500015, 156.910004, 287.980011, 457.429993, 660.409973, 894.700012, 1158.82996, 1451.43005, 1771.48999]; vz = [0.25, -0.439999998, -1.46000004, -3.77999997, -5.9000001, -7.28999996, -8.48999977, -10.5, -9.56000042, 0.25, -0.699999988, -1.79999995, -3.28999996, -4.78999996, -6.48999977, -9.17000008, -12.5299997, -15.3699999, 1.25999999, 2.42000008, 4.23000002, 6.65999985, 9.5, 12.7700005, 16.6800003, 21.2299995, 26.3299999]; d = [25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0, 25.0]; if(configuration=='D'): scale = 3.0; else: if(configuration=='A'): scale = 1.0/9.0; else: scale = 1.0; print 'Using VLA C-array coords'; nn = len(vx); x = (vx - (sum(pl.array(vx))/(nn)))/scale; y = (vy - (sum(pl.array(vy))/(nn)))/scale; z = (vz - (sum(pl.array(vz))/(nn)))/scale; an=[]; for i in range(0,nn): an.append("VLA"+str(i)); return d,an,x,y,z
def run(self): """ Thread loop In an infinite loop, it reads the TDC buffer, converts it in time, and optionally create the histogram To stop the loop, set self.kill = True """ self.kill = False self.demon = True tic = time.time() new_data = [] i = 0 while not self.kill: i += 1 time.sleep(0.04) d = readBuffer() print "%6d"%len(d), #d = random.rand(10)*100 new_data.extend(d) if i %5 == 0: print "" new_data = pl.array(new_data) ## Remove timeouts #t = pl.nonzero(new_data < 3000) try: new_data = new_data[new_data < 3000] except IndexError: pass self.data.extend(new_data) toc = time.time()-tic print "Counts / sec = %8.2f"%(1.*len(new_data)/toc) print ' Starts ', ## Generate channels histogram if self.do_histograms: self.hist = generateHist(new_data, self.bins, rnge= self.rnge,histogram = self.hist[1]) #print "Ch1 ",self.hist[1] ## Save a tempfile and flush (just to be sure) if self.temp_file != None: for d in new_data: self.temp_file.write( "%12.3f \n"%(d) ) tic = time.time() new_data = []
def vert_vectorize(self, arg=None): from matplotlib.pylab import array #assume copy is raw data-points in vertical order data_points = [] #base for final array tmp_list = [] #temporary list for converting to float for line in self.infile: #loops through each line of copy for points in line.split(): #loops through each element in line #add each element of line as float to a temporary list tmp_list.append(float(points)) data_points.append(tmp_list) #make nested list tmp_list = [] data_points = array(data_points) return data_points
def make_error(data_file, xin=None): databox = spinmob.data.load(data_file) errs = [] xs = databox.c('c8') xs -= xs[0] for i in range(6): vals = databox.c('c{:d}'.format(i)) if xin: vals = pylab.array([v for x, v in zip(xs, vals) if xin[0] <= x <= xin[1]]) std = pylab.std(vals) errs.append(std) err = pylab.mean(errs) return err, errs
def main(datafile, err): # load a *.txt data file (see spinmob wiki for formatting rules) d = spinmob.data.load(datafile) # create a fitter object (with a reasonable guess for the Rutherford file) f = spinmob.data.fitter('a*(x-x0)**2+b', 'a,x0,b') # set the data and error bar ys = d.c('R_=_V/I_(ohm)') # Ohms xs = d.c('B_(mT)') / 1000 # T es = d.c('error_V5') # V es = [numpy.sqrt(e**2 + (y*1e-4)**2 + (y*1e-4)**2) for y, e in zip(ys, es)] es = pylab.array(es) / 1.2 a = -(ys[-1]-ys[0])/(xs[-1]**2-xs[0]**2) x0 = 0 b = 65 f.set_data(xs, ys, es) f.set(a=a, x0=x0, b=b) f.fit() res1 = f.results[0] fct1 = lambda x: res1[0] * (x - res1[1])**2 + res1[2] plt.clf() fig = pylab.figure() gs = gridspec.GridSpec(4, 4) TR = fig.add_subplot(gs[1:, :]) TR.errorbar(xs, ys, es, fmt=',') Xs = pylab.linspace(min(xs), max(xs)) TR.plot(Xs, fct1(Xs), '-', color='red') pylab.xlabel('Magnetic field ($\\times10^{-1}\\mathrm{T}$)') pylab.xticks(pylab.linspace(0, 0.5, 6), ['{:1.0f}'.format(i) for i in range(6)]) pylab.xlim(min(xs), max(xs)) pylab.ylabel('Resistance ($\\Omega$)') residual1 = fig.add_subplot(gs[0, :]) rs = [(y - fct1(x))/e for x, y, e in zip(xs, ys, es)] residual1.errorbar(xs, rs, 1, fmt=',', color='blue') xs = pylab.linspace(min(xs), max(xs), 3) residual1.plot(xs, [0 for x in xs], '-', color='red') residual1.xaxis.tick_top() pylab.xticks([]) pylab.xlim(min(xs), max(xs)) pylab.yticks([]) pylab.ylabel('Studentized\nresidual') plt.savefig('../Graphs/Magnetoresistance/Fit.png') plt.savefig('../Graphs/Magnetoresistance/Fit.pdf') return f
def show_color_images(samples, nsamples, d1, d2, nrows, ncols): """ Plots samples in a NumPy 2D array ``samples`` as ``d1`` by ``d2`` images. (one sample per row of ``samples``). The samples are assumed to be color images. The first ``d1*d2`` elements of each row are the R channel values of each pixel, then follows the G and B channels. The images are layed out in a ``nrows`` by ``ncols`` grid. Thanks to Ilya Sutskever for sharing his code, from which this code is inspired. """ samples = samples[:nsamples,:] def fix(X): Y = X - X.min() Y /= Y.max() return Y def print_aligned(w): n1 = nrows n2 = ncols r1 = d1 r2 = d2 Z = numpy.zeros(((r1+1)*n1, (r1+1)*n2), 'd') i1, i2 = 0, 0 for i1 in range(n1): for i2 in range(n2): i = i1*n2+i2 if i>=w.shape[1]: break Z[(r1+1)*i1:(r1+1)*(i1+1)-1, (r2+1)*i2:(r2+1)*(i2+1)-1] = w[:,i].reshape(r1,r2) return Z R = samples[:,:(d1*d2)] G = samples[:,(d1*d2):(2*d1*d2)] B = samples[:,(2*d1*d2):(3*d1*d2)] img = array([print_aligned(R.T), print_aligned(G.T), print_aligned(B.T)]).transpose([1, 2, 0]) imshow(fix(img), interpolation='nearest') xticks([]) yticks([])
def test_interp(): # Testing interpolation nn = 33 # number of nodes ne = 65 # number of evaluation points x = cos(pi*(1+array(range(nn)))/(nn+1)) xp = linspace(-1,1,ne) rbf_list = ['mq','gauss','phs'] ep_list = [3.,5.,7.,9.] m = 3 for ep in ep_list: for ff in rbf_list: # 1D d = array([x]).T p = array([xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("1D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) # 2D d = array([x,x]).T p = array([xp,xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("2D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) # 3D d = array([x,x,x]).T p = array([xp,xp,xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("3D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) print("----------------------------------------------------------")
def residuals_duri_global(p, y, x,yerr,qval): print p #not the squared ones, squaring will be handled by leastsq err = 0 xplot=pyl.array(x,typecode='d') for i,q in enumerate(qval): q= float(q) y_calc=peval_duri_global(x,p,q) # y_calcplot=pyl.array(y_calc,typecode='d') err+=(y[i,:]-y_calc)**2 # err+=y[i,:]-y_calc # pyl.figure(2) # yplot=pyl.array(y[i,:],typecode='d') # pyl.subplot(211) # pyl.semilogx(xplot,y_calcplot-yplot,'-') # pyl.hold(False) # pyl.subplot(212) # pyl.semilogx(xplot,yplot,'o',xplot,y_calcplot,'-') # pyl.hold(False) err = sqrt(err) return err
def test_dmatrix(): # Unit tests for the dmatrix function x = linspace(0,1,5) # Test 1D without formatting input, data is 1D, shape is (N,) data = x DM = dmatrix(data) print(DM) # Test 1D with x in wrong orientation (dim by N pts), data is 2D array data = array([x]) DM = dmatrix(data) print(DM) # Test 1D with x in correct orientation (N by dim pts), data is 2D array data = array([x]).T DM = dmatrix(data) print(DM) # Test 2D with x in wrong orientation (dim by N pts), data is 2D array data = array([x,x]) DM = dmatrix(data) print(DM) # Test 2D with x in correct orientation (N by dim pts), data is 2D array data = array([x,x]).T DM = dmatrix(data) print(DM) # Test 3D with x in wrong orientation (dim by N pts), data is 2D array data = array([x,x,x]) DM = dmatrix(data) print(DM) # Test 3D with x in correct orientation (N by dim pts), data is 2D array data = array([x,x,x]).T DM = dmatrix(data) print(DM)
# Main simulation procedure, setting up extracellular electrode, cell, synapse ################################################################################ #close open figures pl.close('all') #create extracellular electrode object electrode = LFPy.RecExtElectrode(**electrodeParameters) #Initialize cell instance, using the LFPy.Cell class cell = LFPy.Cell(**cellParameters) #set the position of midpoint in soma to Origo (not needed, this is the default) cell.set_pos(xpos = 0, ypos = 0, zpos = 0) #rotate the morphology 90 degrees around z-axis cell.set_rotation(z = pl.pi/2) #attach synapse with parameters and set spike time synapse = LFPy.Synapse(cell, **synapseParameters) synapse.set_spike_times(pl.array([1])) #perform NEURON simulation, results saved as attributes in the cell instance #cell.simulate(electrode = electrode, rec_isyn=True) # Plotting of simulation results: plotstuff(cell, electrode) #pl.savefig('example2.pdf') #pl.show()