def collimfunc(delthetra,delthetdec,lxpc=1,ra0=83.63,dec0=22.01) : """ Read LAXPC collimator response from files and give response (max unity) for given offset angles theta and phi """ fnamera = "LX" + str(lxpc) + "0_RA.txt" fnamedec = "LX" + str(lxpc) + "0_Dec.txt" tlpcr,raval = np.genfromtxt(fnamera,skip_header=1,unpack=True) ipr = ip(tlpcr,raval,k=2) drr = lambda z : ipr.derivatives(z)[1] tlrmax = fsolve(drr,16879)[0] tlpcd,decval = np.genfromtxt(fnamedec,skip_header=1,unpack=True) ipd = ip(tlpcd,decval,k=2) ddr = lambda z : ipd.derivatives(z)[1] tldmax = fsolve(ddr,29226)[0] tra,ra = np.genfromtxt('rascan.txt',skip_header=1,unpack=True) tdec,dec = np.genfromtxt('./decscan.txt',skip_header=1,unpack=True) poltra = np.polyfit(ra-ra0,tra,1) poltdec = np.polyfit(dec-dec0,tdec,1)#Inverting the variables for linfit fra = np.poly1d(poltra) fdec = np.poly1d(poltdec) timra = fra(np.rad2deg(delthetra)) timdec = fdec(np.rad2deg(delthetdec)) if (timra > tra.max() | timra < tra.min() | timdec > tdec.max() | timdec < \ tdec.min()) : raise ValueError("Angle out of FOV") return ipr(timra)/ipr(tlrmax)*ipd(timdec)/ipd(tldmax)
def collimfunc(delthetra, delthetdec, lxpc=1, ra0=83.63, dec0=22.01, full=False): """ Read LAXPC collimator response from files and give response (max unity) for given offset angles theta and phi """ #print "delthetra = " #print delthetra #print "delthetdec = " #print delthetdec fnamera = folfits + "LX" + str(lxpc) + "0_RA.txt" fnamedec = folfits + "LX" + str(lxpc) + "0_Dec.txt" tlpcr, raval = np.genfromtxt(fnamera, skip_header=1, unpack=True) ipr = ip(tlpcr, raval, k=2) drr = lambda z: ipr.derivatives(z)[1] tlrmax = fsolve(drr, 16879)[0] # Note that I am using my maximas instead of #the ones given in Table 2 of Antia's paper. Cursory examination shows #difference to be minimal - must shift to Table 2 vals soon tlpcd, decval = np.genfromtxt(fnamedec, skip_header=1, unpack=True) ipd = ip(tlpcd, decval, k=2) ddr = lambda z: ipd.derivatives(z)[1] tldmax = fsolve(ddr, 29226)[0] tra, ra = np.genfromtxt(folfits + 'rascan.txt', skip_header=1, unpack=True) tdec, dec = np.genfromtxt(folfits + 'decscan.txt', skip_header=1, unpack=True) poltra = np.polyfit(ra - ra0, tra, 1) poltdec = np.polyfit(dec - dec0, tdec, 1) #Inverting the variables for linfit fra = np.poly1d(poltra) fdec = np.poly1d(poltdec) rapc = (tlpcr - poltra[1]) / poltra[0] decpc = (tlpcd - poltdec[1]) / poltdec[0] if ( np.any(np.rad2deg(delthetra) > rapc.max()) | \ np.any(np.rad2deg(delthetra) < rapc.min()) | \ np.any(np.rad2deg(delthetdec) > decpc.max()) | \ np.any(np.rad2deg(delthetdec) < decpc.min()) ) : raise MyValueError("Angle out of FOV") timra = fra(np.rad2deg(delthetra)) timdec = fdec(np.rad2deg(delthetdec)) if (full): dramax = (tlrmax - poltra[1]) / poltra[0] # using inverse polynom funcn ddecmax = (tldmax - poltdec[1]) / poltdec[0] return ipr(timra) / ipr(tlrmax) * ipd(timdec) / ipd( tldmax), dramax, ddecmax return ipr(timra) / ipr(tlrmax) * ipd(timdec) / ipd(tldmax)
def effarea(lxpc) : """ Gets integrated eff. area between 3 to 80 keV """ fname="effarea_lxpc.txt" ener,area = np.genfromtxt(fname,unpack=True) idnan = np.where(np.isnan(ener))[0] if (lxpc == 1) : idpc = np.arange(0,idnan[0]) if (lxpc == 2) : idpc = np.arange(idnan[0]+1,idnan[1]) if (lxpc == 3) : idpc = np.arange(idnan[1]+1,idnan[2]) fn = ip(ener[idpc],area[idpc],k=1) #intar = quad(fn,3.0,31.90)[0] + quad(fn,32.5,80.0)[0] # breaking integral at 32 keV discontinuity intar = quad(fn,3.0,80.0) # no use breaking the func - see what prblm return intar[0]
def effarea(lxpc,elo=3.0,ehi=15.0) : """ Gets integrated eff. area between 3 to 80 keV """ fname=folfits + "effarea_lxpc.txt" ener,area = np.genfromtxt(fname,unpack=True) idnan = np.where(np.isnan(ener))[0] if (lxpc == 1) : idpc = np.arange(0,idnan[0]) if (lxpc == 2) : idpc = np.arange(idnan[0]+1,idnan[1]) if (lxpc == 3) : idpc = np.arange(idnan[1]+1,idnan[2]) fn = ip(ener[idpc],area[idpc],k=1) #intar = quad(fn,3.0,31.90)[0] + quad(fn,32.5,80.0)[0] # breaking integral at 32 keV discontinuity intar = quad(fn,elo,ehi) # no use breaking the func - see what prblm #intar = romb(area[idpc],ener[idpc],elo,ehi) # why not use discrete integration ? geomar = 3600 # cm^2 100cm x 36 cm (and 15 cm depth - see http://www.tifr.res.in/~astrosat_laxpc/specification.html) return intar[0]/(geomar*(ehi - elo))
def interpolate_power(spec, mode="linear", domain=None, kindex=None, newkindex=None, loglog=False, **kwargs): """ Interpolates a given power spectrum at new k(-indices). Parameters ---------- spec : {scalar, list, array, field, function} The power spectrum. A scalars is interpreted as a constant spectrum. mode : string String specifying the interpolation scheme, supported schemes are (default: "linear"): - "linear" - "nearest" - "zero" - "slinear" - "quadratic" - "cubic" domain : space, *optional* The space wherein the power spectrum is defined (default: None). kindex : numpy.ndarray, *optional* Scales corresponding to each band in the old power spectrum; can be retrieved from `domain` (default: None). newkindex : numpy.ndarray, *optional* Scales corresponding to each band in the new power spectrum; can be retrieved from `domain` if `kindex` is given (default: None). loglog : bool, *optional* Flag specifying whether the interpolation is done on log-log-scale (ignoring the monopole) or not (default: False) Returns ------- newspec : numpy.ndarray The interpolated power spectrum. Other Parameters ---------------- log : bool, *optional* Flag specifying if the spectral binning is performed on logarithmic scale or not; if set, the number of used bins is set automatically (if not given otherwise); by default no binning is done (default: None). nbin : integer, *optional* Number of used spectral bins; if given `log` is set to ``False``; integers below the minimum of 3 induce an automatic setting; by default no binning is done (default: None). binbounds : {list, array}, *optional* User specific inner boundaries of the bins, which are preferred over the above parameters; by default no binning is done (default: None). vmin : {scalar, list, ndarray, field}, *optional* Lower limit of the uniform distribution if ``random == "uni"`` (default: 0). See Also -------- scipy.interpolate.interp1d Raises ------ Exception, IndexError, TypeError, ValueError If some input is invalid. ValueError If an interpolation is flawed. """ ## check implicit kindex if (kindex is None): if (isinstance(domain, space)): try: domain.set_power_indices(**kwargs) except: raise ValueError( about._errors.cstring("ERROR: invalid input.")) else: kindex = domain.power_indices.get("kindex") else: raise TypeError( about._errors.cstring("ERROR: insufficient input.")) ## check power spectrum spec = domain.enforce_power(spec, size=np.size(kindex)) ## check explicit newkindex if (newkindex is None): raise Exception( about._errors.cstring("ERROR: insufficient input.")) else: newkindex = np.sort(np.real( np.array(newkindex, dtype=domain.vol.dtype).flatten(order='C')), axis=0, kind="quicksort", order=None) ## check explicit kindex else: kindex = np.sort(np.real( np.array(kindex, dtype=None).flatten(order='C')), axis=0, kind="quicksort", order=None) ## check power spectrum if (isinstance(spec, field)): spec = spec.val.astype(kindex.dtype) elif (callable(spec)): try: spec = np.array(spec(kindex), dtype=None) except: TypeError( about._errors.cstring( "ERROR: invalid power spectra function.") ) ## exception in ``spec(kindex)`` elif (np.isscalar(spec)): spec = np.array([spec], dtype=None) else: spec = np.array(spec, dtype=None) ## drop imaginary part spec = np.real(spec) ## check finiteness and positivity (excluding null) if (not np.all(np.isfinite(spec))): raise ValueError( about._errors.cstring("ERROR: infinite value(s).")) elif (np.any(spec < 0)): raise ValueError( about._errors.cstring("ERROR: nonpositive value(s).")) elif (np.any(spec == 0)): about.warnings.cprint("WARNING: nonpositive value(s).") size = np.size(kindex) ## extend if (np.size(spec) == 1): spec = spec * np.ones(size, dtype=spec.dtype, order='C') ## size check elif (np.size(spec) < size): raise ValueError( about._errors.cstring("ERROR: size mismatch ( " + str(np.size(spec)) + " < " + str(size) + " ).")) elif (np.size(spec) > size): about.warnings.cprint("WARNING: power spectrum cut to size ( == " + str(size) + " ).") spec = spec[:size] ## check implicit newkindex if (newkindex is None): if (isinstance(domain, space)): try: domain.set_power_indices(**kwargs) except: raise ValueError( about._errors.cstring("ERROR: invalid input.")) else: newkindex = domain.power_indices.get("kindex") else: raise TypeError( about._errors.cstring("ERROR: insufficient input.")) ## check explicit newkindex else: newkindex = np.sort(np.real( np.array(newkindex, dtype=None).flatten(order='C')), axis=0, kind="quicksort", order=None) ## check bounds if (kindex[0] < 0) or (newkindex[0] < 0): raise ValueError(about._errors.cstring("ERROR: invalid input.")) if (np.any(newkindex > kindex[-1])): about.warnings.cprint("WARNING: interpolation beyond upper bound.") ## continuation extension by point mirror nmirror = np.size(kindex) - np.searchsorted( kindex, 2 * kindex[-1] - newkindex[-1], side='left') + 1 spec = np.r_[spec, np.exp(2 * np.log(spec[-1]) - np.log(spec[-nmirror:-1][::-1]))] kindex = np.r_[kindex, (2 * kindex[-1] - kindex[-nmirror:-1][::-1])] ## interpolation if (loglog): ## map to log-log-scale ignoring monopole logspec = np.log(spec[1:]) logspec = ip(np.log(kindex[1:]), logspec, kind=mode, axis=0, copy=True, bounds_error=True, fill_value=np.NAN)(np.log(newkindex[1:])) newspec = np.concatenate([[spec[0]], np.exp(logspec)]) else: newspec = ip(kindex, spec, kind=mode, axis=0, copy=True, bounds_error=True, fill_value=np.NAN)(newkindex) ## check new power spectrum if (not np.all(np.isfinite(newspec))): raise ValueError(about._errors.cstring("ERROR: infinite value(s).")) elif (np.any(newspec < 0)): raise ValueError(about._errors.cstring("ERROR: nonpositive value(s).")) elif (np.any(newspec == 0)): about.warnings.cprint("WARNING: nonpositive value(s).") return newspec
def interpolate_power(spec,mode="linear",domain=None,kindex=None,newkindex=None,**kwargs): """ Interpolates a given power spectrum at new k(-indices). Parameters ---------- spec : {scalar, list, array, field, function} The power spectrum. A scalars is interpreted as a constant spectrum. mode : string String specifying the interpolation scheme, supported schemes are (default: "linear"): - "linear" - "nearest" - "zero" - "slinear" - "quadratic" - "cubic" domain : space, *optional* The space wherein the power spectrum is defined (default: None). kindex : numpy.ndarray, *optional* Scales corresponding to each band in the old power spectrum; can be retrieved from `domain` (default: None). newkindex : numpy.ndarray, *optional* Scales corresponding to each band in the new power spectrum; can be retrieved from `domain` if `kindex` is given (default: None). Returns ------- newspec : numpy.ndarray The interpolated power spectrum. Other Parameters ---------------- log : bool, *optional* Flag specifying if the spectral binning is performed on logarithmic scale or not; if set, the number of used bins is set automatically (if not given otherwise); by default no binning is done (default: None). nbin : integer, *optional* Number of used spectral bins; if given `log` is set to ``False``; integers below the minimum of 3 induce an automatic setting; by default no binning is done (default: None). binbounds : {list, array}, *optional* User specific inner boundaries of the bins, which are preferred over the above parameters; by default no binning is done (default: None). vmin : {scalar, list, ndarray, field}, *optional* Lower limit of the uniform distribution if ``random == "uni"`` (default: 0). See Also -------- scipy.interpolate.interp1d Raises ------ Exception, IndexError, TypeError, ValueError If some input is invalid. ValueError If an interpolation is flawed. """ ## check implicit kindex if(kindex is None): if(isinstance(domain,space)): try: domain.set_power_indices(**kwargs) except: raise ValueError(about._errors.cstring("ERROR: invalid input.")) else: kindex = domain.power_indices.get("kindex") else: raise TypeError(about._errors.cstring("ERROR: insufficient input.")) ## check power spectrum spec = domain.enforce_power(spec,size=np.size(kindex)) ## check explicit newkindex if(newkindex is None): raise Exception(about._errors.cstring("ERROR: insufficient input.")) else: newkindex = np.sort(np.real(np.array(newkindex,dtype=domain.vol.dtype).flatten(order='C')),axis=0,kind="quicksort",order=None) ## check explicit kindex else: kindex = np.sort(np.real(np.array(kindex,dtype=None).flatten(order='C')),axis=0,kind="quicksort",order=None) ## check power spectrum if(isinstance(spec,field)): spec = spec.val.astype(kindex.dtype) elif(callable(spec)): try: spec = np.array(spec(kindex),dtype=kindex.dtype) except: TypeError(about._errors.cstring("ERROR: invalid power spectra function.")) ## exception in ``spec(kindex)`` elif(np.isscalar(spec)): spec = np.array([spec],dtype=kindex.dtype) else: spec = np.array(spec,dtype=kindex.dtype) ## drop imaginary part spec = np.real(spec) ## check finiteness and positivity (excluding null) if(not np.all(np.isfinite(spec))): raise ValueError(about._errors.cstring("ERROR: infinite value(s).")) elif(np.any(spec<0)): raise ValueError(about._errors.cstring("ERROR: nonpositive value(s).")) elif(np.any(spec==0)): about.warnings.cprint("WARNING: nonpositive value(s).") size = np.size(kindex) ## extend if(np.size(spec)==1): spec = spec*np.ones(size,dtype=spec.dtype,order='C') ## size check elif(np.size(spec)<size): raise ValueError(about._errors.cstring("ERROR: size mismatch ( "+str(np.size(spec))+" < "+str(size)+" ).")) elif(np.size(spec)>size): about.warnings.cprint("WARNING: power spectrum cut to size ( == "+str(size)+" ).") spec = spec[:size] ## check implicit newkindex if(newkindex is None): if(isinstance(domain,space)): try: domain.set_power_indices(**kwargs) except: raise ValueError(about._errors.cstring("ERROR: invalid input.")) else: newkindex = domain.power_indices.get("kindex") else: raise TypeError(about._errors.cstring("ERROR: insufficient input.")) ## check explicit newkindex else: newkindex = np.sort(np.real(np.array(newkindex,dtype=None).flatten(order='C')),axis=0,kind="quicksort",order=None) ## check bounds if(kindex[0]<0)or(newkindex[0]<0): raise ValueError(about._errors.cstring("ERROR: invalid input.")) if(np.any(newkindex>kindex[-1])): about.warnings.cprint("WARNING: interpolation beyond upper bound.") ## continuation extension by point mirror nmirror = np.size(kindex)-np.searchsorted(kindex,2*kindex[-1]-newkindex[-1],side='left')+1 spec = np.r_[spec,np.exp(2*np.log(spec[-1])-np.log(spec[-nmirror:-1][::-1]))] kindex = np.r_[kindex,(2*kindex[-1]-kindex[-nmirror:-1][::-1])] ## interpolation newspec = ip(kindex,spec,kind=mode,axis=0,copy=True,bounds_error=True,fill_value=np.NAN)(newkindex) ## check new power spectrum if(not np.all(np.isfinite(newspec))): raise ValueError(about._errors.cstring("ERROR: infinite value(s).")) elif(np.any(newspec<0)): raise ValueError(about._errors.cstring("ERROR: nonpositive value(s).")) elif(np.any(newspec==0)): about.warnings.cprint("WARNING: nonpositive value(s).") return newspec
from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import InterpolatedUnivariateSpline as ip from scipy.optimize import fsolve import matplotlib.cm as cm folfits="../../" lxpc=3 ra0 = 83.63 dec0 = 22.01 full = False sz= 100 fnamera = folfits + "LX" + str(lxpc) + "0_RA.txt" fnamedec = folfits + "LX" + str(lxpc) + "0_Dec.txt" tlpcr,raval = np.genfromtxt(fnamera,skip_header=1,unpack=True) ipr = ip(tlpcr,raval,k=2) drr = lambda z : ipr.derivatives(z)[1] tlrmax = fsolve(drr,16879)[0] # Note that I am using my maximas instead of #the ones given in Table 2 of Antia's paper. Cursory examination shows #difference to be minimal - must shift to Table 2 vals soon tlpcd,decval = np.genfromtxt(fnamedec,skip_header=1,unpack=True) ipd = ip(tlpcd,decval,k=2) ddr = lambda z : ipd.derivatives(z)[1] tldmax = fsolve(ddr,29226)[0] tra,ra = np.genfromtxt(folfits + 'rascan.txt',skip_header=1,unpack=True) tdec,dec = np.genfromtxt(folfits + 'decscan.txt',skip_header=1,unpack=True) poltra = np.polyfit(ra-ra0,tra,1) poltdec = np.polyfit(dec-dec0,tdec,1)#Inverting the variables for linfit fra = np.poly1d(poltra) fdec = np.poly1d(poltdec)