def crystalFit(spec: Spectrum, crystal: str, index: int, fname: str): specificPars = crystalFitParameters[crystal][index] spec.setBaseLinePars(specificPars["m"], specificPars["b"]) for i in range(len(specificPars["mu"])): spec.addGaussianParameters(specificPars["A"][i], specificPars["mu"][i], specificPars["sig"][i]) customizeGraph() return spec.fitData(specificPars["range"][0], specificPars["range"][1], fname)
def ExtractSpectrum(self, mask3D): extractedspectrum = Spectrum.CLSpectrum(np.mean(np.mean( np.ma.masked_array(self.data, mask3D), axis=0), axis=0), self.SpectrumRange, units=self.spectrum_units) return extractedspectrum
def testSymmetrizeAroundZLPnegativevalues(self): #Spectrum contains negative values data = np.array([1, -1, 1, 1, 20, 35, 20, 1, -1, -1, 1]) eels = Spectrum.EELSSpectrum(data, dispersion=0.2, ZLP=True) eels_sym = eels.SymmetrizeAroundZLP() data_positive = np.array([1, 0, 1, 1, 20, 35, 20, 1, 0, 0, 1]) self.assertArraysEqual(data_positive, eels_sym.intensity)
def ImportVis(self, wavelengths): filename = '/home/isobel/Documents/McMaster/CL/SystemResponseFcns/SystemResponseVISInterpolated_20150717.csv' dataDict = ReadCSVRef(filename) d = dataDict[(self.grating,)] spectrum_interp = np.interp(wavelengths, d[:, 0], d[:, 1]) correction_spectrum = Spectrum.CLSpectrum(spectrum_interp, wavelengths) return correction_spectrum
def testPadSpectrumright(self): #Pad the right side of the spectrum with 0s data = np.array([1, 1, 1, 1, 20, 35, 20, 1, 1, 1, 1]) data_pad = np.array([1, 1, 1, 1, 20, 35, 20, 1, 1, 1, 1, 0, 0, 0]) eels = Spectrum.EELSSpectrum(data, dispersion=0.2, ZLP=True) eels_pad = eels.PadSpectrum(3, pad_value=0, pad_side='right') self.assertArraysEqual(eels_pad.intensity, data_pad)
def ExtractSpectrum(self, mask3D): extractedspectrum = Spectrum.EELSSpectrum(np.sum(np.sum( np.ma.masked_array(self.data, mask3D), axis=0), axis=0), dispersion=self.dispersion, units=self.spectrum_units) return extractedspectrum
def test_imagesolution(): # load the image and determine its spectrograph parameters hdu = pyfits.open(inimage) # create the data arra data = hdu[1].data # create the header information instrume = hdu[1].header['INSTRUME'].strip() grating = hdu[1].header['GRATING'].strip() grang = hdu[1].header['GR-ANGLE'] arang = hdu[1].header['AR-ANGLE'] filter = hdu[1].header['FILTER'].strip() slit = float(hdu[1].header['MASKID']) xbin, ybin = hdu[1].header['CCDSUM'].strip().split() print instrume, grating, grang, arang, filter print xbin, ybin # create the RSS Model rssmodel = RSSModel.RSSModel(grating_name=grating, gratang=grang, camang=arang, slit=slit, xbin=int(xbin), ybin=int(ybin)) # create the spectrum stype = 'line' w, s = np.loadtxt(inspectra, usecols=(0, 1), unpack=True) spec = Spectrum.Spectrum(w, s, wrange=[4000, 5000], dw=0.1, stype='line') # Now having the model and the data, set up the variables imsol = ImageSolution(data, rssmodel.rss, spec)
def testSymmetrizeAroundZLPright(self): #ZLP is in the right half of the spectrum data = np.array([1, 1, 1, 1, 1, 1, 1, 20, 35, 20, 1]) eels = Spectrum.EELSSpectrum(data, dispersion=0.2, ZLP=True) eels_sym = eels.SymmetrizeAroundZLP() data_sym = np.array([1, 20, 35, 20, 1]) self.assertArraysEqual(eels_sym.intensity, data_sym)
def testNormalize(self): #Test normalization to integrated intensity data = np.array([1, 20, 35, 20, 1, 1, 1, 1, 1, 1, 1]) eels = Spectrum.EELSSpectrum(data, dispersion=0.2, ZLP=True) eels_norm = eels.Normalize() data_norm = data / 83. self.assertArraysEqual(data_norm, eels_norm.intensity)
def testPadSpectrumRangeleft(self): #Pad the left side of the spectrum with 0s data = np.array([1, 1, 1, 1, 20, 35, 20, 1, 1, 1, 1]) s_range = np.array( [-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]) data_pad = np.array([0, 0, 0, 1, 1, 1, 1, 20, 35, 20, 1, 1, 1, 1]) s_range_pad = np.array([ -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, ]) eels = Spectrum.EELSSpectrum(data, SpectrumRange=s_range) eels_pad = eels.PadSpectrum(3, pad_value=0, pad_side='left') self.assertTrue(np.allclose(eels_pad.SpectrumRange, s_range_pad))
def testeVSliceDispersionIrrational(self): data = np.array([35, 20, 1, 28, 3, 5, 4, 7, 9, 15]) Srange = np.linspace(10, 15, num=10) eels = Spectrum.EELSSpectrum(data, SpectrumRange=Srange) sliced = eels.eVSlice(11, 13) print(Srange) self.assertArraysEqual(np.array([1, 28, 3, 5]), sliced)
def process_file(self, filename, num_channels, stimLength, baseline, prestim_baseline): stimCodes = [i + 1 for i in range(num_channels)] signalChannel = self.fileData[filename][0] # timingChannel = f.data[3] codeChannels = { 4 + i: self.fileData[filename][4 + i] for i in range(num_channels) } d = SRP.SRPdecoder() d.baseline = baseline d.stimLength = stimLength d.prestim_baseline = prestim_baseline self.prestim_baseline = prestim_baseline timeCodes = d.GetCodeList(signalChannel, codeChannels) stimTimeStamps = { code: d.GetTimeStamps(code, timeCodes) for code in stimCodes } stimLengths = { code: d.GetStimLengths(stimTimeStamps[code]) for code in stimTimeStamps } avgLength = d.AvgStimLength(stimTimeStamps) stimsPerSession = d.StimsPerSession(stimLengths, avgLength) stims = d.GetStimLists(signalChannel, stimsPerSession, avgLength, stimTimeStamps) stim_avgs = { code: d.GetAverages(stims[code], stimsPerSession) for code in stims } spectral_avgs = { code: sp.getSpectrumAvg(stims[code], stimsPerSession) for code in stims } orient_avgs = dict() for key in stim_avgs: if int(key) % 2 != 0: orient_avgs[key] = d.CombineAvgs(stim_avgs, key, key + 1) self.raw_stims[filename] = stims self.stimTimeStamps[filename] = stimTimeStamps self.timeCodes[filename] = timeCodes self.stimLengths[filename] = stimLengths self.stim_avgs[filename] = stim_avgs self.orient_avgs[filename] = orient_avgs self.total_avgs[filename] = self.get_grand_avgs(stim_avgs) self.grand_avgs[filename] = self.get_grand_avgs(orient_avgs) self.spectral_data[filename] = spectral_avgs
def __plotDataExample__(): # crystalFileNames[currentCrystal] data = getTxtFileArray( "SPEC\\2D\\2D data files\\05-NaCl1-4ordema-01-25s.txt", 0, True) spec = Spectrum.Spectrum(data) cpars = crystalFitParameters[currentCrystal][index] customizeGraph() spec.plotData()
def Initialize(self, dmeson, jtype, jradius, jtitle, reflections, inputPath): self.fName = "_".join(obj for obj in [dmeson, jtype, jradius, self.fBinSetName] if not obj == None) jetDep = self.AmIJetDependent() if jtype or jradius: if not jetDep: return False else: if jetDep: return False if jtype == "Full": for a in self.fAxis: a.fChargedJet = False if jtype and jradius: jetName = "Jet_AKT{0}{1}_pt_scheme".format(jtype, jradius) else: # This is a temporary hack. The detector response analysis does not have an option for "no jet" jetName = "Jet_AKTChargedR040_pt_scheme" if "MCTruth" in dmeson: self.fWeightEfficiency = DetectorResponseLoader.DMesonJetEfficiency(None) else: self.fWeightEfficiency = self.LoadEfficiency(inputPath, dmeson, jetName, self.fEfficiency, None) for s in self.fSpectraConfigs: # skip spectra that do not have this D meson active if not dmeson in s["active_mesons"]: continue # add bin counting axis if "axis" in s: if len(s["axis"]) > 2: print("Error: cannot do bin counting spectra (e.g. side band) with more than 2 axis. Spectrum {}".format(s["name"])) exit(1) bin_count_spectra = [] axis_name = s["axis"].keys()[0] axis_bins = s["axis"].values()[0] bcaxis = Axis.Axis(axis_name, axis_bins, "", (jtype != "Full")) bin_count_spectra.append(bcaxis) self.fBinCountSpectraAxis[s["name"]] = bin_count_spectra # configure efficiency if "efficiency" in s and not "MCTruth" in dmeson: effWeight = self.LoadEfficiency(inputPath, dmeson, jetName, s["efficiency"], self.fAxis[0]) else: effWeight = DetectorResponseLoader.DMesonJetEfficiency(None) spectrum = Spectrum.Spectrum(s, dmeson, jtype, jradius, jtitle, self, effWeight) self.fSpectra[spectrum.fName] = spectrum limits = dict() self.AddBinsRecursive(self.fLimitSetList, limits) if reflections: self.LoadReflections(dmeson, jtype, jradius, reflections) return True
def __fitClassExample__(): data = getTxtFileArray( "SPEC\\2D\\2D data files\\05-NaCl1-4ordema-01-25s.txt", 0, True) spec = Spectrum.Spectrum(data) spec.setBaseLinePars(-500. / 3, 1800) spec.addGaussianParameters(100, 30, 0.1) customizeGraph() fitpars = spec.fitData(30, 31, "test.pdf") print("chi2: ", fitpars[0]) for i in range(len(fitpars[1])): print(fitpars[1][i], ": ", fitpars[2][i], " +/-", fitpars[3][i])
def update_spectrum(self, spectrum, ID): self.currentID = ID if self.SpectrumPlot.main_axis.get_xlabel() != r"%s (%s)" % ( spectrum.unit_label, spectrum.units): print('oh no!', spectrum.units) if spectrum.units == 'nm': spectrum_rangemod = nmtoeV_array(spectrum.SpectrumRange) spectrum_match = Spectrum.Spectrum( spectrum.intensity, units='eV', SpectrumRange=spectrum_rangemod) elif spectrum.units == 'eV': spectrum_rangemod = eVtonm_array(spectrum.SpectrumRange) spectrum_match = Spectrum.Spectrum( spectrum.intensity, units='nm', SpectrumRange=spectrum_rangemod) else: spectrum_match = spectrum self.spectrumDict[ID] = spectrum_match if self.currentID in self.lineDict.keys(): self.lineDict[self.currentID] = self.SpectrumPlot.update_spectrum( self.lineDict[self.currentID], self.spectrumDict[self.currentID]) self.lineDict[self.currentID][0].set_color( self.colourDict[self.currentID]) else: self.lineDict[ self. currentID] = add_function = self.SpectrumPlot.add_spectrum( self.spectrumDict[self.currentID], label=str(self.currentID)) self.make_colour_list() for ll in self.lineDict.keys(): self.lineDict[ll][0].set_color(self.colourDict[ll])
def __main__(): convertAll() spec = Spectrum.Spectrum( getTxtFileArray(crystalFileNames[currentCrystal], 0, True)) cpars = crystalFitParameters[currentCrystal][index] print(cpars) fitpars = crystalFit( spec, currentCrystal, index, currentCrystal + " fit " + str(cpars["range"][0]) + " - " + str(cpars["range"][1]) + ".pdf") print(currentCrystal + " fit " + str(cpars["range"][0]) + " - " + str(cpars["range"][1]) + ".pdf") print("chi2\t", fitpars[0]) for i in range(len(fitpars[1])): print(fitpars[1][i], "\t", fitpars[2][i], "\t", fitpars[3][i])
def process_file(self, filename, num_channels, stimLength, baseline, prestim_baseline): stimCodes = [i + 1 for i in range(num_channels)] signalChannel = self.fileData[filename][0] # timingChannel = f.data[3] codeChannels = {4 + i:self.fileData[filename][4 + i] for i in range(num_channels)} d = SRP.SRPdecoder() d.baseline = baseline d.stimLength = stimLength d.prestim_baseline = prestim_baseline self.prestim_baseline = prestim_baseline timeCodes = d.GetCodeList(signalChannel, codeChannels) stimTimeStamps = {code:d.GetTimeStamps(code, timeCodes) for code in stimCodes} stimLengths = {code:d.GetStimLengths(stimTimeStamps[code]) for code in stimTimeStamps} avgLength = d.AvgStimLength(stimTimeStamps) stimsPerSession = d.StimsPerSession(stimLengths, avgLength) stims = d.GetStimLists(signalChannel, stimsPerSession, avgLength, stimTimeStamps) stim_avgs = {code:d.GetAverages(stims[code], stimsPerSession) for code in stims} spectral_avgs = {code:sp.getSpectrumAvg(stims[code], stimsPerSession) for code in stims} orient_avgs = dict() for key in stim_avgs: if int(key) % 2 != 0: orient_avgs[key] = d.CombineAvgs(stim_avgs, key, key + 1) self.raw_stims[filename] = stims self.stimTimeStamps[filename] = stimTimeStamps self.timeCodes[filename] = timeCodes self.stimLengths[filename] = stimLengths self.stim_avgs[filename] = stim_avgs self.orient_avgs[filename] = orient_avgs self.total_avgs[filename] = self.get_grand_avgs(stim_avgs) self.grand_avgs[filename] = self.get_grand_avgs(orient_avgs) self.spectral_data[filename] = spectral_avgs
def fitFile(fname, index=0): filename = splitext(fname)[0] fitpars = fitParameters[fname][index] spec = Spectrum.Spectrum( getTxtFileArray("SPEC\\2D\\2D data files\\" + fname, 0, True)) for i in range(len(fitpars["A"])): spec.addGaussianParameters(fitpars["A"][i], fitpars["mu"][i], 0.2) spec.setBaseLinePars(fitpars["m"], fitpars["b"]) customizeGraph() afterfitpars = spec.fitData( fitpars["range"][0], fitpars["range"][1], filename + " " + str(fitpars["range"][0]) + " - " + str(fitpars["range"][1]) + ".pdf") print(filename + " " + str(fitpars["range"][0]) + " - " + str(fitpars["range"][1]) + ".pdf") print("chi2\t", afterfitpars[0]) for i in range(len(afterfitpars[1])): print(afterfitpars[1][i], "\t", afterfitpars[2][i], "\t", afterfitpars[3][i])
def run(self): self.Reader = Reader.Reader() self.Reader.read_pickle(file_path_energy, file_path_frequency) self.exp = np.loadtxt(file_path_exp, usecols=( 0, 1, )) idx = np.argsort(self.exp[:, 0]) self.exp = np.asarray(self.exp[idx]) self.freq = self.Reader.get_freq() self.E = self.Reader.get_energy() self.Spectrum = Spectrum.Spectrum(self.exp, self.freq, self.E, T=T, lower_bound=u, higher_bound=h, w1=width1, w2=width2, resolution_exp=resolution, Dipol=dipol, out=out) Alg = Algorithm.Algorithm(self.Spectrum, mu=mu, sigma_0=sigma0, sigma_1=sigma1, cutoff=cutoff, dummy_0=dummy_0, dummy_1=dummy_1) returnvalue, freq_old, freq_new, inten_new = Alg.Needleman_IR() print(-returnvalue) self.Spectrum.set_new_freq(freq_old, freq_new, inten_new) self.Spectrum.plot_unshifted() self.Spectrum.create_shifted() self.Spectrum.plot() p = self.Spectrum.integrate() self.Reader.write(out, p, returnvalue, args) return 1
#Stirrer###################################### N = 10 # Number of stirrer positions Angles = linspace(360 / N, 360, N) fcenter = 0.5 * (fstop + fstart) fspan = fstop - fstart #Measurement bandwidth in Hz RBW = 1e6 #Size of the RBW filter in Hz VBW = 1e6 #Size of the VBW filter in Hz Tmes = 1 #Dwelling time in s #Criterion_Level=-35 #peaksindex=[100,200,300] print '__________________________\nInstruments initializations\n' print '\nSpectrum analyzer' Spectre = Spectrum.FSV30() Spectre.reset() Spectre.RBW(RBW) Spectre.SweepPoint(SwpPt) Spectre.UnitDBM() Spectre.SPAN(fspan) Spectre.centerFreq(fcenter) print '\nStirrer' Stirrer = Stirrer('/com2', 1) print 'Moving to 0 deg' Stirrer.reset() #################################################### ################# Measurement ###################### ####################################################
g.peak_list_VCD_y_theo = [] for peak in g.theo_peaks_x: g.peak_list_VCD_y_theo.append( tmp_vcd[np.abs(tmp_vcd[:, 0] - peak) < 10e-3, 1][0]) self.ax.plot(g.theo_peaks_x, g.peak_list_VCD_y_theo, "o", color="blue") self.ax.set_xlim(g.values["lb"], g.values["hb"]) self.draw() if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = gui.Ui_MainWindow() ui.setupUi(MainWindow) g.Spectrum = Spectrum.Spectrum() g.canvas_list = [] g.canvas_list.append(Canvas(parent=ui.exp_ir_graph)) g.canvas_list.append(Canvas(parent=ui.exp_vcd_graph)) g.canvas_list.append(Canvas(parent=ui.theo_ir_graph)) g.canvas_list.append(Canvas(parent=ui.theo_vcd_graph)) g.canvas_list.append(Canvas(parent=ui.assignment_graph)) g.canvas_list.append(Canvas(parent=ui.shifted_graph)) g.list_buttons = [] g.list_buttons.append(Button(ui.w, "w")) g.list_buttons.append(Button(ui.lb, "lb")) g.list_buttons.append(Button(ui.hb, "hb")) g.list_buttons.append(Button(ui.sigma_1, "s0")) g.list_buttons.append(Button(ui.sigma_2, "s1")) g.list_buttons.append(Button(ui.mu, "mu")) g.list_buttons.append(Button(ui.cutoff, "c"))
#plt.grid() #plt.show() tx_upsampled = rf.UpSampling(txBaseband, 5 / 100, 100) tx_mixer = rf.Mixer(tx_upsampled, 30 / 100, np.pi / 4) tx_sig = tx_mixer.real + rf.WhiteNoise(tx_mixer, 50) #sp.fftPlot(txBaseband.real, txBaseband.imag, n=2) #sp.fftPlot(tx_upsampled.real, tx_upsampled.imag, n=2) #sp.fftPlot(tx_mixer.real, tx_mixer.imag, n=2) #sp.fftPlot(tx_sig.real) rx_mixer = rf.Mixer(tx_sig, -30 / 100, -1 * np.pi / 4) b = signal.remez(100 + 1, [0, .1, 0.2, 0.5], [1, 1e-4]) baseband_flt = np.convolve(b, rx_mixer, 'same') sp.fftPlot(rx_mixer.real, rx_mixer.imag, n=2) sp.fftPlot(baseband_flt.real, baseband_flt.imag, n=2) #baseband_flt = baseband_flt[40::100] #plt.plot(baseband_flt[0:300].real, baseband_flt[0:300].imag, 'ro') plt.plot(baseband_flt[5::10].real, baseband_flt[5::10].imag, 'ro') plt.plot(baseband_flt[40::100].real, baseband_flt[40::100].imag, 'bo') plt.grid() plt.show() elif c == 'm': QAM.QamModem(30, 100, QAM.Constant.ModulationType.QAM16, 13)
f.setFilename('C:/Users/Jesse/Documents/Python Scripts/test/M_SRP11_45d_135d_d6_awake_132_data.bin') f.setDataType('<d') f.openDataFile() f.plotData() num_channels = 4 stimCodes = [1,2,3,4] signalChannel = f.data[0] timingChannel = f.data[3] codeChannels = {4 + i:f.data[4 + i] for i in range(num_channels)} SRP = SRPdecoder() timeCodes = SRP.GetCodeList(signalChannel, codeChannels) stimTimeStamps = {code:SRP.GetTimeStamps(code, timeCodes) for code in stimCodes} stimLengths = {code:SRP.GetStimLengths(stimTimeStamps[code]) for code in stimTimeStamps} avgLength = SRP.AvgStimLength(stimTimeStamps) stimsPerSession = SRP.StimsPerSession(stimLengths, avgLength) stims = SRP.GetStimLists(signalChannel, stimsPerSession, avgLength, stimTimeStamps) avgs = [SRP.GetAverages(stims[code], stimsPerSession) for code in stims] spectra_avgs = [sp.getSpectrumAvg(stims[code], stimsPerSession) for code in stims] plt.figure(4) plt.plot(avgs[0][0]) plt.figure(5) plt.plot(avgs[1][0])
def show_spectrum(self): fig = plt.figure(1) fig.clear() plt.xlabel('Freq (Hz)') plt.ylabel('|Y(freq)|') if self.graphBehavior == 'selected' or self.graphBehavior == 'all': selection = self.selectedBlocks.curselection() stimTypeVar = self.stimTypeVar.get() if stimTypeVar == 1: lookupIndex = 1 elif stimTypeVar == 2 or stimTypeVar == 3: lookupIndex = 0 for item in selection: block, key = self.selectedBlocks.get(item).split(" ") orientation, block = block.split(" ") block = int(block) - 1 if stimTypeVar != 3: stim_type = orientation_lookup[orientation][lookupIndex] #freq, Y = Spectrum.getSpectrum(Data.stim_avgs[key][stim_type][block]) freq, Y = Data.spectral_data[key][stim_type][block] plt.plot(freq,abs(Y), label = orientation + " " + str(block + 1) + " " + key) elif stimTypeVar == 3: stim_type = orientation_lookup[orientation][lookupIndex] #freq, Y = Spectrum.getSpectrum(Data.orient_avgs[key][stim_type][block]) freq, Y = Data.spectral_data[key][stim_type][block] plt.plot(freq,abs(Y), label = orientation + " " + str(block + 1) + " " + key) elif self.graphBehavior == 'total': selection = self.processedList.curselection() selection = [self.processedList.get(item) for item in selection] if (len(selection) == 0): self.processedList.selection_set(0,tk.END) selection = self.processedList.curselection() selection = [self.processedList.get(item) for item in selection] novel = self.novelVar.get() familiar = self.familiarVar.get() for key in Data.grand_avgs: if key in selection: if self.stimTypeVar.get() == 3: if familiar == 1: freq, Y = Spectrum.getSpectrum(Data.grand_avgs[key][1][0]) plt.plot(freq,abs(Y), label = orientations[1][0] + " " + key) if novel == 1 and len(Data.grand_avgs[key])>1: freq, Y = Spectrum.getSpectrum(Data.grand_avgs[key][3][0]) plt.plot(freq,abs(Y), label = orientations[3][0] + " " + key) elif self.stimTypeVar.get() == 1: if familiar == 1: freq, Y = Spectrum.getSpectrum(Data.total_avgs[key][2][0]) plt.plot(freq,abs(Y), label = orientations[2][0] + " " + key) if novel == 1 and len(Data.grand_avgs[key])>1: freq, Y = Spectrum.getSpectrum(Data.total_avgs[key][4][0]) plt.plot(freq,abs(Y), label = orientations[4][0] + " " + key) elif self.stimTypeVar.get() == 2: if familiar == 1: freq, Y = Spectrum.getSpectrum(Data.total_avgs[key][1][0]) plt.plot(freq,abs(Y), label = orientations[1][0] + " " + key) if novel == 1 and len(Data.grand_avgs[key])>1: freq, Y = Spectrum.getSpectrum(Data.total_avgs[key][3][0]) plt.plot(freq,abs(Y), label = orientations[3][0] + " " + key) plt.legend(fontsize = 6,loc='best') plt.xlim((0,200))
def testSymmetrizeAroundZLPcenter(self): #ZLP is exactly in the middle of the spectrum data = np.array([1, 1, 1, 1, 20, 35, 20, 1, 1, 1, 1]) eels = Spectrum.EELSSpectrum(data, dispersion=0.2, ZLP=True) eels_sym = eels.SymmetrizeAroundZLP() self.assertArraysEqual(eels.intensity, eels_sym.intensity)
import numpy as np import Spectrum import SpectrumPlotter import CLSpectrumData import SpectrumImagePlotter import matplotlib.pyplot as plt import SpectrumImage import os #### Testing Spectrum and SpectrumPlotter PSFfolder = '/home/isobel/Documents/McMaster/EELS/2016-04-18/Sq1A_(1,8)' PSFfilename = 'Spectrum_ZLP.csv' Spectrumfilename = 'Processed/Spectrum_1.csv' spectrum = Spectrum.EELSSpectrum.LoadFromCSV( os.path.join(PSFfolder, Spectrumfilename)) Spectrumsmooth = Spectrum.EELSSpectrum(spectrum.SmoothingFilter1D(sigma=2)) #PSF = Spectrum.EELSSpectrum.LoadFromCSV(os.path.join(PSFfolder, PSFfilename)) #PSFsmooth = Spectrum.EELSSpectrum(PSF.SmoothingFilter1D()) s = np.random.random(100) * 0.00003 wvl = np.arange(500, 600) SCL = Spectrum.CLSpectrum(s, wvl) fig = plt.figure() ax = plt.axes() s = SpectrumPlotter.SpectrumManager(spectrum, ax) s.update_spectrum(Spectrumsmooth, 1) s.update_spectrum(SCL, 'CL') plt.show() #S.SaveSpectrumAsCSV('/home/isobel/Documents/McMaster/PythonCodes/DataAnalysis/test.csv')
def test_imagesolution(): # load the image and determine its spectrograph parameters hdu = fits.open(inimage) # create the data arra data = hdu[1].data # create the header information instrume = hdu[1].header['INSTRUME'].strip() grating = hdu[1].header['GRATING'].strip() grang = hdu[1].header['GR-ANGLE'] arang = hdu[1].header['AR-ANGLE'] filter = hdu[1].header['FILTER'].strip() slit = float(hdu[1].header['MASKID']) xbin, ybin = hdu[1].header['CCDSUM'].strip().split() print(instrume, grating, grang, arang, filter) print(xbin, ybin) # create the RSS Model rssmodel = RSSModel.RSSModel(grating_name=grating, gratang=grang, camang=arang, slit=slit, xbin=int(xbin), ybin=int(ybin)) alpha = rssmodel.rss.gratang beta = rssmodel.rss.gratang - rssmodel.rss.camang sigma = 1e7 * rssmodel.rss.calc_resolelement(alpha, beta) # create the spectrum stype = 'line' w, s = np.loadtxt(inspectra, usecols=(0, 1), unpack=True) spec = Spectrum.Spectrum(w, s, wrange=[4000, 5000], dw=0.1, stype=stype, sigma=sigma) # spec.flux=spec.set_dispersion(sigma=sigma) # Now having the model and the data, set up the variables j = int(len(data) / 2) xlen = len(data[0]) xarr = np.arange(len(data[0])) farr = data[j, :] var = abs(farr) + farr.mean() var = var * (farr > 1000) + 1 if 1: imsol = LineSolution(rssmodel.rss, xarr=xarr, farr=farr, spectrum=spec, yval=0, var=var, order=2) output = imsol.fit(imsol.makeflux, imsol.coef, imsol.xarr, imsol.farr, imsol.var) # imsol.fit(imsol.makeflux, imsol.ndcoef, imsol.xarr, imsol.farr, imsol.var) # imsol.fit(imsol.makeflux, imsol.coef, imsol.xarr, imsol.farr, imsol.var) # for i in range(len(imsol.coef)): # print imsol.coef[i]() # for i in range(len(imsol.ndcoef)): # print imsol.ndcoef[i]() print(output.beta) print(imsol.value(output.beta, 500)) # check the results warr = imsol.value(output.beta, imsol.xarr) print((wp - imsol.value(output.beta, xp)).mean(), (wp - imsol.value(output.beta, xp)).std()) pl.figure() pl.plot( imsol.spectrum.wavelength, imsol.spectrum.flux * imsol.farr.max() / imsol.spectrum.flux.max()) pl.plot(warr, imsol.farr) # pl.plot(xp, wp-imsol.value(xp), ls='', marker='o') pl.show() # okay now test the results for a purely matched lines fp = xp * 0.0 + 2.0 var = xp * 0.0 + 1.0 xspec = Spectrum.Spectrum(xp, fp, dw=0.1, stype='line', sigma=sigma) wspec = Spectrum.Spectrum(wp, fp, wrange=[4000, 5000], dw=0.1, stype='line', sigma=sigma) imsol = LineSolution(rssmodel.rss, xarr=xspec.wavelength, farr=xspec.flux, spectrum=wspec, yval=0, var=var, order=3) imsol.xlen = xlen output = imsol.fit(imsol.value, imsol.coef, xp, wp, var) print(output.beta) # imsol.fit(imsol.value, imsol.ndcoef, xp, wp, var) # for i in range(len(imsol.coef)): # print imsol.coef[i]) # for i in range(len(imsol.ndcoef)): # print imsol.ndcoef[i]() print(imsol.value(output.beta, 500)) print((wp - imsol.value(output.beta, xp)).mean(), (wp - imsol.value(output.beta, xp)).std()) # check the results warr = imsol.value(output.beta, xarr) pl.figure() pl.plot(spec.wavelength, spec.flux * farr.max() / spec.flux.max()) pl.plot(warr, farr) # pl.plot(xp, wp-imsol.value(output.beta, xp), ls='', marker='o') pl.show()
sys.exit(0) Data_File = sys.argv[1] Plot_Out = sys.argv[2] #Load it! UncalFreq, LaserRelMag, SourceRelMag = np.loadtxt(Data_File, unpack=True, skiprows=1) #Now process it S = Spectrum(UncalFreq, LaserRelMag, SourceRelMag, lowLimit=300, highLimit=1500, withoutLaser=True, laserBuffer=1, Component_Frac_Min=100, NM_Peak_Allowance=0.2, Peak_Min_RelMag=50) S.plot_range(Plot_Out, printPeaks=False, printPlanck=False) Components = S.analyse_spectrum() for Component in Components.items(): Name = Component[0] Count = Component[1][0] Percent = Component[1][1] print "Component " + Name + " matched " + str(Count) + " peaks (" + str( round(Percent * 100, 1)) + "%)."
spec1name = 'SimRod_(60,0)_10meV.csv' psfname = 'PSF_exp.csv' # Import and plot original data spec1 = Spectrum.EELSSpectrum.LoadFromCSV(os.path.join(folder, spec1name)) spec1plot = SpectrumPlotter.SpectrumManager(spec1, cmap=plt.get_cmap('brg')) # Import and plot original psf psf = Spectrum.EELSSpectrum.LoadFromCSV(os.path.join(folder, psfname)) psf.intensity = psf.intensity/np.max(psf.intensity) psf.SpectrumRange = np.append(psf.SpectrumRange[1:], psf.SpectrumRange[-1] + psf.dispersion) spec1plot.update_spectrum(psf, ID='PSF') # Convolve data with PSF conv = np.convolve(psf.intensity, spec1.intensity, 'same') spec_conv = Spectrum.EELSSpectrum(conv/np.max(conv), ZLP=True, dispersion=0.01) spec1plot.update_spectrum(spec_conv, ID='conv') # Make poisson noise noise = np.random.poisson(spec_conv.intensity/np.min(spec_conv.intensity)) # Noisy data noised = spec_conv.intensity + noise spec_noise = Spectrum.EELSSpectrum(noised/np.max(noised), SpectrumRange=spec_conv.SpectrumRange) spec1plot.update_spectrum(spec_noise, ID='noisy') iterations = np.arange(2001) #iterations = np.array([0, 1, 10, 50, 107, 123, 293, 350, 1000, 2000]) #iterations = np.arange(100) specRL = collections.OrderedDict() error = []
def ImportIR(self): filename = '/home/isobel/Documents/McMaster/CL/SystemResponseFcns/CorrectionFactorSCAlIRCamera_2015_02_26.csv' dataDict = ReadCSVRef(filename) d = dataDict[self.grating, self.center_wavelength] correction_spectrum = Spectrum.CLSpectrum(d[:,1], d[:,0]) return correction_spectrum
def plotFile(filename: str, xmin=0, xmax=0, type=""): customizeGraph(type) Spectrum.Spectrum(getTxtFileArray(filename, 0, True)).plotData(xmin, xmax)
writer = csv.writer(csvfile, delimiter=' ') writer.writerow(ExportHeaders) writer.writerows(ExportData) # Import test data (simulated spectrum from Bellido et al (2014) folder = 'TestCase' spec1name = 'SimRod_(60,0)_10meV.csv' # Plot original data spec1 = Spectrum.EELSSpectrum.LoadFromCSV(os.path.join(folder, spec1name)) spec1plot = SpectrumPlotter.SpectrumManager(spec1) # Create point spread function (PSF) PSF_Gauss = Spectrum.EELSSpectrum(signal.gaussian(801, std=np.sqrt(2)), dispersion=0.01, ZLP=True) # Convolve simulated data with PSF conv = np.convolve(PSF_Gauss.intensity, spec1.intensity) spec2 = Spectrum.EELSSpectrum(conv / np.max(conv), dispersion=0.01, ZLP=True) # Plot PSF and convolved (blurred) spectra spec1plot.update_spectrum(PSF_Gauss, ID='PSF Gauss') spec1plot.update_spectrum(spec2, ID='Convolved') spec1plot.add_legend() iterations = np.append(np.arange(1, 1000), np.array([2000, 2500, 3000, 3500, 4000, 4500, 5000])) iterations = np.arange(10) spec2RL = collections.OrderedDict()