Ejemplo n.º 1
0
def calc_VeilingSED(Thot, Tint, Tcool, fi_fh, fc_fh):
    wave = numpy.arange(1.0, 2.5, 0.01)
    bm = numpy.argsort(abs(wave-2.2))[0]
    Bhot = SpectralTools.blackBody(wl = wave/10000.0, T=Thot,
               outUnits='Energy')
    Bint = SpectralTools.blackBody(wl = wave/10000.0, T=Tint,
               outUnits='Energy')*fi_fh
    Bcool = SpectralTools.blackBody(wl = wave/10000.0, T=Tcool,
               outUnits='Energy')*fc_fh
    composite = Bhot+Bint+Bcool
    composite /= composite[bm]
    return scipy.interpolate.interp1d(wave*10000.0, composite)
Ejemplo n.º 2
0
def calc_VeilingSED(Thot, Tint, Tcool, fi_fh, fc_fh):
    wave = numpy.arange(1.0, 2.5, 0.01)
    bm = numpy.argsort(abs(wave - 2.2))[0]
    Bhot = SpectralTools.blackBody(wl=wave / 10000.0,
                                   T=Thot,
                                   outUnits='Energy')
    Bint = SpectralTools.blackBody(
        wl=wave / 10000.0, T=Tint, outUnits='Energy') * fi_fh
    Bcool = SpectralTools.blackBody(
        wl=wave / 10000.0, T=Tcool, outUnits='Energy') * fc_fh
    composite = Bhot + Bint + Bcool
    composite /= composite[bm]
    return scipy.interpolate.interp1d(wave * 10000.0, composite)
Ejemplo n.º 3
0
def calculateCM(SynthObj, solarWl, rebinnedSpectrum, nominalWave,
                nominalSpectrum):
    IM = numpy.zeros((SynthObj.lineList.numLines + 2, len(solarWl)))
    for i in range(SynthObj.lineList.numLines):
        SynthObj.lineList.perturbLine(i, 0.3)
        wave, flux = SynthObj.run()
        plus = SpectralTools.binSpectrum(flux, wave, solarWl)
        SynthObj.lineList.perturbLine(i, -0.3)
        wave, flux = SynthObj.run()
        minus = SpectralTools.binSpectrum(flux, wave, solarWl)
        IM[i, :] = (plus - minus) / 0.6

    #Continuum Level
    plus = rebinnedSpectrum.copy() + 0.005
    minus = rebinnedSpectrum.copy() - 0.005
    IM[-1, :] = (plus - minus) / 0.01

    plus = SpectralTools.binSpectrum(nominalSpectrum, nominalWave + 0.1,
                                     solarWl)
    minus = SpectralTools.binSpectrum(nominalSpectrum, nominalWave - 0.1,
                                      solarWl)
    edges = (plus != 0) & (minus != 0)
    IM[-2, edges] = (plus[edges] - minus[edges]) / (0.2)

    nFilt = Synth.lineList.numLines - 10
    dims = IM.shape
    U, S, V = scipy.linalg.svd(IM)
    D = 1.0 / (S[0:-nFilt])
    S[-nFilt:] = 0.0
    newS = numpy.zeros((dims[0], dims[1]))
    I = [i for i in range(dims[1])]
    for i in range(len(D)):
        newS[i][i] = D[i]

    S = newS.copy()
    CM = numpy.array(scipy.matrix(V.T.dot(S.T.dot(U.T)),
                                  dtype=numpy.float32)).T

    hdu = pyfits.PrimaryHDU(CM)
    hdu.writeto('CommandMatrix_new.fits', clobber=True)
