ParameterWidgets inside ScrollbarArea;

moved menus to .ui files;
removed some spaces and empty lines
This commit is contained in:
Dominik Demuth 2017-03-15 12:28:28 +01:00
parent a6109c65b9
commit 5e76c419dc
16 changed files with 649 additions and 535 deletions

View File

@ -15,5 +15,6 @@ setup(
'hello': ['*.msg'], 'hello': ['*.msg'],
}, },
license="BSD", license="BSD",
url="https://chaos3.fkp.physik.tu-darmstadt.de/diffusion/QD/QDSfit/" url="https://chaos3.fkp.physik.tu-darmstadt.de/diffusion/QD/QDSfit/", requires=['matplotlib', 'numpy', 'pyqtgraph',
'scipy']
) )

View File

@ -10,11 +10,11 @@ from container_base import BaseContainer
import gui.container_widgets import gui.container_widgets
__author__ = 'markusro' __author__ = 'markusro'
class Conductivity(BaseContainer): class Conductivity(BaseContainer):
def __init__( self, plt_imag=None, plt_real=None, limits=None ): def __init__(self, plt_imag=None, plt_real=None, limits=None):
super(Conductivity, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits) super(Conductivity, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits)
self.widget = gui.container_widgets.ConductivityWidget() self.widget = gui.container_widgets.ConductivityWidget()
self.color = QColor("blue") self.color = QColor("blue")
@ -22,19 +22,18 @@ class Conductivity(BaseContainer):
self.id_string = "cond" self.id_string = "cond"
self.param_number = 3 self.param_number = 3
def function(self, p, x):
def function(self, p ,x):
if self._abort: if self._abort:
raise StopIteration raise StopIteration
return functions.cond_cmplx(p,x) return functions.cond_cmplx(p, x)
def start_parameter(self, pos): def start_parameter(self, pos):
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]
self.set_parameter(beta=cond_par) self.set_parameter(beta=cond_par)
class PowerComplex(BaseContainer): class PowerComplex(BaseContainer):
def __init__( self, plt_real=None, plt_imag=None, limits=None ): def __init__(self, plt_real=None, plt_imag=None, limits=None):
super(PowerComplex, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits) super(PowerComplex, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits)
self.widget = gui.container_widgets.PowerLawWidget() self.widget = gui.container_widgets.PowerLawWidget()
self.color = QColor("#ff44c4") self.color = QColor("#ff44c4")
@ -42,18 +41,18 @@ class PowerComplex(BaseContainer):
self.id_string = "pwr" self.id_string = "pwr"
self.param_number = 2 self.param_number = 2
def function( self, p, x ): def function(self, p, x):
if self._abort: if self._abort:
raise StopIteration raise StopIteration
return functions.power_cmplx(p, x) return functions.power_cmplx(p, x)
def start_parameter(self, pos): def start_parameter(self, pos):
cond_par = [10**(pos.y()+pos.x())*2*np.pi, 1.0] cond_par = [10 ** (pos.y() + pos.x()) * 2 * np.pi, 1.0]
self.set_parameter(cond_par) self.set_parameter(cond_par)
class Static(BaseContainer): class Static(BaseContainer):
def __init__( self, plt_real=None, plt_imag=None, limits=None ): def __init__(self, plt_real=None, plt_imag=None, limits=None):
super(Static, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits) super(Static, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits)
self.widget = gui.container_widgets.StaticWidget() self.widget = gui.container_widgets.StaticWidget()
self.color = QColor('#FF0F13') self.color = QColor('#FF0F13')
@ -61,17 +60,18 @@ class Static(BaseContainer):
self.id_string = "eps_infty" self.id_string = "eps_infty"
self.param_number = 1 self.param_number = 1
def function( self, p, x ): def function(self, p, x):
if self._abort: if self._abort:
raise StopIteration raise StopIteration
return functions.static_cmplx(p, x) return functions.static_cmplx(p, x)
def start_parameter(self, position): def start_parameter(self, position):
cond_par = [10**position.y()] cond_par = [10 ** position.y()]
self.set_parameter(beta=cond_par) self.set_parameter(beta=cond_par)
class Peak(BaseContainer): class Peak(BaseContainer):
def __init__( self, plt_real=None, plt_imag=None, limits=None ): def __init__(self, plt_real=None, plt_imag=None, limits=None):
super(Peak, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits) super(Peak, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits)
self.widget = gui.container_widgets.PeakWidget() self.widget = gui.container_widgets.PeakWidget()
self.id_label = "Hav-Neg" self.id_label = "Hav-Neg"
@ -89,22 +89,23 @@ class Peak(BaseContainer):
self.widget.setColor(self.color) self.widget.setColor(self.color)
self.id_num = id_num self.id_num = id_num
def function( self, p, x ): def function(self, p, x):
if self._abort: if self._abort:
raise StopIteration raise StopIteration
return functions.hn(p, x) return functions.hn(p, x)
def start_parameter(self, pos): def start_parameter(self, pos):
new_peak_beta0 = [2*10**pos.y(), 1/(2*np.pi*10**pos.x()), 1, 1] new_peak_beta0 = [2 * 10 ** pos.y(), 1 / (2 * np.pi * 10 ** pos.x()), 1, 1]
self.set_parameter(beta=new_peak_beta0) self.set_parameter(beta=new_peak_beta0)
class YAFF(BaseContainer): class YAFF(BaseContainer):
def __init__( self, plt_real=None, plt_imag=None, limits=None ): def __init__(self, plt_real=None, plt_imag=None, limits=None):
super(YAFF, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits) super(YAFF, self).__init__(plt_real=plt_real, plt_imag=plt_imag, limits=limits)
self.widget = gui.container_widgets.YaffWidget() self.widget = gui.container_widgets.YaffWidget()
self.widget.on_model_changed.connect(self.change_model) self.widget.on_model_changed.connect(self.change_model)
self.widget.configuration_changed.connect(self.change_configuration) self.widget.configuration_changed.connect(self.change_configuration)
self.color = QColor(32, 120, 29, int(255*0.82)) self.color = QColor(32, 120, 29, int(255 * 0.82))
self._libyaff = yafflib.Yaff(self.widget.getYaffType()) self._libyaff = yafflib.Yaff(self.widget.getYaffType())
self.id_label = self._libyaff.label self.id_label = self._libyaff.label
self.id_string = "yaff" self.id_string = "yaff"
@ -112,26 +113,26 @@ class YAFF(BaseContainer):
self._selector_mask = self.widget.selector_mask self._selector_mask = self.widget.selector_mask
@property @property
def param_number( self ): def param_number(self):
return self._param_number return self._param_number
@param_number.setter @param_number.setter
def param_number( self, num=None ): def param_number(self, num=None):
self._param_number = self._libyaff.params self._param_number = self._libyaff.params
def change_configuration( self, t_list, tau_list ): def change_configuration(self, t_list, tau_list):
self._libyaff.dist_tau = tau_list self._libyaff.dist_tau = tau_list
self._libyaff.time_points = t_list self._libyaff.time_points = t_list
self.update_data() self.update_data()
def change_model( self ): def change_model(self):
self._libyaff = yafflib.Yaff(self.widget.getYaffType()) self._libyaff = yafflib.Yaff(self.widget.getYaffType())
self._selector_mask = self.widget.selector_mask self._selector_mask = self.widget.selector_mask
self.id_label = self._libyaff.label self.id_label = self._libyaff.label
self.param_number = self._libyaff.params self.param_number = self._libyaff.params
self.update_data() self.update_data()
def function( self, p, x ): def function(self, p, x):
if self._abort: if self._abort:
raise StopIteration raise StopIteration
ya = self._libyaff.loss(p, x) ya = self._libyaff.loss(p, x)
@ -139,7 +140,7 @@ class YAFF(BaseContainer):
return cplx return cplx
def start_parameter(self, pos): def start_parameter(self, pos):
gg_y = 10**pos.y()*2 gg_y = 10 ** pos.y() * 2
gg_x = 1/(10**pos.x()*2*np.pi) 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]
self.set_parameter(yaff_par) self.set_parameter(yaff_par)

View File

