Ejemplo n.º 1
0
def initializeStandards(spt,
                        sdss=True,
                        reset=False,
                        sd=False,
                        esd=False,
                        usd=False,
                        beta=False,
                        giant=False,
                        gamma=False,
                        verbose=False):
    if isinstance(spt, list) == False: spt = [spt]
    if isinstance(spt[0], float) == True or isinstance(spt[0], int) == True:
        if len(spt) == 2: spt = numpy.arange(spt[0], spt[1] + 1)
        spt = [kastredux.typeToNum(s) for s in spt]

    if sd == True and 'sd' not in spt[0]: spt = ['sd' + s for s in spt]
    if esd == True and 'esd' not in spt[0]: spt = ['esd' + s for s in spt]
    if usd == True and 'usd' not in spt[0]: spt = ['usd' + s for s in spt]
    if beta == True and 'b' not in spt[0]: spt = [s + 'b' for s in spt]
    if gamma == True and 'g' not in spt[0]: spt = [s + 'g' for s in spt]
    if giant == True and 'I' not in spt[0]: spt = [s + 'I' for s in spt]

    for s in spt:
        if s not in list(kastredux.SPTSTDS.keys()) or reset == True:
            f = numpy.array(
                glob.glob('{}/{}*.txt'.format(kastredux.SPTSTDFOLDER,
                                              s.replace('.', ''))))
            if len(f) > 1:
                if sdss == True and len(f[['SDSS' in x for x in f]]) > 0:
                    f = f[['SDSS' in x for x in f]]
                    # for subdwarfs
                elif (sd == True or esd == True
                      or usd == True) and len(f[['lepine2007' in x
                                                 for x in f]]) > 0:
                    #					print(len(f))
                    f = f[['lepine2007' in x for x in f]]
                else:
                    pass
            if len(f) > 0:
                kastredux.SPTSTDS[s] = kastredux.readSpectrum(
                    f[0], name='{} STD'.format(s))
            else:
                if verbose == True:
                    print(
                        'Warning: cannot find a spectral standard for type {}'.
                        format(s))
    return
Ejemplo n.º 2
0
def classify_by_standard(spec, ref='lepine', plot=False, diag_path=None):

    lepine_str = 'lepine'
    kirkpatrick_str = 'kirkpatrick'
    burgasser_str = 'burgasser'
    sdss_str = 'SDSS'
    all_str = 'all'

    STANDARD_SPECTRA = []
    LEPINE_STANDARDS = []
    KIRKPATRICK_STANDARDS = []
    BURGASSER_STANDARDS = []
    SDSS_STANDARDS = []

    STANDARD_PATHS = glob.glob(kastredux.SPTSTDFOLDER + '*.txt')

    for path in STANDARD_PATHS:
        name = os.path.basename(os.path.splitext(path)[0])
        stand_spec = kastredux.readSpectrum(path)
        stand_spec.name = name

        STANDARD_SPECTRA.append(stand_spec)

        if (lepine_str in name):
            LEPINE_STANDARDS.append(stand_spec)
        elif (kirkpatrick_str in name):
            KIRKPATRICK_STANDARDS.append(stand_spec)
        elif (burgasser_str in name):
            BURGASSER_STANDARDS.append(stand_spec)
        elif sdss_str in name:
            SDSS_STANDARDS.append(stand_spec)

    minimal = 1e90
    minimal_scale = None
    minimal_standard = None
    minimal_standard_name = None

    COMPARISON = []

    if (ref in lepine_str):
        COMPARISON = LEPINE_STANDARDS
    elif (ref in kirkpatrick_str):
        COMPARISON = KIRKPATRICK_STANDARDS
    elif (ref in burgasser_str):
        COMPARISON = BURGASSER_STANDARDS
    elif ref in sdss_str:
        COMPARISON = SDSS_STANDARDS
    else:
        COMPARISON = STANDARD_SPECTRA

    for stand in COMPARISON:

        chi2, scalefactor = kastredux.compareSpectra_simple(spec, stand)

        if chi2 < minimal:
            minimal = chi2
            minimal_scale = scalefactor
            minimal_standard = stand
            minimal_standard_name = stand.name

    if plot or (diag_path is not None):
        placeholder = kastredux.compareSpectra_simple(spec,
                                                      minimal_standard,
                                                      plot=True)

        if diag_path is not None:

            plt.savefig(diag_path + spec.name + '_standardComparison.png')

        if plot:
            plt.show()
        plt.close()

    spt = spt_from_name(minimal_standard_name)

    return spt, minimal_standard_name, minimal, minimal_scale
