def mass_bh(lum, fwhm, a=0.660, b=0.53): mbh = unumpy.uarray(np.zeros(len(lum)), np.zeros(len(lum))) successful = (unumpy.nominal_values(lum) > 0) & (unumpy.nominal_values(fwhm) > 0) try: mbh[successful] = 10**(a + b * unumpy.log10(lum[successful] / 1e44) + 2 * unumpy.log10(fwhm[successful])) except: print('Runtime Error in the FWHM, no number printed') return mbh
def phot_error(cat_name, phot_gc_dens, ch): phot_err = np.loadtxt(cat_name, usecols=(2, )) dens_err = unp.uarray(phot_gc_dens, phot_err) if ch == 'l': denslog_err = unp.log10(dens_err) else: denslog_err = -2.5 * unp.log10(dens_err) error = unp.std_devs(denslog_err) return error
def compute_distance_modulus(par_mas): if par_mas > 0: dist_pc = 1. / (par_mas * 1e-3) mu = 5. * unp.log10(dist_pc) - 5 return dist_pc, mu else: return unp.uarray(np.nan, np.nan), unp.uarray(np.nan, np.nan)
def get_oddsratio_file(datanum, iteration): lls, ells = scale_ll(datanum, iteration) lls = unp.uarray(lls, ells) # compute odd ratios numerator, denominator = np.zeros(3), np.zeros(3) median_ratio, sigma_ratio = np.zeros(3), np.zeros(3) for i in range(3): numerator[i], denominator[i] = i + 1, i try: log10_oddsratio = unp.log10(unp.exp(lls[i + 1] - lls[i])) except ValueError: log10_oddsratio = unp.uarray(-np.inf, np.nan) median_ratio[i], sigma_ratio[i] = unp.nominal_values(log10_oddsratio), \ unp.std_devs(log10_oddsratio) # create odds ratio files f = open( 'Cloutier/TimeSeriesCV/oddsratio_%.4d%s.txt' % (datanum, iteration), 'w') g = '# Number of lnL evaluations, planet model denominator, planet model numerator, mode log10(odds ratio), median log10(odds ratio), minus 2 sigma (not used), minus 1 sigma, plus 1 sigma, plus 2 sigma (not used)' for i in range(3): g += '\n1.6E+07,%i,%i,%.6f,%.6f,NaN,%.6f,%.6f,NaN' % ( denominator[i], numerator[i], median_ratio[i], median_ratio[i], sigma_ratio[i], sigma_ratio[i]) g = g.replace('nan', 'NaN') f.write(g) f.close()
def other(g=True): freq = unumpy.uarray([100, 500, 1000, 5000, 10000, 50000], np.array([100, 500, 1000, 5000, 10000, 50000]) * 0.01) vin = ufloat(1.01, 0.01) vout = unumpy.uarray([0.640, 3.02, 5.27, 9.2, 9.6, 6.4], [0.01, 0.01, 0.01, 0.1, 0.1, 0.1]) fase = unumpy.uarray([92, 108, 123, 166, 178, -125], [1, 2, 1, 1, 1, 1]) Gs = vout / vin dB = 10 * unumpy.log10(Gs) if not g: return None f = plt.figure(figsize=(8, 8)) f.suptitle("Differenziatore", fontsize=15, y=0.98) ax = f.add_subplot(211) ax.errorbar(x=unumpy.nominal_values(freq), y=unumpy.nominal_values(Gs), c='black', fmt='o-') ax.set_xlabel('Frequenza', fontsize=14) ax.set_ylabel('Guadagno G', fontsize=14) ax.set_xscale('log') #ax.set_ylim((-13, 1)) #ax.set_yticklabels(('', 2, 4, 6, 8, 10, 12)) ax.set_xticklabels(('', '100 Hz', u"1 kHz", u"10 kHz", u"100 kHz", u"1 MHz")) ax.minorticks_on() ax.grid(b=True, which='major', color='0.7', linestyle='-', zorder=-5) ax.grid(b=True, which='minor', color='0.9', linestyle='-', zorder=-9) ax.set_axisbelow(True) ax2 = f.add_subplot(212) ax2.errorbar(x=unumpy.nominal_values(freq), y=unumpy.nominal_values(fase), c='black', fmt='o-') ax2.set_ylabel('Sfasamento [Gradi]', fontsize=14) ax2.set_xscale('log') #ax2.set_yticklabels(('', 25, 50, 75, 100)) ax2.set_xticklabels(('', '100 Hz', u"1 kHz", u"10 kHz", u"100 kHz")) ax2.minorticks_on() ax2.grid(b=True, which='major', color='0.7', linestyle='-', zorder=-5) ax2.grid(b=True, which='minor', color='0.9', linestyle='-', zorder=-9) ax2.set_axisbelow(True) ax3 = ax2.twiny() ax3.set_xticks((0, 0.333, 0.666, 1)) ax3.set_xticklabels(('', "1 kHz", u"10 kHz", u"100 kHz")) f.subplots_adjust(top=0.93, hspace=0.25, bottom=0.07, right=0.95) plt.savefig("../latex/diff.pdf") plt.show()
def pH_from_R(R, temp, sal): """ Calculate pH from Base/Acid absorption ratio, at known temperature and salinity. Equation 11 of Nand & Ellwood (2018, doi:10.1002/lom3.10253) Form: pH = pK + log10((R - e1) / (e2 - R * e3)) Parameters ---------- R : array_like Measured Base/Acid absorption ratio. temp : array_like Temperature of measurement (C) sal : array_like Salinity in PSU Returns ------- array_like : Solution pH (Total Scale) """ e1 = 5.3259624e-3 e2 = 2.2319033 e3 = 3.19e-2 pKa = calc_pKBPB(sal) R25 = calc_R25(R, temp) return pKa + unp.log10((R25 - e1) / (e2 - R25 * e3))
def DTM_oxy(axs, i): import Wiseman_data_OH Wiseman_OH = Wiseman_data_OH.OH_abund Wiseman_z = Wiseman_data_OH.z Wiseman_DTM = Wiseman_data_OH.DTM_all import De_Cia_data Cia_OH = De_Cia_data.OH_abund Cia_z = De_Cia_data.z Cia_DTM = De_Cia_data.DTM_all Cia_xuplims = De_Cia_data.xuplims Cia_yuplims = De_Cia_data.yuplims if(i == 0): x = RR_2015['Oxygen'] y = RR_2015['DTM_1B'] yerror = np.abs((0.75*RR_2015['DTM_1B'])) yall = unumpy.uarray(y, yerror) ynew = yall - unumpy.log10(1. + 10**yall) axs.errorbar(x, unumpy.nominal_values(ynew), yerr=unumpy.std_devs(ynew), color='g',label=r'$\mathrm{Remy-Ruyer}$ $\mathrm{2015}$',fmt='o') if(i == 2): ok = np.where(Wiseman_z == 2) x = Wiseman_OH[ok] y = Wiseman_DTM[ok] axs.errorbar(unumpy.nominal_values(x), unumpy.nominal_values(y), xerr = unumpy.std_devs(x), yerr = unumpy.std_devs(y), color='r',label=r'$\mathrm{Wiseman}$ $\mathrm{2017}$',fmt='o') ok = np.where(Cia_z == 2) x = Cia_OH[ok] y = Cia_DTM[ok] xuplims = Cia_xuplims[ok] yuplims = Cia_yuplims[ok] up = np.logical_and(xuplims == 0, yuplims == 0) axs.errorbar(unumpy.nominal_values(x[up]), unumpy.nominal_values(y[up]), xerr = unumpy.std_devs(x[up]), yerr = unumpy.std_devs(y[up]), color='b',label=r'$\mathrm{De}$ $\mathrm{Cia}$ $\mathrm{2016}$',fmt='o') axs.errorbar(unumpy.nominal_values(x[~up]), unumpy.nominal_values(y[~up]), xerr = unumpy.std_devs(x[~up]), yerr = unumpy.std_devs(y[~up]), xuplims = xuplims[~up], uplims = yuplims[~up], color='b', markerfacecolor='None', markeredgecolor = 'b', fmt='o', alpha = 0.8, elinewidth=0.5) if(i == 3): ok = np.where(Wiseman_z == 3) x = Wiseman_OH[ok] y = Wiseman_DTM[ok] axs.errorbar(unumpy.nominal_values(x), unumpy.nominal_values(y), xerr = unumpy.std_devs(x), yerr = unumpy.std_devs(y), label=r'$\mathrm{Wiseman}$ $\mathrm{2017}$', color='r',fmt='o') ok = np.where(Cia_z == 3) x = Cia_OH[ok] y = Cia_DTM[ok] xuplims = Cia_xuplims[ok] yuplims = Cia_yuplims[ok] up = np.logical_and(xuplims == 0, yuplims == 0) axs.errorbar(unumpy.nominal_values(x[up]), unumpy.nominal_values(y[up]), xerr = unumpy.std_devs(x[up]), yerr = unumpy.std_devs(y[up]), color='b',label=r'$\mathrm{De}$ $\mathrm{Cia}$ $\mathrm{2016}$',fmt='o') axs.errorbar(unumpy.nominal_values(x[~up]), unumpy.nominal_values(y[~up]), xerr = unumpy.std_devs(x[~up]), yerr = unumpy.std_devs(y[~up]), xuplims = xuplims[~up], uplims = yuplims[~up], color='b', markerfacecolor='None', markeredgecolor = 'b', fmt='o', alpha = 0.8, elinewidth=0.5) if(i == 4): ok = np.where(Wiseman_z == 4) x = Wiseman_OH[ok] y = Wiseman_DTM[ok] axs.errorbar(unumpy.nominal_values(x), unumpy.nominal_values(y), xerr = unumpy.std_devs(x), yerr = unumpy.std_devs(y), label=r'$\mathrm{Wiseman}$ $\mathrm{2017}$', color='r',fmt='o') if(i == 5): ok = np.where(Wiseman_z == 5) x = Wiseman_OH[ok] y = Wiseman_DTM[ok] axs.errorbar(unumpy.nominal_values(x), unumpy.nominal_values(y), xerr = unumpy.std_devs(x), yerr = unumpy.std_devs(y), label=r'$\mathrm{Wiseman}$ $\mathrm{2017}$', color='r',fmt='o')
def O3N2(OIII5007, NII6583, Halpha, Hbeta): ''' Calculate O3N3 from Yin et al. 2007: O3N2 = log[([O iii]λ5007/Hβ)/([N ii] λ6583/Hα)] ''' O3N2 = unp.log10((OIII5007 / Hbeta) / (NII6583 / Halpha)) return O3N2
def calcSFR(DMpc, logFHa, logFHa_err): Dpc = DMpc*(1E6) logFHa_arr = unumpy.uarray(logFHa,logFHa_err) F_Ha = 10**(logFHa_arr) L_Ha = F_Ha*(4*np.pi*((Dpc*(3.086E18))**2.)) logsfr = unumpy.log10(L_Ha) - 41.27 sfr = 10**(logsfr) return sfr
def DTM_stell(axs, i): if(i == 0): x = RR_2015['SM'] y = RR_2015['DTM_1B'] yerror = np.abs((0.75*RR_2015['DTM_1B'])) yall = unumpy.uarray(y, yerror) ynew = yall - unumpy.log10(1. + 10**yall) axs.errorbar(x, unumpy.nominal_values(ynew), yerr=unumpy.std_devs(ynew), color='g',label=r'$\mathrm{Remy-Ruyer}$ $\mathrm{2015}$',fmt='o')
def getLumin(self): ''' Set the sample log luminosities (and error if flux errors available) based on given flux values and luminosity distance values ''' if self.flux_e is not None: ulum = unumpy.log10(4.0*np.pi*(self.DL*3.086e24)**2 * unumpy.uarray(self.flux,self.flux_e)) self.lum, self.lum_e = unumpy.nominal_values(ulum), unumpy.std_devs(ulum) else: self.lum = np.log10(4.0*np.pi*(self.DL*3.086e24)**2 * self.flux) self.lum_e = None
def EBV_calzetti(HaHb): ''' Computes E(B-V) based on the method of Domínguez et al. 2012, ArXiv 1206.1867, assuming a reddening curve from Calzetti(2000). (NB! Explanation in Atek 2012 is good!) With Calzetti 2000 values of k(alpha) and k(beta), we get: E(B-V) = 1.97 log10((Ha/Hb) / 2.86) ''' EBV = 1.97* unp.log10(HaHb / 2.86) return EBV
def evaluate(energy, amplitude, reference, alpha, beta): """Evaluate the model (static function).""" try: xx = energy / reference exponent = -alpha - beta * np.log10(xx) except AttributeError: from uncertainties.unumpy import log10 xx = energy / reference exponent = -alpha - beta * log10(xx) return amplitude * np.power(xx, exponent)
def config_logplots(dens, err, r): denslog10 = unp.uarray(dens, err) denslog10 = unp.log10(denslog10) errlog = unp.std_devs(denslog10) #rmin = r/60 rlog = r #TO DO: add binsizes return dens, errlog, rlog
def OH_from_TeO3(fluxes, Te=None): ''' Again, translated from Miguel's code. ''' if Te is None: Te = Te_O3(fluxes['OIII4363'], fluxes['OIII4959'], fluxes['OIII5007'], fluxes['Hbeta']) if not 'Te4' in Te.columns: Te['Te4'] = Te['Te'] * 1.e4 Oplus = 7.34e-7 * (fluxes['OII3726'] + fluxes['OII3729'])/fluxes['Hbeta']\ * unp.exp(3.9/Te['Te4']) O2plus = (1.3e-6 / Te['Te4']**0.38) * unp.exp(2.9/Te['Te4'])\ * 4.2 * fluxes['OIII4959']/fluxes['Hbeta'] return 12. + unp.log10(Oplus + O2plus)
def evaluate(energy, amplitude, reference, alpha, beta, z): """Evaluate the model (static function).""" scale_factor = 1 / (1 + z) scaled_energy = energy * scale_factor try: xx = (scaled_energy / reference).to("") exponent = -alpha - beta * np.log10(xx) except AttributeError: from uncertainties.unumpy import log10 xx = scaled_energy / reference exponent = -alpha - beta * log10(xx) return amplitude * np.power(xx, exponent) * scale_factor
def hi_scalelength(self,m=0.86,m_error=0.04,c=0.79,c_error=0.02, k=0.19,k_error=0.03): # Wang+14, Lelli+16 exists = 'R_hi' in self.__dict__ if exists is False: m_param = uf(m,m_error) c_param = uf(c,c_error) k_param = uf(k,k_error) r_d = self.R_disc log_r_d = unp.log10(r_d) logr_hi = m_param * log_r_d + c_param r_hi = 10**logr_hi self.R_hi = k_param * r_hi return self.R_hi
def density(nbin, r, rgal, ): import numpy as np import uncertainties.unumpy as unp n = len(r) NGC = np.zeros(nbin) #number of GC in each bin rmed = [[] for i in range(0,nbin)] for h in range(0, nbin): for i in range(0, n): if (rgal[h+1] >= r[i] and r[i] > rgal[h]): NGC[h] = NGC[h] + 1 rmed[h].append(r[i]) #median value of the bins radius = [[] for i in range(0,nbin)] for i in range(0,nbin): radius[i] = np.linspace(rgal[i], rgal[i+1], 1000) median = np.linspace(0,0,nbin) medianGC = np.linspace(0,0,nbin) for i in range(0,nbin): median[i] = np.median(radius[i]) medianGC[i] = np.median(rmed[i]) area = [] for h in range(0, nbin): area.append((np.pi*rgal[h+1]**2)-(np.pi*rgal[h]**2)) #area per bin binsize = np.linspace(0,0,nbin) for h in range(0,nbin): binsize[h] = rgal[h+1]-rgal[h] binsize = binsize/2 dens2 = np.linspace(0,0,nbin) for h in range(0, nbin): dens2[h] = NGC[h]/area[h] #error in density poi_err = (np.sqrt(NGC)/area) dens2err = unp.uarray(dens2, poi_err) denslog2 = -2.5*np.log10(dens2) denslog2err = -2.5*unp.log10(dens2err) poi_err2 = unp.std_devs(denslog2err) return denslog2, poi_err2, area, NGC, median, rgal, binsize
def ZOH_M13(fluxtab, ext='', method='o3n2', name='ZOH', err=False): N2F = fluxtab['flux_[NII]6583'+ext] O3F = fluxtab['flux_[OIII]5007'+ext] HaF = fluxtab['flux_Halpha'+ext] HbF = fluxtab['flux_Hbeta'+ext] if method == 'o3n2': good = (N2F>0) & (O3F>0) & (HaF>0) & (HbF>0) elif method == 'n2': good = (N2F>0) & (HaF>0) else: raise Exception('Method {} is not recognized'.format(method)) nelt = len(N2F) BPT = bpt_type(fluxtab, ext=ext) if err == False: O3N2 = np.full(nelt, np.nan) O3N2[good] = (np.log10(O3F[good]) - np.log10(HbF[good]) - (np.log10(N2F[good]) - np.log10(HaF[good]))) N2 = np.full(nelt, np.nan) N2[good] = np.log10(N2F[good]) - np.log10(HaF[good]) else: try: from uncertainties import ufloat import uncertainties.unumpy as unp except: print('uncertainties package required for err=True') uN2F = unp.uarray(N2F, fluxtab['e_flux_[NII]6583'+ext]) uO3F = unp.uarray(O3F, fluxtab['e_flux_[OIII]5007'+ext]) uHaF = unp.uarray(HaF, fluxtab['e_flux_Halpha'+ext]) uHbF = unp.uarray(HbF, fluxtab['e_flux_Hbeta'+ext]) O3N2 = unp.uarray(np.full(nelt, np.nan),np.full(nelt, np.nan)) O3N2[good] = (unp.log10(uO3F[good]) - unp.log10(uHbF[good]) - (unp.log10(uN2F[good]) - unp.log10(uHaF[good]))) N2 = unp.uarray(np.full(nelt, np.nan),np.full(nelt, np.nan)) N2[good] = unp.log10(uN2F[good]) - unp.log10(uHaF[good]) if method == 'o3n2': ZOH_M13 = 8.533 - 0.214 * O3N2 # Eq(2) from Marino+2013 else: ZOH_M13 = 8.743 + 0.462 * N2 # Eq(4) from Marino+2013 desc = '12+log(O/H) using {} method in Marino+13'.format(method) if err == False: ZOH_M13[BPT != -1] = np.nan return Column(ZOH_M13, name=name, unit='dex', dtype='f4', description=desc) else: ZOH_M13[BPT != -1] = ufloat(np.nan, np.nan) return (Column(unp.nominal_values(ZOH_M13), name=name, dtype='f4', unit='dex', description=desc), Column(unp.std_devs(ZOH_M13), name='e_'+name, dtype='f4', unit='dex', description='error in '+desc))
def R_halo(self): exists = 'R200' in self.__dict__ exists = False # unit converter cf = (1 * u.Msun)**(1 / 3) * (1 * u.kg)**(-1 / 3) * (1 * u.m) cf = cf.to(u.kpc).value if exists is False: h = 0.7 K = 3 / (4 * np.pi * 200 * self.rho_crit.value) M200 = self.M_halo() logc200 = (0.905 - 0.101 * unp.log10(M200 / (10**12 * h**(-1)))) c200 = 10**logc200 self.R200 = (K * (M200))**(1 / 3) * cf self.a_h = self.R200 / c200 return self.a_h, self.R200
def doPlotWithUnc(self): #plot absolute and phase along with uncertainties f=1 uabs=unumpy.uarray(self.getFAbs(),self.getFAbsUnc()) #scale the uncertainty for the 20*log10 plot uabs=20*unumpy.log10(uabs) u_a=unumpy.nominal_values(uabs) u_s=unumpy.std_devs(uabs) py.figure('FD-ABS-UNC-Plot') py.plot(self.getfreqsGHz(),u_a) py.plot(self.getfreqsGHz(),u_a+u_s,'--',self.getfreqsGHz(),u_a-u_s,'--') py.figure('FD-PH-UNC-Plot') py.plot(self.getfreqsGHz(),self.getFPh()) py.plot(self.getfreqsGHz(),self.getFPh()+f*self.getFPhUnc(),'--',self.getfreqsGHz(),self.getFPh()-self.getFPhUnc(),'--')
def mag(lc: LightCurve) -> LightCurve: """ Converts and normalizes a LighCurve object to magnitudes. :param lc: lightcurve object :return: reduced light curve object """ lc = lc.remove_nans() flux = lc.flux + (np.abs(2 * np.amin(lc.flux)) if np.amin(lc.flux) < 0 else 100) flux = unp.uarray(flux, lc.flux_err) flux = -2.5 * unp.log10(flux) flux = flux[~unp.isnan(flux)] flux -= np.median(flux) lc.flux = unp.nominal_values(flux) * u.mag lc.flux_err = unp.std_devs(flux) * u.mag return lc
def config_pne(N, area, r): area = area / 3600 denslog = N / area #denslog = np.log10(density) errlog = np.sqrt(N) / area #errlog = err/(2.3*(density)) #errlog = np.log10(err) denslog10 = unp.uarray(denslog, errlog) denslog10 = unp.log10(denslog10) errlog = unp.std_devs(denslog10) rmin = r / 60 rlog = rmin #TO DO: add binsizes return denslog, errlog, rlog
def mjy(lognu, ll, dist, llerr=None): """ Converts log(nu/Hz), log(nu Lnu [erg/s]), error in log(nuLnu) to log(lambda/micron), log(Fnu/mJy), error in log(Fnu). The input units are CGS. Usage: If you have errors in the flux: >>> lamb,fnu,ferr=mjy(xdata,ydata,dist,yerr) If you do not have errors in the flux: >>> lamb,fnu=mjy(xdata,ydata,dist) :param dist: distance in Mpc """ import uncertainties.unumpy as unumpy c = 29979245800. # speed of light in CGS dist = dist * 3.085677581e24 # Mpc -> cm nu = 10**lognu lamb = c / nu * 1e4 # cm -> micron if llerr != None: lllerr = unumpy.uarray(ll, llerr) else: lllerr = ll lnuerr = 10**lllerr / nu fluxerr = lnuerr / (1e-26 * 4. * numpy.pi * dist**2 ) # Lnu (erg/s/Hz) -> Fnu (mJy) if llerr != None: fluxerr = unumpy.log10(fluxerr) return numpy.log10(lamb), unumpy.nominal_values( fluxerr), unumpy.std_devs(fluxerr) else: return numpy.log10(lamb), numpy.log10(fluxerr)
from math import * import matplotlib.pyplot as plt import numpy as np from uncertainties import ufloat, unumpy # 20 dB data20 = np.genfromtxt(open("../dati/banda_20.csv"), delimiter=",", skip_header=1) freq20 = data20[:,0] vout20 = unumpy.uarray(data20[:,1] / 2.0, 10*np.ones(len(freq20))) phase20 = data20[:,2] dphase20 = data20[:,3] vin20 = ufloat(50, 0.5) db20 = 20.0 * unumpy.log10(vout20/vin20) m3db = db20[0].nominal_value - 3.0 p3db = None for f1, db1, f2, db2 in zip(freq20[:-1], db20[:-1], freq20[1:], db20[1:]): if db1 > m3db and db2 < m3db: p3db = f1 + (f2 - f1) * (m3db - db1) / (db2 - db1) print(p3db) # 40 dB data40 = np.genfromtxt(open("../dati/banda_40.csv"), delimiter=",", skip_header=1) freq40 = data40[:,0] vout40 = unumpy.uarray(data40[:,1] / 2.0, data40[:,3]) * 1000 phase40 = data40[:,2]
pylab.savefig("bode.png", dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None) print(covm) logF = unumpy.log10(F) logf = unumpy.nominal_values(logF) dlogf = unumpy.std_devs(logF) pylab.figure(num=None, figsize=(12, 6), dpi=80, facecolor='w', edgecolor='k') pylab.errorbar(logf, phi, dphi, dlogf, linestyle='', marker='') #pylab.xscale("log") #pylab.xlim(400, 3200) pylab.legend(numpoints=1, loc='upper right') pylab.xlabel('log(f/1kHz)', size="16") pylab.ylabel(' $\phi$ [$\pi$ rad]', size="16") #pylab.xlim(0,2000) pylab.title('Sfasamento', fontsize="18") pylab.grid() #Fare attenzione che gli errori devono essere sempre sommati con le stesse unita di misura,
retaMax = [InterceptMax, InterceptMax + (Txmax * Esp)] retaMin = [InterceptMin, InterceptMin + (Txmin * Esp)] #retaMax=[IdadeB,IdadeB+(Txmax*IdadeA)] #retaMin=[IdadeB,IdadeB+(Txmin*IdadeA)] plt.figure('taxa Sed') plt.plot([0, Esp], [IdadeB, IdadeA], 'ro') plt.errorbar([0, Esp], [IdadeB, IdadeA], yerr=[ErroB, ErroA], zorder=10) plt.errorbar([0, Esp], [IdadeB, IdadeA], zorder=11) plt.plot([0, Esp], retaMax, 'w--') plt.plot([0, Esp], retaMin, 'w--') plt.fill_between([0, Esp], retaMax, retaMin, color='tomato', alpha=0.2, label='erro taxa') plt.title(f'Simulação taxa sedimentação\ntaxa={TaxaSed} m/mil anos') plt.xlabel('distância estratigráfica (m)') plt.ylabel('idade (mil anos)') plt.legend(loc='upper left') plt.savefig('Erro_taxa.png') Zeta = (UArr[0]**UArr[1]) / (unumpy.log10(UArr[2] - unumpy.log10(UArr[3]))) print(Zeta) #plt.show()
def pH_from_F(F, K): return -log10(K / F)
def _trapz_loglog(self, y, x, axis=-1, intervals=False): """ Integrate along the given axis using the composite trapezoidal rule in loglog space. Integrate y(x) along given axis in loglog space. This follows the script in the Naima package. Parameters ---------- - y (array_like): Input array to integrate. - x (array_like): optional. Independent variable to integrate over. - axis (int): Specify the axis. - intervals (bool): Return array of shape x not the total integral, default: False Returns ------- trapz (float): Definite integral as approximated by trapezoidal rule in loglog space. """ log10 = np.log10 #----- Check for units try: y_unit = y.unit y = y.value except AttributeError: y_unit = 1.0 try: x_unit = x.unit x = x.value except AttributeError: x_unit = 1.0 y = np.asanyarray(y) x = np.asanyarray(x) #----- Define the slices slice1 = [slice(None)] * y.ndim slice2 = [slice(None)] * y.ndim slice1[axis] = slice(None, -1) slice2[axis] = slice(1, None) slice1, slice2 = tuple(slice1), tuple(slice2) #----- arrays with uncertainties contain objects, remove tiny elements if y.dtype == "O": from uncertainties.unumpy import log10 # uncertainties.unumpy.log10 can't deal with tiny values see # https://github.com/gammapy/gammapy/issues/687, so we filter out the values # here. As the values are so small it doesn't affect the final result. # the sqrt is taken to create a margin, because of the later division # y[slice2] / y[slice1] valid = y > np.sqrt(np.finfo(float).tiny) x, y = x[valid], y[valid] #----- reshaping x if x.ndim == 1: shape = [1] * y.ndim shape[axis] = x.shape[0] x = x.reshape(shape) #----- with np.errstate(invalid="ignore", divide="ignore"): # Compute the power law indices in each integration bin b = log10(y[slice2] / y[slice1]) / log10(x[slice2] / x[slice1]) # if local powerlaw index is -1, use \int 1/x = log(x); otherwise use normal # powerlaw integration trapzs = np.where( np.abs(b + 1.0) > 1e-10, (y[slice1] * (x[slice2] * (x[slice2] / x[slice1])**b - x[slice1])) / (b + 1), x[slice1] * y[slice1] * np.log(x[slice2] / x[slice1])) tozero = (y[slice1] == 0.0) + (y[slice2] == 0.0) + (x[slice1] == x[slice2]) trapzs[tozero] = 0.0 if intervals: return trapzs * x_unit * y_unit ret = np.add.reduce(trapzs, axis) * x_unit * y_unit return ret
T_OIII = 0.8254 - 0.0002415*ROIII + (47.77/ROIII) RSII = SII_6716_Flux / SII_6730_Flux a_0 = 2.21 - 1.3/T_OIII - 1.25*T_OIII + 0.23*T_OIII**2 a_1 = -3.35 + 1.94/T_OIII + 1.93*T_OIII - 0.36*T_OIII**2 b_0 = -4.33 + 2.33/T_OIII + 2.72*T_OIII - 0.57*T_OIII**2 b_1 = 1.84 - 1.0/T_OIII - 1.14*T_OIII + 0.24*T_OIII**2 n_SII = (10.0**3)*(RSII*a_0 + a_1)/(RSII*b_0 + b_1) if n_SII > 0.0: T_OII = (1.2 + 0.002*n_SII + 4.2/n_SII)/(1/T_OIII + 0.08 + 0.003*n_SII + 2.5/n_SII) logOII_logHII = -12 + unumpy.log10(OII_7319_Flux/HBeta_Flux) + 6.895 + 2.44/T_OII -0.58*unumpy.log10(T_OII) - unumpy.log10(1.0 + 0.0047*n_SII) logOIII_logHII = -12 + unumpy.log10((OIII_4959_Flux+OIII_5007_Flux)/HBeta_Flux) + 6.144 + 1.251/T_OIII - 0.55*unumpy.log10(T_OII) OII_HII = 10**(logOII_logHII) OIII_HII = 10**(logOIII_logHII) OI_HI = OII_HII + OIII_HII O_Abundances.append(OI_HI) else: if (n_SII < None): Error_Message = "Aritmetic error: n_SII < 0" Comments.append(Error_Message)
INPUT = "/home/federico/Laboratorio3/relazione4/datiBode.txt" OUTPUT = "/home/federico/Laboratorio3/relazione4/datiBode.txt" Vout, dVout, f, df = pylab.loadtxt(INPUT, unpack=True) #Nelle visualizzazioni devo introdurre gli errori F = unumpy.uarray(f, df) VOUT = unumpy.uarray(Vout, dVout) VOUT3 = unumpy.uarray(Vout, (dVout**2 + (0.03*Vout)**2)) VIN = ufloat(1.00, 0.01) VIN3 = ufloat(1.00, ((0.01)**2+(0.03*1.00)**2)**0.5) #Per la visualizzazione inserisco il 3% A = VOUT3/VIN3 dB = 20*unumpy.log10(A) logF = unumpy.log10(F) pylab.title('A vs logf') pylab.xlim(-6, 1) pylab.ylim(-5, 25) pylab.xlabel('log(f/1MHz)') pylab.ylabel('A (dB)') pylab.grid(color = "gray") pylab.errorbar(unumpy.nominal_values(logF), unumpy.nominal_values(dB), unumpy.std_devs(dB), unumpy.std_devs(logF), "o", color="black") pylab.show()
mT = unumpy.matrix(XHB) filename = "resXHB.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') concH = (0.0000169) * (1 + XB) / (XHB) mT = unumpy.matrix(concH) filename = "resconcH.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') FI = 0.5 * (XB * 4 * 0.0000169 + XHB * 0.0000169 + 2 * conc) mT = unumpy.matrix(FI) filename = "resFI.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') pkc = -(unumpy.log10(0.0000169 * XB * (1 + XB) / (1 - XB))) mT = unumpy.matrix(pkc) filename = "respkc.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') sqI = unumpy.sqrt(FI) fi = (sqI) / (1 + 2.3 * sqI) mT = unumpy.matrix(fi) filename = "resfi.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') #http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
import uncertainties from uncertainties import ufloat import math import numpy import numpy import pylab from scipy.optimize import curve_fit import math import scipy.stats import uncertainties from uncertainties import unumpy V_IN = ufloat(0.340, 0.002) V_OUT = ufloat(13.00, 0.2) A = 20.0 * unumpy.log10(V_OUT / V_IN) Amis = A - 3.0 V_OUT_mis = V_IN * 10**(Amis / 20) print(V_OUT_mis)
freq_low = data_low[:,0] va_low = unumpy.uarray(data_low[:,1] / 2.0, data_low[:,3]) vout_low = unumpy.uarray(data_low[:,2] / 2.0, data_low[:,4]) G_low = 1001 * vout_low / va_low data_high = np.genfromtxt(open("../dati/guadagno_alta_freq_sum.csv"), delimiter=",", skip_header=1) freq_high = data_high[:,0] * 1000 va_high = unumpy.uarray(data_high[:,1] / 2.0, data_high[:,3]) vout_high = unumpy.uarray(data_high[:,2] / 2.0, data_high[:,4]) G_high = vout_high / va_high print(G_low, G_high) print(20*unumpy.log10(G_low), 20*unumpy.log10(G_high)) f1 = plt.figure() ax1 = f1.add_subplot(111) ax1.set_xscale('log') ax1.set_yscale('log') p1 = ax1.errorbar(x=freq_low, y=unumpy.nominal_values(G_low), yerr=unumpy.std_devs(G_low), fmt="o", c="black") p2 = ax1.errorbar(x=freq_high, y=unumpy.nominal_values(G_high), yerr=unumpy.std_devs(G_high), fmt="o", c="gray") ax1.set_title("Guadagno di un opamp in funzione della frequenza") ax1.set_xlabel("Frequenza [Hz]") ax1.set_ylabel("Amplificazione") ax1.set_xlim((1, 3e6)) ax1.set_ylim((1e-1, 1e6)) ax1.grid(True)
Errors[n] = Valid_EmLines[n][5] np_HBeta[n] = HBeta_Flux np_HBeta_error[n] = HBeta_Error #Calculation gradient: x = np.zeros(NumberRecombinationRatios) y = np.zeros(NumberRecombinationRatios) FluxEL_and_error = unumpy.uarray([Flux_EL], [Errors]) HBeta_and_Error = unumpy.uarray([np_HBeta], [np_HBeta_error]) for o in range(NumberRecombinationRatios): x[o] = f_lambda[o] - f_Beta y[o] = math.log10(TheoRatio[o]/ObsRatio[o]) y_and_error = unumpy.log10(TheoRatio / (FluxEL_and_error/HBeta_and_Error)) y_err=unumpy.std_devs(y_and_error) y_err = y_err[0] #Old method A = np.vstack([x, np.ones(len(x))]).T cHBeta_Old, n_Old = np.linalg.lstsq(A, y)[0] TrendLine = Axis1.plot(x, cHBeta_Old*x+n_Old, color=Colors[2][1], label='Fitted line') #New method Regression_Fit, Uncertainty_Matrix, Red_Chi_Sq, Residuals = linfit(x, y, y_err, cov=True, relsigma=False, chisq=True, residuals=True) m_n_error = [np.sqrt(Uncertainty_Matrix[t,t]) for t in range(2)] R_Factor = Uncertainty_Matrix[0,1]/(m_n_error[0]*m_n_error[1]) cHbeta, cHbeta_error = Regression_Fit[0], m_n_error[0]
wfc_g102_file = input_path + 'sgas1723_1Dsum_'+item+'_G102_wcontMWdr_meth2.fitdf' wfc_g102_file = cr.deredden(wfc_g102_file, 0.3, 0.02, niter=int(1e5), constant=1e-17, dered=True, change_ID=True, change_errors=True, SNR_thresh=0.014, readcsv=True) # to deredden WFC3 spectra and re-write the file wfc_g141_file = input_path + 'sgas1723_1Dsum_'+item+'_G141_wcontMWdr_meth2.fitdf' wfc_g141_file = cr.deredden(wfc_g141_file, 0.3, 0.02, niter=int(1e5), constant=1e-17, dered=True, change_ID=True, change_errors=True, SNR_thresh=0.014, readcsv=True) # to deredden WFC3 spectra and re-write the file g102 = pd.read_table(wfc_g102_file, delim_whitespace=True, comment='#') g141 = pd.read_table(wfc_g141_file, delim_whitespace=True, comment='#') H_g102 = unp.uarray(cr.getf(g102, g102_hlist), cr.gete(g102, g102_hlist)) H_g141 = unp.uarray(cr.getf(g141, g141_hlist), cr.gete(g141, g141_hlist)) ratio_obs = [H_g141[0] / H_g141[1], H_g141[0] / H_g102[0], H_g102[0] / H_g102[1], H_g102[0] / H_g102[2]] # , H_g102[0]/H_g102[3], H_g102[0]/(H_esi[0]*esi_to_mmt_scale), H_esi[0]/H_esi[1]] Eb_v = (2.5 / delta_k) * unp.log10(ratio_obs / ratio_theoretical) print '\nMean E(B-V) =', np.mean(Eb_v) edf = pd.concat([edf, pd.DataFrame(np.transpose(np.vstack([ratio_labels, spec_labels, ['%.2F' % x.n for x in Eb_v], ['%.2F' % x.s for x in Eb_v], ['%.2F' % x.n for x in ratio_obs], ['%.2F' % x.s for x in ratio_obs]])), columns=['Line ratio', 'Grism(s)', 'E(B-V)', r'E(B-V)$_u$', 'Observed ratio', 'Observed ratio uncert'])]) # ------to plot the E(B-V) values for visual comparison----- col_ar = ['r', 'g', 'b', 'orange'] for ii in range(len(Eb_v)): ax.scatter(index + ii*0.1, Eb_v[ii].n, s=40, color=col_ar[ii], lw=0, label=ratio_labels[ii]+' '+spec_labels[ii] if not index else None) ax.errorbar(index + ii*0.1, Eb_v[ii].n, yerr=Eb_v[ii].s, color=col_ar[ii]) fs = 15 # plot label fontsize plt.legend(loc='lower left', fontsize=fs) ax.set_xticks(np.arange(len(filenames))) ax.set_xticklabels(filenames, rotation=50, fontsize=fs, ha='right', va='top') plt.ylim(-0.6,0.8) plt.ylabel('E(B-V)', fontsize=fs)
mT = unumpy.matrix(XHB) filename = "resXHB.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') concH = (0.0000169)*(1+ XB)/(XHB) mT = unumpy.matrix(concH) filename = "resconcH.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') FI = 0.5*(XB*4*0.0000169+XHB*0.0000169+2*conc) mT = unumpy.matrix(FI) filename = "resFI.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') pkc = -(unumpy.log10(0.0000169*XB*(1+XB)/(1-XB))) mT = unumpy.matrix(pkc) filename = "respkc.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') sqI = unumpy.sqrt(FI) fi = (sqI)/(1+2.3 * sqI) mT = unumpy.matrix(fi) filename = "resfi.csv" numpy.savetxt(filename, mT, fmt='%r', delimiter='\n') #http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
validity_entry = catalogue_df.loc[objName, element + '_valid'] element_abundance_key = '{}I_HI_emis2nd'.format(element) element_abundance_check = isnull(catalogue_df.loc[objName, element_abundance_key]) print objName, element, element_abundance_check if element_abundance_check is False: if (validity_entry not in ['ignored', 'NO_excess', 'Wide Component']): regressions_employed.append(element) else: print 'Fallo', objName, element name_superscript = r'\textsuperscript{{{regrens}}}'.format(regrens = ', '.join(regressions_employed)) entry_name = r'{text}{expo}'.format(text=catalogue_df.loc[objName].quick_index, expo=name_superscript) objData = catalogue_df.loc[objName] abundValues = objData[metals_list].values objData[metals_list] = 12.0 + unumpy.log10(abundValues) HeI_HI_entry = dz.format_for_table(catalogue_df.loc[objName, 'HeII_HII_from_O' + ext_data], rounddig=3, rounddig_er=2) Ymass_O_entry = dz.format_for_table(catalogue_df.loc[objName, 'Ymass_O' + ext_data], rounddig=3, rounddig_er=2) Ymass_S_entry = dz.format_for_table(catalogue_df.loc[objName, 'Ymass_S' + ext_data], rounddig=3, rounddig_er=2) print objName, objData[['OI_HI' + ext_data]].values, objData[['OI_HI' + ext_data]].isnull().values.any(), regressions_employed row = [entry_name] + [HeI_HI_entry, Ymass_O_entry, Ymass_S_entry] row += list(objData[['OI_HI' + ext_data, 'NI_HI' + ext_data, 'SI_HI' + ext_data]].values) dz.addTableRow(row, last_row = False if catalogue_df.index[-1] != objName else True, rounddig=3, rounddig_er=1) # dz.generate_pdf() dz.generate_pdf(output_address=pdf_address)
def X_H(F, M_H): #A = unumpy.uarray([-0.02], [0.1]) #B = unumpy.uarray([-0.15], [0.09]) A = unumpy.uarray([-0.145], [0.051]) B = unumpy.uarray([-0.225], [0.053]) return A + B * (F - 0.598) + M_H #return A + B*(F-0.598) data = np.genfromtxt('./Obs_data/Wiseman_data_2017.txt', delimiter=',') F, Ferr, M_H, M_Herror, z, DTM, DTMerr = data[:, 0], data[:, 1], data[:, 2], data[:, 3], data[:, 4], data[:, 5], data[:, 6] F_all = unumpy.uarray(F, Ferr) M_H_all = unumpy.uarray(M_H, M_Herror) DTM_all = unumpy.log10(unumpy.uarray(DTM, DTMerr) * 0.464) depl = X_H(F_all, M_H_all) OH_abund = depl + 8.69 z = np.round(z, 0)
def plot_lines_and_other_points_NII(): # PLOT LINES plt.figure('BPT_NII') # y1: log([OIII]5007/Hbeta) = 0.61 / (log([NII]6584/Halpha) - 0.05) + 1.3 (curve of Kauffmann+03 line) # y2: log([OIII]5007/Hbeta) = 0.61 / (log([NII]6584/Halpha) - 0.47) + 1.19 (curve of Kewley+01 line) x1 = np.arange(-2, 0.02, 0.01) y1 = 0.61 / (x1 - 0.05) + 1.3 x2 = np.arange(-2, 0.44, 0.01) y2 = 0.61 / (x2 - 0.47) + 1.19 plt.plot(x1, y1, 'k--') plt.plot(x2, y2, 'k--') # AREA LABELS plt.text(-1.25, -0.5, r'Photoionization', fontsize=12) plt.text(0.05, 0.55, r'Shocks', fontsize=12) # plt.text(-1, -0.8, r'Starburst', fontsize=12) # plt.text(-0.22, -0.75, r'Transition', fontsize=12) # plt.text(-0.18, -0.9, r'Objects', fontsize=12) # plt.text(0.16, -0.5, r'LINERs', fontsize=12) # plt.text(0.05, 0.55, r'Seyferts', fontsize=12) # plt.text(-1.46, 1.1, r'Extreme Starburst Line', fontsize=12) # OTHER POINTS FROM PAPER # Olave et al., 2015 (regions of NGC6845) hBetaAbs = [ 0.025, 0.033, 0.007, 0.084, 0.632, 0.075, 0.015, 0.082, 0.013, 0.038, 0.078, 0.055, 0.008, 0.021, 0.894, 0.408, 0.052, 0.009, 0.024, 0.007, 0.012 ] hBetaErr = [ 0.011, 0.027, 0.003, 0.019, 0.03, 0.022, 0.009, 0.017, 0.004, 0.017, 0.019, 0.016, 0.006, 0.013, 0.08, 0.026, 0.014, 0.004, 0.014, 0.003, 0.008 ] oIII5007Abs = [ 0.035, 0.092, 0.036, 0.473, 4.651, 0.134, 0.021, 0.183, 0.02, 0.068, 0.135, 0.082, 0.018, 0.014, 0.672, 0.503, 0.038, 0.008, 0.036, 0.013, 0.028 ] oIII5007Err = [ 0.012, 0.025, 0.029, 0.247, 0.698, 0.027, 0.013, 0.015, 0.007, 0.018, 0.023, 0.018, 0.007, 0.008, 0.072, 0.028, 0.006, 0.004, 0.014, 0.007, 0.016 ] hAlphaAbs = [ 0.069, 0.102, 0.032, 0.377, 3.011, 0.224, 0.05, 0.256, 0.046, 0.111, 0.246, 0.172, 0.027, 0.062, 3.3, 1.66, 0.161, 0.013, 0.062, 0.015, 0.035 ] hAlphaErr = [ 0.01, 0.025, 0.011, 0.029, 0.452, 0.032, 0.015, 0.034, 0.019, 0.024, 0.035, 0.027, 0.013, 0.019, 0.204, 0.14, 0.02, 0.01, 0.017, 0.008, 0.012 ] nII6584Abs = [ 0.011, 0.014, 0.007, 0.04, 0.227, 0.036, 0.009, 0.033, 0.01, 0.022, 0.041, 0.036, 0.006, 0.021, 1.064, 0.48, 0.056, 0.003, 0.011, 0.003, 0.004 ] nII6584Err = [ 0.005, 0.009, 0.006, 0.016, 0.024, 0.017, 0.007, 0.013, 0.004, 0.011, 0.016, 0.012, 0.003, 0.012, 0.062, 0.033, 0.014, 0.002, 0.007, 0.003, 0.003 ] hBeta = (unumpy.uarray(hBetaAbs, hBetaErr)) oIII5007 = unumpy.uarray(oIII5007Abs, oIII5007Err) hAlpha = unumpy.uarray(hAlphaAbs, hAlphaErr) nII6584 = unumpy.uarray(nII6584Abs, nII6584Err) ratioNII = unumpy.log10(nII6584 / hAlpha) ratioOIII = unumpy.log10(oIII5007 / hBeta) x = unumpy.nominal_values(ratioNII) xErr = unumpy.std_devs(ratioNII) y = unumpy.nominal_values(ratioOIII) yErr = unumpy.std_devs(ratioOIII) plt.scatter(x, y, marker='s', color='grey', alpha=0.3, label="Olave et al. 2015") plt.errorbar(x, y, xerr=xErr, yerr=yErr, color='grey', ecolor='grey', elinewidth=0.5, fmt='none', alpha=0.3)
def _trapz_loglog(y, x, axis=-1, intervals=False): """ Integrate along the given axis using the composite trapezoidal rule in loglog space. Integrate `y` (`x`) along given axis in loglog space. Parameters ---------- y : array_like Input array to integrate. x : array_like, optional Independent variable to integrate over. axis : int, optional Specify the axis. intervals : bool, optional Return array of shape x not the total integral, default: False Returns ------- trapz : float Definite integral as approximated by trapezoidal rule in loglog space. """ log10 = np.log10 try: y_unit = y.unit y = y.value except AttributeError: y_unit = 1.0 try: x_unit = x.unit x = x.value except AttributeError: x_unit = 1.0 y = np.asanyarray(y) x = np.asanyarray(x) slice1 = [slice(None)] * y.ndim slice2 = [slice(None)] * y.ndim slice1[axis] = slice(None, -1) slice2[axis] = slice(1, None) slice1, slice2 = tuple(slice1), tuple(slice2) # arrays with uncertainties contain objects if y.dtype == "O": from uncertainties.unumpy import log10 # uncertainties.unumpy.log10 can't deal with tiny values see # https://github.com/gammapy/gammapy/issues/687, so we filter out the values # here. As the values are so small it doesn't affect the final result. # the sqrt is taken to create a margin, because of the later division # y[slice2] / y[slice1] valid = y > np.sqrt(np.finfo(float).tiny) x, y = x[valid], y[valid] if x.ndim == 1: shape = [1] * y.ndim shape[axis] = x.shape[0] x = x.reshape(shape) with np.errstate(invalid="ignore", divide="ignore"): # Compute the power law indices in each integration bin b = log10(y[slice2] / y[slice1]) / log10(x[slice2] / x[slice1]) # if local powerlaw index is -1, use \int 1/x = log(x); otherwise use normal # powerlaw integration trapzs = np.where( np.abs(b + 1.0) > 1e-10, (y[slice1] * (x[slice2] * (x[slice2] / x[slice1]) ** b - x[slice1])) / (b + 1), x[slice1] * y[slice1] * np.log(x[slice2] / x[slice1]), ) tozero = (y[slice1] == 0.0) + (y[slice2] == 0.0) + (x[slice1] == x[slice2]) trapzs[tozero] = 0.0 if intervals: return trapzs * x_unit * y_unit ret = np.add.reduce(trapzs, axis) * x_unit * y_unit return ret
def _trapz_loglog(y, x, axis=-1, intervals=False, ulog10=False): """ Integrate along the given axis using the composite trapezoidal rule in loglog space. Integrate `y` (`x`) along given axis in loglog space. Parameters ---------- y : array_like Input array to integrate. x : array_like, optional Independent variable to integrate over. axis : int, optional Specify the axis. intervals : bool, optional Return array of shape x not the total integral, default: False ulog10 : bool, optional Use `~uncertainties.unumpy.log10` to allow uarrays for y and do error propagation for the integral value. Returns ------- trapz : float Definite integral as approximated by trapezoidal rule in loglog space. """ log10 = np.log10 if ulog10: from uncertainties.unumpy import log10 try: y_unit = y.unit y = y.value except AttributeError: y_unit = 1. try: x_unit = x.unit x = x.value except AttributeError: x_unit = 1. y = np.asanyarray(y) x = np.asanyarray(x) slice1 = [slice(None)] * y.ndim slice2 = [slice(None)] * y.ndim slice1[axis] = slice(None, -1) slice2[axis] = slice(1, None) if x.ndim == 1: shape = [1] * y.ndim shape[axis] = x.shape[0] x = x.reshape(shape) with np.errstate(invalid='ignore', divide='ignore'): # Compute the power law indices in each integration bin b = log10(y[slice2] / y[slice1]) / log10(x[slice2] / x[slice1]) # if local powerlaw index is -1, use \int 1/x = log(x); otherwise use normal # powerlaw integration trapzs = np.where( np.abs(b + 1.) > 1e-10, (y[slice1] * ( x[slice2] * (x[slice2] / x[slice1]) ** b - x[slice1])) / (b + 1), x[slice1] * y[slice1] * np.log(x[slice2] / x[slice1])) tozero = (y[slice1] == 0.) + (y[slice2] == 0.) + (x[slice1] == x[slice2]) trapzs[tozero] = 0. if intervals: return trapzs * x_unit * y_unit ret = np.add.reduce(trapzs, axis) * x_unit * y_unit return ret