@ -6,6 +6,7 @@ import abc
__author__ = 'markusro' __author__ = 'markusro'
class QABCMeta(abc.ABCMeta, QObject.__class__): class QABCMeta(abc.ABCMeta, QObject.__class__):
""" """
Allows us to use abstract base class module to fixate the container API. Allows us to use abstract base class module to fixate the container API.
@ -33,7 +34,7 @@ class BaseContainer(QObject):
changedData = pyqtSignal() changedData = pyqtSignal()
removeObj = pyqtSignal(QObject) removeObj = pyqtSignal(QObject)
def __init__( self, plt_real=None, plt_imag=None, limits=None ): def __init__(self, plt_real=None, plt_imag=None, limits=None):
super(BaseContainer, self).__init__() super(BaseContainer, self).__init__()
myPen = pg.mkPen(style=Qt.DotLine, myPen = pg.mkPen(style=Qt.DotLine,
@ -64,91 +65,91 @@ class BaseContainer(QObject):
self._param_number = 0 self._param_number = 0
self._abort = False self._abort = False
def set_limits( self, limits ): def set_limits(self, limits):
self.limits = limits self.limits = limits
self.update_data() self.update_data()
@pyqtSlot(bool) @pyqtSlot(bool)
def abort( self, abort=False ): def abort(self, abort=False):
self._abort = abort self._abort = abort
@property @property
def param_number( self ): def param_number(self):
return self._param_number return self._param_number
@param_number.setter @param_number.setter
def param_number( self, num ): def param_number(self, num):
self._param_number = num self._param_number = num
@property @property
def id_string( self ): def id_string(self):
return self._id_string return self._id_string
@id_string.setter @id_string.setter
def id_string( self, id ): def id_string(self, id):
# self._func = self.functions.get_function(id) # self._func = self.functions.get_function(id)
self._id_string = id self._id_string = id
@property @property
def id_label( self ): def id_label(self):
return self._id_label return self._id_label
@id_label.setter @id_label.setter
def id_label( self, id ): def id_label(self, id):
self._id_label = id self._id_label = id
@property @property
def color( self ): def color(self):
return self._color return self._color
@color.setter @color.setter
def color( self, c ): def color(self, c):
self._color = c self._color = c
self.data_curve_real.setPen(color=c, style=Qt.DotLine, width=2.5) self.data_curve_real.setPen(color=c, style=Qt.DotLine, width=2.5)
self.data_curve_imag.setPen(color=c, style=Qt.DotLine, width=2.5) self.data_curve_imag.setPen(color=c, style=Qt.DotLine, width=2.5)
@property @property
def widget( self ): def widget(self):
return self._widget return self._widget
@widget.setter @widget.setter
def widget( self, wdgt ): def widget(self, wdgt):
self._widget = wdgt self._widget = wdgt
self._widget.changedTable.connect(self.update_data) # TODO better to use self.setParameter self._widget.changedTable.connect(self.update_data) # TODO better to use self.setParameter
self.removeObj.connect(self._widget.deleteLater) self.removeObj.connect(self._widget.deleteLater)
self._widget.removeMe.connect(self.removeMe) self._widget.removeMe.connect(self.removeMe)
def get_parameter( self ): def get_parameter(self):
p = self.widget.getTable() # TODO ugly ... should return self._beta etc ...? p = self.widget.getTable() # TODO ugly ... should return self._beta etc ...?
return p return p
def set_parameter( self, beta, sd_beta=None ): def set_parameter(self, beta, sd_beta=None):
self._beta = beta self._beta = beta
self._sd_beta = sd_beta self._sd_beta = sd_beta
self.widget.update_table(beta, sd_beta) self.widget.update_table(beta, sd_beta)
self.update_data() self.update_data()
def get_fixed( self ): def get_fixed(self):
p = self.widget.fixedParameter() p = self.widget.fixedParameter()
return p return p
def get_data( self ): def get_data(self):
return self._frequency, self._data return self._frequency, self._data
def removeMe( self ): def removeMe(self):
self.plt_imag.removeItem(self.data_curve_imag) self.plt_imag.removeItem(self.data_curve_imag)
self.plt_real.removeItem(self.data_curve_real) self.plt_real.removeItem(self.data_curve_real)
self.removeObj.emit(self) self.removeObj.emit(self)
self.changedData.emit() self.changedData.emit()
def update_data( self ): def update_data(self):
self._frequency = np.logspace(np.log10(self.limits[0]), np.log10(self.limits[1]), 256) self._frequency = np.logspace(np.log10(self.limits[0]), np.log10(self.limits[1]), 256)
self._data = self.function(self.get_parameter(), self._frequency) self._data = self.function(self.get_parameter(), self._frequency)
self.data_curve_real.setData(x=self._frequency, y=self._data[0]) self.data_curve_real.setData(x=self._frequency, y=self._data[0])
self.data_curve_imag.setData(x=self._frequency, y=self._data[1]) self.data_curve_imag.setData(x=self._frequency, y=self._data[1])
self.changedData.emit() self.changedData.emit()
def resampleData( self, x ): def resampleData(self, x):
data = self.function(self.get_parameter(), x) data = self.function(self.get_parameter(), x)
return np.array([x, data[0], data[1]]).T return np.array([x, data[0], data[1]]).T
@ -157,7 +158,7 @@ class BaseContainer(QObject):
self._data = -self._data self._data = -self._data
self.changedData.emit() self.changedData.emit()
def clear_data( self ): def clear_data(self):
self.data_curve_real.setData(x=[np.nan], y=[np.nan]) self.data_curve_real.setData(x=[np.nan], y=[np.nan])
self.data_curve_imag.setData(x=[np.nan], y=[np.nan]) self.data_curve_imag.setData(x=[np.nan], y=[np.nan])
@ -166,9 +167,7 @@ class BaseContainer(QObject):
raise NotImplementedError("This needs to be implemented in your container subclass") raise NotImplementedError("This needs to be implemented in your container subclass")
@abc.abstractmethod @abc.abstractmethod
def function( self, p, x ): def function(self, p, x):
if self._abort: if self._abort:
raise StopIteration raise StopIteration
raise NotImplementedError("This needs to be implemented in your container subclass") raise NotImplementedError("This needs to be implemented in your container subclass")

View File

@ -7,11 +7,11 @@ from libmath.BDSlib import FitFunctionCreator
class Data: class Data:
def __init__( self, frequency=np.zeros(1), die_real=np.zeros(1), die_imag=np.zeros(1) ): def __init__(self, frequency=np.zeros(1), die_real=np.zeros(1), die_imag=np.zeros(1)):
self.frequency = frequency self.frequency = frequency
self.epsilon = die_real+1j*die_imag self.epsilon = die_real + 1j*die_imag
self.frequency_fit = frequency[:] self.frequency_fit = frequency[:]
self.epsilon_fit = die_real[:]*0+1j*die_imag[:]*0 self.epsilon_fit = die_real[:] * 0 + 1j*die_imag[:]*0
myPen_imag = pg.mkPen(width=2.5, color=(255, 255, 127)) myPen_imag = pg.mkPen(width=2.5, color=(255, 255, 127))
myPen_real = pg.mkPen(width=2.5, color=(51, 255, 127)) myPen_real = pg.mkPen(width=2.5, color=(51, 255, 127))
@ -33,41 +33,39 @@ class Data:
self.fit_funcs = None # list of fit functions self.fit_funcs = None # list of fit functions
self.hide_funcs = None # remove these func from the data self.hide_funcs = None # remove these func from the data
def set_fit( self, param, funcs ): def set_fit(self, param, funcs):
self.fit_funcs = funcs self.fit_funcs = funcs
self.hide_funcs = [] self.hide_funcs = []
self.fit_param = param self.fit_param = param
fit_real, fit_imag = FitFunctionCreator().fitfcn(param, self.frequency_fit, *funcs) fit_real, fit_imag = FitFunctionCreator().fitfcn(param, self.frequency_fit, *funcs)
self.epsilon_fit = fit_real+1j*fit_imag self.epsilon_fit = fit_real+1j*fit_imag
def set_data( self, f, e_real, e_imag ): def set_data(self, f, e_real, e_imag):
self.frequency = f self.frequency = f
self.frequency_fit = f[:] self.frequency_fit = f[:]
self.epsilon = e_real+1j*e_imag self.epsilon = e_real + 1j * e_imag
self.epsilon_fit = 0*e_real+1j*e_imag*0 self.epsilon_fit = 0 * e_real + 1j * e_imag * 0
self.fit_limits = [f.min(), f.max(), e_imag.min(), e_imag.max()] self.fit_limits = [f.min(), f.max(), e_imag.min(), e_imag.max()]
self.experimental_curve_imag.setData(f, e_imag) self.experimental_curve_imag.setData(f, e_imag)
self.experimental_curve_real.setData(f, e_real) self.experimental_curve_real.setData(f, e_real)
def set_fit_xlimits( self, xmin, xmax ): def set_fit_xlimits(self, xmin, xmax):
self.fit_limits[0] = xmin self.fit_limits[0] = xmin
self.fit_limits[1] = xmax self.fit_limits[1] = xmax
self.frequency_fit = self.frequency[(self.frequency <= xmax) & (self.frequency >= xmin)] self.frequency_fit = self.frequency[(self.frequency <= xmax) & (self.frequency >= xmin)]
def set_fit_ylimits( self, ymin, ymax ): def set_fit_ylimits(self, ymin, ymax):
self.fit_limits[2] = ymin self.fit_limits[2] = ymin
self.fit_limits[3] = ymax self.fit_limits[3] = ymax
def get_data( self ): def get_data(self):
# mask = np.ones(len(self.frequency), dtype='bool') # mask = np.ones(len(self.frequency), dtype='bool')
mask = (self.frequency > self.fit_limits[0]) & (self.frequency < self.fit_limits[1]) mask = (self.frequency > self.fit_limits[0]) & (self.frequency < self.fit_limits[1])
#mask &= (self.epsilon.imag > self.fit_limits[2]) & (self.epsilon.imag < self.fit_limits[3]) # mask &= (self.epsilon.imag > self.fit_limits[2]) & (self.epsilon.imag < self.fit_limits[3])
return self.frequency[mask], self.epsilon[mask] return self.frequency[mask], self.epsilon[mask]
def remove_curves( self ): def remove_curves(self):
print "remove data_curve" print "remove data_curve"
# if self.data_curve is not None: self.data_curve.remove() # if self.data_curve is not None: self.data_curve.remove()
print "remove fitted_curve" print "remove fitted_curve"
#if self.fitted_curve is not None: self.fitted_curve.remove() # if self.fitted_curve is not None: self.fitted_curve.remove()

View File

@ -3,29 +3,31 @@ import re
from PyQt4.QtGui import QInputDialog from PyQt4.QtGui import QInputDialog
from PyQt4 import QtCore from PyQt4 import QtCore
class FileReader: class FileReader:
@staticmethod @staticmethod
def read_datafile( path ): def read_datafile(path):
# TODO analyze file (LF,MF, HF) and act accordingly # TODO analyze file (LF,MF, HF) and act accordingly
print "Skipping first 4 lines!" # print "Skipping first 4 lines!"
data = np.loadtxt(path, skiprows=4, comments="#") data = np.loadtxt(path, skiprows=4, comments="#")
numpat = re.compile('\d+\.\d+') numpat = re.compile('\d+\.\d+')
print "successfully read %s"%path # print "successfully read %s" % path
try: try:
Temp = None Temp = None
print "Searching for temperature in %s (any line with 'Fixed or 'Temp', with float, i.e. 273.15K or 273.15)" % path # print "Searching for temperature in %s (any line with 'Fixed or 'Temp', with float, i.e. 273.15K or 273.15)" % path
for i,line in enumerate(open(path).readlines()): for i, line in enumerate(open(path).readlines()):
if re.search("Fixed", line) or re.search("Temp", line): if re.search("Fixed", line) or re.search("Temp", line):
print "Found line containing 'Fixed' or 'Temp' (line %i):"%i # print "Found line containing 'Fixed' or 'Temp' (line %i):" % i
print line # print line
Temp = float(re.search(numpat, line).group()) Temp = float(re.search(numpat, line).group())
print "Temperature found in file:", Temp print "Temperature found in file:", Temp
break break
print "Search temperature in file name %s (float +'K')"%path # print "Search temperature in file name %s (float +'K')" % path
search_temp_in_filename = re.search('\d+\.\d+K', path) search_temp_in_filename = re.search('\d+\.\d+K', path)
if search_temp_in_filename: if search_temp_in_filename:
Temp = float(search_temp_in_filename.group()[:-1]) Temp = float(search_temp_in_filename.group()[:-1])
if Temp == None: raise ValueError if Temp is None:
raise ValueError
except: except:
Temp = QInputDialog.getDouble(None, "No temperature found in data set", "Temperature/K:", value=0.00)[0] Temp = QInputDialog.getDouble(None, "No temperature found in data set", "Temperature/K:", value=0.00)[0]
# mask the data to values > 0 (loglog plot) # mask the data to values > 0 (loglog plot)

View File

@ -1,10 +1,6 @@
import re from PyQt4 import QtGui
import PyQt4.QtGui
__author__ = 'markusro' import tempfile, os
import tempfile,os
import numpy as np import numpy as np
@ -37,43 +33,42 @@ class GracePlot(object):
np.savetxt(tmp_name, np.array([x, y]).T) np.savetxt(tmp_name, np.array([x, y]).T)
# read data from temporary file # read data from temporary file
self.cmds.append('READ NXY "%s"\n'%tmp_name) self.cmds.append('READ NXY "{}"\n'.format(tmp_name))
self.cmds.append('S%i SYMBOL SIZE 0.5\n'%(self.data_counter)) self.cmds.append('S{} SYMBOL SIZE 0.5\n'.format(self.data_counter))
self.cmds.append('S%i SYMBOL FILL PATTERN 1\n'%(self.data_counter)) self.cmds.append('S{} SYMBOL FILL PATTERN 1\n'.format(self.data_counter))
self.cmds.append('S%i SYMBOL 1\n'%(self.data_counter)) # No line self.cmds.append('S{} SYMBOL 1\n'.format(self.data_counter)) # No line
if "label" in kwds.keys(): if "label" in kwds.keys():
# TODO: implement at least greek symbols and lower upper case (_ and ^)? # TODO: implement at least greek symbols and lower upper case (_ and ^)?
# with translate method? # with translate method?
label = unicode(kwds["label"]).encode('ascii', 'ignore') label = unicode(kwds["label"]).encode('ascii', 'ignore')
self.cmds.append('S%i LEGEND "%s"\n'%(self.data_counter, label)) self.cmds.append('S{} LEGEND "{}"\n'.format(self.data_counter, label))
if "ls" in kwds.keys(): if "ls" in kwds.keys():
ls = kwds["ls"] ls = kwds["ls"]
if ls in self.ls_map.keys(): if ls in self.ls_map.keys():
self.cmds.append('S%i LINE LINESTYLE %i\n'%(self.data_counter, self.ls_map[ls])) # Line self.cmds.append('S{} LINE LINESTYLE {}\n'.format(self.data_counter, self.ls_map[ls])) # Line
if "sym" in kwds.keys(): if "sym" in kwds.keys():
sym = kwds["sym"] sym = kwds["sym"]
if sym in self.sym_map.keys(): if sym in self.sym_map.keys():
self.cmds.append('S%i SYMBOL %i\n'%(self.data_counter, self.sym_map[sym])) self.cmds.append('S{} SYMBOL {}\n'.format(self.data_counter, self.sym_map[sym]))
if sym in ['+', 'x', '*']: if sym in ['+', 'x', '*']:
self.cmds.append('S%i SYMBOL COLOR %i\n'%(self.data_counter, self.data_counter)) self.cmds.append('S{} SYMBOL COLOR {}\n'.format(self.data_counter, self.data_counter))
else: else:
self.cmds.append('S%i SYMBOL COLOR %i\n' % (self.data_counter, 1)) # vlack symbol outline self.cmds.append('S{} SYMBOL COLOR {}\n'.format(self.data_counter, 1)) # vlack symbol outline
else: else:
print "Symbol not known: %s"%sym print "Symbol not known: {}".format(sym)
if "color" in kwds.keys(): if "color" in kwds.keys():
color = str(PyQt4.QtGui.QColor(kwds["color"]).getRgb()[:3]) color = str(QtGui.QColor(*kwds["color"]).getRgb()[:3])
if color in self.color_map.keys(): if color in self.color_map.keys():
color_id = self.color_map[color][0] color_id = self.color_map[color][0]
else: else:
self.color_map[color] = [ self.color_map[color] = [
self.color_counter, self.color_counter,
"@MAP COLOR %i TO %s, \"qds%i\" \n"% (self.color_counter, color, self.color_counter) "@MAP COLOR {} TO {}, \"qds{}\" \n".format(self.color_counter, color, self.color_counter)
] ]
color_id = self.color_counter color_id = self.color_counter
self.color_counter += 1 self.color_counter += 1
@ -83,8 +78,7 @@ class GracePlot(object):
self.data_counter += 1 self.data_counter += 1
def loglog(self, x, y, **kwds):
def loglog(self, x,y, **kwds):
self.cmds.append('YAXES SCALE LOGARITHMIC\n') self.cmds.append('YAXES SCALE LOGARITHMIC\n')
self.cmds.append("YAXIS TICKLABEL FORMAT POWER\n") self.cmds.append("YAXIS TICKLABEL FORMAT POWER\n")
self.cmds.append("YAXIS TICKLABEL PREC 0\n") self.cmds.append("YAXIS TICKLABEL PREC 0\n")
@ -105,24 +99,20 @@ class GracePlot(object):
self.cmds.append("YAXIS TICKLABEL PREC 0\n") self.cmds.append("YAXIS TICKLABEL PREC 0\n")
self.plot(x, y, **kwds) self.plot(x, y, **kwds)
def xlabel(self, label):
def xlabel(self, label ):
self.cmds.append('XAXIS LABEL "%s"\n'%label) self.cmds.append('XAXIS LABEL "%s"\n'%label)
pass pass
def ylabel(self, label):
def ylabel(self, label ):
self.cmds.append('YAXIS LABEL "%s"\n'%label) self.cmds.append('YAXIS LABEL "%s"\n'%label)
pass pass
def legend(self, on=True): def legend(self, on=True):
if on: if on:
self.cmds.append('LEGEND ON\n') self.cmds.append('LEGEND ON\n')
else: else:
self.cmds.append('LEGEND OFF\n') self.cmds.append('LEGEND OFF\n')
def save(self): def save(self):
self.cmds.append('AUTOSCALE\n') self.cmds.append('AUTOSCALE\n')
self.cmds.append('SAVEALL "%s"\n'%self.fname) self.cmds.append('SAVEALL "%s"\n'%self.fname)
@ -139,7 +129,7 @@ class GracePlot(object):
with file(self.fname, 'r') as original_agr: data = original_agr.readlines() with file(self.fname, 'r') as original_agr: data = original_agr.readlines()
# get the last "@map color ..." line # get the last "@map color ..." line
last_color_lineno = 0 last_color_lineno = 0
for i,line in enumerate(data): for i, line in enumerate(data):
if line.lower().startswith("@map color"): if line.lower().startswith("@map color"):
last_color_lineno = i+1 last_color_lineno = i+1
with file(self.fname, 'w') as new_agr: with file(self.fname, 'w') as new_agr:

View File

@ -5,37 +5,37 @@ from ui import ConductivityGroupBox, PeakGroupBox, StaticGroupBox, PowerLawGroup
__author__ = 'Markus Rosenstihl <markus.rosenstihl@physik.tu-darmstadt.de>' __author__ = 'Markus Rosenstihl <markus.rosenstihl@physik.tu-darmstadt.de>'
from PyQt4.QtGui import * from PyQt4.QtGui import *
from PyQt4.QtCore import QRegExp, pyqtSignal,pyqtSlot from PyQt4.QtCore import QRegExp, pyqtSignal, pyqtSlot
class ParameterWidget(QWidget): class ParameterWidget(QWidget):
def __init__(self, parent = None): def __init__(self, parent=None):
super(ParameterWidget, self).__init__(parent) super(ParameterWidget, self).__init__(parent)
self.vlayout = QVBoxLayout(self) self.vlayout = QVBoxLayout(self)
self.vlayout.addSpacerItem(QSpacerItem(10,10,QSizePolicy.Minimum, QSizePolicy.Expanding) ) self.vlayout.addSpacerItem(QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding))
self.blockSignals(True) self.blockSignals(True)
def add(self, wdgt): def add(self, wdgt):
self.vlayout.insertWidget(self.vlayout.count()-1, wdgt) self.vlayout.insertWidget(self.vlayout.count() - 1, wdgt)
self.vlayout.update() self.vlayout.update()
class LogFSpinBox(QDoubleSpinBox): class LogFSpinBox(QDoubleSpinBox):
scientificNotationValidator = QRegExpValidator(QRegExp("[+-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+-]?\\d+)?")) scientificNotationValidator = QRegExpValidator(QRegExp("[+-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+-]?\\d+)?"))
def __init__(self, parent = None):
def __init__(self, parent=None):
super(LogFSpinBox, self).__init__(parent) super(LogFSpinBox, self).__init__(parent)
self.setRange(0.0,1e18) self.setRange(0.0, 1e18)
self.setMinimum(0) self.setMinimum(0)
self.setDecimals(17) self.setDecimals(17)
self.setValue(1.0) self.setValue(1.0)
def stepBy(self, up_down): def stepBy(self, up_down):
if self.value() != 0.0: if self.value() != 0.0:
self.setValue(self.value()*10**(up_down/9.0)) # 19 steps per decade self.setValue(self.value() * 10 ** (up_down / 9.0)) # 19 steps per decade
def textFromValue(self, value): def textFromValue(self, value):
return "%.3e"%value return "%.3e" % value
def valueFromText(self, str_value): def valueFromText(self, str_value):
return str_value.toDouble()[0] return str_value.toDouble()[0]
@ -44,7 +44,6 @@ class LogFSpinBox(QDoubleSpinBox):
return self.scientificNotationValidator.validate(str_value, p_int) return self.scientificNotationValidator.validate(str_value, p_int)
class BaseWidget(QGroupBox): class BaseWidget(QGroupBox):
changedTable = pyqtSignal() changedTable = pyqtSignal()
removeMe = pyqtSignal() removeMe = pyqtSignal()
@ -57,18 +56,17 @@ class BaseWidget(QGroupBox):
self.errors = [] self.errors = []
self.names = [] self.names = []
self._subtracted = False self._subtracted = False
self.selector_mask = None # TODO: clean up self.selector_mask = None # TODO: clean up
self.func_type="None" self.func_type = "None"
def remove(self): def remove(self):
self.removeMe.emit() self.removeMe.emit()
def subtract(self): def subtract(self):
self.subtract.emit(self._subtracted) self.subtract.emit(self._subtracted)
self._subtracted = not self._subtracted # Toggle state self._subtracted = not self._subtracted # Toggle state
def change_values(self, num):
def change_values( self, num ):
self.changedTable.emit() self.changedTable.emit()
def fixedParameter(self): def fixedParameter(self):
@ -81,33 +79,33 @@ class BaseWidget(QGroupBox):
self.setPalette(palette) self.setPalette(palette)
def getTable(self): def getTable(self):
tmp = [i.value() # selects the number, ignores the status tmp = [i.value() # selects the number, ignores the status
for i in self.inputs] for i in self.inputs]
#print "getTable:", tmp # print "getTable:", tmp
return tmp return tmp
def update(self): def update(self):
self.changedTable.emit() self.changedTable.emit()
def update_table( self, beta, sd_beta=None ): def update_table(self, beta, sd_beta=None):
self.blockSignals(True) self.blockSignals(True)
for i, arg in enumerate(beta): for i, arg in enumerate(beta):
self.inputs[i].setValue(arg) self.inputs[i].setValue(arg)
sd_style="" sd_style = ""
if isinstance(self.inputs[i], LogFSpinBox) and sd_beta is not None: if isinstance(self.inputs[i], LogFSpinBox) and sd_beta is not None:
#if i in (0,) and sd_beta is not None: # if i in (0,) and sd_beta is not None:
sd = "+/- %.3e"%(sd_beta[i]) sd = "+/- %.3e" % (sd_beta[i])
elif isinstance(self.inputs[i], QDoubleSpinBox) and sd_beta is not None: elif isinstance(self.inputs[i], QDoubleSpinBox) and sd_beta is not None:
#elif i in (1,) and sd_beta is not None: # elif i in (1,) and sd_beta is not None:
sd = "+/- %.2f"%(sd_beta[i]) sd = "+/- %.2f" % (sd_beta[i])
if sd_beta is not None: if sd_beta is not None:
if 0.0 < sd_beta[i]/arg < 0.2: if 0.0 < sd_beta[i] / arg < 0.2:
sd_style="background-color: rgba(0, 255, 0, 64);" sd_style = "background-color: rgba(0, 255, 0, 64);"
if 0.2 < sd_beta[i]/arg < 1.0: if 0.2 < sd_beta[i] / arg < 1.0:
sd_style="background-color: rgba(255,255, 0, 64);" sd_style = "background-color: rgba(255,255, 0, 64);"
elif sd_beta[i]/arg > 1.0: elif sd_beta[i] / arg > 1.0:
sd_style="background-color: rgba(255, 0, 0, 64);" sd_style = "background-color: rgba(255, 0, 0, 64);"
else: else:
sd = "( --- )" sd = "( --- )"
@ -117,13 +115,13 @@ class BaseWidget(QGroupBox):
def replaceDoubleSpinBox(self, layout, widget): def replaceDoubleSpinBox(self, layout, widget):
ndx = layout.indexOf(widget) ndx = layout.indexOf(widget)
row, column, cols, rows = layout.getItemPosition(ndx) row, column, cols, rows = layout.getItemPosition(ndx)
widget.setParent(None) widget.setParent(None)
widget = LogFSpinBox(self) widget = LogFSpinBox(self)
layout.addWidget(widget, row,column) layout.addWidget(widget, row, column)
class PeakWidget(BaseWidget,QGroupBox): class PeakWidget(BaseWidget, QGroupBox):
def __init__(self, parent=None): def __init__(self, parent=None):
QGroupBox.__init__(self) QGroupBox.__init__(self)
BaseWidget.__init__(self) BaseWidget.__init__(self)
@ -133,10 +131,10 @@ class PeakWidget(BaseWidget,QGroupBox):
# replace eps and tau with LogFSpinBox # replace eps and tau with LogFSpinBox
self.ui.doubleSpinBox_1.setParent(None) self.ui.doubleSpinBox_1.setParent(None)
self.ui.doubleSpinBox_1 = LogFSpinBox(self) self.ui.doubleSpinBox_1 = LogFSpinBox(self)
self.ui.gridLayout.addWidget(self.ui.doubleSpinBox_1,1,1) self.ui.gridLayout.addWidget(self.ui.doubleSpinBox_1, 1, 1)
self.ui.doubleSpinBox_2.setParent(None) self.ui.doubleSpinBox_2.setParent(None)
self.ui.doubleSpinBox_2 = LogFSpinBox(self) self.ui.doubleSpinBox_2 = LogFSpinBox(self)
self.ui.gridLayout.addWidget(self.ui.doubleSpinBox_2,2,1) self.ui.gridLayout.addWidget(self.ui.doubleSpinBox_2, 2, 1)
self.ui.removeButton.clicked.connect(self.remove) self.ui.removeButton.clicked.connect(self.remove)
@ -147,21 +145,21 @@ class PeakWidget(BaseWidget,QGroupBox):
"beta" "beta"
] ]
self.func_type="HN" self.func_type = "HN"
self.inputs = [ self.inputs = [
self.ui.doubleSpinBox_1, self.ui.doubleSpinBox_1,
self.ui.doubleSpinBox_2, self.ui.doubleSpinBox_2,
self.ui.doubleSpinBox_3, self.ui.doubleSpinBox_3,
self.ui.doubleSpinBox_4 self.ui.doubleSpinBox_4
] ]
self.errors = [ self.errors = [
self.ui.label_5, self.ui.label_5,
self.ui.label_6, self.ui.label_6,
self.ui.label_7, self.ui.label_7,
self.ui.label_8, self.ui.label_8,
] ]
for dsb in self.inputs: for dsb in self.inputs:
dsb.valueChanged.connect(self.change_values) dsb.valueChanged.connect(self.change_values)
@ -172,19 +170,18 @@ class PeakWidget(BaseWidget,QGroupBox):
self.ui.checkBox_4] self.ui.checkBox_4]
self.ui.comboBox.currentIndexChanged.connect(self._distrib_select) self.ui.comboBox.currentIndexChanged.connect(self._distrib_select)
def _distrib_select(self, dist): def _distrib_select(self, dist):
self._distrib_hn(1) self._distrib_hn(1)
if dist == 0: # hav-neg: if dist == 0: # hav-neg:
self._distrib_hn(1) self._distrib_hn(1)
if dist == 1: # Cole-Cole: if dist == 1: # Cole-Cole:
self._distrib_cc(1) self._distrib_cc(1)
if dist == 2: # Cole-Davidson if dist == 2: # Cole-Davidson
self._distrib_cd(1) self._distrib_cd(1)
if dist == 3: # Cole-Davidson if dist == 3: # Cole-Davidson
self._distrib_debye(1) self._distrib_debye(1)
def _distrib_hn( self, state ): def _distrib_hn(self, state):
self.ui.checkBox_3.setChecked(False) self.ui.checkBox_3.setChecked(False)
self.ui.checkBox_3.setDisabled(False) self.ui.checkBox_3.setDisabled(False)
self.ui.checkBox_4.setChecked(False) self.ui.checkBox_4.setChecked(False)
@ -222,7 +219,6 @@ class PeakWidget(BaseWidget,QGroupBox):
self.ui.doubleSpinBox_4.setDisabled(False) self.ui.doubleSpinBox_4.setDisabled(False)
self.func_type = "HN" self.func_type = "HN"
def _distrib_cc(self, state): def _distrib_cc(self, state):
if state: if state:
self.ui.doubleSpinBox_4.setValue(1.0) self.ui.doubleSpinBox_4.setValue(1.0)
@ -237,8 +233,6 @@ class PeakWidget(BaseWidget,QGroupBox):
self.ui.doubleSpinBox_4.setDisabled(False) self.ui.doubleSpinBox_4.setDisabled(False)
self.func_type = "HN" self.func_type = "HN"
def setId(self, id): def setId(self, id):
self.id = id self.id = id
self.setTitle("Peak %i" % id) self.setTitle("Peak %i" % id)
@ -249,33 +243,32 @@ class PeakWidget(BaseWidget,QGroupBox):
self.setPalette(palette) self.setPalette(palette)
# #
# def updateTable(self, beta=None, sd_beta = None): # def updateTable(self, beta=None, sd_beta = None):
# #
# #
# for i, arg in enumerate(beta): # for i, arg in enumerate(beta):
# self.inputs[i].setValue(arg) # self.inputs[i].setValue(arg)
# sd_style="" # sd_style=""
# if i in (0,1) and sd_beta is not None: # if i in (0,1) and sd_beta is not None:
# sd = "+/- %.3e"%(sd_beta[i]) # sd = "+/- %.3e"%(sd_beta[i])
# elif i in (2,3) and sd_beta is not None: # elif i in (2,3) and sd_beta is not None:
# sd = "+/- %.2f"%(sd_beta[i]) # sd = "+/- %.2f"%(sd_beta[i])
# if sd_beta is not None: # if sd_beta is not None:
# if 0.0 < sd_beta[i]/arg < 0.2: # if 0.0 < sd_beta[i]/arg < 0.2:
# sd_style="background-color: rgba(0, 255, 0, 64);" # sd_style="background-color: rgba(0, 255, 0, 64);"
# if 0.2 < sd_beta[i]/arg < 1.0: # if 0.2 < sd_beta[i]/arg < 1.0:
# sd_style="background-color: rgba(255,255, 0, 64);" # sd_style="background-color: rgba(255,255, 0, 64);"
# elif sd_beta[i]/arg > 1.0: # elif sd_beta[i]/arg > 1.0:
# sd_style="background-color: rgba(255, 0, 0, 64);" # sd_style="background-color: rgba(255, 0, 0, 64);"
# #
# else: # else:
# sd = "( --- )" # sd = "( --- )"
# self.errors[i].setStyleSheet(sd_style) # self.errors[i].setStyleSheet(sd_style)
# self.errors[i].setText(sd) # self.errors[i].setText(sd)
class StaticWidget(BaseWidget, QGroupBox): class StaticWidget(BaseWidget, QGroupBox):
def __init__(self, parent=None): def __init__(self, parent=None):
QGroupBox.__init__(self) QGroupBox.__init__(self)
BaseWidget.__init__(self) BaseWidget.__init__(self)
@ -284,25 +277,23 @@ class StaticWidget(BaseWidget, QGroupBox):
self.ui = StaticGroupBox.Ui_StaticGroupBox() self.ui = StaticGroupBox.Ui_StaticGroupBox()
self.ui.setupUi(self) self.ui.setupUi(self)
#self.ui.doubleSpinBox_2.setParent(None) # self.ui.doubleSpinBox_2.setParent(None)
#self.ui.doubleSpinBox_2 = LogFSpinBox(self) # self.ui.doubleSpinBox_2 = LogFSpinBox(self)
#self.ui.gridLayout.addWidget(self.ui.doubleSpinBox_2,1,1) # self.ui.gridLayout.addWidget(self.ui.doubleSpinBox_2,1,1)
self.names = ["e_infty"] self.names = ["e_infty"]
self.errors = [self.ui.label_4] self.errors = [self.ui.label_4]
self.inputs = [self.ui.doubleSpinBox_1] self.inputs = [self.ui.doubleSpinBox_1]
self.fixedCheckBoxes = [ self.ui.checkBox_1] self.fixedCheckBoxes = [self.ui.checkBox_1]
for dsb in self.inputs: for dsb in self.inputs:
dsb.valueChanged.connect(self.change_values) dsb.valueChanged.connect(self.change_values)
self.ui.removeButton.clicked.connect(self.remove) self.ui.removeButton.clicked.connect(self.remove)
self.func_type=r"$\epsilon_\infty$" self.func_type = r"$\epsilon_\infty$"
class ConductivityWidget(BaseWidget, QGroupBox): class ConductivityWidget(BaseWidget, QGroupBox):
def __init__(self, parent=None): def __init__(self, parent=None):
QGroupBox.__init__(self) QGroupBox.__init__(self)
BaseWidget.__init__(self) BaseWidget.__init__(self)
@ -313,16 +304,16 @@ class ConductivityWidget(BaseWidget, QGroupBox):
self.ui.iSigma.setParent(None) self.ui.iSigma.setParent(None)
self.ui.iSigma = LogFSpinBox(self) self.ui.iSigma = LogFSpinBox(self)
self.ui.gridLayout.addWidget(self.ui.iSigma,1,1) self.ui.gridLayout.addWidget(self.ui.iSigma, 1, 1)
self.ui.rSigma.setParent(None) self.ui.rSigma.setParent(None)
self.ui.rSigma = LogFSpinBox(self) self.ui.rSigma = LogFSpinBox(self)
self.ui.gridLayout.addWidget(self.ui.rSigma,2,1) self.ui.gridLayout.addWidget(self.ui.rSigma, 2, 1)
self.ui.removeButton.clicked.connect(self.remove) self.ui.removeButton.clicked.connect(self.remove)
self.ui.pushButton_hide.clicked.connect(self.subtract) self.ui.pushButton_hide.clicked.connect(self.subtract)
self.func_type="Cond." self.func_type = "Cond."
self.names = [ self.names = [
"iSig", "iSig",
@ -330,12 +321,12 @@ class ConductivityWidget(BaseWidget, QGroupBox):
"pwrSig", "pwrSig",
] ]
self.errors = [self.ui.iSigma_sd, self.errors = [self.ui.iSigma_sd,
self.ui.rSigma_sd, self.ui.rSigma_sd,
self.ui.pwrSigma_sd] self.ui.pwrSigma_sd]
self.inputs = [self.ui.iSigma, self.inputs = [self.ui.iSigma,
self.ui.rSigma, self.ui.rSigma,
self.ui.pwrSigma] self.ui.pwrSigma]
self.fixedCheckBoxes = [self.ui.checkBox_1, self.fixedCheckBoxes = [self.ui.checkBox_1,
self.ui.checkBox_2, self.ui.checkBox_2,
@ -344,11 +335,9 @@ class ConductivityWidget(BaseWidget, QGroupBox):
dsb.valueChanged.connect(self.change_values) dsb.valueChanged.connect(self.change_values)
class PowerLawWidget(BaseWidget): class PowerLawWidget(BaseWidget):
def __init__(self, parent=None): def __init__(self, parent=None):
#QGroupBox.__init__(self) # QGroupBox.__init__(self)
BaseWidget.__init__(self) BaseWidget.__init__(self)
super(PowerLawWidget, self).__init__(parent) super(PowerLawWidget, self).__init__(parent)
@ -357,19 +346,19 @@ class PowerLawWidget(BaseWidget):
self.ui.doubleSpinBox_2.setParent(None) self.ui.doubleSpinBox_2.setParent(None)
self.ui.doubleSpinBox_2 = LogFSpinBox(self) self.ui.doubleSpinBox_2 = LogFSpinBox(self)
self.ui.gridLayout.addWidget(self.ui.doubleSpinBox_2,1,1) self.ui.gridLayout.addWidget(self.ui.doubleSpinBox_2, 1, 1)
self.ui.removeButton.clicked.connect(self.remove) self.ui.removeButton.clicked.connect(self.remove)
self.ui.pushButton_hide.toggled.connect(self.subtract) self.ui.pushButton_hide.toggled.connect(self.subtract)
self.func_type="Power Law" self.func_type = "Power Law"
self.names = ["Amp", "pwrAmp"] self.names = ["Amp", "pwrAmp"]
self.errors = [self.ui.label_5, self.errors = [self.ui.label_5,
self.ui.label_6] self.ui.label_6]
self.inputs = [self.ui.doubleSpinBox_2, self.inputs = [self.ui.doubleSpinBox_2,
self.ui.doubleSpinBox_3] self.ui.doubleSpinBox_3]
self.fixedCheckBoxes = [ self.ui.checkBox_2, self.fixedCheckBoxes = [self.ui.checkBox_2,
self.ui.checkBox_3] self.ui.checkBox_3]
for dsb in self.inputs: for dsb in self.inputs:
dsb.valueChanged.connect(self.change_values) dsb.valueChanged.connect(self.change_values)
@ -377,14 +366,14 @@ class PowerLawWidget(BaseWidget):
class YaffWidget(BaseWidget): class YaffWidget(BaseWidget):
on_model_changed = pyqtSignal() on_model_changed = pyqtSignal()
configuration_changed = pyqtSignal(list,list) configuration_changed = pyqtSignal(list, list)
def __init__(self, parent=None): def __init__(self, parent=None):
#QGroupBox.__init__(self) # QGroupBox.__init__(self)
BaseWidget.__init__(self) BaseWidget.__init__(self)
super(YaffWidget, self).__init__(parent) super(YaffWidget, self).__init__(parent)
self.func_type="YAFF" # Todo wie bei peak für gg gb gge etc. self.func_type = "YAFF" # Todo wie bei peak für gg gb gge etc.
self.ui = YAFFparameters.Ui_Form() self.ui = YAFFparameters.Ui_Form()
self.ui.setupUi(self) self.ui.setupUi(self)
@ -431,30 +420,30 @@ class YaffWidget(BaseWidget):
self.ui.label_102 self.ui.label_102
] ]
self.errors = [self.ui.label_1, self.errors = [self.ui.label_1,
self.ui.label_2, self.ui.label_2,
self.ui.label_3, self.ui.label_3,
self.ui.label_4, self.ui.label_4,
self.ui.label_5, self.ui.label_5,
self.ui.label_6, self.ui.label_6,
self.ui.label_7, self.ui.label_7,
self.ui.label_8, self.ui.label_8,
self.ui.label_9, self.ui.label_9,
self.ui.label_10, self.ui.label_10,
] ]
self.inputs = [self.ui.doubleSpinBox_1, self.inputs = [self.ui.doubleSpinBox_1,
self.ui.doubleSpinBox_2, self.ui.doubleSpinBox_2,
self.ui.doubleSpinBox_3, self.ui.doubleSpinBox_3,
self.ui.doubleSpinBox_4, self.ui.doubleSpinBox_4,
self.ui.doubleSpinBox_5, self.ui.doubleSpinBox_5,
self.ui.doubleSpinBox_6, self.ui.doubleSpinBox_6,
self.ui.doubleSpinBox_7, self.ui.doubleSpinBox_7,
self.ui.doubleSpinBox_8, self.ui.doubleSpinBox_8,
self.ui.doubleSpinBox_9, self.ui.doubleSpinBox_9,
self.ui.doubleSpinBox_10, self.ui.doubleSpinBox_10,
] ]
self.fixedCheckBoxes = [ self.ui.checkBox_1, self.fixedCheckBoxes = [self.ui.checkBox_1,
self.ui.checkBox_2, self.ui.checkBox_2,
self.ui.checkBox_3, self.ui.checkBox_3,
self.ui.checkBox_4, self.ui.checkBox_4,
@ -471,32 +460,33 @@ class YaffWidget(BaseWidget):
self._t_list, self._tau_list = None, None self._t_list, self._tau_list = None, None
def configure(self): def configure(self):
qd = YaffConfigWidget(t_list = self._t_list, tau_list = self._tau_list) qd = YaffConfigWidget(t_list=self._t_list, tau_list=self._tau_list)
qd.configuration_changed.connect(self._store_config) qd.configuration_changed.connect(self._store_config)
qd.exec_() qd.exec_()
#qd.show() # qd.show()
def _store_config(self,t_list,tau_list):
def _store_config(self, t_list, tau_list):
self._t_list = t_list self._t_list = t_list
self._tau_list = tau_list self._tau_list = tau_list
self.configuration_changed.emit(t_list,tau_list) self.configuration_changed.emit(t_list, tau_list)
def getYaffType(self): def getYaffType(self):
return self.ui.comboBox.currentIndex() return self.ui.comboBox.currentIndex()
@pyqtSlot(int) @pyqtSlot(int)
def change_model(self,ndx): def change_model(self, ndx):
#ndx = self.ui.comboBox.currentIndex() # ndx = self.ui.comboBox.currentIndex()
mask = [ # 0 show, 1 hide mask = [ # 0 show, 1 hide
(0,0,0,0,1,1,1,1,1,1), # GG (0, 0, 0, 0, 1, 1, 1, 1, 1, 1), # GG
(0,0,0,0,1,1,1,1,0,0), # GGe (0, 0, 0, 0, 1, 1, 1, 1, 0, 0), # GGe
(0,1,1,1,1,0,0,0,1,1), # Gb (0, 1, 1, 1, 1, 0, 0, 0, 1, 1), # Gb
(0,0,0,0,0,0,0,0,1,1), # GG + Gb (0, 0, 0, 0, 0, 0, 0, 0, 1, 1), # GG + Gb
(0,0,0,0,0,0,0,0,0,0), # GGe + Gb (0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # GGe + Gb
] ]
self.names = [] self.names = []
for i,inp in enumerate(self.inputs): for i, inp in enumerate(self.inputs):
self.inputs[i].setDisabled(mask[ndx][i]) self.inputs[i].setDisabled(mask[ndx][i])
self.inputs[i].setHidden(mask[ndx][i]) self.inputs[i].setHidden(mask[ndx][i])
@ -509,52 +499,51 @@ class YaffWidget(BaseWidget):
self.fixedCheckBoxes[i].setHidden(mask[ndx][i]) self.fixedCheckBoxes[i].setHidden(mask[ndx][i])
self.labels[i].setHidden(mask[ndx][i]) self.labels[i].setHidden(mask[ndx][i])
if mask[ndx][i]==0: self.names.append(self._names[i]) if mask[ndx][i] == 0: self.names.append(self._names[i])
self.selector_mask = [not i for i in mask[ndx] ] self.selector_mask = [not i for i in mask[ndx]]
self.on_model_changed.emit() self.on_model_changed.emit()
class YaffConfigWidget(QDialog): class YaffConfigWidget(QDialog):
configuration_changed = pyqtSignal(list,list) configuration_changed = pyqtSignal(list, list)
def __init__(self, parent=None, t_list=None, tau_list=None): def __init__(self, parent=None, t_list=None, tau_list=None):
super(YaffConfigWidget,self).__init__(parent) super(YaffConfigWidget, self).__init__(parent)
self.ui = YAFFConfig.Ui_Dialog() self.ui = YAFFConfig.Ui_Dialog()
self.ui.setupUi(self) self.ui.setupUi(self)
# not working; cannot set values # not working; cannot set values
#self.replaceDoubleSpinBox(self.ui.gridLayout_time, self.ui.doubleSpinBox_tmin) # self.replaceDoubleSpinBox(self.ui.gridLayout_time, self.ui.doubleSpinBox_tmin)
#self.replaceDoubleSpinBox(self.ui.gridLayout_time, self.ui.doubleSpinBox_tmax) # self.replaceDoubleSpinBox(self.ui.gridLayout_time, self.ui.doubleSpinBox_tmax)
#self.replaceDoubleSpinBox(self.ui.gridLayout_tau, self.ui.doubleSpinBox_taumin) # self.replaceDoubleSpinBox(self.ui.gridLayout_tau, self.ui.doubleSpinBox_taumin)
#self.replaceDoubleSpinBox(self.ui.gridLayout_tau, self.ui.doubleSpinBox_taumax) # self.replaceDoubleSpinBox(self.ui.gridLayout_tau, self.ui.doubleSpinBox_taumax)
ndx = self.ui.gridLayout_time.indexOf(self.ui.doubleSpinBox_tmin) ndx = self.ui.gridLayout_time.indexOf(self.ui.doubleSpinBox_tmin)
row, column, cols, rows = self.ui.gridLayout_time.getItemPosition(ndx) row, column, cols, rows = self.ui.gridLayout_time.getItemPosition(ndx)
self.ui.doubleSpinBox_tmin.setParent(None) self.ui.doubleSpinBox_tmin.setParent(None)
self.ui.doubleSpinBox_tmin = LogFSpinBox(self) self.ui.doubleSpinBox_tmin = LogFSpinBox(self)
self.ui.gridLayout_time.addWidget(self.ui.doubleSpinBox_tmin, row, column)
self.ui.gridLayout_time.addWidget(self.ui.doubleSpinBox_tmin, row,column)
ndx = self.ui.gridLayout_time.indexOf(self.ui.doubleSpinBox_tmax) ndx = self.ui.gridLayout_time.indexOf(self.ui.doubleSpinBox_tmax)
row, column, cols, rows = self.ui.gridLayout_time.getItemPosition(ndx) row, column, cols, rows = self.ui.gridLayout_time.getItemPosition(ndx)
self.ui.doubleSpinBox_tmax.setParent(None) self.ui.doubleSpinBox_tmax.setParent(None)
self.ui.doubleSpinBox_tmax = LogFSpinBox(self) self.ui.doubleSpinBox_tmax = LogFSpinBox(self)
self.ui.gridLayout_time.addWidget(self.ui.doubleSpinBox_tmax, row,column) self.ui.gridLayout_time.addWidget(self.ui.doubleSpinBox_tmax, row, column)
ndx = self.ui.gridLayout_tau.indexOf(self.ui.doubleSpinBox_taumin) ndx = self.ui.gridLayout_tau.indexOf(self.ui.doubleSpinBox_taumin)
row, column, cols, rows = self.ui.gridLayout_tau.getItemPosition(ndx) row, column, cols, rows = self.ui.gridLayout_tau.getItemPosition(ndx)
self.ui.doubleSpinBox_taumin.setParent(None) self.ui.doubleSpinBox_taumin.setParent(None)
self.ui.doubleSpinBox_taumin = LogFSpinBox(self) self.ui.doubleSpinBox_taumin = LogFSpinBox(self)
self.ui.gridLayout_tau.addWidget(self.ui.doubleSpinBox_taumin, row,column) self.ui.gridLayout_tau.addWidget(self.ui.doubleSpinBox_taumin, row, column)
ndx = self.ui.gridLayout_tau.indexOf(self.ui.doubleSpinBox_taumax) ndx = self.ui.gridLayout_tau.indexOf(self.ui.doubleSpinBox_taumax)
row, column, cols, rows = self.ui.gridLayout_tau.getItemPosition(ndx) row, column, cols, rows = self.ui.gridLayout_tau.getItemPosition(ndx)
self.ui.doubleSpinBox_taumax.setParent(None) self.ui.doubleSpinBox_taumax.setParent(None)
self.ui.doubleSpinBox_taumax = LogFSpinBox(self) self.ui.doubleSpinBox_taumax = LogFSpinBox(self)
self.ui.gridLayout_tau.addWidget(self.ui.doubleSpinBox_taumax, row,column) self.ui.gridLayout_tau.addWidget(self.ui.doubleSpinBox_taumax, row, column)
if t_list is not None: if t_list is not None:
self.ui.doubleSpinBox_tmin.setValue(t_list[0]) self.ui.doubleSpinBox_tmin.setValue(t_list[0])
@ -585,5 +574,4 @@ class YaffConfigWidget(QDialog):
tau_list = [self.ui.doubleSpinBox_taumin.value(), tau_list = [self.ui.doubleSpinBox_taumin.value(),
self.ui.doubleSpinBox_taumax.value(), self.ui.doubleSpinBox_taumax.value(),
self.ui.spinBox_taun.value()] self.ui.spinBox_taun.value()]
self.configuration_changed.emit(t_list,tau_list) self.configuration_changed.emit(t_list, tau_list)

View File

@ -11,7 +11,7 @@ import pyqtgraph as pg
class Graph(object): class Graph(object):
def __init__(self,x = None, y = None): def __init__(self, x=None, y=None):
super(Graph, self).__init__(self) super(Graph, self).__init__(self)
print "Graph" print "Graph"
self._pen = pg.mkPen(color="w", width=2.0, style=3) self._pen = pg.mkPen(color="w", width=2.0, style=3)
@ -47,7 +47,6 @@ class Graph(object):
gr.setSymbol(s) gr.setSymbol(s)
gr.setStyle(0) gr.setStyle(0)
def update_graph_data(self, x, y_real, y_imag): def update_graph_data(self, x, y_real, y_imag):
""" """
Update Graph data. Update Graph data.
@ -59,8 +58,9 @@ class Graph(object):
self.graph_real.setData(x, y_real) self.graph_real.setData(x, y_real)
self.graph_imag.setData(x, y_imag) self.graph_imag.setData(x, y_imag)
class DataGraph(Graph):
def __init__(self): class DataGraph(Graph):
def __init__(self, x, y):
super(DataGraph, self).__init__() super(DataGraph, self).__init__()
self._pen = pg.mkPen(QColor(0, 0, 0, 0)) self._pen = pg.mkPen(QColor(0, 0, 0, 0))
self.graph_real = pg.PlotDataItem(x=x, y=y, pen=self._pen, symbol="o", symbolBrush=(255, 127, 0, 127)) self.graph_real = pg.PlotDataItem(x=x, y=y, pen=self._pen, symbol="o", symbolBrush=(255, 127, 0, 127))
@ -69,6 +69,7 @@ class DataGraph(Graph):
class GraphObject(Graph, Daten, ModelFunction): class GraphObject(Graph, Daten, ModelFunction):
parameter_changed_signal = pyqtSignal(list) parameter_changed_signal = pyqtSignal(list)
def __init__(self): def __init__(self):
super(GraphObject, self).__init__(self) super(GraphObject, self).__init__(self)
self.data_changed_signal.connect(self.update_graph_data) self.data_changed_signal.connect(self.update_graph_data)

View File

@ -1,8 +1,6 @@
# -*- encoding: utf-8 -*- # -*- encoding: utf-8 -*-
import yafflib import yafflib
__author__ = 'markusro'
from PyQt4.QtGui import QColor from PyQt4.QtGui import QColor
from PyQt4.QtCore import QObject, pyqtSignal, pyqtSlot from PyQt4.QtCore import QObject, pyqtSignal, pyqtSlot
@ -10,7 +8,7 @@ import numpy as np
from scipy import optimize as opt, odr from scipy import optimize as opt, odr
def id_to_color( id ): def id_to_color(id):
colors = [ colors = [
QColor(255, 255, 255), QColor(255, 255, 255),
QColor(168, 149, 17), QColor(168, 149, 17),
@ -22,20 +20,19 @@ def id_to_color( id ):
QColor(31, 105, 7), QColor(31, 105, 7),
QColor(124, 109, 8), QColor(124, 109, 8),
] ]
chosen_color = colors[id%len(colors)] chosen_color = colors[id % len(colors)]
return chosen_color return chosen_color
class FitFunctionCreator(QObject): class FitFunctionCreator(QObject):
new_data = pyqtSignal(np.ndarray, np.ndarray) new_data = pyqtSignal(np.ndarray, np.ndarray)
def __init__( self ): def __init__(self):
super(FitFunctionCreator, self).__init__() super(FitFunctionCreator, self).__init__()
self.data = None self.data = None
self.functions = Functions() self.functions = Functions()
def fitfcn(self, p0, x, *funcs):
def fitfcn( self, p0, x, *funcs ):
if x.ndim == 2: if x.ndim == 2:
self.data = np.zeros(x.shape) self.data = np.zeros(x.shape)
else: else:
@ -43,7 +40,7 @@ class FitFunctionCreator(QObject):
ndx = 0 ndx = 0
for fn in funcs: # loop over functions and add the results for fn in funcs: # loop over functions and add the results
f, num_p = fn.function, fn.param_number f, num_p = fn.function, fn.param_number
p = p0[ndx:ndx+num_p] p = p0[ndx:ndx + num_p]
if x.ndim == 2: if x.ndim == 2:
x = x[0] x = x[0]
result = f(p, x) result = f(p, x)
@ -53,7 +50,7 @@ class FitFunctionCreator(QObject):
self.new_data.emit(x, self.data) self.new_data.emit(x, self.data)
return self.data return self.data
def fitfcn_imag( self, p0, x, *funcs ): def fitfcn_imag(self, p0, x, *funcs):
if x.ndim == 2: if x.ndim == 2:
self.data = np.zeros(x.shape) self.data = np.zeros(x.shape)
else: else:
@ -61,7 +58,7 @@ class FitFunctionCreator(QObject):
ndx = 0 ndx = 0
for fn in funcs: # loop over functions and add the results for fn in funcs: # loop over functions and add the results
f, num_p = fn.function, fn.param_number f, num_p = fn.function, fn.param_number
p = p0[ndx:ndx+num_p] p = p0[ndx:ndx + num_p]
if x.ndim == 2: if x.ndim == 2:
x = x[0] x = x[0]
result = f(p, x) result = f(p, x)
@ -75,7 +72,7 @@ class FitRoutine(QObject):
finished_fit = pyqtSignal() finished_fit = pyqtSignal()
data_ready = pyqtSignal(np.ndarray, np.ndarray) data_ready = pyqtSignal(np.ndarray, np.ndarray)
def __init__( self ): def __init__(self):
super(FitRoutine, self).__init__() super(FitRoutine, self).__init__()
self.f = FitFunctionCreator() self.f = FitFunctionCreator()
self.f.new_data.connect(self.data_ready.emit) self.f.new_data.connect(self.data_ready.emit)
@ -84,53 +81,53 @@ class FitRoutine(QObject):
self._start_parameter = None self._start_parameter = None
@property @property
def start_parameter( self ): def start_parameter(self):
return self._start_parameter return self._start_parameter
@start_parameter.setter @start_parameter.setter
def start_paramter( self, p0 ): def start_parameter(self, p0):
self._start_parameter = p0 self._start_parameter = p0
@property @property
def fitter( self ): def fitter(self):
return self._fitter return self._fitter
@fitter.setter @fitter.setter
def fitter( self, f ): def fitter(self, f):
self._fitter = f self._fitter = f
def fit_odr_cmplx( self, x, y, p0, fixed, fcns ): def fit_odr_cmplx(self, x, y, p0, fixed, fcns):
self._start_parameter = p0 self._start_parameter = p0
if np.iscomplexobj(y) and y.ndim == 1: if np.iscomplexobj(y) and y.ndim == 1:
weights = 1/np.abs(y)**2 weights = 1 / np.abs(y) ** 2
we = np.resize(weights, (2, weights.size)) we = np.resize(weights, (2, weights.size))
# we = 1/N.array([y.real**2, y.imag**2]) # we = 1/N.array([y.real**2, y.imag**2])
y = np.array([y.real, y.imag]) y = np.array([y.real, y.imag])
else: else:
raise NotImplementedError, "need complex input for now" raise NotImplementedError("need complex input for now")
dat = odr.Data(x, y, we=we) dat = odr.Data(x, y, we=we)
mod = odr.Model(self.f.fitfcn, extra_args=fcns) mod = odr.Model(self.f.fitfcn, extra_args=fcns)
self._odr_fit = odr.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=800) self._odr_fit = odr.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=800)
def fit_odr_imag( self, x, y, p0, fixed, fcns ): def fit_odr_imag(self, x, y, p0, fixed, fcns):
self._start_parameter = p0 self._start_parameter = p0
if np.iscomplexobj(y) and y.ndim == 1: if np.iscomplexobj(y) and y.ndim == 1:
we = 1/np.imag(y)**2 we = 1 / np.imag(y) ** 2
else: else:
raise NotImplementedError, "need complex input for now" raise NotImplementedError("need complex input for now")
dat = odr.Data(x, y.imag, we=we) dat = odr.Data(x, y.imag, we=we)
mod = odr.Model(self.f.fitfcn_imag, extra_args=fcns) mod = odr.Model(self.f.fitfcn_imag, extra_args=fcns)
self._odr_fit = odr.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=800) self._odr_fit = odr.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=800)
@pyqtSlot() @pyqtSlot()
def fit( self ): def fit(self):
try: try:
self._odr_fit.run() self._odr_fit.run()
except RuntimeError: except RuntimeError:
print "muh" print "muh"
self.finished_fit.emit() self.finished_fit.emit()
def result( self ): def result(self):
if self._odr_fit.output is None: if self._odr_fit.output is None:
self._odr_fit.output = odr.Output([self.start_parameter, None, None]) self._odr_fit.output = odr.Output([self.start_parameter, None, None])
self._odr_fit.output.stopreason = ["Aborted by user"] self._odr_fit.output.stopreason = ["Aborted by user"]
@ -138,27 +135,27 @@ class FitRoutine(QObject):
class FunctionRegister: class FunctionRegister:
def __init__( self ): def __init__(self):
self.registry = { } self.registry = {}
def register_function( self, obj ): def register_function(self, obj):
# print "FR: Registering:",obj # print "FR: Registering:",obj
id_string = obj.id_label id_string = obj.id_label
if self.registry.has_key(obj): if self.registry.has_key(obj):
raise AssertionError, "The object is already registered! This should NOT happen" raise AssertionError("The object is already registered! This should NOT happen")
self.registry[obj] = id_string self.registry[obj] = id_string
#print "FR: ",self.registry # print "FR: ",self.registry
def unregister_function( self, obj ): def unregister_function(self, obj):
# print "FR: UnRegistering:",obj # print "FR: UnRegistering:",obj
if self.registry.has_key(obj): if self.registry.has_key(obj):
self.registry.pop(obj) self.registry.pop(obj)
else: else:
obj.deleteLater() obj.deleteLater()
raise AssertionError, "The object is not in the registry! This should NOT happen" raise AssertionError("The object is not in the registry! This should NOT happen")
#print "FR: ",self.registry # print "FR: ",self.registry
def get_registered_functions( self ): def get_registered_functions(self):
# returns functions, peaks sorted by tau # returns functions, peaks sorted by tau
sorted_functions = list() sorted_functions = list()
@ -188,28 +185,28 @@ class FunctionRegister:
# ############# deprecated ##################### # ############# deprecated #####################
def fit_odr_cmplx( x, y, p0, fixed, fcns ): def fit_odr_cmplx(x, y, p0, fixed, fcns):
f = FitFunctionCreator() f = FitFunctionCreator()
#if x.ndim < 2: # if x.ndim < 2:
# x = N.resize(x, (2,x.size)) # x = N.resize(x, (2,x.size))
if np.iscomplexobj(y) and y.ndim == 1: if np.iscomplexobj(y) and y.ndim == 1:
weights = 1/np.abs(y)**2 weights = 1 / np.abs(y) ** 2
we = np.resize(weights, (2, weights.size)) we = np.resize(weights, (2, weights.size))
#we = 1/N.array([y.real**2, y.imag**2]) # we = 1/N.array([y.real**2, y.imag**2])
y = np.array([y.real, y.imag]) y = np.array([y.real, y.imag])
else: else:
raise NotImplementedError, "need complex input for now" raise NotImplementedError("need complex input for now")
dat = odr.Data(x, y, we=we) dat = odr.Data(x, y, we=we)
mod = odr.Model(f.fitfcn, extra_args=fcns) mod = odr.Model(f.fitfcn, extra_args=fcns)
fit = odr.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=8000) fit = odr.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=8000)
fit.run() fit.run()
#print fit.output.pprint() # print fit.output.pprint()
return fit.output return fit.output
### define funcs here # define funcs here
class Functions(QObject): class Functions(QObject):
def __init__( self ): def __init__(self):
super(Functions, self).__init__() super(Functions, self).__init__()
self.list = { self.list = {
# provides functions: "id_string":(function, number_of_parameters) # provides functions: "id_string":(function, number_of_parameters)
@ -221,51 +218,56 @@ class Functions(QObject):
} }
self.YAFF = yafflib.Yaff() self.YAFF = yafflib.Yaff()
def hn_cmplx( self, p, x ): @staticmethod
om = 2*np.pi*x def hn_cmplx(p, x):
#hn = om*1j om = 2 * np.pi * x
# hn = om*1j
eps, t, a, b = p eps, t, a, b = p
hn = eps/(1+(1j*om*t)**a)**b hn = eps / (1 + (1j * om * t) ** a) ** b
cplx = np.array([hn.real, -hn.imag]) cplx = np.array([hn.real, -hn.imag])
return cplx return cplx
def cond_cmplx( self, p, x ): @staticmethod
om = 2*np.pi*x def cond_cmplx(p, x):
om = 2 * np.pi * x
sgma, isgma, n = p sgma, isgma, n = p
cond = sgma/(om**n)+isgma/(1j*om**n) # Jonscher (Universal Dielectric Response: e",e' prop sigma/omega**n cond = sgma / (om ** n) + isgma / (
1j * om ** n) # Jonscher (Universal Dielectric Response: e",e' prop sigma/omega**n
cplx = np.array([cond.real, -cond.imag]) cplx = np.array([cond.real, -cond.imag])
return cplx return cplx
def power_cmplx( self, p, x ): @staticmethod
om = 2*np.pi*x def power_cmplx(p, x):
om = 2 * np.pi * x
sgma, n = p sgma, n = p
power = sgma/(om*1j)**n power = sgma / (om * 1j) ** n
cplx = np.array([power.real, -power.imag]) cplx = np.array([power.real, -power.imag])
return cplx return cplx
def static_cmplx( self, p, x ): @staticmethod
def static_cmplx(p, x):
eps_inf = p[0] eps_inf = p[0]
static = np.ones((2, x.size))*eps_inf static = np.ones((2, x.size)) * eps_inf
static[1, :] *= 0 # set imag part zero static[1, :] *= 0 # set imag part zero
#cplx = N.array([static.real, static.imag]) # cplx = N.array([static.real, static.imag])
return static return static
def yaff( self, p, x ): def yaff(self, p, x):
ya = self.YAFF.yaff(p[:8], x) ya = self.YAFF.yaff(p[:8], x)
cplx = np.array([ya.imag, ya.real]) cplx = np.array([ya.imag, ya.real])
return cplx return cplx
def get_name( self, name ): def get_name(self, name):
return self.list[name] return self.list[name]
def get_function( self, name ): def get_function(self, name):
return self.list[name][0] return self.list[name][0]
def fit_anneal( x, y, p0, fixed, funcs ): def fit_anneal(x, y, p0, fixed, funcs):
raise NotImplementedError raise NotImplementedError
bounds = [(0, 1e14), (0, 1)] bounds = [(0, 1e14), (0, 1)]
for i in xrange(len(p0[2:])/4): for i in xrange(len(p0[2:]) / 4):
bounds.append((1e-4, 1e12)) # delta_eps bounds.append((1e-4, 1e12)) # delta_eps
bounds.append((1e-12, 1e3)) # tau bounds.append((1e-12, 1e3)) # tau
bounds.append((0.1, 1)) # a bounds.append((0.1, 1)) # a
@ -278,9 +280,9 @@ def fit_anneal( x, y, p0, fixed, funcs ):
upper=[b[1] for b in bounds], upper=[b[1] for b in bounds],
dwell=100, dwell=100,
full_output=1) full_output=1)
#pmin, func_min, final_Temp, cooling_iters,accepted_tests, retval # pmin, func_min, final_Temp, cooling_iters,accepted_tests, retval
#retval : int # retval : int
#Flag indicating stopping condition:: # Flag indicating stopping condition::
# 0 : Points no longer changing # 0 : Points no longer changing
# 1 : Cooled to final temperature # 1 : Cooled to final temperature
@ -293,11 +295,11 @@ def fit_anneal( x, y, p0, fixed, funcs ):
return ret[0] return ret[0]
def fit_lbfgsb( x, y, p0, fixed, funcs ): def fit_lbfgsb(x, y, p0, fixed, funcs):
raise NotImplementedError raise NotImplementedError
# TODO fixed parameters… # TODO fixed parameters…
bounds = [(0, None), (0, 1)] bounds = [(0, None), (0, 1)]
for i in xrange(len(p0[3:])/4): for i in xrange(len(p0[3:]) / 4):
bounds.append((1e-4, 1e12)) # delta_eps bounds.append((1e-4, 1e12)) # delta_eps
bounds.append((1e-12, 1e3)) # tau bounds.append((1e-12, 1e3)) # tau
bounds.append((0.1, 1)) # a bounds.append((0.1, 1)) # a
@ -317,7 +319,7 @@ def fit_lbfgsb( x, y, p0, fixed, funcs ):
# Replaced with fit_odr_cmplx # Replaced with fit_odr_cmplx
# #
#def fit_odr(x, y, p0, fixed, funcs): # def fit_odr(x, y, p0, fixed, funcs):
# dat = odr.Data(x, y, 1.0 / y**2) # dat = odr.Data(x, y, 1.0 / y**2)
# mod = odr.Model(multi_hn) # mod = odr.Model(multi_hn)
# fit = odr.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=2000) # fit = odr.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=2000)
@ -325,48 +327,45 @@ def fit_lbfgsb( x, y, p0, fixed, funcs ):
# return fit.output.beta # return fit.output.beta
def hn( p, nu ): def hn(p, nu):
delta_eps, tau, a, b = p delta_eps, tau, a, b = p
om = 2*np.pi*nu om = 2 * np.pi * nu
Phi = np.arctan((om*tau)**a*np.sin(np.pi*a/2.)/(1.+(om*tau)**a*np.cos(np.pi*a/2.))) Phi = np.arctan((om * tau) ** a * np.sin(np.pi * a / 2.) / (1. + (om * tau) ** a * np.cos(np.pi * a / 2.)))
e_loss = delta_eps*(1+2*(om*tau)**a*np.cos(np.pi*a/2.)+(om*tau)**(2.*a) )**( e_loss = delta_eps * (1 + 2 * (om * tau) ** a * np.cos(np.pi * a / 2.) + (om * tau) ** (2. * a)) ** (
-b/2.)*np.sin(b*Phi) -b / 2.) * np.sin(b * Phi)
e_stor = delta_eps*(1+2*(om*tau)**a*np.cos(np.pi*a/2.)+(om*tau)**(2.*a) )**( e_stor = delta_eps * (1 + 2 * (om * tau) ** a * np.cos(np.pi * a / 2.) + (om * tau) ** (2. * a)) ** (
-b/2.)*np.cos(b*Phi) -b / 2.) * np.cos(b * Phi)
return e_loss # 2* oder nicht? return e_loss # 2* oder nicht?
def mini_func( p, x, y ): def mini_func(p, x, y):
res = y-multi_hn(p, x) res = y - multi_hn(p, x)
# apply weights # apply weights
res /= 1/y res /= 1 / y
return np.sqrt(np.dot(res, res)) return np.sqrt(np.dot(res, res))
def multi_hn( p, nu ): def multi_hn(p, nu):
conductivity = p[1] conductivity = p[1]
cond_beta = p[2] cond_beta = p[2]
om = 2*np.pi*nu om = 2 * np.pi * nu
e_loss = conductivity/om**cond_beta e_loss = conductivity / om ** cond_beta
e_loss += p[0] e_loss += p[0]
#for key, igroup in groupby(p[3:], lambda x: x//4): # for key, igroup in groupby(p[3:], lambda x: x//4):
for i in xrange(len(p[3:])/4): for i in xrange(len(p[3:]) / 4):
delta_eps, tau, a, b = p[3+i*4:3+(i+1)*4] delta_eps, tau, a, b = p[3 + i * 4:3 + (i + 1) * 4]
#delta_eps, tau, a, b = list(igroup) # delta_eps, tau, a, b = list(igroup)
#print delta_eps,tau,a,b # print delta_eps,tau,a,b
#a = 0.5 *(1 + N.tanh(a)) # a = 0.5 *(1 + N.tanh(a))
#b = 0.5 *(1 + N.tanh(b)) # b = 0.5 *(1 + N.tanh(b))
Phi = np.arctan((om*tau)**a*np.sin(np.pi*a/2.)/(1.+(om*tau)**a*np.cos(np.pi*a/2.))) Phi = np.arctan((om * tau) ** a * np.sin(np.pi * a / 2.) / (1. + (om * tau) ** a * np.cos(np.pi * a / 2.)))
e_loss += 2*delta_eps*(1+2*(om*tau)**a*np.cos(np.pi*a/2.)+(om*tau)**(2.*a) )**( e_loss += 2 * delta_eps * (1 + 2 * (om * tau) ** a * np.cos(np.pi * a / 2.) + (om * tau) ** (2. * a)) ** (
-b/2.)*np.sin(b*Phi) -b / 2.) * np.sin(b * Phi)
#e_stor = delta_eps * (1+ 2*(om*tau)**a * N.cos(N.pi*a/2.) + (om*tau)**(2.*a) )**(-b/2.)*N.cos(b*Phi) # e_stor = delta_eps * (1+ 2*(om*tau)**a * N.cos(N.pi*a/2.) + (om*tau)**(2.*a) )**(-b/2.)*N.cos(b*Phi)
return e_loss return e_loss
def tau_peak( f, a, b ): def tau_peak(f, a, b):
tau = (np.sin(np.pi*a/2./(b+1))/np.sin(np.pi*a*b/2./(b+1)))**(1/a) tau = (np.sin(np.pi * a / 2. / (b + 1)) / np.sin(np.pi * a * b / 2. / (b + 1))) ** (1 / a)
tau /= 2*np.pi*f tau /= 2 * np.pi * f
return tau return tau

