From 582019d7cb1ce0bf946624d3fcdb5265d19199d8 Mon Sep 17 00:00:00 2001 From: Markus Rosenstihl Date: Wed, 24 Sep 2014 22:09:39 +0200 Subject: [PATCH] optimized imports --- QDS.py | 146 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 71 insertions(+), 75 deletions(-) diff --git a/QDS.py b/QDS.py index 96a19f8..7164a5e 100755 --- a/QDS.py +++ b/QDS.py @@ -4,16 +4,17 @@ from gui import ExtraDifferentialWidget _author_ = "Markus Rosenstihl" -import hashlib,uuid +import hashlib, uuid import time -import os,sys,re,signal +import os, sys, re, signal import matplotlib + matplotlib.use('agg') from matplotlib import pyplot from matplotlib.colors import hex2color -#matplotlib.rc_file("default.mplrc") +# matplotlib.rc_file("default.mplrc") from PyQt4.QtCore import * @@ -32,7 +33,7 @@ from bds_io import bds_file_reader class AppWindow(QMainWindow): - def __init__(self, files=[], parent=None): + def __init__( self, files=[], parent=None ): super(AppWindow, self).__init__(parent) self.ui = QDSMain.Ui_MainWindow() self.ui.setupUi(self) @@ -40,11 +41,11 @@ class AppWindow(QMainWindow): self._last_written_header = None actions = { - self.ui.actionAdd_Peak:self.addPeak, - self.ui.actionAdd_Cond:self.addCond, - self.ui.actionAdd_PowerLaw:self.addPowerComplex, - self.ui.actionAdd_Eps_Infty:self.addEpsInfty, - self.ui.actionYAFF:self.addYaff, + self.ui.actionAdd_Peak: self.addPeak, + self.ui.actionAdd_Cond: self.addCond, + self.ui.actionAdd_PowerLaw: self.addPowerComplex, + self.ui.actionAdd_Eps_Infty: self.addEpsInfty, + self.ui.actionYAFF: self.addYaff, } self.myActionGroup = QActionGroup(self) @@ -59,11 +60,10 @@ class AppWindow(QMainWindow): self.parameterWidget = ParameterWidget() self.ui.dockWidget_3.setWidget(self.parameterWidget) - self.data = Data() - self.fit_boundary_imag = pg.LinearRegionItem(brush=QColor(0,127,254,15)) - self.fit_boundary_real = pg.LinearRegionItem(brush=QColor(0,127,254,15)) + self.fit_boundary_imag = pg.LinearRegionItem(brush=QColor(0, 127, 254, 15)) + self.fit_boundary_real = pg.LinearRegionItem(brush=QColor(0, 127, 254, 15)) self.ui.pgPlotWidget_imag.addItem(self.data.data_curve_imag) self.ui.pgPlotWidget_real.addItem(self.data.data_curve_real) @@ -85,7 +85,7 @@ class AppWindow(QMainWindow): pltwidgt.disableAutoRange() pltwidgt.setLabel("bottom", "Frequency", units="Hz") - self.ui.pgPlotWidget_imag.setLabel("left", u'Dielectric loss ε"' , units="Debye") + self.ui.pgPlotWidget_imag.setLabel("left", u'Dielectric loss ε"', units="Debye") self.ui.pgPlotWidget_real.setLabel("left", u"Dielectric loss ε' ", units="Debye") sc_real = self.ui.pgPlotWidget_real.scene() @@ -96,7 +96,6 @@ class AppWindow(QMainWindow): sc_imag.sigMouseClicked.connect(self.mousePress) sc_imag.sigMouseMoved.connect(self.updateCrosshair) - self._fit_thread = QThread() self._fit_method = FitRoutine() self._fit_method.moveToThread(self._fit_thread) @@ -110,7 +109,7 @@ class AppWindow(QMainWindow): self.openFile(unicode(self._file_paths[0])) self._current_file_index = 0 - def _init_menu(self): + def _init_menu( self ): fileMenu = self.menuBar().addMenu("File") openFile = QAction("&Open", self) @@ -158,13 +157,12 @@ class AppWindow(QMainWindow): self.ui.actionShow_Derivative.triggered.connect(self.show_derivative) - - def show_derivative(self): + def show_derivative( self ): self.xtra_wdgt = ExtraDifferentialWidget.DifferentialWidget() #self.xtra_wdgt.set deriv_r = np.diff(np.log10(self.data.epsilon.real)) deriv_i = np.diff(np.log10(self.data.epsilon.imag))*0 - deriv_i = -np.pi/2 * np.diff(np.log10(self.data.epsilon.real))/np.diff(np.log10(self.data.frequency)) + deriv_i = -np.pi/2*np.diff(np.log10(self.data.epsilon.real))/np.diff(np.log10(self.data.frequency)) self.xtra_wdgt.plot(self.data.frequency[:-1], deriv_r, deriv_i) # self.xtra_wdgt.plot([0,1], [0,1], [0,1]) self.xtra_wdgt.setGeometry(self.ui.pgPlotWidget_real.geometry()) @@ -173,7 +171,7 @@ class AppWindow(QMainWindow): self.xtra_wdgt.raise_() - def updateCrosshair(self,evt): + def updateCrosshair( self, evt ): vb_real = self.ui.pgPlotWidget_real.getPlotItem().vb vb_imag = self.ui.pgPlotWidget_imag.getPlotItem().vb @@ -185,7 +183,7 @@ class AppWindow(QMainWindow): pos = QPointF(0.0, 0.0) self.last_pos = pos - def mousePress(self, evt): + def mousePress( self, evt ): data_pos = self.last_pos mouse_in_imag = self.ui.pgPlotWidget_imag.underMouse() mouse_in_real = self.ui.pgPlotWidget_real.underMouse() @@ -232,12 +230,12 @@ class AppWindow(QMainWindow): msgBox.exec_() - def abortFit(self): + def abortFit( self ): for container in self.function_registry.get_registered_functions(): container.abort(True) self._fit_thread.terminate() - def saveFitResult(self): + def saveFitResult( self ): """ Saving fit parameters to fitresults.log including temperature @@ -263,18 +261,18 @@ class AppWindow(QMainWindow): tau_comp = 0 for i_fcn, fcn in enumerate(self.function_registry.get_registered_functions()): if fcn.id_string == "hn": - for i,varname in enumerate(fcn.widget.names): + for i, varname in enumerate(fcn.widget.names): if varname == "tau": if fcn._beta[i] <= tau_comp: sorted_functions.append(fcn) else: - sorted_functions.insert(0,fcn) + sorted_functions.insert(0, fcn) tau_comp = fcn._beta[i] # eps_infty to the front for a in self.function_registry.get_registered_functions(): print a.id_string if a.id_string == "eps_infty": - sorted_functions.insert(0,a) + sorted_functions.insert(0, a) print a # sort the rest lexigraphically for a in self.function_registry.get_registered_functions(): @@ -306,7 +304,7 @@ class AppWindow(QMainWindow): f_fcn.write("# SourceID=%s\n"%file_id) #else: # f_fcn.write("# type=%s\n"%fit_function_name) - for i,par in enumerate(fcn._beta): # params # TODO: ughh + for i, par in enumerate(fcn._beta): # params # TODO: ughh if fcn._selector_mask is not None: if fcn._selector_mask[i]: pars.extend([par]) @@ -342,36 +340,36 @@ class AppWindow(QMainWindow): np.savetxt(f, pars, fmt='%-12.3e', delimiter=" ") f.close() - def _saveFitFigure(self): + def _saveFitFigure( self ): fig = pyplot.figure(figsize=(3.54*1.4, 2.75*1.4)) - font = {'family' : 'sans serif', - 'weight' : 'normal', - 'size' : 9} + font = { 'family': 'sans serif', + 'weight': 'normal', + 'size': 9 } matplotlib.rc('font', **font) - pyplot.grid(linestyle="solid",alpha=0.3, color="0.5") + pyplot.grid(linestyle="solid", alpha=0.3, color="0.5") pyplot.loglog(self.data.frequency, self.data.epsilon.imag, 'bo', markersize=4, label="Data") pyplot.loglog(self.data.frequency_fit, self.data.epsilon_fit.imag, 'r-', lw=1.2, label="Fit") for fcn in self.function_registry.get_registered_functions(): - f,eps = fcn.get_data() + f, eps = fcn.get_data() label = fcn.id_label color = hex2color(str(fcn.color.name())) - pyplot.loglog(f,eps[1], ls=":", color=color, lw=1, dashes=(1,1), label=label) + pyplot.loglog(f, eps[1], ls=":", color=color, lw=1, dashes=(1, 1), label=label) - for i in (0,1): pyplot.axvline(x=self.data.fit_limits[i], color='b', ls="-", lw=0.5) - pyplot.legend(title = "T=%.1f K"%(self.data.meta["T"])) + for i in (0, 1): pyplot.axvline(x=self.data.fit_limits[i], color='b', ls="-", lw=0.5) + pyplot.legend(title="T=%.1f K"%(self.data.meta["T"])) pyplot.xlabel('f/Hz') pyplot.ylabel(u'ε"') - pyplot.ylim(self.data.epsilon.imag.min(), self.data.epsilon.imag.max() ) + pyplot.ylim(self.data.epsilon.imag.min(), self.data.epsilon.imag.max()) #pyplot.savefig(os.path.splitext(self.filepath)[0]+".png") pyplot.savefig(os.path.splitext(self.filepath)[0]+".pdf") fig.clear() del (fig) - def _saveFitFigureGrace(self): + def _saveFitFigureGrace( self ): #agrtemplate = open('template.agr').read() agrtemplate = """ @@ -379,7 +377,7 @@ class AppWindow(QMainWindow): #TODO: need interface/method for adding function blocks, this is too repetitive - def addYaff(self, pos): + def addYaff( self, pos ): _yaff = YAFF(plt_real=self.ui.pgPlotWidget_real, plt_imag=self.ui.pgPlotWidget_imag, limits=self.data.fit_limits) @@ -388,7 +386,7 @@ class AppWindow(QMainWindow): _yaff.removeObj.connect(self.delParamterObject) gg_y = 10**pos.y()*2 gg_x = 1/(10**pos.x()*2*np.pi) - yaff_par = [ gg_y, gg_x , 20.0, 1.0, 0.5, gg_x/100, 1.0, 1.0] + yaff_par = [gg_y, gg_x, 20.0, 1.0, 0.5, gg_x/100, 1.0, 1.0] _yaff.setParameter(beta=yaff_par) self.parameterWidget.add(_yaff.widget) self.function_registry.register_function(_yaff) @@ -396,14 +394,14 @@ class AppWindow(QMainWindow): _yaff.blockSignals(False) - def addCond(self, pos): + def addCond( self, pos ): _conductivity = Conductivity(plt_real=self.ui.pgPlotWidget_real, plt_imag=self.ui.pgPlotWidget_imag, limits=self.data.fit_limits) _conductivity.blockSignals(True) _conductivity.changedData.connect(self.updatePlot) _conductivity.removeObj.connect(self.delParamterObject) - cond_par = [0.0, 10**(pos.y() + pos.x())*2*np.pi , 1.0] + cond_par = [0.0, 10**(pos.y()+pos.x())*2*np.pi, 1.0] _conductivity.setParameter(beta=cond_par) self.parameterWidget.add(_conductivity.widget) self.function_registry.register_function(_conductivity) @@ -411,19 +409,19 @@ class AppWindow(QMainWindow): _conductivity.blockSignals(False) - def addPowerComplex(self, pos): + def addPowerComplex( self, pos ): _power_complex = PowerComplex(plt_imag=self.ui.pgPlotWidget_imag, plt_real=self.ui.pgPlotWidget_real, limits=self.data.fit_limits) _power_complex.changedData.connect(self.updatePlot) _power_complex.removeObj.connect(self.delParamterObject) - cond_par = [10**(pos.y() + pos.x())*2*np.pi , 1.0] + cond_par = [10**(pos.y()+pos.x())*2*np.pi, 1.0] _power_complex.setParameter(beta=cond_par) self.parameterWidget.add(_power_complex.widget) self.function_registry.register_function(_power_complex) self.updatePlot() - def addEpsInfty(self, pos): + def addEpsInfty( self, pos ): _eps_infty = Static(plt_imag=self.ui.pgPlotWidget_imag, plt_real=self.ui.pgPlotWidget_real, limits=self.data.fit_limits) @@ -435,14 +433,14 @@ class AppWindow(QMainWindow): self.function_registry.register_function(_eps_infty) self.updatePlot() - def delParamterObject(self, obj): + def delParamterObject( self, obj ): self.function_registry.unregister_function(obj) self.updatePlot() - def addPeak(self, pos): - id_list = [ key.id_num for key in - self.function_registry.get_registered_functions() - if key.id_string == 'hn'] + def addPeak( self, pos ): + id_list = [key.id_num for key in + self.function_registry.get_registered_functions() + if key.id_string == 'hn'] self.peakId = 1 print id_list while self.peakId in id_list: @@ -455,22 +453,22 @@ class AppWindow(QMainWindow): _peak.changedData.connect(self.updatePlot) _peak.removeObj.connect(self.delParamterObject) - new_peak_beta0 = [2*10**pos.y(), 1 / (2*np.pi*10**pos.x()), 1, 1] - _peak.setParameter(beta = new_peak_beta0) + new_peak_beta0 = [2*10**pos.y(), 1/(2*np.pi*10**pos.x()), 1, 1] + _peak.setParameter(beta=new_peak_beta0) self.parameterWidget.add(_peak.widget) self.updatePlot() - def fitData_start(self, method): + def fitData_start( self, method ): #fit_methods = [fit_odr_cmplx, fit_odr_imag, fit_lbfgsb, fit_anneal] self.fit_boundary_real.hide() self.fit_boundary_imag.hide() fit_method = [ self._fit_method.fit_odr_cmplx, self._fit_method.fit_odr_imag, - ][method] + ][method] # build function list - p0,funcs,fixed_params = [],[],[] + p0, funcs, fixed_params = [], [], [] for fcn in self.function_registry.get_registered_functions(): p0.extend(fcn.getParameter()) funcs.append(fcn) @@ -486,10 +484,10 @@ class AppWindow(QMainWindow): else: self.ui.statusbar.showMessage("Still fitting ...") - def fitData_update(self): + def fitData_update( self ): self._fit_thread.quit() odr_result = self._fit_method.result() - p0,funcs,fixed_params = [],[],[] + p0, funcs, fixed_params = [], [], [] for fcn in self.function_registry.get_registered_functions(): p0.extend(fcn.getParameter()) funcs.append(fcn) @@ -498,11 +496,10 @@ class AppWindow(QMainWindow): for container in self.function_registry.get_registered_functions(): container.abort(False) - self.data.set_fit(odr_result.beta, funcs) self.ui.statusbar.showMessage(" ".join(odr_result.stopreason)) ndx = 0 - for i,fcn in enumerate(self.function_registry.get_registered_functions()): + for i, fcn in enumerate(self.function_registry.get_registered_functions()): num_p = len(fcn.getParameter()) beta = odr_result.beta[ndx:num_p+ndx] if odr_result.sd_beta is not None: @@ -515,7 +512,7 @@ class AppWindow(QMainWindow): self.fit_boundary_real.show() self.fit_boundary_imag.show() - def getFileNames(self): + def getFileNames( self ): tmp = QFileDialog.getOpenFileNames(self, "Open file", "", '*.dat *.TXT') if len(tmp) != 0: self._file_paths = tmp @@ -523,9 +520,9 @@ class AppWindow(QMainWindow): path = unicode(self._file_paths[self._current_file_index]) self.openFile(path) - def nextFile(self): - lim = self.fit_boundary_imag.getRegion() # store limits - if len(self._file_paths) > self._current_file_index+1: # wrap around + def nextFile( self ): + lim = self.fit_boundary_imag.getRegion() # store limits + if len(self._file_paths) > self._current_file_index+1: # wrap around self._current_file_index += 1 else: self._current_file_index = 0 @@ -533,10 +530,10 @@ class AppWindow(QMainWindow): self.openFile(path) self.fit_boundary_imag.setRegion(lim) - def previousFile(self): - lim = self.fit_boundary_imag.getRegion() # store limits - if self._current_file_index == 0: # wrap around - self._current_file_index = len(self._file_paths) - 1 + def previousFile( self ): + lim = self.fit_boundary_imag.getRegion() # store limits + if self._current_file_index == 0: # wrap around + self._current_file_index = len(self._file_paths)-1 else: self._current_file_index -= 1 path = unicode(self._file_paths[self._current_file_index]) @@ -547,9 +544,9 @@ class AppWindow(QMainWindow): return QStringList(sorted(files, key=lambda x: re.findall("\d+\.\d+K", x))) - def openFile(self,path): + def openFile( self, path ): print "opening: %s"%path - self.filepath=path + self.filepath = path Temp, _die_loss, _die_stor, _freq = bds_file_reader.FileReader.read_datafile(path) self.setWindowTitle("%s - %.2f K"%(os.path.basename(path), Temp)) @@ -557,8 +554,6 @@ class AppWindow(QMainWindow): self.data.set_data(_freq, _die_stor, _die_loss) self.data.meta["T"] = Temp self.fit_boundary_imag.setRegion([np.log10(_freq.min()), np.log10(_freq.max())]) -# self.ui.pgPlotWidget_imag.enableAutoRange() -# self.ui.pgPlotWidget_real.enableAutoRange() self.ui.pgPlotWidget_imag.disableAutoRange() self.ui.pgPlotWidget_real.disableAutoRange() @@ -574,11 +569,11 @@ class AppWindow(QMainWindow): self.updatePlot() - def updatePlot(self): + def updatePlot( self ): log10fmin, log10fmax = self.fit_boundary_imag.getRegion() self.data.set_fit_xlimits(10**log10fmin, 10**log10fmax) - p0,funcs = [],[] + p0, funcs = [], [] for fcn in self.function_registry.get_registered_functions(): p0.extend(fcn.getParameter()) funcs.append(fcn) @@ -601,7 +596,7 @@ class AppWindow(QMainWindow): self.data.fitted_curve_imag.setData(x=np.array([np.nan]), y=np.array([np.nan])) - def updateIntermediatePlot(self, freq, intermediate_data): + def updateIntermediatePlot( self, freq, intermediate_data ): self.data.fitted_curve_real.setData(freq, intermediate_data[0]) self.data.fitted_curve_imag.setData(freq, intermediate_data[1]) @@ -619,7 +614,7 @@ class AppWindow(QMainWindow): self.fit_boundary_imag.setRegion(self.fit_boundary_real.getRegion()) self._update_fit_boundary() - def _update_fit_boundary(self): + def _update_fit_boundary( self ): """ Update limits in container. """ @@ -627,7 +622,8 @@ class AppWindow(QMainWindow): lims = [10**i for i in self.fit_boundary_real.getRegion()] container.set_limits(lims) -def sigint_handler(*args): + +def sigint_handler( *args ): """ Handler for the SIGINT signal (CTRL + C). """