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,6 +6,7 @@ import ConductivityGroupBox
class ConductivityWidget(QGroupBox):
changedTable = pyqtSignal()
def __init__(self, parent=None):
QGroupBox.__init__(self)
super(ConductivityWidget, self).__init__(parent)

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
#===============================================================================

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,6 +5,7 @@ import PeakGroupBox
class PeakWidget(QGroupBox):
changedTable = pyqtSignal()
def __init__(self, parent=None):
QGroupBox.__init__(self)
super(PeakWidget, self).__init__(parent)

246
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,6 +37,9 @@ def sigint_handler(*args):
def id_to_color(id):
"""
"""
colors = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
conv = matplotlib.colors.ColorConverter()
return conv.to_rgb(colors[id % len(colors)])
@ -47,14 +50,18 @@ def tau_peak(f,a,b):
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)
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]
@ -69,29 +76,21 @@ def multi_hn(p,nu):
#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_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)
# apply weights
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)
@ -100,6 +99,7 @@ def fit_odr(x,y,p0, fixed):
odr.run()
return odr.output.beta
def fit_lbfgsb(x, y, p0, fixed):
# TODO fixed parameters…
bounds = [(0, None), (0, 1)]
@ -120,6 +120,7 @@ def fit_lbfgsb(x,y,p0, fixed):
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):
@ -150,68 +151,9 @@ def fit_anneal(x,y,p0,fixed):
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__()
@ -249,7 +191,8 @@ class Peak(QObject):
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,7 +208,6 @@ class AppWindow(QMainWindow):
self.picked_artist = None
self.data = None
self.Conductivity = None
self._lines = dict()
@ -281,9 +222,10 @@ class AppWindow(QMainWindow):
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.setShortcut(QKeySequence("Ctrl+F"))
fitMenu.addAction(fit_lmAction)
# lbfgsb
fit_lbfgsbAction = QAction("&L-BFGS-B", self)
@ -291,6 +233,12 @@ class AppWindow(QMainWindow):
# Simulated Annealing
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
@ -301,19 +249,25 @@ class AppWindow(QMainWindow):
# 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_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):
"""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)
for line in self.mplWidget.canvas.axes.get_lines():
@ -324,14 +278,20 @@ 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")
# write header
f.write('# T ')
if self.Conductivity != None:
f.write("e_s sig pow_sig ")
f.write("%8s %8s %8s " % ("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))
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:
@ -339,27 +299,28 @@ class AppWindow(QMainWindow):
#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=" ")
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)
self.updatePlot()
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()
@ -426,7 +387,6 @@ class AppWindow(QMainWindow):
[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
@ -440,77 +400,82 @@ class AppWindow(QMainWindow):
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"
#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():
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():
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
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]
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.data_curve, = ax.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():
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():
@ -522,11 +487,11 @@ class AppWindow(QMainWindow):
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()
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],
self.data.fitted_curve, = ax.loglog(nu[mask], fit[mask],
'k-',
alpha=0.5,
label="Sum",
@ -534,14 +499,27 @@ class AppWindow(QMainWindow):
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):
@ -554,27 +532,30 @@ class PlotWidget(QWidget):
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 = []
@ -655,7 +636,6 @@ class CustomToolbar(NavigationToolbar):
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!

66
data.py
View File

@ -1,4 +1,8 @@
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
@ -26,3 +30,65 @@ class Data:
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

@ -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!