View File

@ -7,8 +7,6 @@ __author__ = 'markusro'
class Function(object): class Function(object):
def __init__(self): def __init__(self):
super(Function, self).__init__() super(Function, self).__init__()
self._id_string = None self._id_string = None
@ -16,27 +14,33 @@ class Function(object):
self._pretty_name = "" self._pretty_name = ""
self._function = None self._function = None
@classmethod
def get_id_string(cls): def get_id_string(cls):
if cls._id_string is None: if cls._id_string is None:
raise NotImplementedError("You need to set the id_string") raise NotImplementedError("You need to set the id_string")
return cls._id_string return cls._id_string
@classmethod
def set_id_string(cls, s): def set_id_string(cls, s):
cls._id_string = s cls._id_string = s
@classmethod
def get_num_paramters(cls): def get_num_paramters(cls):
if cls._num_paramters is None: if cls._num_paramters is None:
raise NotImplementedError("You need to set the num_paramters") raise NotImplementedError("You need to set the num_paramters")
return cls._num_paramters return cls._num_paramters
@classmethod
def set_num_paramters(cls, s): def set_num_paramters(cls, s):
cls._num_paramters = s cls._num_paramters = s
@classmethod
def get_function(cls): def get_function(cls):
if cls._function is None: if cls._function is None:
raise NotImplementedError("You need to set f") raise NotImplementedError("You need to set f")
return cls._function return cls._function
@classmethod
def set_function(cls, f): def set_function(cls, f):
cls._function = f cls._function = f
@ -71,7 +75,7 @@ class ConductivityCmplx(Function):
self.set_id_string("conductivity") self.set_id_string("conductivity")
def cond_cmplx(p, x ): def cond_cmplx(p, x):
om = 2*np.pi*x om = 2*np.pi*x
sgma, isgma, n = p sgma, isgma, n = p
cond = sgma/(om**n)+isgma/(1j*om**n) # Jonscher (Universal Dielectric Response: e",e' prop sigma/omega**n cond = sgma/(om**n)+isgma/(1j*om**n) # Jonscher (Universal Dielectric Response: e",e' prop sigma/omega**n
@ -87,7 +91,7 @@ class PowerCmplx(Function):
self.set_id_string("power_law") self.set_id_string("power_law")
def power_cmplx( p, x ): def power_cmplx(p, x):
om = 2*np.pi*x om = 2*np.pi*x
sgma, n = p sgma, n = p
power = sgma/(om*1j)**n power = sgma/(om*1j)**n
@ -103,14 +107,13 @@ class EpsInftyCmplx(Function):
self.set_num_paramters(1) self.set_num_paramters(1)
def static_cmplx(p, x ): def static_cmplx(p, x):
eps_inf = p[0] eps_inf = p[0]
static = np.ones((2, x.size))*eps_inf static = np.ones((2, x.size))*eps_inf
static[1, :] *= 0 # set imag part zero static[1, :] *= 0 # set imag part zero
return static return static
class YaffCmplx(Function): class YaffCmplx(Function):
def __init__(self): def __init__(self):
super(YaffCmplx, self).__init__() super(YaffCmplx, self).__init__()
@ -119,7 +122,7 @@ class YaffCmplx(Function):
self.set_num_paramters(8) self.set_num_paramters(8)
def yaff( p, x ): def yaff(p, x):
#ya = self.YAFF.yaff(p[:8], x) #ya = self.YAFF.yaff(p[:8], x)
ya = yafflib.Yaff.yaff(p[:,0], x) ya = yafflib.Yaff.yaff(p[:,0], x)
cplx = np.array([ya.imag, ya.real]) cplx = np.array([ya.imag, ya.real])
@ -133,7 +136,7 @@ class ModelFunction(object):
@classmethod @classmethod
def select_model(self, model): def select_model(self, model):
self._functions_avail = ", ".join( cls().get_id_string() for cls in Function.__subclasses__()) self._functions_avail = ", ".join(cls().get_id_string() for cls in Function.__subclasses__())
for cls in Function.__subclasses__(): for cls in Function.__subclasses__():
if model == cls().get_id_string(): if model == cls().get_id_string():
self.model = cls() self.model = cls()

