Skip to content
Commits on Source (7)
1.1.6
- fix: improve support for Confocor FCS file format
(see discussion in #37)
- ref: make pathlib.Path a standard in readfiles
- code cleanup
- drop support for Python<3.6
1.1.5
- docs: fix build with recent version of latex (#191)
1.1.4
......@@ -343,4 +349,4 @@
- Code cleanup: Opening data files is now handled internally differently.
0.6.9
- Initital GitHub commit
\ No newline at end of file
......@@ -17,7 +17,7 @@ at the `issues page <https://github.com/FCS-analysis/PyCorrFit/wiki/Creating-a-n
.. |PyCorrFit| image:: https://raw.github.com/FCS-analysis/PyCorrFit/master/doc/Images/PyCorrFit_logo_dark.png
.. |PyPI Version| image:: http://img.shields.io/pypi/v/PyCorrFit.svg
.. |PyPI Version| image:: https://img.shields.io/pypi/v/PyCorrFit.svg
:target: https://pypi.python.org/pypi/pycorrfit
.. |Build Status Win| image:: https://img.shields.io/appveyor/ci/paulmueller/PyCorrFit/master.svg?label=win
:target: https://ci.appveyor.com/project/paulmueller/pycorrfit
......
pycorrfit (1.1.6+dfsg-1) UNRELEASED; urgency=medium
* Update d/watch, normalize upstream version from d/changelog
* New upstream version 1.1.6+dfsg
* Bump Policy to 4.3.0
* Add X-Python3-Version: >= 3.6 to d/control
* Use debhelper-compat, drop d/compat
-- Alexandre Mestiashvili <mestia@debian.org> Mon, 06 May 2019 10:44:58 +0200
pycorrfit (1.1.5+dfsg-1) unstable; urgency=medium
* New upstream version 1.1.5+dfsg
......
......@@ -5,7 +5,7 @@ Uploaders: Alexandre Mestiashvili <mestia@debian.org>,
Section: python
Priority: optional
Build-Depends: cython3,
debhelper (>= 11),
debhelper-compat (= 12),
dh-python,
faketime,
imagemagick,
......@@ -27,10 +27,11 @@ Build-Depends: cython3,
texlive-latex-extra,
texlive-latex-recommended,
texlive-science
Standards-Version: 4.2.1
Standards-Version: 4.3.0
Vcs-Browser: https://salsa.debian.org/med-team/pycorrfit
Vcs-Git: https://salsa.debian.org/med-team/pycorrfit.git
Homepage: http://fcs-analysis.github.io/PyCorrFit/
X-Python3-Version: >= 3.6
Package: pycorrfit
Architecture: any
......@@ -44,7 +45,9 @@ Depends: python3-matplotlib,
${misc:Depends},
${python3:Depends},
${shlibs:Depends}
Recommends: dvipng, texlive-latex-base, texlive-science
Recommends: dvipng,
texlive-latex-base,
texlive-science
Description: tool for fitting correlation curves on a logarithmic plot
PyCorrFit is a general-purpose FCS evaluation software that,
amongst other formats, supports the established Zeiss ConfoCor3 ~.fcs
......
version=4
opts=uversionmangle=s/(\d)[_\.\-\+]?((RC|rc|pre|dev|beta|alpha)\d*)$/$1~$2/,\
filenamemangle=s/.+\/v?(\d\S*)\.tar\.gz/pycorrfit-$1\.tar\.gz/,dversionmangle=s/\+dfsg(\.\d+)?$//,repacksuffix=+dfsg,repack \
filenamemangle=s/.+\/v?(\d\S*)\.tar\.gz/pycorrfit-$1\.tar\.gz/,dversionmangle=s/\+dfsg.*$//,repacksuffix=+dfsg,repack \
https://github.com/paulmueller/PyCorrFit/tags .*/v?(\d\S*)\.tar\.gz
.. _index:
PyCorrFit documentation
=======================
.. image:: _static/PyCorrFit_logo_dark.png
|
Welcome to the documentation of PyCorrFit (version |release|), a data analysis software for
fluorescence correlation spectroscopy (FCS).
Documentation
=============
.. toctree::
:maxdepth: 1
:caption: Contents:
:maxdepth: 2
sec_about
sec_gallery
sec_getting_started
sec_contribute
.. toctree::
:maxdepth: 1
sec_changelog
......
......@@ -3,8 +3,7 @@ from os.path import dirname, abspath, split
import sys
sys.path = [split(abspath(dirname(__file__)))[0]] + sys.path
from pycorrfit.gui import main
from pycorrfit.gui import main # noqa: E402
if __name__ == "__main__":
......
......@@ -138,4 +138,4 @@ if True: # pragma: no cover
save_version(longversion, versionfile)
# PEP 440-conform development version:
version = ".dev".join(longversion.split("-")[:2])
version = ".post".join(longversion.split("-")[:2])
......@@ -12,6 +12,7 @@ from .trace import Trace
class Correlation(object):
""" unifies correlation curve handling
"""
def __init__(self, backgrounds=[], correlation=None, corr_type="AC",
filename=None, fit_algorithm="Lev-Mar",
fit_model=6000, fit_ival=(0, 0),
......@@ -93,7 +94,7 @@ class Correlation(object):
else:
c = "CC"
text = "{} correlation '{}' with {} traces".format(
c, self.title, len(self._traces))
c, self.title, len(self._traces))
return text
def background_replace(self, channel, background):
......@@ -144,7 +145,8 @@ class Correlation(object):
elif isinstance(v, Trace):
backgrounds.append(v)
else:
raise ValueError("Each background must be instance of Trace or ndarray")
raise ValueError(
"Each background must be instance of Trace or ndarray")
self._backgrounds = backgrounds
@property
......@@ -321,12 +323,13 @@ class Correlation(object):
else:
raise NotImplementedError("Unknown model identifier")
if newmodel != self._fit_model :
if newmodel != self._fit_model:
self._fit_model = newmodel
# overwrite fitting parameters
self._fit_parameters = self._fit_model.default_values
self._fit_parameters_variables = self._fit_model.default_variables
self._fit_parameters_range = np.zeros((len(self._fit_parameters), 2))
self._fit_parameters_range = np.zeros(
(len(self._fit_parameters), 2))
self.normparm = None
@property
......@@ -390,8 +393,8 @@ class Correlation(object):
expect_shape = (self.fit_parameters.shape[0], 2)
if value.shape != expect_shape:
msg = "Expected shape of fit parameters: {} (vs {})".format(
expect_shape, value.shape
)
expect_shape, value.shape
)
raise ValueError(msg)
self._fit_parameters_range = value
......@@ -399,7 +402,8 @@ class Correlation(object):
def fit_parameters_variable(self):
"""which parameters are variable during fitting"""
if self._fit_parameters_variable is None:
self._fit_parameters_variable = np.array(self.fit_model.default_variables, dtype=bool)
self._fit_parameters_variable = np.array(
self.fit_model.default_variables, dtype=bool)
return self._fit_parameters_variable
@fit_parameters_variable.setter
......@@ -408,7 +412,7 @@ class Correlation(object):
expect_size = self.fit_parameters.shape[0]
if value.shape[0] != expect_size:
msg = "Fit parameter variables must have size {}!".format(
expect_size)
expect_size)
raise ValueError(msg)
self._fit_parameters_variable = value
......@@ -416,17 +420,18 @@ class Correlation(object):
def lag_time(self):
"""logarithmic lag time axis"""
if self.correlation is not None:
return self._correlation[:,0].copy()
return self._correlation[:, 0].copy()
elif self._lag_time is not None:
return self._lag_time
else:
# some default lag time
return 10**np.linspace(-6,8,1001)
return 10**np.linspace(-6, 8, 1001)
@lag_time.setter
def lag_time(self, value):
if self.correlation is not None:
warnings.warn("Setting lag time not possible, because of existing correlation")
warnings.warn(
"Setting lag time not possible, because of existing correlation")
else:
self._lag_time = value
......@@ -441,8 +446,8 @@ class Correlation(object):
# perform parameter normalization
lag = self.lag_time
modeled = np.zeros((lag.shape[0], 2))
modeled[:,0] = lag
modeled[:,1] = self.fit_model(self.fit_parameters, lag)
modeled[:, 0] = lag
modeled[:, 1] = self.fit_model(self.fit_parameters, lag)
return modeled.copy()
@property
......@@ -455,7 +460,7 @@ class Correlation(object):
def modeled_plot(self):
"""fitted data values, same shape as self.correlation_fit"""
toplot = self.modeled_fit
toplot[:,1] *= self.normalize_factor
toplot[:, 1] *= self.normalize_factor
return toplot
@property
......@@ -479,14 +484,14 @@ class Correlation(object):
if self.correlation is None:
raise ValueError("Cannot compute residuals; No correlation given!")
residuals = self.correlation.copy()
residuals[:,1] -= self.modeled[:,1]
residuals[:, 1] -= self.modeled[:, 1]
return residuals
@property
def residuals_fit(self):
"""fit residuals, same shape as self.correlation_fit"""
residuals_fit = self.correlation_fit.copy()
residuals_fit[:,1] -= self.modeled_fit[:,1]
residuals_fit[:, 1] -= self.modeled_fit[:, 1]
return residuals_fit
@property
......@@ -495,7 +500,7 @@ class Correlation(object):
cp = self.correlation_plot
if cp is not None:
residuals_plot = self.correlation_plot.copy()
residuals_plot[:,1] -= self.modeled_plot[:,1]
residuals_plot[:, 1] -= self.modeled_plot[:, 1]
return residuals_plot
def set_weights(self, type_name, data):
......@@ -532,7 +537,8 @@ class Correlation(object):
elif isinstance(v, Trace):
traces.append(v)
else:
raise ValueError("Each trace must be instance of Trace or ndarray")
raise ValueError(
"Each trace must be instance of Trace or ndarray")
self._traces = traces
if len(self._traces) == 2:
......
This diff is collapsed.
......@@ -61,10 +61,10 @@ def info(version):
texta = textlin
one = u" PyCorrFit version "+version+"\n\n"
two = u"\n\n Supported file types:"
keys = readfiles.Filetypes.keys()
keys = readfiles.filetypes_dict.keys()
keys = sorted(list(keys))
for item in keys:
if item.split("|")[0] != readfiles.Allsupfilesstring:
if item.split("|")[0] != readfiles.ALL_SUP_STRING:
two = two + "\n - "+item.split("|")[0]
lizenz = ""
for line in licence().splitlines():
......@@ -90,19 +90,19 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
def SoftwareUsed():
"""Return some Information about the software used for this program"""
text = "Python "+sys.version+\
"\n\nModules:"+\
"\n - cython "+\
"\n - lmfit "+lmfit.__version__+\
"\n - matplotlib "+matplotlib.__version__+\
"\n - NumPy "+numpy.__version__+\
text = "Python "+sys.version +\
"\n\nModules:" +\
"\n - cython " +\
"\n - lmfit "+lmfit.__version__ +\
"\n - matplotlib "+matplotlib.__version__ +\
"\n - NumPy "+numpy.__version__ +\
"\n - PyYAML "+yaml.__version__ +\
"\n - SciPy "+scipy.__version__+\
"\n - simplejson "+simplejson.__version__+\
"\n - SciPy "+scipy.__version__ +\
"\n - simplejson "+simplejson.__version__ +\
"\n - sympy "+sympy.__version__ +\
"\n - wxPython "+wx.__version__
# Other software
text += "\n\nOther software:"+\
text += "\n\nOther software:" +\
"\n - FCS_point_correlator ({})".format(read_pt3_scripts.version) +\
"\n PicoQuant file format for Python by Dominic Waithe"
if hasattr(sys, 'frozen'):
......
......@@ -7,15 +7,16 @@ import traceback
import warnings
import matplotlib
import wx
import wx
# We do catch warnings about performing this before matplotlib.backends stuff
#matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets
# matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets for dialogs
# Tells matplotlib to use WxWidgets for dialogs
matplotlib.use('WXAgg')
except:
pass
......@@ -24,10 +25,10 @@ class ChoicesDialog(wx.Dialog):
def __init__(self, parent, dropdownlist, title, text):
# parent is main frame
self.parent = parent
#super(ChoicesDialog, self).__init__(parent=parent,
# super(ChoicesDialog, self).__init__(parent=parent,
# title=title)
wx.Dialog.__init__(self, parent, -1, title)
## Controls
# Controls
panel = wx.Panel(self)
# text1
textopen = wx.StaticText(panel, label=text)
......@@ -35,7 +36,7 @@ class ChoicesDialog(wx.Dialog):
btnabort = wx.Button(panel, wx.ID_CANCEL)
# Dropdown
self.dropdown = wx.ComboBox(panel, -1, "", (15, 30),
wx.DefaultSize, dropdownlist, wx.CB_DROPDOWN|wx.CB_READONLY)
wx.DefaultSize, dropdownlist, wx.CB_DROPDOWN | wx.CB_READONLY)
self.dropdown.SetSelection(0)
# Bindings
self.Bind(wx.EVT_BUTTON, self.OnOK, btnok)
......@@ -50,19 +51,17 @@ class ChoicesDialog(wx.Dialog):
topSizer.Add(btnSizer)
panel.SetSizer(topSizer)
topSizer.Fit(self)
#self.Show(True)
# self.Show(True)
self.SetFocus()
def OnOK(self, event=None):
self.SelcetedID = self.dropdown.GetSelection()
self.EndModal(wx.ID_OK)
def OnAbort(self, event=None):
self.EndModal(wx.ID_CANCEL)
def save_figure(self, evt=None):
"""
A substitude function for save in:
......@@ -70,8 +69,8 @@ def save_figure(self, evt=None):
We want to be able to give parameters such as dirname and filename.
"""
try:
parent=self.canvas.HACK_parent
fig=self.canvas.HACK_fig
parent = self.canvas.HACK_parent
fig = self.canvas.HACK_fig
Page = self.canvas.HACK_Page
add = self.canvas.HACK_append
dirname = parent.dirname
......@@ -89,8 +88,8 @@ def save_figure(self, evt=None):
fieltypestring += formats[key]+"(*."+key+")|*."+key+"|"
# remove last |
fieltypestring = fieltypestring[:-1]
dlg = wx.FileDialog(parent, "Save figure", dirname, filename,
fieltypestring, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
dlg = wx.FileDialog(parent, "Save figure", dirname, filename,
fieltypestring, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
# png is default
dlg.SetFilterIndex(keys.index("png"))
# user cannot do anything until he clicks "OK"
......@@ -104,7 +103,7 @@ def save_figure(self, evt=None):
savename = filename
try:
self.canvas.figure.savefig(savename)
except: # RuntimeError:
except: # RuntimeError:
# The file does not seem to be what it seems to be.
info = sys.exc_info()
errstr = "Could not latex output:\n"
......@@ -113,8 +112,8 @@ def save_figure(self, evt=None):
errstr += str(info[1])+"\n"
for tb_item in traceback.format_tb(info[2]):
errstr += tb_item
wx.MessageDialog(parent, errstr, "Error",
style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP)
wx.MessageDialog(parent, errstr, "Error",
style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP)
else:
dirname = dlg.GetDirectory()
try:
......@@ -127,37 +126,39 @@ class MyScrolledDialog(wx.Dialog):
def __init__(self, parent, overtext, readtext, title):
wx.Dialog.__init__(self, parent, title=title)
overtext = wx.StaticText(self, label=overtext)
text = wx.TextCtrl(self, -1, readtext, size=(500,400),
text = wx.TextCtrl(self, -1, readtext, size=(500, 400),
style=wx.TE_MULTILINE | wx.TE_READONLY)
sizer = wx.BoxSizer(wx.VERTICAL )
sizer = wx.BoxSizer(wx.VERTICAL)
btnsizer = wx.BoxSizer()
btn = wx.Button(self, wx.ID_OK)#, "OK ")
btn = wx.Button(self, wx.ID_OK) # , "OK ")
btnsizer.Add(btn, 0, wx.ALL, 5)
btnsizer.Add((5,-1), 0, wx.ALL, 5)
btn = wx.Button(self, wx.ID_CANCEL)#, "Abort ")
btnsizer.Add((5, -1), 0, wx.ALL, 5)
btn = wx.Button(self, wx.ID_CANCEL) # , "Abort ")
btnsizer.Add(btn, 0, wx.ALL, 5)
sizer.Add(overtext, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(text, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
sizer.Add(overtext, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(text, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.EXPAND |
wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
self.SetSizerAndFit(sizer)
class MyOKAbortDialog(wx.Dialog):
def __init__(self, parent, text, title):
wx.Dialog.__init__(self, parent, title=title)
overtext = wx.StaticText(self, label=text)
sizer = wx.BoxSizer(wx.VERTICAL )
sizer = wx.BoxSizer(wx.VERTICAL)
btnsizer = wx.BoxSizer()
btn = wx.Button(self, wx.ID_OK)#, "OK ")
btn = wx.Button(self, wx.ID_OK) # , "OK ")
btnsizer.Add(btn, 0, wx.ALL, 5)
btnsizer.Add((5,-1), 0, wx.ALL, 5)
btn = wx.Button(self, wx.ID_CANCEL)#, "Abort ")
btnsizer.Add((5, -1), 0, wx.ALL, 5)
btn = wx.Button(self, wx.ID_CANCEL) # , "Abort ")
btnsizer.Add(btn, 0, wx.ALL, 5)
sizer.Add(overtext, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
sizer.Add(overtext, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.EXPAND |
wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
self.SetSizerAndFit(sizer)
class MyYesNoAbortDialog(wx.Dialog):
def __init__(self, parent, text, title):
wx.Dialog.__init__(self, parent, title=title)
......@@ -167,18 +168,19 @@ class MyYesNoAbortDialog(wx.Dialog):
btn1 = wx.Button(self, wx.ID_YES)
#btn1.Bind(wx.EVT_BTN, self.YES)
btnsizer.Add(btn1, 0, wx.ALL, 5)
btnsizer.Add((1,-1), 0, wx.ALL, 5)
btnsizer.Add((1, -1), 0, wx.ALL, 5)
btn2 = wx.Button(self, wx.ID_NO)
btnsizer.Add(btn2, 0, wx.ALL, 5)
btnsizer.Add((1,-1), 0, wx.ALL, 5)
btnsizer.Add((1, -1), 0, wx.ALL, 5)
btn3 = wx.Button(self, wx.ID_CANCEL)
btnsizer.Add(btn3, 0, wx.ALL, 5)
sizer.Add(overtext, 0, wx.EXPAND|wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
sizer.Add(overtext, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.EXPAND |
wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
self.SetSizerAndFit(sizer)
self.SetFocus()
self.Show()
def YES(self, e):
self.EndModal(wx.ID_YES)
......
This diff is collapsed.
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
# This file was generated by /usr/bin/img2py
#
from wx.lib.embeddedimage import PyEmbeddedImage
......
"""Main execution script"""
from distutils.version import LooseVersion
import os
import sys
import warnings
import yaml
import numpy as np
import scipy
class Fake(object):
""" Fake module.
"""
def __init__(self):
self.__version__ = "0.0 unknown"
self.version = "0.0 unknown"
......@@ -20,13 +25,10 @@ try:
except ImportError:
matplotlib = Fake()
# We do catch warnings about performing this before matplotlib.backends stuff
#matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets
import warnings
# matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets
with warnings.catch_warnings():
warnings.simplefilter("ignore")
matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets for dialogs
import numpy as np # NumPy
import scipy
matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets for dialogs
# Sympy is optional:
......@@ -38,16 +40,14 @@ except ImportError:
# We create a fake module sympy with a __version__ property.
# This way users can run PyCorrFit without having installed sympy.
sympy = Fake()
# We must not import wx here. frontend/gui does that. If we do import wx here,
# somehow unicode characters will not be displayed correctly on windows.
# import wx
import yaml
## Continue with the import:
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from . import doc
from . import frontend as gui # The actual program
# Continue with the import:
from . import frontend as gui # noqa: E402
from . import doc # noqa: E402
def CheckVersion(given, required, name):
......@@ -62,22 +62,22 @@ def CheckVersion(given, required, name):
print(" WARNING: Could not verify version of "+name+".")
return
if req > giv:
print(" WARNING: You are using "+name+" v. "+given+\
" | Required: "+name+" "+ required)
print(" WARNING: You are using "+name+" v. "+given +
" | Required: "+name+" " + required)
else:
print(" OK: "+name+" v. "+given+" | "+required+" required")
## Start gui
# Start gui
def Main():
## VERSION
# VERSION
version = doc.__version__
__version__ = version
print(gui.doc.info(version))
## Check important module versions
# Check important module versions
print("\n\nChecking module versions...")
CheckVersion(matplotlib.__version__, "2.2.2", "matplotlib")
CheckVersion(np.__version__, "1.14.2", "NumPy")
......@@ -86,7 +86,7 @@ def Main():
CheckVersion(sympy.__version__, "1.1.1", "sympy")
CheckVersion(gui.wx.__version__, "4.0.1", "wxPython")
## Start gui
# Start gui
app = gui.MyApp(False)
frame = gui.MyFrame(None, -1, version)
......
......@@ -31,12 +31,12 @@ def parseString2Pagenum(parent, string, nodialog=False):
return PageNumbers
except:
if nodialog is False:
errstring = "Invalid syntax in page selection: "+string+\
". Please use a comma separated list with"+\
errstring = "Invalid syntax in page selection: "+string +\
". Please use a comma separated list with" +\
" optional dashes, e.g. '1-3,6,8'."
try:
wx.MessageDialog(parent, errstring, "Error",
style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP)
style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP)
except:
raise ValueError(errstring)
else:
......@@ -110,4 +110,3 @@ def getMainIcon(pxlength=32):
iconBMP = wx.Bitmap(image)
iconICO = wx.Icon(iconBMP)
return iconICO
This diff is collapsed.
......@@ -13,15 +13,16 @@ import re
with warnings.catch_warnings():
warnings.simplefilter("ignore")
matplotlib.use('WXAgg') # Tells matplotlib to use WxWidgets for dialogs
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
# Text rendering with matplotlib
from matplotlib import rcParams
import unicodedata
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# For finding latex tools
from pycorrfit.meta import find_program
from pycorrfit import models as mdls
import unicodedata
from .. import models as mdls
from ..meta import find_program
def greek2tex(char):
......@@ -103,7 +104,7 @@ def latexmath(string):
else:
anew += char
# lower case
lcitems = anew.split("_",1)
lcitems = anew.split("_", 1)
if len(lcitems) > 1:
anew = lcitems[0]+"_{\\text{"+lcitems[1]+"}}"
return anew + r" \hspace{0.3em} \mathrm{"+b+r"}"
......@@ -154,7 +155,7 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
weights = Page.weights_plot_fill_area
tabtitle = Page.tabtitle.GetValue()
#fitlabel = ur"Fit model: "+str(mdls.modeldict[Page.modelid][0])
# fitlabel = ur"Fit model: "+str(mdls.modeldict[Page.modelid][0])
fitlabel = Page.corr.fit_model.name
labelweights = r"Weights of fit"
labels, parms = mdls.GetHumanReadableParms(Page.modelid,
......@@ -168,22 +169,23 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
if tabtitle.strip() == "":
tabtitle = "page"+str(Page.counter).strip().strip(":")
if Page.corr.normparm is not None:
fitlabel += r", normalized to "+Page.corr.fit_model.parameters[0][Page.corr.normparm]
fitlabel += r", normalized to " + \
Page.corr.fit_model.parameters[0][Page.corr.normparm]
## Check if we can use latex for plotting:
# Check if we can use latex for plotting:
r1 = find_program("latex")[0]
r2 = find_program("dvipng")[0]
# Ghostscript
r31 = find_program("gs")[0]
r32 = find_program("mgs")[0] # from miktex
r3 = max(r31,r32)
r32 = find_program("mgs")[0] # from miktex
r3 = max(r31, r32)
if r1+r2+r3 < 3:
uselatex = False
if uselatex == True:
rcParams['text.usetex'] = True
rcParams['text.latex.unicode'] = True
rcParams['font.family'] = 'serif'
rcParams['text.latex.preamble']=[r"""\usepackage{amsmath}
rcParams['text.latex.preamble'] = [r"""\usepackage{amsmath}
\usepackage[utf8x]{inputenc}
\usepackage{amssymb}
\usepackage{siunitx}"""]
......@@ -191,31 +193,31 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
tabtitle = r"{\normalsize "+escapechars(tabtitle)+r"}"
labelweights = r"{\normalsize "+escapechars(labelweights)+r"}"
else:
rcParams['text.usetex']=False
rcParams['text.usetex'] = False
# create plot
# plt.plot(x, y, '.', label = 'original data', markersize=5)
fig=plt.figure()
fig = plt.figure()
wtit = "Correlation #{:04d}_{}".format(int(Page.counter.strip(":# ")),
Page.title.strip())
Page.title.strip())
fig.canvas.set_window_title(wtit)
if resid is not None:
gs = gridspec.GridSpec(2, 1, height_ratios=[5,1])
gs = gridspec.GridSpec(2, 1, height_ratios=[5, 1])
ax = plt.subplot(gs[0])
else:
ax = plt.subplot(111)
# ax = plt.axes()
ax.semilogx()
# plot fit first
plt.plot(fit[:,0], fit[:,1], '-', label=fitlabel, lw=1.5,
plt.plot(fit[:, 0], fit[:, 1], '-', label=fitlabel, lw=1.5,
color="blue")
if dataexp is not None:
plt.plot(dataexp[:,0], dataexp[:,1], '-', color="black",
plt.plot(dataexp[:, 0], dataexp[:, 1], '-', color="black",
alpha=.7, label=tabtitle, lw=1)
else:
plt.xlabel(r'lag time $\tau$ [ms]')
if weights is not None and show_weights is True:
plt.fill_between(weights[0][:,0],weights[0][:,1],weights[1][:,1],
plt.fill_between(weights[0][:, 0], weights[0][:, 1], weights[1][:, 1],
color='cyan')
# fake legend:
p = plt.Rectangle((0, 0), 0, 0, color='cyan',
......@@ -223,16 +225,16 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
ax.add_patch(p)
plt.ylabel('correlation')
if dataexp is not None:
mind = np.min([ dataexp[:,1], fit[:,1]])
maxd = np.max([ dataexp[:,1], fit[:,1]])
mind = np.min([dataexp[:, 1], fit[:, 1]])
maxd = np.max([dataexp[:, 1], fit[:, 1]])
else:
mind = np.min(fit[:,1])
maxd = np.max(fit[:,1])
mind = np.min(fit[:, 1])
maxd = np.max(fit[:, 1])
ymin = mind - (maxd - mind)/20.
ymax = maxd + (maxd - mind)/20.
ax.set_ylim(bottom=ymin, top=ymax)
xmin = np.min(fit[:,0])
xmax = np.max(fit[:,0])
xmin = np.min(fit[:, 0])
xmax = np.max(fit[:, 0])
ax.set_xlim(xmin, xmax)
# Add some nice text:
if uselatex == True and len(parms) != 0:
......@@ -240,8 +242,8 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
text += r'\['
text += r'\begin{split}'
text += genLatexText(parms, labels)
## According to issue #54, we remove fitting errors from plots
#if errparms is not None:
# According to issue #54, we remove fitting errors from plots
# if errparms is not None:
# keys = errparms.keys()
# keys.sort()
# for key in keys:
......@@ -252,21 +254,19 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
text = r""
for i in np.arange(len(parms)):
text += u"{} = {:.3g}\n".format(labels[i], parms[i])
## According to issue #54, we remove fitting errors from plots
#if errparms is not None:
# According to issue #54, we remove fitting errors from plots
# if errparms is not None:
# keys = errparms.keys()
# keys.sort()
# for key in keys:
# text += "Err "+key+" = " + str(errparms[key]) +"\n"
logmax = np.log10(xmax)
logmin = np.log10(xmin)
logtext = 0.6*(logmax-logmin)+logmin
xt = 10**(logtext)
yt = 0.3*ymax
plt.text(xt,yt,text, size=12)
plt.text(xt, yt, text, size=12)
if resid is not None:
ax2 = plt.subplot(gs[1])
#ax2 = plt.axes()
......@@ -276,15 +276,15 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
lb = r"\newline \indent "
else:
lb = "\n"
yLabelRes = "weighted "+ lb +"residuals"
yLabelRes = "weighted " + lb + "residuals"
else:
yLabelRes = "residuals"
minx = np.min(resid[:,0])
maxx = np.max(resid[:,0])
miny = np.min(resid[:,1])
maxy = np.max(resid[:,1])
minx = np.min(resid[:, 0])
maxx = np.max(resid[:, 0])
miny = np.min(resid[:, 1])
maxy = np.max(resid[:, 1])
plt.hlines(0, minx, maxx, colors="orange")
plt.plot(resid[:,0], resid[:,1], '-', color="black",
plt.plot(resid[:, 0], resid[:, 1], '-', color="black",
alpha=.85, label=yLabelRes, lw=1)
plt.xlabel(r'lag time $\tau$ [ms]')
plt.ylabel(yLabelRes, multialignment='center')
......@@ -294,14 +294,13 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
ax2.set_ylim(-maxy, maxy)
ticks = ax2.get_yticks()
ax2.set_yticks([ticks[0], ticks[-1], 0])
## Hack
# Hack
# We need this for hacking. See edclasses.
fig.canvas.HACK_parent = parent
fig.canvas.HACK_fig = fig
fig.canvas.HACK_Page = Page
fig.canvas.HACK_append = ".png"
# Legend outside of plot
# Decrease size of plot to fit legend
box = ax.get_position()
......@@ -312,11 +311,10 @@ def savePlotCorrelation(parent, dirname, Page, uselatex=False,
if resid is not None:
box2 = ax2.get_position()
ax2.set_position([box2.x0, box2.y0 + box.height * 0.2,
box2.width, box2.height])
box2.width, box2.height])
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.55),
prop={'size':9})
prop={'size': 9})
if verbose == True:
plt.show()
......@@ -364,44 +362,44 @@ def savePlotTrace(parent, dirname, Page, uselatex=False, verbose=False):
for ii, tr in enumerate(traces):
labels.append("Channel {}: {}".format(ii+1, tr.name))
## Check if we can use latex for plotting:
# Check if we can use latex for plotting:
r1 = find_program("latex")[0]
r2 = find_program("dvipng")[0]
# Ghostscript
r31 = find_program("gs")[0]
r32 = find_program("mgs")[0]
r3 = max(r31,r32)
r3 = max(r31, r32)
if r1+r2+r3 < 3:
uselatex = False
if uselatex == True:
rcParams['text.usetex']=True
rcParams['text.latex.unicode']=True
rcParams['font.family']='serif'
rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
rcParams['text.usetex'] = True
rcParams['text.latex.unicode'] = True
rcParams['font.family'] = 'serif'
rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"]
for i in np.arange(len(labels)):
labels[i] = r"{\normalsize "+escapechars(labels[i])+r"}"
else:
rcParams['text.usetex']=False
rcParams['text.usetex'] = False
# create plot
# plt.plot(x, y, '.', label = 'original data', markersize=5)
fig=plt.figure(figsize=(10,3))
fig = plt.figure(figsize=(10, 3))
wtit = "Trace #{:04d}_{}".format(int(Page.counter.strip(":# ")),
Page.title.strip())
fig.canvas.set_window_title(wtit)
ax = plt.subplot(111)
for i in np.arange(len(traces)):
# Columns
time = traces[i][:,0]*timefactor
intensity = traces[i][:,1]
time = traces[i][:, 0]*timefactor
intensity = traces[i][:, 1]
plt.plot(time, intensity, '-',
label = labels[i],
label=labels[i],
lw=1)
# set plot boundaries
maxy = -np.infty
miny = np.infty
for tr in traces:
maxy = max(np.max(tr[:,1]), maxy)
miny = min(np.min(tr[:,1]), miny)
maxy = max(np.max(tr[:, 1]), maxy)
miny = min(np.min(tr[:, 1]), miny)
ax.set_ylim(miny, maxy)
plt.ylabel('count rate [kHz]')
......@@ -414,17 +412,17 @@ def savePlotTrace(parent, dirname, Page, uselatex=False, verbose=False):
box.width, box.height * 0.9])
plt.legend(loc='upper center',
bbox_to_anchor=(0.5, -0.35),
prop={'size':9},
prop={'size': 9},
)
## Hack
# Hack
# We need this for hacking. See edclasses.
fig.canvas.HACK_parent = parent
fig.canvas.HACK_fig = fig
fig.canvas.HACK_Page = Page
fig.canvas.HACK_append = "_trace.png"
plt.tight_layout(rect=(.001,.34,.999,1.0))
plt.tight_layout(rect=(.001, .34, .999, 1.0))
if verbose == True:
plt.show()
......@@ -441,5 +439,6 @@ def savePlotTrace(parent, dirname, Page, uselatex=False, verbose=False):
except:
pass
# set dpi to 300
matplotlib.rcParams['savefig.dpi'] = 300
......@@ -20,6 +20,7 @@ class KThread(threading.Thread):
thread will not actually be killed until the next Python statement is
executed.
"""
def __init__(self, *args, **keywords):
threading.Thread.__init__(self, *args, **keywords)
self.killed = False
......@@ -53,9 +54,9 @@ class KThread(threading.Thread):
self.killed = True
class WorkerThread(KThread):
"""Worker Thread Class."""
def __init__(self, target, args, kwargs):
"""Init Worker Thread Class."""
KThread.__init__(self)
......@@ -134,21 +135,20 @@ class ThreadedProgressDlg(object):
elif isinstance(args, list):
# convenience-convert args to tuples
if not isinstance(args[0], tuple):
args = [ (t,) for t in args ]
args = [(t,) for t in args]
if isinstance(kwargs, dict):
kwargs = [kwargs]*nums
if not messages:
messages = [ "item {} of {}".format(a+1, nums) for a in range(nums) ]
messages = ["item {} of {}".format(a+1, nums) for a in range(nums)]
time1 = time.time()
sty = wx.PD_SMOOTH|wx.PD_AUTO_HIDE|wx.PD_CAN_ABORT
sty = wx.PD_SMOOTH | wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT
if len(targets) > 1:
sty = sty|wx.PD_REMAINING_TIME
sty = sty | wx.PD_REMAINING_TIME
dlgargs = [title, "initializing..."]
dlgkwargs = {"maximum":nums, "parent":parent, "style":sty }
dlgkwargs = {"maximum": nums, "parent": parent, "style": sty}
dlg = None
self.aborted = False
......@@ -166,7 +166,7 @@ class ThreadedProgressDlg(object):
dlg = wx.ProgressDialog(*dlgargs, **dlgkwargs)
wx.EndBusyCursor()
init=False
init = False
time.sleep(.01)
if dlg:
if len(targets) == 1:
......@@ -207,25 +207,25 @@ class ThreadedProgressDlg(object):
pass
if __name__ == "__main__":
# GUI Frame class that spins off the worker thread
class MainFrame(wx.Frame):
"""Class MainFrame."""
def __init__(self, parent, aid):
"""Create the MainFrame."""
wx.Frame.__init__(self, parent, aid, 'Thread Test')
# Dumb sample frame with two buttons
but = wx.Button(self, wx.ID_ANY, 'Start Progress', pos=(0,0))
but = wx.Button(self, wx.ID_ANY, 'Start Progress', pos=(0, 0))
self.Bind(wx.EVT_BUTTON, self.OnStart, but)
def OnStart(self, event):
"""Start Computation."""
# Trigger the worker thread unless it's already busy
arguments = [ test_class(a) for a in range(10) ]
arguments = [test_class(a) for a in range(10)]
def method(x):
x.arg *= 1.1
time.sleep(1)
......@@ -233,9 +233,9 @@ if __name__ == "__main__":
print(tp.index_aborted)
print([a.arg for a in arguments])
class MainApp(wx.App):
"""Class Main App."""
def OnInit(self):
"""Init Main App."""
self.frame = MainFrame(None, -1)
......@@ -247,6 +247,5 @@ if __name__ == "__main__":
def __init__(self, arg):
self.arg = arg
app = MainApp(0)
app.MainLoop()
\ No newline at end of file
app.MainLoop()