Ejemplo n.º 3
0
def calc_spec_info(filepath,
                   plot=False,
                   no_index_trials=100,
                   no_EW_trials=30,
                   diag_path=None):

    t1 = datetime.datetime.now()

    #collecting header info
    print('Reading in {}'.format(filepath))

    spec = kastredux.readSpectrum(filepath)
    spec.name = fits.getheader(filepath)['OBJECT']

    ra = fits.getheader(filepath)['RA']

    dec = fits.getheader(filepath)['DEC']

    date = fits.getheader(filepath)['DATE']

    filename = os.path.basename(filepath)

    if plot:
        spec.plot()
        plt.show()
    if diag_path is not None:

        spec.plot()
        plt.savefig(diag_path + spec.name + '_spec.png')

    print('Classifying by standard comparison...')
    spt, stand_name, spt_chi2, spt_scale = classify_by_standard(
        spec, ref='all', plot=plot, diag_path=diag_path)

    print('Done!')

    print('Measuring indices...')
    indices = {}

    for ref in list(kastclassify.defs.index_dict):

        print('Mesuring index set {}...'.format(ref))

        indices[ref] = measure_index_set(spec,
                                         ref=ref,
                                         no_trials=no_index_trials)

        print('Done!')

    print('Done!')

    print('Measuring Equivalent Widths...')
    EWs = {}

    for ref in list(kastclassify_EW_dict):

        print('Measuring EW for {}...'.format(ref))

        EWs[ref] = measure_EW_element(spec,
                                      ref=ref,
                                      plot=plot,
                                      no_trials=no_EW_trials,
                                      diag_path=diag_path)

        print('Done!')

    print('Done!')
    #calculating with the measurements

    print('Calculating spectral types by index...')
    index_spt, zeta_info, metallicity_class = classify_by_index(
        spec, index_dict=indices)

    print('Done!')

    print('Calculating L_Halpha/L_bol...')

    Lratio, Lratio_err = calculate_L_Lbol(EWs['Halpha']['EW'],
                                          EWs['Halpha']['EW_err'], spt)

    print('Done!')

    plt.close('all')
    #unpacking results

    print('Packaging results...')

    results = {}

    results['name'] = spec.name
    results['filename'] = filename
    results['RA'] = ra
    results['DEC'] = dec
    results['OBSDATE'] = date

    results['spt'] = spt
    results['subtype'] = typeToNum(spt) - 10
    results['spt_chi2'] = spt_chi2
    results['spt_scale'] = spt_scale

    for ref in list(indices):

        for name in list(indices[ref]):

            results[ref + '_' + name] = indices[ref][name][0]
            results[ref + '_' + name + '_err'] = indices[ref][name][1]

    for ref in list(EWs):

        for name in list(EWs[ref]):

            results[ref + '_' + name + '_(Angstrom)'] = EWs[ref][name]

    for ref in list(index_spt):

        results[ref] = index_spt[ref]

    results['zeta'] = zeta_info[0]

    results['zeta_err'] = zeta_info[1]

    results['metallicity_class'] = metallicity_class

    results['L_Halpha/L_bol'] = Lratio

    results['L_Halpha/L_bol_err'] = Lratio_err

    print('Done!')

    t2 = datetime.datetime.now()
    dt = t2 - t1

    print('All done in {}! All done at {}'.format(dt, t2))

    return results
Ejemplo n.º 4
0
def reduction_batch(dates):
    for date in dates:
        folder = '{}/{}/'.format(base_folder, date)
        # red
        instruct_file = '{}/{}'.format(folder, red_input)
        if os.path.exists(instruct_file):
            print('\n\nReducing RED data from {}\n\n'.format(date))
            par = kastredux.readInstructions(instruct_file)
            # first run a profileCheck
            tmp = kastredux.profileCheck(instruct_file)
            # now reduce
            redux = kastredux.reduce(
                instructions=instruct_file,
                bias_file='bias_RED.fits',
                flat_file='flat_RED.fits',
                mask_file='mask_RED.fits',
                cal_flux_file='cal_flux_RED.pkl',
                reset=True)  #,cal_wave_file='cal_wave_BLUE.pkl')

            # classify results
            print('\n\nClassifying RED data from {}\n\n'.format(date))
            sources = list(par['SOURCE'].keys())
            for src in sources:
                spec = kastredux.readSpectrum('{}/kastRED_{}_20{}.fits'.format(
                    par['REDUCTION_FOLDER'], src, date))
                spec.name = src
                stats = []
                stds = list(kastredux.SPTSTDS.keys())
                for s in stds:
                    st, scl = kastredux.compareSpectra_simple(
                        spec,
                        kastredux.SPTSTDS[s],
                        fit_range=[6800, 8800],
                        plot=False)
                    stats.append(st)
                spt = stds[numpy.argmin(stats)]
                kastredux.compareSpectra_simple(
                    spec,
                    kastredux.SPTSTDS[spt],
                    fit_range=[6800, 8800],
                    plot=True,
                    plot_file='{}/classify{}_{}.pdf'.format(
                        par['REDUCTION_FOLDER'], par['MODE'], src))
#			except:
#				print('Problem reducing RED data from {}'.format(date))

# blue
        instruct_file = '{}/{}'.format(folder, blue_input)
        if os.path.exists(instruct_file):
            print('Reducing BLUE data from {}'.format(date))
            par = kastredux.readInstructions(instruct_file)
            # first run a profileCheck
            tmp = kastredux.profileCheck(instruct_file)
            # now reduce
            redux = kastredux.reduce(
                instructions=instruct_file,
                bias_file='bias_BLUE.fits',
                flat_file='flat_BLUE.fits',
                mask_file='mask_BLUE.fits',
                cal_flux_file='cal_flux_BLUE.pkl',
                reset=True)  #,cal_wave_file='cal_wave_BLUE.pkl')

# classify results
# sources = list(par['SOURCE'].keys())
# for src in sources:
# 	spec = kastredux.readSpectrum('{}/kastBLUE_{}_20{}.fits'.format(par['REDUCTION_FOLDER'],src,date))
# 	spec.name = src
# 	stats = []
# 	stds = list(kastredux.SPTSTDS.keys())
# 	for s in stds:
# 		st,scl = kastredux.compareSpectra_simple(spec,kastredux.SPTSTDS[s],fit_range=[4500,5300],plot=False)
# 		stats.append(st)
# 	spt = stds[numpy.argmin(stats)]
# 	kastredux.compareSpectra_simple(spec,kastredux.SPTSTDS[spt],fit_range=[4500,5300],plot=True,plot_file='{}/classify{}_{}.pdf'.format(par['REDUCTION_FOLDER'],par['MODE'],src))
#			except:
#				print('Problem reducing BLUE data from {}'.format(date))

    return