View File

@ -1,14 +1,14 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- encoding: utf-8 -*- # -*- encoding: utf-8 -*-
import fileio.gracedriver from __future__ import division
import hashlib
_author_ = "Markus Rosenstihl"
import hashlib, uuid
import time
import os, sys, re, signal
import matplotlib import matplotlib
import os
import re
import signal
import sys
import time
import uuid
matplotlib.use('agg') matplotlib.use('agg')
@ -16,7 +16,6 @@ from matplotlib import pyplot
from matplotlib.colors import hex2color from matplotlib.colors import hex2color
# matplotlib.rc_file("default.mplrc") # matplotlib.rc_file("default.mplrc")
from PyQt4.QtCore import * from PyQt4.QtCore import *
from PyQt4.QtGui import * from PyQt4.QtGui import *
@ -24,36 +23,28 @@ import numpy as np
import pyqtgraph as pg import pyqtgraph as pg
from data.Container import Conductivity, PowerComplex, Static, Peak, YAFF from data.Container import Conductivity, PowerComplex, Static, Peak, YAFF
from gui.container_widgets import ParameterWidget from data.experimental import Data
from ui import QDSMain
from libmath.BDSlib import FunctionRegister, FitRoutine from libmath.BDSlib import FunctionRegister, FitRoutine
from data.experimental import Data from gui.container_widgets import ParameterWidget
from gui import ExtraDifferentialWidget from gui import ExtraDifferentialWidget
from ui import QDSMain
from fileio import bds_file_reader from fileio import bds_file_reader
import fileio.gracedriver
__author__ = "Markus Rosenstihl"
class AppWindow(QMainWindow): class AppWindow(QMainWindow):
def __init__( self, files=[], parent=None ): def __init__(self, files=[], parent=None):
super(AppWindow, self).__init__(parent) super(AppWindow, self).__init__(parent)
self.ui = QDSMain.Ui_MainWindow() self.ui = QDSMain.Ui_MainWindow()
self.ui.setupUi(self) self.ui.setupUi(self)
self._file_paths = self._sortInputFiles(files) self._file_paths = self._sortInputFiles(files)
self._last_written_header = None self._last_written_header = None
# create action group
actions = {
self.ui.actionAdd_Peak: True,
self.ui.actionAdd_Cond: True,
self.ui.actionAdd_PowerLaw: True,
self.ui.actionAdd_Eps_Infty: True,
self.ui.actionYAFF: True,
}
self.myActionGroup = QActionGroup(self)
for a in actions.keys(): self.myActionGroup.addAction(a)
self._init_menu() self._init_menu()
self.function_registry = FunctionRegister() self.function_registry = FunctionRegister()
@ -61,7 +52,12 @@ class AppWindow(QMainWindow):
self.peakId = 0 self.peakId = 0
self.parameterWidget = ParameterWidget() self.parameterWidget = ParameterWidget()
self.ui.dockWidget_3.setWidget(self.parameterWidget)
# if too many widgets are added some of them are outside the display and inaccessible
# so we need a scrollbar
self.ui.scrollArea.setMinimumWidth(278)
self.ui.scrollArea.setWidget(self.parameterWidget)
self.ui.dockWidget_3.hide()
self.data = Data() self.data = Data()
@ -82,6 +78,9 @@ class AppWindow(QMainWindow):
self.fit_boundary_real.sigRegionChanged.connect(self._update_fit_boundary_real) self.fit_boundary_real.sigRegionChanged.connect(self._update_fit_boundary_real)
self.fit_boundary_real.sigRegionChangeFinished.connect(self.update_plot) self.fit_boundary_real.sigRegionChangeFinished.connect(self.update_plot)
# x axis of real and imag are changed together
self.ui.pgPlotWidget_real.setXLink(self.ui.pgPlotWidget_imag)
for pltwidgt in (self.ui.pgPlotWidget_real, self.ui.pgPlotWidget_imag): for pltwidgt in (self.ui.pgPlotWidget_real, self.ui.pgPlotWidget_imag):
pltwidgt.setLogMode(x=True, y=True) pltwidgt.setLogMode(x=True, y=True)
pltwidgt.showGrid(x=True, y=True) pltwidgt.showGrid(x=True, y=True)
@ -106,83 +105,39 @@ class AppWindow(QMainWindow):
self._fit_method.data_ready.connect(self.updateIntermediatePlot) self._fit_method.data_ready.connect(self.updateIntermediatePlot)
self._fit_thread.started.connect(self._fit_method.fit) self._fit_thread.started.connect(self._fit_method.fit)
# finally process cmd line args # finally process cmd line args
if files != []: if files:
self.openFile(unicode(self._file_paths[0])) self.openFile(unicode(self._file_paths[0]))
self._current_file_index = 0 self._current_file_index = 0
def _init_menu( self ): def _init_menu(self):
fileMenu = self.menuBar().addMenu("File")
openFile = QAction("&Open", self)
openFile.setShortcut(QKeySequence.Open)
openFile.triggered.connect(self.getFileNames)
fileMenu.addAction(openFile)
nextFile = QAction("Next", self)
nextFile.setShortcut(QKeySequence("Ctrl+k"))
nextFile.triggered.connect(self.nextFile)
fileMenu.addAction(nextFile)
previousFile = QAction("Previous", self)
previousFile.setShortcut(QKeySequence("Ctrl+j"))
previousFile.triggered.connect(self.previousFile)
fileMenu.addAction(previousFile)
saveFile = QAction("&Save Fit Result (Data)", self)
saveFile.setShortcut(QKeySequence.Save)
saveFile.triggered.connect(self.saveFitResult)
fileMenu.addAction(saveFile)
self.ui.actionSave_FitResult.triggered.connect(lambda: self._saveFitFigure(mode="w")) self.ui.actionSave_FitResult.triggered.connect(lambda: self._saveFitFigure(mode="w"))
self.ui.actionAppend_Fit.triggered.connect(lambda: self._saveFitFigure(mode="a")) self.ui.actionAppend_Fit.triggered.connect(lambda: self._saveFitFigure(mode="a"))
# fitting methods # fitting methods
fitMenu = self.menuBar().addMenu("Standard Fits") self.ui.action_fit_lm.triggered.connect(lambda: self.fitData_start(0))
# lm self.ui.action_NLS_imag.triggered.connect(lambda: self.fitData_start(1))
fit_lmAction = QAction("Complex NLS", self) self.ui.actionSimulated_Annealing.triggered.connect(lambda: self.fitData_start(2))
fit_lmAction.setShortcut(QKeySequence("Ctrl+F"))
fitMenu.addAction(fit_lmAction)
# lbfgsb
fit_lbfgsbAction = QAction("NLS (Imag.)", self)
fitMenu.addAction(fit_lbfgsbAction)
# Simulated Annealing
fit_annealAction = QAction("&Simulated Annealing", self)
fitMenu.addAction(fit_annealAction)
self.ui.actionActionAbortFit.triggered.connect(self.abortFit)
self.signalMapper = QSignalMapper(self)
for i, fit_action in enumerate([fit_lmAction, fit_lbfgsbAction, fit_annealAction
]):
self.signalMapper.setMapping(fit_action, i)
fit_action.triggered.connect(self.signalMapper.map)
self.signalMapper.mapped.connect(self.fitData_start)
self.ui.actionShow_Derivative.triggered.connect(self.show_derivative)
self.ui.menuConfiguration.triggered.connect(self.conf)
@pyqtSlot(name='on_menuConfiguration_triggered')
def conf(self): def conf(self):
pass pass
def show_derivative( self ): @pyqtSlot(name='on_actionShow_Derivative_triggered')
def show_derivative(self):
self.xtra_wdgt = ExtraDifferentialWidget.DifferentialWidget() self.xtra_wdgt = ExtraDifferentialWidget.DifferentialWidget()
#self.xtra_wdgt.set # self.xtra_wdgt.set
deriv_r = np.diff(np.log10(self.data.epsilon.real)) deriv_r = np.diff(np.log10(self.data.epsilon.real))
deriv_i = np.diff(np.log10(self.data.epsilon.imag))*0 # 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(self.data.frequency[:-1], deriv_r, deriv_i)
# self.xtra_wdgt.plot([0,1], [0,1], [0,1]) # self.xtra_wdgt.plot([0,1], [0,1], [0,1])
self.xtra_wdgt.setGeometry(self.ui.pgPlotWidget_real.geometry()) self.xtra_wdgt.setGeometry(self.ui.pgPlotWidget_real.geometry())
self.xtra_wdgt.show() self.xtra_wdgt.show()
#self.xtra_wdgt.showCenterd() # self.xtra_wdgt.showCenterd()
self.xtra_wdgt.raise_() self.xtra_wdgt.raise_()
def updateCrosshair(self, evt):
def updateCrosshair( self, evt ):
vb_real = self.ui.pgPlotWidget_real.getPlotItem().vb vb_real = self.ui.pgPlotWidget_real.getPlotItem().vb
vb_imag = self.ui.pgPlotWidget_imag.getPlotItem().vb vb_imag = self.ui.pgPlotWidget_imag.getPlotItem().vb
if self.ui.pgPlotWidget_imag.underMouse(): if self.ui.pgPlotWidget_imag.underMouse():
@ -193,7 +148,7 @@ class AppWindow(QMainWindow):
pos = QPointF(0.0, 0.0) pos = QPointF(0.0, 0.0)
self.last_pos = pos self.last_pos = pos
def mousePress( self, evt ): def mousePress(self, evt):
data_pos = self.last_pos data_pos = self.last_pos
mouse_in_imag = self.ui.pgPlotWidget_imag.underMouse() mouse_in_imag = self.ui.pgPlotWidget_imag.underMouse()
mouse_in_real = self.ui.pgPlotWidget_real.underMouse() mouse_in_real = self.ui.pgPlotWidget_real.underMouse()
@ -202,14 +157,14 @@ class AppWindow(QMainWindow):
if self.ui.actionAdd_Peak.isChecked(): if self.ui.actionAdd_Peak.isChecked():
if mouse_in_imag: if mouse_in_imag:
id_list = [key.id_num for key in id_list = [key.id_num for key in
self.function_registry.get_registered_functions() self.function_registry.get_registered_functions()
if key.id_string == 'hn'] if key.id_string == 'hn']
self.peakId = 1 self.peakId = 1
while self.peakId in id_list: while self.peakId in id_list:
self.peakId += 1 self.peakId += 1
_pk = self.addContainer(Peak, data_pos) _pk = self.addContainer(Peak, data_pos)
_pk.set_id(self.peakId) _pk.set_id(self.peakId)
# self.addPeak(data_pos) # self.addPeak(data_pos)
self.ui.actionAdd_Peak.setChecked(False) self.ui.actionAdd_Peak.setChecked(False)
else: else:
msgBox.setText("Click in imaginary part") msgBox.setText("Click in imaginary part")
@ -247,21 +202,19 @@ class AppWindow(QMainWindow):
msgBox.setText("Click in real part") msgBox.setText("Click in real part")
msgBox.exec_() msgBox.exec_()
def abortFit( self ): @pyqtSlot(name='on_actionActionAbortFit_triggered')
def abortFit(self):
for container in self.function_registry.get_registered_functions(): for container in self.function_registry.get_registered_functions():
container.abort(True) container.abort(True)
self._fit_thread.terminate() self._fit_thread.terminate()
def saveFitResult( self ): @pyqtSlot(name='on_action_saveFile_triggered')
def saveFitResult(self):
""" """
Saving fit parameters to fitresults.log Saving fit parameters to fitresults.log
including temperature including temperature
""" """
self._saveFitFigure() self._saveFitFigure()
if not os.path.exists("fitresults.log"):
f = open("fitresults.log", "w")
else:
f = open("fitresults.log", "a")
# prepare header # prepare header
file_id = hashlib.md5(open(self._file_paths[self._current_file_index]).read()).hexdigest() file_id = hashlib.md5(open(self._file_paths[self._current_file_index]).read()).hexdigest()
@ -275,28 +228,29 @@ class AppWindow(QMainWindow):
for i_fcn, fcn in enumerate(self.function_registry.get_registered_functions()): for i_fcn, fcn in enumerate(self.function_registry.get_registered_functions()):
fit_function_name = fcn.id_string fit_function_name = fcn.id_string
for i, name in enumerate(fcn.widget.names): # get variable names for i, name in enumerate(fcn.widget.names): # get variable names
header += "{n:13}{n_sd:13}".format(n="%i:%s"%(varnum, name), n_sd="%i:%s_sd"%(varnum+1, name)) header += "{n:13}{n_sd:13}".format(n="%i:%s" % (varnum, name), n_sd="%i:%s_sd" % (varnum + 1, name))
varnum += 2 varnum += 2
pre_header += "# %s\n"%fit_function_name pre_header += "# %s\n" % fit_function_name
# write for each function an extra file # write for each function an extra file
fit_filename = "%s_%i.fit"%(base_filename, i_fcn) fit_filename = "%s_%i.fit" % (base_filename, i_fcn)
f_fcn = open(fit_filename, 'w') f_fcn = open(fit_filename, 'w')
print 'Save to {}'.format(fit_filename)
# retrieve correct function type peak # retrieve correct function type peak
#if fit_function_name == "hn": # if fit_function_name == "hn":
f_fcn.write("# type=%s\n"%fcn.widget.func_type) f_fcn.write("# type=%s\n" % fcn.widget.func_type)
f_fcn.write("# SourceID=%s\n"%file_id) f_fcn.write("# SourceID=%s\n" % file_id)
#else: # else:
# f_fcn.write("# type=%s\n"%fit_function_name) # 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 is not None:
if fcn._selector_mask[i]: if fcn._selector_mask[i]:
pars.extend([par]) pars.extend([par])
pars.extend([fcn._sd_beta[i]]) pars.extend([fcn._sd_beta[i]])
f_fcn.write('# param=%s %e %e\n'%(fcn.widget.names[i], par, fcn._sd_beta[i])) f_fcn.write('# param=%s %e %e\n' % (fcn.widget.names[i], par, fcn._sd_beta[i]))
else: else:
pars.extend([par]) pars.extend([par])
pars.extend([fcn._sd_beta[i]]) pars.extend([fcn._sd_beta[i]])
f_fcn.write('# param=%s %e %e\n'%(fcn.widget.names[i], par, fcn._sd_beta[i])) f_fcn.write('# param=%s %e %e\n' % (fcn.widget.names[i], par, fcn._sd_beta[i]))
# finish writing fit function file # finish writing fit function file
f_fcn.flush() f_fcn.flush()
@ -304,8 +258,15 @@ class AppWindow(QMainWindow):
f_fcn.close() f_fcn.close()
# append fit limits header # append fit limits header
header += "%-13s%-13s\n"%("fit_xlow", "fit_xhigh") header += "%-13s%-13s\n" % ("fit_xlow", "fit_xhigh")
fpath = os.path.split(self.filepath)[0]
save_fname = os.path.join(fpath, "fitresults.log")
if not os.path.exists(save_fname):
f = open(save_fname, "w")
else:
f = open(save_fname, "a")
print 'Save fitresults to {}'.format(save_fname)
# write new header if fit model changed TODO: more robust detection # write new header if fit model changed TODO: more robust detection
if self._last_written_header != header: if self._last_written_header != header:
f.write(pre_header) f.write(pre_header)
@ -316,19 +277,19 @@ class AppWindow(QMainWindow):
pass pass
pars.insert(0, self.data.meta["T"]) pars.insert(0, self.data.meta["T"])
pars.insert(1, 1e3/self.data.meta["T"]) pars.insert(1, 1e3 / self.data.meta["T"])
pars.append(self.data.fit_limits[0]) pars.append(self.data.fit_limits[0])
pars.append(self.data.fit_limits[1]) pars.append(self.data.fit_limits[1])
pars = np.array([pars]) pars = np.array([pars])
np.savetxt(f, pars, fmt='%-12.3e', delimiter=" ") np.savetxt(f, pars, fmt='%-12.3e', delimiter=" ")
f.close() f.close()
def _saveFitFigure( self , mode="w"): def _saveFitFigure(self, mode="w"):
fig = pyplot.figure(figsize=(3.54*1.4, 2.75*1.4)) fig = pyplot.figure(figsize=(3.54 * 1.4, 2.75 * 1.4))
font = { 'family': 'sans serif', font = {'family': 'sans serif',
'weight': 'normal', 'weight': 'normal',
'size': 9 } 'size': 9}
matplotlib.rc('font', **font) matplotlib.rc('font', **font)
pyplot.grid(linestyle="solid", alpha=0.3, color="0.5") pyplot.grid(linestyle="solid", alpha=0.3, color="0.5")
@ -342,15 +303,16 @@ class AppWindow(QMainWindow):
color = hex2color(str(fcn.color.name())) 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) for i in (0, 1):
pyplot.legend(title="T=%.1f K"%(self.data.meta["T"])) 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.xlabel('f/Hz')
pyplot.ylabel(u'ε"') 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]+".png")
pyplot.savefig(os.path.splitext(self.filepath)[0]+".pdf") pyplot.savefig(os.path.splitext(self.filepath)[0] + ".pdf")
fig.clear() fig.clear()
del (fig) del fig
self._saveFitFigureGrace(mode) self._saveFitFigureGrace(mode)
def _saveFitFigureGrace(self, mode="w"): def _saveFitFigureGrace(self, mode="w"):
@ -375,18 +337,19 @@ class AppWindow(QMainWindow):
color = hex2color(str(fcn.color.name())) color = hex2color(str(fcn.color.name()))
self.grace_plot.loglog(f, eps[1], ls=":", color=color, sym=None, label=label) self.grace_plot.loglog(f, eps[1], ls=":", color=color, sym=None, label=label)
# vertical lines (fit limits) # vertical lines (fit limits)
#for i in (0, 1): pyplot.axvline(x=self.data.fit_limits[i], color='b', ls="-", lw=0.5) # for i in (0, 1): pyplot.axvline(x=self.data.fit_limits[i], color='b', ls="-", lw=0.5)
self.grace_plot.legend(True) self.grace_plot.legend(True)
self.grace_plot.xlabel("f / Hz") self.grace_plot.xlabel("f / Hz")
self.grace_plot.ylabel("eps") self.grace_plot.ylabel("eps")
print self.grace_plot.cmds # print self.grace_plot.cmds
self.grace_plot.save() self.grace_plot.save()
def addContainer(self, selected_container, pos): def addContainer(self, selected_container, pos):
if not self.ui.dockWidget_3.isVisible():
self.ui.dockWidget_3.show()
_cont = selected_container(plt_real=self.ui.pgPlotWidget_real, _cont = selected_container(plt_real=self.ui.pgPlotWidget_real,
plt_imag=self.ui.pgPlotWidget_imag, plt_imag=self.ui.pgPlotWidget_imag,
limits=self.data.fit_limits) limits=self.data.fit_limits)
_cont.blockSignals(True) _cont.blockSignals(True)
_cont.changedData.connect(self.update_plot) _cont.changedData.connect(self.update_plot)
_cont.removeObj.connect(self.delParamterObject) _cont.removeObj.connect(self.delParamterObject)
@ -397,12 +360,12 @@ class AppWindow(QMainWindow):
_cont.blockSignals(False) _cont.blockSignals(False)
return _cont return _cont
def delParamterObject( self, obj ): def delParamterObject(self, obj):
self.function_registry.unregister_function(obj) self.function_registry.unregister_function(obj)
self.update_plot() self.update_plot()
def fitData_start( self, method ): def fitData_start(self, method):
#fit_methods = [fit_odr_cmplx, fit_odr_imag, fit_lbfgsb, fit_anneal] # fit_methods = [fit_odr_cmplx, fit_odr_imag, fit_lbfgsb, fit_anneal]
self.fit_boundary_real.hide() self.fit_boundary_real.hide()
self.fit_boundary_imag.hide() self.fit_boundary_imag.hide()
fit_method = [ fit_method = [
@ -420,14 +383,15 @@ class AppWindow(QMainWindow):
_freq, _fit = self.data.get_data() _freq, _fit = self.data.get_data()
if not self._fit_thread.isRunning(): if not self._fit_thread.isRunning():
#self._fit_method.fit_odr_cmplx(_freq, _fit, p0, fixed_params, funcs) # self._fit_method.fit_odr_cmplx(_freq, _fit, p0, fixed_params, funcs)
fit_method(_freq, _fit, p0, fixed_params, funcs) fit_method(_freq, _fit, p0, fixed_params, funcs)
self._fit_thread.start() self._fit_thread.start()
self.ui.statusbar.showMessage("Fitting ...") self.ui.statusbar.showMessage("Fitting ...")
else: else:
self.ui.statusbar.showMessage("Still fitting ...") self.ui.statusbar.showMessage("Still fitting ...")
def fitData_update( self ): @pyqtSlot()
def fitData_update(self):
self._fit_thread.quit() self._fit_thread.quit()
odr_result = self._fit_method.result() odr_result = self._fit_method.result()
p0, funcs, fixed_params = [], [], [] p0, funcs, fixed_params = [], [], []
@ -444,9 +408,9 @@ class AppWindow(QMainWindow):
ndx = 0 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.get_parameter()) num_p = len(fcn.get_parameter())
beta = odr_result.beta[ndx:num_p+ndx] beta = odr_result.beta[ndx:num_p + ndx]
if odr_result.sd_beta is not None: if odr_result.sd_beta is not None:
sd_beta = odr_result.sd_beta[ndx:num_p+ndx] sd_beta = odr_result.sd_beta[ndx:num_p + ndx]
else: else:
sd_beta = None sd_beta = None
fcn.set_parameter(beta, sd_beta) fcn.set_parameter(beta, sd_beta)
@ -455,17 +419,19 @@ class AppWindow(QMainWindow):
self.fit_boundary_real.show() self.fit_boundary_real.show()
self.fit_boundary_imag.show() self.fit_boundary_imag.show()
def getFileNames( self ): @pyqtSlot(name='on_action_openFile_triggered')
tmp = QFileDialog.getOpenFileNames(self, "Open file", "", '*.dat *.TXT') def getFileNames(self):
tmp = QFileDialog().getOpenFileNames(self, "Open file", "", '*.dat *.TXT')
if len(tmp) != 0: if len(tmp) != 0:
self._file_paths = tmp self._file_paths = tmp
self._current_file_index = 0 self._current_file_index = 0
path = unicode(self._file_paths[self._current_file_index]) path = unicode(self._file_paths[self._current_file_index])
self.openFile(path) self.openFile(path)
def nextFile( self ): @pyqtSlot(name='on_action_nextFile_triggered')
def nextFile(self):
lim = self.fit_boundary_imag.getRegion() # store limits lim = self.fit_boundary_imag.getRegion() # store limits
if len(self._file_paths) > self._current_file_index+1: # wrap around if len(self._file_paths) > self._current_file_index + 1: # wrap around
self._current_file_index += 1 self._current_file_index += 1
else: else:
self._current_file_index = 0 self._current_file_index = 0
@ -473,26 +439,26 @@ class AppWindow(QMainWindow):
self.openFile(path) self.openFile(path)
self.fit_boundary_imag.setRegion(lim) self.fit_boundary_imag.setRegion(lim)
def previousFile( self ): @pyqtSlot(name='on_action_previousFile_triggered')
def previousFile(self):
lim = self.fit_boundary_imag.getRegion() # store limits lim = self.fit_boundary_imag.getRegion() # store limits
if self._current_file_index == 0: # wrap around if self._current_file_index == 0: # wrap around
self._current_file_index = len(self._file_paths)-1 self._current_file_index = len(self._file_paths) - 1
else: else:
self._current_file_index -= 1 self._current_file_index -= 1
path = unicode(self._file_paths[self._current_file_index]) path = unicode(self._file_paths[self._current_file_index])
self.openFile(path) self.openFile(path)
self.fit_boundary_imag.setRegion(lim) self.fit_boundary_imag.setRegion(lim)
def _sortInputFiles( self, files ): def _sortInputFiles(self, files):
return QStringList(sorted(files, key=lambda x: re.findall("\d+\.\d+K", x))) 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
print "opening: %s"%path
self.filepath = path self.filepath = path
Temp, _die_loss, _die_stor, _freq = bds_file_reader.FileReader.read_datafile(path) Temp, _die_loss, _die_stor, _freq = bds_file_reader.FileReader.read_datafile(path)
self.setWindowTitle("%s - %.2f K"%(os.path.basename(path), Temp)) self.setWindowTitle("%s - %.2f K" % (os.path.basename(path), Temp))
self.data.set_data(_freq, _die_stor, _die_loss) self.data.set_data(_freq, _die_stor, _die_loss)
self.data.meta["T"] = Temp self.data.meta["T"] = Temp
@ -506,70 +472,67 @@ class AppWindow(QMainWindow):
self.ui.pgPlotWidget_real.setXRange(np.log10(_freq.min()), np.log10(_freq.max())) self.ui.pgPlotWidget_real.setXRange(np.log10(_freq.min()), np.log10(_freq.max()))
self.ui.pgPlotWidget_real.setYRange(np.log10(_die_stor.min()), np.log10(_die_stor.max())) self.ui.pgPlotWidget_real.setYRange(np.log10(_die_stor.min()), np.log10(_die_stor.max()))
# self.ui.pgPlotWidget_real.setRange(xRange=(_freq.min(), _freq.max()),
#self.ui.pgPlotWidget_real.setRange(xRange=(_freq.min(), _freq.max()),
# yRange=(_die_stor.min(), _die_stor.max()) ) # yRange=(_die_stor.min(), _die_stor.max()) )
self.update_plot() self.update_plot()
def update_plot(self):
def update_plot( self ): # print "redrawing plot", self.sender()
print "redrawing plot", self.sender()
log10fmin, log10fmax = self.fit_boundary_imag.getRegion() log10fmin, log10fmax = self.fit_boundary_imag.getRegion()
self.data.set_fit_xlimits(10**log10fmin, 10**log10fmax) self.data.set_fit_xlimits(10 ** log10fmin, 10 ** log10fmax)
p0, funcs = [], [] p0, funcs = [], []
for fcn in self.function_registry.get_registered_functions(): for fcn in self.function_registry.get_registered_functions():
p0.extend(fcn.get_parameter()) p0.extend(fcn.get_parameter())
funcs.append(fcn) funcs.append(fcn)
# calculate parametrized curve # calculate parametrized curve
self.data.set_fit(p0, funcs) self.data.set_fit(p0, funcs)
# replot data and fit, TODO: replot only if measurement data changed # replot data and fit, TODO: replot only if measurement data changed
self.data.experimental_curve_real.setData(self.data.frequency, self.data.epsilon.real) self.data.experimental_curve_real.setData(self.data.frequency, self.data.epsilon.real)
self.data.experimental_curve_imag.setData(self.data.frequency, self.data.epsilon.imag) self.data.experimental_curve_imag.setData(self.data.frequency, self.data.epsilon.imag)
#print "updatePlot: ",self.data.frequency_fit, self.data.epsilon_fit # print "updatePlot: ",self.data.frequency_fit, self.data.epsilon_fit
if len(funcs) > 0: if len(funcs) > 0:
#print "funcs > 0:",self.data.frequency_fit, self.data.epsilon_fit # print "funcs > 0:",self.data.frequency_fit, self.data.epsilon_fit
self.data.model_curve_real.setData(x=self.data.frequency_fit, y=self.data.epsilon_fit.real) self.data.model_curve_real.setData(x=self.data.frequency_fit, y=self.data.epsilon_fit.real)
self.data.model_curve_imag.setData(x=self.data.frequency_fit, y=self.data.epsilon_fit.imag) self.data.model_curve_imag.setData(x=self.data.frequency_fit, y=self.data.epsilon_fit.imag)
else: # else:
self.data.model_curve_real.setData(x=np.array([np.nan]), y=np.array([np.nan])) # self.data.model_curve_real.setData(x=np.array([np.nan]), y=np.array([np.nan]))
self.data.model_curve_imag.setData(x=np.array([np.nan]), y=np.array([np.nan])) # self.data.model_curve_imag.setData(x=np.array([np.nan]), y=np.array([np.nan]))
@pyqtSlot(object, object)
def updateIntermediatePlot( self, freq, intermediate_data ): def updateIntermediatePlot(self, freq, intermediate_data):
self.data.model_curve_real.setData(freq, intermediate_data[0]) self.data.model_curve_real.setData(freq, intermediate_data[0])
self.data.model_curve_imag.setData(freq, intermediate_data[1]) self.data.model_curve_imag.setData(freq, intermediate_data[1])
def _update_fit_boundary_imag( self ): def _update_fit_boundary_imag(self):
""" """
Update real region when with imag reagion Update real region when with imag reagion
""" """
self.fit_boundary_real.setRegion(self.fit_boundary_imag.getRegion()) self.fit_boundary_real.setRegion(self.fit_boundary_imag.getRegion())
self._update_fit_boundary() self._update_fit_boundary()
def _update_fit_boundary_real( self ): def _update_fit_boundary_real(self):
""" """
Update imag region when with real reagion Update imag region when with real reagion
""" """
self.fit_boundary_imag.setRegion(self.fit_boundary_real.getRegion()) self.fit_boundary_imag.setRegion(self.fit_boundary_real.getRegion())
self._update_fit_boundary() self._update_fit_boundary()
def _update_fit_boundary( self ): def _update_fit_boundary(self):
""" """
Update limits in container. Update limits in container.
""" """
for container in self.function_registry.get_registered_functions(): for container in self.function_registry.get_registered_functions():
lims = [10**i for i in self.fit_boundary_real.getRegion()] lims = [10 ** i for i in self.fit_boundary_real.getRegion()]
container.set_limits(lims) container.set_limits(lims)
def sigint_handler( *args ): def sigint_handler(*args):
""" """
Handler for the SIGINT signal (CTRL + C). Handler for the SIGINT signal (CTRL + C).
Does this really work?
""" """
sys.stderr.write('\r') sys.stderr.write('\r')
if QMessageBox.question(None, '', "Are you sure you want to quit?", if QMessageBox.question(None, '', "Are you sure you want to quit?",

View File

@ -2,8 +2,7 @@
# Form implementation generated from reading ui file 'ui/PeakGroupBox.ui' # Form implementation generated from reading ui file 'ui/PeakGroupBox.ui'
# #
# Created: Wed Sep 24 21:21:48 2014 # Created by: PyQt4 UI code generator 4.11.4
# by: PyQt4 UI code generator 4.11.1
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!
@ -27,13 +26,13 @@ class Ui_PeakGroupBox(object):
def setupUi(self, PeakGroupBox): def setupUi(self, PeakGroupBox):
PeakGroupBox.setObjectName(_fromUtf8("PeakGroupBox")) PeakGroupBox.setObjectName(_fromUtf8("PeakGroupBox"))
PeakGroupBox.setEnabled(True) PeakGroupBox.setEnabled(True)
PeakGroupBox.resize(269, 179) PeakGroupBox.resize(269, 218)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0) sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0) sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(PeakGroupBox.sizePolicy().hasHeightForWidth()) sizePolicy.setHeightForWidth(PeakGroupBox.sizePolicy().hasHeightForWidth())
PeakGroupBox.setSizePolicy(sizePolicy) PeakGroupBox.setSizePolicy(sizePolicy)
PeakGroupBox.setMinimumSize(QtCore.QSize(0, 0)) PeakGroupBox.setMinimumSize(QtCore.QSize(269, 0))
PeakGroupBox.setAutoFillBackground(False) PeakGroupBox.setAutoFillBackground(False)
PeakGroupBox.setFlat(False) PeakGroupBox.setFlat(False)
PeakGroupBox.setCheckable(False) PeakGroupBox.setCheckable(False)
@ -42,8 +41,8 @@ class Ui_PeakGroupBox(object):
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.gridLayout = QtGui.QGridLayout() self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize) self.gridLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.gridLayout.setSpacing(1)
self.gridLayout.setContentsMargins(0, 0, -1, -1) self.gridLayout.setContentsMargins(0, 0, -1, -1)
self.gridLayout.setSpacing(1)
self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.label = QtGui.QLabel(PeakGroupBox) self.label = QtGui.QLabel(PeakGroupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)