Ejemplo n.º 4
0
def calculateCM(SynthObj, solarWl, rebinnedSpectrum, nominalWave, nominalSpectrum):
    IM = numpy.zeros((SynthObj.lineList.numLines+2, len(solarWl)))
    for i in range(SynthObj.lineList.numLines):
        SynthObj.lineList.perturbLine(i, 0.3)
        wave, flux = SynthObj.run()
        plus = SpectralTools.binSpectrum(flux, wave, solarWl)
        SynthObj.lineList.perturbLine(i, -0.3)
        wave, flux = SynthObj.run()
        minus = SpectralTools.binSpectrum(flux, wave, solarWl)
        IM[i,:] = (plus - minus)/0.6

    #Continuum Level
    plus = rebinnedSpectrum.copy()+ 0.005
    minus = rebinnedSpectrum.copy()- 0.005
    IM[-1, :] = (plus-minus)/0.01

    plus = SpectralTools.binSpectrum(nominalSpectrum, nominalWave+0.1, solarWl)
    minus = SpectralTools.binSpectrum(nominalSpectrum, nominalWave-0.1, solarWl)
    edges = (plus !=0) & (minus != 0)
    IM[-2, edges] = (plus[edges]-minus[edges])/(0.2)

    nFilt = Synth.lineList.numLines-10
    dims = IM.shape
    U,S,V = scipy.linalg.svd(IM)
    D = 1.0/(S[0:-nFilt])
    S[-nFilt:] = 0.0
    newS = numpy.zeros((dims[0], dims[1]))
    I = [i for i in range(dims[1])]
    for i in range(len(D)):
        newS[i][i] = D[i]

    S = newS.copy()
    CM = numpy.array(scipy.matrix(V.T.dot(S.T.dot(U.T)),dtype=numpy.float32)).T

    hdu = pyfits.PrimaryHDU(CM)
    hdu.writeto('CommandMatrix_new.fits', clobber=True)
Ejemplo n.º 5
0
 def loadSpectra(self):
     self.wave = []
     self.flux = []
     for i, good in zip(range(self.nSpectra), self.inWlRange):
         if good:
             data = pyfits.getdata(self.datafile, ext=i+1)
             if self.resolvingPower != None:
                 wave, flux = SpectralTools.resample(data.field('Wavelength'), 
                     data.field('Stokes_I'), self.resolvingPower)
                 self.wave.append(wave)
                 self.flux.append(flux)
             else:
                 self.wave.append(data.field('Wavelength'))
                 self.flux.append(data.field('Stokes_I'))
         else:
             self.wave.append([])
             self.flux.append([])
     #self.wave, self.flux = SpectralTools.resample(data[0], data[1], 
     #        self.resolvingPower)
     self.wave = numpy.array(self.wave)
     self.flux = numpy.array(self.flux)
