def calcBIS(self, x, y, bisect_val=[0.35, 0.95], n_ord=None): """ Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k. """ y_low = np.max(y)*bisect_val[0] y_high = np.max(y)*bisect_val[1] s_low = interpolate.splrep(x.value, y - y_low) s_high = interpolate.splrep(x.value, y - y_high) roots_low = interpolate.sproot(s_low, mest=2) roots_high = interpolate.sproot(s_high, mest=2) if (len(roots_low) == 2) and (len(roots_high) == 2): low = [self.subpixel_CCF(x, y, v=roots_low[0]), self.subpixel_CCF(x, y, v=roots_low[1])] high = [self.subpixel_CCF(x, y, v=roots_high[0]), self.subpixel_CCF(x, y, v=roots_high[1])] _, err, _, _ = self.extract_RV(x, y, n_ord=n_ord) BIS = (low[1]+low[0])/2 - (high[1]+high[0])/2 eBIS = np.sqrt(2)*err return BIS, eBIS, x.unit else: return np.nan, np.nan, None
def get_next_time(self, t_0): """Get time from *t_0* when the trajectory will have travelled more than pixel size.""" if self.stationary: return np.inf * q.s elif not self.bound: raise TrajectoryError("Trajectory not bound") u_0 = self.get_parameter(t_0) distances = self.get_distances(u_0=u_0) # Use the same parameter for distances and trajectory so that we can directly use the # parameter for time calculation. This is however an approximation and if the distance # spline doesn't have enough points it can cause inaccuracies. dtck = interp.splprep(distances, u=self.parameter, s=0)[0] def shift_spline(sgn): t, c, k = dtck c = np.array(c) + sgn * self._pixel_size.simplified.magnitude return t, c, k t_1 = t_2 = np.inf lower_tck = shift_spline(1) upper_tck = shift_spline(-1) # Get the +/- distance roots (we can traverse the trajectory backwards) lower = interp.sproot(lower_tck) upper = interp.sproot(upper_tck) # Combine lower and upper into one list of roots for every dimension roots = [np.concatenate((lower[i], upper[i])) for i in range(3)] # Mix all dimensions, they are not necessary for obtaining the minimum # parameter difference roots = np.concatenate(roots) # Filter roots to get only the infimum and supremum based on u_0 smallest = smath.infimum(u_0, roots) greatest = smath.supremum(u_0, roots) # Get next time for both directions if smallest is not None: t_1 = self._get_next_time(t_0, smallest) if t_1 is None: t_1 = np.inf if greatest is not None: t_2 = self._get_next_time(t_0, greatest) if t_2 is None: t_2 = np.inf # Next time is the smallest one which is greater than t_0. # Get a supremum and if the result is not infinity there # is a time in the future for which the trajectory moves # the associated object more than *distance*. closest_time = smath.supremum(t_0.simplified.magnitude, [t_1, t_2]) return closest_time * q.s
def intercept(self, y): '''Find the value of x for which the interpolator goes through [y]''' # use a fun little trick: if self.realization: tck = self.realization[0][::],self.realization[1]-y,\ self.realization[2] else: tck = self.tck[0][::],self.tck[1]-y,self.tck[2] roots = sproot(tck) gids = num.greater_equal(roots,tck[0][0])*num.less_equal(roots,tck[0][-1]) return sproot(tck)
def encased_old(self): """ see encased, but is too slow due to sproot """ def shift_spline(spline, shift_vec): spline_coefficients = np.array(spline[1]) return [ spline[0], [ spline_coefficients[0] + shift_vec[0], spline_coefficients[1] + shift_vec[1]], spline[2]] encased_from_top = [] encased_from_below = [] idx = 0 TOLERANCE_THERESHOLD = 10**-2 for knots in self._knots: for _ in knots: ys = [] for spline_compare in self._splines: spline_shifted = shift_spline( spline_compare, [-self.x_position[idx], 0]) roots = interpolate.sproot(spline_shifted, mest=10) if len(roots[0]) > 0: ys.extend(interpolate.splev( roots[0], spline_compare)[1]) encased_from_top.append( 1*any(y > self.y_position[idx] + TOLERANCE_THERESHOLD for y in ys)) encased_from_below.append( 1*any(y < self.y_position[idx] - TOLERANCE_THERESHOLD for y in ys)) idx += 1 return encased_from_below, encased_from_top
def _area_vs_hamiltonian_fine(tck_potential_well, indexAmplitude, min_n_points): tck_adjusted = (tck_potential_well[0], tck_potential_well[1] - tck_potential_well[1][indexAmplitude], tck_potential_well[2]) roots_adjusted = interp.sproot(tck_adjusted) if len(roots_adjusted) != 2: return left_position = np.min(roots_adjusted) right_position = np.max(roots_adjusted) n_points_reinterp = len( np.where((tck_potential_well[0] >= left_position) * (tck_potential_well[0] <= right_position))[0]) if n_points_reinterp < min_n_points: n_points_reinterp = min_n_points fine_time_array = np.linspace(left_position, right_position, n_points_reinterp) fine_potential_well = interp.splev(fine_time_array, tck_adjusted) + \ tck_potential_well[1][indexAmplitude] return fine_time_array, fine_potential_well
def fwhm(t_hrf, hrf, k=3): """Return the full width at half maximum. Parameters: ----------- t_hrf : 1d np.ndarray, the sampling od time. hrf : 1d np.ndarray, the HRF. k : int (default=3), the degree of spline to fit the HRF. Return: ------- fwhm : float, the FWHM """ half_max = np.amax(hrf) / 2.0 s = splrep(t_hrf, hrf - half_max, k=k) roots = sproot(s) try: return np.abs(roots[1] - roots[0]) except IndexError: return -1
def getYcrossings(curveX, curveY, xgrid, ygrid): splineY, u = interp.splprep((curveX, curveY), s=0, k=3, per=True) ty, cy, ky = splineY xvalsy, yvalsy = cy posY = [[], []] derY = [[], []] for i, shifty in enumerate(ygrid): newcy = ((np.array(xvalsy), np.array(yvalsy) - shifty)) shiftedSplineY = (ty, newcy, ky) rootsY = interp.sproot(shiftedSplineY) if (len(rootsY[1])): posYtemp = interp.splev(rootsY[1], splineY) posY[0] = posY[0] + list(posYtemp[0]) posY[1] = posY[1] + list(posYtemp[1]) derYtemp = interp.splev(rootsY[1], splineY, der=1) for ind in range(len(derYtemp[0])): derYtemp[0][ind], derYtemp[1][ind] = (np.array( (derYtemp[0][ind], derYtemp[1][ind])) / np.sqrt( (derYtemp[0][ind]**2 + derYtemp[1][ind]**2))) derY[0] = derY[0] + list(derYtemp[0]) derY[1] = derY[1] + list(derYtemp[1]) return np.array(posY).T, np.array(derY).T
def fwhm(x, y, k=10): # http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak """ Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k. """ class MultiplePeaks(Exception): pass class NoPeaksFound(Exception): pass half_max = np.amax(y) / 2.0 s = splrep(x, y - half_max) roots = sproot(s) if len(roots) > 2: raise MultiplePeaks("The dataset appears to have multiple peaks, and " "thus the FWHM can't be determined.") elif len(roots) < 2: raise NoPeaksFound("No proper peaks were found in the data set; likely " "the dataset is flat (e.g. all zeros).") else: return roots[0], roots[1]
def fwhm(x, y, k=5): """ Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k. """ class MultiplePeaks(Exception): pass class NoPeaksFound(Exception): pass half_max = np.amax(y) / 2.0 s = splrep(x, y - half_max) roots = sproot(s) if len(roots) > 2: return roots raise MultiplePeaks("The dataset appears to have multiple peaks, and " "thus the FWHM can't be determined.") elif len(roots) < 2: raise NoPeaksFound( "No proper peaks were found in the data set; likely " "the dataset is flat (e.g. all zeros).") else: return abs(roots[1] - roots[0])
def hamFindGiao2Interpolation(x, y1, y2): # chuan bi data roi rac y3 = y2 - y1 #ve thu data roi rac # plt.plot(x, y1,'x') # plt.plot(x, y2,'o') # plt.show() #noi suy #tck1 = interpolate.splrep(x, y1, s=0) #tck2 = interpolate.splrep(x, y2, s=0) tck3 = interpolate.splrep(x, y3, s=0) #ve thu ham sau noi suy # x_new=x # y1_new=interpolate.splev(x_new, tck1, der=0) # y2_new=interpolate.splev(x_new, tck2, der=0) # y3_new=interpolate.splev(x_new, tck3, der=0) # plt.plot(x, y1,'x',x_new, y1_new,'b') # plt.plot(x, y2,'o',x_new, y2_new,'r') # plt.plot(x, y3,'o',x_new, y3_new,'-') #plt.plot() #plt.savefig("xacsuat_b.pdf") #tim nghiem cua 2 duong return interpolate.sproot(tck3)[0] #khi co 1 diem cat
def period_estimation_spline(signal_one_pixel, stepSize): signal_one_pixel -= np.mean(signal_one_pixel) nsteps = np.size(signal_one_pixel) xg = np.mgrid[0:(nsteps-1)*stepSize:nsteps*1j] xg2 = np.mgrid[0:(nsteps-1)*stepSize:nsteps*10j] tck = splrep(xg, signal_one_pixel) y2 = splev(xg2, tck) estimated_period = np.mean(np.diff(sproot(tck)))*2 plt.figure() plt.plot(xg*1e6, signal_one_pixel, '-o', xg2*1e6, y2, '--.') plt.annotate(r'period = {:.3} $\mu m$'.format(estimated_period*1e6), xy=(.80, .90), xycoords='axes fraction', xytext=(-20, 20), textcoords='offset pixels', fontsize=16, bbox=dict(boxstyle="round", fc="0.9")) plt.legend(['data', 'spline'], loc=4) plt.xlabel(r'$\mu m$') plt.ylabel('Counts') plt.grid() plt.show(block=False) return estimated_period
def find_extrema(self, xmin=None, xmax=None): '''Find the position and values of the maxima/minima. Returns a tuple: (roots,vals,ypps) where roots are the x-values where the extrema occur, vals are the y-values at these points, and ypps are the 2nd derivatives. Optionall, search only betwwen xmin and xmax.''' #evaluate the 1st derivative at k+1 intervals between the knots if self.realization: t,c,k = self.realization else: t,c,k = self.tck if xmax is None: xmax = t[-1] if xmin is None: xmin = t[0] x0s = t[k:-k] xs = [] for i in range(len(x0s)-1): xs.append(num.arange(x0s[i],x0s[i+1],(x0s[i+1]-x0s[i])/(k+1))) xs = num.concatenate(xs) yps = self.deriv(xs, n=1) # now find the roots of the 1st derivative tck2 = splrep(xs, yps, k=3, s=0) roots = sproot(tck2) curvs = [] vals = [] for root in roots: vals.append(self.__call__(root)[0]) curvs.append(self.deriv(root, n=2)) gids = num.greater_equal(roots,xmin)*num.less_equal(roots,xmax) curvs = num.where(num.equal(curvs,0), 0, curvs/num.absolute(curvs)) return roots[gids],num.array(vals)[gids],num.array(curvs)[gids]
def find_extrema(self, xmin=None, xmax=None): '''Find the position and values of the maxima/minima. Returns a tuple: (roots,vals,ypps) where roots are the x-values where the extrema occur, vals are the y-values at these points, and ypps are the 2nd derivatives. Optionall, search only betwwen xmin and xmax.''' #evaluate the 1st derivative at k+1 intervals between the knots if self.realization: t, c, k = self.realization else: t, c, k = self.tck if xmax is None: xmax = t[-1] if xmin is None: xmin = t[0] x0s = t[k:-k] xs = [] for i in range(len(x0s) - 1): xs.append( num.arange(x0s[i], x0s[i + 1], (x0s[i + 1] - x0s[i]) / (k + 1))) xs = num.concatenate(xs) yps = self.deriv(xs, n=1) # now find the roots of the 1st derivative tck2 = splrep(xs, yps, k=3, s=0) roots = sproot(tck2) curvs = [] vals = [] for root in roots: vals.append(self.__call__(root)[0]) curvs.append(self.deriv(root, n=2)) gids = num.greater_equal(roots, xmin) * num.less_equal(roots, xmax) curvs = num.where(num.equal(curvs, 0), 0, curvs / num.absolute(curvs)) return roots[gids], num.array(vals)[gids], num.array(curvs)[gids]
def get_root(up=1): y_s = interp.splev(x_0, tck) + up * y_d t, c, k = np.copy(tck) # Adjust spline coefficients to be able to find f(x) = 0. c -= y_s return closest(interp.sproot((t, c, k)), x_0)
def getXcrossings(curveX, curveY, xgrid, ygrid): splineX, u = interp.splprep((curveY, curveX), s=0, k=3, per=True) tx, cx, kx = splineX xvalsx, yvalsx = cx posX = [[], []] derX = [[], []] for shiftx in xgrid: newcx = ((np.array(xvalsx), np.array(yvalsx) - shiftx)) shiftedSplineX = (tx, newcx, kx) rootsX = interp.sproot(shiftedSplineX) if (len(rootsX[1])): posXtemp = interp.splev(rootsX[1], splineX) posX[0] = posX[0] + list(posXtemp[1]) posX[1] = posX[1] + list(posXtemp[0]) derXtemp = interp.splev(rootsX[1], splineX, der=1) for ind in range(len(derXtemp[0])): derXtemp[0][ind], derXtemp[1][ind] = (np.array( (derXtemp[0][ind], derXtemp[1][ind])) / np.sqrt( (derXtemp[0][ind]**2 + derXtemp[1][ind]**2))) derX[0] = derX[0] + list(derXtemp[1]) derX[1] = derX[1] + list(derXtemp[0]) return np.array(posX).T, np.array(derX).T
def above_threshold(x, y, k=10, threshold=0.99): """ Determine the "width above the threshold" The function uses a spline interpolation of order k. """ half_max = amax(y)/2.0 s = splrep(x, y - threshold) roots = sproot(s) if len(roots)==0: interv = [(x[0], x[-1])] else: interv = [(x[0],roots[0])] for r in roots[1:]: interv.append((interv[-1][-1], r)) interv.append((interv[-1][-1], x[-1])) tot = 0 len_max = 0 for start, stop in interv: if(splev((start+stop)/2, s)>0): tot += stop - start if stop-start>len_max: len_max = stop-start pylab.figure("reflexion") xx = linspace(x[0],x[-1],1000) yy = splev(xx, s) + threshold pylab.plot(xx,yy) pylab.plot(x,y) return len_max
def fit_lorentzian(x,y): # f_guess_y0: should be the function min for resonance dips and max for gain curves index, ymax = max(enumerate(y), key=operator.itemgetter(1)) ymax = np.average(y[index - 5: index + 6]) #average near max point to account for noisy data x0 = x[index] y0 = min(y) spline = splrep(x, y-(y0+ymax)/2) roots = sproot(spline) whm = roots[-1]-roots[0] # y0=-0.00072 #x0=7.68377*1e9 # whm=5e6 B = whm*whm/4.0 B = B #correction to start initial bandwidth larger A = B*(ymax-y0) #print x0,y0,B,A #x0=7.68374*1e9;y0=0.0019;B=((100*1e3)**2)/4;A=B*(max(y)-min(y)) #weights = (1,) popt, pcov = curve_fit(lorentzian,x,y,(x0,y0,A,B)) #popt=[x0,y0,A,B] return popt
def period_estimation_spline(signal_one_pixel, stepSize): signal_one_pixel -= np.mean(signal_one_pixel) nsteps = np.size(signal_one_pixel) xg = np.mgrid[0:(nsteps - 1) * stepSize:nsteps * 1j] xg2 = np.mgrid[0:(nsteps - 1) * stepSize:nsteps * 10j] tck = splrep(xg, signal_one_pixel) y2 = splev(xg2, tck) estimated_period = np.mean(np.diff(sproot(tck))) * 2 plt.figure() plt.plot(xg * 1e6, signal_one_pixel, '-o', xg2 * 1e6, y2, '--.') plt.annotate(r'period = {:.3} $\mu m$'.format(estimated_period * 1e6), xy=(.80, .90), xycoords='axes fraction', xytext=(-20, 20), textcoords='offset pixels', fontsize=16, bbox=dict(boxstyle="round", fc="0.9")) plt.legend(['data', 'spline'], loc=4) plt.xlabel(r'$\mu m$') plt.ylabel('Counts') plt.grid() plt.show(block=False) return estimated_period
def half_peak_domain(x, y, negative_peak=True, plot=False): """ Finding the half peak domain (for calculation of the half peak width) using B-spline interpolation. Note: Assuming the baseline is 0. :param x, y: data describing the function y(x) :param negative_peak: True if fitting the negative peak, default False :param plot: True if plot for debugging :return: domain: a list of two values x' for which y(x')==y_peak/2 """ y_peak, index_peak = (min(y), np.argmin(y)) if negative_peak else (max(y), np.argmax(y)) x_peak = x[index_peak] spline_representation = interpolate.splrep(x, y) xs, ys, k = spline_representation roots = interpolate.sproot((xs, ys - y_peak/2, k)) roots = np.hstack((min(x),roots, max(x))) # ensure x_peak is not at either end of the list index_roots = np.searchsorted(roots, x_peak) domain = list(roots[range(index_roots-1, index_roots+1)]) if plot: logging.info ('Peak at %f, with half width domain %f ~ %f' % (x_peak, min(domain), max(domain))) xnew = np.arange(min(x), max(x), step=min(np.diff(x))/5) ynew = interpolate.splev(xnew, spline_representation) plt.plot(x, y, 'x', xnew, ynew, 'b-') annotate_x_bar(domain, y_peak / 2) plt.show() return domain
def fit_fwhm_enclosed_direct(peak, rad, flux): # We use splines to interpolate and derivate spl = splrep(rad, flux) # First derivative vald1 = splev(rad, spl, der=1) splinter = splrep(rad, vald1 - math.pi * peak * rad) roots = sproot(splinter) nroots = len(roots) if peak < 0: msg = "The method doesn't converge, peak is negative" fwhm = -99 else: if nroots == 0: msg = "The method doesn't converge, no roots" fwhm = -99 elif nroots == 1: r12 = roots[0] fwhm = 2 * r12 msg = "The method converges, one root" else: msg = "The method doesn't converge, multiple roots" r12 = roots[0] fwhm = 2 * r12 return peak, fwhm, msg
def debye_temp(num_formula_units, tdata, cvph_t, cvph_v, inppath, outpath, T_accurate): filedebye = open(outpath + "/DebyeT-%s.dat" % (str(T_accurate)), 'w') filedebye.write("# T/K Debye temperature\n") for nV, P in enumerate(cvph_v[0][:, 0]): filedebye.write("# V=%18.13f\n" % cvph_v[0][:, 0][nV]) for nT, t in enumerate(tdata): xlist = [] ydifflist = [] theta_d = 1.0 while theta_d < 1000: xlist.append(theta_d) if t == 0: t = 1 x0 = theta_d / t yint, err = integrate.quad(Constants.y, 0.0, x0) cv_debye = 9 * R * x0**(-3) * yint # Compare C_V of the lattice vib. with C_V from the Debye model. ydifflist.append(cvph_t[nV][nT][1] / num_formula_units - cv_debye) theta_d += 10 tck = interpolate.splrep(xlist, ydifflist) root = interpolate.sproot(tck, mest=100) if list(root): filedebye.write("%8.3f%20.1f\n" % (t, root[0])) filedebye.write("\n") filedebye.close return None
def zero_find(xVals, yVals): """To find zero points for function y(x) using iterpolation """ # TODO: may be improved for near degenerate states # For eigen energy solver, psiEnd's dependence on energy is significant # near eigenenergy tck = interpolate.splrep(xVals.real, yVals.real) # print "------debug------ Here zero_find is called" return interpolate.sproot(tck, mest=len(xVals))
def test_roots(self): x = np.linspace(0, 1, 31)**2 y = np.sin(30*x) spl = splrep(x, y, s=0, k=3) pp = PPoly.from_spline(spl) r = pp.roots() r = r[(r >= 0) & (r <= 1)] assert_allclose(r, sproot(spl), atol=1e-15)
def test_roots(self): x = np.linspace(0, 1, 31)**2 y = np.sin(30 * x) spl = splrep(x, y, s=0, k=3) pp = PPoly.from_spline(spl) r = pp.roots() r = r[(r >= 0) & (r <= 1)] assert_allclose(r, sproot(spl), atol=1e-15)
def find_cross_point(y1, y2): ydiff = y2 - y1 xlist = [i[0] for i in y1] ydifflist = [i[1] for i in ydiff] tck = interpolate.splrep(xlist, ydifflist) root = interpolate.sproot(tck, mest=100) return root
def plot_fwhm(x, y, k=10): y_max = amax(y) s = splrep(x, y - y_max / 2.0) r1, r2 = sproot(s) xx = linspace(amin(x), amax(x), 200) yy = splev(xx, s) + y_max / 2.0 f = figure() plot(x, y, 'ko') plot(xx, yy, 'r-') axvspan(r1, r2, facecolor='k', alpha=0.5) return f
def test_sproot(self): b, b2 = self.b, self.b2 roots = np.array([0.5, 1.5, 2.5, 3.5]) * np.pi # sproot accepts a BSpline obj w/ 1D coef array assert_allclose(sproot(b), roots, atol=1e-7, rtol=1e-7) assert_allclose(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7) # ... and deals with trailing dimensions if coef array is n-D with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) r = sproot(b2, mest=50) r = np.asarray(r) assert_equal(r.shape, (3, 2, 4)) assert_allclose(r - roots, 0, atol=1e-12) # and legacy behavior is preserved for a tck tuple w/ n-D coef c2r = b2.c.transpose(1, 2, 0) rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50)) assert_equal(rr.shape, (3, 2, 4)) assert_allclose(rr - roots, 0, atol=1e-12)
def roots(self): """ Return the zeros of the spline. Note: Only cubic splines are supported. """ if self.degree != 3: raise RuntimeError('finding roots unsupported for non-cubic splines') z,m,ier = sproot(*self.tck(), mest = 10); if not ier == 0: raise RuntimeError("Error code returned by spalde: %s" % ier) return z[:m];
def plot_fwhm(x, y, k=10): y_max = amax(y) s = splrep(x, y - y_max/2.0) r1, r2 = sproot(s) xx = linspace(amin(x), amax(x), 200) yy = splev(xx, s) + y_max/2.0 f = figure() plot(x, y, 'ko') plot(xx, yy, 'r-') axvspan(r1, r2, facecolor='k', alpha=0.5) return f
def test_sproot(self): b, b2 = self.b, self.b2 roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi # sproot accepts a BSpline obj w/ 1D coef array assert_allclose(sproot(b), roots, atol=1e-7, rtol=1e-7) assert_allclose(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7) # ... and deals with trailing dimensions if coef array is n-D with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) r = sproot(b2, mest=50) r = np.asarray(r) assert_equal(r.shape, (3, 2, 4)) assert_allclose(r - roots, 0, atol=1e-12) # and legacy behavior is preserved for a tck tuple w/ n-D coef c2r = b2.c.transpose(1, 2, 0) rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50)) assert_equal(rr.shape, (3, 2, 4)) assert_allclose(rr - roots, 0, atol=1e-12)
def test_sproot(self): b, b2 = self.b, self.b2 roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi # sproot accepts a BSpline obj w/ 1-D coef array assert_allclose(sproot(b), roots, atol=1e-7, rtol=1e-7) assert_allclose(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7) # ... and deals with trailing dimensions if coef array is N-D with suppress_warnings() as sup: sup.filter(DeprecationWarning, "Calling sproot.. with BSpline objects with c.ndim > 1 is not recommended.") r = sproot(b2, mest=50) r = np.asarray(r) assert_equal(r.shape, (3, 2, 4)) assert_allclose(r - roots, 0, atol=1e-12) # and legacy behavior is preserved for a tck tuple w/ N-D coef c2r = b2.c.transpose(1, 2, 0) rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50)) assert_equal(rr.shape, (3, 2, 4)) assert_allclose(rr - roots, 0, atol=1e-12)
def Poincare(self): plt.close('all') yspline = interpolate.splrep(self.qp[:, 4], self.qpR[:, 1], s=0) roots = interpolate.sproot(yspline) if len(roots) == 0: return xspline = interpolate.splrep(self.qp[:, 4], self.qpR[:, 0], s=0) vxspline = interpolate.splrep(self.qp[:, 4], self.qpR[:, 2], s=0) x = interpolate.splev(roots, xspline) vx = interpolate.splev(roots, vxspline) plt.scatter(x, vx) plt.show() return
def fwhm(x, y, k=10): class MultiplePeaks(Exception): pass class NoPeaksFound(Exception): pass half_max = amax(y)/2.0 s = splrep(x, y - half_max) roots = sproot(s) if len(roots) < 2: raise NoPeaksFound("No clear peaks were found in the image") else: return abs(roots[1] - roots[0]), roots[1], roots[0]
def roots(self): """ Return the zeros of the spline. Note: Only cubic splines are supported. """ if self.degree != 3: raise RuntimeError( 'finding roots unsupported for non-cubic splines') z, m, ier = sproot(*self.tck(), mest=10) if not ier == 0: raise RuntimeError("Error code returned by spalde: %s" % ier) return z[:m]
def test_sproot(self): b, b2 = self.b, self.b2 roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi # sproot accepts a BSpline obj w/ 1D coef array assert_allclose(sproot(b), roots, atol=1e-7, rtol=1e-7) assert_allclose(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7) # ... and deals with trailing dimensions if coef array is n-D with suppress_warnings() as sup: sup.filter(DeprecationWarning, "Calling sproot.. with BSpline objects with c.ndim > 1 is not recommended.") r = sproot(b2, mest=50) r = np.asarray(r) assert_equal(r.shape, (3, 2, 4)) assert_allclose(r - roots, 0, atol=1e-12) # and legacy behavior is preserved for a tck tuple w/ n-D coef c2r = b2.c.transpose(1, 2, 0) rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50)) assert_equal(rr.shape, (3, 2, 4)) assert_allclose(rr - roots, 0, atol=1e-12)
def find_zeros_cubic(x, y, tck=None, s=0, rettck=False, mest=10): ''' Function to find the location of all zero crossings of a numerical function ''' if tck is None: tck = interp.splrep(x, y, s=s) roots = interp.sproot(tck, mest=mest) if rettck: return roots, tck else: return roots
def construct_maxwell(H,T,S,binstep,verbose): beta = np.divide(1,T) beta_range = np.arange(1/Tmax,1/Tmin, binstep) count, found = 0, 0 data={} while found == 0: count += 1 if count>100: sys.exit("Error: count too high") for t in range(len(beta_range)): dT = beta - beta_range[t] # Represent dT as a spline interpolation dTfit = interpolate.splrep(H,dT) # Find the roots of dT roots = interpolate.sproot(dTfit, mest=200) if len(roots)<3: sys.exit("Error: Not enough crossing in interpolation") area = [] # Calculate area of roots by integrating between them for r in range(len(roots)-1): area.append(interpolate.splint(roots[r],roots[r+1],dTfit)) area1 = 0 area2 = 0 # Sum areas for a in area: if a>0: area1 += a else: area2 += a area_sum = area1 + area2 # Check whether total area is zero if np.abs(area_sum)<tol: found = 1 Tm = 1/beta_range[t] print("Transition temperature is %10.5f K" % (Tm)) data=calc_gibbs_hull(roots,H,T,S,beta_range[t],verbose) data["Tm"] = Tm # If area is less than zero, already passed Tm # Reduce the window, and try again if area_sum<0: bmin = beta_range[t-1] bmax = beta_range[t+1] binstep /= 10 if binstep<1e-12: sys.exit("Error: bin too small") beta_range = np.arange(bmin,bmax,binstep) if len(beta_range) == 0: sys.exit("Error: ran out of temperatures") break return data
def fwhm(self,x, y, order=3): """ Determine full-with-half-maximum of a peaked set of points, x and y. """ y=gaussian_filter(y,5) # filtre for reducing noise half_max = np.amax(y)/2.0 s = splrep(x, y - half_max,k=order) # F roots = sproot(s) # Given the knots . if len(roots) > 2: pass elif len(roots) < 2: pass else: return np.around(abs(roots[1] - roots[0]),decimals=2)
def corr_spline_interpolation(y1,y2, window_size): y1 = np.array([y1]) y2 = np.array([y2]) corr, delay = corr_no_interpolation(y1,y2, window_size) if window_size%2!=0: window_interp = np.arange(delay-(window_size-1)/2,delay+(window_size-1)/2) else: window_interp = np.arange(delay-(window_size)/2,delay+(window_size)/2-1) tck = interpolate.splrep(window_interp, corr[window_interp], s=0, k=4) dspl = interpolate.splder(tck) delay_spl = interpolate.sproot(dspl, mest = 20) if len(delay_spl) > 1: delay = delay_spl[np.argmax(interpolate.splev(delay_spl, tck, der=0))] else: delay = delay_spl[0] return corr, delay-len(y1[0,:])+1
def _get_next_time(self, t_0, u_0): """ Get the next time when the trajectory parameter will be at position *u_0*. There can be multiple results but only the closest one is returned. """ if self.stationary: return np.inf * q.s t, c, k = self._time_tck c = c - (self.length.magnitude * u_0) shifted_tck = t, c, k roots = interp.sproot(shifted_tck, mest=100) if len(roots) == 0: return np.inf * q.s return smath.supremum(t_0.simplified.magnitude, roots)
def fwhm(x, y): """ Determine full-with-half-maximum of a peaked set of points, x and y. http://motherboard.vice.com/blog/solar-powered-trash-cans-saved-philadelphia-almost-a-million-bucks Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k. """ half_max = amax(y)/2.0 s = splrep(x, y - half_max) roots = sproot(s) if len(roots) > 2: raise MultiplePeaks("The dataset appears to have multiple peaks, and " "thus the FWHM can't be determined.") elif len(roots) < 2: raise NoPeaksFound("No proper peaks were found in the data set; likely " "the dataset is flat (e.g. all zeros).") else: return abs(roots[1] - roots[0])
def fit_lorentzian(x,y): index, ymax = max(enumerate(y), key=operator.itemgetter(1)) x0 = x[index] y0 = min(y) spline = splrep(x, y-(y0+ymax)/2) roots = sproot(spline) whm = roots[-1]-roots[0] # y0=-0.00072 #x0=7.68377*1e9 #whm=0.1*1e6 B = whm*whm/4.0 A = B*(ymax-y0) #print x0,y0,B,A #x0=7.68374*1e9;y0=0.0019;B=((100*1e3)**2)/4;A=B*(max(y)-min(y)) popt, pcov = curve_fit(lorentzian,x,y,(x0,y0,A,B)) #popt=[x0,y0,A,B] return popt
def fwhm(x, y, k=10, debug=False): from scipy.interpolate import splrep, sproot """ Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k. Taken from https://stackoverflow.com/questions/10582795/finding-the-full- width-half-maximum-of-a-peak, written by user: jdg """ class MultiplePeaks(Exception): pass class NoPeaksFound(Exception): pass half_max = np.max(y)/2.0 s = splrep(x, y - half_max) if debug: x2 = np.linspace(np.min(x), np.max(x), 200) from scipy.interpolation import splev y2 = splev(x2, s) import matplotlib.pyplot as plt plt.plot(x, y-half_max, 'o') plt.plot(x2, y2) plt.show() roots = sproot(s) if len(roots) > 2: raise MultiplePeaks("The dataset appears to have multiple peaks, and " "thus the FWHM can't be determined.") elif len(roots) < 2: raise NoPeaksFound("No proper peaks were found in the data set; likely " "the dataset is flat (e.g. all zeros).") else: return abs(roots[1] - roots[0])
def resonant_fit(self, frequency, z, shunt): #Fits a single calibrated S21 trace.""" # The following calculates the center of the resonance in the complex plane. # The basic idea is to find the mean of the max and the min of both the realz # and imagz. This would give the center of the circle if this were a true # circle. However, since the resonance is not a circle we find the center by # rotating the resonance by an angle, finding the mean of the max and the min # of both the realz and imagz of the rotated circle, then rotating this new # point back to the original orientation. Finally, the middle of the resonance # is given by finding the mean of all these rotated back ave max min values. # Note: we only need to rotate a quarter of a turn because anything over # that would be redundant. if shunt: zold = z z = zold -1 steps = 100 centerpoints = array(range(steps),dtype=complex) for ang in range(steps): rotation = exp((2j * pi * (ang+1) / steps) / 4) # the 4 here is for a quarter turn zrot = rotation*z re = (zrot.real.max() + zrot.real.min()) / 2. im = (zrot.imag.max() + zrot.imag.min()) / 2. centerpoints[ang] = complex(re,im) / rotation # here the new center point is rotated back center=centerpoints.mean(); # Finding an estimate for the diameter of a circle that would fit the # resonance data diameter = 2 * abs(z - center).mean() # Finding the stray coupling # First a rough estimate of the stray is found by averaging all the points, # utilizing the fact that most of the points are located near the origin. # Then, a unit vector A is created that points from the center to the stray # Finally, the stray is found by taking the point at the tip of a vector # from the center, the length of the diameter, in the direction of A. stray = z.mean() A = (stray - center) / abs(center - stray) stray = center + A * diameter / 2 # This finds an aproximation to the resonant frequncy located at an angle of zero # and the frequency of the 3dB points which are located at pi/2 and -pi/2. # We also calculate an aproximatin for Q from John's paper deltaOmega/Omega0 = 1/Q angles = numpy.angle((center - z) / A) # anglesmid = numpy.logical_and(angles>-pi/4,angles<pi/4) # fmid = numpy.median(frequency[anglesmid]) anglesrange = numpy.logical_and(angles>-2,angles<2) freqinterp = frequency[anglesrange] anginterp = angles[anglesrange] freqplus = numpy.median(interpolate.sproot(interpolate.splrep(freqinterp,anginterp-(pi/2)))) freqneg = numpy.median(interpolate.sproot(interpolate.splrep(freqinterp,anginterp-(-pi/2)))) f0 = numpy.median(interpolate.sproot(interpolate.splrep(freqinterp,anginterp))) Q = f0 / (freqneg - freqplus) # For the fitting function we will need some other quantaties, namely Qc and # Q0. From John's paper, 1/Q = R0(1/R + 1/Rc), Qc = Rc/R0, and d = 1/(1 + Rc/R). # Combining these gives the result Qc = Q/d. Qc = Q / diameter # To find Q0 we have the equation from John's paper 1/Qi = 1/Q - 1/Qc. Now # with the result we just found for Qc, we have: Qi = Q / (1 - diameter) # From the quantaties determined above, we can determine a guess function # for the parameters of a function to be fit, which we will construct shortly angleA = numpy.angle(A) guess = array([angleA,Qc,Qi,f0,stray.real,stray.imag]) # From John's paper s21 = -1/(1+Rc/R) * 1/(1+i*2*Q*(f-f0)/f0 ). However, this # is for the ideal case. In our case, we have stray coupling (origin shift) # and a rotation of the curve. Putting these factors in we obtain # s21 = -exp(i*theta)/(1+Rc/R) * 1/( 1+i2Q(f-f0)/f0 ) + stray. We note # that Rc/R = Qc/Qi and Q = (1/Qc + 1/Qi)^(-1) and we obtain the following # s21 = -exp(i*theta)/(1+Qc/Qi) * 1/( 1+i*2*(1/Qc + 1/Qi)^(-1)*(f-f0)/f0 ) + stray # Now, to form a minizable quantity we take minimize the sum of the squares # of the quantity (s21 measured - s21 as defined above) # For the least squares function we will use to find a fit, we will need to # create a vector of the parameters to be minimized. Thus, use for our # variables the following elements of a vector "parm" with the following # identification # parm[0] is theta # parm[1]is Qc # parm[2] is Qi # parm[3] is f0 # parm[4]+j*parm[5] is stray # Thus we need to minimize the following least = optimize.leastsq(self.thru_residues,guess,args=(z,frequency),full_output=True) lsparm = least[0] nparm = 6 rsd=(least[2]["fvec"]**2).sum()/(len(frequency)-nparm) covar = sqrt(rsd*numpy.diag(least[1])).real # # The variables are all reassigned to the fit values theta = lsparm[0] Qc = lsparm[1] Qi = lsparm[2] f0 = lsparm[3] strayRe = lsparm[4] strayIm = lsparm[5] Q = (1/Qc+1/Qi)**-1 fit = array([theta, Qc, Qi, Q, f0, strayRe, strayIm]) thetaerror = covar[0] Qcerror = covar[1] Qierror = covar[2] f0error = covar[3] strayerrorRe = covar[4] strayerrorIm = covar[5] Qerror = (1/(1/Qi+1/Qc)**2)*(Qcerror/Qc**2+Qierror/Qi**2) fiterror = array([thetaerror,Qcerror,Qierror,Qerror,f0error,strayerrorRe,strayerrorIm]) # # We now calculate the max power transmitted on resonance by sampling 500 # # point of the fitting function, converting the voltage to power, and # # finding the maximum of these points. nPoints = 500 f = numpy.linspace(frequency[0],frequency[-1],nPoints) if shunt: maxpower_c = (20 * numpy.log10(abs(1-exp(1j*theta)/(1+Qc/Qi) * 1./( 1 + 2j*(1/Qc + 1/Qi)**(-1) * (f - f0)/f0 )))).max() else: maxpower_c = (20 * numpy.log10(abs(-exp(1j*theta)/(1+Qc/Qi) * 1./( 1 + 2j*(1/Qc + 1/Qi)**(-1) * (f - f0)/f0 )))).max() fitreturn = (fit, fiterror, maxpower_c, guess) return fitreturn
def check_cuts(self): # determine at which points the wall crosses a cut, for instance # (55,107,231) would mean that we change charge 3 times # hence self.splittings would have length, 3 while # self.local_charge would have length 4. # local charges are determined one the branch-cut data is given, # perhaps computed by an external function. disc_locus_position = [bp.locus for bp in self.fibration.branch_points] # the x-coordinates of the discriminant loci disc_x = [z.real for z in disc_locus_position] # parametrizing the x-coordinate of the k-wall's coordinates # as a function of proper time traj_t = numpy.array(range(len(self.coordinates))) traj_x = numpy.array([z[0] for z in self.coordinates]) # traj_y = numpy.array([z[1] for z in self.coordinates]) # f = interp1d(traj_t, traj_x, kind = 'linear') # all_cuts_intersections = [] # Scan over branch cuts, see if path ever crosses one # based on x-coordinates only for b_pt_num, x_0 in list(enumerate(disc_x)): g = interpolate.splrep(traj_t, traj_x - x_0, s=0) # now produce a list of integers corresponding to points in the # k-wall's coordinate list that seem to cross branch-cuts # based on the x-coordinate. # Will get a list [i_0, i_1, ...] of intersections intersections = map(int, map(round, interpolate.sproot(g))) # removing duplicates intersections = list(set(intersections)) # enforcing y-coordinate intersection criterion: # branch cuts extend vertically y_0 = self.fibration.branch_points[b_pt_num].locus.imag intersections = [i for i in intersections if \ self.coordinates[i][1] > y_0 ] # adding the branch-point identifier to each intersection intersections = [[self.fibration.branch_points[b_pt_num], i] \ for i in intersections] # dropping intersections of a primary k-wall with the # branch cut emanating from its parent branch-point # if such intersections happens at t=0 intersections = [[br_pt, i] for br_pt, i in intersections if \ not (br_pt in self.parents and i == 0)] # add the direction to the intersection data: either 'cw' or 'ccw' intersections = [[br_pt, i, clock(left_right(self.coordinates,i))]\ for br_pt, i in intersections] self.cuts_intersections += intersections ### Might be worth implementing an algorithm for handling ### overlapping branch cuts: e.g. the one with a lower starting point ### will be taken to be on the left, or a similar criterion. ### Still, there will be other sorts of problems, it is necessary ### to just rotate the u-plane and avoid such situations. ### now sort intersections according to where they happen in proper ### time; recall that the elements of cuts_intersections are organized ### as [..., [branch_point, t, 'ccw'] ,...] ### where 't' is the integer of proper time at the intersection. self.cuts_intersections = sorted(self.cuts_intersections , \ cmp = lambda k1,k2: cmp(k1[1],k2[1])) logging.debug(\ '\nK-wall {}\nintersects the following cuts at the points\n{}\n'\ .format(self.identifier, intersections)) ### now define the lis of splitting points (for convenience) ad the ### list of local charges self.splittings = [t for br_pt, t, chi in self.cuts_intersections] self.local_charge = [self.initial_charge] self.local_flavor_charge = [self.initial_flavor_charge] for k in range(len(self.cuts_intersections)): branch_point = self.cuts_intersections[k][0] # branch-point # t = self.cuts_intersections[k][1] # proper time direction = self.cuts_intersections[k][2] # 'ccw' or 'cw' gauge_charge = self.local_charge[-1] flavor_charge = self.local_flavor_charge[-1] new_gauge_charge = charge_monodromy(gauge_charge, branch_point, direction) new_flavor_charge = flavor_charge_monodromy( gauge_charge, flavor_charge, branch_point, direction, self.fibration.dsz_matrix) self.local_charge.append(new_gauge_charge) self.local_flavor_charge.append(new_flavor_charge)
if not test_spectra: print '\n Generating spectra (this may take a while) ...' for temp in test_temperatures: test_spectrum = temperature.lines(istate, vi, fstate, vf, J[-1], temp) test_spectrum = test_spectrum.map(exp_spectrum.wavelengths) test_spectrum = test_spectrum.broaden(fwhm, linetype=1) test_spectra.append(test_spectrum.normalize()) errors = [] for test_spectrum in test_spectra: errors.append(pylab.sum(abs(exp_spectrum.intensities - test_spectrum.intensities))) tck1 = interpolate.splrep(test_temperatures, errors, s=0) der1 = interpolate.splev(test_temperatures, tck1, der=1) tck2 = interpolate.splrep(test_temperatures, der1, s=0) roots = interpolate.sproot(tck2) if len(roots) is not 1: print 'Temperature ambiguous, setting to zero...' ctemps.append(0) minerrs.append(0) else: matched = temperature.lines(istate, vi, fstate, vf, J[-1], roots[-1]) #matched.inair() matched = matched.map(exp_spectrum.wavelengths) matched = matched.broaden(fwhm, linetype=1) matched = matched.normalize() minerrs.append(sum((exp_spectrum.intensities - matched.intensities)**2)) ctemps.append(roots) print '%f K\n (surface error of %f)' % (ctemps[-1], minerrs[-1]) if debug:
for n in xrange(len(out)): out[n] = interpolate.splint(0, x[n], tck) out += constant return out # >>> yint = integ(xnew, tck) plt.figure() plt.plot(xnew, yint, xnew, -np.cos(xnew), '--') plt.legend(['Cubic Spline', 'True']) plt.axis([-0.05, 6.33, -1.05, 1.05]) plt.title('Integral estimation from spline') plt.show() # Roots of spline print(interpolate.sproot(tck)) # [ 0. 3.1416] # Parametric spline t = np.arange(0, 1.1, .1) x = np.sin(2*np.pi*t) y = np.cos(2*np.pi*t) tck,u = interpolate.splprep([x,y], s=0) unew = np.arange(0, 1.01, 0.01) out = interpolate.splev(unew, tck) plt.figure() plt.plot(x, y, 'x', out[0], out[1], np.sin(2*np.pi*unew), np.cos(2*np.pi*unew), x, y, 'b') plt.legend(['Linear', 'Cubic Spline', 'True']) plt.axis([-1.05, 1.05, -1.05, 1.05]) plt.title('Spline of parametrically-defined curve')
def likelihood(param_vector): for i in range(len(param_vector)): if i in kr_idx: #Sampled value is a KD value that is then used with the kf to choose a kr earm.parameters_rules()[name_dict[i]].value = 10**(param_vector[i]+param_vector[i-1]) # earm.parameters_rules()[name_dict[i]].value = 10**param_vector[i] #print 'KD value = ',10**param_vector[i] #print 'set parameter: ',earm.parameters_rules()[name_dict[i]].name,' to ',10**(param_vector[i]+param_vector[i-1]) else: earm.parameters_rules()[name_dict[i]].value = 10**param_vector[i] #print 'set parameter: ',earm.parameters_rules()[name_dict[i]].name,' to ',10**param_vector[i] #earm.parameters_rules()[name_dict[i]].value = 10**param_vector[i] #print 'subbed kf vals: ',10**param_vector[kf_idx] #print 'subbed kr vals: ',10**param_vector[kr_idx] #print 'subbed kc vals: ',10**param_vector[kc_idx] solver.run() e1 = {} sims = {} for obs_name, data_name, var_name, obs_total in \ zip(obs_names, data_names, var_names, obs_totals): # Get model observable trajectory (this is the slice expression # mentioned above in the comment for tspan) ysim = solver.yobs[obs_name][::tmul] # Normalize it to 0-1 ysim_norm = ysim / obs_total # Get experimental measurement and variance ydata = exp_data[data_name] yvar = exp_data[var_name] # Compute error between simulation and experiment (chi-squared) e1[obs_name] = np.sum((ydata - ysim_norm) ** 2 / (2 * yvar)) / len(ydata) sims[obs_name] = ysim_norm e1_mBid = e1['mBid'] e1_mBid = -np.log10(e1_mBid) if np.isnan(e1_mBid): e1_mBid = -np.inf e1_cPARP = e1['cPARP'] e1_cPARP = -np.log10(e1_cPARP) if np.isnan(e1_cPARP): e1_cPARP = -np.inf sim_mBid = sims['mBid'] if np.any(np.isnan(sim_mBid)): sim_mBid.fill(-np.inf) sim_cPARP = sims['cPARP'] if np.any(np.isnan(sim_cPARP)): sim_cPARP.fill(-np.inf) # Calculate Td, Ts, and final value for IMS-RP reporter # ===== # Normalize trajectory ysim_momp = solver.yobs[momp_obs] if np.nanmax(ysim_momp) == 0: ysim_momp_norm = ysim_momp t10 = 0 t90 = 0 else: ysim_momp_norm = ysim_momp / np.nanmax(ysim_momp) # Build a spline to interpolate it st, sc, sk = interpolate.splrep(solver.tspan, ysim_momp_norm) try: # Use root-finding to find the point where trajectory reaches 10% and 90% t10 = interpolate.sproot((st, sc-0.10, sk))[0] t90 = interpolate.sproot((st, sc-0.90, sk))[0] #If integration has failed and nans are present in trajectory, # interpolation will fail and an IndexError will occur except IndexError: t10 = 0 t90 = 0 # Calculate Td as the mean of these times td = (t10 + t90) / 2 # Calculate Ts as their difference ts = t90 - t10 # Get yfinal, the last element from the trajectory yfinal = ysim_momp[-1] # Build a vector of the 3 variables to fit momp_sim = np.array([td, ts, yfinal]) #to use gpu add type='float32' # Perform chi-squared calculation against mean and variance vectors e2 = np.sum((momp_data - momp_sim) ** 2 / (2 * momp_var)) / 3 e2 = -np.log10(e2) if np.isnan(e2): e2 = -np.inf momp_sim.fill(-np.inf) #error = e1_mBid + e1_cPARP + e2 #print 'subbed values: ',[np.log10(param.value) for param in earm.parameters_rules()] #print 'mBid error: ',e1_mBid #print 'e1_cPARP: ',e1_cPARP #print 'e2: ',e2 #print 'sim mBid shape: ',sim_mBid.shape #print 'sim cPARP shape: ',sim_cPARP.shape #print 'sim MOMP shape: ',momp_sim.shape logp = np.sum(norm.logpdf(sim_mBid, exp_data['norm_ICRP'], exp_data['nrm_var_ICRP'])) + np.sum(norm.logpdf(sim_cPARP, exp_data['norm_ECRP'], exp_data['nrm_var_ECRP'])) + np.sum(norm.logpdf(momp_sim, momp_data, momp_var)) return logp
def get_f0_reflection(f, a_out): phase = np.unwrap(np.angle(a_out)) phase_avg = (np.min(phase)+np.max(phase))/2 spline = splrep(f, phase-phase_avg) roots = sproot(spline) return roots[0]
def get_bisector(x, y, ylim = None, num = 50): """ Gets the bisector of the curve given by x and y. The required arguments are x : The x values. y : The y values corresponding to the x values. The optional arguments is ylim : Specifies an upper limit, above which the bisector is not calculated. If set to None, no such limit is used. Otherwise, ylim has to be a number or a function. If it is a function it will accept the y values and return a number, which will be the y limit. Default is None. num : Specifies how many points the bisector should be calculated in (at most). Note that if there are more or less then two x coordinates for a given y coordinate, it will be ignored. """ # Make sure x and y have the same length if len(x) != len(y): raise Exception("x and y must have equal length, but x had length " + str(len(x)) + " while y had length " + str(len(y)) + ".") # If x and y had 0 length, return empty arrays if len(x) == 0: return np.array([]), np.array([]) # Initialize the lists that stores the bisector points x_pts = [] y_pts = [] # Estimate the minimum xmin, ymin = _estimate_minimum(x, y) # If no y limit was given, set it to the maximum y value if ylim == None: ylim = max(y) elif hasattr(ylim, "__call__"): ylim = ylim(y) # Find the bisector points for curr_y in np.linspace(min(y), ylim, num = num): # Find the root at y = curr_y by using quadratic interpolation tck = si.splrep(x, y - curr_y) roots = np.sort(si.sproot(tck)) # If there are exactly 2 roots, there is a bisector point if len(roots) == 2: # Make sure both roots are on either side of the minimum if roots[0] < xmin and roots[1] > xmin: x_pts.append(np.mean(roots)) y_pts.append(curr_y) elif len(roots) > 2: print("Number of roots:", len(roots)) # Determine the x on either side of xmin by subtracting xmin and taking the x values directly on the left # and right side of the transition between negative and positive. x_left = None x_right = None for xval in (roots - xmin): if xval < 0: x_left = xval else: x_right = xval break # If either x_left or x_right is None, then all roots are on one side of xmin and nothing should be added # to the list of bisector x values if x_left != None and x_right != None: x_pts.append(np.mean([x_left + xmin, x_right + xmin])) y_pts.append(curr_y) # Return the bisector points as an array over the x values and an array over the y values return np.array(x_pts), np.array(y_pts)
# trying out the splines in scipy import numpy as np import matplotlib.pyplot as plt from scipy import interpolate # cubic spline y = np.array([1,0.5,2,0.75,3,0.3,4,-0.6]) x = np.array([0,1,2,3,4,5,6,6.5]) tck = interpolate.splrep(x,y,k=3,s=0) print tck xnew = np.arange(0,len(y),0.1) ynew = interpolate.splev(xnew,tck,der=0) dtck = interpolate.splrep(xnew,ynew,s=0) print interpolate.sproot(dtck) plt.figure() plt.plot(x,y,'x',xnew,ynew,'g-') plt.legend(['Linear','Cubic Spline']) #plt.axis([-0.05,6.33,-1.05,1.05]) plt.title('Cubic-spline interpolation') plt.show()
def p_width(self, peaks, bline, filtered, minWidth, maxWidth, cell_ind, data, show, deltax=25, normed=False): if len(peaks)>1: tmean_interpeak_dist, fmid = self.mean_int_peak(peaks=peaks, fps=36) #deltax = fmid/2.0 #half distance of peak frequency in num. of frames. def bline_fn(*args): if normed: return 1 return bline[args] for i in range(len(peaks)): num_frames = len(filtered) left_bound = (peaks[i]-deltax)//1 right_bound = (peaks[i]+deltax)//1 #Making sure we are in bounds of frames. if left_bound<0: left_bound=0 if right_bound>=num_frames: right_bound=num_frames-1 half_max = (filtered[peaks[i]]-bline_fn(peaks[i]))/2.0 x1 = np.arange(left_bound, right_bound+1) y1 = (np.ones(len(filtered))*(bline_fn(peaks[i])+half_max))[left_bound:right_bound+1] y2 = filtered[left_bound:right_bound+1] if show==True: plt.plot(x1, y1, '-', x1, y2, '--', x1, bline_fn(x1), '.', peaks[i], filtered[peaks[i]], 'r+', mew=2, ms=8) plt.show() s = splrep(x1, y2 - (bline_fn(peaks[i])+half_max)) roots = sproot(s) all_big_widths = [] cell_indeces = [] #find smallest interval in roots which... #contains the peak index. if len(roots)>1: #separate indeces left, right of peak. calc closest. more_than_peak=[x for x in it.ifilter(lambda x: x if x>peaks[i] else 0, roots)] less_than_peak=[x for x in it.ifilter(lambda x: x if x<peaks[i] else 0, roots)] if len(more_than_peak)>0 and len(less_than_peak)>0: big_width = min(more_than_peak)-max(less_than_peak) print('Width: '+str(big_width)) all_big_widths.append(big_width) else: print('No widths detected.') else: print('None or too few roots detected.') if all_big_widths!=[]: self.avg_peak_widths.append(np.mean(all_big_widths)) self.all_cell_indeces.append(cell_ind) self.timed_pulse_interval.append(tmean_interpeak_dist) print('Mean interpeak duration: '+str(tmean_interpeak_dist)+' seconds') #record the contours we use. self.blinky_contours.append(data)