View File

@ -10,7 +10,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>269</width> <width>269</width>
<height>179</height> <height>218</height>
</rect> </rect>
</property> </property>
<property name="sizePolicy"> <property name="sizePolicy">
@ -21,7 +21,7 @@
</property> </property>
<property name="minimumSize"> <property name="minimumSize">
<size> <size>
<width>0</width> <width>269</width>
<height>0</height> <height>0</height>
</size> </size>
</property> </property>

View File

@ -2,8 +2,7 @@
# Form implementation generated from reading ui file 'ui/QDSMain.ui' # Form implementation generated from reading ui file 'ui/QDSMain.ui'
# #
# Created: Fri Jan 9 21:17:26 2015 # Created by: PyQt4 UI code generator 4.11.4
# by: PyQt4 UI code generator 4.11.3
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!
@ -26,7 +25,7 @@ except AttributeError:
class Ui_MainWindow(object): class Ui_MainWindow(object):
def setupUi(self, MainWindow): def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(956, 699) MainWindow.resize(956, 687)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0) sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0) sizePolicy.setVerticalStretch(0)
@ -40,6 +39,7 @@ class Ui_MainWindow(object):
self.centralwidget.setSizePolicy(sizePolicy) self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setMargin(0)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.splitter = QtGui.QSplitter(self.centralwidget) self.splitter = QtGui.QSplitter(self.centralwidget)
self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setOrientation(QtCore.Qt.Horizontal)
@ -63,12 +63,16 @@ class Ui_MainWindow(object):
self.verticalLayout.addWidget(self.splitter) self.verticalLayout.addWidget(self.splitter)
MainWindow.setCentralWidget(self.centralwidget) MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow) self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 956, 22)) self.menubar.setGeometry(QtCore.QRect(0, 0, 956, 30))
self.menubar.setObjectName(_fromUtf8("menubar")) self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuExtras = QtGui.QMenu(self.menubar) self.menuExtras = QtGui.QMenu(self.menubar)
self.menuExtras.setObjectName(_fromUtf8("menuExtras")) self.menuExtras.setObjectName(_fromUtf8("menuExtras"))
self.menuConfiguration = QtGui.QMenu(self.menubar) self.menuConfiguration = QtGui.QMenu(self.menubar)
self.menuConfiguration.setObjectName(_fromUtf8("menuConfiguration")) self.menuConfiguration.setObjectName(_fromUtf8("menuConfiguration"))
self.fileMenu = QtGui.QMenu(self.menubar)
self.fileMenu.setObjectName(_fromUtf8("fileMenu"))
self.menuStandard_Fits = QtGui.QMenu(self.menubar)
self.menuStandard_Fits.setObjectName(_fromUtf8("menuStandard_Fits"))
MainWindow.setMenuBar(self.menubar) MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar")) self.statusbar.setObjectName(_fromUtf8("statusbar"))
@ -83,6 +87,18 @@ class Ui_MainWindow(object):
self.dockWidget_3.setObjectName(_fromUtf8("dockWidget_3")) self.dockWidget_3.setObjectName(_fromUtf8("dockWidget_3"))
self.dockWidgetContents_4 = QtGui.QWidget() self.dockWidgetContents_4 = QtGui.QWidget()
self.dockWidgetContents_4.setObjectName(_fromUtf8("dockWidgetContents_4")) self.dockWidgetContents_4.setObjectName(_fromUtf8("dockWidgetContents_4"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.dockWidgetContents_4)
self.verticalLayout_2.setMargin(0)
self.verticalLayout_2.setSpacing(0)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.scrollArea = QtGui.QScrollArea(self.dockWidgetContents_4)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 82, 512))
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout_2.addWidget(self.scrollArea)
self.dockWidget_3.setWidget(self.dockWidgetContents_4) self.dockWidget_3.setWidget(self.dockWidgetContents_4)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget_3) MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget_3)
self.actionAdd_Peak = QtGui.QAction(MainWindow) self.actionAdd_Peak = QtGui.QAction(MainWindow)
@ -130,7 +146,30 @@ class Ui_MainWindow(object):
icon6.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/append_save_fit.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon6.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/append_save_fit.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionAppend_Fit.setIcon(icon6) self.actionAppend_Fit.setIcon(icon6)
self.actionAppend_Fit.setObjectName(_fromUtf8("actionAppend_Fit")) self.actionAppend_Fit.setObjectName(_fromUtf8("actionAppend_Fit"))
self.action_openFile = QtGui.QAction(MainWindow)
self.action_openFile.setObjectName(_fromUtf8("action_openFile"))
self.action_nextFile = QtGui.QAction(MainWindow)
self.action_nextFile.setObjectName(_fromUtf8("action_nextFile"))
self.action_previousFile = QtGui.QAction(MainWindow)
self.action_previousFile.setObjectName(_fromUtf8("action_previousFile"))
self.action_saveFile = QtGui.QAction(MainWindow)
self.action_saveFile.setObjectName(_fromUtf8("action_saveFile"))
self.action_fit_lm = QtGui.QAction(MainWindow)
self.action_fit_lm.setObjectName(_fromUtf8("action_fit_lm"))
self.action_NLS_imag = QtGui.QAction(MainWindow)
self.action_NLS_imag.setObjectName(_fromUtf8("action_NLS_imag"))
self.actionSimulated_Annealing = QtGui.QAction(MainWindow)
self.actionSimulated_Annealing.setObjectName(_fromUtf8("actionSimulated_Annealing"))
self.menuExtras.addAction(self.actionShow_Derivative) self.menuExtras.addAction(self.actionShow_Derivative)
self.fileMenu.addAction(self.action_openFile)
self.fileMenu.addAction(self.action_nextFile)
self.fileMenu.addAction(self.action_previousFile)
self.fileMenu.addAction(self.action_saveFile)
self.menuStandard_Fits.addAction(self.action_fit_lm)
self.menuStandard_Fits.addAction(self.action_NLS_imag)
self.menuStandard_Fits.addAction(self.actionSimulated_Annealing)
self.menubar.addAction(self.fileMenu.menuAction())
self.menubar.addAction(self.menuStandard_Fits.menuAction())
self.menubar.addAction(self.menuExtras.menuAction()) self.menubar.addAction(self.menuExtras.menuAction())
self.menubar.addAction(self.menuConfiguration.menuAction()) self.menubar.addAction(self.menuConfiguration.menuAction())
self.toolBar.addAction(self.actionAdd_Peak) self.toolBar.addAction(self.actionAdd_Peak)
@ -152,16 +191,22 @@ class Ui_MainWindow(object):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.menuExtras.setTitle(_translate("MainWindow", "Extras", None)) self.menuExtras.setTitle(_translate("MainWindow", "Extras", None))
self.menuConfiguration.setTitle(_translate("MainWindow", "Configuration", None)) self.menuConfiguration.setTitle(_translate("MainWindow", "Configuration", None))
self.fileMenu.setTitle(_translate("MainWindow", "File", None))
self.menuStandard_Fits.setTitle(_translate("MainWindow", "Standard Fits", None))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar", None)) self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar", None))
self.actionAdd_Peak.setText(_translate("MainWindow", "Add Peak", None)) self.actionAdd_Peak.setText(_translate("MainWindow", "Add Peak", None))
self.actionAdd_Peak.setShortcut(_translate("MainWindow", "Alt+1", None))
self.actionAdd_Cond.setText(_translate("MainWindow", "Add Cond.", None)) self.actionAdd_Cond.setText(_translate("MainWindow", "Add Cond.", None))
self.actionAdd_Cond.setToolTip(_translate("MainWindow", "Added Conductivity Term", None)) self.actionAdd_Cond.setToolTip(_translate("MainWindow", "Added Conductivity Term", None))
self.actionAdd_Cond.setShortcut(_translate("MainWindow", "Alt+2", None))
self.actionSave_FitResult.setText(_translate("MainWindow", "Save Fit", None)) self.actionSave_FitResult.setText(_translate("MainWindow", "Save Fit", None))
self.actionSave_FitResult.setToolTip(_translate("MainWindow", "Save Fit Result", None)) self.actionSave_FitResult.setToolTip(_translate("MainWindow", "Save Fit Result", None))
self.actionAdd_PowerLaw.setText(_translate("MainWindow", "Add Power Law", None)) self.actionAdd_PowerLaw.setText(_translate("MainWindow", "Add Power Law", None))
self.actionAdd_PowerLaw.setToolTip(_translate("MainWindow", "Add (complex) Power Law", None)) self.actionAdd_PowerLaw.setToolTip(_translate("MainWindow", "Add (complex) Power Law", None))
self.actionAdd_PowerLaw.setShortcut(_translate("MainWindow", "Alt+3", None))
self.actionAdd_Eps_Infty.setText(_translate("MainWindow", "Add e_infty", None)) self.actionAdd_Eps_Infty.setText(_translate("MainWindow", "Add e_infty", None))
self.actionAdd_Eps_Infty.setToolTip(_translate("MainWindow", "Add eps_infty", None)) self.actionAdd_Eps_Infty.setToolTip(_translate("MainWindow", "Add eps_infty", None))
self.actionAdd_Eps_Infty.setShortcut(_translate("MainWindow", "Alt+4", None))
self.actionYAFF.setText(_translate("MainWindow", "YAFF", None)) self.actionYAFF.setText(_translate("MainWindow", "YAFF", None))
self.actionYAFF.setToolTip(_translate("MainWindow", "Fit with YAFF", None)) self.actionYAFF.setToolTip(_translate("MainWindow", "Fit with YAFF", None))
self.actionActionAbortFit.setText(_translate("MainWindow", "Abort Fit", None)) self.actionActionAbortFit.setText(_translate("MainWindow", "Abort Fit", None))
@ -169,6 +214,19 @@ class Ui_MainWindow(object):
self.actionShow_Derivative.setText(_translate("MainWindow", "Show Derivative", None)) self.actionShow_Derivative.setText(_translate("MainWindow", "Show Derivative", None))
self.actionAppend_Fit.setText(_translate("MainWindow", "Append Fit", None)) self.actionAppend_Fit.setText(_translate("MainWindow", "Append Fit", None))
self.actionAppend_Fit.setToolTip(_translate("MainWindow", "Appends current plot to existing plot.", None)) self.actionAppend_Fit.setToolTip(_translate("MainWindow", "Appends current plot to existing plot.", None))
self.action_openFile.setText(_translate("MainWindow", "&Open", None))
self.action_openFile.setShortcut(_translate("MainWindow", "Ctrl+O", None))
self.action_nextFile.setText(_translate("MainWindow", "Next", None))
self.action_nextFile.setShortcut(_translate("MainWindow", "Ctrl+K", None))
self.action_previousFile.setText(_translate("MainWindow", "Previous", None))
self.action_previousFile.setShortcut(_translate("MainWindow", "Ctrl+J", None))
self.action_saveFile.setText(_translate("MainWindow", "&Save Fit Result (Data)", None))
self.action_saveFile.setShortcut(_translate("MainWindow", "Ctrl+S", None))
self.action_fit_lm.setText(_translate("MainWindow", "Complex NLS", None))
self.action_fit_lm.setShortcut(_translate("MainWindow", "Ctrl+F", None))
self.action_NLS_imag.setText(_translate("MainWindow", "NLS (Imag.)", None))
self.action_NLS_imag.setShortcut(_translate("MainWindow", "Ctrl+Shift+F", None))
self.actionSimulated_Annealing.setText(_translate("MainWindow", "Simulated Annealing", None))
from pyqtgraph import PlotWidget from pyqtgraph import PlotWidget
import images_rc import images_rc

