Fit limits are shown and labeles

Size of PeakBox elements are now OK
Conductivity moved to data
This commit is contained in:
Markus Rosenstihl 2013-07-10 18:36:07 +02:00
parent 4f6421ae22
commit 805a726346
11 changed files with 464 additions and 420 deletions

View File

@ -2,8 +2,8 @@
# Form implementation generated from reading ui file 'ConductivityGroupBox.ui'
#
# Created: Fri Jun 14 08:45:33 2013
# by: PyQt4 UI code generator 4.10.1
# Created: Wed Jul 10 18:32:01 2013
# by: PyQt4 UI code generator 4.10.2
#
# WARNING! All changes made in this file will be lost!

View File

@ -6,15 +6,16 @@ import ConductivityGroupBox
class ConductivityWidget(QGroupBox):
changedTable = pyqtSignal()
def __init__(self, parent=None):
QGroupBox.__init__(self)
super(ConductivityWidget, self).__init__(parent)
self.setTitle(u"Conductivity …")
self.ui = ConductivityGroupBox.Ui_ConductivityGroupBox()
self.ui.setupUi(self)
self.lineEdits = [self.ui.lineEdit_1,
self.ui.lineEdit_2,
self.ui.lineEdit_3]
self.lineEdits = [self.ui.lineEdit_1,
self.ui.lineEdit_2,
self.ui.lineEdit_3]
self.fixedCheckBoxes = [self.ui.checkBox_1,
self.ui.checkBox_2,
self.ui.checkBox_3]
@ -22,13 +23,13 @@ class ConductivityWidget(QGroupBox):
le.editingFinished.connect(self.changedTable.emit)
self.signalMapper = QSignalMapper(self)
for i, button in enumerate([self.ui.pushButton_1,
self.ui.pushButton_2,
self.ui.pushButton_3,
self.ui.pushButton_4,
self.ui.pushButton_5,
self.ui.pushButton_6,
]):
self.signalMapper.setMapping(button,i)
self.ui.pushButton_2,
self.ui.pushButton_3,
self.ui.pushButton_4,
self.ui.pushButton_5,
self.ui.pushButton_6,
]):
self.signalMapper.setMapping(button, i)
button.clicked.connect(self.signalMapper.map)
self.signalMapper.mapped.connect(self.changeValues)
@ -38,38 +39,38 @@ class ConductivityWidget(QGroupBox):
# 0-3 down/up for d_eps and tau, respectively
# 4-7 down, up for a, b
if num == 0:
self.ui.lineEdit_1.setText("%.2e"%(self.ui.lineEdit_1.text().toDouble()[0]/logstep))
self.ui.lineEdit_1.setText("%.2e" % (self.ui.lineEdit_1.text().toDouble()[0] / logstep))
if num == 1:
self.ui.lineEdit_1.setText("%.2e"%(self.ui.lineEdit_1.text().toDouble()[0]*logstep))
self.ui.lineEdit_1.setText("%.2e" % (self.ui.lineEdit_1.text().toDouble()[0] * logstep))
if num == 2:
self.ui.lineEdit_2.setText("%.2e"%(self.ui.lineEdit_2.text().toDouble()[0]/logstep))
self.ui.lineEdit_2.setText("%.2e" % (self.ui.lineEdit_2.text().toDouble()[0] / logstep))
if num == 3:
self.ui.lineEdit_2.setText("%.2e"%(self.ui.lineEdit_2.text().toDouble()[0]*logstep))
self.ui.lineEdit_2.setText("%.2e" % (self.ui.lineEdit_2.text().toDouble()[0] * logstep))
if num == 4:
self.ui.lineEdit_3.setText("%.2e"%(self.ui.lineEdit_3.text().toDouble()[0]-linstep))
self.ui.lineEdit_3.setText("%.2e" % (self.ui.lineEdit_3.text().toDouble()[0] - linstep))
if num == 5:
self.ui.lineEdit_3.setText("%.2e"%(self.ui.lineEdit_3.text().toDouble()[0]+linstep))
self.ui.lineEdit_3.setText("%.2e" % (self.ui.lineEdit_3.text().toDouble()[0] + linstep))
self.changedTable.emit()
def fixedParameter(self):
return [0 if cb.isChecked() else 1 for cb in self.fixedCheckBoxes]
def setColor(self, color):
r,g,b = color
r, g, b = color
palette = self.palette()
palette.setColor(QPalette.Foreground, QColor(r,g,b))
palette.setColor(QPalette.Foreground, QColor(r, g, b))
self.setPalette(palette)
def getTable(self):
tmp = [i.text().toDouble()[0] # selects the number, ignores the status
for i in self.lineEdits ]
print "peakParams:",tmp
for i in self.lineEdits]
print "peakParams:", tmp
return tmp
def update(self):
self.changedTable.emit()
def updateTable(self, *args):
for i,arg in enumerate(args):
self.lineEdits[i].setText("%g"%(args[i]))
for i, arg in enumerate(args):
self.lineEdits[i].setText("%g" % (args[i]))

View File

