def get_plotsymbolcolorinfo(): """ Return the arrays needed to always plot the same photometric system with the same color. """ photsystem_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'list_photsystems_sorted.dat') plotcolorvalues_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'plotcolorvalues.dat') try: sortedphotsystems = ascii.read2array(photsystem_file, dtype='str') except IOError: logger.info( 'Loading of {} file failed. No fixed symbol color for each photometric system possible.' .format(photsystem_file)) try: plotcolorvalues = ascii.read2array(plotcolorvalues_file) except IOError: logger.info( 'Loading of {} file failed. No fixed symbol color for each photometric system possible.' .format(plotcolorvalues_file)) try: if len(sortedphotsystems) == len(plotcolorvalues): return sortedphotsystems.ravel(), plotcolorvalues.ravel() else: raise IndexError print('{} should be of equal length as {}.'.format( plotcolorvalues_file, photsystem_file)) except NameError: return None, None
def get_response(photband): """ Retrieve the response curve of a photometric system 'SYSTEM.FILTER' OPEN.BOL represents a bolometric open filter. Example usage: >>> p = pl.figure() >>> for band in ['J','H','KS']: ... p = pl.plot(*get_response('2MASS.%s'%(band))) If you defined a custom filter with the same name as an existing one and you want to use that one in the future, set C{prefer_file=False} in the C{custom_filters} module dictionary. @param photband: photometric passband @type photband: str ('SYSTEM.FILTER') @return: (wavelength [A], response) @rtype: (array, array) """ photband = photband.upper() prefer_file = custom_filters['_prefer_file'] if photband == 'OPEN.BOL': return np.array([1, 1e10]), np.array([1 / (1e10 - 1), 1 / (1e10 - 1)]) #-- either get from file or get from dictionary photfile = os.path.join(basedir, 'filters', photband) photfile_is_file = os.path.isfile(photfile) #-- if the file exists and files have preference if photfile_is_file and prefer_file: wave, response = ascii.read2array(photfile).T[:2] #-- if the custom_filter exist elif photband in custom_filters: wave, response = custom_filters[photband]['response'] #-- if the file exists but custom filters have preference elif photfile_is_file: wave, response = ascii.read2array(photfile).T[:2] else: raise IOError, ('{0} does not exist {1}'.format( photband, custom_filters.keys())) sa = np.argsort(wave) return wave[sa], response[sa]
def get_response(photband): """ Retrieve the response curve of a photometric system 'SYSTEM.FILTER' OPEN.BOL represents a bolometric open filter. Example usage: >>> p = pl.figure() >>> for band in ['J','H','KS']: ... p = pl.plot(*get_response('2MASS.%s'%(band))) If you defined a custom filter with the same name as an existing one and you want to use that one in the future, set C{prefer_file=False} in the C{custom_filters} module dictionary. @param photband: photometric passband @type photband: str ('SYSTEM.FILTER') @return: (wavelength [A], response) @rtype: (array, array) """ photband = photband.upper() prefer_file = custom_filters['_prefer_file'] if photband=='OPEN.BOL': return np.array([1,1e10]),np.array([1/(1e10-1),1/(1e10-1)]) #-- either get from file or get from dictionary photfile = os.path.join(basedir,'filters',photband) photfile_is_file = os.path.isfile(photfile) #-- if the file exists and files have preference if photfile_is_file and prefer_file: wave, response = ascii.read2array(photfile).T[:2] #-- if the custom_filter exist elif photband in custom_filters: wave, response = custom_filters[photband]['response'] #-- if the file exists but custom filters have preference elif photfile_is_file: wave, response = ascii.read2array(photfile).T[:2] else: raise IOError,('{0} does not exist {1}'.format(photband,custom_filters.keys())) sa = np.argsort(wave) return wave[sa],response[sa]
def csv2recarray(filename): """ Read a MAST csv (comma-sep) file into a record array. @param filename: name of the TCSV file @type filename: str @return: catalog data columns, units, comments @rtype: record array, dict, list of str """ data, comms = ascii.read2array(filename, dtype=np.str, splitchar=',', return_comments=True) results = None units = {} #-- retrieve the data and put it into a record array if len(data) > 1: #-- now convert this thing into a nice dictionary data = np.array(data) #-- retrieve the format of the columns. They are given in the # Fortran format. In rare cases, columns contain multiple values # themselves (so called vectors). In those cases, we interpret # the contents as a long string formats = np.zeros_like(data[0]) for i, fmt in enumerate(data[1]): if 'string' in fmt or fmt == 'datetime': formats[i] = 'U100' if fmt == 'integer': formats[i] = 'f8' if fmt == 'ra': formats[i] = 'f8' if fmt == 'dec': formats[i] = 'f8' if fmt == 'float': formats[i] = 'f8' #-- define dtypes for record array dtypes = np.dtype([(i, j) for i, j in zip(data[0], formats)]) #-- remove spaces or empty values cols = [] for i, key in enumerate(data[0]): col = data[2:, i] #-- fill empty values with nan cols.append([(row.isspace() or not row) and np.nan or row for row in col]) #-- fix unit name for source in cat_info.sections(): if cat_info.has_option(source, data[0, i] + '_unit'): units[key] = cat_info.get(source, data[0, i] + '_unit') break else: units[key] = 'nan' #-- define columns for record array and construct record array cols = [np.cast[dtypes[i]](cols[i]) for i in range(len(cols))] results = np.rec.array(cols, dtype=dtypes) else: results = None units = {} return results, units, comms
def calibrate(wave,flux,header=None): """ Rough calibration of Hermes spectrum. Thanks to Roy Ostensen for computing the response function via detailed modeling of Feige 66. """ #-- read instrument response function instrument = config.get_datafile('catalogs/hermes','hermes_20110319.resp') iwave,iflux = ascii.read2array(instrument).T keep = (iwave.min()<=wave) & (wave<=iwave.max()) #-- interpolate on observed wavelength array iflux = np.interp(wave[keep],iwave,iflux) return wave[keep],flux[keep]/iflux,iflux
def calibrate(wave,flux,header=None): """ Rough calibration of Hermes spectrum. Thanks to Roy Ostensen for computing the response function via detailed modeling of Feige 66. """ #-- read instrument response function instrument = config.get_datafile('catalogs/hermes','hermes_20110319.resp') iwave,iflux = ascii.read2array(instrument).T keep = (iwave.min()<=wave) & (wave<=iwave.max()) #-- interpolate on observed wavelength array iflux = np.interp(wave[keep],iwave,iflux) return wave[keep],flux[keep]/iflux,iflux
def csv2recarray(filename): """ Read a MAST csv (comma-sep) file into a record array. @param filename: name of the TCSV file @type filename: str @return: catalog data columns, units, comments @rtype: record array, dict, list of str """ data,comms = ascii.read2array(filename,dtype=np.str,splitchar=',',return_comments=True) results = None units = {} #-- retrieve the data and put it into a record array if len(data)>1: #-- now convert this thing into a nice dictionary data = np.array(data) #-- retrieve the format of the columns. They are given in the # Fortran format. In rare cases, columns contain multiple values # themselves (so called vectors). In those cases, we interpret # the contents as a long string formats = np.zeros_like(data[0]) for i,fmt in enumerate(data[1]): if 'string' in fmt or fmt=='datetime': formats[i] = 'a100' if fmt=='integer': formats[i] = 'f8' if fmt=='ra': formats[i] = 'f8' if fmt=='dec': formats[i] = 'f8' if fmt=='float': formats[i] = 'f8' #-- define dtypes for record array dtypes = np.dtype([(i,j) for i,j in zip(data[0],formats)]) #-- remove spaces or empty values cols = [] for i,key in enumerate(data[0]): col = data[2:,i] #-- fill empty values with nan cols.append([(row.isspace() or not row) and np.nan or row for row in col]) #-- fix unit name for source in cat_info.sections(): if cat_info.has_option(source,data[0,i]+'_unit'): units[key] = cat_info.get(source,data[0,i]+'_unit') break else: units[key] = 'nan' #-- define columns for record array and construct record array cols = [np.cast[dtypes[i]](cols[i]) for i in range(len(cols))] results = np.rec.array(cols, dtype=dtypes) else: results = None units = {} return results,units,comms
def fitzpatrick2004(Rv=3.1, **kwargs): """ From Fitzpatrick 2004 (downloaded from FTP) This function returns A(lambda)/A(V). To get A(lambda)/E(B-V), multiply the return value with Rv (A(V)=Rv*E(B-V)) Extra kwags are to catch unwanted keyword arguments. @param Rv: Rv (2.1, 3.1 or 5.0) @type Rv: float @return: wavelengths (A), A(lambda)/Av @rtype: (ndarray,ndarray) """ filename = 'Fitzpatrick2004_Rv_%.1f.red' % (Rv) myfile = os.path.join(basename, filename) wave_inv, elamv_ebv = ascii.read2array(myfile, skip_lines=15).T logger.info('Fitzpatrick2004 curve with Rv=%.2f' % (Rv)) return 1e4 / wave_inv[::-1], ((elamv_ebv + Rv) / Rv)[::-1]
def fitzpatrick2004(Rv=3.1,**kwargs): """ From Fitzpatrick 2004 (downloaded from FTP) This function returns A(lambda)/A(V). To get A(lambda)/E(B-V), multiply the return value with Rv (A(V)=Rv*E(B-V)) Extra kwags are to catch unwanted keyword arguments. @param Rv: Rv (2.1, 3.1 or 5.0) @type Rv: float @return: wavelengths (A), A(lambda)/Av @rtype: (ndarray,ndarray) """ filename = 'Fitzpatrick2004_Rv_%.1f.red'%(Rv) myfile = os.path.join(basename,filename) wave_inv,elamv_ebv = ascii.read2array(myfile,skip_lines=15).T logger.info('Fitzpatrick2004 curve with Rv=%.2f'%(Rv)) return 1e4/wave_inv[::-1],((elamv_ebv+Rv)/Rv)[::-1]
def fitzpatrick1999(Rv=3.1, **kwargs): """ From Fitzpatrick 1999 (downloaded from ASAGIO database) This function returns A(lambda)/A(V). To get A(lambda)/E(B-V), multiply the return value with Rv (A(V)=Rv*E(B-V)) Extra kwags are to catch unwanted keyword arguments. @param Rv: Rv (2.1, 3.1 or 5.0) @type Rv: float @return: wavelengths (A), A(lambda)/Av @rtype: (ndarray,ndarray) """ filename = 'Fitzpatrick1999_Rv_%.1f' % (Rv) filename = filename.replace('.', '_') + '.red' myfile = os.path.join(basename, filename) wave, alam_ebv = ascii.read2array(myfile).T alam_av = alam_ebv / Rv logger.info('Fitzpatrick1999 curve with Rv=%.2f' % (Rv)) return wave, alam_av
def chiar2006(Rv=3.1, curve='ism', **kwargs): """ Extinction curve at infrared wavelengths from Chiar and Tielens (2006) We return A(lambda)/E(B-V), by multiplying A(lambda)/Av with Rv. This is only defined for Rv=3.1. If it is different, this will raise an AssertionError Extra kwags are to catch unwanted keyword arguments. UNCERTAIN NORMALISATION @param Rv: Rv @type Rv: float @param curve: extinction curve @type curve: string (one of 'gc' or 'ism', galactic centre or local ISM) @return: wavelengths (A), A(lambda)/Av @rtype: (ndarray,ndarray) """ source = os.path.join(basename, 'Chiar2006.red') #-- check Rv assert (Rv == 3.1) wavelengths, gc, ism = ascii.read2array(source).T if curve == 'gc': alam_ak = gc elif curve == 'ism': keep = ism > 0 alam_ak = ism[keep] wavelengths = wavelengths[keep] else: raise ValueError, 'no curve %s' % (curve) alam_aV = alam_ak * 0.09 #plot(1/wavelengths,alam_aV,'o-') return wavelengths * 1e4, alam_aV
def fitzpatrick1999(Rv=3.1,**kwargs): """ From Fitzpatrick 1999 (downloaded from ASAGIO database) This function returns A(lambda)/A(V). To get A(lambda)/E(B-V), multiply the return value with Rv (A(V)=Rv*E(B-V)) Extra kwags are to catch unwanted keyword arguments. @param Rv: Rv (2.1, 3.1 or 5.0) @type Rv: float @return: wavelengths (A), A(lambda)/Av @rtype: (ndarray,ndarray) """ filename = 'Fitzpatrick1999_Rv_%.1f'%(Rv) filename = filename.replace('.','_') + '.red' myfile = os.path.join(basename,filename) wave,alam_ebv = ascii.read2array(myfile).T alam_av = alam_ebv/Rv logger.info('Fitzpatrick1999 curve with Rv=%.2f'%(Rv)) return wave,alam_av
def chiar2006(Rv=3.1,curve='ism',**kwargs): """ Extinction curve at infrared wavelengths from Chiar and Tielens (2006) We return A(lambda)/E(B-V), by multiplying A(lambda)/Av with Rv. This is only defined for Rv=3.1. If it is different, this will raise an AssertionError Extra kwags are to catch unwanted keyword arguments. UNCERTAIN NORMALISATION @param Rv: Rv @type Rv: float @param curve: extinction curve @type curve: string (one of 'gc' or 'ism', galactic centre or local ISM) @return: wavelengths (A), A(lambda)/Av @rtype: (ndarray,ndarray) """ source = os.path.join(basename,'Chiar2006.red') #-- check Rv assert(Rv==3.1) wavelengths,gc,ism = ascii.read2array(source).T if curve=='gc': alam_ak = gc elif curve=='ism': keep = ism>0 alam_ak = ism[keep] wavelengths = wavelengths[keep] else: raise ValueError,'no curve %s'%(curve) alam_aV = alam_ak * 0.09 #plot(1/wavelengths,alam_aV,'o-') return wavelengths*1e4,alam_aV
pl.show() sys.exit() #-- if arguments are given, we assume the user wants to run one of the # functions with arguments given in the command line # EXAMPLES: # $:> python freqanalyse.py find_frequency infile=test.dat full_output=True # $:> python freqanalyse.py time_frequency infile=test.dat full_output=True else: method, args, kwargs = argkwargparser.parse() print("Running method %s with arguments %s and keyword arguments %s" % (method, args, kwargs)) if '--help' in args or 'help' in args or 'help' in kwargs: sys.exit() full_output = kwargs.get('full_output', False) times, signal = ascii.read2array(kwargs.pop('infile')).T[:2] out = globals()[method](times, signal, **kwargs) #-- when find_frequency is called if method == 'find_frequency' and full_output: print(pl.mlab.rec2txt(out[0], precision=8)) pl.figure() pl.subplot(211) pl.plot(out[1][0], out[1][1], 'k-') pl.subplot(212) pl.plot(times, signal, 'ko', ms=2) pl.plot(times, out[2], 'r-', lw=2) pl.show() elif method == 'find_frequency': print(pl.mlab.rec2txt(out))
doctest.testmod() pl.show() sys.exit() #-- if arguments are given, we assume the user wants to run one of the # functions with arguments given in the command line # EXAMPLES: # $:> python freqanalyse.py find_frequency infile=test.dat full_output=True # $:> python freqanalyse.py time_frequency infile=test.dat full_output=True else: method,args,kwargs = argkwargparser.parse() print "Running method %s with arguments %s and keyword arguments %s"%(method,args,kwargs) if '--help' in args or 'help' in args or 'help' in kwargs: sys.exit() full_output = kwargs.get('full_output',False) times,signal = ascii.read2array(kwargs.pop('infile')).T[:2] out = globals()[method](times,signal, **kwargs) #-- when find_frequency is called if method=='find_frequency' and full_output: print pl.mlab.rec2txt(out[0],precision=8) pl.figure() pl.subplot(211) pl.plot(out[1][0],out[1][1],'k-') pl.subplot(212) pl.plot(times,signal,'ko',ms=2) pl.plot(times,out[2],'r-',lw=2) pl.show() elif method=='find_frequency': print pl.mlab.rec2txt(out)