-
->>>>>>> xml
+
-
->>>>>>> Revert "xml"
+
+
+
+
+
+
+
diff --git a/Data.py b/Data.py
index a4c8720..3fc3c67 100644
--- a/Data.py
+++ b/Data.py
@@ -5,6 +5,9 @@
class Data():
+ '''
+ Holds all of the data needed in PyTrA
+ '''
time_C = np.array([])
wavelength_C = np.array([])
Chirp = np.array([])
@@ -19,4 +22,7 @@ class Data():
tracefitmodel = []
Traces = np.array([0])
Pixels = np.array([])
- Range = np.array([-1,2])
\ No newline at end of file
+ Range = np.array([-1,2])
+ mcmc = {}
+ xi = np.array([])
+ yi = np.array([])
\ No newline at end of file
diff --git a/Data.pyc b/Data.pyc
index caa461c..ab5b4f7 100644
Binary files a/Data.pyc and b/Data.pyc differ
diff --git a/LICENCE.txt b/LICENCE.txt
new file mode 100644
index 0000000..8257dad
--- /dev/null
+++ b/LICENCE.txt
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Jacob Martin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/PyTrA.py b/PyTrA.py
index 20f8045..6ecf159 100644
--- a/PyTrA.py
+++ b/PyTrA.py
@@ -1,70 +1,111 @@
-##--PyTrA--##
+'''
+PyTrA: Python based fitting of femtosecond transient absorption spectroscopy data
+Author: Jake Martin, Photon Factory, University of Auckland
+'''
import numpy as np
+from datetime import date
+from os import startfile
+from os.path import dirname,splitext,split
+from numpy import sqrt, log, exp, array, linspace, polyfit, polyval, abs, hstack, vstack, sum, meshgrid, multiply, zeros, arange, ones, average, delete
from numpy import genfromtxt
from pylab import ginput
-import matplotlib.pyplot as plt
-import os
-import mcmc
-import Global as glo
-from traits.api import HasTraits, File, Button, Array, Enum, Instance, Str, Range
-from traitsui.api import Group, Item, View, Label, HSplit, Tabbed
from scipy import interpolate, special, linalg
-from Data import Data
-import pymodelfit.fitgui as fitgui
+from matplotlib.pyplot import figure, contourf, title, xlabel, ylabel, show, close, xlim, ylim, subplot, semilogy, gca, colorbar, cm, legend, plot, subplots_adjust
+from traits.api import HasTraits, File, Button, Array, Instance, Str, Int, Float, Bool
+from traitsui.menu import Action, Menu,MenuBar
+from traitsui.api import Group, Item, View, Label, HSplit, Tabbed, VSplit, RangeEditor, ValueEditor
+from chaco.api import ArrayPlotData, Plot, jet
+from chaco.tools.api import PanTool, ZoomTool
from tvtk.pyface.scene_editor import SceneEditor
from mayavi.tools.mlab_scene_model import MlabSceneModel
from mayavi.core.ui.mayavi_scene import MayaviScene
-from pymodelfit import FunctionModel1DAuto
-from pymodelfit import register_model
-from datetime import date
-import scipy.fftpack as fft
+from enable.component_editor import ComponentEditor
+from pymodelfit import fitgui, FunctionModel1DAuto, register_model
+from Data import Data
+import mcmc
from PyTrA_Help import Help
##--Describes exponential models--##
class Convoluted_exp1(FunctionModel1DAuto):
- def f(self,x,T1=1,A1=1,w=1,mu=1,y0=1):
- d = (w/(2*np.sqrt(2*np.log(2))))
- return A1*1/2*np.exp(-x/T1)*np.exp((mu+(d**2)/(2*T1))/T1)*(1+special.erf((x-(mu+(d**2)/T1))/(np.sqrt(2)*d))) + y0
+ def f(self,x,Tone=20,Aone=0.1,fwhm=0.5,mu=0,c=0):
+ d = (fwhm/(2*sqrt(2*log(2))))
+ return Aone*1/2*exp(-x/Tone)*exp((mu+(d**2)/(2*Tone))/Tone)*(1+special.erf((x-(mu+(d**2)/Tone))/(sqrt(2)*d))) + c
class Convoluted_exp2(FunctionModel1DAuto):
- def f(self,x,T1=1,T2=2,A1=1,A2=1,w=0.25,mu=1,y0=1):
- d = w/(2*np.sqrt(2*np.log(2)))
- return A1*1/2*np.exp(-x/T1)*np.exp((mu+(d**2)/(2*T1))/T1)*(1+special.erf((x-(mu+(d**2)/T1))/(np.sqrt(2)*d))) + A2*1/2*np.exp(-x/T2)*np.exp((mu+(d**2)/(2*T2))/T2)*(1+special.erf((x-(mu+(d**2)/T2))/(np.sqrt(2)*d))) + y0
+ def f(self,x,Tone=20,Ttwo=20,Aone=0.1,Atwo=0.1,fwhm=0.5,mu=0,c=0):
+ d = fwhm/(2*sqrt(2*log(2)))
+ return Aone*1/2*exp(-x/Tone)*exp((mu+(d**2)/(2*Tone))/Tone)*(1+special.erf((x-(mu+(d**2)/Tone))/(sqrt(2)*d))) + Atwo*1/2*exp(-x/Ttwo)*exp((mu+(d**2)/(2*Ttwo))/Ttwo)*(1+special.erf((x-(mu+(d**2)/Ttwo))/(sqrt(2)*d))) + c
class Convoluted_exp3(FunctionModel1DAuto):
- def f(self,x,T1=1,T2=1,T3=1,A1=1,A2=1,A3=1,w=1,mu=1,y0=1):
- d = (w/(2*np.sqrt(2*np.log(2))))
- return A1*1/2*np.exp(-x/T1)*np.exp((mu+(d**2)/(2*T1))/T1)*(1+special.erf((x-(mu+(d**2)/T1))/(np.sqrt(2)*d))) + A2*1/2*np.exp(-x/T2)*np.exp((mu+(d**2)/(2*T2))/T2)*(1+special.erf((x-(mu+(d**2)/T2))/(np.sqrt(2)*d))) + A3*1/2*np.exp(-x/T3)*np.exp((mu+(d**2)/(2*T3))/T3)*(1+special.erf((x-(mu+(d**2)/T3))/(np.sqrt(2)*d))) + y0
+ def f(self,x,Tone=20,Ttwo=20,Tthree=20,Aone=0.1,Atwo=0.1,Athree=0.1,fwhm=0.5,mu=0,c=0):
+ d = (fwhm/(2*sqrt(2*log(2))))
+ return Aone*1/2*exp(-x/Tone)*exp((mu+(d**2)/(2*Tone))/Tone)*(1+special.erf((x-(mu+(d**2)/Tone))/(sqrt(2)*d))) + Atwo*1/2*exp(-x/Ttwo)*exp((mu+(d**2)/(2*Ttwo))/Ttwo)*(1+special.erf((x-(mu+(d**2)/Ttwo))/(sqrt(2)*d))) + Athree*1/2*exp(-x/Tthree)*exp((mu+(d**2)/(2*Tthree))/Tthree)*(1+special.erf((x-(mu+(d**2)/Tthree))/(sqrt(2)*d))) + c
class Convoluted_exp4(FunctionModel1DAuto):
- def f(self,x,T1=1,T2=1,T3=1,T4=1,A1=1,A2=1,A3=1,A4=1,w=1,mu=1,y0=1,):
- d = (w/(2*np.sqrt(2*np.log(2))))
- return A1*1/2*np.exp(-x/T1)*np.exp((mu+(d**2)/(2*T1))/T1)*(1+special.erf((x-(mu+(d**2)/T1))/(np.sqrt(2)*d))) + A2*1/2*np.exp(-x/T2)*np.exp((mu+(d**2)/(2*T2))/T2)*(1+special.erf((x-(mu+(d**2)/T2))/(np.sqrt(2)*d))) + A3*1/2*np.exp(-x/T3)*np.exp((mu+(d**2)/(2*T3))/T3)*(1+special.erf((x-(mu+(d**2)/T3))/(np.sqrt(2)*d))) + A4*1/2*np.exp(-x/T4)*np.exp((mu+(d**2)/(2*T4))/T4)*(1+special.erf((x-(mu+(d**2)/T4))/(np.sqrt(2)*d))) + y0
+ def f(self,x,Tone=20,Ttwo=20,Tthree=20,Tfour=20,Aone=0.1,Atwo=0.1,Athree=0.1,Afour=0.1,fwhm=0.5,mu=0,c=0):
+ d = (fwhm/(2*sqrt(2*log(2))))
+ return Aone*1/2*exp(-x/Tone)*exp((mu+(d**2)/(2*Tone))/Tone)*(1+special.erf((x-(mu+(d**2)/Tone))/(sqrt(2)*d))) + Atwo*1/2*exp(-x/Ttwo)*exp((mu+(d**2)/(2*Ttwo))/Ttwo)*(1+special.erf((x-(mu+(d**2)/Ttwo))/(sqrt(2)*d))) + Athree*1/2*exp(-x/Tthree)*exp((mu+(d**2)/(2*Tthree))/Tthree)*(1+special.erf((x-(mu+(d**2)/Tthree))/(sqrt(2)*d))) + Afour*1/2*exp(-x/Tfour)*exp((mu+(d**2)/(2*Tfour))/Tfour)*(1+special.erf((x-(mu+(d**2)/Tfour))/(sqrt(2)*d))) + c
+
+class Gauss_1(FunctionModel1DAuto):
+ def f(self,x,Aone=0.1,fwhm=30.0,mu=500.0,c=0.0):
+ d = (fwhm/(2*sqrt(2*log(2))))
+ return Aone*exp(-((x-mu)**2)/(2*d**2))+c
+
+class Gauss_2(FunctionModel1DAuto):
+ def f(self,x,Aone=0.1,Atwo=0.1,fwhm_1=40.0,fwhm_2=30.0,mu_1=500,mu_2=600,c=0.0):
+ d_1 = (fwhm_1/(2*sqrt(2*log(2))))
+ d_2 = (fwhm_2/(2*sqrt(2*log(2))))
+ return Aone*exp(-((x-mu_1)**2)/(2*d_1**2))+Atwo*exp(-((x-mu_2)**2)/(2*d_2**2))+c
+
+class Gauss_3(FunctionModel1DAuto):
+ def f(self,x,Aone=0.1,Atwo=0.1,Athree=0.2,fwhm_1=40.0,fwhm_2=30.0,fwhm_3=20,mu_1=500,mu_2=600,mu_3=700,c=0.0):
+ d_1 = (fwhm_1/(2*sqrt(2*log(2))))
+ d_2 = (fwhm_2/(2*sqrt(2*log(2))))
+ d_3 = (fwhm_3/(2*sqrt(2*log(2))))
+ return Aone*exp(-((x-mu_1)**2)/(2*d_1**2))+Atwo*exp(-((x-mu_2)**2)/(2*d_2**2))+Athree*exp(-((x-mu_3)**2)/(2*d_3**2))+c
+
+class Gauss_4(FunctionModel1DAuto):
+ def f(self,x,Aone=0.1,Atwo=0.1,Athree=0.2,Afour=0.2,fwhm_1=40.0,fwhm_2=30.0,fwhm_3=20,fwhm_4=20,mu_1=500,mu_2=600,mu_3=700,mu_4=750,c=0.0):
+ d_1 = (fwhm_1/(2*sqrt(2*log(2))))
+ d_2 = (fwhm_2/(2*sqrt(2*log(2))))
+ d_3 = (fwhm_3/(2*sqrt(2*log(2))))
+ d_4 = (fwhm_4/(2*sqrt(2*log(2))))
+ return Aone*exp(-((x-mu_1)**2)/(2*d_1**2))+Atwo*exp(-((x-mu_2)**2)/(2*d_2**2))+Athree*exp(-((x-mu_3)**2)/(2*d_3**2))+Afour*exp(-((x-mu_4)**2)/(2*d_4**2))+c
register_model(Convoluted_exp1, name='Convoluted_exp1', overwrite=False)
register_model(Convoluted_exp2, name='Convoluted_exp2', overwrite=False)
register_model(Convoluted_exp3, name='Convoluted_exp3', overwrite=False)
register_model(Convoluted_exp4, name='Convoluted_exp4', overwrite=False)
-
-##--set up window--##
+register_model(Gauss_1, name='Gauss_1', overwrite=False)
+register_model(Gauss_2, name='Gauss_2', overwrite=False)
+register_model(Gauss_3, name='Gauss_3', overwrite=False)
+register_model(Gauss_4, name='Gauss_4', overwrite=False)
class OhioLoader(HasTraits):
- Data_file = File()
- Delay = File()
- WaveCal = Array(np.float, (6,2), np.array([[400, 2013.07],[450,1724.29],[500,1397.38],[570,955.733],[600,775.612],[650,458.316]]))
+ '''
+ Window to import data from Ohio State University Ultrafast TrA system. Calibration of wavelength to pixel is done and imported into a file that PyTrA can use.
+ '''
+ Data_file = File("TrA data")
+ Delay = File("Delay file")
+ WaveCal = Array(float, (6,2), array([[400, 2013.07],[450,1724.29],[500,1397.38],[570,955.733],[600,775.612],[650,458.316]]))
Load_data = Button("Load data")
view = View(
- Item('Data_file', style = 'simple', label = 'TrA data'),
- Item('Delay', style = 'simple', label = 'Delay'),
- Item('WaveCal', label='Wavelength pixel calibration'),
+ Label('Importer for Ohio State University ultrafast TrA system'),
+ Item('Data_file', style = 'simple', show_label=False),
+ Item('Delay', style = 'simple', show_label=False),
+ Label('Wavelength pixel calibration'),
+ Item('WaveCal', show_label=False),
Item('Load_data', show_label=False),
title = 'Ohio data loader', resizable=True,
buttons = [ 'OK', 'Cancel' ]
)
def _Load_data_fired(self):
+ '''
+ Data is loaded in from file and calibrated to the correct wavelength values
+ '''
TrA_Raw_T = genfromtxt(self.Data_file, filling_values='0')
# Take transponse of matrix
@@ -79,10 +120,10 @@ def _Load_data_fired(self):
# Calculating the wavelengths from the calibration data
- wave = np.linspace(1, TrA_Raw_n, TrA_Raw_n)
- fitcoeff = np.polyfit(self.WaveCal[:, 1], self.WaveCal[:, 0], 1)
+ wave = linspace(1, TrA_Raw_n, TrA_Raw_n)
+ fitcoeff = polyfit(self.WaveCal[:, 1], self.WaveCal[:, 0], 1)
- Data.wavelength = np.polyval(fitcoeff, wave)
+ Data.wavelength = polyval(fitcoeff, wave)
#Sort data from smallest wavelength to largest wavelength
@@ -93,142 +134,84 @@ def _Load_data_fired(self):
Data.time_C = Data.time
Data.wavelength_C = Data.wavelength
-class FFTfilter(HasTraits):
- raw_plot = Button('2D plot of raw data')
- FFT_raw = Button('FFT')
- filter_high = int(0)
- filter_low = int(0)
- data = np.array([])
- fft_filter = Button('Apply filter')
- accept = Button('Apply to data set')
+class Dataviewer(HasTraits):
+ data = Data
view = View(
- Item('raw_plot', show_label=False),
- Item('FFT_raw', show_label=False),
- Item('filter_high', show_label=False),
- Item('filter_low', show_label=False),
- Item('fft_filter', show_label=False),
- Item('accept', show_label=False),
- title = 'FFT filter', resizable=False,
- )
-
- def _raw_plot_fired(self):
- plt.figure()
- plt.contourf(Data.TrA_Data,100,cmap=plt.cm.Greys_r)
- plt.title('Raw data')
- plt.show()
-
- def _FFT_raw_fired(self):
- fft_shift = fft.fft2(Data.TrA_Data)
- Data.FFT = fft.ifftshift(fft_shift)
- plt.figure()
- plt.contourf(np.log(np.abs(Data.FFT)**2),cmap=plt.cm.Greys_r)
- plt.title('FFT of raw')
- plt.show()
-
- def _fft_filter_fired(self):
- Data.FFT[int(self.filter_high):int(self.filter_low),:] = 0
- Data.FFT[int(Data.time.shape[0])-int(self.filter_low)+1:int(Data.time.shape[0])-int(self.filter_high)+1,:] = 0
- plt.figure()
- plt.contourf(np.log(np.abs(Data.FFT)**2),cmap=plt.cm.Greys_r)
- plt.show()
-
- shift = fft.fftshift(Data.FFT)
- self.data = fft.ifft2(shift)
- plt.figure()
- plt.contourf(self.data,200,cmap=plt.cm.Greys_r)
- plt.title('filtered raw data')
- plt.show()
-
- def _accept_fired(self):
- Data.TrA_Data = np.real(self.data)
+ Item('data',show_label=False,editor=ValueEditor()),
+ resizable=True
+ )
class MainWindow(HasTraits):
+ '''
+ Main window for PyTrA sets up the view objects and views the different methods that can be applied to the data
+ '''
+
+ #--View objects for TraitsUI--#
+
scene = Instance(MlabSceneModel, ())
+ plot2D = Instance(Plot)
+ plotwaveindexshow = Float
+ plotwaveindex = Float
+ wavelow=Float(0)
+ wavehigh=Float(100)
+ waverange=int(100)
+ plottimeindexshow = Float
+ plottimeindex = Float
+ timelow=Float(-1.0)
+ timehigh=Float(100.0)
+ timerange=int(100)
+ plottime = Instance(Plot)
+ updateplots = Button('Reset plots')
+ zoom_on = Bool(False)
+ plotwavelength = Instance(Plot)
+ plot2Db = Button("plot")
TrA_Raw_file = File("TrA data")
Chirp_file = File("Chirp data")
Load_files = Button("Load data")
+ open_csv = Button("Open csv")
Shiftzero = Button("Shift time zero")
Ohioloader = Button("Ohio data loader")
- DeleteTraces = Button("Delete traces")
- Delete_spectra = Button('Delete spectra')
- fft_filter = Button('FFT filter')
+ DeleteTraces = Button("Delete multiple traces")
+ Delete_spectra = Button('Delete multiple spectra')
+ DeleteTraces_1 = Button('Delete trace')
+ DeleteSpectra_1 = Button('Delete spectrum')
PlotChirp = Button("2D plot of chirp")
- Timelim = Array(np.float,(1,2))
+ Timelim = Array(float,(1,2))
Fix_Chirp = Button("Fix for chirp")
- Fit_Trace = Button("Fit trace")
- mcmc = Button("MCMC fitting")
+ Fit_Trace = Button("Fit Trace")
+ Fit_Spec = Button("Fit Spectra")
+ mcmc = Button("MCMC")
Fit_Chirp = Button("Fit chirp")
- SVD = Enum(1,2,3,4,5)
- SVD = Button("SVD on plot")
- EFA = Button("Evolving factor analysis")
+ SVD = Button("SVD")
+ EFA = Button("EFA")
Traces_num = 0
Multiple_Trace = Button("Select multiple traces")
Global = Button("Global fit")
+ savetraces = Button("save traces")
title = Str("Welcome to PyTrA")
- z_height = Range(1,100)
+ z_height = Int(4)
Plot_3D = Button("3D plot")
Plot_2D = Button("2D plot")
- Plot_log = Button("2D log plot")
Plot_Traces = Button("Plot traces")
- multiple_plots = Button("Multiple traces/spectra on plot")
- Normalise = Button("Normalise")
+ multiple_plots = Button("Averaged")
+ Normalise = Button("Normalised")
Kinetic_Trace = Button("Kinetic trace")
Spectra = Button("Spectra")
- Trace_Igor = Button("Send traces to Igor")
- Global = Button("Global fit")
Save_Glo = Button("Save as Glotaran file")
Save_csv = Button("Save csv with title as file name")
Save_log = Button("Save log file")
Help = Button("Help")
- log = Str
-
- #Setting up views
+ log = Str("PyTrA:Python based fitting of Ultra-fast Transient Absorption Data")
+ showdata=Button("Show python data")
- buttons_group = Group(
- Item('title', show_label=False),
- Item('TrA_Raw_file', style = 'simple', show_label=False),
- Item('Chirp_file', style = 'simple', show_label=False),
- Item('Load_files', show_label=False),
- Item('Ohioloader', show_label=False),
- Item('DeleteTraces', show_label=False),
- Item('Delete_spectra', show_label=False),
- Item('fft_filter', show_label=False),
- Item('Shiftzero', show_label=False),
- Label('Chirp Correction'),
- Item('PlotChirp', show_label=False),
- Label('Time range for chirp corr short/long'),
- Item('Timelim', show_label=False),
- Item('Fix_Chirp', show_label=False),
- Label('Data Analysis'),
- Item('Fit_Trace', show_label=False),
- Item('mcmc',show_label=False),
- Item('Plot_2D', show_label=False),
- Item('SVD', show_label=False),
- Item('EFA', show_label=False),
- Label('Global fitting'),
- Item('Multiple_Trace', show_label=False),
- Item('Trace_Igor', show_label=False),
- Item('Plot_Traces', show_label=False),
- Item('Global', show_label=False),
- Label('Visualisation'),
- Item('Plot_3D', show_label=False),
- Item('z_height', show_label=False),
- Item('Plot_2D', show_label=False),
- Item('Plot_log', show_label=False),
- Item('Spectra', show_label=False),
- Item('Kinetic_Trace', show_label=False),
- Item('multiple_plots', show_label=False),
- Item('Normalise', show_label=False),
- Label('Export Data'),
- Item('Save_csv', show_label=False),
- Item('Save_log', show_label=False),
- Item('Save_Glo', show_label=False),
- Item('Help', show_label=False)
- )
+ #--Setting up views in TraitsUI--#
threed_group = Group(
- Item('scene', editor=SceneEditor(scene_class=MayaviScene),height=600, width=800, show_label=False),
+ HSplit(Item('Plot_3D', show_label=False),
+ Item('z_height', show_label=False)
+ ),
+ Item('scene', editor=SceneEditor(scene_class=MayaviScene), show_label=False),
label='3d graph'
)
@@ -237,26 +220,181 @@ class MainWindow(HasTraits):
label='log file'
)
- view = View(
-
+ plot_group = Group(
HSplit(
- buttons_group,
- Tabbed(
- threed_group,
- log_group,
+ VSplit(
+ (
+ Label('Hold Ctrl to zoom in plots'),
+ Item('plot2D', editor=ComponentEditor(), show_label=False),
+ (HSplit(Item('updateplots', show_label=False),Item('zoom_on'),Item('Plot_2D', show_label=False),Item('multiple_plots', show_label=False),Item('Normalise', show_label=False),Item('SVD', show_label=False),Item('EFA', show_label=False))
+ )
),
+ (Item('log',style='custom',show_label=False),
+ HSplit(Item('Save_log', show_label=False))),
+ ),
+ VSplit(
+ (
+ Item('plottime', editor=ComponentEditor(), show_label=False),
+ (HSplit(Item('Kinetic_Trace', show_label=False),Item('Fit_Trace', show_label=False),Item('mcmc',show_label=False),Item('DeleteTraces_1', show_label=False),Item('plotwaveindexshow', show_label=False, style='readonly'))),
+ Item('plotwaveindex', show_label=False, editor=RangeEditor(low_name='wavelow',high_name='wavehigh',format='%6f',label_width=waverange,mode='slider'))
+ ),
+ (
+ Item('plotwavelength', editor=ComponentEditor(), show_label=False),
+ (HSplit(Item('Spectra', show_label=False),Item('Fit_Spec', show_label=False),Item('DeleteSpectra_1', show_label=False),Item('plottimeindexshow',show_label=False,style='readonly'))),
+ Item('plottimeindex', show_label=False, editor=RangeEditor(low_name='timelow',high_name='timehigh',format='%d',label_width=timerange,mode='slider'))
+ ),
+ ),
),
+ label='2D plot'
+ )
+
+ view = View(
+ Group(HSplit(
+ Item('TrA_Raw_file', style = 'simple', show_label=False),
+ Item('Chirp_file', style = 'simple', show_label=False),
+ Item('Load_files', show_label=False),
+ Item('title', show_label=False)),
+ Tabbed(
+ plot_group,
+ threed_group
+ )),
+ menubar=MenuBar(Menu(
+ Action(name="Ohio data loader",action="_Ohioloader_fired"),
+ Action(name="Spreadsheet",action="_open_csv_fired"),
+ Action(name="Save csv",action="_Save_csv_fired"),
+ Action(name="Save as Glotaran",action="_Save_Glo_fired"),
+ Action(name="Delete multple traces",action="_DeleteTraces_fired"),
+ Action(name="Delete multple spectra",action="_Delete_spectra_fired"),
+ Action(name="Show python data",action='_showdata_fired'),
+ name="File"),
+ Menu(
+ Action(name="Plot chirp",action='_PlotChirp_fired'),
+ Action(name="Chirp correction",action='_Fix_Chirp_fired'),
+ Action(name="Shift time zero",action='_Shiftzero_fired'),
+ name="Chirp correction"
+ ),
+ Menu(
+ Action(name="Select traces",action='_Multiple_Trace_fired'),
+ Action(name="Plot traces",action='_Plot_Traces_fired'),
+ Action(name='Save traces to File',action='_savetraces_fired'),
+ Action(name='Send to Igor',action='_Trace_Igor_fired'),
+ name="Global fit"
+ ),
+ Menu(
+ Action(name="Help file", action='_Help_fired'),
+ name="Help"
+ )
+ ),
title = 'PyTrA', resizable=True,
)
+ def _plot2Db_fired(self):
+ '''
+ Plotting the 2D chaco plot
+ '''
+
+ #self.grid_data()
+
+ ds = ArrayPlotData()
+ ds.set_data('img',Data.TrA_Data)
+
+ img = Plot(ds)
+ cmapImgPlot = img.img_plot("img",colormap=jet,xbounds=(Data.wavelength[0],Data.wavelength[-1]),ybounds=(0,(len(Data.time)-1)))
+
+ self.plot2D = img
+
+ self.plot2D.x_axis.title="Wavelength (nm)"
+ self.plot2D.y_axis.title="Samples"
+
+ if self.zoom_on==True:
+ zoom = ZoomTool(component=img, tool_mode="box", always_on=True)
+ img.overlays.append(zoom)
+
+ img.tools.append(PanTool(img))
+
+ self._plottimeindex_changed()
+ self._plotwaveindex_changed()
+
+ def _zoom_on_changed(self):
+ self._updateplots_fired()
+
+ def _updateplots_fired(self):
+ #Don't regrid just reset 2D and 1D graphs
+ ds = ArrayPlotData()
+ ds.set_data('img',Data.TrA_Data)
+
+ img = Plot(ds)
+ cmapImgPlot = img.img_plot("img",colormap=jet,xbounds=(Data.wavelength[0],Data.wavelength[-1]),ybounds=(0,(len(Data.time)-1)))
+ self.plot2D = img
+
+ self.plot2D.x_axis.title="Wavelength (nm)"
+ self.plot2D.y_axis.title="Samples"
+
+ if self.zoom_on==True:
+ zoom = ZoomTool(component=img, tool_mode="box", always_on=True)
+ img.overlays.append(zoom)
+
+ img.tools.append(PanTool(img))
+
+ self._plottimeindex_changed()
+ self._plotwaveindex_changed()
+
+ def _plottimeindex_changed(self):
+ '''
+ Plotting the 1D spectra chaco plot
+ '''
+ index_time_left=self.plottimeindex
+
+ self.plottimeindexshow = Data.time[index_time_left]
+
+ dw = ArrayPlotData(x=Data.wavelength,y=Data.TrA_Data[index_time_left,:])
+ plot = Plot(dw)
+ plot.plot(("x","y"), line_width=1)
+
+ if self.zoom_on==True:
+ zoom = ZoomTool(component=img, tool_mode="box", always_on=True)
+ img.overlays.append(zoom)
+
+ plot.tools.append(PanTool(plot))
+
+ self.plotwavelength = plot
+ self.plotwavelength.y_axis.title="Abs."
+ self.plotwavelength.x_axis.title="Wavelength (nm)"
+
+ def _plotwaveindex_changed(self):
+ '''
+ Plotting the 1D kinetic chaco plot
+ '''
+
+ index_wave_left=(abs(Data.wavelength-float(self.plotwaveindex))).argmin()
+
+ self.plotwaveindexshow = Data.wavelength[index_wave_left]
+
+ dt = ArrayPlotData(x=Data.time,y=Data.TrA_Data[:,index_wave_left])
+ plot = Plot(dt)
+ plot.plot(("x","y"), line_width=1)
+
+ if self.zoom_on==True:
+ zoom = ZoomTool(component=img, tool_mode="box", always_on=True)
+ img.overlays.append(zoom)
+
+ plot.tools.append(PanTool(plot))
+
+ self.plottime = plot
+ self.plottime.y_axis.title="Abs."
+ self.plottime.x_axis.title="Time (ps)"
+
def _Load_files_fired(self):
+ '''
+ Loads in all the files for PyTrA
+ '''
# Load TrA file into array depends on extension
Data.filename = self.TrA_Raw_file
- TrA_Raw_file_name, TrA_Raw_file_extension = os.path.splitext(self.TrA_Raw_file)
- TrA_Raw_file_dir, TrA_Raw_file_name = os.path.split(self.TrA_Raw_file)
- TrA_Raw_name, TrA_Raw_ex = os.path.splitext(TrA_Raw_file_name)
+ TrA_Raw_file_name, TrA_Raw_file_extension = splitext(self.TrA_Raw_file)
+ TrA_Raw_file_dir, TrA_Raw_file_name = split(self.TrA_Raw_file)
+ TrA_Raw_name, TrA_Raw_ex = splitext(TrA_Raw_file_name)
self.title = TrA_Raw_name
if TrA_Raw_file_extension == '.csv':
@@ -279,8 +417,8 @@ def _Load_files_fired(self):
# deleting last time if equal to zero this occurs if data is saved in excel
if Data.TrA_Data[-1,0]==0:
- Data.TrA_Data=Data.TrA_Data[0:-1,:]
- Data.time=Data.time[0:-1]
+ Data.TrA_Data=Data.TrA_Data[0:-2,:]
+ Data.time=Data.time[0:-2]
#Sort data into correct order
inds = Data.wavelength.argsort()
@@ -290,11 +428,21 @@ def _Load_files_fired(self):
indst = Data.time.argsort()
Data.TrA_Data = Data.TrA_Data[indst,:]
Data.time = Data.time[indst]
+ self.timelist = Data.time.tolist()
+
+ self.wavelow = float(Data.wavelength[0])
+ self.wavehigh = float(Data.wavelength[-1])
+ self.waverange = len(Data.wavelength)
+ self.timelow = int(0)
+ self.timehigh = len(Data.time)-1
+ self.timerange = len(Data.time)
+ self.plottimeindex = float(Data.time[0])
+ self.plotwaveindex = float(Data.wavelength[0])
# Importing Chirp data
try:
- Chirp_file_name, Chirp_file_extension = os.path.splitext(self.Chirp_file)
+ Chirp_file_name, Chirp_file_extension = splitext(self.Chirp_file)
if Chirp_file_extension == '.csv':
Chirp_Raw_T = genfromtxt(self.Chirp_file, delimiter=',', filling_values='0')
@@ -310,273 +458,323 @@ def _Load_files_fired(self):
Data.Chirp = Chirp_Raw[1:Chirp_Raw_m,1:Chirp_Raw_n]
except:
- self.log=("%s \nNo Chirp found"%(self.log))
+ self.log=("%s\nNo Chirp found"%(self.log))
+
+ # Update chaco plot
+ self._plot2Db_fired()
+
+ self.log=("%s\nData file imported of size t=%s and wavelength=%s name=%s" %(self.log,Data.TrA_Data.shape[0],Data.TrA_Data.shape[1],TrA_Raw_name))
- self.log=('%s\nData file imported of size t=%s and wavelength=%s name=%s' %(self.log,Data.TrA_Data.shape[0],Data.TrA_Data.shape[1],TrA_Raw_name))
+ def _showdata_fired(self):
+ Dataviewer().edit_traits()
+
+ def _open_csv_fired(self):
+ '''
+ Opens the file in the original
+ '''
+ startfile(self.TrA_Raw_file)
def _Ohioloader_fired(self):
ohio = OhioLoader().edit_traits()
- self.log = ('%s \nData file imported of size %s by %s' %(self.log,Data.TrA_Data.shape[0],Data.TrA_Data.shape[1]))
- def _fft_filter_fired(self):
- fft_live = FFTfilter().edit_traits()
+ # Update chaco plot
+ self._plot2Db_fired()
+
+ self.log = ('%s\nData file imported of size %s by %s' %(self.log,Data.TrA_Data.shape[0],Data.TrA_Data.shape[1]))
def _Shiftzero_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength, Data.time[1:20], Data.TrA_Data[1:20,:], 100)
- plt.title('Pick time zero')
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- fittingto = np.array(ginput(1))
- plt.show()
- plt.close()
+ figure()
+ contourf(Data.wavelength, Data.time[1:20], Data.TrA_Data[1:20,:], 100)
+ title('Pick time zero')
+ xlabel('Wavelength')
+ ylabel('Time')
+ fittingto = array(ginput(1))
+ show()
+ close()
Data.time = Data.time-fittingto[0][1]
- self.log = "%s \nDeleted traces between %s and %s" %(self.log,fittingto[0,0],fittingto[1,0])
+ # Update chaco plot
+ self._plot2Db_fired()
+
+ self.log = "%s\nShifted time by %s" %(self.log,fittingto[0][1])
def _DeleteTraces_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
- plt.title('Pick between wavelength to delete (left to right)')
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- fittingto = np.array(ginput(2))
- plt.show()
- plt.close()
+ figure()
+ contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
+ title('Pick between wavelength to delete (left to right)')
+ xlabel('Wavelength')
+ ylabel('Time')
+ fittingto = array(ginput(2))
+ show()
+ close()
- index_wavelength_left=(np.abs(Data.wavelength-fittingto[0,0])).argmin()
- index_wavelength_right=(np.abs(Data.wavelength-fittingto[1,0])).argmin()+1
+ index_wavelength_left=(abs(Data.wavelength-fittingto[0,0])).argmin()
+ index_wavelength_right=(abs(Data.wavelength-fittingto[1,0])).argmin()+1
+ Data.TrA_Data = delete(Data.TrA_Data,arange(index_wavelength_left,index_wavelength_right,1),1)
+ Data.wavelength = delete(Data.wavelength,arange(index_wavelength_left,index_wavelength_right,1))
- if index_wavelength_right <= index_wavelength_left:
- hold = index_wavelength_left
- index_wavelength_left = index_wavelength_right
- index_wavelength_right = hold
+ self.wavelow = float(Data.wavelength[0])
+ self.wavehigh = float(Data.wavelength[-1])
+ self.waverange = len(Data.wavelength)
- if index_wavelength_left == 0:
- Data.TrA_Data = Data.TrA_Data[:,index_wavelength_right:]
- Data.wavelength = Data.wavelength[index_wavelength_right:]
+ # Update chaco plot
+ self._plot2Db_fired()
- if index_wavelength_right == Data.wavelength.shape:
- Data.TrA_Data = Data.TrA_Data[:,:index_wavelength_left]
- Data.wavelength = Data.wavelength[:index_wavelength_left]
+ self.log = "%s\n \nDeleted traces %s and %s" %(self.log,fittingto[0,0],fittingto[1,0])
- if index_wavelength_left != 0 & index_wavelength_right != Data.wavelength.shape:
- Data.TrA_Data = np.hstack((Data.TrA_Data[:,:index_wavelength_left],Data.TrA_Data[:,index_wavelength_right:]))
- Data.wavelength = np.hstack((Data.wavelength[:index_wavelength_left],Data.wavelength[index_wavelength_right:]))
+ def _Delete_spectra_fired(self):
+ '''
+ Delete rows
+ '''
+ figure()
+ contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
+ title('Pick between times to delete (top to bottom)')
+ xlabel('Wavelength')
+ ylabel('Time')
+ fittingto = array(ginput(2))
+ show()
+ close()
- self.log = "%s \nDeleted traces between %s and %s" %(self.log,fittingto[0,0],fittingto[1,0])
+ index_time_top=(abs(Data.time-fittingto[1,1])).argmin()
+ index_time_bottom=(abs(Data.time-fittingto[0,1])).argmin()
- def _Delete_spectra_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
- plt.title('Pick between times to delete (top to bottom)')
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- fittingto = np.array(ginput(2))
- plt.show()
- plt.close()
+ Data.TrA_Data = delete(Data.TrA_Data,arange(index_time_top,index_time_bottom,1),0)
+ Data.time = delete(Data.time,arange(index_time_top,index_time_bottom,1))
- index_time_top=(np.abs(Data.time-fittingto[1,1])).argmin()
- index_time_bottom=(np.abs(Data.time-fittingto[0,1])).argmin()+1
+ self.timelow = float(0)
+ self.timehigh = len(Data.time)-1
+ self.timerange = len(Data.time)
- if index_time_bottom <= index_time_top:
- hold = index_time_top
- index_time_top = index_time_bottom
- index_time_bottom = hold
+ # Update chaco plot
+ self._plot2Db_fired()
- if index_time_top == 0:
- Data.TrA_Data = Data.TrA_Data[index_time_bottom:,:]
- Data.time = Data.time[index_time_bottom:]
+ self.log = "%s\n \nDeleted spectra between %s and %s" %(self.log,fittingto[0,1],fittingto[1,1])
- if index_time_bottom == Data.time.shape:
- Data.TrA_Data = Data.TrA_Data[:index_time_top,:]
- Data.time = Data.time[:index_time_top]
+ def _DeleteSpectra_1_fired(self):
+ '''
+ Delete single spectrum
+ '''
- if index_time_top != 0 & index_time_bottom != Data.time.shape:
- Data.TrA_Data = np.vstack((Data.TrA_Data[:index_time_top,:],Data.TrA_Data[index_time_bottom:,:]))
- Data.time = np.hstack((Data.time[:index_time_top],Data.time[index_time_bottom:]))
+ index_time_left=self.plottimeindex
+ time_val = Data.time[index_time_left]
- self.log = "%s \nDeleted spectra between %s and %s" %(self.log,fittingto[0,1],fittingto[1,1])
+ Data.TrA_Data = delete(Data.TrA_Data,index_time_left,0)
+ Data.time = delete(Data.time,index_time_left)
- def _PlotChirp_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength_C, Data.time_C, Data.Chirp, 100)
- plt.title('%s Chirp' %(self.title))
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- plt.show()
+ self.timelow = float(0)
+ self.timehigh = len(Data.time)-1
+ self.timerange = len(Data.time)
+
+ # Update chaco plot
+ self._plot2Db_fired()
+
+ self.log = "%s\nDeleted spectrum %s" %(self.log,time_val)
+
+ def _DeleteTraces_1_fired(self):
+ '''
+ Delete single trace
+ '''
+
+ index_wave_left=(abs(Data.wavelength-float(self.plotwaveindex))).argmin()
+
+ wave_val = Data.wavelength[index_wave_left]
+
+ Data.TrA_Data = delete(Data.TrA_Data,index_wave_left,1)
+ Data.wavelength = delete(Data.wavelength,index_wave_left)
+
+ self.wavelow = float(Data.wavelength[0])
+ self.wavehigh = float(Data.wavelength[-1])
+ self.waverange = len(Data.wavelength)
- def _Timelim_changed(self):
- Data.Range = self.Timelim
+ # Update chaco plot
+ self._plot2Db_fired()
+
+ self.log = "%s\nDeleted trace at %s" %(self.log,wave_val)
+
+ def _PlotChirp_fired(self):
+ figure()
+ contourf(Data.wavelength_C, Data.time_C, Data.Chirp, 100)
+ title('Zoom into region you want to fit chirp')
+ xlabel('Wavelength (nm)')
+ ylabel('Time (ps)')
+ show()
def _Fix_Chirp_fired(self):
+
+ try:
+ ymin, ymax = ylim()
+
+ except:
+ self.log = "%s\nPlot the chirp and zoom into the area you want to fit to" %(self.log)
+
#plot file and pick points for graphing
- plt.figure(figsize=(20,12))
- plt.title('Pick 8 points')
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- plt.contourf(Data.wavelength_C, Data.time_C, Data.Chirp, 20)
- plt.ylim((Data.Range[0][0],Data.Range[0][1]))
- polypts = np.array(ginput(8))
- plt.show()
- plt.close()
+ figure(figsize=(20,12))
+ title('Pick 8 points on the chirp')
+ xlabel('Wavelength')
+ ylabel('Time')
+ contourf(Data.wavelength_C, Data.time_C, Data.Chirp, 20)
+ ylim((ymin,ymax))
+ polypts = array(ginput(8))
+ show()
+ close()
#Fit a polynomial of the form p(x) = p[2] + p[1] + p[0]
- fitcoeff, residuals, rank, singular_values, rcond = np.polyfit(polypts[:, 0], polypts[:, 1], 2, full=True)
+ fitcoeff, residuals, rank, singular_values, rcond = polyfit(polypts[:, 0], polypts[:, 1], 2, full=True)
- stdev = np.sum(residuals**2)/8
+ stdev = sum(residuals**2)/8
#finding where zero time is
- idx=(np.abs(Data.time-0)).argmin()
- plt.figure(figsize=(20,12))
- plt.title("Pick point on wave front")
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- plt.contourf(Data.wavelength, Data.time[idx-1:idx+10], Data.TrA_Data[idx-1:idx+10,:], 100)
- fittingto = np.array(ginput(1)[0])
- plt.show()
- plt.close()
+ figure(figsize=(20,12))
+ title("Pick point on wave front")
+ xlabel('Wavelength')
+ ylabel('Time')
+ contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
+ ylim((-2,2))
+ fittingto = array(ginput(1)[0])
+ show()
+ close()
#Moves the chirp inorder to correct coefficient
- fitcoeff[2] = (fitcoeff[0]*fittingto[0]**2 + fitcoeff[1]*fittingto[0] + fittingto[1])*-1
+ fitcoeff[2] = (-fitcoeff[0]*fittingto[0]**2 - fitcoeff[1]*fittingto[0] + fittingto[1])
#Iterate over the wavelengths and interpolate for the corrected values
for i in range(0, len(Data.wavelength), 1):
- correcttimeval = np.polyval(fitcoeff, Data.wavelength[i])
+ correcttimeval = polyval(fitcoeff, Data.wavelength[i])
f = interpolate.interp1d((Data.time-correcttimeval), (Data.TrA_Data[:, i]), bounds_error=False, fill_value=0)
fixed_wave = f(Data.time)
Data.TrA_Data[:, i] = fixed_wave
- self.log = "%s \nPolynomial fit with form %s*x^2 + %s*x + %s stdev %s" %(self.log,fitcoeff[0],fitcoeff[1],fitcoeff[2],stdev)
+ # Update chaco plot
+ self._plot2Db_fired()
- def _Fit_Trace_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
- plt.title('Pick wavelength to fit')
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- fittingto = np.array(ginput(1))
- plt.show()
- plt.close()
+ self.log = "%s\n \nPolynomial fit with form %s*x^2 + %s*x + %s stdev %s" %(self.log,fitcoeff[0],fitcoeff[1],fitcoeff[2],stdev)
- index_wavelength=(np.abs(Data.wavelength-fittingto[:,0])).argmin()
- Data.tracefitmodel = fitgui.fit_data(Data.time,Data.TrA_Data[:,index_wavelength],autoupdate=False,model=Convoluted_exp1,include_models='Convoluted_exp1,Convoluted_exp2,Convoluted_exp3,Convoluted_exp4')
+ def _Fit_Trace_fired(self):
- #If you want to have the fitting gui in another window while PyTrA remains responsive change the fit model to a model instance and use the line bellow to call it
- #Data.tracefitmodel.edit_traits()
+ index_wavelength=(abs(Data.wavelength-self.plotwaveindex)).argmin()
+ Data.tracefitmodel = fitgui.fit_data(Data.time,Data.TrA_Data[:,index_wavelength],autoupdate=False,model=Convoluted_exp1)
results_error = Data.tracefitmodel.getCov().diagonal()
results_par = Data.tracefitmodel.params
results = Data.tracefitmodel.parvals
- self.log= ('%s \nFitted parameters at wavelength %s \nFitting parameters'%(self.log,fittingto[:,0]))
+ self.log= ('%s\n \nFitted parameters at wavelength %s \nFitting parameters'%(self.log,Data.wavelength[index_wavelength]))
+
+ # Update chaco plot
+ self._plot2Db_fired()
for i in range(len(results)):
- self.log = ('%s \n%s = %s +- %s'%(self.log,results_par[i],results[i],results_error[i]))
+ self.log = ('%s\n%s = %s +- %s'%(self.log,results_par[i],results[i],results_error[i]))
- def _mcmc_fired(self):
- mcmc_app = mcmc.MCMC(parameters=[ mcmc.Params(name=i) for i in Data.tracefitmodel.params])
- mcmc_app.edit_traits()
- mcmc_app = mcmc.MCMC(parameters=[])
+ def _Fit_Spec_fired(self):
- def _Global_fired(self):
- global_app = glo.Global(parameters=[ glo.Params(name=i) for i in Data.tracefitmodel.params])
- global_app.edit_traits()
- global_app = glo.Global(parameters=[])
+ index_time=self.plottimeindex
+ Data.tracefitmodel = fitgui.fit_data(Data.wavelength,Data.TrA_Data[index_time,:],autoupdate=False,model=Gauss_1)
- def _SVD_fired(self):
+ results_error = Data.tracefitmodel.getCov().diagonal()
+ results_par = Data.tracefitmodel.params
+ results = Data.tracefitmodel.parvals
- try:
- plt.fignum_exists()
- xmin, xmax = plt.xlim()
- ymin, ymax = plt.ylim()
+ self.log= ('%s\n \nFitted parameters at time %s \nFitting parameters'%(self.log,Data.time[index_time]))
- index_wavelength_left=(np.abs(Data.wavelength-xmin)).argmin()
- index_wavelength_right=(np.abs(Data.wavelength-xmax)).argmin()
+ for i in range(len(results)):
+ self.log = ('%s\n%s = %s +- %s'%(self.log,results_par[i],results[i],results_error[i]))
- index_time_left=(np.abs(Data.time-ymin)).argmin()
- index_time_right=(np.abs(Data.time-ymax)).argmin()
- except:
- index_wavelength_left=0
- index_wavelength_right=Data.wavelength[-1]
+ def _mcmc_fired(self):
+ mcmc_app = mcmc.MCMC_1(parameters=[ mcmc.Params(name=i) for i in Data.tracefitmodel.params])
+ mcmc_app.edit_traits(kind='livemodal')
+ mcmc_app = mcmc.MCMC_1(parameters=[])
+ self.log = ('%s\n \n---MCMC sampler summary (pymc)---\nBayesian Information Criterion = %s'%(self.log,Data.mcmc['MAP']))
+ for i in Data.tracefitmodel.params:
+ self.log = ('%s\n%s,mean %s,stdev %s'%(self.log,i,Data.mcmc['MCMC'].stats()[i]['mean'],Data.mcmc['MCMC'].stats()[i]['standard deviation']))
+ self.log = ('%s\nsigma,mean %s,stdev %s'%(self.log,Data.mcmc['MCMC'].stats()['sig']['mean'],Data.mcmc['MCMC'].stats()['sig']['standard deviation']))
+
+ def _SVD_fired(self):
- index_time_left=0
- index_time_right=Data.wavelength[-1]
+ xmin=self.plot2D.range2d.x_range.low
+ xmax=self.plot2D.range2d.x_range.high
+ ymin=self.plot2D.range2d.y_range.low
+ ymax=self.plot2D.range2d.y_range.high
+ index_wavelength_left=(abs(Data.wavelength-xmin)).argmin()
+ index_wavelength_right=(abs(Data.wavelength-xmax)).argmin()
+
+ index_time_left=(abs(Data.time-ymin)).argmin()
+ index_time_right=(abs(Data.time-ymax)).argmin()
U, s, V_T = linalg.svd(Data.TrA_Data[index_time_left:index_time_right,index_wavelength_left:index_wavelength_right])
- f=plt.figure()
+ f=figure()
f.text(0.5,0.975,("SVD %s" %(self.title)),horizontalalignment='center',verticalalignment='top')
- plt.subplot(341)
- plt.plot(Data.time[index_time_left:index_time_right],U[:,0])
- plt.title("1")
- plt.xlabel("time (ps)")
- plt.ylabel("abs.")
- plt.subplot(342)
- plt.plot(Data.time[index_time_left:index_time_right],U[:,1])
- plt.title("2")
- plt.xlabel("time (ps)")
- plt.ylabel("abs.")
- plt.subplot(343)
- plt.plot(Data.time[index_time_left:index_time_right],U[:,2])
- plt.title("3")
- plt.xlabel("time (ps)")
- plt.ylabel("abs.")
- plt.subplot(344)
- plt.plot(Data.time[index_time_left:index_time_right],U[:,3])
- plt.title("4")
- plt.xlabel("time (ps)")
- plt.ylabel("abs.")
- plt.subplot(345)
- plt.plot(Data.wavelength[index_wavelength_left:index_wavelength_right],V_T[0,:])
- plt.title("%s" %(s[0]))
- plt.xlabel("wavelength (nm)")
- plt.ylabel("abs.")
- plt.subplot(346)
- plt.plot(Data.wavelength[index_wavelength_left:index_wavelength_right],V_T[1,:])
- plt.title("%s" %(s[1]))
- plt.xlabel("wavelength (nm)")
- plt.ylabel("abs.")
- plt.subplot(347)
- plt.plot(Data.wavelength[index_wavelength_left:index_wavelength_right],V_T[2,:])
- plt.title("%s" %(s[2]))
- plt.xlabel("wavelength (nm)")
- plt.ylabel("abs.")
- plt.subplot(348)
- plt.plot(Data.wavelength[index_wavelength_left:index_wavelength_right],V_T[3,:])
- plt.title("%s" %(s[3]))
- plt.xlabel("wavelength (nm)")
- plt.ylabel("abs.")
- plt.subplot(349)
- [SVD_1_x,SVD_1_y]=np.meshgrid(V_T[0,:],U[:,0])
- SVD_1 = np.multiply(SVD_1_x,SVD_1_y)*s[0]
- plt.contourf(Data.wavelength[index_wavelength_left:index_wavelength_right],Data.time[index_time_left:index_time_right],SVD_1,50)
- plt.subplot(3,4,10)
- [SVD_2_x,SVD_2_y]=np.meshgrid(V_T[1,:],U[:,1])
- SVD_2 = np.multiply(SVD_2_x,SVD_2_y)*s[1]
- plt.contourf(Data.wavelength[index_wavelength_left:index_wavelength_right],Data.time[index_time_left:index_time_right],SVD_2,50)
- plt.subplot(3,4,11)
- [SVD_3_x,SVD_3_y]=np.meshgrid(V_T[2,:],U[:,2])
- SVD_3 = np.multiply(SVD_3_x,SVD_3_y)*s[2]
- plt.contourf(Data.wavelength[index_wavelength_left:index_wavelength_right],Data.time[index_time_left:index_time_right],SVD_3,50)
- plt.subplot(3,4,12)
- [SVD_4_x,SVD_4_y]=np.meshgrid(V_T[3,:],U[:,3])
- SVD_4 = np.multiply(SVD_4_x,SVD_4_y)*s[3]
- plt.contourf(Data.wavelength[index_wavelength_left:index_wavelength_right],Data.time[index_time_left:index_time_right],SVD_4,50)
- plt.subplots_adjust(left=0.03, bottom=0.05, right=0.99, top=0.94, wspace=0.2, hspace=0.2)
- plt.show()
-
- plt.figure()
- plt.semilogy(s[0:9],'*')
- plt.title("First 10 singular values")
- plt.show()
-
- self.log = "%s \nFirst 5 singular values %s in range wavelength %s to %s, time %s to %s" %(self.log,s[0:5], xmin, xmax, ymin, ymax)
+ subplot(341)
+ plot(Data.time[index_time_left:index_time_right],U[:,0])
+ title("1")
+ xlabel("time (ps)")
+ ylabel("abs.")
+ subplot(342)
+ plot(Data.time[index_time_left:index_time_right],U[:,1])
+ title("2")
+ xlabel("time (ps)")
+ ylabel("abs.")
+ subplot(343)
+ plot(Data.time[index_time_left:index_time_right],U[:,2])
+ title("3")
+ xlabel("time (ps)")
+ ylabel("abs.")
+ subplot(344)
+ plot(Data.time[index_time_left:index_time_right],U[:,3])
+ title("4")
+ xlabel("time (ps)")
+ ylabel("abs.")
+ subplot(345)
+ plot(Data.wavelength[index_wavelength_left:index_wavelength_right],V_T[0,:])
+ title("%s" %(s[0]))
+ xlabel("wavelength (nm)")
+ ylabel("abs.")
+ subplot(346)
+ plot(Data.wavelength[index_wavelength_left:index_wavelength_right],V_T[1,:])
+ title("%s" %(s[1]))
+ xlabel("wavelength (nm)")
+ ylabel("abs.")
+ subplot(347)
+ plot(Data.wavelength[index_wavelength_left:index_wavelength_right],V_T[2,:])
+ title("%s" %(s[2]))
+ xlabel("wavelength (nm)")
+ ylabel("abs.")
+ subplot(348)
+ plot(Data.wavelength[index_wavelength_left:index_wavelength_right],V_T[3,:])
+ title("%s" %(s[3]))
+ xlabel("wavelength (nm)")
+ ylabel("abs.")
+ subplot(349)
+ [SVD_1_x,SVD_1_y]=meshgrid(V_T[0,:],U[:,0])
+ SVD_1 = multiply(SVD_1_x,SVD_1_y)*s[0]
+ contourf(Data.wavelength[index_wavelength_left:index_wavelength_right],Data.time[index_time_left:index_time_right],SVD_1,50)
+ subplot(3,4,10)
+ [SVD_2_x,SVD_2_y]=meshgrid(V_T[1,:],U[:,1])
+ SVD_2 = multiply(SVD_2_x,SVD_2_y)*s[1]
+ contourf(Data.wavelength[index_wavelength_left:index_wavelength_right],Data.time[index_time_left:index_time_right],SVD_2,50)
+ subplot(3,4,11)
+ [SVD_3_x,SVD_3_y]=meshgrid(V_T[2,:],U[:,2])
+ SVD_3 = multiply(SVD_3_x,SVD_3_y)*s[2]
+ contourf(Data.wavelength[index_wavelength_left:index_wavelength_right],Data.time[index_time_left:index_time_right],SVD_3,50)
+ subplot(3,4,12)
+ [SVD_4_x,SVD_4_y]=meshgrid(V_T[3,:],U[:,3])
+ SVD_4 = multiply(SVD_4_x,SVD_4_y)*s[3]
+ contourf(Data.wavelength[index_wavelength_left:index_wavelength_right],Data.time[index_time_left:index_time_right],SVD_4,50)
+ subplots_adjust(left=0.03, bottom=0.05, right=0.99, top=0.94, wspace=0.2, hspace=0.2)
+ show()
+
+ figure()
+ semilogy(s[0:9],'*')
+ title("First 10 singular values")
+ show()
+
+ self.log = "%s\nFirst 5 singular values %s in range wavelength %s to %s, time %s to %s" %(self.log,s[0:5], xmin, xmax, ymin, ymax)
def _EFA_fired(self):
@@ -585,8 +783,8 @@ def _EFA_fired(self):
#Time
rows = Data.TrA_Data.shape[0]
- forward_r = np.zeros((rows,singvals))
- backward_r = np.zeros((rows,singvals))
+ forward_r = zeros((rows,singvals))
+ backward_r = zeros((rows,singvals))
stepl_r = rows-singvals
#Forward
@@ -603,18 +801,18 @@ def _EFA_fired(self):
partsvd = linalg.svdvals(Data.TrA_Data[j:,:]).T
backward_r[j,:] = partsvd[:singvals]
- plt.figure()
- plt.semilogy(Data.time[singvals:],forward_r[singvals:,:],'b',Data.time[:(rows-singvals)],backward_r[:(rows-singvals),:],'r')
- plt.title("%s EFA time" %(self.title))
- plt.xlabel("Time (ps)")
- plt.ylabel("Log(EV)")
- plt.show()
+ figure()
+ semilogy(Data.time[singvals:],forward_r[singvals:,:],'b',Data.time[:(rows-singvals)],backward_r[:(rows-singvals),:],'r')
+ title("%s EFA time" %(self.title))
+ xlabel("Time (ps)")
+ ylabel("Log(EV)")
+ show()
#Wavelength
cols = Data.TrA_Data.shape[1]
- forward_c = np.zeros((cols,singvals))
- backward_c = np.zeros((cols,singvals))
+ forward_c = zeros((cols,singvals))
+ backward_c = zeros((cols,singvals))
stepl_c = cols-singvals
#Forward
@@ -631,327 +829,266 @@ def _EFA_fired(self):
partsvd = linalg.svdvals(Data.TrA_Data[:,j:])
backward_c[j,:] = partsvd[:singvals]
- plt.figure()
- plt.semilogy(Data.wavelength[singvals:],forward_c[singvals:,:],'b',Data.wavelength[:cols-singvals],backward_c[:cols-singvals,:],'r')
- plt.title("%s EFA wavelength" %(self.title))
- plt.xlabel("Wavelength (nm)")
- plt.ylabel("Log(EV)")
- plt.show()
+ figure()
+ semilogy(Data.wavelength[singvals:],forward_c[singvals:,:],'b',Data.wavelength[:cols-singvals],backward_c[:cols-singvals,:],'r')
+ title("%s EFA wavelength" %(self.title))
+ xlabel("Wavelength (nm)")
+ ylabel("Log(EV)")
+ show()
def _Multiple_Trace_fired(self):
self.Traces_num = 0
Data.Traces = 0
- plt.figure(figsize=(15,10))
- plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
- plt.title('Pick between wavelength to fit (left to right)')
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- fittingto = np.array(ginput(2))
- plt.show()
- plt.close()
+ figure(figsize=(15,10))
+ contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
+ title('Pick between wavelength to fit (left to right)')
+ xlabel('Wavelength')
+ ylabel('Time')
+ fittingto = array(ginput(2))
+ show()
+ close()
- index_wavelength_left=(np.abs(Data.wavelength-fittingto[0,0])).argmin()
- index_wavelength_right=(np.abs(Data.wavelength-fittingto[1,0])).argmin()
+ index_wavelength_left=(abs(Data.wavelength-fittingto[0,0])).argmin()
+ index_wavelength_right=(abs(Data.wavelength-fittingto[1,0])).argmin()
Data.Traces = Data.TrA_Data[:,index_wavelength_left:index_wavelength_right].transpose()
- self.log= '%s \n%s Traces saved from %s to %s' %(self.log,Data.Traces.shape[0], fittingto[0,0], fittingto[1,0])
+ self.log= '%s\n\n%s Traces saved from %s to %s' %(self.log,Data.Traces.shape[0], fittingto[0,0], fittingto[1,0])
- def _Plot_3D_fired(self):
+ def grid_data(self):
+ '''
+ Populate the Data.TrA_Data_gridded for 3D plot and chaco plot
+ '''
+ Data.TrA_Data_gridded = array([])
- try:
- plt.fignum_exists()
- xmin, xmax = plt.xlim()
- ymin, ymax = plt.ylim()
+ #Gets smallest spacing to use to construct mesh
+ y_step = Data.time[(abs(Data.time-0)).argmin()+1]-Data.time[(abs(Data.time-0)).argmin()]
- index_wavelength_left=(np.abs(Data.wavelength-xmin)).argmin()
- index_wavelength_right=(np.abs(Data.wavelength-xmax)).argmin()
+ x = linspace(Data.wavelength[0],Data.wavelength[-1],len(Data.wavelength))
+ y = arange(Data.time[0], Data.time[-1],y_step)
- index_time_left=(np.abs(Data.time-ymin)).argmin()
- index_time_right=(np.abs(Data.time-ymax)).argmin()
- except:
- index_wavelength_left=0
- index_wavelength_right=Data.wavelength[-1]
+ [xi,yi] = meshgrid(x,y)
- index_time_left=0
- index_time_right=Data.wavelength[-1]
+ Data.xi = xi
+ Data.yi = yi
- Data.Three_d = Data.TrA_Data[index_time_left:index_time_right,index_wavelength_left:index_wavelength_right]
- Data.Three_d_wavelength = Data.wavelength[index_wavelength_left:index_wavelength_right]
- Data.Three_d_time = Data.time[index_time_left:index_time_right]
+ Data.TrA_Data_gridded = xi
- self.scene.mlab.clf()
-
- x = np.linspace(Data.Three_d_wavelength[0],Data.Three_d_wavelength[-1],len(Data.Three_d_wavelength))
- y = np.linspace(Data.Three_d_time[0], Data.Three_d_time[-1],len(Data.Three_d_wavelength))
- [xi,yi] = np.meshgrid(x,y)
+ vectors = array([[0],[0],[0]])
- for i in range(len(Data.Three_d_wavelength)):
- repeating_wavelength = np.array(np.ones((len(Data.Three_d_time)))*Data.Three_d_wavelength[i])
- vectors = np.array([Data.Three_d_time,repeating_wavelength,Data.Three_d[:,i]])
+ # Create the x, y, z vectors
+ for i in range(len(Data.wavelength)):
+ repeating_wavelength = array(ones((len(Data.time)))*Data.wavelength[i])
+ vectors_temp = array([Data.time,repeating_wavelength,Data.TrA_Data[:,i]])
if i==0:
- Data.TrA_Data_gridded = vectors
+ vectors = vectors_temp
else:
- Data.TrA_Data_gridded = np.hstack((Data.TrA_Data_gridded, vectors))
+ vectors = hstack((vectors, vectors_temp))
- zi = interpolate.griddata((Data.TrA_Data_gridded[1,:],Data.TrA_Data_gridded[0,:]),Data.TrA_Data_gridded[2,:],(xi,yi), method='linear', fill_value=0)
+ Data.TrA_Data_gridded = interpolate.griddata((vectors[1,:],vectors[0,:]),vectors[2,:],(xi,yi), method='linear', fill_value=0)
+
+ def _Plot_3D_fired(self):
+
+ self.scene.mlab.clf()
+ self.grid_data()
#Sends 3D plot to mayavi in gui
#uncomment for plotting actual data matrix
#self.scene.mlab.surf(Data.time,Data.wavelength,Data.TrA_Data,warp_scale=-self.z_height*100)
-
#gridded plot which gives correct view
- self.plot = self.scene.mlab.surf(yi,xi,zi, warp_scale=-self.z_height*100)
+ self.scene.mlab.surf(Data.yi,Data.xi,Data.TrA_Data_gridded, warp_scale=-self.z_height*100)
self.scene.mlab.colorbar(orientation="vertical")
self.scene.mlab.axes(nb_labels=5,)
self.scene.mlab.ylabel("wavelength (nm)")
self.scene.mlab.xlabel("time (ps)")
def _z_height_changed(self):
- # Need to work out how to just modify the the warp scalar without redrawing
- self._Plot_3D_fired()
+ # Only redraws it so does not have to regrid
+ self.scene.mlab.clf()
+ self.scene.mlab.surf(Data.yi,Data.xi,Data.TrA_Data_gridded, warp_scale=-self.z_height*100)
+ self.scene.mlab.colorbar(orientation="vertical")
+ self.scene.mlab.axes(nb_labels=5,)
+ self.scene.mlab.axes(z_axis_visibility=False)
+ self.scene.mlab.ylabel("wavelength (nm)")
+ self.scene.mlab.xlabel("time (ps)")
def _Plot_2D_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 200)
- plt.xlabel('Wavelength (nm)')
- plt.ylabel('Times (ps)')
- plt.title(self.title)
- plt.colorbar()
- plt.show()
-
- def _Plot_log_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
- plt.xlabel('Wavelength (nm)')
- plt.ylabel('Times (ps)')
- plt.title(self.title)
- plt.colorbar()
- plt.yscale('symlog',basey=10,linthreshy=(-100,-0.1),subsy=[0,1,2,3,4])
- plt.show()
-
+ figure()
+ contourf(Data.wavelength, Data.time, Data.TrA_Data, 200)
+ xlabel('Wavelength (nm)')
+ ylabel('Times (ps)')
+ title(self.title)
+ colorbar()
+ show()
def _Plot_Traces_fired(self):
- plt.figure(figsize=(15,10))
- plt.plot(Data.time, Data.Traces.transpose())
- plt.title("%s Traces" %(self.title))
- plt.xlabel('Time')
- plt.ylabel('Abs')
- plt.show()
+ figure(figsize=(15,10))
+ plot(Data.time, Data.Traces.transpose() )
+ title("%s Traces" %(self.title))
+ xlabel('Time')
+ ylabel('Abs')
+ show()
def _Kinetic_Trace_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
- plt.title('Pick wavelength')
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- fittingto = np.array(ginput(1))
- plt.show()
- plt.close()
-
- index_wavelength=(np.abs(Data.wavelength-fittingto[:,0])).argmin()
+ index_wavelength=(abs(Data.wavelength-float(self.plotwaveindex))).argmin()
- plt.figure(figsize=(20,12))
- plt.plot(Data.time, Data.TrA_Data[:,index_wavelength])
- plt.title("%s %s" %(self.title, Data.wavelength[index_wavelength]))
- plt.xlabel('Time')
- plt.ylabel('Abs')
- plt.show()
+ figure(figsize=(20,12))
+ plot(Data.time, Data.TrA_Data[:,index_wavelength] )
+ title("%s %s" %(self.title, Data.wavelength[index_wavelength]))
+ xlabel('Time')
+ ylabel('Abs')
+ show()
def _Spectra_fired(self):
- plt.figure()
- plt.contourf(Data.wavelength, Data.time, Data.TrA_Data, 100)
- plt.title('Pick time')
- plt.xlabel('Wavelength')
- plt.ylabel('Time')
- fittingto = np.array(ginput(1))
- plt.show()
- plt.close()
+ index_time=self.plottimeindex
- index_time=(np.abs(Data.time-fittingto[:,1])).argmin()
-
- plt.figure()
- plt.plot(Data.wavelength, Data.TrA_Data[index_time,:])
- plt.title("%s %s" %(self.title, Data.time[index_time]))
- plt.xlabel('Wavelength')
- plt.ylabel('Abs')
- plt.show()
+ figure()
+ plot(Data.wavelength, Data.TrA_Data[index_time,:] )
+ title("%s %s" %(self.title, Data.time[index_time]))
+ xlabel('Wavelength')
+ ylabel('Abs')
+ show()
def _multiple_plots_fired(self):
- try:
- plt.fignum_exists()
- xmin, xmax = plt.xlim()
- ymin, ymax = plt.ylim()
- index_wavelength_left=(np.abs(Data.wavelength-xmin)).argmin()
- index_wavelength_right=(np.abs(Data.wavelength-xmax)).argmin()
+ xmin=self.plot2D.range2d.x_range.low
+ xmax=self.plot2D.range2d.x_range.high
+ ymin=self.plot2D.range2d.y_range.low
+ ymax=self.plot2D.range2d.y_range.high
- index_time_left=(np.abs(Data.time-ymin)).argmin()
- index_time_right=(np.abs(Data.time-ymax)).argmin()
- except:
- index_wavelength_left=0
- index_wavelength_right=Data.wavelength[-1]
+ index_wavelength_left=(abs(Data.wavelength-xmin)).argmin()
+ index_wavelength_right=(abs(Data.wavelength-xmax)).argmin()
- index_time_left=0
- index_time_right=Data.wavelength[-1]
+ index_time_left=(abs(Data.time-ymin)).argmin()
+ index_time_right=(abs(Data.time-ymax)).argmin()
indexwave = int((index_wavelength_right-index_wavelength_left)/10)
# spectrum from every 10th spectra
- timevec = np.ones([Data.time[index_time_left:index_time_right].shape[0],10])
- time = np.ones([Data.time[index_time_left:index_time_right].shape[0],10])
- wavelengthvals = np.ones(10)
+ timevec = ones([Data.time[index_time_left:index_time_right].shape[0],10])
+ time = ones([Data.time[index_time_left:index_time_right].shape[0],10])
+ wavelengthvals = ones(10)
for i in range(10):
- timevec[:,i] = np.average(Data.TrA_Data[index_time_left:index_time_right,index_wavelength_left+((i)*indexwave):index_wavelength_left+((i)*indexwave)+indexwave],axis=1)
+ timevec[:,i] = average(Data.TrA_Data[index_time_left:index_time_right,index_wavelength_left+((i)*indexwave):index_wavelength_left+((i)*indexwave)+indexwave],axis=1)
time[:,i] = Data.time[index_time_left:index_time_right]
- wavelengthvals[i] = round(np.average(Data.wavelength[index_wavelength_left+((i)*indexwave):index_wavelength_left+((i)*indexwave)+indexwave]),1)
-
- plt.figure()
- colormap = plt.cm.jet
- plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, 10)])
- plt.plot(time,timevec)
- plt.legend(wavelengthvals)
- plt.xlabel('Time (ps)')
- plt.ylabel('Abs.')
- plt.title("Averaged %s %s" %(self.title, 'Wavelengths (nm)'))
- plt.show()
+ wavelengthvals[i] = round(average(Data.wavelength[index_wavelength_left+((i)*indexwave):index_wavelength_left+((i)*indexwave)+indexwave]),1)
+
+ figure()
+ colormap = cm.jet
+ gca().set_color_cycle([colormap(i) for i in linspace(0, 0.9, 10)])
+ plot(time,timevec )
+ legend(wavelengthvals)
+ xlabel('Time (ps)')
+ ylabel('Abs.')
+ title("Averaged %s %s" %(self.title, 'Wavelengths (nm)'))
+ show()
indextime = int((index_time_right-index_time_left)/10)
- wavevec = np.ones([Data.wavelength[index_wavelength_left:index_wavelength_right].shape[0],10])
- wave = np.ones([Data.wavelength[index_wavelength_left:index_wavelength_right].shape[0],10])
- timevals = np.ones(10)
+ wavevec = ones([Data.wavelength[index_wavelength_left:index_wavelength_right].shape[0],10])
+ wave = ones([Data.wavelength[index_wavelength_left:index_wavelength_right].shape[0],10])
+ timevals = ones(10)
for i in range(10):
- wavevec[:,i] = np.average(Data.TrA_Data[index_time_left+((i)*indextime):index_time_left+((i)*indextime)+indextime,index_wavelength_left:index_wavelength_right],axis=0)
+ wavevec[:,i] = average(Data.TrA_Data[index_time_left+((i)*indextime):index_time_left+((i)*indextime)+indextime,index_wavelength_left:index_wavelength_right],axis=0)
wave[:,i] = Data.wavelength[index_wavelength_left:index_wavelength_right]
- timevals[i] = round(np.average(Data.time[index_time_left+((i)*indextime):index_time_left+((i)*indextime)+indextime]),1)
-
- plt.figure()
- colormap = plt.cm.jet
- plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, 10)])
- plt.plot(wave,wavevec)
- plt.legend(timevals)
- plt.title("Averaged %s %s" %(self.title, 'Times (ps)'))
- plt.xlabel('Wavelength (nm)')
- plt.ylabel('Abs.')
- plt.show()
+ timevals[i] = round(average(Data.time[index_time_left+((i)*indextime):index_time_left+((i)*indextime)+indextime]),1)
+
+ figure()
+ colormap = cm.jet
+ gca().set_color_cycle([colormap(i) for i in linspace(0, 0.9, 10)])
+ plot(wave,wavevec )
+ legend(timevals)
+ title("Averaged %s %s" %(self.title, 'Times (ps)'))
+ xlabel('Wavelength (nm)')
+ ylabel('Abs.')
+ show()
def _Normalise_fired(self):
- try:
- plt.fignum_exists()
- xmin, xmax = plt.xlim()
- ymin, ymax = plt.ylim()
- index_wavelength_left=(np.abs(Data.wavelength-xmin)).argmin()
- index_wavelength_right=(np.abs(Data.wavelength-xmax)).argmin()
+ xmin=self.plot2D.range2d.x_range.low
+ xmax=self.plot2D.range2d.x_range.high
+ ymin=self.plot2D.range2d.y_range.low
+ ymax=self.plot2D.range2d.y_range.high
- index_time_left=(np.abs(Data.time-ymin)).argmin()
- index_time_right=(np.abs(Data.time-ymax)).argmin()
- except:
- index_wavelength_left=0
- index_wavelength_right=Data.wavelength[-1]
+ index_wavelength_left=(abs(Data.wavelength-xmin)).argmin()
+ index_wavelength_right=(abs(Data.wavelength-xmax)).argmin()
- index_time_left=0
- index_time_right=Data.wavelength[-1]
+ index_time_left=(abs(Data.time-ymin)).argmin()
+ index_time_right=(abs(Data.time-ymax)).argmin()
indextime = int((index_time_right-index_time_left)/10)
- wavevec = np.ones([Data.wavelength[index_wavelength_left:index_wavelength_right].shape[0],10])
- wave = np.ones([Data.wavelength[index_wavelength_left:index_wavelength_right].shape[0],10])
- timevals = np.ones(10)
+ wavevec = ones([Data.wavelength[index_wavelength_left:index_wavelength_right].shape[0],10])
+ wave = ones([Data.wavelength[index_wavelength_left:index_wavelength_right].shape[0],10])
+ timevals = ones(10)
for i in range(10):
wavevec[:,i] = Data.TrA_Data[(index_time_left+((i)*indextime)),index_wavelength_left:index_wavelength_right]
- max_i = np.max(wavevec[:,i])
- min_i = np.min(wavevec[:,i])
+ max_i = max(wavevec[:,i])
+ min_i = min(wavevec[:,i])
wavevec[:,i] = (wavevec[:,i]-min_i)/(max_i-min_i)
wave[:,i] = Data.wavelength[index_wavelength_left:index_wavelength_right]
timevals[i] = Data.time[index_time_left+((i)*indextime)]
- plt.figure()
- colormap = plt.cm.jet
- plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, 10)])
- plt.plot(wave,wavevec)
- plt.jet()
- plt.legend(timevals)
- plt.title("Normalised %s %s" %(self.title, 'Times (ps)'))
- plt.xlabel('Wavelength (nm)')
- plt.ylabel('Abs.')
- plt.show()
+ figure()
+ colormap = cm.jet
+ gca().set_color_cycle([colormap(i) for i in linspace(0, 0.9, 10)])
+ plot(wave,wavevec)
+ legend(timevals)
+ title("Normalised %s %s" %(self.title, 'Times (ps)'))
+ xlabel('Wavelength (nm)')
+ ylabel('Abs.')
+ show()
indexwave = int((index_wavelength_right-index_wavelength_left)/10)
# spectrum from every 10th spectra
- timevec = np.ones([Data.time[index_time_left:index_time_right].shape[0],10])
- time = np.ones([Data.time[index_time_left:index_time_right].shape[0],10])
- wavelengthvals = np.ones(10)
+ timevec = ones([Data.time[index_time_left:index_time_right].shape[0],10])
+ time = ones([Data.time[index_time_left:index_time_right].shape[0],10])
+ wavelengthvals = ones(10)
for i in range(10):
timevec[:,i] = Data.TrA_Data[index_time_left:index_time_right,(index_wavelength_left+((i)*indexwave))]
- max2_i = np.max(timevec[:,i])
- min2_i = np.min(timevec[:,i])
+ max2_i = max(timevec[:,i])
+ min2_i = min(timevec[:,i])
timevec[:,i] = (timevec[:,i]-min2_i)/(max2_i-min2_i)
time[:,i] = Data.time[index_time_left:index_time_right]
wavelengthvals[i] = Data.wavelength[index_wavelength_left+((i)*indexwave)]
- plt.figure()
- colormap = plt.cm.jet
- plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, 10)])
- plt.plot(time,timevec)
- plt.legend(wavelengthvals)
- plt.xlabel('Time (ps)')
- plt.ylabel('Abs.')
- plt.title("Normalised %s %s" %(self.title, 'Wavelengths (nm)'))
- plt.show()
-
- def _Trace_Igor_fired(self):
-
+ figure()
+ colormap = cm.jet
+ gca().set_color_cycle([colormap(i) for i in linspace(0, 0.9, 10)])
+ plot(time,timevec )
+ legend(wavelengthvals)
+ xlabel('Time (ps)')
+ ylabel('Abs.')
+ title("Normalised %s %s" %(self.title, 'Wavelengths (nm)'))
+ show()
+
+ def _savetraces_fired(self):
try:
- import win32com.client # Communicates with Igor needs pywin32 library
- f=open(("%s\Traces.txt" %(os.path.dirname(self.TrA_Raw_file))), 'w')
+ f=open(("%s\Traces.txt" %(dirname(self.TrA_Raw_file))), 'w')
for i in range(len(Data.time)):
f.write("%s" %(Data.time[i]))
for j in range(len(Data.Traces)):
f.write(",%s" %(Data.Traces[j,i]))
f.write("\n")
f.close()
-
- # Sends traces to Igor and opens up Global fitting gui in Igor
- igor=win32com.client.Dispatch("IgorPro.Application")
-
- #Load into igor using LoadWave(/A=Traces/J/P=pathname) /J specifies it as a txt delimited file
- igor.Execute('NewPath pathName, "%s"' %(os.path.dirname(self.TrA_Raw_file)))
- igor.Execute('Loadwave/J/P=pathName "Traces.txt"')
- igor.Execute('Rename wave0,timeval')
-
- # Run global fitting gui in Igor
- igor.Execute('WM_NewGlobalFit1#InitNewGlobalFitPanel()')
- igor.clear()
-
+ self.log = '%s\n\nTraces saved to %s' %(self.log,dirname(self.TrA_Raw_file))
except:
- self.log = '%s \nsetuptools not installed or Igor not open. Saved traces into directory' %(self.log)
- try:
- f=open(("%s\Traces.txt" %(os.path.dirname(self.TrA_Raw_file))), 'w')
- for i in range(len(Data.time)):
- f.write("%s" %(Data.time[i]))
- for j in range(len(Data.Traces)):
- f.write(",%s" %(Data.Traces[j,i]))
- f.write("\n")
- f.close()
- except:
- self.log = '%s \nPlease select multiple traces' %(self.log)
+ self.log = '%s\n\nPlease select multiple traces' %(self.log)
def _Save_Glo_fired(self):
# Generates ouput file in Glotaran Time explicit format
- pathname = "%s\Glotaran.txt" %(os.path.dirname(self.TrA_Raw_file))
+ pathname = "%s\Glotaran.txt" %(dirname(self.TrA_Raw_file))
f = open(pathname, 'w')
f.write("#-#-#-#-#-# Made with PyTrA #-#-#-#-#-#\n")
f.write("\n")
@@ -968,9 +1105,31 @@ def _Save_Glo_fired(self):
self.log = '%s \nSaved Glotaran file to TrA data file directory' %(self.log)
+ def _Trace_Igor_fired(self):
+
+ import win32com.client # Communicates with Igor needs pywin32 library
+ f=open(("%s\Traces.txt" %(dirname(self.TrA_Raw_file))), 'w')
+ for i in range(len(Data.time)):
+ f.write("%s" %(Data.time[i]))
+ for j in range(len(Data.Traces)):
+ f.write(",%s" %(Data.Traces[j,i]))
+ f.write("\n")
+ f.close()
+ # Sends traces to Igor and opens up Global fitting gui in Igor
+ igor=win32com.client.Dispatch("IgorPro.Application")
+
+ #Load into igor using LoadWave(/A=Traces/J/P=pathname) /J specifies it as a txt delimited file
+ igor.Execute('NewPath pathName, "%s"' %(dirname(self.TrA_Raw_file)))
+ igor.Execute('Loadwave/J/P=pathName "Traces.txt"')
+ igor.Execute('Rename wave0,timeval')
+
+ # Run global fitting gui in Igor
+ igor.Execute('WM_NewGlobalFit1#InitNewGlobalFitPanel()')
+ igor.clear()
+
def _Save_csv_fired(self):
now = date.today()
- pathname = "%s\Saved%s%s.csv" %(os.path.dirname(self.TrA_Raw_file), now.strftime("%m-%d-%y"),self.title)
+ pathname = "%s\Saved%s%s.csv" %(dirname(self.TrA_Raw_file), now.strftime("%m-%d-%y"),self.title)
f = open(pathname, 'w')
f.write("0")
for i in range(len(Data.time)):
@@ -982,15 +1141,15 @@ def _Save_csv_fired(self):
f.write(",%s" %(Data.TrA_Data[j,i]))
f.write("\n")
- self.log= '%s \nSaved to TrA data file directory' %(self.log)
+ self.log= '%s\n\nSaved to TrA data file directory' %(self.log)
def _Save_log_fired(self):
now = date.today()
- pathname = "%s\log%s_%s.log" %(os.path.dirname(self.TrA_Raw_file), now.strftime("%m-%d-%y"),self.title)
+ pathname = "%s\log%s_%s.log" %(dirname(self.TrA_Raw_file), now.strftime("%m-%d-%y"),self.title)
f = open(pathname, 'w')
f.write("%s"%(self.log))
- self.log= '%s \nSaved log file to %s' %(self.log,os.path.dirname(self.TrA_Raw_file))
+ self.log= '%s\n\nSaved log file to %s' %(self.log,dirname(self.TrA_Raw_file))
def _Help_fired(self):
help = Help().edit_traits()
diff --git a/PyTrA_Help.py b/PyTrA_Help.py
index b150676..284a8cc 100644
--- a/PyTrA_Help.py
+++ b/PyTrA_Help.py
@@ -7,9 +7,7 @@ class Help(HasTraits):
PyTrA Help
-Click here to see the video
-
-
More information on the websitenznano
+
Click here to go to the website
Importing Data
@@ -57,57 +55,53 @@ class Help(HasTraits):
Importing data from Ohio State University involves inputing the data file and the delay file (A single vector of the time delays). The wavelength and corresponding pixel number are input for calibrating the data. To load the data press Load data button and click ok
-You may want to delete a range of wavelengths between which the data is offscale click the Delete traces button and pick the wavelengths you want to delete between
-
Correcting Chirp
Due to the ultrashort pulses from femtosecond transient absorption spectrometers shorter wavelengths arrive at the spectrometer before longer wavelengths
To correct for this we can fit a polynomial to the chirp spectrum and then interpolate our values to correct for the dispersion
-View the chirp by clicking the 2D plot of chirp button
-
-Now find the times between which the chirp is visible.
+View the chirp by going to the Chirp correction menu and click on Plot chirp
-Close the plot and input the time range when the chirp is visible in the two text boxes under the Time range for chirp correction label
+Zoom into the area you want to fit the chirp to
-Click the Fix for chirp button. You will be asked to pick 8 points on the chirp wavefront and then another graph will ask you to pick the top of the wavefront
+Click the Chirp correction item in the Chirp correction menu. You will be asked to pick 8 points on the chirp wavefront and then another graph will ask you to pick the front of the wavefront
-The polynomial fit and the standard deviation and added to the bottom text bar
+The polynomial fit and the standard deviation are printed in the log
Data anaylsis
-To fit a single trace at a certain wavelength click the Fit trace button plot will appear click on a wavelength that you want to fit to
+To fit a single trace or spectra go to type the value into the text box under the line plots then click either Fit Trace
-The pymodelfit window will open and the data will be displayed the trace.
+The pymodelfit window will open and the data will be displayed.
-
-
- In fitting the data it is recommended that you click the Fit Model button until it converges and the solution no longer changes
+
On exit the parameters used to fit the trace are printed in the status bar
Pick the model that you want to use click on the new model button.
-
Convoluted_1 is a single exponential with the instrument response (gaussian)
-Convoluted_2 is a double expoential convoluted with the instrument response (gaussian)
-Click the Fit model multiple times until the variable do not change. Each time you fit the model the algorithim uses the varibles from the previous fit to get a better intial guess. This leads to an accurate fit of the data and leads to what is called convergence.
+Convoluted_1,2,3,4 are exponential sums convoluted with the instrument response (gaussian)
+Gauss_1,2,3,4 are Gaussian function with x and y shifts
+Click the Fit model multiple times until the variable do not change. Each time you fit the model the algorithim uses the varibles from the previous fit to get a better intial guess. This leads to an accurate fit of the data where the solution convergence on the best value for the model and data.
+
The variables that are used in the fit.
-A1 = Amplitude
+A = Amplitude
mu = shift in the centre of the gaussian distribution
w = Full width half maximum of the gaussian (instrument response)
-T1 = Time constant
+T = Time constant
y0 = baseline
-Where w gives us the width of the instrument at half the height of the peak and T1 gives us the time constant for the exponential decay.
+
+Where w gives the width of the instrument at half the height of the peak and T gives us the time constant for the exponential decay.
Global fitting
Global fitting can be done using Igor Pro from Wavemetrics. Otherwise TIMP library for R is a free alternative.
-Click the Select multiple traces button. You will be prompted to pick between which wavelengths to fit to.
+Click the Select traces button under the Global fit menu item. You will be prompted to pick between which wavelengths to fit to.
-The number of traces saved and between which wavelengths will be printed in the Status bar
+The number of traces saved and between which wavelengths will be printed in the log file
-Make sure Igor Pro is open and then click on the Send traces to Igor Igor Pro should prompt you to load the data click the Load button the traces will be inputted and the time vector will be saved as timevals
+Make sure Igor Pro is open and then click on the Send to Igor in the Global fit menu item. Igor Pro should prompt you to load the data click the Load button the traces will be inputted and the time vector will be saved as timevals
The Global Analysis window wil open click on Add/Remove Waves
@@ -121,16 +115,37 @@ class Help(HasTraits):
Click Fit! and wait for Igor Pro to compute the global minimum. The coefficients will be printed out make sure in the output it reads Global Fit converged normally. Note down the global time constant which is the same for all of the data traces.
+MCMC
+
+One method for model checking and non-linear regression is to use Markov Chain Monte Carlo. This method defines all of the parameters and the error as distribution from which to sample from, these are the priors. You then can sample the distributions to see if a stable solution exist and if the chain converges
+
+To begin you need to do a single trace fit of the kinetics and open up the MCMC dialog box found under the kinetic trace in the main window
+
+
+
+Setting the parameters you will need to choose priors that do not restrict the parameters but hold the parameter from becoming unphysical (such as a negative time decay tau). It is recomended to only use Uniform priors
+
+Once the chain has run you should see the plots of each parameter. The top left plot is of the chain value at the different iterations, the chain must converge to a stable value. If converge does not occur the model is not a stable solution within the noise of the system. The bottom left graph is the autocorrelation plot. This shows the amount of correlation of the sample with the samples previously, we want a Markov chain which is only correlated to the previous state this being an autocorrelation plot showing minimal correlation. The right plot is the histogram for the distribution of the chain we want a high density around a mean.
+
+
+
+The next step is tuning the chain. If the chain has converged you can use the Raftery Lewis statistics to set the values for the burn-in, thining and number of iterations.
+
+ Once you are finished shut the window the values of the mean and standard deviation will be printed out in the log file.
+
+The Bayesian information Criterion (BIC) can be used to compare different models. This is calculated from a maximum a posteriori (MAP) which optimises the parameters to the value of maximum denisty. More negative BIC indicate more dense distribution and a better fit with the number of parameters also taken into account.
+
Visualisation
-A 3D plot can be opened by clicking the 3D plot button. The surface will be sent to MayaVi window for viewing. You can customise the plot using the tool bar on the top of the 3D plot the far left button opens up a dialog with many different options for label sizes titles and surface colours.
+A 3D plot can be opened by clicking the 3D plot button in the 2d graph tab. The surface will be sent to MayaVi window for viewing. You can customise the plot using the tool bar on the top of the 3D plot the far left button opens up a dialog with many different options for label sizes titles and surface colours. By changing the value right of the 3D plot button you can scale the z axis of the plot
-2D contour plot, spectra at a certain time value and trace at a certain wavelength can be viewed using matplotlib.
+The plots in the main window can be zoomed by holding Ctrl and dragging over the area of interest. The Averaged and Normalised buttons will slice the 2D plot into 10 sections within the zoomed area of the main 2D plot in the main window. SVD and EFA also work within the zoom range of the main 2D plot.
-Exporting data
+2D contour plot, spectra at a certain time value and trace at a certain wavelength can be viewed using matplotlib as well which can produce publication quality images.
-Data can be exported as csv in same format it was imported as. The file is saved in the same directory where the data was taken and starts with the date in front with the name of the file taken from the title.
+Exporting data
+Data can be exported as csv in same format it was imported as. The file is saved in the same directory where the data was taken and starts with the date in front with the name of the file taken from the title. The log file will also be saved in the same place if the Save log file is clicked.