View File

@ -7,7 +7,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>956</width> <width>956</width>
<height>699</height> <height>687</height>
</rect> </rect>
</property> </property>
<property name="sizePolicy"> <property name="sizePolicy">
@ -27,6 +27,9 @@
</sizepolicy> </sizepolicy>
</property> </property>
<layout class="QVBoxLayout" name="verticalLayout"> <layout class="QVBoxLayout" name="verticalLayout">
<property name="margin">
<number>0</number>
</property>
<item> <item>
<widget class="QSplitter" name="splitter"> <widget class="QSplitter" name="splitter">
<property name="orientation"> <property name="orientation">
@ -64,7 +67,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>956</width> <width>956</width>
<height>22</height> <height>30</height>
</rect> </rect>
</property> </property>
<widget class="QMenu" name="menuExtras"> <widget class="QMenu" name="menuExtras">
@ -78,6 +81,25 @@
<string>Configuration</string> <string>Configuration</string>
</property> </property>
</widget> </widget>
<widget class="QMenu" name="fileMenu">
<property name="title">
<string>File</string>
</property>
<addaction name="action_openFile"/>
<addaction name="action_nextFile"/>
<addaction name="action_previousFile"/>
<addaction name="action_saveFile"/>
</widget>
<widget class="QMenu" name="menuStandard_Fits">
<property name="title">
<string>Standard Fits</string>
</property>
<addaction name="action_fit_lm"/>
<addaction name="action_NLS_imag"/>
<addaction name="actionSimulated_Annealing"/>
</widget>
<addaction name="fileMenu"/>
<addaction name="menuStandard_Fits"/>
<addaction name="menuExtras"/> <addaction name="menuExtras"/>
<addaction name="menuConfiguration"/> <addaction name="menuConfiguration"/>
</widget> </widget>
@ -120,7 +142,33 @@
<attribute name="dockWidgetArea"> <attribute name="dockWidgetArea">
<number>1</number> <number>1</number>
</attribute> </attribute>
<widget class="QWidget" name="dockWidgetContents_4"/> <widget class="QWidget" name="dockWidgetContents_4">
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="spacing">
<number>0</number>
</property>
<property name="margin">
<number>0</number>
</property>
<item>
<widget class="QScrollArea" name="scrollArea">
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>82</width>
<height>512</height>
</rect>
</property>
</widget>
</widget>
</item>
</layout>
</widget>
</widget> </widget>
<action name="actionAdd_Peak"> <action name="actionAdd_Peak">
<property name="checkable"> <property name="checkable">
@ -133,6 +181,9 @@
<property name="text"> <property name="text">
<string>Add Peak</string> <string>Add Peak</string>
</property> </property>
<property name="shortcut">
<string>Alt+1</string>
</property>
</action> </action>
<action name="actionAdd_Cond"> <action name="actionAdd_Cond">
<property name="checkable"> <property name="checkable">
@ -148,6 +199,9 @@
<property name="toolTip"> <property name="toolTip">
<string>Added Conductivity Term</string> <string>Added Conductivity Term</string>
</property> </property>
<property name="shortcut">
<string>Alt+2</string>
</property>
</action> </action>
<action name="actionSave_FitResult"> <action name="actionSave_FitResult">
<property name="icon"> <property name="icon">
@ -175,6 +229,9 @@
<property name="toolTip"> <property name="toolTip">
<string>Add (complex) Power Law</string> <string>Add (complex) Power Law</string>
</property> </property>
<property name="shortcut">
<string>Alt+3</string>
</property>
</action> </action>
<action name="actionAdd_Eps_Infty"> <action name="actionAdd_Eps_Infty">
<property name="checkable"> <property name="checkable">
@ -190,6 +247,9 @@
<property name="toolTip"> <property name="toolTip">
<string>Add eps_infty</string> <string>Add eps_infty</string>
</property> </property>
<property name="shortcut">
<string>Alt+4</string>
</property>
</action> </action>
<action name="actionYAFF"> <action name="actionYAFF">
<property name="checkable"> <property name="checkable">
@ -235,6 +295,59 @@
<string>Appends current plot to existing plot.</string> <string>Appends current plot to existing plot.</string>
</property> </property>
</action> </action>
<action name="action_openFile">
<property name="text">
<string>&amp;Open</string>
</property>
<property name="shortcut">
<string>Ctrl+O</string>
</property>
</action>
<action name="action_nextFile">
<property name="text">
<string>Next</string>
</property>
<property name="shortcut">
<string>Ctrl+K</string>
</property>
</action>
<action name="action_previousFile">
<property name="text">
<string>Previous</string>
</property>
<property name="shortcut">
<string>Ctrl+J</string>
</property>
</action>
<action name="action_saveFile">
<property name="text">
<string>&amp;Save Fit Result (Data)</string>
</property>
<property name="shortcut">
<string>Ctrl+S</string>
</property>
</action>
<action name="action_fit_lm">
<property name="text">
<string>Complex NLS</string>
</property>
<property name="shortcut">
<string>Ctrl+F</string>
</property>
</action>
<action name="action_NLS_imag">
<property name="text">
<string>NLS (Imag.)</string>
</property>
<property name="shortcut">
<string>Ctrl+Shift+F</string>
</property>
</action>
<action name="actionSimulated_Annealing">
<property name="text">
<string>Simulated Annealing</string>
</property>
</action>
</widget> </widget>
<customwidgets> <customwidgets>
<customwidget> <customwidget>

View File

@ -2,8 +2,7 @@
# Form implementation generated from reading ui file 'ui/YAFFparameters.ui' # Form implementation generated from reading ui file 'ui/YAFFparameters.ui'
# #
# Created: Wed Sep 24 21:21:48 2014 # Created by: PyQt4 UI code generator 4.11.4
# by: PyQt4 UI code generator 4.11.1
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!