Ejemplo n.º 6
0
def calculateCM(SynthObj, nominalWave, nominalSpectrum):
    solarWl = SynthObj.solarSpectrum.wave
    solarFl = SynthObj.solarSpectrum.flux
    resolution = 45000.0
    nLines = SynthObj.lineList.numLines
    nModes = 2 * nLines + 3
    nFilt = nLines

    IM = numpy.zeros((nModes, len(solarWl)))

    stroke = numpy.ones(nModes)
    factor = numpy.ones(nModes)
    stroke[-1] = 0.005  # Continuum Shift
    stroke[-2] = 0.1  # WL Shift
    stroke[-3] = 0.01  # Smoothing
    for i in range(nLines):
        SynthObj.lineList.writeLineLists(i)
        wave, flux = SynthObj.run()
        stroke[i] = SynthObj.lineList.getGf(i) / 5.0
        stroke[i + nLines] = 0.1
        """
        while ((factor[i] < 0.9) | (factor[i] > 1.1)):
            stroke[i] *= factor[i]
            SynthObj.lineList.perturbGf(i, stroke[i])
            SynthObj.lineList.writeLineLists(i,partial=True)
            wave, plus = SynthObj.run()
            wave, plus = SpectralTools.resample(wave, plus, resolution)
            SynthObj.lineList.perturbGf(i, -2.0*stroke[i])
            SynthObj.lineList.writeLineLists(i,partial=True)
            wave, minus = SynthObj.run()
            wave, minus = SpectralTools.resample(wave, minus, resolution)
            SynthObj.lineList.perturbGf(i, stroke[i])
            factor[i] = numpy.abs(target[i]/(numpy.min(plus)-numpy.min(minus)))
            print factor[i]
            raw_input()
        #"""

    for i in range(nLines):
        #  log gf
        SynthObj.lineList.perturbGf(i, stroke[i])
        SynthObj.lineList.writeLineLists(i)
        wave, plus = SynthObj.run()
        newWave, plus = SpectralTools.resample(wave, plus, resolution)
        SynthObj.lineList.perturbGf(i, -2.0 * stroke[i])
        SynthObj.lineList.writeLineLists(i)
        wave, minus = SynthObj.run()
        newWave, minus = SpectralTools.resample(wave, minus, resolution)
        SynthObj.lineList.perturbGf(i, stroke[i])
        IM[i, :] = SpectralTools.interpolate_spectrum(newWave,
                                                      solarWl, (plus - minus) /
                                                      (2.0 * stroke[i]),
                                                      pad=0.0)
        factor[i] = numpy.max(numpy.abs(IM[i, :]))
        IM[i, :] /= factor[i]

        # damping
        SynthObj.lineList.perturbVdW(i, stroke[i + nLines])
        SynthObj.lineList.writeLineLists(i)
        wave, plus = SynthObj.run()
        newWave, plus = SpectralTools.resample(wave, plus, resolution)
        SynthObj.lineList.perturbVdW(i, -2.0 * stroke[i + nLines])
        SynthObj.lineList.writeLineLists(i)
        wave, minus = SynthObj.run()
        newWave, minus = SpectralTools.resample(wave, minus, resolution)
        SynthObj.lineList.perturbVdW(i, stroke[i + nLines])
        IM[i + nLines, :] = SpectralTools.interpolate_spectrum(
            newWave,
            solarWl, (plus - minus) / (2.0 * stroke[i + nLines]),
            pad=0.0)
        factor[i + nLines] = numpy.max(numpy.abs(IM[i + nLines, :]))
        IM[i + nLines, :] /= factor[i + nLines]

    #Continuum Level
    plus = nominalSpectrum + stroke[-1]
    newWave, plus = SpectralTools.resample(nominalWave, plus, resolution)
    minus = nominalSpectrum - stroke[-1]
    newWave, minus = SpectralTools.resample(nominalWave, minus, resolution)

    IM[-1, :] = SpectralTools.interpolate_spectrum(newWave,
                                                   solarWl, (plus - minus) /
                                                   (2.0 * stroke[-1]),
                                                   pad=0.0)
    factor[-1] = numpy.max(numpy.abs(IM[-1, :]))
    IM[-1, :] /= factor[-1]

    #Wavelength Shift
    plus = SpectralTools.interpolate_spectrum(wave,
                                              wave - stroke[-2],
                                              nominalSpectrum,
                                              pad=True)
    newWave, plus = SpectralTools.resample(wave, plus, resolution)
    minus = SpectralTools.interpolate_spectrum(wave,
                                               wave + stroke[-2],
                                               nominalSpectrum,
                                               pad=True)
    newWave, minus = SpectralTools.resample(wave, minus, resolution)
    IM[-2, :] = SpectralTools.interpolate_spectrum(newWave,
                                                   solarWl, (plus - minus) /
                                                   (2.0 * stroke[-2]),
                                                   pad=0.0)
    factor[-2] = numpy.max(numpy.abs(IM[-2, :]))
    IM[-2, :] /= factor[-2]

    #"""
    #Instrumental Smoothing
    wavePlus, plus = SpectralTools.resample(wave, nominalSpectrum,
                                            resolution * (1.0 + stroke[-3]))
    waveMinus, minus = SpectralTools.resample(wave, nominalSpectrum,
                                              resolution * (1.0 - stroke[-3]))
    diffx, diffy = SpectralTools.diff_spectra(wavePlus,
                                              plus,
                                              waveMinus,
                                              minus,
                                              pad=True)
    IM[-3, :] = SpectralTools.interpolate_spectrum(diffx,
                                                   solarWl,
                                                   diffy / (2.0 * stroke[-3]),
                                                   pad=0.0)
    factor[-3] = numpy.max(numpy.abs(IM[-3, :]))
    IM[-3, :] /= factor[-3]
    #"""

    hdu = pyfits.PrimaryHDU(IM)
    hdu.writeto("InteractionMatrix.fits", clobber=True)
    #nFilt = Synth.lineList.numLines-2
    dims = IM.shape
    U, S, V = scipy.linalg.svd(IM)
    D = 1.0 / S
    #D = 1.0/(S[0:-nFilt])
    #S[-nFilt:] = 0.0
    newS = numpy.zeros((dims[0], dims[1]))
    I = [i for i in range(dims[1])]
    for i in range(len(D)):
        newS[i][i] = D[i]

    S = newS.copy()
    CM = numpy.array(scipy.matrix(V.T.dot(S.T.dot(U.T)),
                                  dtype=numpy.float32)).T

    fig = pyplot.figure(0)
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    ax.plot(S)

    hdu = pyfits.PrimaryHDU(CM)
    hdu.writeto('CommandMatrix.fits', clobber=True)
    hdu = pyfits.PrimaryHDU(factor)
    hdu.writeto('scalingfactor.fits', clobber=True)