@ -25,6 +25,7 @@ from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as Canvas
from matplotlib.figure import Figure
from matplotlib import rcParams
rcParams['font.size'] = 9
@ -61,6 +62,7 @@ class MatplotlibWidget(Canvas):
self.widget.axes.plot(x, x**2)
self.wdiget.axes.plot(x, x**3)
"""
def __init__(self, parent=None, title='', xlabel='', ylabel='',
xlim=None, ylim=None, xscale='linear', yscale='linear',
width=6, height=4, dpi=100, hold=False):
@ -93,7 +95,6 @@ class MatplotlibWidget(Canvas):
return QSize(10, 10)
#===============================================================================
# Example
#===============================================================================
@ -101,7 +102,7 @@ if __name__ == '__main__':
import sys
from PyQt4.QtGui import QMainWindow, QApplication
from numpy import linspace
class ApplicationWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
@ -112,12 +113,12 @@ if __name__ == '__main__':
self.mplwidget.setFocus()
self.setCentralWidget(self.mplwidget)
self.plot(self.mplwidget.axes)
def plot(self, axes):
x = linspace(-10, 10)
axes.plot(x, x**2)
axes.plot(x, x**3)
axes.plot(x, x ** 2)
axes.plot(x, x ** 3)
app = QApplication(sys.argv)
win = ApplicationWindow()
win.show()

View File

@ -2,8 +2,8 @@
# Form implementation generated from reading ui file 'PeakGroupBox.ui'
#
# Created: Fri Jun 14 08:45:33 2013
# by: PyQt4 UI code generator 4.10.1
# Created: Wed Jul 10 18:32:01 2013
# by: PyQt4 UI code generator 4.10.2
#
# WARNING! All changes made in this file will be lost!
@ -27,16 +27,18 @@ class Ui_PeakGroupBox(object):
def setupUi(self, PeakGroupBox):
PeakGroupBox.setObjectName(_fromUtf8("PeakGroupBox"))
PeakGroupBox.setEnabled(True)
PeakGroupBox.resize(385, 230)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding)
PeakGroupBox.resize(320, 210)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(PeakGroupBox.sizePolicy().hasHeightForWidth())
PeakGroupBox.setSizePolicy(sizePolicy)
PeakGroupBox.setMinimumSize(QtCore.QSize(275, 210))
PeakGroupBox.setMinimumSize(QtCore.QSize(308, 210))
PeakGroupBox.setAutoFillBackground(False)
PeakGroupBox.setFlat(False)
PeakGroupBox.setCheckable(False)
self.gridLayout_2 = QtGui.QGridLayout(PeakGroupBox)
self.gridLayout_2.setMargin(10)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
@ -48,13 +50,12 @@ class Ui_PeakGroupBox(object):
self.checkBox_2.setObjectName(_fromUtf8("checkBox_2"))
self.gridLayout.addWidget(self.checkBox_2, 2, 4, 1, 1)
self.lineEdit_3 = QtGui.QLineEdit(PeakGroupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit_3.sizePolicy().hasHeightForWidth())
self.lineEdit_3.setSizePolicy(sizePolicy)
self.lineEdit_3.setMinimumSize(QtCore.QSize(128, 0))
self.lineEdit_3.setMaximumSize(QtCore.QSize(90, 16777215))
self.lineEdit_3.setMinimumSize(QtCore.QSize(96, 0))
self.lineEdit_3.setObjectName(_fromUtf8("lineEdit_3"))
self.gridLayout.addWidget(self.lineEdit_3, 3, 1, 1, 1)
self.checkBox_3 = QtGui.QCheckBox(PeakGroupBox)
@ -66,7 +67,7 @@ class Ui_PeakGroupBox(object):
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_7.sizePolicy().hasHeightForWidth())
self.pushButton_7.setSizePolicy(sizePolicy)
self.pushButton_7.setMinimumSize(QtCore.QSize(64, 0))
self.pushButton_7.setMinimumSize(QtCore.QSize(56, 0))
self.pushButton_7.setObjectName(_fromUtf8("pushButton_7"))
self.gridLayout.addWidget(self.pushButton_7, 4, 2, 1, 1)
self.label_2 = QtGui.QLabel(PeakGroupBox)
@ -79,13 +80,12 @@ class Ui_PeakGroupBox(object):
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 1)
self.lineEdit_4 = QtGui.QLineEdit(PeakGroupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit_4.sizePolicy().hasHeightForWidth())
self.lineEdit_4.setSizePolicy(sizePolicy)
self.lineEdit_4.setMinimumSize(QtCore.QSize(128, 0))
self.lineEdit_4.setMaximumSize(QtCore.QSize(90, 16777215))
self.lineEdit_4.setMinimumSize(QtCore.QSize(96, 0))
self.lineEdit_4.setObjectName(_fromUtf8("lineEdit_4"))
self.gridLayout.addWidget(self.lineEdit_4, 4, 1, 1, 1)
self.pushButton_1 = QtGui.QPushButton(PeakGroupBox)
@ -94,7 +94,8 @@ class Ui_PeakGroupBox(object):
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_1.sizePolicy().hasHeightForWidth())
self.pushButton_1.setSizePolicy(sizePolicy)
self.pushButton_1.setMinimumSize(QtCore.QSize(64, 0))
self.pushButton_1.setMinimumSize(QtCore.QSize(56, 0))
self.pushButton_1.setBaseSize(QtCore.QSize(0, 0))
self.pushButton_1.setAutoDefault(False)
self.pushButton_1.setDefault(False)
self.pushButton_1.setFlat(False)
@ -107,7 +108,7 @@ class Ui_PeakGroupBox(object):
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_6.sizePolicy().hasHeightForWidth())
self.pushButton_6.setSizePolicy(sizePolicy)
self.pushButton_6.setMinimumSize(QtCore.QSize(64, 0))
self.pushButton_6.setMinimumSize(QtCore.QSize(56, 0))
self.pushButton_6.setObjectName(_fromUtf8("pushButton_6"))
self.gridLayout.addWidget(self.pushButton_6, 3, 3, 1, 1)
self.label = QtGui.QLabel(PeakGroupBox)
@ -125,7 +126,7 @@ class Ui_PeakGroupBox(object):
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_5.sizePolicy().hasHeightForWidth())
self.pushButton_5.setSizePolicy(sizePolicy)
self.pushButton_5.setMinimumSize(QtCore.QSize(64, 0))
self.pushButton_5.setMinimumSize(QtCore.QSize(56, 0))
self.pushButton_5.setObjectName(_fromUtf8("pushButton_5"))
self.gridLayout.addWidget(self.pushButton_5, 3, 2, 1, 1)
self.removeButton = QtGui.QPushButton(PeakGroupBox)
@ -144,7 +145,7 @@ class Ui_PeakGroupBox(object):
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_8.sizePolicy().hasHeightForWidth())
self.pushButton_8.setSizePolicy(sizePolicy)
self.pushButton_8.setMinimumSize(QtCore.QSize(64, 0))
self.pushButton_8.setMinimumSize(QtCore.QSize(56, 0))
self.pushButton_8.setObjectName(_fromUtf8("pushButton_8"))
self.gridLayout.addWidget(self.pushButton_8, 4, 3, 1, 1)
self.label_3 = QtGui.QLabel(PeakGroupBox)
@ -163,7 +164,7 @@ class Ui_PeakGroupBox(object):
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
self.pushButton_4.setSizePolicy(sizePolicy)
self.pushButton_4.setMinimumSize(QtCore.QSize(64, 0))
self.pushButton_4.setMinimumSize(QtCore.QSize(56, 0))
self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
self.gridLayout.addWidget(self.pushButton_4, 2, 3, 1, 1)
self.label_1 = QtGui.QLabel(PeakGroupBox)
@ -176,13 +177,12 @@ class Ui_PeakGroupBox(object):
self.label_1.setObjectName(_fromUtf8("label_1"))
self.gridLayout.addWidget(self.label_1, 1, 0, 1, 1)
self.lineEdit_2 = QtGui.QLineEdit(PeakGroupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
self.lineEdit_2.setSizePolicy(sizePolicy)
self.lineEdit_2.setMinimumSize(QtCore.QSize(128, 0))
self.lineEdit_2.setMaximumSize(QtCore.QSize(90, 16777215))
self.lineEdit_2.setMinimumSize(QtCore.QSize(96, 0))
self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
self.gridLayout.addWidget(self.lineEdit_2, 2, 1, 1, 1)
self.checkBox_1 = QtGui.QCheckBox(PeakGroupBox)
@ -191,13 +191,13 @@ class Ui_PeakGroupBox(object):
self.checkBox_1.setObjectName(_fromUtf8("checkBox_1"))
self.gridLayout.addWidget(self.checkBox_1, 1, 4, 1, 1)
self.lineEdit_1 = QtGui.QLineEdit(PeakGroupBox)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit_1.sizePolicy().hasHeightForWidth())
self.lineEdit_1.setSizePolicy(sizePolicy)
self.lineEdit_1.setMinimumSize(QtCore.QSize(128, 0))
self.lineEdit_1.setMaximumSize(QtCore.QSize(90, 16777215))
self.lineEdit_1.setMinimumSize(QtCore.QSize(96, 0))
self.lineEdit_1.setBaseSize(QtCore.QSize(0, 0))
self.lineEdit_1.setObjectName(_fromUtf8("lineEdit_1"))
self.gridLayout.addWidget(self.lineEdit_1, 1, 1, 1, 1)
self.pushButton_3 = QtGui.QPushButton(PeakGroupBox)
@ -206,7 +206,7 @@ class Ui_PeakGroupBox(object):
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
self.pushButton_3.setSizePolicy(sizePolicy)
self.pushButton_3.setMinimumSize(QtCore.QSize(64, 0))
self.pushButton_3.setMinimumSize(QtCore.QSize(56, 0))
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
self.gridLayout.addWidget(self.pushButton_3, 2, 2, 1, 1)
self.label_4 = QtGui.QLabel(PeakGroupBox)
@ -228,9 +228,10 @@ class Ui_PeakGroupBox(object):
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
self.pushButton_2.setSizePolicy(sizePolicy)
self.pushButton_2.setMinimumSize(QtCore.QSize(64, 0))
self.pushButton_2.setMinimumSize(QtCore.QSize(56, 0))
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.gridLayout.addWidget(self.pushButton_2, 1, 3, 1, 1)
self.gridLayout.setColumnStretch(1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
self.retranslateUi(PeakGroupBox)

View File

@ -9,25 +9,28 @@
<rect>
<x>0</x>
<y>0</y>
<width>385</width>
<height>230</height>
<width>320</width>
<height>210</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>275</width>
<width>308</width>
<height>210</height>
</size>
</property>
<property name="windowTitle">
<string>GroupBox</string>
</property>
<property name="autoFillBackground">
<bool>false</bool>
</property>
<property name="title">
<string>GroupBox</string>
</property>
@ -37,9 +40,12 @@
<property name="checkable">
<bool>false</bool>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<layout class="QGridLayout" name="gridLayout_2" rowstretch="0">
<property name="margin">
<number>10</number>
</property>
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout" rowstretch="0,0,0,0,0" columnstretch="0,0,0,0,0">
<layout class="QGridLayout" name="gridLayout" rowstretch="0,0,0,0,0" columnstretch="0,1,0,0,0" rowminimumheight="0,0,0,0,0" columnminimumwidth="0,0,0,0,0">
<property name="sizeConstraint">
<enum>QLayout::SetDefaultConstraint</enum>
</property>
@ -62,23 +68,17 @@
<item row="3" column="1">
<widget class="QLineEdit" name="lineEdit_3">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>128</width>
<width>96</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>90</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>0.0</string>
</property>
@ -101,7 +101,7 @@
</property>
<property name="minimumSize">
<size>
<width>64</width>
<width>56</width>
<height>0</height>
</size>
</property>
@ -129,23 +129,17 @@
<item row="4" column="1">
<widget class="QLineEdit" name="lineEdit_4">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>128</width>
<width>96</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>90</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>0.0</string>
</property>
@ -161,7 +155,13 @@
</property>
<property name="minimumSize">
<size>
<width>64</width>
<width>56</width>
<height>0</height>
</size>
</property>
<property name="baseSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
@ -192,7 +192,7 @@
</property>
<property name="minimumSize">
<size>
<width>64</width>
<width>56</width>
<height>0</height>
</size>
</property>
@ -227,7 +227,7 @@
</property>
<property name="minimumSize">
<size>
<width>64</width>
<width>56</width>
<height>0</height>
</size>
</property>
@ -268,7 +268,7 @@
</property>
<property name="minimumSize">
<size>
<width>64</width>
<width>56</width>
<height>0</height>
</size>
</property>
@ -306,7 +306,7 @@
</property>
<property name="minimumSize">
<size>
<width>64</width>
<width>56</width>
<height>0</height>
</size>
</property>
@ -334,23 +334,17 @@
<item row="2" column="1">
<widget class="QLineEdit" name="lineEdit_2">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>128</width>
<width>96</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>90</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>0.00e+00</string>
</property>
@ -369,21 +363,21 @@
<item row="1" column="1">
<widget class="QLineEdit" name="lineEdit_1">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>128</width>
<width>96</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<property name="baseSize">
<size>
<width>90</width>
<height>16777215</height>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="text">
@ -401,7 +395,7 @@
</property>
<property name="minimumSize">
<size>
<width>64</width>
<width>56</width>
<height>0</height>
</size>
</property>
@ -446,7 +440,7 @@
</property>
<property name="minimumSize">
<size>
<width>64</width>
<width>56</width>
<height>0</height>
</size>
</property>

View File

@ -5,15 +5,16 @@ import PeakGroupBox
class PeakWidget(QGroupBox):
changedTable = pyqtSignal()
def __init__(self, parent=None):
QGroupBox.__init__(self)
super(PeakWidget, self).__init__(parent)
self.ui = PeakGroupBox.Ui_PeakGroupBox()
self.ui.setupUi(self)
self.lineEdits = [self.ui.lineEdit_1,
self.ui.lineEdit_2,
self.ui.lineEdit_3,
self.ui.lineEdit_4]
self.lineEdits = [self.ui.lineEdit_1,
self.ui.lineEdit_2,
self.ui.lineEdit_3,
self.ui.lineEdit_4]
self.fixedCheckBoxes = [self.ui.checkBox_1,
self.ui.checkBox_2,
self.ui.checkBox_3,
@ -22,15 +23,15 @@ class PeakWidget(QGroupBox):
le.editingFinished.connect(self.changedTable.emit)
self.signalMapper = QSignalMapper(self)
for i, button in enumerate([self.ui.pushButton_1,
self.ui.pushButton_2,
self.ui.pushButton_3,
self.ui.pushButton_4,
self.ui.pushButton_5,
self.ui.pushButton_6,
self.ui.pushButton_7,
self.ui.pushButton_8,
]):
self.signalMapper.setMapping(button,i)
self.ui.pushButton_2,
self.ui.pushButton_3,
self.ui.pushButton_4,
self.ui.pushButton_5,
self.ui.pushButton_6,
self.ui.pushButton_7,
self.ui.pushButton_8,
]):
self.signalMapper.setMapping(button, i)
button.clicked.connect(self.signalMapper.map)
self.signalMapper.mapped.connect(self.changeValues)
@ -40,48 +41,48 @@ class PeakWidget(QGroupBox):
# 0-3 down/up for d_eps and tau, respectively
# 4-7 down, up for a, b
if num == 0:
self.ui.lineEdit_1.setText("%.2e"%(self.ui.lineEdit_1.text().toDouble()[0]/logstep))
self.ui.lineEdit_1.setText("%.2e" % (self.ui.lineEdit_1.text().toDouble()[0] / logstep))
if num == 1:
self.ui.lineEdit_1.setText("%.2e"%(self.ui.lineEdit_1.text().toDouble()[0]*logstep))
self.ui.lineEdit_1.setText("%.2e" % (self.ui.lineEdit_1.text().toDouble()[0] * logstep))
if num == 2:
self.ui.lineEdit_2.setText("%.2e"%(self.ui.lineEdit_2.text().toDouble()[0]/logstep))
self.ui.lineEdit_2.setText("%.2e" % (self.ui.lineEdit_2.text().toDouble()[0] / logstep))
if num == 3:
self.ui.lineEdit_2.setText("%.2e"%(self.ui.lineEdit_2.text().toDouble()[0]*logstep))
self.ui.lineEdit_2.setText("%.2e" % (self.ui.lineEdit_2.text().toDouble()[0] * logstep))
if num == 4:
self.ui.lineEdit_3.setText("%.2e"%(self.ui.lineEdit_3.text().toDouble()[0]-linstep))
self.ui.lineEdit_3.setText("%.2e" % (self.ui.lineEdit_3.text().toDouble()[0] - linstep))
if num == 5:
self.ui.lineEdit_3.setText("%.2e"%(self.ui.lineEdit_3.text().toDouble()[0]+linstep))
self.ui.lineEdit_3.setText("%.2e" % (self.ui.lineEdit_3.text().toDouble()[0] + linstep))
if num == 6:
self.ui.lineEdit_4.setText("%.2e"%(self.ui.lineEdit_4.text().toDouble()[0]-linstep))
self.ui.lineEdit_4.setText("%.2e" % (self.ui.lineEdit_4.text().toDouble()[0] - linstep))
if num == 7:
self.ui.lineEdit_4.setText("%.2e"%(self.ui.lineEdit_4.text().toDouble()[0]+linstep))
self.ui.lineEdit_4.setText("%.2e" % (self.ui.lineEdit_4.text().toDouble()[0] + linstep))
self.changedTable.emit()
def fixedParameter(self):
return [0 if cb.isChecked() else 1 for cb in self.fixedCheckBoxes]
def setId(self,id):
self.id=id
self.setTitle("Peak %i"%id)
def setId(self, id):
self.id = id
self.setTitle("Peak %i" % id)
def setColor(self, color):
r,g,b = color
r, g, b = color
palette = self.palette()
palette.setColor(QPalette.Foreground, QColor(r,g,b))
palette.setColor(QPalette.Foreground, QColor(r, g, b))
self.setPalette(palette)
def peakParameter(self):
tmp = [i.text().toDouble()[0] # selects the number, ignores the status
for i in self.lineEdits ]
print "peakParams:",tmp
for i in self.lineEdits]
print "peakParams:", tmp
return tmp
def update(self):
self.changedTable.emit()
def updateTable(self, *args):
print "updateTable", args
for i,arg in enumerate(args):
self.lineEdits[i].setText("%g"%(args[i]))
for i, arg in enumerate(args):
self.lineEdits[i].setText("%g" % (args[i]))

534
QDS.py
View File

@ -1,17 +1,17 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os,sys
import os
import sys
import re
import signal
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.uic import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
#from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt
#import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as N
@ -21,14 +21,14 @@ import scipy.optimize as opt
import MatplotlibWidget
import QDSMain
import PeakWidget
import ConductivityWidget
from data import Data
from data import Data, Conductivity, conductivity
#import yaff
def sigint_handler(*args):
"""Handler for the SIGINT signal."""
"""Handler for the SIGINT signal (CTRL + C).
"""
sys.stderr.write('\r')
if QMessageBox.question(None, '', "Are you sure you want to quit?",
QMessageBox.Yes | QMessageBox.No,
@ -37,181 +37,123 @@ def sigint_handler(*args):
def id_to_color(id):
colors = ['b', 'r','g','c','m','y','k']
"""
"""
colors = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
conv = matplotlib.colors.ColorConverter()
return conv.to_rgb(colors[id%len(colors)])
return conv.to_rgb(colors[id % len(colors)])
def tau_peak(f,a,b):
tau = (N.sin( N.pi*a/2./(b+1) )/N.sin( N.pi*a*b/2./(b+1) ))**(1/a)
tau /= 2*N.pi*f
def tau_peak(f, a, b):
tau = (N.sin(N.pi * a / 2. / (b + 1)) / N.sin(N.pi * a * b / 2. / (b + 1))) ** (1 / a)
tau /= 2 * N.pi * f
return tau
def hn(p,nu):
delta_eps,tau,a,b = p
om = 2*N.pi*nu
Phi = N.arctan( (om*tau)**a*N.sin(N.pi*a/2.)/(1.+(om*tau)**a*N.cos(N.pi*a/2.)) )
e_loss = delta_eps * (1+ 2*(om*tau)**a * N.cos(N.pi*a/2.) + (om*tau)**(2.*a) )**(-b/2.)*N.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)
return 2*e_loss
def multi_hn(p,nu):
def hn(p, nu):
delta_eps, tau, a, b = p
om = 2 * N.pi * nu
Phi = N.arctan((om * tau) ** a * N.sin(N.pi * a / 2.) / (1. + (om * tau) ** a * N.cos(N.pi * a / 2.)))
e_loss = delta_eps * (1 + 2 * (om * tau) ** a * N.cos(N.pi * a / 2.) + (om * tau) ** (2. * a) ) ** (
-b / 2.) * N.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)
return 2 * e_loss
def multi_hn(p, nu):
conductivity = p[1]
cond_beta = p[2]
om = 2*N.pi*nu
e_loss = conductivity/om**cond_beta
om = 2 * N.pi * nu
e_loss = conductivity / om ** cond_beta
e_loss += p[0]
#for key, igroup in groupby(p[3:], lambda x: x//4):
for i in xrange(len(p[3:])/4):
delta_eps, tau, a, b = p[3+i*4:3+(i+1)*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 = list(igroup)
#print delta_eps,tau,a,b
#a = 0.5 *(1 + N.tanh(a))
#b = 0.5 *(1 + N.tanh(b))
Phi = N.arctan( (om*tau)**a*N.sin(N.pi*a/2.)/(1.+(om*tau)**a*N.cos(N.pi*a/2.)) )
e_loss += 2*delta_eps * (1+ 2*(om*tau)**a * N.cos(N.pi*a/2.) + (om*tau)**(2.*a) )**(-b/2.)*N.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)
Phi = N.arctan((om * tau) ** a * N.sin(N.pi * a / 2.) / (1. + (om * tau) ** a * N.cos(N.pi * a / 2.)))
e_loss += 2 * delta_eps * (1 + 2 * (om * tau) ** a * N.cos(N.pi * a / 2.) + (om * tau) ** (2. * a) ) ** (
-b / 2.) * N.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)
return e_loss
def mini_func(p,x, y):
res = y - multi_hn(p,x)
def mini_func(p, x, y):
res = y - multi_hn(p, x)
# apply weights
res /= 1/y
return N.sqrt(N.dot(res,res))
res /= 1 / y
return N.sqrt(N.dot(res, res))
def conductivity(p, nu):
c = p[0]/(2*N.pi*nu)**p[1]
return c
def hnfit(delta_eps, tau, points):
x = [point[0] for point in points]
y = [point[1] for point in points]
dat = O.Data(x,y)
mod = O.Model(hn)
odr = O.ODR(dat,mod, [delta_eps, tau, 1, 1], ifixb=(0,0,1,1), ifixx=(0,), maxit=1000)
odr.run()
odr.output.pprint()
return odr.output.beta
def fit_odr(x,y,p0, fixed):
dat = O.Data(x,y, 1.0/y)
def fit_odr(x, y, p0, fixed):
dat = O.Data(x, y, 1.0 / y)
mod = O.Model(multi_hn)
odr = O.ODR(dat, mod, p0, ifixx=(0,), ifixb=fixed, maxit=2000)
odr.run()
return odr.output.beta
def fit_lbfgsb(x,y,p0, fixed):
# TODO fixed parameters…
bounds = [(0,None), (0,1)]
for i in xrange(len(p0[3:])/4):
bounds.append((1e-4,1e12)) # delta_eps
bounds.append((1e-12,1e3)) # tau
bounds.append((0.1,1)) # a
bounds.append((0.1,1)) # b
x,f_minvalue, info_dict = opt.fmin_l_bfgs_b(mini_func, p0,
fprime=None,
args=(x,y),
approx_grad=True,
bounds=bounds,
iprint=0,
maxfun=4000)
def fit_lbfgsb(x, y, p0, fixed):
# TODO fixed parameters…
bounds = [(0, None), (0, 1)]
for i in xrange(len(p0[3:]) / 4):
bounds.append((1e-4, 1e12)) # delta_eps
bounds.append((1e-12, 1e3)) # tau
bounds.append((0.1, 1)) # a
bounds.append((0.1, 1)) # b
x, f_minvalue, info_dict = opt.fmin_l_bfgs_b(mini_func, p0,
fprime=None,
args=(x, y),
approx_grad=True,
bounds=bounds,
iprint=0,
maxfun=4000)
if info_dict['warnflag'] != 0:
print info_dict["task"]
return x
def fit_anneal(x,y,p0,fixed):
bounds = [(0,1e14), (0,1)]
for i in xrange(len(p0[2:])/4):
bounds.append((1e-4,1e12)) # delta_eps
bounds.append((1e-12,1e3)) # tau
bounds.append((0.1,1)) # a
bounds.append((0.1,1)) # b
def fit_anneal(x, y, p0, fixed):
bounds = [(0, 1e14), (0, 1)]
for i in xrange(len(p0[2:]) / 4):
bounds.append((1e-4, 1e12)) # delta_eps
bounds.append((1e-12, 1e3)) # tau
bounds.append((0.1, 1)) # a
bounds.append((0.1, 1)) # b
ret = opt.anneal(mini_func, p0,
args=(x,y),
maxeval=20000,
maxiter=30000,
lower=[b[0] for b in bounds],
upper=[b[1] for b in bounds],
dwell=100,
full_output=1)
args=(x, y),
maxeval=20000,
maxiter=30000,
lower=[b[0] for b in bounds],
upper=[b[1] for b in bounds],
dwell=100,
full_output=1)
#pmin, func_min, final_Temp, cooling_iters,accepted_tests, retval
#retval : int
#Flag indicating stopping condition::
# 0 : Points no longer changing
# 1 : Cooled to final temperature
# 2 : Maximum function evaluations
# 3 : Maximum cooling iterations reached
# 4 : Maximum accepted query locations reached
# 5 : Final point not the minimum amongst encountered points
# 0 : Points no longer changing
# 1 : Cooled to final temperature
# 2 : Maximum function evaluations
# 3 : Maximum cooling iterations reached
# 4 : Maximum accepted query locations reached
# 5 : Final point not the minimum amongst encountered points
print "Stop reason", ret
return ret[0]
class Conductivity(QObject):
changedData = pyqtSignal()
def __init__(self, mpl=None):
QObject.__init__(self)
super(Conductivity, self)
self.widget = ConductivityWidget.ConductivityWidget()
self.widget.changedTable.connect(self.updateData)
self.mpl_line = None
self.mpl_line_static = None
self.mpl = mpl
def getParameter(self):
p = self.widget.getTable()
return p
def getFixed(self):
p = self.widget.fixedParameter()
return p
def setParameter(self, eps_static=None, sigma=None, sigma_N=None):
self.widget.updateTable(eps_static, sigma, sigma_N)
self.updateData()
def updateData(self):
# get current axis limits
x_min, x_max = self.mpl.canvas.axes.get_xlim()
y_min, y_max = self.mpl.canvas.axes.get_ylim()
nu = N.logspace(N.log10(x_min), N.log10(x_max), 1024)
eps_static, sigma, sigma_N = self.getParameter()
y = conductivity([sigma, sigma_N],nu)
y_static = N.ones(len(nu))*eps_static
# clip data to axes limits
mask_static = (y_static < y_max) & (y_static > y_min)
# clip data to axes limits
mask = (y < y_max) & (y > y_min)
#mask = mask_static = N.ones(1024, dtype='bool')
if self.mpl_line == None:
self.mpl_line, = self.mpl.canvas.axes.loglog(nu[mask],y[mask],'k--',label="Cond.", animated=True) # peak
else:
self.mpl_line.set_xdata(nu[mask])
self.mpl_line.set_ydata(y[mask])
if self.mpl_line_static == None:
self.mpl_line_static, = self.mpl.canvas.axes.loglog(nu[mask_static],
y_static[mask_static],
'k:',
label=r"$\epsilon_S$",
animated=True) # peak
else:
self.mpl_line_static.set_xdata(nu[mask_static])
self.mpl_line_static.set_ydata(y_static[mask_static])
self.changedData.emit()
class Peak(QObject):
changedData = pyqtSignal()
def __init__(self, id=None, mpl=None):
QObject.__init__(self)
super(Peak, self).__init__()
@ -219,18 +161,18 @@ class Peak(QObject):
self.color = id_to_color(id)
self.widget = PeakWidget.PeakWidget()
self.widget.setId(id)
self.widget.setColor(map(int, [255*i for i in self.color]))
self.widget.setColor(map(int, [255 * i for i in self.color]))
self.widget.changedTable.connect(self.updatePeak)
self.mpl = mpl
self.mpl_line = None
def getParameter(self):
p = self.widget.peakParameter()
p = self.widget.peakParameter()
return p
def getFixed(self):
p = self.widget.fixedParameter()
p = self.widget.fixedParameter()
return p
def setParameter(self, delta_eps=None, tau=None, a=None, b=None):
@ -243,13 +185,14 @@ class Peak(QObject):
y_min, y_max = self.mpl.canvas.axes.get_ylim()
nu = N.logspace(N.log10(x_min), N.log10(x_max), 2048)
y = hn(self.getParameter(),nu)
y = hn(self.getParameter(), nu)
# clip data to axes limits
mask = (y < y_max) & (y > y_min)
y = y[mask]
nu = nu[mask]
if self.mpl_line == None:
self.mpl_line, = self.mpl.canvas.axes.loglog(nu,y,'--',label="Peak %i"%(self.widget.id), animated=True) # peak
self.mpl_line, = self.mpl.canvas.axes.loglog(nu, y, '--', label="Peak %i" % (self.widget.id),
animated=True) # peak
self.mpl_line.set_color(self.color)
else:
self.mpl_line.set_xdata(nu)
@ -257,7 +200,6 @@ class Peak(QObject):
self.changedData.emit()
class AppWindow(QMainWindow):
def __init__(self, parent=None):
super(AppWindow, self).__init__(parent)
@ -266,56 +208,68 @@ class AppWindow(QMainWindow):
self.picked_artist = None
self.data = None
self.Conductivity = None
self._lines = dict()
self.peakId = 0
self.peakBoxes = {}
## menubar
fileMenu = self.menuBar().addMenu("File")
openFile = QAction("&Open",self)
openFile = QAction("&Open", self)
openFile.setShortcut(QKeySequence.Open)
openFile.triggered.connect(self.openFile)
fileMenu.addAction(openFile)
# fitting methods
fitMenu = self.menuBar().addMenu("Fit")
fitMenu = self.menuBar().addMenu("Standard Fits")
# lm
fit_lmAction = QAction("&Levenberg-Marquardt",self)
fit_lmAction = QAction("&Levenberg-Marquardt", self)
fit_lmAction.setShortcut(QKeySequence("Ctrl+F"))
fitMenu.addAction(fit_lmAction)
# lbfgsb
fit_lbfgsbAction = QAction("&L-BFGS-B",self)
fit_lbfgsbAction = QAction("&L-BFGS-B", self)
fitMenu.addAction(fit_lbfgsbAction)
# Simulated Annealing
fit_annealAction = QAction("&Simulated Annealing",self)
fit_annealAction = QAction("&Simulated Annealing", self)
fitMenu.addAction(fit_annealAction)
# YAFF
yaffMenu = self.menuBar().addMenu("YAFF")
start_yaff = QAction("&Startparam.", self)
yaffMenu.addAction(start_yaff)
fit_yaff = QAction("&Fit", self)
yaffMenu.addAction(fit_yaff)
self.signalMapper = QSignalMapper(self)
for i, fit_action in enumerate([fit_lmAction, fit_lbfgsbAction, fit_annealAction
]):
self.signalMapper.setMapping(fit_action,i)
]):
self.signalMapper.setMapping(fit_action, i)
fit_action.triggered.connect(self.signalMapper.map)
self.signalMapper.mapped.connect(self.fitData)
# save fitted values
self.ui.actionSave_FitResult.triggered.connect(self.saveFit)
# he plot area, a matplotlib widget
# the plot area, a matplotlib widget
self.mplWidget = PlotWidget(self.ui.mplWidget)
self.mplWidget.canvas.draw()
self.mplWidget.updateGeometry()
# what to do with CIDs?
self.cid = []
self.cid.append( self.mplWidget.canvas.mpl_connect("button_press_event", self.onclick) )
self.cid.append( self.mplWidget.canvas.mpl_connect("pick_event", self.pick) )
self.cid.append( self.mplWidget.canvas.mpl_connect("button_release_event", self.mpl_button_release) )
self.cid.append(self.mplWidget.canvas.mpl_connect("button_press_event", self.mpl_button_press))
self.cid.append(self.mplWidget.canvas.mpl_connect("pick_event", self.mpl_button_pick))
self.cid.append(self.mplWidget.canvas.mpl_connect("button_release_event", self.mpl_button_release))
#self.cid.append(self.mplWidget.canvas.mpl_connect("resize_event", self.myresizeEvent))
self.mplWidget.toolbar.spanSelectedTrigger.connect(self.set_fit_xlimits)
def resizeEvent(self,evt):
def resizeEvent(self, evt):
"""resizing the main window executes this method
TODO: FIX RESIZEING keeping mainwindow maximised for now
:param evt:
"""
self.mplWidget.canvas.draw()
self.mplWidget._bg_cache = self.mplWidget.canvas.copy_from_bbox(self.mplWidget.canvas.axes.bbox)
self.mplWidget._bg_cache = self.mplWidget.canvas.copy_from_bbox(self.mplWidget.canvas.axes.bbox)
for line in self.mplWidget.canvas.axes.get_lines():
line.set_animated(False)
self.mplWidget.canvas.draw()
@ -324,53 +278,60 @@ class AppWindow(QMainWindow):
def saveFit(self):
"""
Saving fit parameters to fitresults.log
including temperature
"""
if not os.path.exists("fitresults.log"):
f = open("fitresults.log","w")
f = open("fitresults.log", "w")
# write header
f.write('# T ')
if self.Conductivity != None:
f.write("e_s sig pow_sig ")
for i,pb in enumerate(self.peakBoxes):
f.write("e_inf_%i tau_%i alpha_%i beta_%i"%(i,i,i,i))
f.write("%8s %8s %8s " % ("e_s", "sig", "pow_sig"))
for i, pb in enumerate(self.peakBoxes):
enum_peak = ("e_inf_%i" % i, "tau_%i" % i, "alpha_%i" % i, "beta_%i" % i)
f.write("%8s %8s %8s %8s " % enum_peak)
f.write("high_lim lower_lim")
f.write('\n')
f.flush()
else:
f = open("fitresults.log","a")
#f.write("%3.2f "%(self.data.meta["T"]))
f = open("fitresults.log", "a")
#f.write("%3.2f "%(self.data.meta["T"]))
pars = list(self.fitresult)
pars.insert(0,self.data.meta["T"] )
print pars
N.savetxt(f,N.array([pars,]),fmt="%.5g", delimiter=" ")
pars.insert(0, self.data.meta["T"])
N.savetxt(f, N.array([pars, ]), fmt="%8.5g", delimiter=" ")
f.close()
def set_fit_xlimits(self,xmin,xmax):
self.data.fit_limits = (xmin, xmax, None,None)
def set_fit_xlimits(self, xmin, xmax):
self.data.fit_limits = (xmin, xmax, None, None)
self.updatePlot()
def mpl_button_release(self,event):
if self.picked_artist:
def mpl_button_release(self, event):
ax = self.mplWidget.canvas.axes
if self.picked_artist:
if not event.inaxes: # moved outside the plot, add back to original position
self.mplWidget.canvas.axes.add_artist(self.picked_artist)
ax.add_artist(self.picked_artist)
else: # we move one of the three points determinig the peak
self.picked_artist.set_xdata(event.xdata)
self.picked_artist.set_ydata(event.ydata)
self.mplWidget.canvas.axes.add_artist(self.picked_artist)
ax.add_artist(self.picked_artist)
for peak in self.peakBoxes.keys():
peak.updatePeak()
self.picked_artist = None
self.mplWidget.canvas.draw_idle()
def pick(self,event):
def mpl_button_pick(self, event):
self.picked_artist = event.artist
event.artist.remove()
self.mplWidget.canvas.draw_idle()
def addCond(self, pos):
if self.Conductivity != None:
return
self.statusBar().showMessage("Click on graph")
self.Conductivity = Conductivity(mpl=self.mplWidget)
self.Conductivity.changedData.connect(self.updatePlot)
self.Conductivity.setParameter(0, 1/(pos[0]/pos[1]/2/N.pi), 1.0)
self.Conductivity.setParameter(0, 1 / (pos[0] / pos[1] / 2 / N.pi), 1.0)
self.ui.scrollAreaWidgetContents.layout().addWidget(self.Conductivity.widget)
self.Conductivity.widget.ui.removeButton.clicked.connect(self.delCond)
@ -392,21 +353,21 @@ class AppWindow(QMainWindow):
# connect to delPeak
peak.widget.ui.removeButton.clicked.connect(self.delPeak)
peak.setParameter(delta_eps=pos[1], tau=1/(2.*N.pi*pos[0]), a=1, b=1)
peak.setParameter(delta_eps=pos[1], tau=1 / (2. * N.pi * pos[0]), a=1, b=1)
peak.changedData.connect(self.updatePlot)
self.peakBoxes[peak]=None
self.peakBoxes[peak] = None
for pb in self.peakBoxes.keys():
self.ui.scrollAreaWidgetContents.layout().addWidget(pb.widget)
self.updatePlot()
def delPeak(self):
deletePeaks = []
for i in xrange(self.ui.scrollAreaWidgetContents.layout().count()):
print i
for i,peak in enumerate(self.peakBoxes.keys()):
for i, peak in enumerate(self.peakBoxes.keys()):
if peak.widget.isHidden():
peak.mpl_line.remove()
deletePeaks.append(peak)
@ -417,131 +378,148 @@ class AppWindow(QMainWindow):
def fitData(self, method):
if self.Conductivity != None:
start_parameter = list(self.Conductivity.getParameter())
fixed_params = [ i for i in self.Conductivity.getFixed() ]
fixed_params = [i for i in self.Conductivity.getFixed()]
else:
start_parameter = [0,0,1]
fixed_params = [0,0,0]
start_parameter = [0, 0, 1]
fixed_params = [0, 0, 0]
for pb in self.peakBoxes.keys():
[ start_parameter.append(i) for i in pb.getParameter() ]
[ fixed_params.append(i) for i in pb.getFixed() ]
[start_parameter.append(i) for i in pb.getParameter()]
[fixed_params.append(i) for i in pb.getFixed()]
fit_methods = [fit_odr, fit_lbfgsb, fit_anneal]
print "StartParameter",start_parameter
print "FixedParameter",fixed_params
print "StartParameter", start_parameter
print "FixedParameter", fixed_params
print "Limits (xmin, xmax, ymin, ymax)", self.data.fit_limits
_freq, _fit = self.data.get_data()
result = fit_methods[method](_freq, _fit.imag, start_parameter, fixed_params)
self.fitresult = result
for i,pb in enumerate(self.peakBoxes.keys()):
delta_eps, tau, a, b = result[3+i*4:3+(i+1)*4]
pb.setParameter(delta_eps, tau, a, b )
e_static,sigma, sigma_N = result[:3]
for i, pb in enumerate(self.peakBoxes.keys()):
delta_eps, tau, a, b = result[3 + i * 4:3 + (i + 1) * 4]
pb.setParameter(delta_eps, tau, a, b)
e_static, sigma, sigma_N = result[:3]
if self.Conductivity != None:
self.Conductivity.setParameter(e_static,sigma,sigma_N)
print "*** FIT RESULTS ***"
print u"\u03c3"
print u"\u0394\u03b5"
self.Conductivity.setParameter(e_static, sigma, sigma_N)
#print "*** FIT RESULTS ***"
#print u"\u03c3"
#print u"\u0394\u03b5"
self.updatePlot()
def onclick(self, event):
def mpl_button_press(self, event):
"""
Handles the clicks on the matplotlib figure canvas
"""
if self.ui.actionAdd_Peak.isChecked():
x,y = event.xdata,event.ydata
self.addPeak((x,y))
if self.ui.actionAdd_Peak.isChecked() and event.inaxes:
x, y = event.xdata, event.ydata
self.addPeak((x, y))
self.ui.actionAdd_Peak.setChecked(False)
self.statusBar().clear()
if self.ui.actionAdd_Cond.isChecked():
x,y = event.xdata,event.ydata
self.addCond((x,y))
if self.ui.actionAdd_Cond.isChecked() and event.inaxes:
x, y = event.xdata, event.ydata
self.addCond((x, y))
self.ui.actionAdd_Cond.setChecked(False)
self.statusBar().clear()
def openFile(self):
ax = self.mplWidget.canvas.axes
path = unicode(QFileDialog.getOpenFileName(self, "Open file"))
# TODO anaylize file (LF,MF, HF) and act accordingly
data = N.loadtxt(path, skiprows=4)
numpat = re.compile('\d+\.\d+')
try:
Temp = None
for line in open(path).readlines():
if re.search("Fixed", line) or re.search("Temp", line):
print "Found line with Fixed or Temp"
Temp = float(re.search(numpat, line).group())
print "Temperature found in file:",Temp
print "Temperature found in file:", Temp
break
else:
print "No Temperature found in file"
raise
#Temp = QInputDialog.getDouble(self, "No temperature found in data set","Temperature/K:", value=Temp)[0]
if Temp == None: raise ValueError
except:
Temp = QInputDialog.getDouble(self, "No temperature found in data set","Temperature/K:", value=0.0)[0]
# mask the data to values > 0 (loglog plot)
mask = (data[:,1]>0) & (data[:,2]>0) #& (data[:,2]>1e-3) & (data[:,0] > 1e-2)
_freq = data[mask,0]
_die_stor = data[mask,1]
_die_loss = data[mask,2]
Temp = QInputDialog.getDouble(self, "No temperature found in data set", "Temperature/K:", value=0.00)[0]
# mask the data to values > 0 (loglog plot)
mask = (data[:, 1] > 0) & (data[:, 2] > 0) #& (data[:,2]>1e-3) & (data[:,0] > 1e-2)
_freq = data[mask, 0]
_die_stor = data[mask, 1]
_die_loss = data[mask, 2]
# clear the figure
self.mplWidget.canvas.axes.clear()
ax.clear()
#if self.data != None:
# self.data.remove_curves()
self.data = Data(_freq, _die_stor, _die_loss)
self.data.meta["T"]=Temp
self.data.data_curve, = self.mplWidget.canvas.axes.loglog(self.data.frequency,
self.data.epsilon.imag,
'b.',
markersize=4,
label="Data",
animated=True)
self.mplWidget.canvas.axes.set_xlim(_freq.min(), _freq.max())
self.mplWidget.canvas.axes.set_xlabel("frequency/Hz", fontsize=16)
self.mplWidget.canvas.axes.set_ylabel(u'\u03B5"', fontsize=16)
self.mplWidget.canvas.axes.autoscale(True)
self.legend = self.mplWidget.canvas.axes.legend(title="T=%.2f"%Temp)
for line in self.mplWidget.canvas.axes.get_lines():
self.data.meta["T"] = Temp
self.data.data_curve, = ax.loglog(self.data.frequency,
self.data.epsilon.imag,
'b.',
markersize=4,
label="Data",
animated=True)
ax.set_xlabel("Frequency/Hz", fontsize=16)
#ax.set_ylabel(u'\u03B5"', fontsize=16)
ax.set_ylabel(u'e"', fontsize=16)
ax.autoscale(True)
ax.set_xlim(_freq.min()/3, _freq.max()*3)
self.legend = ax.legend(title="T=%.2f" % Temp)
for line in ax.get_lines():
line.set_animated(False)
self.mplWidget.canvas.axes.grid()
ax.grid()
self.mplWidget.canvas.draw()
for line in self.mplWidget.canvas.axes.get_lines():
# weird behaviour need to draw all first, then set_animated the redraw
for line in ax.get_lines():
line.set_animated(True)
self.legend.set_animated(True)
self.mplWidget.canvas.axes.autoscale(False)
self.mplWidget._bg_cache = self.mplWidget.canvas.copy_from_bbox(self.mplWidget.canvas.axes.bbox)
ax.autoscale(False)
self.mplWidget._bg_cache = self.mplWidget.canvas.copy_from_bbox(ax.bbox)
self.updatePlot()
def updatePlot(self):
ax = self.mplWidget.canvas.axes
nu = self.data.frequency
fit = N.zeros(len(nu))
for peak in self.peakBoxes.keys():
params = peak.getParameter()
fit += hn(params,nu)
fit += hn(params, nu)
if self.Conductivity != None:
print "Cond. given"
params = self.Conductivity.getParameter()[1:]
fit += conductivity(params, nu)
fit += self.Conductivity.getParameter()[0] # eps static
# clip data to axes limits
y_min, y_max = self.mplWidget.canvas.axes.get_ylim()
# clip data to axes limits
y_min, y_max = ax.get_ylim()
mask = (fit < y_max) & (fit > y_min)
#mask = N.ones(len(fit), dtype="bool")
if self.data.fitted_curve == None:
self.data.fitted_curve, = self.mplWidget.canvas.axes.loglog(nu[mask],fit[mask],
'k-',
alpha=0.5,
label="Sum",
animated=True)
self.data.fitted_curve, = ax.loglog(nu[mask], fit[mask],
'k-',
alpha=0.5,
label="Sum",
animated=True)
else:
self.data.fitted_curve.set_xdata(nu[mask])
self.data.fitted_curve.set_ydata(fit[mask])
# update lines
if self.mplWidget._axvlims != []:
[axv.remove() for axv in self.mplWidget._axvlims]
self.mplWidget._axvlims = []
if self.mplWidget._axvname != []:
[axvname.remove() for axvname in self.mplWidget._axvname]
self.mplWidget._axvname = []
for xlim in self.data.fit_limits[:2]:
self.mplWidget._axvlims.append(ax.axvline(xlim, color="k", ls="--", alpha=0.5, animated=True))
self.mplWidget._axvname.append(ax.text(xlim, y_min*3. , "%.3g"%xlim,
horizontalalignment='center',
verticalalignment='center',
animated=True) )
self.mplWidget.canvas.restore_region(self.mplWidget._bg_cache)
self.legend = self.mplWidget.canvas.axes.legend(title = "T=%.2f"%(self.data.meta["T"]) )
self.legend = ax.legend(title="T=%.2f" % (self.data.meta["T"]))
self.legend.set_animated(True)
for animated_artist in self.mplWidget.canvas.axes.findobj(match=lambda x: x.get_animated()):
for animated_artist in ax.findobj(match=lambda x: x.get_animated()):
#print "updatePlot: animated artist:",animated_artist
self.mplWidget.canvas.axes.draw_artist(animated_artist)
self.mplWidget.canvas.blit( self.mplWidget.canvas.axes.bbox )
ax.draw_artist(animated_artist)
self.mplWidget.canvas.blit(ax.bbox)
class PlotWidget(QWidget):
@ -549,46 +527,49 @@ class PlotWidget(QWidget):
QWidget.__init__(self)
super(PlotWidget, self).__init__(parent)
self.mplwidget = MatplotlibWidget.MatplotlibWidget(hold=True,
xlim=(1e-2,1e7),
xscale='log',
yscale='log')
xlim=(1e-2, 1e7),
xscale='log',
yscale='log')
self.canvas = self.mplwidget.figure.canvas # shortcut
self.canvas.axes.grid(True)
self.bbox_size = self.canvas.axes.bbox.size
print "PlotWidget",self.bbox_size
#self.toolbar = NavigationToolbar(self.mplwidget, parent)
#self.bbox_size = self.canvas.axes.bbox.size
self.toolbar = CustomToolbar(self.canvas, self.mplwidget, parent)
self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
layout = QVBoxLayout(parent)
#self.mplwidget.setLayout(layout)
layout.addWidget(self.canvas)
layout.addWidget(self.mplwidget)
layout.addWidget(self.toolbar)
self._bg_cache = None
self._axvlims = []
self._axvname = []
class CustomToolbar(NavigationToolbar):
# our spanChanged signal
spanSelectedTrigger = pyqtSignal(float, float, name='spanChanged')
def __init__(self, plotCanvas, plotWidget, parent=None):
NavigationToolbar.__init__(self, plotCanvas, plotWidget, coordinates=True)
self.canvas = plotCanvas
# Span select Button
#self.span_button = QAction(QIcon("border-1d-right-icon.png" ), "Span", self)
self.span_button = QAction( QIcon(QPixmap(":/icons/fit_limits.png")), "Span", self)
self.span_button = QAction(QIcon(QPixmap(":/icons/fit_limits.png")), "Fit Limits", self)
self.span_button.setCheckable(True)
self.cids = []
self.cids.append(self.canvas.mpl_connect('button_press_event', self.press))
self.cids.append(self.canvas.mpl_connect('motion_notify_event', self.onmove))
self.cids.append(self.canvas.mpl_connect('button_release_event', self.release))
self.cids.append(self.canvas.mpl_connect('draw_event', self.update_background))
# act.setCheckable(True)
# add actions before the coordinates widget
self.insertAction(self.actions()[-1], self.span_button)
self.buttons={}
self.buttons = {}
self._pressed = False
self.background = None
self.span = None
@ -597,18 +578,18 @@ class CustomToolbar(NavigationToolbar):
self.xstart = 0
self.xend = 0
def set_span(self,x1,x2):
def set_span(self, x1, x2):
#trans = blended_transform_factory(self.axes.transData, self.axes.transAxes)
cur = self.span.get_xy()
cur[0,0] = x1
cur[1,0] = x1
cur[2,0] = x2
cur[3,0] = x2
cur[0, 0] = x1
cur[1, 0] = x1
cur[2, 0] = x2
cur[3, 0] = x2
self.span.set_xy(cur)
def ignore(self, event):
# 'return ``True`` if *event* should be ignored'
return event.inaxes!=self.canvas.axes or event.button !=1
return event.inaxes != self.canvas.axes or event.button != 1
def update_background(self, event):
#if self.canvas.axes is None:
@ -624,13 +605,13 @@ class CustomToolbar(NavigationToolbar):
self.xstart = event.xdata
self.istart = event.x
if self.span is None:
self.span = self.canvas.axes.axvspan(event.xdata, event.xdata, alpha = 0.10, color = "k", animated=False)
self.span = self.canvas.axes.axvspan(event.xdata, event.xdata, alpha=0.10, color="k", animated=False)
else:
self.set_span(event.xdata, event.xdata)
self._pressed = True
def onmove(self,event):
if self.span_button.isChecked() and self._pressed and not self.ignore(event):
def onmove(self, event):
if self.span_button.isChecked() and self._pressed and not self.ignore(event):
self.set_span(self.xstart, event.xdata)
self.update()
@ -641,21 +622,20 @@ class CustomToolbar(NavigationToolbar):
self.canvas.axes.draw_artist(line)
self.canvas.blit(self.canvas.axes.bbox)
def release(self,event):
def release(self, event):
self.span_button.setChecked(False)
self.xend = event.xdata
self.iend = event.x
if self.iend < self.istart:
self.iend,self.istart = self.istart,self.iend
print "released",self.xstart,self.xend
self.iend, self.istart = self.istart, self.iend
print "released", self.xstart, self.xend
if self._pressed:
if self.ignore(event):
self.istart = 0
self.spanSelectedTrigger.emit(self.xstart,self.xend)
self.spanSelectedTrigger.emit(self.xstart, self.xend)
self._pressed = False
if __name__ == '__main__':
signal.signal(signal.SIGINT, sigint_handler)
app = QApplication(sys.argv)

View File

@ -2,8 +2,8 @@
# Form implementation generated from reading ui file 'QDSMain.ui'
#
# Created: Fri Jun 14 08:45:33 2013
# by: PyQt4 UI code generator 4.10.1
# Created: Wed Jul 10 18:32:01 2013
# by: PyQt4 UI code generator 4.10.2
#
# WARNING! All changes made in this file will be lost!

74
data.py
View File

@ -1,13 +1,17 @@
from PyQt4.QtCore import QObject, pyqtSignal
import numpy as N
import ConductivityWidget
class Data:
def __init__(self, frequency, die_real, die_imag):
self.frequency = frequency
self.epsilon = die_real +1j *die_imag
self.epsilon = die_real + 1j * die_imag
self.data_curve = None # mpl object
self.fitted_curve = None # mpl object
self.length = len(frequency)
self.meta = dict()
self.fit_limits = (frequency.min(),frequency.max(),die_imag.min(),die_imag.max())
self.fit_limits = (frequency.min(), frequency.max(), die_imag.min(), die_imag.max())
def __del__(self):
self.remove_curves()
@ -17,7 +21,7 @@ class Data:
"""
"""
mask = N.ones(len(self.frequency),dtype = 'bool')
mask = N.ones(len(self.frequency), dtype='bool')
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[1])
return self.frequency[mask], self.epsilon[mask]
@ -25,4 +29,66 @@ class Data:
def remove_curves(self):
if self.data_curve is not None: self.data_curve.remove()
if self.fitted_curve is not None: self.fitted_curve.remove()
class Conductivity(QObject):
changedData = pyqtSignal()
def __init__(self, mpl=None):
QObject.__init__(self)
super(Conductivity, self)
self.widget = ConductivityWidget.ConductivityWidget()
self.widget.changedTable.connect(self.updateData)
self.mpl_line = None
self.mpl_line_static = None
self.mpl = mpl
def getParameter(self):
p = self.widget.getTable()
return p
def getFixed(self):
p = self.widget.fixedParameter()
return p
def setParameter(self, eps_static=None, sigma=None, sigma_N=None):
self.widget.updateTable(eps_static, sigma, sigma_N)
self.updateData()
def updateData(self):
# get current axis limits
x_min, x_max = self.mpl.canvas.axes.get_xlim()
y_min, y_max = self.mpl.canvas.axes.get_ylim()
nu = N.logspace(N.log10(x_min), N.log10(x_max), 1024)
eps_static, sigma, sigma_N = self.getParameter()
y = conductivity([sigma, sigma_N], nu)
y_static = N.ones(len(nu)) * eps_static
# clip data to axes limits
mask_static = (y_static < y_max) & (y_static > y_min)
# clip data to axes limits
mask = (y < y_max) & (y > y_min)
#mask = mask_static = N.ones(1024, dtype='bool')
if self.mpl_line == None:
self.mpl_line, = self.mpl.canvas.axes.loglog(nu[mask], y[mask], 'k--', label="Cond.", animated=True) # peak
else:
self.mpl_line.set_xdata(nu[mask])
self.mpl_line.set_ydata(y[mask])
if self.mpl_line_static == None:
self.mpl_line_static, = self.mpl.canvas.axes.loglog(nu[mask_static],
y_static[mask_static],
'k:',
label=r"$\epsilon_S$",
animated=True) # peak
else:
self.mpl_line_static.set_xdata(nu[mask_static])
self.mpl_line_static.set_ydata(y_static[mask_static])
self.changedData.emit()
def conductivity(p, nu):
c = p[0] / (2 * N.pi * nu) ** p[1]
return c

View File

@ -1,8 +1,8 @@
<RCC>
<qresource prefix="icons">
<file>add_cond.svg</file>
<file>add_peak.svg</file>
<file>save_fit.svg</file>
<file>fit_limits.png</file>
</qresource>
<qresource prefix="icons">
<file>add_cond.svg</file>
<file>add_peak.svg</file>
<file>save_fit.svg</file>
<file>fit_limits.png</file>
</qresource>
</RCC>

View File

@ -2,7 +2,7 @@
# Resource object code
#
# Created: Fr. Jun 14 08:45:33 2013
# Created: Mi. Jul 10 18:32:00 2013
# by: The Resource Compiler for PyQt (Qt v4.8.4)
#
# WARNING! All changes made in this file will be lost!