Ejemplo n.º 7
0
diffplot = False

Synth = MoogTools.Moog(configFile)
Synth.lineList.writeLineLists()
Synth.parameterFile.writeParFile()

solarWave = Synth.solarSpectrum.wave + 0.1
solarFlux = Synth.solarSpectrum.flux + 0.001 + numpy.random.randn(
    len(solarWave)) * 0.001

continuum = 0.0
wlOffset = 0.0
resolution = 45000

nominalWavelength, nominalSpectrum = Synth.run()
wave, spectrum = SpectralTools.resample(nominalWavelength, nominalSpectrum,
                                        resolution)

if True:
    calculateCM(Synth, nominalWavelength, nominalSpectrum)

CM = pyfits.getdata("CommandMatrix.fits")
factor = pyfits.getdata("scalingfactor.fits")

f1 = pyplot.figure(0)
f1.clear()
ax1 = f1.add_axes([0.1, 0.1, 0.8, 0.8])

cb = ax1.matshow(CM, aspect='auto')
blah = pyplot.colorbar(cb)
f1.show()
def main(fname, binsize=5, interactive_mode=False, bin_range=None, limits=None, plot=False):
    # load the fits file 
    data = fits.getdata(fname)
    hdr = fits.getheader(fname)

    try:
        # Gasgano reduction
        I = data["Extracted_OPT"]
        I = np.array(I, dtype="float64")
    except:
        # Dracs reduction
        try:
            I = data["Extracted_DRACS"]
            print(type(I))
            I = np.array(I, dtype="float64")
            print(type(I))
        except:
            I = data
    try:
        wl = data["Wavelength"]
        xscale = "nm"
    except:
        # no wavelength values so use pixel positions
        wl = range(len(I))
        xscale = "pixel"
        
    if interactive_mode:
        # do interactve mode stuff
        pass

    elif limits: 
        limited_wl, limited_flux = s_tools.fast_wav_selector(wl, I, limits[0], limits[1])
        limit_snr = snr(limited_flux)
        print("SNR of the spectra between the given limits {0}-{1} is {2}".format(limits[0], limits[1], limit_snr))
        if plot:
            simple_plot(wl, I, label="Spectra", xscale=xscale)

    else:
        # Default to scan mode

        binsize = int(binsize)
       
        snr_list = snrscan(I, binsize)
        print("snr list", snr_list)
        # Try using stride on np.array
        plt.hist(snr_list)
        plt.show()
        # striding
        if bin_range:

            bins = np.arange(bin_range[0], bin_range[1], bin_range[2])  # TODO ability for less than 3 args?
            hopper = 1
            print("itemsize", I.itemsize, "dtype", I.dtype)
            store_list = []
            for i, b in enumerate(bins):
                store_list.append(strided_snr(I, b, hop_length=hopper))
            
            # pandas dataframe (not nessesary)
            df_list = pd.DataFrame(store_list, index=bins, columns=np.round(wl,2))
            # ploting heatmap
            plt.subplot(221)
            plt.plot(wl, I, label="spectra")
            plt.ylabel("Flux")
            plt.xlabel("Wavelength")
            plt.title("Spectra of {0}".format(fname))
            plt.subplot(212)
            sns.set()
            cmap = sns.diverging_palette(220, 10, as_cmap=True)
            #ax = sns.heatmap(store_list, cmap=cmap, xticklabels=200, vmax=300, vmin=10)
            ax = sns.heatmap(df_list, cmap=cmap, xticklabels=200, vmax=300, vmin=0)
            #ax = sns.heatmap(df_list)
            #plt.xticks(np.arange(int(np.min(wl)), int(np.max(wl)+1), 1.0))
            ax.set(ylabel="Binsize", xlabel="Wavelength")
            plt.title("SNR")
            
            plt.show()
Ejemplo n.º 9
0
import numpy

configFile = sys.argv[1]

config = AstroUtils.parse_config(configFile)

watched_dir = config['watched_dir']
wlStart = config['wlStart']
wlStop = config['wlStop']

parameters = {}
parameters["TEFF"] = []
parameters["LOGG"] = []
parameters["BFIELD"] = []

parameters, waves, fluxes = SpectralTools.winnow_MoogStokes_Spectra(watched_dir, wlStart, wlStop, trackedParams=parameters)
EWs = []

teff = numpy.array(parameters["TEFF"])
logg = numpy.array(parameters["LOGG"])
bfield = numpy.array(parameters["BFIELD"])

temps = numpy.unique(teff)
gravs = numpy.unique(logg)
bs = numpy.unique(bfield)

for w, f in zip(waves, fluxes):
    EWs.append(SpectralTools.calc_EW(w, f, wlStart, wlStop))

EWs = numpy.array(EWs)
fig = pyplot.figure(0)
Ejemplo n.º 10
0
    Name = dataheader.get('OBJECT')
    headerKWs['OBJECT'] = Name
    headerKWs["DATE-OBS"] = dataheader.get('DATE-OBS')
    headerKWs["INSTRUMENT"] = dataheader.get('INSTRUME')
    headerKWs["OBSERVER"] = dataheader.get('OBSERVER')
    headerKWs["EXPTIME"] = dataheader.get('EXPTIME')
    Score = Moog960.Score()
    Melody = Moog960.ObservedMelody(Score=Score, name=Name)
    for wl, I, sn, v in zip(wlsol, data, snr, var):

        header = pyfits.Header()
        header.set('NAME', Name)
        header.set("WLSTART", numpy.min(wl))
        header.set("WLSTOP", numpy.max(wl))

        Melody.addPhrase(Moog960.ObservedPhrase(observedData=[SpectralTools.Spectrum(wl=wl, 
            I=I, dI=I/sn, header=header, spectrum_type="OBSERVED")], Melody=Melody))

        ID = Melody.phrases[-1].ID
        parameters = {}
        parameters["PHRASE"] = ID
        parameters["MELODY"] = Melody.ID
        parameters["SCORE"] = Melody.Score.ID
        parameters["WLSTART"] = header.get('WLSTART')
        parameters["WLSTOP"] = header.get('WLSTOP')
        parameters["SELECTED"] = False
        if not(Melody.ID in Melody.Score.observed_labels.keys()):
            Melody.Score.observed_labels[Melody.ID] = {}
        Melody.Score.observed_labels[Melody.ID][ID] = []

        Melody.Score.observed_labels[Melody.ID][ID].append(Moog960.Label(parameters,
                  reference=Melody.phrases[-1].observedData[-1], Phrase=Melody.phrases[-1],
Ejemplo n.º 11
0
    edges = (plus != 0) & (minus != 0)
    IM[-2, edges] = (plus[edges] - minus[edges]) / (0.2)

    nFilt = Synth.lineList.numLines - 10
    dims = IM.shape
    U, S, V = scipy.linalg.svd(IM)
    D = 1.0 / (S[0:-nFilt])
    S[-nFilt:] = 0.0
    newS = numpy.zeros((dims[0], dims[1]))
    I = [i for i in range(dims[1])]
    for i in range(len(D)):
        newS[i][i] = D[i]

    S = newS.copy()
    CM = numpy.array(scipy.matrix(V.T.dot(S.T.dot(U.T)),
                                  dtype=numpy.float32)).T

    hdu = pyfits.PrimaryHDU(CM)
    hdu.writeto('CommandMatrix_new.fits', clobber=True)


configFile = 'CMTeacher.cfg'

Synth = MoogTools.Moog(configFile)
Synth.lineList.writeLineLists()
Synth.parameterFile.writeParFile()

wavelengths, nominalSpectrum = Synth.run()
newWave, newFlux = SpectralTools.resample(wavelengths, nominalSpectrum, 40000)
SpectralTools.write_2col_spectrum("observed.dat", newWave, newFlux)
Ejemplo n.º 12
0
    edges = (plus !=0) & (minus != 0)
    IM[-2, edges] = (plus[edges]-minus[edges])/(0.2)

    nFilt = Synth.lineList.numLines-10
    dims = IM.shape
    U,S,V = scipy.linalg.svd(IM)
    D = 1.0/(S[0:-nFilt])
    S[-nFilt:] = 0.0
    newS = numpy.zeros((dims[0], dims[1]))
    I = [i for i in range(dims[1])]
    for i in range(len(D)):
        newS[i][i] = D[i]

    S = newS.copy()
    CM = numpy.array(scipy.matrix(V.T.dot(S.T.dot(U.T)),dtype=numpy.float32)).T

    hdu = pyfits.PrimaryHDU(CM)
    hdu.writeto('CommandMatrix_new.fits', clobber=True)



configFile = 'CMTeacher.cfg'

Synth = MoogTools.Moog(configFile)
Synth.lineList.writeLineLists()
Synth.parameterFile.writeParFile()

wavelengths, nominalSpectrum = Synth.run()
newWave, newFlux = SpectralTools.resample(wavelengths, nominalSpectrum, 40000)
SpectralTools.write_2col_spectrum("observed.dat", newWave, newFlux)
Ejemplo n.º 13
0
        continuum *= float(raw_input("Enter multiplicative continuum factor : "))
    elif choice == 'v':
        veiling = float(raw_input("Enter new Veiling :"))
    elif choice == 's':
        outfile = raw_input("Enter the name of the file you wish to save")
        fig.savefig(outfile)
    Ensemble = Orchestra.getEnsemble()
    ax1.clear()
    ax2.clear()
    wave = Orchestra.observed.wave+wlOffset
    flux = Orchestra.observed.flux*continuum
    ax1.plot(wave, flux, label='TW Hydra')
    ax2.plot([Orchestra.wlStart, Orchestra.wlStop], [0.0, 0.0])

    for spectra, l in zip(Ensemble[0], Ensemble[1]):
        newSpec = (SpectralTools.binSpectrum(spectra[1], spectra[0], wave)+veiling)/(1.0+veiling)
        difference = flux - newSpec

        ax1.plot(wave, newSpec, label=l)
        ax2.plot(wave, difference)

    ax1.set_xbound(lower = Orchestra.wlStart, upper=Orchestra.wlStop)
    ax1.set_ybound(lower = 0.0, upper = 1.5)
    ax2.set_xbound(lower = Orchestra.wlStart, upper=Orchestra.wlStop)
    ax2.set_ybound(lower = -0.15, upper = 0.15)
    ax1.set_xticklabels([])
    params = ax1.text(0.1, 0.8, "wlShift = %.1f A\nContinuum Scaling = %.2f\nVeiling = %.2f"
            % (wlOffset, continuum, veiling), transform = ax1.transAxes, fontsize=19.0)

    ax1.legend(loc=3)
    fig.show()
Ejemplo n.º 14
0
def calculateCM(SynthObj, nominalWave, nominalSpectrum):
    solarWl = SynthObj.solarSpectrum.wave
    solarFl = SynthObj.solarSpectrum.flux
    resolution = 45000.0
    nLines = SynthObj.lineList.numLines
    nModes = 2*nLines+3
    nFilt = nLines

    IM = numpy.zeros((nModes, len(solarWl)))

    stroke = numpy.ones(nModes)
    factor = numpy.ones(nModes)
    stroke[-1] = 0.005                  # Continuum Shift
    stroke[-2] = 0.1                    # WL Shift
    stroke[-3] = 0.01                # Smoothing
    for i in range(nLines):
        SynthObj.lineList.writeLineLists(i)
        wave, flux = SynthObj.run()
        stroke[i] = SynthObj.lineList.getGf(i)/5.0
        stroke[i+nLines] = 0.1
        """
        while ((factor[i] < 0.9) | (factor[i] > 1.1)):
            stroke[i] *= factor[i]
            SynthObj.lineList.perturbGf(i, stroke[i])
            SynthObj.lineList.writeLineLists(i,partial=True)
            wave, plus = SynthObj.run()
            wave, plus = SpectralTools.resample(wave, plus, resolution)
            SynthObj.lineList.perturbGf(i, -2.0*stroke[i])
            SynthObj.lineList.writeLineLists(i,partial=True)
            wave, minus = SynthObj.run()
            wave, minus = SpectralTools.resample(wave, minus, resolution)
            SynthObj.lineList.perturbGf(i, stroke[i])
            factor[i] = numpy.abs(target[i]/(numpy.min(plus)-numpy.min(minus)))
            print factor[i]
            raw_input()
        #"""

    for i in range(nLines):
        #  log gf
        SynthObj.lineList.perturbGf(i, stroke[i])
        SynthObj.lineList.writeLineLists(i)
        wave, plus = SynthObj.run()
        newWave, plus = SpectralTools.resample(wave, plus, resolution)
        SynthObj.lineList.perturbGf(i, -2.0*stroke[i])
        SynthObj.lineList.writeLineLists(i)
        wave, minus = SynthObj.run()
        newWave, minus = SpectralTools.resample(wave, minus, resolution)
        SynthObj.lineList.perturbGf(i, stroke[i])
        IM[i,:] = SpectralTools.interpolate_spectrum(newWave, solarWl,
                        (plus - minus)/(2.0*stroke[i]), pad=0.0)
        factor[i] = numpy.max(numpy.abs(IM[i,:]))
        IM[i,:] /= factor[i]

        # damping
        SynthObj.lineList.perturbVdW(i, stroke[i+nLines])
        SynthObj.lineList.writeLineLists(i)
        wave, plus = SynthObj.run()
        newWave, plus = SpectralTools.resample(wave, plus, resolution)
        SynthObj.lineList.perturbVdW(i, -2.0*stroke[i+nLines])
        SynthObj.lineList.writeLineLists(i)
        wave, minus = SynthObj.run()
        newWave, minus = SpectralTools.resample(wave, minus, resolution)
        SynthObj.lineList.perturbVdW(i, stroke[i+nLines])
        IM[i+nLines,:] = SpectralTools.interpolate_spectrum(newWave, solarWl,
                        (plus-minus)/(2.0*stroke[i+nLines]), pad=0.0)
        factor[i+nLines] = numpy.max(numpy.abs(IM[i+nLines,:]))
        IM[i+nLines,:] /= factor[i+nLines]



    #Continuum Level
    plus = nominalSpectrum + stroke[-1]
    newWave, plus = SpectralTools.resample(nominalWave, plus, resolution)
    minus = nominalSpectrum - stroke[-1]
    newWave, minus = SpectralTools.resample(nominalWave, minus, resolution)

    IM[-1, :] = SpectralTools.interpolate_spectrum(newWave, solarWl, 
        (plus-minus)/(2.0*stroke[-1]), pad=0.0)
    factor[-1] = numpy.max(numpy.abs(IM[-1,:]))
    IM[-1,:] /= factor[-1]

    #Wavelength Shift
    plus = SpectralTools.interpolate_spectrum(wave, wave-stroke[-2], nominalSpectrum,
            pad=True)
    newWave, plus = SpectralTools.resample(wave, plus, resolution)
    minus = SpectralTools.interpolate_spectrum(wave, wave+stroke[-2], nominalSpectrum,
            pad=True)
    newWave, minus = SpectralTools.resample(wave, minus, resolution)
    IM[-2, :] = SpectralTools.interpolate_spectrum(newWave, solarWl, 
                (plus-minus)/(2.0*stroke[-2]), pad=0.0)
    factor[-2] = numpy.max(numpy.abs(IM[-2,:]))
    IM[-2,:] /= factor[-2]

    #"""
    #Instrumental Smoothing
    wavePlus, plus = SpectralTools.resample(wave, nominalSpectrum, resolution*(1.0+stroke[-3]))
    waveMinus, minus = SpectralTools.resample(wave, nominalSpectrum, resolution*(1.0-stroke[-3]))
    diffx, diffy = SpectralTools.diff_spectra(wavePlus, plus, waveMinus, minus, pad=True)
    IM[-3,:] = SpectralTools.interpolate_spectrum(diffx, solarWl, diffy/(2.0*stroke[-3]), pad=0.0)
    factor[-3] = numpy.max(numpy.abs(IM[-3,:]))
    IM[-3,:] /= factor[-3]
    #"""


    hdu = pyfits.PrimaryHDU(IM)
    hdu.writeto("InteractionMatrix.fits", clobber=True)
    #nFilt = Synth.lineList.numLines-2
    dims = IM.shape
    U,S,V = scipy.linalg.svd(IM)
    D = 1.0/S
    #D = 1.0/(S[0:-nFilt])
    #S[-nFilt:] = 0.0
    newS = numpy.zeros((dims[0], dims[1]))
    I = [i for i in range(dims[1])]
    for i in range(len(D)):
        newS[i][i] = D[i]

    S = newS.copy()
    CM = numpy.array(scipy.matrix(V.T.dot(S.T.dot(U.T)),dtype=numpy.float32)).T

    fig = pyplot.figure(0)
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    ax.plot(S)

    hdu = pyfits.PrimaryHDU(CM)
    hdu.writeto('CommandMatrix.fits', clobber=True)
    hdu = pyfits.PrimaryHDU(factor)
    hdu.writeto('scalingfactor.fits', clobber=True)
Ejemplo n.º 15
0
diffplot = False

Synth = MoogTools.Moog(configFile)
Synth.lineList.writeLineLists()
Synth.parameterFile.writeParFile()

solarWave = Synth.solarSpectrum.wave+0.1
solarFlux = Synth.solarSpectrum.flux+0.001+ numpy.random.randn(len(solarWave))*0.001

continuum = 0.0
wlOffset = 0.0
resolution = 45000


nominalWavelength, nominalSpectrum = Synth.run()
wave, spectrum = SpectralTools.resample(nominalWavelength, nominalSpectrum, resolution)

if True:
    calculateCM(Synth, nominalWavelength, nominalSpectrum)

CM = pyfits.getdata("CommandMatrix.fits")
factor = pyfits.getdata("scalingfactor.fits")


f1 = pyplot.figure(0)
f1.clear()
ax1 = f1.add_axes([0.1, 0.1, 0.8, 0.8])

cb = ax1.matshow(CM, aspect='auto')
blah = pyplot.colorbar(cb)
f1.show()
Ejemplo n.º 16
0
    headerKWs["OBSERVER"] = dataheader.get('OBSERVER')
    headerKWs["EXPTIME"] = dataheader.get('EXPTIME')
    Score = Moog960.Score()
    Melody = Moog960.ObservedMelody(Score=Score, name=Name)
    for wl, I, sn, v in zip(wlsol, data, snr, var):

        header = pyfits.Header()
        header.set('NAME', Name)
        header.set("WLSTART", numpy.min(wl))
        header.set("WLSTOP", numpy.max(wl))

        Melody.addPhrase(
            Moog960.ObservedPhrase(observedData=[
                SpectralTools.Spectrum(wl=wl,
                                       I=I,
                                       dI=I / sn,
                                       header=header,
                                       spectrum_type="OBSERVED")
            ],
                                   Melody=Melody))

        ID = Melody.phrases[-1].ID
        parameters = {}
        parameters["PHRASE"] = ID
        parameters["MELODY"] = Melody.ID
        parameters["SCORE"] = Melody.Score.ID
        parameters["WLSTART"] = header.get('WLSTART')
        parameters["WLSTOP"] = header.get('WLSTOP')
        parameters["SELECTED"] = False
        if not (Melody.ID in Melody.Score.observed_labels.keys()):
            Melody.Score.observed_labels[Melody.ID] = {}