From fafdf0f4e1631c16efa4f0cc1c0af1bfb0454954 Mon Sep 17 00:00:00 2001
From: Caden Myers
Date: Tue, 16 Jul 2024 12:40:11 -0400
Subject: [PATCH] black edits
---
conda-recipe/expandpdfguibase.py | 8 +-
conda-recipe/run_test.py | 1 +
setup.py | 151 ++--
src/diffpy/__init__.py | 1 +
src/diffpy/pdfgui/__init__.py | 4 +-
src/diffpy/pdfgui/applications/pdfgui.py | 27 +-
src/diffpy/pdfgui/control/calculation.py | 169 ++--
src/diffpy/pdfgui/control/constraint.py | 47 +-
src/diffpy/pdfgui/control/controlerrors.py | 22 +-
src/diffpy/pdfgui/control/fitdataset.py | 213 +++--
src/diffpy/pdfgui/control/fitstructure.py | 276 +++---
src/diffpy/pdfgui/control/fitting.py | 184 ++--
src/diffpy/pdfgui/control/organizer.py | 63 +-
src/diffpy/pdfgui/control/parameter.py | 36 +-
src/diffpy/pdfgui/control/pdfcomponent.py | 5 +-
src/diffpy/pdfgui/control/pdfdataset.py | 144 +--
src/diffpy/pdfgui/control/pdfguicontrol.py | 111 +--
src/diffpy/pdfgui/control/pdfguimacros.py | 125 ++-
src/diffpy/pdfgui/control/pdflist.py | 7 +-
src/diffpy/pdfgui/control/pdfstructure.py | 69 +-
src/diffpy/pdfgui/control/plotter.py | 308 ++++---
src/diffpy/pdfgui/control/structureviewer.py | 55 +-
.../pdfgui/doc/manual/extractEquations.py | 58 +-
src/diffpy/pdfgui/doc/manual/fixHTMLCode.py | 12 +-
.../doc/tutorial/tui_mno_bond_lengths.py | 42 +-
src/diffpy/pdfgui/gui/aboutdialog.py | 93 +-
src/diffpy/pdfgui/gui/adddatapanel.py | 65 +-
src/diffpy/pdfgui/gui/addphasepanel.py | 91 +-
src/diffpy/pdfgui/gui/blankpanel.py | 3 +
src/diffpy/pdfgui/gui/bondangledialog.py | 48 +-
src/diffpy/pdfgui/gui/bondlengthdialog.py | 27 +-
src/diffpy/pdfgui/gui/calculationpanel.py | 128 ++-
.../pdfgui/gui/datasetconfigurepanel.py | 212 +++--
.../pdfgui/gui/datasetconstraintpanel.py | 52 +-
src/diffpy/pdfgui/gui/datasetpanel.py | 15 +-
src/diffpy/pdfgui/gui/datasetresultspanel.py | 54 +-
src/diffpy/pdfgui/gui/debugoptions.py | 17 +-
src/diffpy/pdfgui/gui/dopingseriespanel.py | 113 ++-
src/diffpy/pdfgui/gui/errorreportdialog.py | 53 +-
.../gui/errorreportdialog_control_fix.py | 23 +-
src/diffpy/pdfgui/gui/errorwrapper.py | 19 +-
src/diffpy/pdfgui/gui/extendedplotframe.py | 220 +++--
src/diffpy/pdfgui/gui/fitnotebookpanel.py | 11 +-
src/diffpy/pdfgui/gui/fittree.py | 197 ++--
src/diffpy/pdfgui/gui/insertrowsdialog.py | 11 +-
src/diffpy/pdfgui/gui/journalpanel.py | 23 +-
src/diffpy/pdfgui/gui/main.py | 5 +
src/diffpy/pdfgui/gui/mainframe.py | 849 +++++++++++-------
src/diffpy/pdfgui/gui/outputpanel.py | 16 +-
src/diffpy/pdfgui/gui/paneltest.py | 24 +-
src/diffpy/pdfgui/gui/parameterspanel.py | 165 ++--
src/diffpy/pdfgui/gui/pdfguiglobals.py | 18 +-
src/diffpy/pdfgui/gui/pdfpanel.py | 10 +-
src/diffpy/pdfgui/gui/phaseconfigurepanel.py | 344 ++++---
.../pdfgui/gui/phaseconstraintspanel.py | 288 ++++--
src/diffpy/pdfgui/gui/phasenotebookpanel.py | 42 +-
src/diffpy/pdfgui/gui/phasepanelutils.py | 141 +--
src/diffpy/pdfgui/gui/phaseresultspanel.py | 111 ++-
src/diffpy/pdfgui/gui/plotpanel.py | 83 +-
src/diffpy/pdfgui/gui/preferencespanel.py | 62 +-
src/diffpy/pdfgui/gui/resultspanel.py | 30 +-
src/diffpy/pdfgui/gui/rseriespanel.py | 73 +-
src/diffpy/pdfgui/gui/sgconstraindialog.py | 51 +-
src/diffpy/pdfgui/gui/sgstructuredialog.py | 69 +-
src/diffpy/pdfgui/gui/supercelldialog.py | 12 +-
.../pdfgui/gui/temperatureseriespanel.py | 117 ++-
src/diffpy/pdfgui/gui/tooltips.py | 244 +++--
src/diffpy/pdfgui/gui/welcomepanel.py | 11 +-
.../gui/wxextensions/autowidthlabelsgrid.py | 19 +-
.../pdfgui/gui/wxextensions/listctrls.py | 66 +-
.../pdfgui/gui/wxextensions/paneldialog.py | 6 +-
.../pdfgui/gui/wxextensions/textctrlutils.py | 1 +
.../pdfgui/gui/wxextensions/validators.py | 8 +-
src/diffpy/pdfgui/gui/wxextensions/wx12.py | 19 +-
src/diffpy/pdfgui/tests/__init__.py | 31 +-
src/diffpy/pdfgui/tests/debug.py | 5 +-
src/diffpy/pdfgui/tests/run.py | 5 +-
src/diffpy/pdfgui/tests/rundeps.py | 3 +-
.../pdfgui/tests/showphasenotebookpanel.py | 10 +-
src/diffpy/pdfgui/tests/testaboutdialog.py | 17 +-
src/diffpy/pdfgui/tests/testcalculation.py | 43 +-
src/diffpy/pdfgui/tests/testconstraint.py | 40 +-
src/diffpy/pdfgui/tests/testdatasetpanels.py | 20 +-
.../pdfgui/tests/testdopingseriespanel.py | 10 +-
.../pdfgui/tests/testextendedplotframe.py | 24 +-
src/diffpy/pdfgui/tests/testfitdataset.py | 235 ++---
src/diffpy/pdfgui/tests/testfitstructure.py | 331 ++++---
.../pdfgui/tests/testinsertrowsdialog.py | 6 +-
src/diffpy/pdfgui/tests/testloadproject.py | 33 +-
src/diffpy/pdfgui/tests/testmainframe.py | 8 +-
src/diffpy/pdfgui/tests/testparameter.py | 9 +-
.../pdfgui/tests/testparameterspanel.py | 19 +-
src/diffpy/pdfgui/tests/testpdfdataset.py | 70 +-
src/diffpy/pdfgui/tests/testpdfguicontrol.py | 7 +-
src/diffpy/pdfgui/tests/testpdfstructure.py | 113 ++-
.../pdfgui/tests/testphaseconfigurepanel.py | 11 +-
.../pdfgui/tests/teststructureviewer.py | 59 +-
.../tests/testtemperatureseriespanel.py | 10 +-
src/diffpy/pdfgui/tests/testutils.py | 34 +-
src/diffpy/pdfgui/tui.py | 13 +-
src/diffpy/pdfgui/utils.py | 35 +-
src/diffpy/pdfgui/version.py | 24 +-
102 files changed, 4568 insertions(+), 3154 deletions(-)
diff --git a/conda-recipe/expandpdfguibase.py b/conda-recipe/expandpdfguibase.py
index 66ac9844..e97614d1 100644
--- a/conda-recipe/expandpdfguibase.py
+++ b/conda-recipe/expandpdfguibase.py
@@ -3,13 +3,13 @@
import sys
from pkg_resources import Requirement, resource_filename
-pkg = Requirement.parse('diffpy.pdfgui')
-PDFGUIPATH = resource_filename(pkg, '')
+pkg = Requirement.parse("diffpy.pdfgui")
+PDFGUIPATH = resource_filename(pkg, "")
assert PDFGUIPATH.lower().startswith(sys.prefix.lower())
-PDFGUIBASE = PDFGUIPATH[len(sys.prefix):].replace('\\', '/').strip('/')
+PDFGUIBASE = PDFGUIPATH[len(sys.prefix) :].replace("\\", "/").strip("/")
if __name__ == "__main__":
with open(sys.argv[1]) as fp:
content = fp.read()
- output = content.replace('@PDFGUIBASE@', PDFGUIBASE)
+ output = content.replace("@PDFGUIBASE@", PDFGUIBASE)
sys.stdout.write(output)
diff --git a/conda-recipe/run_test.py b/conda-recipe/run_test.py
index c8ded775..a2a69494 100644
--- a/conda-recipe/run_test.py
+++ b/conda-recipe/run_test.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
import diffpy.pdfgui.tests
+
assert diffpy.pdfgui.tests.testdeps().wasSuccessful()
diff --git a/setup.py b/setup.py
index 5c60ca72..713b4c31 100755
--- a/setup.py
+++ b/setup.py
@@ -15,27 +15,29 @@
# Use this version when git data are not available, like in git zip archive.
# Update when tagging a new release.
-FALLBACK_VERSION = '2.0.4'
+FALLBACK_VERSION = "2.0.4"
# determine if we run with Python 3.
-PY3 = (sys.version_info[0] == 3)
+PY3 = sys.version_info[0] == 3
# versioncfgfile holds version data for git commit hash and date.
# It must reside in the same directory as version.py.
MYDIR = os.path.dirname(os.path.abspath(__file__))
-versioncfgfile = os.path.join(MYDIR, 'src/diffpy/pdfgui/version.cfg')
-gitarchivecfgfile = os.path.join(MYDIR, '.gitarchive.cfg')
+versioncfgfile = os.path.join(MYDIR, "src/diffpy/pdfgui/version.cfg")
+gitarchivecfgfile = os.path.join(MYDIR, ".gitarchive.cfg")
+
def gitinfo():
from subprocess import Popen, PIPE
+
kw = dict(stdout=PIPE, cwd=MYDIR, universal_newlines=True)
- proc = Popen(['git', 'describe', '--tags', '--match=v[[:digit:]]*'], **kw)
+ proc = Popen(["git", "describe", "--tags", "--match=v[[:digit:]]*"], **kw)
desc = proc.stdout.read()
- proc = Popen(['git', 'log', '-1', '--format=%H %ct %ci'], **kw)
+ proc = Popen(["git", "log", "-1", "--format=%H %ct %ci"], **kw)
glog = proc.stdout.read()
rv = {}
- rv['version'] = '.post'.join(desc.strip().split('-')[:2]).lstrip('v')
- rv['commit'], rv['timestamp'], rv['date'] = glog.strip().split(None, 2)
+ rv["version"] = ".post".join(desc.strip().split("-")[:2]).lstrip("v")
+ rv["commit"], rv["timestamp"], rv["date"] = glog.strip().split(None, 2)
return rv
@@ -44,19 +46,19 @@ def getversioncfg():
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
- vd0 = dict(version=FALLBACK_VERSION, commit='', date='', timestamp=0)
+ vd0 = dict(version=FALLBACK_VERSION, commit="", date="", timestamp=0)
# first fetch data from gitarchivecfgfile, ignore if it is unexpanded
g = vd0.copy()
cp0 = RawConfigParser(vd0)
cp0.read(gitarchivecfgfile)
- if len(cp0.get('DEFAULT', 'commit')) > 20:
+ if len(cp0.get("DEFAULT", "commit")) > 20:
g = cp0.defaults()
- mx = re.search(r'\btag: v(\d[^,]*)', g.pop('refnames'))
+ mx = re.search(r"\btag: v(\d[^,]*)", g.pop("refnames"))
if mx:
- g['version'] = mx.group(1)
+ g["version"] = mx.group(1)
# then try to obtain version data from git.
- gitdir = os.path.join(MYDIR, '.git')
- if os.path.exists(gitdir) or 'GIT_DIR' in os.environ:
+ gitdir = os.path.join(MYDIR, ".git")
+ if os.path.exists(gitdir) or "GIT_DIR" in os.environ:
try:
g = gitinfo()
except OSError:
@@ -65,94 +67,97 @@ def getversioncfg():
cp = RawConfigParser()
cp.read(versioncfgfile)
d = cp.defaults()
- rewrite = not d or (g['commit'] and (
- g['version'] != d.get('version') or g['commit'] != d.get('commit')))
+ rewrite = not d or (
+ g["commit"]
+ and (g["version"] != d.get("version") or g["commit"] != d.get("commit"))
+ )
if rewrite:
- cp.set('DEFAULT', 'version', g['version'])
- cp.set('DEFAULT', 'commit', g['commit'])
- cp.set('DEFAULT', 'date', g['date'])
- cp.set('DEFAULT', 'timestamp', g['timestamp'])
- with open(versioncfgfile, 'w') as fp:
+ cp.set("DEFAULT", "version", g["version"])
+ cp.set("DEFAULT", "commit", g["commit"])
+ cp.set("DEFAULT", "date", g["date"])
+ cp.set("DEFAULT", "timestamp", g["timestamp"])
+ with open(versioncfgfile, "w") as fp:
cp.write(fp)
return cp
+
versiondata = getversioncfg()
def dirglob(d, *patterns):
from glob import glob
+
rv = []
for p in patterns:
rv += glob(os.path.join(d, p))
return rv
-with open(os.path.join(MYDIR, 'README.rst')) as fp:
+with open(os.path.join(MYDIR, "README.rst")) as fp:
long_description = fp.read()
# define distribution
setup_args = dict(
- name = 'diffpy.pdfgui',
- version='3.0.5',
- packages = find_packages(os.path.join(MYDIR, 'src')),
- package_dir = {'' : 'src'},
- include_package_data = True,
- test_suite = 'diffpy.pdfgui.tests',
- entry_points = {
- 'gui_scripts': [
- 'pdfgui=diffpy.pdfgui.applications.pdfgui:main',
+ name="diffpy.pdfgui",
+ version="3.0.5",
+ packages=find_packages(os.path.join(MYDIR, "src")),
+ package_dir={"": "src"},
+ include_package_data=True,
+ test_suite="diffpy.pdfgui.tests",
+ entry_points={
+ "gui_scripts": [
+ "pdfgui=diffpy.pdfgui.applications.pdfgui:main",
],
},
- data_files = [
- ('icons', dirglob('icons', '*.png', '*.ico')),
- ('doc', dirglob('doc', '*.pdf')),
- ('doc/manual', dirglob('doc/manual', '*.html', '*.pdf')),
- ('doc/manual/images', dirglob('doc/manual/images', '*.png')),
- ('doc/tutorial', dirglob('doc/tutorial', '*')),
+ data_files=[
+ ("icons", dirglob("icons", "*.png", "*.ico")),
+ ("doc", dirglob("doc", "*.pdf")),
+ ("doc/manual", dirglob("doc/manual", "*.html", "*.pdf")),
+ ("doc/manual/images", dirglob("doc/manual/images", "*.png")),
+ ("doc/tutorial", dirglob("doc/tutorial", "*")),
],
# manual and tutorial files should not be zipped
- zip_safe = False,
- install_requires = [
- 'six',
- 'diffpy.structure>=3',
- 'diffpy.pdffit2',
- 'diffpy.utils',
+ zip_safe=False,
+ install_requires=[
+ "six",
+ "diffpy.structure>=3",
+ "diffpy.pdffit2",
+ "diffpy.utils",
],
-
- author = 'Simon J.L. Billinge',
- author_email = 'sb2896@columbia.edu',
- maintainer = 'Pavol Juhas',
- maintainer_email = 'pavol.juhas@gmail.com',
- url = 'https://github.com/diffpy/diffpy.pdfgui',
- description = "GUI for PDF simulation and structure refinement.",
- long_description = long_description,
- long_description_content_type = 'text/x-rst',
- license = 'BSD',
- keywords = 'PDF structure refinement GUI',
- classifiers = [
+ author="Simon J.L. Billinge",
+ author_email="sb2896@columbia.edu",
+ maintainer="Pavol Juhas",
+ maintainer_email="pavol.juhas@gmail.com",
+ url="https://github.com/diffpy/diffpy.pdfgui",
+ description="GUI for PDF simulation and structure refinement.",
+ long_description=long_description,
+ long_description_content_type="text/x-rst",
+ license="BSD",
+ keywords="PDF structure refinement GUI",
+ classifiers=[
# List of possible values at
# http://pypi.python.org/pypi?:action=list_classifiers
- 'Development Status :: 5 - Production/Stable',
- 'Environment :: MacOS X',
- 'Environment :: Win32 (MS Windows)',
- 'Environment :: X11 Applications',
- 'Intended Audience :: Science/Research',
- 'License :: OSI Approved :: BSD License',
- 'Operating System :: MacOS',
- 'Operating System :: Microsoft :: Windows',
- 'Operating System :: POSIX',
- 'Programming Language :: Python :: 2.7',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
- 'Programming Language :: Python :: 3.9',
- 'Programming Language :: Python :: 3.10',
- 'Programming Language :: Python :: 3.10',
- 'Topic :: Scientific/Engineering :: Chemistry',
- 'Topic :: Scientific/Engineering :: Physics',
+ "Development Status :: 5 - Production/Stable",
+ "Environment :: MacOS X",
+ "Environment :: Win32 (MS Windows)",
+ "Environment :: X11 Applications",
+ "Intended Audience :: Science/Research",
+ "License :: OSI Approved :: BSD License",
+ "Operating System :: MacOS",
+ "Operating System :: Microsoft :: Windows",
+ "Operating System :: POSIX",
+ "Programming Language :: Python :: 2.7",
+ "Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: 3.8",
+ "Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.10",
+ "Topic :: Scientific/Engineering :: Chemistry",
+ "Topic :: Scientific/Engineering :: Physics",
],
)
-if __name__ == '__main__':
+if __name__ == "__main__":
setup(**setup_args)
# End of file
diff --git a/src/diffpy/__init__.py b/src/diffpy/__init__.py
index fd655e96..50128bcc 100644
--- a/src/diffpy/__init__.py
+++ b/src/diffpy/__init__.py
@@ -20,6 +20,7 @@
from pkgutil import extend_path
+
__path__ = extend_path(__path__, __name__)
diff --git a/src/diffpy/pdfgui/__init__.py b/src/diffpy/pdfgui/__init__.py
index 1c95e37f..c12002ca 100644
--- a/src/diffpy/pdfgui/__init__.py
+++ b/src/diffpy/pdfgui/__init__.py
@@ -13,9 +13,9 @@
#
##############################################################################
-'''Constants:
+"""Constants:
__version__ -- full version of this PDFgui release
-'''
+"""
from diffpy.pdfgui.version import __version__
diff --git a/src/diffpy/pdfgui/applications/pdfgui.py b/src/diffpy/pdfgui/applications/pdfgui.py
index 73f53967..b6bace7c 100755
--- a/src/diffpy/pdfgui/applications/pdfgui.py
+++ b/src/diffpy/pdfgui/applications/pdfgui.py
@@ -40,8 +40,7 @@
def usage():
- """Show usage info.
- """
+ """Show usage info."""
myname = os.path.basename(sys.argv[0])
msg = __doc__.replace("pdfgui", myname)
print(msg)
@@ -50,12 +49,13 @@ def usage():
def version():
from diffpy.pdfgui import __version__
+
print("PDFgui", __version__)
return
def processArguments(argv1):
- '''Process command line arguments and store results in pdfguiglobals.
+ """Process command line arguments and store results in pdfguiglobals.
This method updates cmdopts, cmdargs and dbopts attributes in the
pdfguiglobals module.
@@ -66,13 +66,13 @@ def processArguments(argv1):
Raises GetoptError for invalid options.
Raises ValueError for more than one project file arguments or
when project is not a valid file.
- '''
+ """
from diffpy.pdfgui.gui import pdfguiglobals
+
dbopts = pdfguiglobals.dbopts
- dboptions = [('db-' + o[0]) for o in dbopts.alldebugoptions]
+ dboptions = [("db-" + o[0]) for o in dbopts.alldebugoptions]
# default parameters
- opts, args = getopt.gnu_getopt(sys.argv[1:], "hV",
- ["help", "version"] + dboptions)
+ opts, args = getopt.gnu_getopt(sys.argv[1:], "hV", ["help", "version"] + dboptions)
# process options
proceed = True
for o, a in opts:
@@ -82,13 +82,14 @@ def processArguments(argv1):
elif o in ("-V", "--version"):
version()
proceed = False
- elif o.startswith('--') and o[2:] in dboptions:
+ elif o.startswith("--") and o[2:] in dboptions:
# strip "--db-"
dbo = o[5:]
setattr(dbopts, dbo, True)
pdfguiglobals.cmdopts = opts
# bail-out here if options contain --help or --version
- if not proceed: return False
+ if not proceed:
+ return False
# otherwise continue checking arguments
if len(args) == 1 and not os.path.isfile(args[0]):
emsg = "Project file %s does not exist." % args[0]
@@ -102,8 +103,7 @@ def processArguments(argv1):
def main():
- '''Main entry point to PDFgui.
- '''
+ """Main entry point to PDFgui."""
# process arguments
proceed = False
try:
@@ -112,12 +112,15 @@ def main():
print(err, file=sys.stderr)
sys.exit(1)
# bail out when no gui is needed
- if not proceed: sys.exit()
+ if not proceed:
+ sys.exit()
# initialize gui
import diffpy.pdfgui.gui.main as guimain
+
# Catch control errors, that may happen during project
# loading, before the GUI gets running
from diffpy.pdfgui.control.controlerrors import ControlError
+
try:
guimain.main()
except ControlError as err:
diff --git a/src/diffpy/pdfgui/control/calculation.py b/src/diffpy/pdfgui/control/calculation.py
index 4417be2b..0bd6d6c9 100644
--- a/src/diffpy/pdfgui/control/calculation.py
+++ b/src/diffpy/pdfgui/control/calculation.py
@@ -62,7 +62,7 @@ def __init__(self, name):
self.setRGrid(rmin=0.1, rstep=0.01, rmax=10.0)
self.rcalc = []
self.Gcalc = []
- self.stype = 'X'
+ self.stype = "X"
# user must specify qmax to get termination ripples
self.qmax = 0.0
self.qdamp = 0.001
@@ -78,7 +78,6 @@ def _getStrId(self):
"""
return "c_" + self.name
-
def setRGrid(self, rmin=None, rstep=None, rmax=None):
"""Change specified r-grid parameters (rmin, rstep, rmax).
Adjust rmax for integer number of steps.
@@ -90,9 +89,12 @@ def setRGrid(self, rmin=None, rstep=None, rmax=None):
No return value.
Raise ControlValueError for invalid range specification.
"""
- if rmin is None: rmin = self.rmin
- if rstep is None: rstep = self.rstep
- if rmax is None: rmax = self.rmax
+ if rmin is None:
+ rmin = self.rmin
+ if rstep is None:
+ rstep = self.rstep
+ if rmax is None:
+ rmax = self.rmax
rstep = float(rstep)
# check if arguments are valid
if not rmin > 0:
@@ -105,22 +107,26 @@ def setRGrid(self, rmin=None, rstep=None, rmax=None):
emsg = "Invalid value of rstep, rstep must be positive."
raise ControlValueError(emsg)
# find number of r bins
- nbins = int( math.ceil( (rmax - rmin)/rstep ) )
+ nbins = int(math.ceil((rmax - rmin) / rstep))
# check for overshot due to round-off
epsilonr = 1.0e-8 * rstep
- deltarmax = abs(rmin + (nbins - 1)*rstep - rmax)
+ deltarmax = abs(rmin + (nbins - 1) * rstep - rmax)
if nbins > 1 and deltarmax < epsilonr:
nbins -= 1
# All went well, let us go ahead and set the attributes.
self.rmin = rmin
self.rstep = rstep
- self.rmax = rmin + nbins*rstep
+ self.rmax = rmin + nbins * rstep
self.rlen = nbins + 1
return
def start(self):
"""entry function for calculation"""
- from diffpy.pdfgui.control.fitting import getEngineExceptions,handleEngineException
+ from diffpy.pdfgui.control.fitting import (
+ getEngineExceptions,
+ handleEngineException,
+ )
+
try:
self.calculate()
except getEngineExceptions() as error:
@@ -135,8 +141,7 @@ def start(self):
return
def calculate(self):
- """do the real calculation
- """
+ """do the real calculation"""
# clean up old results
self.rcalc = []
self.Gcalc = []
@@ -148,19 +153,19 @@ def calculate(self):
# make sure parameters are initialized
self.owner.updateParameters()
from diffpy.pdffit2 import PdfFit
+
server = PdfFit()
# structure needs to be read before dataset allocation
for struc in self.owner.strucs:
- server.read_struct_string(struc.writeStr('pdffit'))
- for key,var in struc.constraints.items():
+ server.read_struct_string(struc.writeStr("pdffit"))
+ for key, var in struc.constraints.items():
server.constrain(key, var.formula)
# set up dataset
- server.alloc(self.stype, self.qmax, self.qdamp,
- self.rmin, self.rmax, self.rlen)
- server.setvar('qbroad', self.qbroad)
- server.setvar('dscale', self.dscale)
+ server.alloc(self.stype, self.qmax, self.qdamp, self.rmin, self.rmax, self.rlen)
+ server.setvar("qbroad", self.qbroad)
+ server.setvar("dscale", self.dscale)
# phase related variables
# pair selection applies to current dataset,
@@ -168,13 +173,13 @@ def calculate(self):
for phaseidx0, struc in enumerate(self.owner.strucs):
phaseidx1 = phaseidx0 + 1
server.setphase(phaseidx1)
- server.setvar('pscale', struc.getvar('pscale'))
- server.setvar('spdiameter', struc.getvar('spdiameter'))
+ server.setvar("pscale", struc.getvar("pscale"))
+ server.setvar("spdiameter", struc.getvar("spdiameter"))
struc.applyPairSelection(server, phaseidx1)
# set up parameters
for index, par in self.owner.parameters.items():
- server.setpar(index, par.initialValue()) # info[0] = init value
+ server.setpar(index, par.initialValue()) # info[0] = init value
# fix if fixed. Note: all parameters are free after server.reset().
if par.fixed:
server.fixpar(index)
@@ -194,7 +199,7 @@ def write(self, filename):
No return value.
"""
txt = self.writeStr()
- f = open( filename, 'w' )
+ f = open(filename, "w")
f.write(txt)
f.close()
return
@@ -206,39 +211,43 @@ def writeStr(self):
"""
import time
from getpass import getuser
+
lines = []
# write metadata
- lines.extend([
- 'History written: ' + time.ctime(),
- 'produced by ' + getuser(),
- '##### PDFgui calculation' ])
+ lines.extend(
+ [
+ "History written: " + time.ctime(),
+ "produced by " + getuser(),
+ "##### PDFgui calculation",
+ ]
+ )
# stype
- if self.stype == 'X':
- lines.append('stype=X x-ray scattering')
- elif self.stype == 'N':
- lines.append('stype=N neutron scattering')
+ if self.stype == "X":
+ lines.append("stype=X x-ray scattering")
+ elif self.stype == "N":
+ lines.append("stype=N neutron scattering")
# dscale
if self.dscale:
- lines.append('dscale=%g' % self.dscale)
+ lines.append("dscale=%g" % self.dscale)
# qmax
if self.qmax == 0:
- qmax_line = 'qmax=0 correction not applied'
+ qmax_line = "qmax=0 correction not applied"
else:
- qmax_line = 'qmax=%.2f' % self.qmax
+ qmax_line = "qmax=%.2f" % self.qmax
lines.append(qmax_line)
# qdamp
if isinstance(self.qdamp, float):
- lines.append('qdamp=%g' % self.qdamp)
+ lines.append("qdamp=%g" % self.qdamp)
# qbroad
if self.qbroad:
- lines.append('qbroad=%g' % self.qbroad)
+ lines.append("qbroad=%g" % self.qbroad)
# write data:
- lines.append('##### start data')
- lines.append('#L r(A) G(r)')
+ lines.append("##### start data")
+ lines.append("#L r(A) G(r)")
for i in range(len(self.rcalc)):
- lines.append( '%g %g' % (self.rcalc[i], self.Gcalc[i]) )
+ lines.append("%g %g" % (self.rcalc[i], self.Gcalc[i]))
# lines are ready here
- datastring = '\n'.join(lines) + '\n'
+ datastring = "\n".join(lines) + "\n"
return datastring
def load(self, z, subpath):
@@ -249,19 +258,19 @@ def load(self, z, subpath):
returns a tree of internal hierachy
"""
- config = pickle_loads(z.read(subpath + 'config'))
- self.rmin = config['rmin']
- self.rstep = config['rstep']
- self.rmax = config['rmax']
- self.rlen = config['rlen']
- self.rcalc = config['rcalc']
- self.Gcalc = config['Gcalc']
- self.stype = config['stype']
- self.qmax = config['qmax']
- self.qdamp = config.get('qdamp', config.get('qsig'))
- self.qbroad = config.get('qbroad', config.get('qalp', 0.0))
- self.spdiameter = config.get('spdiameter')
- self.dscale = config['dscale']
+ config = pickle_loads(z.read(subpath + "config"))
+ self.rmin = config["rmin"]
+ self.rstep = config["rstep"]
+ self.rmax = config["rmax"]
+ self.rlen = config["rlen"]
+ self.rcalc = config["rcalc"]
+ self.Gcalc = config["Gcalc"]
+ self.stype = config["stype"]
+ self.qmax = config["qmax"]
+ self.qdamp = config.get("qdamp", config.get("qsig"))
+ self.qbroad = config.get("qbroad", config.get("qalp", 0.0))
+ self.spdiameter = config.get("spdiameter")
+ self.dscale = config["dscale"]
return
def save(self, z, subpath):
@@ -271,19 +280,19 @@ def save(self, z, subpath):
subpath -- path to its own storage within project file
"""
config = {
- 'rmin' : self.rmin,
- 'rstep' : self.rstep,
- 'rmax' : self.rmax,
- 'rlen' : self.rlen,
- 'rcalc' : self.rcalc,
- 'Gcalc' : self.Gcalc,
- 'stype' : self.stype,
- 'qmax' : self.qmax,
- 'qdamp' : self.qdamp,
- 'qbroad' : self.qbroad,
- 'dscale' : self.dscale,
+ "rmin": self.rmin,
+ "rstep": self.rstep,
+ "rmax": self.rmax,
+ "rlen": self.rlen,
+ "rcalc": self.rcalc,
+ "Gcalc": self.Gcalc,
+ "stype": self.stype,
+ "qmax": self.qmax,
+ "qdamp": self.qdamp,
+ "qbroad": self.qbroad,
+ "dscale": self.dscale,
}
- z.writestr(subpath + 'config', safeCPickleDumps(config))
+ z.writestr(subpath + "config", safeCPickleDumps(config))
return
def copy(self, other=None):
@@ -298,10 +307,20 @@ def copy(self, other=None):
# rcalc and Gcalc may be assigned, they get replaced by new lists
# after every calculation
- assign_attributes = ( 'rmin', 'rstep', 'rmax', 'rlen',
- 'rcalc', 'Gcalc', 'stype', 'qmax', 'qdamp',
- 'qbroad', 'dscale', )
- copy_attributes = ( )
+ assign_attributes = (
+ "rmin",
+ "rstep",
+ "rmax",
+ "rlen",
+ "rcalc",
+ "Gcalc",
+ "stype",
+ "qmax",
+ "qdamp",
+ "qbroad",
+ "dscale",
+ )
+ copy_attributes = ()
for a in assign_attributes:
setattr(other, a, getattr(self, a))
for a in copy_attributes:
@@ -313,14 +332,18 @@ def getYNames(self):
returns a name str list
"""
- return ['Gcalc',]
+ return [
+ "Gcalc",
+ ]
def getXNames(self):
"""get names of data item which can be plotted as x
returns a name str list
"""
- return ['r', ]
+ return [
+ "r",
+ ]
def getData(self, dataname, step=None):
"""get Calculation data member
@@ -330,14 +353,13 @@ def getData(self, dataname, step=None):
returns data object, be it a single number, a list, or a list of list
"""
- if dataname not in ['rcalc', 'Gcalc']:
+ if dataname not in ["rcalc", "Gcalc"]:
emsg = "%s is not valid dataname" % dataname
raise ControlKeyError(emsg)
return self.__dict__[dataname]
def getMetaDataNames(self):
- """return all applicable meta data names
- """
+ """return all applicable meta data names"""
# FIXME: Currently we haven't thought about this
return []
@@ -349,10 +371,11 @@ def getMetaData(self, name):
"""
return None
+
# End of class Calculation
# simple test code
if __name__ == "__main__":
- Calculation('name')
+ Calculation("name")
# End of file
diff --git a/src/diffpy/pdfgui/control/constraint.py b/src/diffpy/pdfgui/control/constraint.py
index f1cee832..1ba0487f 100644
--- a/src/diffpy/pdfgui/control/constraint.py
+++ b/src/diffpy/pdfgui/control/constraint.py
@@ -22,6 +22,7 @@
from diffpy.pdfgui.control.controlerrors import ControlSyntaxError
+
class Constraint:
"""Constraint --> storage and check of a single constraint equation
@@ -47,9 +48,9 @@ def __init__(self, formula, value=None):
"""
# initialize private members firsts
self.__lhs = None
- self.parguess = { }
+ self.parguess = {}
# initialize formula member avoid __setattr__
- self.__dict__['formula'] = 'None'
+ self.__dict__["formula"] = "None"
# formula should be assigned as a last one
self.formula = formula
if value is not None:
@@ -73,8 +74,8 @@ def lambdaFormula(self):
returns lambda function
"""
- expr = re.sub(r'@(\d*)', r'p[\1]', self.formula)
- f = eval('lambda p:' + expr, vars(math))
+ expr = re.sub(r"@(\d*)", r"p[\1]", self.formula)
+ f = eval("lambda p:" + expr, vars(math))
return f
def guess(self, value):
@@ -97,29 +98,28 @@ def guess(self, value):
# check if fncp is linear with eps precision
try:
eps = 1.0e-8
- lo, hi = 1.0 - eps , 1.0 + eps
- k, = self.parguess.keys()
- y = [ fncp({k : 0.25}), fncp({k : 0.5}), fncp({k : 0.75}) ]
- dy = [ y[1] - y[0], y[2] - y[1] ]
- ady = [ abs(z) for z in dy ]
- if lo*ady[0] <= ady[1] <= hi*ady[0] and dy[0]!=0.0:
- a = 4*dy[0]
- b = y[1] - 0.5*a
- self.parguess[k] = (value-b)/a
+ lo, hi = 1.0 - eps, 1.0 + eps
+ (k,) = self.parguess.keys()
+ y = [fncp({k: 0.25}), fncp({k: 0.5}), fncp({k: 0.75})]
+ dy = [y[1] - y[0], y[2] - y[1]]
+ ady = [abs(z) for z in dy]
+ if lo * ady[0] <= ady[1] <= hi * ady[0] and dy[0] != 0.0:
+ a = 4 * dy[0]
+ b = y[1] - 0.5 * a
+ self.parguess[k] = (value - b) / a
except (ValueError, ZeroDivisionError):
pass
return dict(self.parguess)
def __setattr__(self, name, value):
- """check math and update parguess when formula is assigned
- """
+ """check math and update parguess when formula is assigned"""
if name != "formula":
self.__dict__[name] = value
return
# here we are assigning to formula
# first we need to check it it is valid
newformula = value
- pars = re.findall(r'@\d+', newformula)
+ pars = re.findall(r"@\d+", newformula)
# require at least one parameter in the formula
if len(pars) == 0:
message = "No parameter in formula '%s'" % newformula
@@ -127,25 +127,26 @@ def __setattr__(self, name, value):
try:
# this raises ControlSyntaxError if newformula is invalid
# define fncx in math module namespace
- fncx = eval('lambda x:' +
- re.sub(r'@\d+', 'x', newformula), vars(math))
+ fncx = eval("lambda x:" + re.sub(r"@\d+", "x", newformula), vars(math))
# check if fncx(0.25) is float
fncx(0.25) + 0.0
except (ValueError, SyntaxError, TypeError, NameError):
message = "invalid constraint formula '%s'" % newformula
raise ControlSyntaxError(message)
# few more checks of the formula:
- if newformula.find('**') != -1:
- emsg = ("invalid constraint formula '{}', "
- "operator '**' not supported.").format(newformula)
+ if newformula.find("**") != -1:
+ emsg = (
+ "invalid constraint formula '{}', " "operator '**' not supported."
+ ).format(newformula)
raise ControlSyntaxError(emsg)
# checks checked
- self.__dict__['formula'] = newformula
- self.parguess = dict.fromkeys([ int(p[1:]) for p in pars ])
+ self.__dict__["formula"] = newformula
+ self.parguess = dict.fromkeys([int(p[1:]) for p in pars])
if self.__lhs is not None:
self.guess(self.__lhs)
return
+
# End of class Constraint
# End of file
diff --git a/src/diffpy/pdfgui/control/controlerrors.py b/src/diffpy/pdfgui/control/controlerrors.py
index 12ec2374..3142ac17 100644
--- a/src/diffpy/pdfgui/control/controlerrors.py
+++ b/src/diffpy/pdfgui/control/controlerrors.py
@@ -13,8 +13,10 @@
#
##############################################################################
+
class ControlError(Exception):
"""Basic PDFGuiControl exception class"""
+
def __init__(self, info):
"""initialize
@@ -29,52 +31,62 @@ def __str__(self):
class ControlConfigError(ControlError):
"""PDFGuiControl exception class -- object config is invalid"""
+
pass
class ControlFileError(ControlError):
"""PDFGuiControl exception class -- object config is invalid"""
+
pass
class ControlKeyError(ControlError):
"""PDFGuiControl exception class -- requested object can't be found"""
+
pass
class ControlValueError(ControlError):
"""PDFGuiControl exception class -- Invalid value"""
+
pass
class ControlTypeError(ControlError):
"""PDFGuiControl exception class -- Type mismatch"""
+
pass
class ControlStatusError(ControlError):
"""PDFGuiControl exception class -- Fitting status doesn't match"""
+
pass
class ControlRuntimeError(ControlError):
"""PDFGuiControl exception class -- various irrecoverable runtime error"""
+
pass
class ControlIndexError(ControlError):
- """PDFGuiControl exception class -- index out of bound """
+ """PDFGuiControl exception class -- index out of bound"""
+
pass
class ControlSyntaxError(ControlError):
- """PDFGuiControl exception class -- invalid syntax of constraint formula
- """
+ """PDFGuiControl exception class -- invalid syntax of constraint formula"""
+
pass
+
class TempControlSelectError(ControlError):
- """Temporary define this error to identify the select-control error in python3
- """
+ """Temporary define this error to identify the select-control error in python3"""
+
pass
+
# End of file
diff --git a/src/diffpy/pdfgui/control/fitdataset.py b/src/diffpy/pdfgui/control/fitdataset.py
index ad85c37d..2e07edea 100644
--- a/src/diffpy/pdfgui/control/fitdataset.py
+++ b/src/diffpy/pdfgui/control/fitdataset.py
@@ -23,6 +23,7 @@
from diffpy.pdfgui.control.parameter import Parameter
from diffpy.pdfgui.control.controlerrors import ControlStatusError
+
class FitDataSet(PDFDataSet):
"""FitDataSet stores experimental and calculated PDF data and related
fitting parameters. Inherited from PDFDataSet.
@@ -58,9 +59,16 @@ class FitDataSet(PDFDataSet):
persistentItems -- list of attributes saved in project file
"""
- persistentItems = [ 'rcalc', 'Gcalc', 'dGcalc',
- 'fitrmin', 'fitrmax', 'fitrstep',
- 'initial', 'refined' ]
+ persistentItems = [
+ "rcalc",
+ "Gcalc",
+ "dGcalc",
+ "fitrmin",
+ "fitrmax",
+ "fitrstep",
+ "initial",
+ "refined",
+ ]
def __init__(self, name):
"""Initialize FitDataSet.
@@ -74,8 +82,7 @@ def __init__(self, name):
return
def __setattr__(self, name, value):
- """Assign refinable variables to self.initial.
- """
+ """Assign refinable variables to self.initial."""
if name in PDFDataSet.refinableVars:
self.initial[name] = value
else:
@@ -105,8 +112,9 @@ def getYNames(self):
returns list of strings
"""
- ynames = [ 'Gobs', 'Gcalc', 'Gdiff', 'Gtrunc', 'dGcalc', 'crw' ] + \
- list(self.constraints.keys())
+ ynames = ["Gobs", "Gcalc", "Gdiff", "Gtrunc", "dGcalc", "crw"] + list(
+ self.constraints.keys()
+ )
return ynames
def getXNames(self):
@@ -114,9 +122,11 @@ def getXNames(self):
returns list of strings
"""
- return ['r',]
+ return [
+ "r",
+ ]
- def getData(self, name, step = -1 ):
+ def getData(self, name, step=-1):
"""get self's data member
name -- data item name
@@ -132,25 +142,24 @@ def getData(self, name, step = -1 ):
# data in below
if name in self.metadata:
return self.metadata[name]
- elif name in ( 'Gobs', 'Gcalc', 'Gtrunc', 'Gdiff', 'crw', 'robs', 'rcalc'):
+ elif name in ("Gobs", "Gcalc", "Gtrunc", "Gdiff", "crw", "robs", "rcalc"):
d = getattr(self, name)
# for Gtrunc and rcalc, we can use Gobs and robs instead when they
# are not ready.
- if not d :
- if name == 'Gtrunc':
- return getattr(self, 'Gobs')
- if name == 'rcalc':
- return getattr(self, 'robs')
+ if not d:
+ if name == "Gtrunc":
+ return getattr(self, "Gobs")
+ if name == "rcalc":
+ return getattr(self, "robs")
return d
# otherwise fitting's repository is preferred
- return self.owner._getData(self, name, step)
+ return self.owner._getData(self, name, step)
def clear(self):
- """Reset all data members to initial empty values.
- """
+ """Reset all data members to initial empty values."""
PDFDataSet.clear(self)
self._rcalc_changed = True
self._rcalc = []
@@ -167,8 +176,7 @@ def clear(self):
return
def clearRefined(self):
- """Clear all refinement results.
- """
+ """Clear all refinement results."""
self.Gcalc = []
self.dGcalc = []
self.crw = []
@@ -192,8 +200,7 @@ def obtainRefined(self, server, idataset):
return
def read(self, filename):
- """Same as readObs().
- """
+ """Same as readObs()."""
return self.readObs(filename)
def _updateRcalcRange(self):
@@ -221,8 +228,7 @@ def readObs(self, filename):
return self
def readStr(self, datastring):
- """Same as readObsStr().
- """
+ """Same as readObsStr()."""
return self.readObsStr(datastring)
def readObsStr(self, datastring):
@@ -254,7 +260,7 @@ def writeCalc(self, filename):
No return value.
"""
txt = self.writeCalcStr()
- f = open(filename, 'w')
+ f = open(filename, "w")
f.write(txt)
f.close()
return
@@ -275,44 +281,50 @@ def writeCalcStr(self):
raise ControlStatusError("Gcalc not available")
import time
from getpass import getuser
+
lines = []
# write metadata
- lines.extend([
- 'History written: ' + time.ctime(),
- 'produced by ' + getuser(),
- '##### PDFgui fit' ])
+ lines.extend(
+ [
+ "History written: " + time.ctime(),
+ "produced by " + getuser(),
+ "##### PDFgui fit",
+ ]
+ )
# stype
- if self.stype == 'X':
- lines.append('stype=X x-ray scattering')
- elif self.stype == 'N':
- lines.append('stype=N neutron scattering')
+ if self.stype == "X":
+ lines.append("stype=X x-ray scattering")
+ elif self.stype == "N":
+ lines.append("stype=N neutron scattering")
# qmax
if self.qmax:
- lines.append('qmax=%.2f' % self.qmax)
+ lines.append("qmax=%.2f" % self.qmax)
# qdamp
- lines.append('qdamp=%g' % self.refined['qdamp'])
+ lines.append("qdamp=%g" % self.refined["qdamp"])
# qbroad
- lines.append('qbroad=%g' % self.refined['qbroad'])
+ lines.append("qbroad=%g" % self.refined["qbroad"])
# dscale
- lines.append('dscale=%g' % self.refined['dscale'])
+ lines.append("dscale=%g" % self.refined["dscale"])
# fitrmin, fitrmax
if self.fitrmin is not None and self.fitrmax is not None:
- lines.append('fitrmin=%g' % self.fitrmin)
- lines.append('fitrmax=%g' % self.fitrmax)
+ lines.append("fitrmin=%g" % self.fitrmin)
+ lines.append("fitrmax=%g" % self.fitrmax)
# metadata
if len(self.metadata) > 0:
- lines.append('# metadata')
+ lines.append("# metadata")
for k, v in self.metadata.items():
- lines.append( "%s=%s" % (k,v) )
+ lines.append("%s=%s" % (k, v))
# write data:
- lines.append('##### start data')
- lines.append('#L r(A) G(r) d_r d_Gr Gdiff')
+ lines.append("##### start data")
+ lines.append("#L r(A) G(r) d_r d_Gr Gdiff")
# cache Gdiff here so it is not calculated many times
Gdiff = self.Gdiff
drcalc = 0.0
for i in range(len(self.rcalc)):
- lines.append( '%g %g %.1f %g %g' % (self.rcalc[i],
- self.Gcalc[i], drcalc, self.dGcalc[i], Gdiff[i]) )
+ lines.append(
+ "%g %g %.1f %g %g"
+ % (self.rcalc[i], self.Gcalc[i], drcalc, self.dGcalc[i], Gdiff[i])
+ )
# lines are ready here
datastring = "\n".join(lines) + "\n"
return datastring
@@ -394,7 +406,7 @@ def applyParameters(self, parameters):
Dictionary may also have float-type values.
"""
# convert values to floats
- parvalues = { }
+ parvalues = {}
for pidx, par in parameters.items():
if isinstance(par, Parameter):
parvalues[pidx] = par.initialValue()
@@ -413,6 +425,7 @@ def changeParameterIndex(self, oldidx, newidx):
this fit.
"""
import re
+
for var in self.constraints:
formula = self.constraints[var].formula
pat = r"@%i\b" % oldidx
@@ -453,33 +466,36 @@ def load(self, z, subpath):
subpath -- path to its own storage within project file
"""
from diffpy.pdfgui.utils import asunicode, pickle_loads
+
self.clear()
- subs = subpath.split('/')
+ subs = subpath.split("/")
rootDict = z.fileTree[subs[0]][subs[1]][subs[2]][subs[3]]
# raw data
- obsdata = asunicode(z.read(subpath + 'obs'))
+ obsdata = asunicode(z.read(subpath + "obs"))
self.readObsStr(obsdata)
# data from calculation
- content = pickle_loads(z.read(subpath + 'calc'))
+ content = pickle_loads(z.read(subpath + "calc"))
for item in FitDataSet.persistentItems:
# skip items which are not in the project file
- if item not in content: continue
+ if item not in content:
+ continue
# update dictionaries so that old project files load fine
- if item == 'initial':
+ if item == "initial":
self.initial.update(content[item])
- elif item == 'refined':
+ elif item == "refined":
self.refined.update(content[item])
else:
setattr(self, item, content[item])
self._updateRcalcRange()
# constraints
- if 'constraints' in rootDict:
+ if "constraints" in rootDict:
from diffpy.pdfgui.control.pdfguicontrol import CtrlUnpickler
- self.constraints = CtrlUnpickler.loads(z.read(subpath+'constraints'))
+
+ self.constraints = CtrlUnpickler.loads(z.read(subpath + "constraints"))
# handle renamed variable from old project files
- translate = {'qsig' : 'qdamp', 'qalp' : 'qbroad'}
+ translate = {"qsig": "qdamp", "qalp": "qbroad"}
for old, new in translate.items():
if old in self.constraints:
self.constraints[new] = self.constraints.pop(old)
@@ -493,18 +509,19 @@ def save(self, z, subpath):
subpath -- path to its own storage within project file
"""
from diffpy.pdfgui.utils import safeCPickleDumps
+
# write raw data
- z.writestr(subpath + 'obs', self.writeObsStr())
+ z.writestr(subpath + "obs", self.writeObsStr())
content = {}
for item in FitDataSet.persistentItems:
content[item] = getattr(self, item, None)
spkl = safeCPickleDumps(content)
- z.writestr(subpath+'calc', spkl)
+ z.writestr(subpath + "calc", spkl)
# make a picklable dictionary of constraints
if self.constraints:
spkl = safeCPickleDumps(self.constraints)
- z.writestr(subpath + 'constraints', spkl)
+ z.writestr(subpath + "constraints", spkl)
return
# interface for data sampling
@@ -550,11 +567,12 @@ def setFitSamplingType(self, tp, value=None):
return
def getObsSampling(self):
- """Return the average r-step used in robs or zero when not defined.
- """
+ """Return the average r-step used in robs or zero when not defined."""
n = len(self.robs)
- if n > 1: rv = (self.robs[-1] - self.robs[0])/(n - 1.0)
- else: rv = 0.0
+ if n > 1:
+ rv = (self.robs[-1] - self.robs[0]) / (n - 1.0)
+ else:
+ rv = 0.0
return rv
def getNyquistSampling(self):
@@ -576,7 +594,8 @@ def _updateRcalcSampling(self):
No return value.
"""
- if not self._rcalc_changed: return
+ if not self._rcalc_changed:
+ return
frmin, frmax = self.fitrmin, self.fitrmax
frstep = float(self.fitrstep)
# new rcalc must cover the whole [fitrmin, fitrmax] interval
@@ -586,7 +605,7 @@ def _updateRcalcSampling(self):
rcalcfirst = robs_below[-1]
else:
rcalcfirst = self.robs[0]
- nrcalc = numpy.round(1.0*(frmax - rcalcfirst)/frstep)
+ nrcalc = numpy.round(1.0 * (frmax - rcalcfirst) / frstep)
if frmax - (rcalcfirst + nrcalc * frstep) > frstep * 1e-8:
nrcalc += 1
newrcalc = rcalcfirst + frstep * numpy.arange(nrcalc + 1)
@@ -617,8 +636,9 @@ def _set_fitrmin(self, value):
self._fitrmin = float(value)
return
- fitrmin = property(_get_fitrmin, _set_fitrmin, doc =
- "Lower boundary for simulated PDF curve.")
+ fitrmin = property(
+ _get_fitrmin, _set_fitrmin, doc="Lower boundary for simulated PDF curve."
+ )
# fitrmax
@@ -630,8 +650,9 @@ def _set_fitrmax(self, value):
self._fitrmax = float(value)
return
- fitrmax = property(_get_fitrmax, _set_fitrmax, doc =
- "Upper boundary for simulated PDF curve.")
+ fitrmax = property(
+ _get_fitrmax, _set_fitrmax, doc="Upper boundary for simulated PDF curve."
+ )
# fitrstep
@@ -643,8 +664,9 @@ def _set_fitrstep(self, value):
self._fitrstep = float(value)
return
- fitrstep = property(_get_fitrstep, _set_fitrstep, doc =
- "R-step used for simulated PDF curve.")
+ fitrstep = property(
+ _get_fitrstep, _set_fitrstep, doc="R-step used for simulated PDF curve."
+ )
# rcalc
@@ -656,9 +678,12 @@ def _set_rcalc(self, value):
self._rcalc = value
return
- rcalc = property(_get_rcalc, _set_rcalc, doc =
- """R-grid for refined data, read-only.
- Use fitrmin, fitrmax, fitrstep to change it""")
+ rcalc = property(
+ _get_rcalc,
+ _set_rcalc,
+ doc="""R-grid for refined data, read-only.
+ Use fitrmin, fitrmax, fitrstep to change it""",
+ )
# Gcalc
@@ -670,8 +695,7 @@ def _set_Gcalc(self, value):
self._Gcalc = value
return
- Gcalc = property(_get_Gcalc, _set_Gcalc, doc =
- "List of calculate G values.")
+ Gcalc = property(_get_Gcalc, _set_Gcalc, doc="List of calculate G values.")
# dGcalc
@@ -683,8 +707,9 @@ def _set_dGcalc(self, value):
self._dGcalc = value
return
- dGcalc = property(_get_dGcalc, _set_dGcalc, doc =
- "List of standard deviations of Gcalc.")
+ dGcalc = property(
+ _get_dGcalc, _set_dGcalc, doc="List of standard deviations of Gcalc."
+ )
# Gtrunc
@@ -699,8 +724,7 @@ def _set_Gtrunc(self, value):
self._Gtrunc = value
return
- Gtrunc = property(_get_Gtrunc, _set_Gtrunc, doc =
- "Gobs resampled to rcalc grid.")
+ Gtrunc = property(_get_Gtrunc, _set_Gtrunc, doc="Gobs resampled to rcalc grid.")
# dGtrunc
@@ -708,9 +732,13 @@ def _get_dGtrunc(self):
self._updateRcalcSampling()
if not self._dGtrunc:
# use sum to avoid index error for empty arrays
- newdGtrunc = grid_interpolation(self.robs, self.dGobs, self.rcalc,
- youtleft=sum(self.dGobs[:1]),
- youtright=sum(self.dGobs[-1:]))
+ newdGtrunc = grid_interpolation(
+ self.robs,
+ self.dGobs,
+ self.rcalc,
+ youtleft=sum(self.dGobs[:1]),
+ youtright=sum(self.dGobs[-1:]),
+ )
self._dGtrunc = list(newdGtrunc)
return self._dGtrunc
@@ -718,8 +746,7 @@ def _set_dGtrunc(self, value):
self._dGtrunc = value
return
- dGtrunc = property(_get_dGtrunc, _set_dGtrunc, doc =
- "dGobs resampled to rcalc grid.")
+ dGtrunc = property(_get_dGtrunc, _set_dGtrunc, doc="dGobs resampled to rcalc grid.")
# Gdiff
@@ -730,8 +757,9 @@ def _get_Gdiff(self):
rv = []
return rv
- Gdiff = property(_get_Gdiff, doc =
- "Difference between observed and calculated PDF on rcalc grid.")
+ Gdiff = property(
+ _get_Gdiff, doc="Difference between observed and calculated PDF on rcalc grid."
+ )
# crw
def _get_crw(self):
@@ -745,8 +773,7 @@ def _set_crw(self, value):
self._crw = value[:]
return
- crw = property(_get_crw, _set_crw, doc =
- "cumulative rw on rcalc grid")
+ crw = property(_get_crw, _set_crw, doc="cumulative rw on rcalc grid")
# End of Property Attributes
@@ -758,6 +785,7 @@ def _set_crw(self, value):
# helper functions
##############################################################################
+
def grid_interpolation(x0, y0, x1, youtleft=0.0, youtright=0.0):
"""Linear interpolation of x0, y0 values to a new grid x1.
@@ -787,8 +815,8 @@ def grid_interpolation(x0, y0, x1, youtleft=0.0, youtright=0.0):
dx0 = (x0[-1] - x0[0]) / (n0 - 1.0)
epsx = dx0 * 1e-8
# find covered values in x1
- m1, = numpy.where(numpy.logical_and(x0[0] - epsx < x1, x1 < x0[-1] + epsx))
- ilo0 = numpy.floor((x1[m1] - x0[0])/dx0)
+ (m1,) = numpy.where(numpy.logical_and(x0[0] - epsx < x1, x1 < x0[-1] + epsx))
+ ilo0 = numpy.floor((x1[m1] - x0[0]) / dx0)
ilo0 = numpy.array(ilo0, dtype=int)
# ilo0 may be out of bounds for x1 close to the edge
ilo0[ilo0 < 0] = 0
@@ -797,11 +825,12 @@ def grid_interpolation(x0, y0, x1, youtleft=0.0, youtright=0.0):
# make sure hi indices remain valid
w0hi = (x1[m1] - x0[ilo0]) / dx0
w0lo = 1.0 - w0hi
- y1[m1] = w0lo*y0[ilo0] + w0hi*y0[ihi0]
+ y1[m1] = w0lo * y0[ilo0] + w0hi * y0[ihi0]
return y1
+
# simple test code
if __name__ == "__main__":
- FitDataSet('name')
+ FitDataSet("name")
# End of file
diff --git a/src/diffpy/pdfgui/control/fitstructure.py b/src/diffpy/pdfgui/control/fitstructure.py
index 77012c8c..d38f2022 100644
--- a/src/diffpy/pdfgui/control/fitstructure.py
+++ b/src/diffpy/pdfgui/control/fitstructure.py
@@ -26,6 +26,7 @@
from diffpy.pdfgui.control.controlerrors import ControlTypeError, ControlValueError
from diffpy.structure import Atom
+
class FitStructure(PDFStructure):
"""FitStructure holds initial and refined structure and related fit
parameters. Inherited from PDFStructure.
@@ -72,11 +73,10 @@ def __init__(self, name, *args, **kwargs):
self.refined = None
self.constraints = {}
self.selected_pairs = "all-all"
- self.initial.pdffit['sgoffset'] = [0.0, 0.0, 0.0]
+ self.initial.pdffit["sgoffset"] = [0.0, 0.0, 0.0]
self.custom_spacegroup = None
return
-
def _update_custom_spacegroup(self, parser):
"""Helper method for read() and readStr(), which takes care
of setting custom_spacegroup after successful reading.
@@ -86,7 +86,7 @@ def _update_custom_spacegroup(self, parser):
No return value.
"""
self.custom_spacegroup = None
- self.initial.pdffit['sgoffset'] = [0.0, 0.0, 0.0]
+ self.initial.pdffit["sgoffset"] = [0.0, 0.0, 0.0]
if hasattr(parser, "spacegroup"):
sg = parser.spacegroup
# when sg.number is None or 0, we have a custom spacegroup
@@ -95,11 +95,10 @@ def _update_custom_spacegroup(self, parser):
sg.number = 0
self.custom_spacegroup = sg
# here sg.number is 0 or positive integer
- self.initial.pdffit['spcgr'] = sg.short_name
+ self.initial.pdffit["spcgr"] = sg.short_name
return
-
- def read(self, filename, format='auto'):
+ def read(self, filename, format="auto"):
"""Load structure from a file, raise ControlFileError for invalid
or unknown structure format. Overloads PDFStructure.read()
to handle custom_spacegroup attribute.
@@ -119,8 +118,7 @@ def read(self, filename, format='auto'):
self.anisotropy = True
return p
-
- def readStr(self, s, format='auto'):
+ def readStr(self, s, format="auto"):
"""Same as PDFStructure.readStr, but handle the
custom_spacegroup data.
@@ -135,7 +133,6 @@ def readStr(self, s, format='auto'):
self.anisotropy = True
return p
-
def __getattr__(self, name):
"""Map self.initial to self.
This is called only when normal attribute lookup fails.
@@ -155,8 +152,7 @@ def _getStrId(self):
return "p_" + self.name
def clearRefined(self):
- """Clear all refinement results.
- """
+ """Clear all refinement results."""
self.refined = None
return
@@ -169,7 +165,7 @@ def obtainRefined(self, server, iphase):
server.setphase(iphase)
if self.refined is None:
self.refined = PDFStructure(self.name)
- self.refined.readStr(server.save_struct_string(iphase), 'pdffit')
+ self.refined.readStr(server.save_struct_string(iphase), "pdffit")
return
def findParameters(self):
@@ -200,7 +196,7 @@ def applyParameters(self, parameters):
instance values. Values may also be float type.
"""
# convert values to floats
- parvalues = { }
+ parvalues = {}
for pidx, par in parameters.items():
if isinstance(par, Parameter):
parvalues[pidx] = par.initialValue()
@@ -236,10 +232,11 @@ def _popAtomConstraints(self):
"""
rv = {}
# atom variable pattern
- avpat = re.compile(r'^([xyz]|occ|u11|u22|u33|u12|u13|u23)\((\d+)\)')
+ avpat = re.compile(r"^([xyz]|occ|u11|u22|u33|u12|u13|u23)\((\d+)\)")
for var in list(self.constraints.keys()):
m = avpat.match(var)
- if not m: continue
+ if not m:
+ continue
barevar = m.group(1)
atomidx = int(m.group(2)) - 1
cnts = rv.setdefault(self.initial[atomidx], {})
@@ -254,7 +251,8 @@ def _restoreAtomConstraints(self, acd):
acd -- dictionary obtained from _popAtomConstraints()
"""
for i, a in enumerate(self.initial):
- if not a in acd: continue
+ if not a in acd:
+ continue
# there are some constraints for atom a
siteindex = i + 1
cnts = acd[a]
@@ -304,23 +302,29 @@ def expandSuperCell(self, mno):
the a, b, c axis
"""
# check argument
- if tuple(mno) == (1, 1, 1): return
+ if tuple(mno) == (1, 1, 1):
+ return
if min(mno) < 1:
raise ControlValueError("mno must contain 3 positive integers")
# back to business
acd = self._popAtomConstraints()
mnofloats = numpy.array(mno[:3], dtype=float)
- ijklist = [(i,j,k) for i in range(mno[0])
- for j in range(mno[1]) for k in range(mno[2])]
+ ijklist = [
+ (i, j, k)
+ for i in range(mno[0])
+ for j in range(mno[1])
+ for k in range(mno[2])
+ ]
# build a list of new atoms
newatoms = []
for a in self.initial:
for ijk in ijklist:
adup = Atom(a)
- adup.xyz = (a.xyz + ijk)/mnofloats
+ adup.xyz = (a.xyz + ijk) / mnofloats
newatoms.append(adup)
# does atom a have any constraint?
- if a not in acd: continue
+ if a not in acd:
+ continue
# add empty constraint dictionary for duplicate atom
acd[adup] = {}
for barevar, con in acd[a].items():
@@ -331,7 +335,7 @@ def expandSuperCell(self, mno):
formula += " + %i" % ijk[symidx]
if mno[symidx] > 1:
formula = "(%s)/%.1f" % (formula, mno[symidx])
- formula = re.sub(r'\((@\d+)\)', r'\1', formula)
+ formula = re.sub(r"\((@\d+)\)", r"\1", formula)
# keep other formulas intact and add constraint
# for barevar of the duplicate atom
acd[adup][barevar] = Constraint(formula)
@@ -344,16 +348,17 @@ def expandSuperCell(self, mno):
self._restoreAtomConstraints(acd)
# take care of lattice parameters
self.initial.lattice.setLatPar(
- a=mno[0]*self.initial.lattice.a,
- b=mno[1]*self.initial.lattice.b,
- c=mno[2]*self.initial.lattice.c )
+ a=mno[0] * self.initial.lattice.a,
+ b=mno[1] * self.initial.lattice.b,
+ c=mno[2] * self.initial.lattice.c,
+ )
# adjust lattice constraints if present
- latvars = ( "lat(1)", "lat(2)", "lat(3)" )
+ latvars = ("lat(1)", "lat(2)", "lat(3)")
for var, multiplier in zip(latvars, mno):
if var in self.constraints and multiplier > 1:
con = self.constraints[var]
formula = "%.0f*(%s)" % (multiplier, con.formula)
- formula = re.sub(r'\((@\d+)\)', r'\1', formula)
+ formula = re.sub(r"\((@\d+)\)", r"\1", formula)
con.formula = formula
return
@@ -365,8 +370,8 @@ def isSpaceGroupPossible(self, spacegroup):
Return bool.
"""
from diffpy.structure.symmetryutilities import isSpaceGroupLatPar
- return isSpaceGroupLatPar(spacegroup, *self.initial.lattice.abcABG())
+ return isSpaceGroupLatPar(spacegroup, *self.initial.lattice.abcABG())
def getSpaceGroupList(self):
"""Return a list of SpaceGroup instances sorted by International
@@ -375,6 +380,7 @@ def getSpaceGroupList(self):
"""
if not FitStructure.sorted_standard_space_groups:
import diffpy.structure.spacegroups as SG
+
existing_names = {}
unique_named_list = []
for sg in SG.SpaceGroupList:
@@ -383,7 +389,9 @@ def getSpaceGroupList(self):
existing_names[sg.short_name] = True
# sort by International Tables number, stay compatible with 2.3
n_sg = [(sg.number % 1000, sg) for sg in unique_named_list]
- n_sg = sorted(n_sg, key=lambda x: x[0]) #sort by the first element of tuple.
+ n_sg = sorted(
+ n_sg, key=lambda x: x[0]
+ ) # sort by the first element of tuple.
FitStructure.sorted_standard_space_groups = [sg for n, sg in n_sg]
sglist = list(FitStructure.sorted_standard_space_groups)
if self.custom_spacegroup:
@@ -399,9 +407,9 @@ def getSpaceGroup(self, sgname):
in getSpaceGroupList().
"""
import diffpy.structure.spacegroups as SG
+
# this should match the "CIF data" sgname
- sgmatch = [sg for sg in self.getSpaceGroupList()
- if sg.short_name == sgname]
+ sgmatch = [sg for sg in self.getSpaceGroupList() if sg.short_name == sgname]
# use standard lookup function when not matched by short_name
if not sgmatch:
sgmatch.append(SG.GetSpaceGroup(sgname))
@@ -411,7 +419,7 @@ def getSpaceGroup(self, sgname):
sgfound = sgmatch[0]
return sgfound
- def expandAsymmetricUnit(self, spacegroup, indices, sgoffset=[0,0,0]):
+ def expandAsymmetricUnit(self, spacegroup, indices, sgoffset=[0, 0, 0]):
"""Perform symmetry expansion for atoms at given indices.
Temperature factors may be corrected to reflect the symmetry.
All constraints for expanded atoms are erased with the exception
@@ -423,14 +431,16 @@ def expandAsymmetricUnit(self, spacegroup, indices, sgoffset=[0,0,0]):
sgoffset -- optional offset of space group origin [0,0,0]
"""
from diffpy.structure.symmetryutilities import ExpandAsymmetricUnit
+
acd = self._popAtomConstraints()
# get unique, reverse sorted indices
ruindices = sorted(set(indices), reverse=True)
coreatoms = [self.initial[i] for i in ruindices]
corepos = [a.xyz for a in coreatoms]
coreUijs = [a.U for a in coreatoms]
- eau = ExpandAsymmetricUnit(spacegroup, corepos, coreUijs,
- sgoffset=sgoffset, eps=self.symposeps)
+ eau = ExpandAsymmetricUnit(
+ spacegroup, corepos, coreUijs, sgoffset=sgoffset, eps=self.symposeps
+ )
# build a nested list of new atoms:
newatoms = []
for i in range(len(coreatoms)):
@@ -438,19 +448,20 @@ def expandAsymmetricUnit(self, spacegroup, indices, sgoffset=[0,0,0]):
caocc_con = None
if ca in acd and "occ" in acd[ca]:
caocc_con = acd[ca]["occ"]
- eca = [] # expanded core atom
+ eca = [] # expanded core atom
for j in range(eau.multiplicity[i]):
a = Atom(ca)
a.xyz = eau.expandedpos[i][j]
a.U = eau.expandedUijs[i][j]
eca.append(a)
- if caocc_con is None: continue
+ if caocc_con is None:
+ continue
# make a copy of occupancy constraint
- acd[a] = {"occ" : copy.copy(caocc_con)}
+ acd[a] = {"occ": copy.copy(caocc_con)}
newatoms.append(eca)
# insert new atoms where they belong
for i, atomlist in zip(ruindices, newatoms):
- self.initial[i:i+1] = atomlist
+ self.initial[i : i + 1] = atomlist
# remember this spacegroup as the last one used
self.initial.pdffit["spcgr"] = spacegroup.short_name
self.initial.pdffit["sgoffset"] = list(sgoffset)
@@ -458,8 +469,9 @@ def expandAsymmetricUnit(self, spacegroup, indices, sgoffset=[0,0,0]):
self._restoreAtomConstraints(acd)
return
- def applySymmetryConstraints(self, spacegroup, indices, posflag, Uijflag,
- sgoffset=[0,0,0]):
+ def applySymmetryConstraints(
+ self, spacegroup, indices, posflag, Uijflag, sgoffset=[0, 0, 0]
+ ):
"""Generate symmetry constraints for positions and thermal factors.
Both positions and thermal factors may get corrected to reflect
space group symmetry. Old positional and thermal constraints get
@@ -472,15 +484,17 @@ def applySymmetryConstraints(self, spacegroup, indices, posflag, Uijflag,
Uijflag -- required bool flag for Uij constrainment
sgoffset -- optional offset of space group origin [0,0,0]
"""
- if not posflag and not Uijflag: return
+ if not posflag and not Uijflag:
+ return
# need to do something
from diffpy.structure.symmetryutilities import SymmetryConstraints
+
# get unique sorted indices
tobeconstrained = dict.fromkeys(indices)
uindices = sorted(tobeconstrained.keys())
# remove old constraints
- pospat = re.compile(r'^([xyz])\((\d+)\)')
- Uijpat = re.compile(r'^(u11|u22|u33|u12|u13|u23)\((\d+)\)')
+ pospat = re.compile(r"^([xyz])\((\d+)\)")
+ Uijpat = re.compile(r"^(u11|u22|u33|u12|u13|u23)\((\d+)\)")
for var in list(self.constraints.keys()):
mpos = posflag and pospat.match(var)
mUij = Uijflag and Uijpat.match(var)
@@ -491,18 +505,20 @@ def applySymmetryConstraints(self, spacegroup, indices, posflag, Uijflag,
# find the largest used parameter index; pidxused must have an element
pidxused = [i for i in self.owner.updateParameters()] + [0]
# new parameters will start at the next decade
- parzeroidx = 10*(int(max(pidxused)/10)) + 10
+ parzeroidx = 10 * (int(max(pidxused) / 10)) + 10
# dictionary of parameter indices and their values
newparvalues = {}
selatoms = [self.initial[i] for i in uindices]
selpos = [a.xyz for a in selatoms]
selUijs = [a.U for a in selatoms]
- symcon = SymmetryConstraints(spacegroup, selpos, selUijs,
- sgoffset=sgoffset, eps=self.symposeps)
+ symcon = SymmetryConstraints(
+ spacegroup, selpos, selUijs, sgoffset=sgoffset, eps=self.symposeps
+ )
# deal with positions
if posflag:
# fix positions:
- for a, xyz in zip(selatoms, symcon.positions): a.xyz = xyz
+ for a, xyz in zip(selatoms, symcon.positions):
+ a.xyz = xyz
possymbols, parvalues = _makeParNames(symcon.pospars, parzeroidx)
newparvalues.update(parvalues)
eqns = symcon.positionFormulasPruned(possymbols)
@@ -514,7 +530,8 @@ def applySymmetryConstraints(self, spacegroup, indices, posflag, Uijflag,
# deal with temperature factors
if Uijflag:
# fix thermals
- for a, Uij in zip(selatoms, symcon.Uijs): a.U = Uij
+ for a, Uij in zip(selatoms, symcon.Uijs):
+ a.U = Uij
Usymbols, parvalues = _makeParNames(symcon.Upars, parzeroidx)
newparvalues.update(parvalues)
eqns = symcon.UFormulasPruned(Usymbols)
@@ -559,7 +576,7 @@ def setSelectedPairs(self, s):
"""
# check syntax of s
psf = self.getPairSelectionFlags(s)
- self.selected_pairs = psf['fixed_pair_string']
+ self.selected_pairs = psf["fixed_pair_string"]
return
def getSelectedPairs(self):
@@ -578,32 +595,34 @@ def getPairSelectionFlags(self, s=None):
secondflags -- list of selection flags for second indices
fixed_pair_string -- argument corrected to standard syntax
"""
- if s is None: s = self.selected_pairs
+ if s is None:
+ s = self.selected_pairs
Natoms = len(self.initial)
# sets of first and second indices
firstflags = Natoms * [False]
secondflags = Natoms * [False]
# words of fixed_pair_string
words_fixed = []
- s1 = s.strip(' \t,')
- words = re.split(r' *, *', s1)
+ s1 = s.strip(" \t,")
+ words = re.split(r" *, *", s1)
for w in words:
- wparts = w.split('-')
+ wparts = w.split("-")
if len(wparts) != 2:
emsg = "Selection word '%s' must contain one dash '-'." % w
raise ControlValueError(emsg)
sel0 = self._parseAtomSelectionString(wparts[0])
sel1 = self._parseAtomSelectionString(wparts[1])
- wfixed = sel0['fixedstring'] + '-' + sel1['fixedstring']
+ wfixed = sel0["fixedstring"] + "-" + sel1["fixedstring"]
words_fixed.append(wfixed)
- for idx, flg in sel0['flags'].items():
+ for idx, flg in sel0["flags"].items():
firstflags[idx] = flg
- for idx, flg in sel1['flags'].items():
+ for idx, flg in sel1["flags"].items():
secondflags[idx] = flg
# build returned dictionary
- rv = { 'firstflags' : firstflags,
- 'secondflags' : secondflags,
- 'fixed_pair_string' : ", ".join(words_fixed),
+ rv = {
+ "firstflags": firstflags,
+ "secondflags": secondflags,
+ "fixed_pair_string": ", ".join(words_fixed),
}
return rv
@@ -615,15 +634,14 @@ def applyPairSelection(self, server, phaseidx):
"""
psf = self.getPairSelectionFlags()
idx = 0
- for iflag, jflag in zip(psf['firstflags'], psf['secondflags']):
+ for iflag, jflag in zip(psf["firstflags"], psf["secondflags"]):
idx += 1
- server.selectAtomIndex(phaseidx, 'i', idx, iflag)
- server.selectAtomIndex(phaseidx, 'j', idx, jflag)
+ server.selectAtomIndex(phaseidx, "i", idx, iflag)
+ server.selectAtomIndex(phaseidx, "j", idx, jflag)
return
-
def getSelectedIndices(self, s):
- '''Indices of the atoms that match the specified selection string.
+ """Indices of the atoms that match the specified selection string.
s -- selection string consisting of one or more atom selection
words formatted as [!]{element|indexOrRange|all}
@@ -631,13 +649,13 @@ def getSelectedIndices(self, s):
Return a list of integers.
Raise ControlValueError for invalid selection string format.
- '''
- s1 = ''.join(c for c in s if not c.isspace())
- words = s1.split(',')
+ """
+ s1 = "".join(c for c in s if not c.isspace())
+ words = s1.split(",")
indices = set()
for w in words:
asd = self._parseAtomSelectionString(w)
- for idx, flg in asd['flags'].items():
+ for idx, flg in asd["flags"].items():
if flg:
indices.add(idx)
else:
@@ -645,13 +663,12 @@ def getSelectedIndices(self, s):
rv = sorted(indices)
return rv
-
# Regular expression object for matching atom selection strings.
# Will be assign with the first call to _parseAtomSelectionString.
_rxatomselection = None
def _parseAtomSelectionString(self, s):
- '''Process string that describes a set of atoms in the structure.
+ """Process string that describes a set of atoms in the structure.
s -- selection string formatted as [!]{element|indexOrRange|all}
"!" negates the selection, indexOrRange can be 1, 1:4,
@@ -662,53 +679,56 @@ def _parseAtomSelectionString(self, s):
'flags' -- dictionary of atom indices and boolean flags for
normal or negated selection.
Raise ControlValueError for invalid string format.
- '''
+ """
# delayed initialization of the class variable
if self._rxatomselection is None:
- FitStructure._rxatomselection = re.compile(r'''
+ FitStructure._rxatomselection = re.compile(
+ r"""
(?P!?) # exclamation point
(?:(?P[a-zA-Z]+)$| # element|all or
(?P\d+)(?P:\d+)?$ # number range
- )''', re.VERBOSE)
+ )""",
+ re.VERBOSE,
+ )
assert self._rxatomselection
Natoms = len(self.initial)
- flags = {}
- rv = {'fixedstring' : '', 'flags' : flags}
+ flags = {}
+ rv = {"fixedstring": "", "flags": flags}
# allow empty string and return an empty flags dictionary
- s1 = s.replace(' ', '')
- if not s1: return rv
+ s1 = s.replace(" ", "")
+ if not s1:
+ return rv
mx = self._rxatomselection.match(s1)
if not mx:
emsg = "Invalid selection syntax in '%s'" % s
raise ControlValueError(emsg)
- if mx.group('negate'):
- rv['fixedstring'] = '!'
- flg = not mx.group('negate')
+ if mx.group("negate"):
+ rv["fixedstring"] = "!"
+ flg = not mx.group("negate")
# process atom type
- if mx.group('element'):
- elfixed = mx.group('element')
+ if mx.group("element"):
+ elfixed = mx.group("element")
elfixed = elfixed[0:1].upper() + elfixed[1:].lower()
- if elfixed == 'All':
+ if elfixed == "All":
flags.update(dict.fromkeys(range(Natoms), flg))
- rv['fixedstring'] += elfixed.lower()
+ rv["fixedstring"] += elfixed.lower()
else:
for idx in range(Natoms):
if self.initial[idx].element == elfixed:
flags[idx] = flg
- rv['fixedstring'] += elfixed
+ rv["fixedstring"] += elfixed
# process range
else:
- lo = max(int(mx.group('start')) - 1, 0)
- rv['fixedstring'] += mx.group('start')
+ lo = max(int(mx.group("start")) - 1, 0)
+ rv["fixedstring"] += mx.group("start")
hi = lo + 1
- if mx.group('stop'):
- hi = int(mx.group('stop')[1:])
- rv['fixedstring'] += mx.group('stop')
+ if mx.group("stop"):
+ hi = int(mx.group("stop")[1:])
+ rv["fixedstring"] += mx.group("stop")
hi = min(hi, Natoms)
flags.update(dict.fromkeys(range(lo, hi), flg))
return rv
-
def copy(self, other=None):
"""copy self to other. if other is None, create new instance
@@ -741,38 +761,37 @@ def load(self, z, subpath):
z -- zipped project file
subpath -- path to its own storage within project file
"""
- #subpath = projname/fitname/structure/myname/
+ # subpath = projname/fitname/structure/myname/
from diffpy.pdfgui.utils import asunicode
from diffpy.pdfgui.control.pdfguicontrol import CtrlUnpickler
- subs = subpath.split('/')
+
+ subs = subpath.split("/")
rootDict = z.fileTree[subs[0]][subs[1]][subs[2]][subs[3]]
- strudata = asunicode(z.read(subpath + 'initial'))
- self.initial.readStr(strudata, 'pdffit')
+ strudata = asunicode(z.read(subpath + "initial"))
+ self.initial.readStr(strudata, "pdffit")
# refined
- if 'refined' in rootDict:
+ if "refined" in rootDict:
self.refined = PDFStructure(self.name)
- refdata = asunicode(z.read(subpath + 'refined'))
- self.refined.readStr(refdata, 'pdffit')
+ refdata = asunicode(z.read(subpath + "refined"))
+ self.refined.readStr(refdata, "pdffit")
# constraints
- if 'constraints' in rootDict:
- self.constraints = CtrlUnpickler.loads(z.read(subpath+'constraints'))
- translate = { 'gamma' : 'delta1',
- 'delta' : 'delta2',
- 'srat' : 'sratio' }
+ if "constraints" in rootDict:
+ self.constraints = CtrlUnpickler.loads(z.read(subpath + "constraints"))
+ translate = {"gamma": "delta1", "delta": "delta2", "srat": "sratio"}
for old, new in translate.items():
if old in self.constraints:
self.constraints[new] = self.constraints.pop(old)
# selected_pairs
if "selected_pairs" in rootDict:
- self.selected_pairs = asunicode(z.read(subpath+'selected_pairs'))
+ self.selected_pairs = asunicode(z.read(subpath + "selected_pairs"))
# sgoffset
if "sgoffset" in rootDict:
- sgoffsetstr = asunicode(z.read(subpath+'sgoffset'))
+ sgoffsetstr = asunicode(z.read(subpath + "sgoffset"))
sgoffset = [float(w) for w in sgoffsetstr.split()]
- self.initial.pdffit['sgoffset'] = sgoffset
+ self.initial.pdffit["sgoffset"] = sgoffset
# custom_spacegroup
if "custom_spacegroup" in rootDict:
- spkl = z.read(subpath+'custom_spacegroup')
+ spkl = z.read(subpath + "custom_spacegroup")
self.custom_spacegroup = CtrlUnpickler.loads(spkl)
return
@@ -783,20 +802,21 @@ def save(self, z, subpath):
subpath -- path to its own storage within project file
"""
from diffpy.pdfgui.utils import safeCPickleDumps
- z.writestr(subpath+'initial', self.initial.writeStr('pdffit'))
+
+ z.writestr(subpath + "initial", self.initial.writeStr("pdffit"))
if self.refined:
- z.writestr(subpath+'refined', self.refined.writeStr('pdffit'))
+ z.writestr(subpath + "refined", self.refined.writeStr("pdffit"))
if self.constraints:
spkl = safeCPickleDumps(self.constraints)
- z.writestr(subpath+'constraints', spkl)
- z.writestr(subpath+'selected_pairs', self.selected_pairs)
+ z.writestr(subpath + "constraints", spkl)
+ z.writestr(subpath + "selected_pairs", self.selected_pairs)
# sgoffset
- sgoffset = self.initial.pdffit.get('sgoffset', [0.0, 0.0, 0.0])
+ sgoffset = self.initial.pdffit.get("sgoffset", [0.0, 0.0, 0.0])
sgoffsetstr = "%g %g %g" % tuple(sgoffset)
- z.writestr(subpath+'sgoffset', sgoffsetstr)
+ z.writestr(subpath + "sgoffset", sgoffsetstr)
if self.custom_spacegroup:
spkl = safeCPickleDumps(self.custom_spacegroup)
- z.writestr(subpath+'custom_spacegroup', spkl)
+ z.writestr(subpath + "custom_spacegroup", spkl)
return
def getYNames(self):
@@ -814,7 +834,7 @@ def getXNames(self):
# in fact nothing
return []
- def getData(self, name, step = -1 ):
+ def getData(self, name, step=-1):
"""get self's data member
name -- data item name
@@ -833,12 +853,14 @@ def getData(self, name, step = -1 ):
return data
return self.owner._getData(self, name, step)
+
# End of class FitStructure
# Local helper functions -----------------------------------------------------
+
def _makeParNames(sympars, parzeroindex):
- '''Return a tuple of (symbols, parvalues), where symbols is a list of
+ """Return a tuple of (symbols, parvalues), where symbols is a list of
unique PDFFit parameter strings in "@%i" format and parvalues is a
dictionary of parameter indices and their values.
The symbols have indices 10n + (1, 2, 3) when referring to x, y, z, or
@@ -851,23 +873,31 @@ def _makeParNames(sympars, parzeroindex):
Return a tuple of (possymbols, Usymbols, parvalues).
This function is only used in FitStructure.applySymmetryConstraints method.
- '''
+ """
if parzeroindex % 10:
- raise ValueError('parzeroindex must be a multiple of 10.')
- smbindex = {'x' : 1, 'y' : 2, 'z' : 3,
- 'U11' : 4, 'U22' : 5, 'U33' : 6,
- 'U12' : 7, 'U13' : 8, 'U23' : 9}
+ raise ValueError("parzeroindex must be a multiple of 10.")
+ smbindex = {
+ "x": 1,
+ "y": 2,
+ "z": 3,
+ "U11": 4,
+ "U22": 5,
+ "U33": 6,
+ "U12": 7,
+ "U13": 8,
+ "U23": 9,
+ }
symbols = []
parvalues = {}
for smb, value in sympars:
- if smb[:1] == 'U':
+ if smb[:1] == "U":
nsite = 10 * int(smb[3:])
nvar = smbindex[smb[:3]]
else:
nsite = 10 * int(smb[1:])
nvar = smbindex[smb[:1]]
pidx = parzeroindex + nsite + nvar
- symbols.append('@%i' % pidx)
+ symbols.append("@%i" % pidx)
parvalues[pidx] = value
assert len(symbols) == len(parvalues)
rv = (symbols, parvalues)
diff --git a/src/diffpy/pdfgui/control/fitting.py b/src/diffpy/pdfgui/control/fitting.py
index a85bddce..a11cbb71 100644
--- a/src/diffpy/pdfgui/control/fitting.py
+++ b/src/diffpy/pdfgui/control/fitting.py
@@ -26,20 +26,27 @@
# helper routines to deal with PDFfit2 exceptions
+
def getEngineExceptions():
- """Return a tuple of possible exceptions from diffpy.pdffit2.pdffit2.
- """
- from diffpy.pdffit2.pdffit2 import dataError, unassignedError, \
- constraintError, structureError, calculationError
+ """Return a tuple of possible exceptions from diffpy.pdffit2.pdffit2."""
+ from diffpy.pdffit2.pdffit2 import (
+ dataError,
+ unassignedError,
+ constraintError,
+ structureError,
+ calculationError,
+ )
+
engine_exceptions = (
- dataError,
- unassignedError,
- constraintError,
- structureError,
- calculationError,
- )
+ dataError,
+ unassignedError,
+ constraintError,
+ structureError,
+ calculationError,
+ )
return engine_exceptions
+
def handleEngineException(error, gui=None):
"""Common handler of PDFfit2 engine exceptions.
@@ -49,15 +56,18 @@ def handleEngineException(error, gui=None):
errorInfo = "(%s)\n%s" % (error.__class__.__name__, str(error))
# be more verbose for Singular matrix exception
if "singular matrix" in errorInfo.lower():
- errorInfo += ("\n\n"
- "Common reasons are degeneracy in fit parameters,\n"
- "zero thermal factors or fit range starting at zero.")
+ errorInfo += (
+ "\n\n"
+ "Common reasons are degeneracy in fit parameters,\n"
+ "zero thermal factors or fit range starting at zero."
+ )
if gui:
gui.postEvent(gui.ERROR, " %s" % errorInfo)
else:
print(" %s" % errorInfo)
return
+
##############################################################################
class Fitting(Organizer):
"""Fitting is the class to control a PdfFit process running locally.
@@ -69,21 +79,23 @@ class Fitting(Organizer):
res: fitting result string
parameters: parameter dictionary
"""
- #Fit status -- mask 0xff
+
+ # Fit status -- mask 0xff
INITIALIZED = 1
- CONNECTED = 1<<1
- CONFIGURED = 1<<2
- DONE = 1<<3
+ CONNECTED = 1 << 1
+ CONFIGURED = 1 << 2
+ DONE = 1 << 3
- #JOB Status -- mask 0xff00
- VOID = 1<<8
- QUEUED = 1<<9
- RUNNING = 1<<10
- PAUSED = 1<<11
+ # JOB Status -- mask 0xff00
+ VOID = 1 << 8
+ QUEUED = 1 << 9
+ RUNNING = 1 << 10
+ PAUSED = 1 << 11
class Worker(threading.Thread):
"""Worker is the daemon thread of fitting"""
- def __init__( self, fitting ):
+
+ def __init__(self, fitting):
"""Worker ( self, fitting) --> initialize
fitting -- fitting object
@@ -92,7 +104,7 @@ def __init__( self, fitting ):
self.fitting = fitting
def run(self):
- """overload function from Thread """
+ """overload function from Thread"""
try:
self.fitting.run()
except ControlError as error:
@@ -129,9 +141,9 @@ def __init__(self, name):
self.parameters = {}
self.rw = 1.0
self.tolerancy = 0.001
- self.res = ''
+ self.res = ""
self.snapshots = []
- self.res = ''
+ self.res = ""
# All the calculated data are to be stored in a list.
# Such flat storage require unique index for each data item
@@ -147,7 +159,7 @@ def __changeStatus(self, fitStatus=None, jobStatus=None):
"""
self.fitStatus = fitStatus or self.fitStatus
self.jobStatus = jobStatus or self.jobStatus
- if fitStatus or jobStatus: # either of them is not None
+ if fitStatus or jobStatus: # either of them is not None
gui = self.controlCenter.gui
if gui:
gui.postEvent(gui.UPDATE, self)
@@ -155,7 +167,7 @@ def __changeStatus(self, fitStatus=None, jobStatus=None):
def _release(self):
"""release resources"""
- if self.server: # server has been allocated, we need free the memory
+ if self.server: # server has been allocated, we need free the memory
self.server.reset()
def _getStrId(self):
@@ -174,6 +186,7 @@ def copy(self, other=None):
if other is None:
other = Fitting(self.name)
import copy
+
Organizer.copy(self, other)
other.parameters = copy.deepcopy(self.parameters)
other.snapshots = copy.deepcopy(self.snapshots)
@@ -191,17 +204,19 @@ def load(self, z, subpath):
returns a tree of internal hierachy
"""
# subpath = projName/fitName/
- subs = subpath.split('/')
+ subs = subpath.split("/")
rootDict = z.fileTree[subs[0]][subs[1]]
- if 'parameters' in rootDict:
+ if "parameters" in rootDict:
from diffpy.pdfgui.control.pdfguicontrol import CtrlUnpickler
- self.parameters = CtrlUnpickler.loads(z.read(subpath+'parameters'))
- if 'steps' in rootDict:
- self.itemIndex, self.dataNameDict, self.snapshots = \
- pickle_loads(z.read(subpath+'steps'))
- if 'result' in rootDict:
- self.rw, self.res = pickle_loads(z.read(subpath+'result'))
+
+ self.parameters = CtrlUnpickler.loads(z.read(subpath + "parameters"))
+ if "steps" in rootDict:
+ self.itemIndex, self.dataNameDict, self.snapshots = pickle_loads(
+ z.read(subpath + "steps")
+ )
+ if "result" in rootDict:
+ self.rw, self.res = pickle_loads(z.read(subpath + "result"))
return Organizer.load(self, z, subpath)
@@ -213,14 +228,13 @@ def save(self, z, subpath):
"""
if self.parameters:
spkl = safeCPickleDumps(self.parameters)
- z.writestr(subpath + 'parameters', spkl)
+ z.writestr(subpath + "parameters", spkl)
if self.res:
spkl = safeCPickleDumps((self.rw, self.res))
- z.writestr(subpath + 'result', spkl)
+ z.writestr(subpath + "result", spkl)
if self.snapshots:
- spkl = safeCPickleDumps(
- (self.itemIndex, self.dataNameDict, self.snapshots) )
- z.writestr(subpath + 'steps', spkl)
+ spkl = safeCPickleDumps((self.itemIndex, self.dataNameDict, self.snapshots))
+ z.writestr(subpath + "steps", spkl)
Organizer.save(self, z, subpath)
return
@@ -232,7 +246,7 @@ def stripped(self):
returns reference to stripped copy
"""
- unpickleables = ('controlCenter', 'lock', 'pauseEvent', 'thread')
+ unpickleables = ("controlCenter", "lock", "pauseEvent", "thread")
naked = self.copy()
for a in unpickleables:
if a in self.__dict__:
@@ -265,8 +279,7 @@ def updateParameters(self):
return self.parameters
def applyParameters(self):
- """Evaluate all constrained variables using current parameters.
- """
+ """Evaluate all constrained variables using current parameters."""
for struc in self.strucs:
struc.applyParameters(self.parameters)
for dataset in self.datasets:
@@ -291,6 +304,7 @@ def changeParameterIndex(self, oldidx, newidx):
newfiteq = "=%s:%i" % (self.name, newidx)
from diffpy.pdfgui.control.pdfguicontrol import pdfguicontrol
+
fits = pdfguicontrol().fits
for fit in fits:
parameters = fit.parameters
@@ -313,16 +327,15 @@ def queue(self, enter=True):
self.__changeStatus(jobStatus=Fitting.VOID)
def getServer(self):
- """get a PDFfit2 instance either locally or remotely
- """
+ """get a PDFfit2 instance either locally or remotely"""
if self.fitStatus != Fitting.INITIALIZED:
return
# create a new instance of calculation server
from diffpy.pdffit2 import PdfFit
+
self.server = PdfFit()
self.__changeStatus(fitStatus=Fitting.CONNECTED)
-
def configure(self):
"""configure fitting"""
if self.fitStatus != Fitting.CONNECTED:
@@ -333,7 +346,7 @@ def configure(self):
self.server.reset()
for struc in self.strucs:
struc.clearRefined()
- self.server.read_struct_string(struc.initial.writeStr("pdffit") )
+ self.server.read_struct_string(struc.initial.writeStr("pdffit"))
for key, var in struc.constraints.items():
self.server.constrain(key, var.formula)
@@ -341,12 +354,14 @@ def configure(self):
for dataset in self.datasets:
dataset.clearRefined()
- self.server.read_data_string(dataset.writeResampledObsStr(),
- dataset.stype,
- dataset.qmax,
- dataset.qdamp)
- self.server.setvar('qbroad', dataset.qbroad)
- for key,var in dataset.constraints.items():
+ self.server.read_data_string(
+ dataset.writeResampledObsStr(),
+ dataset.stype,
+ dataset.qmax,
+ dataset.qdamp,
+ )
+ self.server.setvar("qbroad", dataset.qbroad)
+ for key, var in dataset.constraints.items():
self.server.constrain(key, var.formula)
# Removed call to pdfrange call, because data were already
# resampled to at fit range.
@@ -360,7 +375,7 @@ def configure(self):
for index, par in self.parameters.items():
# clean any refined value
par.refined = None
- self.server.setpar(index, par.initialValue()) # info[0] = init value
+ self.server.setpar(index, par.initialValue()) # info[0] = init value
# fix if fixed. Note: all parameters are free after self.server.reset().
if par.fixed:
self.server.fixpar(index)
@@ -371,7 +386,6 @@ def configure(self):
self.__changeStatus(fitStatus=Fitting.CONFIGURED)
return
-
def resetStatus(self):
"""reset status back to initialized"""
self.snapshots = []
@@ -383,8 +397,7 @@ def resetStatus(self):
self.__changeStatus(fitStatus=Fitting.INITIALIZED)
def run(self):
- """function to be run in daemon thread.
- """
+ """function to be run in daemon thread."""
# Begin
self.__changeStatus(jobStatus=Fitting.RUNNING)
try:
@@ -402,7 +415,7 @@ def run(self):
if self.refine_step():
break
else:
- #Wait on an event, pause for a while
+ # Wait on an event, pause for a while
self.__changeStatus(jobStatus=Fitting.PAUSED)
self.pauseEvent.wait()
@@ -414,7 +427,7 @@ def run(self):
self._release()
# job status should be changed because of thread exit
- self.__changeStatus ( jobStatus = Fitting.VOID)
+ self.__changeStatus(jobStatus=Fitting.VOID)
return
def _configureBondCalculation(self, struc):
@@ -433,7 +446,6 @@ def _configureBondCalculation(self, struc):
self.server.read_struct_string(strucstr)
return
-
def outputBondAngle(self, struc, i, j, k):
"""Output bond angle defined by atoms i, j, k.
The angle is calculated using the shortest lengths ji and jk with
@@ -458,7 +470,6 @@ def outputBondAngle(self, struc, i, j, k):
raise ControlValueError(str(error))
return
-
def outputBondLengthAtoms(self, struc, i, j):
"""Output shortest bond between atoms i, j.
Periodic boundary conditions are applied to find the shortest bond.
@@ -482,7 +493,6 @@ def outputBondLengthAtoms(self, struc, i, j):
raise ControlValueError(str(error))
return
-
def outputBondLengthTypes(self, struc, a1, a2, lb, ub):
"""Output all a1-a2 bond lenghts within specified range.
@@ -508,7 +518,6 @@ def outputBondLengthTypes(self, struc, a1, a2, lb, ub):
raise ControlValueError(str(error))
return
-
def pause(self, bPause=None):
"""pause ( self, bPause = None ) --> pause a fitting process
@@ -569,11 +578,13 @@ def close(self, force=False):
if force:
if self.isThreadRunning():
self.stop()
- #NOTE: Not waiting for thread to stop. There's no graceful
+ # NOTE: Not waiting for thread to stop. There's no graceful
# way while user choose to stop forcefully
else:
if self.isThreadRunning():
- raise ControlStatusError("Fitting: Fitting %s is still running"%self.name)
+ raise ControlStatusError(
+ "Fitting: Fitting %s is still running" % self.name
+ )
if self.thread is not None:
self.thread.join()
@@ -599,11 +610,11 @@ def buildNameDict(self):
self.itemIndex = 0
dataNameDict = {}
- #dataNameDict for datasets
+ # dataNameDict for datasets
for dataset in self.datasets:
id = dataset._getStrId()
dataNameDict[id] = {}
- for itemName in list(dataset.constraints.keys()) + ['Gcalc','crw']:
+ for itemName in list(dataset.constraints.keys()) + ["Gcalc", "crw"]:
dataNameDict[id][itemName] = self.itemIndex
self.itemIndex += 1
@@ -618,7 +629,7 @@ def buildNameDict(self):
# dataNameDict for self
id = self._getStrId()
dataNameDict[id] = {}
- dataNameDict[id]['rw'] = self.itemIndex
+ dataNameDict[id]["rw"] = self.itemIndex
self.itemIndex += 1
for parameter in self.parameters.keys():
dataNameDict[id][parameter] = self.itemIndex
@@ -648,15 +659,15 @@ def appendStep(self, source):
for name in dataset.constraints.keys():
snapshot[nameDict[name]] = source.getvar(name)
- snapshot[nameDict['Gcalc']] = dataset.Gcalc
- snapshot[nameDict['crw']] = dataset.crw
+ snapshot[nameDict["Gcalc"]] = dataset.Gcalc
+ snapshot[nameDict["crw"]] = dataset.crw
seq += 1
# udpate strucs
seq = 1
for struc in self.strucs:
id = struc._getStrId()
- #set current struc
+ # set current struc
source.setphase(seq)
# use nameDict for current struc
nameDict = self.dataNameDict[id]
@@ -668,7 +679,7 @@ def appendStep(self, source):
# update global data
id = self._getStrId()
nameDict = self.dataNameDict[id]
- snapshot[nameDict['rw']] = self.rw
+ snapshot[nameDict["rw"]] = self.rw
for parameter in self.parameters.keys():
snapshot[nameDict[parameter]] = source.getpar(parameter)
@@ -683,7 +694,7 @@ def refine_step(self):
# do nothing but return finished
return True
- finished = self.server.refine_step(self.tolerancy)
+ finished = self.server.refine_step(self.tolerancy)
# get fitted data
idataset = 1
@@ -706,15 +717,15 @@ def refine_step(self):
self.step += 1
self.appendStep(self.server)
- #update plots and structure renderer
+ # update plots and structure renderer
gui = self.controlCenter.gui
if gui:
gui.postEvent(gui.OUTPUT, None)
gui.postEvent(gui.PLOTNOW, self)
if finished:
- self.res = "* %s\n\n"%time.ctime()+ self.server.save_res_string()
- self.__changeStatus(fitStatus = Fitting.DONE)
+ self.res = "* %s\n\n" % time.ctime() + self.server.save_res_string()
+ self.__changeStatus(fitStatus=Fitting.DONE)
return finished
@@ -724,7 +735,7 @@ def getYNames(self):
returns a name str list
"""
names = list(self.parameters.keys())
- names.append('rw')
+ names.append("rw")
return names
def getXNames(self):
@@ -755,8 +766,7 @@ def getData(self, name, step=-1):
return self._getData(self, name, step)
def getMetaDataNames(self):
- """return all applicable meta data names
- """
+ """return all applicable meta data names"""
names = []
for dataset in self.datasets:
# build up the name list
@@ -793,20 +803,22 @@ def _getData(self, id, name, step=-1):
"""
# find the unique index
if len(self.snapshots) == 0:
- return None
+ return None
try:
# if it is a 'int', it must be parameter. So only fitting has its value.
- if isinstance(name, int): id = self
+ if isinstance(name, int):
+ id = self
nameDict = self.dataNameDict[id._getStrId()]
index = nameDict[name]
except KeyError:
- return None # data is not ready
+ return None # data is not ready
if step is None:
- return [ snapshot[index] for snapshot in self.snapshots ]
- elif isinstance( step, list):
- return [ self.snapshots[i][index] for i in step ]
+ return [snapshot[index] for snapshot in self.snapshots]
+ elif isinstance(step, list):
+ return [self.snapshots[i][index] for i in step]
else:
return self.snapshots[step][index]
+
# End of file
diff --git a/src/diffpy/pdfgui/control/organizer.py b/src/diffpy/pdfgui/control/organizer.py
index 574bd10c..4746877f 100644
--- a/src/diffpy/pdfgui/control/organizer.py
+++ b/src/diffpy/pdfgui/control/organizer.py
@@ -19,6 +19,7 @@
from diffpy.pdfgui.control.calculation import Calculation
from diffpy.pdfgui.control.controlerrors import ControlTypeError
+
class Organizer(PDFComponent):
"""Base class for Fitting. It holds separate lists of datasets,
strucs and calculations
@@ -34,6 +35,7 @@ def __init__(self, name):
name -- component name
"""
from diffpy.pdfgui.control.pdflist import PDFList
+
PDFComponent.__init__(self, name)
self.datasets = PDFList()
@@ -46,6 +48,7 @@ def __init__(self, name):
# controlCenter is the reference to global PDFGuiControl object
from diffpy.pdfgui.control.pdfguicontrol import pdfguicontrol
+
self.controlCenter = pdfguicontrol()
def __findList(self, id):
@@ -149,24 +152,25 @@ def load(self, z, subpath):
"""
# subpath = projName/myName/
from diffpy.pdfgui.utils import unquote_plain
- subs = subpath.split('/')
+
+ subs = subpath.split("/")
rootDict = z.fileTree[subs[0]][subs[1]]
- if 'structure' in rootDict:
- for strucName in rootDict['structure'].keys():
+ if "structure" in rootDict:
+ for strucName in rootDict["structure"].keys():
struc = FitStructure(unquote_plain(strucName))
- struc.load(z, subpath + 'structure/' + strucName + '/')
+ struc.load(z, subpath + "structure/" + strucName + "/")
self.add(struc)
- if 'dataset' in rootDict:
- for datasetName in rootDict['dataset'].keys():
+ if "dataset" in rootDict:
+ for datasetName in rootDict["dataset"].keys():
dataset = FitDataSet(unquote_plain(datasetName))
- dataset.load(z, subpath + 'dataset/' + datasetName + '/')
+ dataset.load(z, subpath + "dataset/" + datasetName + "/")
self.add(dataset)
- if 'calculation' in rootDict:
- for calcName in rootDict['calculation'].keys():
+ if "calculation" in rootDict:
+ for calcName in rootDict["calculation"].keys():
calc = Calculation(unquote_plain(calcName))
- calc.load(z, subpath + 'calculation/' + calcName + '/')
+ calc.load(z, subpath + "calculation/" + calcName + "/")
self.add(calc)
self.__forward_spdiameter()
@@ -181,15 +185,16 @@ def save(self, z, subpath):
"""
# strucs and datasets
from diffpy.pdfgui.utils import quote_plain
+
for struc in self.strucs:
- struc.save(z, subpath + 'structure/' + quote_plain(struc.name) + '/')
+ struc.save(z, subpath + "structure/" + quote_plain(struc.name) + "/")
for dataset in self.datasets:
- dataset.save(z, subpath + 'dataset/' + quote_plain(dataset.name) + '/')
+ dataset.save(z, subpath + "dataset/" + quote_plain(dataset.name) + "/")
for calc in self.calcs:
- calc.save(z, subpath + 'calculation/' + quote_plain(calc.name) + '/')
+ calc.save(z, subpath + "calculation/" + quote_plain(calc.name) + "/")
return
- def copy(self, other = None):
+ def copy(self, other=None):
"""copy self to other. if other is None, create an instance
other -- ref to other object
@@ -211,21 +216,20 @@ def organization(self):
returns a tree of internal hierachy
"""
- org = [None]*4
- org [0] = self
- org [1] = []
+ org = [None] * 4
+ org[0] = self
+ org[1] = []
for dataset in self.datasets:
org[1].append((dataset.name, dataset))
- org [2] = []
+ org[2] = []
for struc in self.strucs:
org[2].append((struc.name, struc))
- org [3] = []
+ org[3] = []
for calc in self.calcs:
org[3].append((calc.name, calc))
return org
-
def __forward_spdiameter(self):
"""Copy spdiameter value loaded from fit or calculation to phase.
@@ -235,10 +239,11 @@ def __forward_spdiameter(self):
"""
# Jump out if any of structures has spdiameter set
for stru in self.strucs:
- if stru.getvar('spdiameter'): return
+ if stru.getvar("spdiameter"):
+ return
# Search datasets for spdiameter and its constraints
- spd_assigned = lambda ds : bool(ds.spdiameter)
- spd_constrained = lambda ds : 'spdiameter' in ds.constraints
+ spd_assigned = lambda ds: bool(ds.spdiameter)
+ spd_constrained = lambda ds: "spdiameter" in ds.constraints
# Figure out the value and constraint for spdiameter.
# The highest priority is for a dataset with constrained spdiameter,
# then for dataset with assigned spdiameter and finally from
@@ -249,20 +254,20 @@ def __forward_spdiameter(self):
assigned_calcs = list(filter(spd_assigned, self.calcs))
if constrained_datas:
spd_val = constrained_datas[0].spdiameter
- spd_cns = constrained_datas[0].constraints['spdiameter']
+ spd_cns = constrained_datas[0].constraints["spdiameter"]
elif assigned_datas:
spd_val = assigned_datas[0].spdiameter
elif assigned_calcs:
spd_val = assigned_calcs[0].spdiameter
# assign spd_val to all structures that don't have it set
for stru in self.strucs:
- if spd_val and not stru.getvar('spdiameter'):
- stru.setvar('spdiameter', spd_val)
+ if spd_val and not stru.getvar("spdiameter"):
+ stru.setvar("spdiameter", spd_val)
if spd_cns:
- stru.constraints.setdefault('spdiameter', spd_cns)
+ stru.constraints.setdefault("spdiameter", spd_cns)
# finally remove any spdiameter constraints from all datasets
for ds in self.datasets:
- ds.constraints.pop('spdiameter', None)
+ ds.constraints.pop("spdiameter", None)
return
@@ -270,6 +275,6 @@ def __forward_spdiameter(self):
# simple test code
if __name__ == "__main__":
- Organizer('name')
+ Organizer("name")
# End of file
diff --git a/src/diffpy/pdfgui/control/parameter.py b/src/diffpy/pdfgui/control/parameter.py
index 6c5f849e..6ed68d6d 100644
--- a/src/diffpy/pdfgui/control/parameter.py
+++ b/src/diffpy/pdfgui/control/parameter.py
@@ -19,8 +19,13 @@
import six
-from diffpy.pdfgui.control.controlerrors import \
- ControlTypeError, ControlKeyError, ControlRuntimeError, ControlError
+from diffpy.pdfgui.control.controlerrors import (
+ ControlTypeError,
+ ControlKeyError,
+ ControlRuntimeError,
+ ControlError,
+)
+
class Parameter:
"""Parameter is class for value and properties of refined parameter.
@@ -37,6 +42,7 @@ class Parameter:
__initial -- stores the initial value, float, or "=fitname:idx" string
__fitrepr -- None or string representation of Fitting instance
"""
+
# fits should reference PDFGuiControl.fits
def __init__(self, idx, initial=0.0):
@@ -47,7 +53,7 @@ def __init__(self, idx, initial=0.0):
It can be float, Fitting, "=fitname" or "=fitname:idx" string.
"""
self.idx = idx
- self.name = ''
+ self.name = ""
self.refined = None
self.fixed = False
self.__initial = None
@@ -64,6 +70,7 @@ def setInitial(self, initial):
"""
self.__fitrepr = None
from diffpy.pdfgui.control.fitting import Fitting
+
try:
self.__initial = float(initial)
return
@@ -72,7 +79,7 @@ def setInitial(self, initial):
if isinstance(initial, Fitting):
self.__initial = "=" + initial.name
self.__fitrepr = repr(initial)
- elif isinstance(initial, six.string_types) and initial[:1] == '=':
+ elif isinstance(initial, six.string_types) and initial[:1] == "=":
self.__initial = initial
self.__findLinkedFitting()
else:
@@ -115,10 +122,9 @@ def initialValue(self):
return float(value)
def __getLinkedValue(self):
- """Private retrieval of parameter value from linked Fitting.
- """
+ """Private retrieval of parameter value from linked Fitting."""
# Check to see if the fit name has a ':' in it
- isplit = self.__initial.split(':')
+ isplit = self.__initial.split(":")
# Who needs regular expressions?
try:
if len(isplit) == 1:
@@ -126,7 +132,7 @@ def __getLinkedValue(self):
fitname = self.__initial[1:]
else:
srcidx = int(isplit[-1])
- fitname = (':'.join(isplit[:-1]))[1:]
+ fitname = (":".join(isplit[:-1]))[1:]
except ValueError:
# __initial should be in the form "=fitname[:srcidx]"
raise ControlError("Malformed linked parameter %s" % self.__initial)
@@ -137,7 +143,9 @@ def __getLinkedValue(self):
try:
srcpar = srcfit.parameters[srcidx]
except KeyError:
- raise ControlKeyError("Fitting '%s' has no parameter %s" % (fitname, srcidx))
+ raise ControlKeyError(
+ "Fitting '%s' has no parameter %s" % (fitname, srcidx)
+ )
if srcpar.refined is not None:
value = srcpar.refined
@@ -155,18 +163,19 @@ def __findLinkedFitting(self):
returns reference to Fitting when found or None
"""
# Check to see if the fit name has a ':' in it
- isplit = self.__initial.split(':')
+ isplit = self.__initial.split(":")
try:
srcidx = int(isplit[-1])
- fitname = (':'.join(isplit[:-1]))[1:]
+ fitname = (":".join(isplit[:-1]))[1:]
except ValueError:
fitname = self.__initial[1:]
srcidx = self.idx
self.__initial += ":%i" % srcidx
from diffpy.pdfgui.control.pdfguicontrol import pdfguicontrol
+
fits = pdfguicontrol().fits
- fitnames = [ f.name for f in fits ]
- fitrepres = [ repr(f) for f in fits ]
+ fitnames = [f.name for f in fits]
+ fitrepres = [repr(f) for f in fits]
# first find linked fitting by name
if fitname in fitnames:
idx = fitnames.index(fitname)
@@ -184,4 +193,5 @@ def __findLinkedFitting(self):
ref = None
return ref
+
# End of class Parameter
diff --git a/src/diffpy/pdfgui/control/pdfcomponent.py b/src/diffpy/pdfgui/control/pdfcomponent.py
index 4325241b..d3ac7903 100644
--- a/src/diffpy/pdfgui/control/pdfcomponent.py
+++ b/src/diffpy/pdfgui/control/pdfcomponent.py
@@ -13,8 +13,10 @@
#
##############################################################################
+
class PDFComponent(object):
"""Common base class."""
+
def __init__(self, name):
"""initialize
@@ -22,11 +24,12 @@ def __init__(self, name):
"""
self.name = name
- def close ( self, force = False ):
+ def close(self, force=False):
"""close myself
force -- if forcibly (no wait)
"""
pass
+
# End of file
diff --git a/src/diffpy/pdfgui/control/pdfdataset.py b/src/diffpy/pdfgui/control/pdfdataset.py
index 48fb53e0..4159ae77 100644
--- a/src/diffpy/pdfgui/control/pdfdataset.py
+++ b/src/diffpy/pdfgui/control/pdfdataset.py
@@ -23,8 +23,8 @@
from getpass import getuser
from diffpy.pdfgui.control.pdfcomponent import PDFComponent
-from diffpy.pdfgui.control.controlerrors import \
- ControlKeyError, ControlFileError
+from diffpy.pdfgui.control.controlerrors import ControlKeyError, ControlFileError
+
class PDFDataSet(PDFComponent):
"""PDFDataSet is a class for experimental PDF data.
@@ -56,9 +56,21 @@ class PDFDataSet(PDFComponent):
refinableVars -- set (dict) of refinable variable names.
"""
- persistentItems = [ 'robs', 'Gobs', 'drobs', 'dGobs', 'stype', 'qmax',
- 'qdamp', 'qbroad', 'dscale', 'rmin', 'rmax', 'metadata' ]
- refinableVars = dict.fromkeys(('qdamp', 'qbroad', 'dscale'))
+ persistentItems = [
+ "robs",
+ "Gobs",
+ "drobs",
+ "dGobs",
+ "stype",
+ "qmax",
+ "qdamp",
+ "qbroad",
+ "dscale",
+ "rmin",
+ "rmax",
+ "metadata",
+ ]
+ refinableVars = dict.fromkeys(("qdamp", "qbroad", "dscale"))
def __init__(self, name):
"""Initialize.
@@ -75,7 +87,7 @@ def clear(self):
self.Gobs = []
self.drobs = []
self.dGobs = []
- self.stype = 'X'
+ self.stype = "X"
# user must specify qmax to get termination ripples
self.qmax = 0.0
self.qdamp = 0.001
@@ -134,13 +146,14 @@ def read(self, filename):
self.readStr(fp.read())
except PDFDataFormatError as err:
basename = os.path.basename(filename)
- emsg = ("Could not open '%s' due to unsupported file format " +
- "or corrupted data. [%s]") % (basename, err)
+ emsg = (
+ "Could not open '%s' due to unsupported file format "
+ + "or corrupted data. [%s]"
+ ) % (basename, err)
raise ControlFileError(emsg)
self.filename = os.path.abspath(filename)
return self
-
def readStr(self, datastring):
"""read experimental PDF data from a string
@@ -150,15 +163,15 @@ def readStr(self, datastring):
"""
self.clear()
# useful regex patterns:
- rx = { 'f' : r'[-+]?(\d+(\.\d*)?|\d*\.\d+)([eE][-+]?\d+)?' }
+ rx = {"f": r"[-+]?(\d+(\.\d*)?|\d*\.\d+)([eE][-+]?\d+)?"}
# find where does the data start
- res = re.search(r'^#+ start data\s*(?:#.*\s+)*', datastring, re.M)
+ res = re.search(r"^#+ start data\s*(?:#.*\s+)*", datastring, re.M)
# start_data is position where the first data line starts
if res:
start_data = res.end()
else:
# find line that starts with a floating point number
- regexp = r'^\s*%(f)s' % rx
+ regexp = r"^\s*%(f)s" % rx
res = re.search(regexp, datastring, re.M)
if res:
start_data = res.start()
@@ -168,18 +181,18 @@ def readStr(self, datastring):
databody = datastring[start_data:].strip()
# find where the metadata starts
- metadata = ''
- res = re.search(r'^#+\ +metadata\b\n', header, re.M)
+ metadata = ""
+ res = re.search(r"^#+\ +metadata\b\n", header, re.M)
if res:
- metadata = header[res.end():]
- header = header[:res.start()]
+ metadata = header[res.end() :]
+ header = header[: res.start()]
# parse header
# stype
- if re.search('(x-?ray|PDFgetX)', header, re.I):
- self.stype = 'X'
- elif re.search('(neutron|PDFgetN)', header, re.I):
- self.stype = 'N'
+ if re.search("(x-?ray|PDFgetX)", header, re.I):
+ self.stype = "X"
+ elif re.search("(neutron|PDFgetN)", header, re.I):
+ self.stype = "N"
# qmax
regexp = r"\bqmax *= *(%(f)s)\b" % rx
res = re.search(regexp, header, re.I)
@@ -209,12 +222,12 @@ def readStr(self, datastring):
regexp = r"\b(?:temp|temperature|T)\ *=\ *(%(f)s)\b" % rx
res = re.search(regexp, header)
if res:
- self.metadata['temperature'] = float(res.groups()[0])
+ self.metadata["temperature"] = float(res.groups()[0])
# doping
regexp = r"\b(?:x|doping)\ *=\ *(%(f)s)\b" % rx
res = re.search(regexp, header)
if res:
- self.metadata['doping'] = float(res.groups()[0])
+ self.metadata["doping"] = float(res.groups()[0])
# parsing gerneral metadata
if metadata:
@@ -223,12 +236,12 @@ def readStr(self, datastring):
res = re.search(regexp, metadata, re.M)
if res:
self.metadata[res.groups()[0]] = float(res.groups()[1])
- metadata = metadata[res.end():]
+ metadata = metadata[res.end() :]
else:
break
# read actual data - robs, Gobs, drobs, dGobs
- inf_or_nan = re.compile('(?i)^[+-]?(NaN|Inf)\\b')
+ inf_or_nan = re.compile("(?i)^[+-]?(NaN|Inf)\\b")
has_drobs = True
has_dGobs = True
# raise PDFDataFormatError if something goes wrong
@@ -239,15 +252,13 @@ def readStr(self, datastring):
self.robs.append(float(v[0]))
self.Gobs.append(float(v[1]))
# drobs is valid if all values are defined and positive
- has_drobs = (has_drobs and
- len(v) > 2 and not inf_or_nan.match(v[2]))
+ has_drobs = has_drobs and len(v) > 2 and not inf_or_nan.match(v[2])
if has_drobs:
v2 = float(v[2])
has_drobs = v2 > 0.0
self.drobs.append(v2)
# dGobs is valid if all values are defined and positive
- has_dGobs = (has_dGobs and
- len(v) > 3 and not inf_or_nan.match(v[3]))
+ has_dGobs = has_dGobs and len(v) > 3 and not inf_or_nan.match(v[3])
if has_dGobs:
v3 = float(v[3])
has_dGobs = v3 > 0.0
@@ -260,11 +271,12 @@ def readStr(self, datastring):
raise PDFDataFormatError(err)
self.rmin = self.robs[0]
self.rmax = self.robs[-1]
- if not has_drobs: self.drobs = len(self.robs) * [0.0]
- if not has_dGobs: self.dGobs = len(self.robs) * [0.0]
+ if not has_drobs:
+ self.drobs = len(self.robs) * [0.0]
+ if not has_dGobs:
+ self.dGobs = len(self.robs) * [0.0]
return self
-
def write(self, filename):
"""Write experimental PDF data to a file.
@@ -273,7 +285,7 @@ def write(self, filename):
No return value.
"""
txt = self.writeStr()
- f = open(filename, 'w')
+ f = open(filename, "w")
f.write(txt)
f.close()
return
@@ -285,38 +297,43 @@ def writeStr(self):
"""
lines = []
# write metadata
- lines.extend([
- 'History written: ' + time.ctime(),
- 'produced by ' + getuser(),
- '##### PDFgui' ])
+ lines.extend(
+ [
+ "History written: " + time.ctime(),
+ "produced by " + getuser(),
+ "##### PDFgui",
+ ]
+ )
# stype
- if self.stype == 'X':
- lines.append('stype=X x-ray scattering')
- elif self.stype == 'N':
- lines.append('stype=N neutron scattering')
+ if self.stype == "X":
+ lines.append("stype=X x-ray scattering")
+ elif self.stype == "N":
+ lines.append("stype=N neutron scattering")
# qmax
if self.qmax == 0:
- qmax_line = 'qmax=0 correction not applied'
+ qmax_line = "qmax=0 correction not applied"
else:
- qmax_line = 'qmax=%.2f' % self.qmax
+ qmax_line = "qmax=%.2f" % self.qmax
lines.append(qmax_line)
# qdamp
- lines.append('qdamp=%g' % self.qdamp)
+ lines.append("qdamp=%g" % self.qdamp)
# qbroad
- lines.append('qbroad=%g' % self.qbroad)
+ lines.append("qbroad=%g" % self.qbroad)
# dscale
- lines.append('dscale=%g' % self.dscale)
+ lines.append("dscale=%g" % self.dscale)
# metadata
if len(self.metadata) > 0:
- lines.append('# metadata')
+ lines.append("# metadata")
for k, v in self.metadata.items():
- lines.append( "%s=%s" % (k,v) )
+ lines.append("%s=%s" % (k, v))
# write data:
- lines.append('##### start data')
- lines.append('#L r(A) G(r) d_r d_Gr')
+ lines.append("##### start data")
+ lines.append("#L r(A) G(r) d_r d_Gr")
for i in range(len(self.robs)):
- lines.append('%g %g %g %g' % \
- (self.robs[i], self.Gobs[i], self.drobs[i], self.dGobs[i]) )
+ lines.append(
+ "%g %g %g %g"
+ % (self.robs[i], self.Gobs[i], self.drobs[i], self.dGobs[i])
+ )
# that should be it
datastring = "\n".join(lines) + "\n"
return datastring
@@ -333,23 +350,36 @@ def copy(self, other=None):
other.clear()
# some attributes can be assigned, e.g., robs, Gobs, drobs, dGobs are
# constant so they can be shared between copies.
- assign_attributes = ( 'robs', 'Gobs', 'drobs', 'dGobs', 'stype',
- 'qmax', 'qdamp', 'qbroad', 'dscale',
- 'rmin', 'rmax', 'filename' )
+ assign_attributes = (
+ "robs",
+ "Gobs",
+ "drobs",
+ "dGobs",
+ "stype",
+ "qmax",
+ "qdamp",
+ "qbroad",
+ "dscale",
+ "rmin",
+ "rmax",
+ "filename",
+ )
# for others we will assign a copy
- copy_attributes = ( 'metadata', )
+ copy_attributes = ("metadata",)
for a in assign_attributes:
setattr(other, a, getattr(self, a))
for a in copy_attributes:
setattr(other, a, copy.deepcopy(getattr(self, a)))
return other
+
# End of class PDFDataSet
class PDFDataFormatError(Exception):
- """Exception class marking failure to proccess PDF data string.
- """
+ """Exception class marking failure to proccess PDF data string."""
+
pass
+
# End of file
diff --git a/src/diffpy/pdfgui/control/pdfguicontrol.py b/src/diffpy/pdfgui/control/pdfguicontrol.py
index 8d74c312..e0816b74 100644
--- a/src/diffpy/pdfgui/control/pdfguicontrol.py
+++ b/src/diffpy/pdfgui/control/pdfguicontrol.py
@@ -39,6 +39,7 @@ class PDFGuiControl:
It has a container of Calculation and Fitting instances.
Each Calculation and Fitting has a unique name.
"""
+
def __init__(self, gui=None):
"""initialize
@@ -60,10 +61,10 @@ def reset(self):
"""clean up for a new project"""
self.fits = PDFList()
self.plots = PDFList()
- self.journal = ''
+ self.journal = ""
self.projfile = None
- #self.saved = False
+ # self.saved = False
# a simple thread to handle fitting queue
class QueueManager(threading.Thread):
@@ -79,11 +80,12 @@ def run(self):
except ControlError as error:
gui = self.control.gui
if gui:
- gui.postEvent(gui.ERROR, " %s"%error.info)
+ gui.postEvent(gui.ERROR, " %s" % error.info)
else:
- print(" %s"%error.info)
+ print(" %s" % error.info)
# another check before go to sleep
- if not self.running: break
+ if not self.running:
+ break
time.sleep(1)
def startQueue(self):
@@ -100,7 +102,7 @@ def checkQueue(self):
# No fitting in the queue is running.
try:
self.lock.acquire()
- if len(self.fittingQueue) > 0 :
+ if len(self.fittingQueue) > 0:
self.currentFitting = self.fittingQueue.pop(0)
else:
self.currentFitting = None
@@ -110,7 +112,7 @@ def checkQueue(self):
self.currentFitting.start()
- def enqueue(self, fits, enter = True):
+ def enqueue(self, fits, enter=True):
"""enqueue or dequeue fittings
fits -- list of fittings to be queued/dequeued
@@ -142,7 +144,7 @@ def enqueue(self, fits, enter = True):
finally:
self.lock.release()
- def close(self, force = True):
+ def close(self, force=True):
"""close a project
force -- if exit forciably
@@ -156,8 +158,7 @@ def close(self, force = True):
self.reset()
def exit(self):
- """exit when program finished
- """
+ """exit when program finished"""
self.close()
if self.queueManager.is_alive():
self.queueManager.running = False
@@ -204,7 +205,7 @@ def newStructure(self, targetID, name, position=None):
targetID.add(struct, position)
return struct
- def loadStructure(self, targetID, filename, name = None, position=None):
+ def loadStructure(self, targetID, filename, name=None, position=None):
"""add blank structure to a Fitting
targetID -- reference to Fitting
@@ -222,7 +223,7 @@ def loadStructure(self, targetID, filename, name = None, position=None):
targetID.add(struct, position)
return struct
- def loadDataset(self, targetID, filename, name = None, position=None):
+ def loadDataset(self, targetID, filename, name=None, position=None):
"""load Dataset from a file to a Fitting
targetID -- reference to Fitting
@@ -236,20 +237,19 @@ def loadDataset(self, targetID, filename, name = None, position=None):
if name is None:
name = os.path.basename(filename)
- #insert to target
+ # insert to target
dataset = FitDataSet(name)
dataset.readObs(filename)
targetID.add(dataset, position)
return dataset
- def add(self, ID, position = None):
+ def add(self, ID, position=None):
"""add fitting/calculation to internal list
Id -- reference to the object to be inserted
position -- where the object is to be inserted, default is last
"""
- if not isinstance(ID, Fitting) and \
- not isinstance(ID, Calculation):
+ if not isinstance(ID, Fitting) and not isinstance(ID, Calculation):
raise ControlTypeError("Can't add %s to list" % self.__class__.__name__)
if position is not None:
self.fits.insert(position, ID)
@@ -334,17 +334,17 @@ def paste(self, dup, target=None, new_name=None, position=None):
target.add(o, position)
return o
-
def load(self, projfile):
"""load project from projfile.
projfile -- a zip file of everything
"""
+
def _nameParser(namelist):
"""parse the zipfile name list to get a file tree"""
fileTree = {}
for name in namelist:
- subs = name.split('/')
+ subs = name.split("/")
pathDict = fileTree
for x in subs[:-1]:
# if no node has been created
@@ -353,7 +353,7 @@ def _nameParser(namelist):
pathDict = pathDict[x]
# check if the entry is a leaf(file, not folder)
- if subs[-1] != '':
+ if subs[-1] != "":
pathDict[subs[-1]] = None
return fileTree
@@ -370,7 +370,7 @@ def _nameParser(namelist):
emsg_invalid_file = "Invalid or corrupted project %s." % projfile
z = None
try:
- z = zipfile.ZipFile(projfile, 'r')
+ z = zipfile.ZipFile(projfile, "r")
z.fileTree = _nameParser(z.namelist())
if len(z.fileTree) == 0:
@@ -379,20 +379,20 @@ def _nameParser(namelist):
rootDict = next(iter(z.fileTree.values()))
projName = next(iter(z.fileTree.keys()))
- if 'journal' in rootDict:
- self.journal = asunicode(z.read(projName + '/journal'))
+ if "journal" in rootDict:
+ self.journal = asunicode(z.read(projName + "/journal"))
# all the fitting and calculations
- #NOTE: It doesn't hurt to keep backward compatibility
+ # NOTE: It doesn't hurt to keep backward compatibility
# old test project may not have file 'fits'
- if 'fits' in rootDict:
- ftxt = asunicode(z.read(projName + '/fits'))
+ if "fits" in rootDict:
+ ftxt = asunicode(z.read(projName + "/fits"))
fitnames = ftxt.splitlines()
else:
- fitnames = [ x for x in rootDict.keys() if rootDict[x] is not None]
+ fitnames = [x for x in rootDict.keys() if rootDict[x] is not None]
for name in fitnames:
- if not name: # empty string
+ if not name: # empty string
continue
fit = Fitting(name)
# fitting name stored in rootDict should be quoted
@@ -401,7 +401,7 @@ def _nameParser(namelist):
if rdname not in rootDict:
rdname = name
if rdname in rootDict:
- org = fit.load(z, projName + '/' + rdname + '/')
+ org = fit.load(z, projName + "/" + rdname + "/")
else:
# it's simply a blank fitting, has no info in proj file yet
org = fit.organization()
@@ -413,11 +413,11 @@ def _nameParser(namelist):
# close input file if opened
finally:
- if z: z.close()
+ if z:
+ z.close()
return organizations
-
def save(self, projfile=None):
"""Save project to projfile, default projfile is self.projfile
@@ -444,19 +444,19 @@ def save(self, projfile=None):
fitnames = []
z = None
tmpfilename = None
- try :
+ try:
tmpfd, tmpfilename = tempfile.mkstemp()
os.close(tmpfd)
- z = zipfile.ZipFile(tmpfilename, 'w', zipfile.ZIP_DEFLATED)
+ z = zipfile.ZipFile(tmpfilename, "w", zipfile.ZIP_DEFLATED)
# fits also contain calculations
for fit in self.fits:
name = fit.name
- fit.save(z, projName + '/' + quote_plain(fit.name) + '/')
+ fit.save(z, projName + "/" + quote_plain(fit.name) + "/")
fitnames.append(name)
if self.journal:
- z.writestr(projName + '/journal', asunicode(self.journal))
- ftxt = '\n'.join(fitnames)
- z.writestr(projName + '/fits', asunicode(ftxt))
+ z.writestr(projName + "/journal", asunicode(self.journal))
+ ftxt = "\n".join(fitnames)
+ z.writestr(projName + "/fits", asunicode(ftxt))
z.close()
shutil.copyfile(tmpfilename, self.projfile)
@@ -472,8 +472,7 @@ def save(self, projfile=None):
return
-
- def plot (self, xItem, yItems, Ids, shift = 1.0, dry=False):
+ def plot(self, xItem, yItems, Ids, shift=1.0, dry=False):
"""Make a 2D plot
xItem -- x data item name
@@ -483,24 +482,25 @@ def plot (self, xItem, yItems, Ids, shift = 1.0, dry=False):
dry -- not a real plot, only check if plot is valid
"""
from diffpy.pdfgui.control.plotter import Plotter
+
plotter = Plotter()
plotter.plot(xItem, yItems, Ids, shift, dry)
self.plots.append(plotter)
def start(self, IDlist):
- """execute Calculations and Fittings in IDlist.
- """
+ """execute Calculations and Fittings in IDlist."""
self.redirectStdout()
- fits = [ ID for ID in IDlist if isinstance(ID, Fitting) ]
+ fits = [ID for ID in IDlist if isinstance(ID, Fitting)]
# only add calcs which is not in fits, because fits will automatically run calcs under it anyway
- calcs = [ ID for ID in IDlist if isinstance(ID, Calculation) and ID.owner not in fits]
+ calcs = [
+ ID for ID in IDlist if isinstance(ID, Calculation) and ID.owner not in fits
+ ]
for calc in calcs:
calc.start()
self.enqueue(fits)
def stop(self):
- """stop all Fittings
- """
+ """stop all Fittings"""
self.enqueue(self.fits, False)
for id in self.fits:
if isinstance(id, Fitting):
@@ -517,6 +517,7 @@ def redirectStdout(self):
This redirect engine output to StringIO if not done yet.
"""
from diffpy.pdffit2 import redirect_stdout, output
+
if output.stdout is sys.stdout:
redirect_stdout(six.StringIO())
return
@@ -524,12 +525,16 @@ def redirectStdout(self):
def getEngineOutput(self):
"""Get the output from the engine."""
from diffpy.pdffit2 import output, redirect_stdout
+
txt = output.stdout.getvalue()
output.stdout.close()
redirect_stdout(six.StringIO())
return txt
+
_pdfguicontrol = None
+
+
def pdfguicontrol(*args, **kwargs):
"""This function will return the single instance of class PDFGuiControl"""
global _pdfguicontrol
@@ -537,6 +542,7 @@ def pdfguicontrol(*args, **kwargs):
_pdfguicontrol = PDFGuiControl(*args, **kwargs)
return _pdfguicontrol
+
def _importByName(mname, name):
try:
module = __import__(mname, globals(), locals(), [name])
@@ -544,31 +550,34 @@ def _importByName(mname, name):
return None
return getattr(module, name)
+
def _find_global(moduleName, clsName):
- #from diffpy.pdfgui.control.parameter import Parameter
- moduleName = 'diffpy.pdfgui.control.' + moduleName.split('.')[-1]
- m = _importByName(moduleName,clsName)
+ # from diffpy.pdfgui.control.parameter import Parameter
+ moduleName = "diffpy.pdfgui.control." + moduleName.split(".")[-1]
+ m = _importByName(moduleName, clsName)
return m
class CtrlUnpickler:
- '''Occasionally the project file may be generated on a platform where
+ """Occasionally the project file may be generated on a platform where
PYTHONPATH is not correctly set up. CtrlUnpickler will transform the
module path in the project file to be relative to diffpy so that it can
be safely loaded. Only constraints and parameters need this class to un-
pickle.
- '''
+ """
+
@staticmethod
def loads(s):
try:
return pickle.loads(s)
except ImportError as err:
- missedModule = str(err).split(' ')[-1]
- if missedModule.find('pdfgui.control') == -1:
+ missedModule = str(err).split(" ")[-1]
+ if missedModule.find("pdfgui.control") == -1:
raise err
f = six.StringIO(s)
unpickler = pickle.Unpickler(f)
unpickler.find_global = _find_global
return unpickler.load()
+
# End of file
diff --git a/src/diffpy/pdfgui/control/pdfguimacros.py b/src/diffpy/pdfgui/control/pdfguimacros.py
index d522c4c5..91d78ed2 100644
--- a/src/diffpy/pdfgui/control/pdfguimacros.py
+++ b/src/diffpy/pdfgui/control/pdfguimacros.py
@@ -23,8 +23,17 @@
from diffpy.pdfgui.control.controlerrors import ControlValueError
from diffpy.pdfgui.control.fitdataset import FitDataSet
-def makeRSeries(control, fit, maxfirst = None, maxlast = None, maxstep = None,
- minfirst = None, minlast = None, minstep = None):
+
+def makeRSeries(
+ control,
+ fit,
+ maxfirst=None,
+ maxlast=None,
+ maxstep=None,
+ minfirst=None,
+ minlast=None,
+ minstep=None,
+):
"""Make an series of fits with an increasing r-range.
The new fits are appended to the end of any current fits in the control.
@@ -43,35 +52,43 @@ def makeRSeries(control, fit, maxfirst = None, maxlast = None, maxstep = None,
# Check to see if the input values are correct.
# MIN-MIN: FIRST < LAST
- if minfirst is not None and minlast is not None\
- and not minfirst < minlast:
- message = "The first value of the minimum (%.2f)\
+ if minfirst is not None and minlast is not None and not minfirst < minlast:
+ message = (
+ "The first value of the minimum (%.2f)\
\nmust be less than the last value of the\
- \nminimum (%.2f)" % (minfirst, minlast)
+ \nminimum (%.2f)"
+ % (minfirst, minlast)
+ )
raise ControlValueError(message)
# MAX-MAX: FIRST < LAST
- if maxfirst is not None and maxlast is not None\
- and not maxfirst < maxlast:
- message = "The first value of the maximum (%.2f)\
+ if maxfirst is not None and maxlast is not None and not maxfirst < maxlast:
+ message = (
+ "The first value of the maximum (%.2f)\
\nmust be less than the last value of the\
- \nmaximum (%.2f)" % (maxfirst, maxlast)
+ \nmaximum (%.2f)"
+ % (maxfirst, maxlast)
+ )
raise ControlValueError(message)
# MAX > MIN: FIRST-FIRST
- if maxfirst is not None and minfirst is not None\
- and not maxfirst > minfirst:
- message = "The first value of the fit maximum (%.2f)\
+ if maxfirst is not None and minfirst is not None and not maxfirst > minfirst:
+ message = (
+ "The first value of the fit maximum (%.2f)\
\nmust be greater than first value of the fit\
- \nminimum (%.2f)." % (maxfirst, minfirst)
+ \nminimum (%.2f)."
+ % (maxfirst, minfirst)
+ )
raise ControlValueError(message)
# MAX > MIN: LAST-LAST
- if maxlast is not None and minlast is not None\
- and not maxlast > minlast:
- message = "The last value of the fit maximum (%.2f)\
+ if maxlast is not None and minlast is not None and not maxlast > minlast:
+ message = (
+ "The last value of the fit maximum (%.2f)\
\nmust be greater than last value of the fit\
- \nminimum (%.2f)." % (maxlast, minlast)
+ \nminimum (%.2f)."
+ % (maxlast, minlast)
+ )
raise ControlValueError(message)
# STEP > 0
@@ -92,13 +109,15 @@ def makeRSeries(control, fit, maxfirst = None, maxlast = None, maxstep = None,
maxlist = []
minlist = []
if maxfirst is not None:
- if maxstep is None: maxstep = minstep
- maxrange = int((maxlast-maxfirst)/(1.0*maxstep)+1)
- maxlist = [maxfirst + i*maxstep for i in range(maxrange)]
+ if maxstep is None:
+ maxstep = minstep
+ maxrange = int((maxlast - maxfirst) / (1.0 * maxstep) + 1)
+ maxlist = [maxfirst + i * maxstep for i in range(maxrange)]
if minfirst is not None:
- if minstep is None: minstep = maxstep
- minrange = int((minlast-minfirst)/(1.0*minstep)+1)
- minlist = [minfirst + i*minstep for i in range(minrange)]
+ if minstep is None:
+ minstep = maxstep
+ minrange = int((minlast - minfirst) / (1.0 * minstep) + 1)
+ minlist = [minfirst + i * minstep for i in range(minrange)]
# Resize the lists to the length of the shortest
serieslen = min(len(maxlist), len(minlist))
@@ -106,13 +125,13 @@ def makeRSeries(control, fit, maxfirst = None, maxlast = None, maxstep = None,
maxlist = maxlist[:serieslen]
minlist = minlist[:serieslen]
else:
- serieslen = max(len(maxlist), len(minlist))
+ serieslen = max(len(maxlist), len(minlist))
basename = fit.name
fits = []
- newname = ''
- lastname = ''
+ newname = ""
+ lastname = ""
fitcopy = control.copy(fit)
# Duplicate the original fit and change the appropriate parameters.
for i in range(serieslen):
@@ -132,24 +151,30 @@ def makeRSeries(control, fit, maxfirst = None, maxlast = None, maxstep = None,
# Check to see that the values are in bounds and sensical
if fitrmin < ds.rmin or fitrmin >= ds.rmax:
- message = "Fit minimum (%.2f) is outside the data range\
+ message = (
+ "Fit minimum (%.2f) is outside the data range\
\n[%.2f, %.2f].\
- \nAdjust the range of the series."\
- % (fitrmin, ds.rmin, ds.rmax)
+ \nAdjust the range of the series."
+ % (fitrmin, ds.rmin, ds.rmax)
+ )
raise ControlValueError(message)
if fitrmax <= ds.rmin or fitrmax > ds.rmax:
- message = "Fit maximum (%.2f) is outside the data range\
+ message = (
+ "Fit maximum (%.2f) is outside the data range\
\n[%.2f, %.2f].\
- \nAdjust the range of the series."\
- % (fitrmax, ds.rmin, ds.rmax)
+ \nAdjust the range of the series."
+ % (fitrmax, ds.rmin, ds.rmax)
+ )
raise ControlValueError(message)
if fitrmin >= fitrmax:
- message = "Fit minimum (%.2f) is greater than the\
+ message = (
+ "Fit minimum (%.2f) is greater than the\
\nmaximum (%.2f).\
- \nIncrease maxstep or reduce minstep." % (fitrmin, fitrmax)
+ \nIncrease maxstep or reduce minstep."
+ % (fitrmin, fitrmax)
+ )
raise ControlValueError(message)
-
# Set the values if all is well
if minlist:
ds.fitrmin = fitrmin
@@ -164,7 +189,7 @@ def makeRSeries(control, fit, maxfirst = None, maxlast = None, maxstep = None,
# Now paste the copy into the control.
newname = "%s-(%.2f,%.2f)" % (basename, fitrmin, fitrmax)
- o = control.paste(fitcopy, new_name = newname)
+ o = control.paste(fitcopy, new_name=newname)
fits.append(o)
return [f.organization() for f in fits]
@@ -216,7 +241,8 @@ def makeTemperatureSeries(control, fit, paths, temperatures):
st = dataset.getFitSamplingType()
newdataset.setFitSamplingType(st, rstep)
doping = dataset.metadata.get("doping")
- if doping is None: doping = 0.0
+ if doping is None:
+ doping = 0.0
newdataset.metadata["doping"] = doping
newdataset.constraints = copy.deepcopy(dataset.constraints)
@@ -234,11 +260,12 @@ def makeTemperatureSeries(control, fit, paths, temperatures):
# Now paste the copy into the control.
fitnewname = "%s-T%i=%g" % (fitbasename, i + 1, temperatures[i])
- o = control.paste(fitcopy, new_name = fitnewname)
+ o = control.paste(fitcopy, new_name=fitnewname)
fits.append(o)
return [f.organization() for f in fits]
+
# Doping Series
def makeDopingSeries(control, fit, base, dopant, paths, doping):
"""Make a temperature series.
@@ -258,9 +285,9 @@ def makeDopingSeries(control, fit, base, dopant, paths, doping):
base = base.title()
dopant = dopant.title()
if not is_element(base):
- raise ControlValueError("'%s' is not an element!"%base)
+ raise ControlValueError("'%s' is not an element!" % base)
if not is_element(dopant):
- raise ControlValueError("'%s' is not an element!"%dopant)
+ raise ControlValueError("'%s' is not an element!" % dopant)
# Make sure that base and dopant are in the structure file(s)
hasBase = False
@@ -271,7 +298,8 @@ def makeDopingSeries(control, fit, base, dopant, paths, doping):
hasBase = True
if atom.element == dopant:
hasDopant = True
- if hasBase and hasDopant: break
+ if hasBase and hasDopant:
+ break
if not hasBase:
message = "The template structure does not contain the base atom."
@@ -286,7 +314,6 @@ def makeDopingSeries(control, fit, base, dopant, paths, doping):
message = "Can't apply macro to fits with multiple datasets."
raise ControlValueError(message)
-
fits = []
# holds all of the other information about the dataset
fitbasename = fit.name
@@ -317,7 +344,8 @@ def makeDopingSeries(control, fit, base, dopant, paths, doping):
st = dataset.getFitSamplingType()
newdataset.setFitSamplingType(st, rstep)
temperature = dataset.metadata.get("temperature")
- if temperature is None: temperature = 300.0
+ if temperature is None:
+ temperature = 300.0
newdataset.metadata["temperature"] = temperature
newdataset.constraints = copy.deepcopy(dataset.constraints)
@@ -333,8 +361,7 @@ def makeDopingSeries(control, fit, base, dopant, paths, doping):
if A.element == dopant:
A.occupancy = doping[i]
if A.element == base:
- A.occupancy = 1-doping[i]
-
+ A.occupancy = 1 - doping[i]
# Set the parameters to the previous fit's name, if one exists.
if fitlastname:
@@ -344,17 +371,19 @@ def makeDopingSeries(control, fit, base, dopant, paths, doping):
# Now paste the copy into the control.
fitnewname = "%s-%1.4f" % (fitbasename, doping[i])
- o = control.paste(fitcopy, new_name = fitnewname)
+ o = control.paste(fitcopy, new_name=fitnewname)
fits.append(o)
return [f.organization() for f in fits]
+
if __name__ == "__main__":
from diffpy.pdfgui.control.pdfguicontrol import PDFGuiControl
+
control = PDFGuiControl()
control.load("../../tests/testdata/ni.ddp")
fit = control.fits[0]
olist = makeRSeries(control, fit, 5, 20, 5)
- print('\n'.join(f[0].name for f in olist))
+ print("\n".join(f[0].name for f in olist))
# End of file
diff --git a/src/diffpy/pdfgui/control/pdflist.py b/src/diffpy/pdfgui/control/pdflist.py
index 2e5bbe42..00ec4a13 100644
--- a/src/diffpy/pdfgui/control/pdflist.py
+++ b/src/diffpy/pdfgui/control/pdflist.py
@@ -15,10 +15,12 @@
from diffpy.pdfgui.control.controlerrors import ControlKeyError
+
class PDFList(list):
"""list class of PDFComponent, which can be accessed through index or a
name string
"""
+
def __init__(self, *args):
"""Initialize
@@ -93,7 +95,7 @@ def keys(self):
return: list of names
"""
- return [ x.name for x in self ]
+ return [x.name for x in self]
def values(self):
"""Get all held objects
@@ -107,6 +109,7 @@ def items(self):
return: a list of tuple ( name, object)
"""
- return [ (x.name, x) for x in self ]
+ return [(x.name, x) for x in self]
+
# End of file
diff --git a/src/diffpy/pdfgui/control/pdfstructure.py b/src/diffpy/pdfgui/control/pdfstructure.py
index 67839f12..12e383c4 100644
--- a/src/diffpy/pdfgui/control/pdfstructure.py
+++ b/src/diffpy/pdfgui/control/pdfstructure.py
@@ -18,8 +18,7 @@
from diffpy.structure import PDFFitStructure
from diffpy.pdfgui.control.pdfcomponent import PDFComponent
-from diffpy.pdfgui.control.controlerrors import \
- ControlKeyError, ControlFileError
+from diffpy.pdfgui.control.controlerrors import ControlKeyError, ControlFileError
class PDFStructure(PDFComponent, PDFFitStructure):
@@ -36,8 +35,7 @@ def __init__(self, name, *args, **kwargs):
PDFFitStructure.__init__(self, *args, **kwargs)
return
-
- def read(self, filename, format='auto'):
+ def read(self, filename, format="auto"):
"""Load structure from a file, raise ControlFileError for invalid
or unknown structure format.
@@ -49,16 +47,16 @@ def read(self, filename, format='auto'):
See Structure.read() for more info.
"""
from diffpy.structure import StructureFormatError
+
try:
p = PDFFitStructure.read(self, filename, format)
except StructureFormatError as err:
import os.path
- emsg = "Unable to read file '%s'\n%s." % (
- os.path.basename(filename), err)
+
+ emsg = "Unable to read file '%s'\n%s." % (os.path.basename(filename), err)
raise ControlFileError(emsg)
return p
-
def copy(self, other=None):
"""copy self to other. if other is None, create an instance
@@ -73,12 +71,11 @@ def copy(self, other=None):
other[:] = copy.deepcopy(self[:])
return other
-
# dictionary of allowed keys from self.pdffit dictionary,
# that can be used in setvar and getvar methods.
- _allowed_pdffit_vars = dict.fromkeys(('spdiameter', 'stepcut',
- 'delta1', 'delta2', 'sratio', 'rcut'))
-
+ _allowed_pdffit_vars = dict.fromkeys(
+ ("spdiameter", "stepcut", "delta1", "delta2", "sratio", "rcut")
+ )
def setvar(self, var, value):
"""assign to data member using PdfFit-style variable
@@ -93,29 +90,29 @@ def setvar(self, var, value):
"""
barevar = var.strip()
fvalue = float(value)
- parenthesis = re.match(r'^(\w+)\((\d+)\)$', barevar)
+ parenthesis = re.match(r"^(\w+)\((\d+)\)$", barevar)
# common error message
emsg = "Invalid PdfFit phase variable %r" % barevar
- if barevar in ('pscale'):
- self.pdffit['scale'] = fvalue
+ if barevar in ("pscale"):
+ self.pdffit["scale"] = fvalue
elif barevar in PDFStructure._allowed_pdffit_vars:
self.pdffit[barevar] = fvalue
- elif barevar == 'lat(1)':
+ elif barevar == "lat(1)":
self.lattice.setLatPar(a=fvalue)
- elif barevar == 'lat(2)':
+ elif barevar == "lat(2)":
self.lattice.setLatPar(b=fvalue)
- elif barevar == 'lat(3)':
+ elif barevar == "lat(3)":
self.lattice.setLatPar(c=fvalue)
- elif barevar == 'lat(4)':
+ elif barevar == "lat(4)":
self.lattice.setLatPar(alpha=fvalue)
- elif barevar == 'lat(5)':
+ elif barevar == "lat(5)":
self.lattice.setLatPar(beta=fvalue)
- elif barevar == 'lat(6)':
+ elif barevar == "lat(6)":
self.lattice.setLatPar(gamma=fvalue)
elif parenthesis:
pvar = parenthesis.group(1)
idx = int(parenthesis.group(2))
- atom = self[idx-1]
+ atom = self[idx - 1]
if pvar == "x":
atom.xyz[0] = fvalue
elif pvar == "y":
@@ -125,15 +122,14 @@ def setvar(self, var, value):
elif pvar == "occ":
atom.occupancy = fvalue
elif pvar in ("u11", "u22", "u33", "u12", "u13", "u23"):
- i, j = int(pvar[1]) - 1, int(pvar[2]) - 1
- atom.U[i,j], atom.U[j,i] = fvalue, fvalue
+ i, j = int(pvar[1]) - 1, int(pvar[2]) - 1
+ atom.U[i, j], atom.U[j, i] = fvalue, fvalue
else:
raise ControlKeyError(emsg)
else:
raise ControlKeyError(emsg)
return
-
def getvar(self, var):
"""obtain value corresponding to PdfFit phase variable var
This can be used when guessing Parameter values from constraints
@@ -147,29 +143,29 @@ def getvar(self, var):
returns value of var
"""
barevar = var.strip()
- parenthesis = re.match(r'^(\w+)\((\d+)\)$', barevar)
+ parenthesis = re.match(r"^(\w+)\((\d+)\)$", barevar)
# common error message
emsg = "Invalid PdfFit phase variable %r" % barevar
- if barevar in ('pscale'):
- value = self.pdffit['scale']
+ if barevar in ("pscale"):
+ value = self.pdffit["scale"]
elif barevar in PDFStructure._allowed_pdffit_vars:
value = self.pdffit[barevar]
- elif barevar == 'lat(1)':
+ elif barevar == "lat(1)":
value = self.lattice.a
- elif barevar == 'lat(2)':
+ elif barevar == "lat(2)":
value = self.lattice.b
- elif barevar == 'lat(3)':
+ elif barevar == "lat(3)":
value = self.lattice.c
- elif barevar == 'lat(4)':
+ elif barevar == "lat(4)":
value = self.lattice.alpha
- elif barevar == 'lat(5)':
+ elif barevar == "lat(5)":
value = self.lattice.beta
- elif barevar == 'lat(6)':
+ elif barevar == "lat(6)":
value = self.lattice.gamma
elif parenthesis:
pvar = parenthesis.group(1)
idx = int(parenthesis.group(2))
- atom = self[idx-1]
+ atom = self[idx - 1]
if pvar == "x":
value = atom.xyz[0]
elif pvar == "y":
@@ -179,8 +175,8 @@ def getvar(self, var):
elif pvar == "occ":
value = atom.occupancy
elif pvar in ("u11", "u22", "u33", "u12", "u13", "u23"):
- i, j = int(pvar[1]) - 1, int(pvar[2]) - 1
- value = atom.U[i,j]
+ i, j = int(pvar[1]) - 1, int(pvar[2]) - 1
+ value = atom.U[i, j]
else:
raise ControlKeyError(emsg)
else:
@@ -189,6 +185,7 @@ def getvar(self, var):
value = float(value)
return value
+
# End of class PDFStructure
# End of file
diff --git a/src/diffpy/pdfgui/control/plotter.py b/src/diffpy/pdfgui/control/plotter.py
index c7697e31..d475e2a2 100644
--- a/src/diffpy/pdfgui/control/plotter.py
+++ b/src/diffpy/pdfgui/control/plotter.py
@@ -19,43 +19,69 @@
from diffpy.pdfgui.gui.extendedplotframe import ExtendedPlotFrame
# Preset plotting style
-colors = ("red","blue","magenta","cyan","green","yellow", #"black",
- "darkRed", "darkBlue","darkMagenta", "darkCyan", "darkGreen","darkYellow")
-lines = ('solid','dash','dot','dashDot')
-symbols = ("circle","square","triangle","diamond")#,"cross","xCross")
+colors = (
+ "red",
+ "blue",
+ "magenta",
+ "cyan",
+ "green",
+ "yellow", # "black",
+ "darkRed",
+ "darkBlue",
+ "darkMagenta",
+ "darkCyan",
+ "darkGreen",
+ "darkYellow",
+)
+lines = ("solid", "dash", "dot", "dashDot")
+symbols = ("circle", "square", "triangle", "diamond") # ,"cross","xCross")
# this is to map 'r' to what it is supposed to be. For example, when user asks
# for plotting 'Gobs' against 'r', the real data objects are 'Gobs' and 'robs'
-transdict = { 'Gobs':'robs',
- 'Gcalc':'rcalc','Gdiff':'rcalc','Gtrunc':'rcalc','crw':'rcalc'}
-baselineStyle = {'with':'lines','line':'solid','color':'black','width':1, 'legend':'_nolegend_'}
+transdict = {
+ "Gobs": "robs",
+ "Gcalc": "rcalc",
+ "Gdiff": "rcalc",
+ "Gtrunc": "rcalc",
+ "crw": "rcalc",
+}
+baselineStyle = {
+ "with": "lines",
+ "line": "solid",
+ "color": "black",
+ "width": 1,
+ "legend": "_nolegend_",
+}
+
def _transName(name):
- '''translate name of y object
+ """translate name of y object
This is mainly for plotting of parameters. GUI will pass in a integer to
indicate which parameter to be plotted. However, in data storage the
parameter is denoted as '@n'
name -- name of data item
- '''
+ """
if isinstance(name, int):
- rv = '@' + str(name)
+ rv = "@" + str(name)
else:
rv = str(name)
return rv
def _fullName(dataId):
- '''construct full name'''
+ """construct full name"""
from diffpy.pdfgui.control.fitting import Fitting
- if hasattr(dataId, 'owner') and isinstance(dataId.owner, Fitting):
+
+ if hasattr(dataId, "owner") and isinstance(dataId.owner, Fitting):
return _fullName(dataId.owner) + "/" + dataId.name
else:
return dataId.name
+
def _buildStyle(plotter, name, group, yNames):
- '''trying to figure out a good style
+ """trying to figure out a good style
1. generally we want line style for Gcalc, Gdiff, crw, symbol style for Gobs,
and line-symbol style for the rest
@@ -66,45 +92,47 @@ def _buildStyle(plotter, name, group, yNames):
group -- which group the curve is in (group = -1 means it is the only group)
yNames -- all y to be plotted
return: style dictionay
- '''
- if name in ('Gcalc', 'Gdiff', 'crw'):
+ """
+ if name in ("Gcalc", "Gdiff", "crw"):
style = plotter.buildLineStyle()
- style['line'] = 'solid'
- elif name in ('Gobs', 'Gtrunc'):
+ style["line"] = "solid"
+ elif name in ("Gobs", "Gtrunc"):
style = plotter.buildSymbolStyle()
# Use open circle always
- style['symbolColor'] = 'white'
- style['symbol'] = 'circle'
- style['symbolSize'] = 6
+ style["symbolColor"] = "white"
+ style["symbol"] = "circle"
+ style["symbolSize"] = 6
else:
style = plotter.buildLineSymbolStyle()
- style['line'] = 'dash'
- style['symbol'] = 'circle'
- style['symbolSize'] = 8
+ style["line"] = "dash"
+ style["symbol"] = "circle"
+ style["symbolSize"] = 8
# We only care about how to arrange Gdiff Gobs Gcalc Gtrunc crw nicely
if group < 0:
# use fixed style for single PDFFit picture
- if name == 'Gcalc':
- style['color'] = 'red'
- elif name in ('Gobs', 'Gtrunc'):
- style['color'] = 'blue'
- elif name in ('Gdiff', 'crw'):
- style['color'] = 'green'
+ if name == "Gcalc":
+ style["color"] = "red"
+ elif name in ("Gobs", "Gtrunc"):
+ style["color"] = "blue"
+ elif name in ("Gdiff", "crw"):
+ style["color"] = "green"
else:
# make sure Gdiff, Gtrunc, Gobs, crw are having same color
- if name in ('Gobs', 'Gtrunc', 'Gdiff', 'Gcalc', 'crw'):
- style['color'] = colors[group%len(colors)]
- if name == 'Gcalc':
+ if name in ("Gobs", "Gtrunc", "Gdiff", "Gcalc", "crw"):
+ style["color"] = colors[group % len(colors)]
+ if name == "Gcalc":
# for visual effect, change Gcalc to black if it's going to be plotted against Gobs/Gtrunc
- if 'Gobs' in yNames or 'Gtrunc' in yNames:
- style['color'] = 'black'
+ if "Gobs" in yNames or "Gtrunc" in yNames:
+ style["color"] = "black"
return style
+
class Plotter(PDFComponent):
- """Plots a single graph. It can have multiple curves. """
+ """Plots a single graph. It can have multiple curves."""
+
__plotWindowNumber = 1
class Curve:
@@ -133,6 +161,7 @@ class Curve:
initialized -- if curve has been inserted
dataChanged -- if curve data has changed
"""
+
def __init__(self, name, plotwnd, xStr, yStr, steps, ids, offset, style):
"""initialize
@@ -169,24 +198,24 @@ def __init__(self, name, plotwnd, xStr, yStr, steps, ids, offset, style):
self.initialized = False
self.dataChanged = False
- #validate user's choice
+ # validate user's choice
self.validate()
def validate(self):
- """ validate(self) --> check if the curve is valid. Validity
+ """validate(self) --> check if the curve is valid. Validity
is broken:
(1) when xStr or yStr doesn't refer to a legal vector
(2) when sizes of xStr and yStr don't match
"""
bItemIsVector = False
- if self.xStr in ('r', 'rcalc', 'robs'):
- if self.yStr not in ('Gobs', 'Gcalc', 'Gdiff', 'Gtrunc','crw'):
+ if self.xStr in ("r", "rcalc", "robs"):
+ if self.yStr not in ("Gobs", "Gcalc", "Gdiff", "Gtrunc", "crw"):
emsg = "x={}, y={} don't match".format(self.xStr, self.yStr)
raise ControlConfigError(emsg)
bItemIsVector = True
- elif self.xStr in ('Gobs', 'Gcalc', 'Gdiff', 'Gtrunc','crw'):
+ elif self.xStr in ("Gobs", "Gcalc", "Gdiff", "Gtrunc", "crw"):
raise ControlConfigError("%s can't be x axis" % self.xStr)
- elif self.yStr in ('Gobs', 'Gcalc', 'Gdiff', 'Gtrunc','crw'):
+ elif self.yStr in ("Gobs", "Gcalc", "Gdiff", "Gtrunc", "crw"):
# Get called when x is not r but y is not Gobs, Gtrunc Gdiff...
raise ControlConfigError("%s can only be plotted against r" % self.yStr)
@@ -196,19 +225,23 @@ def validate(self):
# (3) self.allSteps
# The logic below make sure only one of them can be true.
if bItemIsVector:
- if self.bMultiData or self.bMultiStep:
- emsg = ("({}, {}) can't be plotted with multiple "
- "refinements/steps").format(self.xStr, self.yStr)
+ if self.bMultiData or self.bMultiStep:
+ emsg = (
+ "({}, {}) can't be plotted with multiple " "refinements/steps"
+ ).format(self.xStr, self.yStr)
raise ControlConfigError(emsg)
else:
- if not self.bMultiData and not self.bMultiStep:
- raise ControlConfigError("(%s, %s) is a single point" % (self.xStr, self.yStr))
+ if not self.bMultiData and not self.bMultiStep:
+ raise ControlConfigError(
+ "(%s, %s) is a single point" % (self.xStr, self.yStr)
+ )
elif self.bMultiData and self.bMultiStep:
- emsg = ("({}, {}) can't be plotted with both multiple "
- "refinements and multiple steps").format(self.xStr, self.yStr)
+ emsg = (
+ "({}, {}) can't be plotted with both multiple "
+ "refinements and multiple steps"
+ ).format(self.xStr, self.yStr)
raise ControlConfigError(emsg)
-
def notify(self, changedIds=None, plotwnd=None):
"""notify Curve object certain data is updated
@@ -226,7 +259,7 @@ def notify(self, changedIds=None, plotwnd=None):
affectedIds.append(id)
break
- #If the change doesn't affect any id, do nothing
+ # If the change doesn't affect any id, do nothing
if not affectedIds:
return False
else:
@@ -234,11 +267,11 @@ def notify(self, changedIds=None, plotwnd=None):
# translation may be required
xStr = self.xStr
- if xStr == 'r':
+ if xStr == "r":
xStr = transdict.get(self.yStr, xStr)
if self.bMultiData:
- #Local list is maintained here
+ # Local list is maintained here
if self.xData is None:
self.xData = [None] * len(self.ids)
if self.yData is None:
@@ -246,23 +279,23 @@ def notify(self, changedIds=None, plotwnd=None):
for id in affectedIds:
i = self.ids.index(id)
self.yData[i] = id.getData(self.yStr, -1)
- if xStr == 'step':
+ if xStr == "step":
raise AssertionError("Can not plot against step")
- elif xStr == 'index':
+ elif xStr == "index":
self.xData[i] = i
else:
self.xData[i] = id.getData(xStr, -1)
else:
# affectedIds has only one member
- if self.bMultiStep:
- steps = None # None to get the whole steps
+ if self.bMultiStep:
+ steps = None # None to get the whole steps
else:
- steps = -1 #
+ steps = -1 #
# plot multiple refinement steps for a single dataId
# in deed, the reference is not gonna change
self.yData = affectedIds[0].getData(self.yStr, steps)
- if xStr == 'step':
+ if xStr == "step":
if self.yData is None:
self.xData = None
else:
@@ -276,10 +309,10 @@ def notify(self, changedIds=None, plotwnd=None):
def _shift(y):
return y + self.offset
- if self.yData and self.offset: # not zero
+ if self.yData and self.offset: # not zero
self.yData = [_shift(yi) for yi in self.yData]
- if self.xData and self.yData: # not empty or None
+ if self.xData and self.yData: # not empty or None
return self.draw()
else:
return False
@@ -293,7 +326,7 @@ def draw(self):
# used for plotting
xs = []
ys = []
- plotData = sorted(zip(self.xData,self.yData))
+ plotData = sorted(zip(self.xData, self.yData))
for x, y in plotData:
if x is not None and y is not None:
xs.append(x)
@@ -310,7 +343,7 @@ def draw(self):
# If it can get here, data is ready now.
if self.ref is None:
self.ref = self.plotwnd.insertCurve(xs, ys, self.style)
- if self.yStr == 'Gdiff':
+ if self.yStr == "Gdiff":
# add a baseline for any Gdiff
rs = self.ids[0].rcalc
if not rs:
@@ -318,7 +351,9 @@ def draw(self):
hMin = min(rs)
hMax = max(rs)
- self.plotwnd.insertCurve([hMin, hMax], [self.offset, self.offset], baselineStyle)
+ self.plotwnd.insertCurve(
+ [hMin, hMax], [self.offset, self.offset], baselineStyle
+ )
else:
# update only
self.plotwnd.updateData(self.ref, xs, ys)
@@ -331,21 +366,24 @@ def __init__(self, name=None):
name -- name of plot
"""
if name is None:
- name = 'Plot [%i]' % Plotter.__plotWindowNumber
+ name = "Plot [%i]" % Plotter.__plotWindowNumber
PDFComponent.__init__(self, name)
import threading
+
self.lock = threading.RLock()
self.curves = []
self.window = None
self.isShown = False
from diffpy.pdfgui.control.pdfguicontrol import pdfguicontrol
+
self.controlCenter = pdfguicontrol()
# add some flavor by starting with random style
import random
- self.symbolStyleIndex = random.randint(0,100)
- self.lineStyleIndex = random.randint(0,100)
+
+ self.symbolStyleIndex = random.randint(0, 100)
+ self.lineStyleIndex = random.randint(0, 100)
return
def close(self, force=True):
@@ -354,13 +392,12 @@ def close(self, force=True):
force -- if True, close forcibly
"""
if self.window is not None:
- #self.window.Close(True)
+ # self.window.Close(True)
self.window.Destroy()
self.window = None
def onWindowClose(self):
- """get called when self.window is closed by user
- """
+ """get called when self.window is closed by user"""
self.window = None
try:
self.controlCenter.plots.remove(self)
@@ -381,11 +418,13 @@ def buildSymbolStyle(self, index=-1):
symbolIndex = i % len(symbols)
colorIndex = i % len(colors)
- return {'with':'points',
- 'color':colors[colorIndex],
- 'symbolColor':colors[colorIndex],
- 'symbol':symbols[symbolIndex],
- 'symbolSize':3}
+ return {
+ "with": "points",
+ "color": colors[colorIndex],
+ "symbolColor": colors[colorIndex],
+ "symbol": symbols[symbolIndex],
+ "symbolSize": 3,
+ }
def buildLineStyle(self, index=-1):
"""generate a line style
@@ -400,10 +439,12 @@ def buildLineStyle(self, index=-1):
lineIndex = i % len(lines)
colorIndex = i % len(colors)
- return {'with':'lines',
- 'color':colors[colorIndex],
- 'line':lines[lineIndex],
- 'width':2}
+ return {
+ "with": "lines",
+ "color": colors[colorIndex],
+ "line": lines[lineIndex],
+ "width": 2,
+ }
def buildLineSymbolStyle(self, index=-1):
"""generate a linesymbol style
@@ -412,10 +453,10 @@ def buildLineSymbolStyle(self, index=-1):
"""
style = self.buildLineStyle(index)
style.update(self.buildSymbolStyle(index))
- style['with'] = 'linespoints'
+ style["with"] = "linespoints"
return style
- def plot(self, xName, yNames, ids, shift, dry):
+ def plot(self, xName, yNames, ids, shift, dry):
"""Make a 2D plot
xName -- x data item name
@@ -424,12 +465,15 @@ def plot(self, xName, yNames, ids, shift, dry):
shift -- y spacing for different ids
dry -- dry run
"""
+
def _addCurve(dataIds):
# Identify the plot type. This is used to automatically modify
# 'Gdiff' and 'crw' in certain types of plots.
yset = set(yNames)
- if 'Gdiff' in yset: yset.remove('Gdiff')
- if 'crw' in yset: yset.remove('crw')
+ if "Gdiff" in yset:
+ yset.remove("Gdiff")
+ if "crw" in yset:
+ yset.remove("crw")
# add yNames one by one for given dataIds
for y in yNames:
@@ -438,7 +482,7 @@ def _addCurve(dataIds):
style = None
if not dry:
if len(dataIds) == 1 and group != -1:
- #legend = dataIds[0].name + ": " + _transName(y)
+ # legend = dataIds[0].name + ": " + _transName(y)
legend = _fullName(dataIds[0]) + ": " + _transName(y)
else:
# 1.Group = -1, multiple ids give a single curve
@@ -446,19 +490,20 @@ def _addCurve(dataIds):
legend = _transName(y)
style = _buildStyle(self, y, group, yNames)
- style['legend'] = legend
+ style["legend"] = legend
# automatically apply offset if we're plotting more than
# just 'Gdiff' and 'crw'
- if y in ('Gdiff','crw') and group == -1 and len(yset) > 0:
+ if y in ("Gdiff", "crw") and group == -1 and len(yset) > 0:
_offset = shift
- #Create curve, get data for it and update it in the plot
- curve = Plotter.Curve(legend, self.window, xName, y,
- step, dataIds, _offset, style)
+ # Create curve, get data for it and update it in the plot
+ curve = Plotter.Curve(
+ legend, self.window, xName, y, step, dataIds, _offset, style
+ )
self.curves.append(curve)
return
- if not ids: # empty
+ if not ids: # empty
raise ControlConfigError("Plotter: No data is selected")
if not yNames:
raise ControlConfigError("Plotter: No y item is selected")
@@ -466,22 +511,22 @@ def _addCurve(dataIds):
# bSeparateID indicates if we want data from different ID to be
# plotted in different curve or not
bSeparateID = False
- if len(ids) > 1 and xName in ('r', 'rcalc', 'step'):
+ if len(ids) > 1 and xName in ("r", "rcalc", "step"):
# multi ID and within each ID we wants a vector, so curve can
# only be plotted separately.
bSeparateID = True
# set up the step
- if xName == 'step':
+ if xName == "step":
step = None
else:
step = -1
self.curves = []
- if 'Gcalc' in yNames:
- yNames.remove('Gcalc')
- yNames.append('Gcalc')
+ if "Gcalc" in yNames:
+ yNames.remove("Gcalc")
+ yNames.append("Gcalc")
# default is no shift, single group.
offset = 0.0
@@ -489,7 +534,11 @@ def _addCurve(dataIds):
if bSeparateID:
for id in ids:
group += 1
- _addCurve([id,])
+ _addCurve(
+ [
+ id,
+ ]
+ )
offset += shift
else:
_addCurve(ids)
@@ -509,22 +558,22 @@ def _addCurve(dataIds):
self.window.clear()
for curve in self.curves:
- #Initial notification, don't plot immediately, wait for last line to be added
- #This is to optimize plotting multiple curves.
+ # Initial notification, don't plot immediately, wait for last line to be added
+ # This is to optimize plotting multiple curves.
curve.notify(plotwnd=self.window)
# make the graph title, x, y label
yStrs = [_transName(yName) for yName in yNames]
- if yStrs[0].startswith('G'):
- #then all are Gs
- yLabel = 'G'
+ if yStrs[0].startswith("G"):
+ # then all are Gs
+ yLabel = "G"
else:
- yLabel = ','.join(yStrs)
- title = ''
+ yLabel = ",".join(yStrs)
+ title = ""
if len(ids) == 1:
- title = ids[0].name + ': '
+ title = ids[0].name + ": "
title += yLabel
- self.window.setTitle(self.name+' '+title, title)
+ self.window.setTitle(self.name + " " + title, title)
self.window.setXLabel(_transName(xName))
self.window.setYLabel(yLabel)
@@ -532,8 +581,7 @@ def _addCurve(dataIds):
self.window.replot()
self.show(True)
-
- def show(self, bShow=None) :
+ def show(self, bShow=None):
"""show the plot on screen
bShow -- True to show, False to Hide. None to toggle
@@ -544,51 +592,56 @@ def show(self, bShow=None) :
if bShow is None:
bShow = not self.isShown
self.window.Show(bShow)
- if bShow: # True
+ if bShow: # True
# further bring it to top
self.window.Raise()
self.isShown = bShow
return self.isShown
def notify(self, data):
- '''change of the data is notified
+ """change of the data is notified
data -- data object that has changed
- '''
+ """
if not self.curves or self.window is None:
return
ret = False
for curve in self.curves:
- ret |= (curve.notify(changedIds=[data,]))
+ ret |= curve.notify(
+ changedIds=[
+ data,
+ ]
+ )
if ret:
self.window.replot()
def export(self, filename):
- '''export current data to external file
+ """export current data to external file
filename -- the name of the file to save data
- '''
+ """
# Check if any curve
if len(self.curves) == 0:
return
import time, getpass
- outfile = open(filename, 'w')
+
+ outfile = open(filename, "w")
header = "# Generated on %s by %s.\n" % (time.ctime(), getpass.getuser())
header += "# This file was created by PDFgui.\n"
outfile.write(header)
- deblank = lambda s: ''.join(s.split())
+ deblank = lambda s: "".join(s.split())
xylist = [(c.x, c.y) for c in self.curves]
- xynames = [(_transName(c.xStr), deblank(c.name))
- for c in self.curves]
+ xynames = [(_transName(c.xStr), deblank(c.name)) for c in self.curves]
_exportCompactData(outfile, xylist, xynames)
outfile.close()
return
+
# End of class Plotter
def _exportCompactData(fp, xylist, xynames=None):
- '''Write the xylist data in a text format to the file object fp.
+ """Write the xylist data in a text format to the file object fp.
The curves with the same x are groupped in the same datasets.
The datasets are marked with "#S 1", "#S 2", etc. labels according
to the spec format http://www.certif.com/cplot_manual/ch0c_C_11_3.html
@@ -600,17 +653,19 @@ def _exportCompactData(fp, xylist, xynames=None):
used as a header in the dataset blocks.
No return value.
- '''
- dataformat = '%g'
+ """
+ dataformat = "%g"
# build the default xynames:
if xynames is None:
- xynames = [('x%i' % i, 'y%i' % i) for i in range(len(xylist))]
+ xynames = [("x%i" % i, "y%i" % i) for i in range(len(xylist))]
datasets = []
datanames = []
xt2idx = {}
for ((x, y), (xn, yn)) in zip(xylist, xynames):
- if x is None or not len(x): continue
- if y is None or not len(y): continue
+ if x is None or not len(x):
+ continue
+ if y is None or not len(y):
+ continue
xt = tuple(x)
i = xt2idx.setdefault(xt, len(xt2idx))
if not i < len(datasets):
@@ -626,14 +681,15 @@ def _exportCompactData(fp, xylist, xynames=None):
for i, (ds, dn) in enumerate(zip(datasets, datanames)):
# separate datasets with a blank line:
if i > 0:
- fp.write('\n')
- fp.write('#S %i\n' % (i + 1))
- fp.write('#L %s\n' % (' '.join(dn)))
+ fp.write("\n")
+ fp.write("#S %i\n" % (i + 1))
+ fp.write("#L %s\n" % (" ".join(dn)))
ncols = len(ds)
- fmt = ' '.join(ncols * [dataformat]) + '\n'
+ fmt = " ".join(ncols * [dataformat]) + "\n"
for cols in zip(*ds):
line = fmt % cols
fp.write(line)
return
+
# End of file
diff --git a/src/diffpy/pdfgui/control/structureviewer.py b/src/diffpy/pdfgui/control/structureviewer.py
index 2f52d1a3..5a064222 100644
--- a/src/diffpy/pdfgui/control/structureviewer.py
+++ b/src/diffpy/pdfgui/control/structureviewer.py
@@ -27,15 +27,14 @@
def getStructureViewer():
- """Factory returning singleton instance of the StructureViewer class.
- """
+ """Factory returning singleton instance of the StructureViewer class."""
global _struviewer
if _struviewer is None:
_struviewer = StructureViewer()
return _struviewer
-_struviewer = None
+_struviewer = None
class StructureViewer(object):
@@ -62,7 +61,6 @@ class StructureViewer(object):
_plotcount -- Number of plots created by this viewer.
"""
-
def __init__(self, executable=None, argstr=None, fileformat=None):
"""Create StructureViewer instance. All arguments are optional,
they override defaults described in class docstring. The
@@ -76,9 +74,9 @@ def __init__(self, executable=None, argstr=None, fileformat=None):
fileformat -- structure format supported by diffpy.structure package.
"""
# declare instance data
- self.executable = ''
- self.argstr = '%s'
- self.fileformat = 'pdb'
+ self.executable = ""
+ self.argstr = "%s"
+ self.fileformat = "pdb"
self._tmpdir = None
self._plotcount = 0
# process arguments:
@@ -91,19 +89,17 @@ def __init__(self, executable=None, argstr=None, fileformat=None):
# finish every method with return
return
-
def getConfig(self):
"""Return current configuration of StructureViewer instance.
Returns new dictionary with the following keys:
('executable', 'argstr', 'fileformat')
"""
- cfgkeys = ('executable', 'argstr', 'fileformat')
+ cfgkeys = ("executable", "argstr", "fileformat")
kv = [(k, getattr(self, k)) for k in cfgkeys]
rv = dict(kv)
return rv
-
def setConfig(self, cfg):
"""Configure StructureViewer instance using values in a dictionary.
@@ -114,17 +110,17 @@ def setConfig(self, cfg):
"""
# iterate over keys from getConfig dictionary
for k in self.getConfig():
- if k in cfg: setattr(self, k, cfg[k])
+ if k in cfg:
+ setattr(self, k, cfg[k])
return
-
def getFileFormats():
- """Return list of valid values for the fileformat attribute.
- """
+ """Return list of valid values for the fileformat attribute."""
from diffpy.structure.parsers import outputFormats
+
return outputFormats()
- getFileFormats = staticmethod(getFileFormats)
+ getFileFormats = staticmethod(getFileFormats)
def plot(self, stru):
"""Launch new structure viewer and open a temporary copy of stru.
@@ -135,6 +131,7 @@ def plot(self, stru):
Raise ControlConfigError if structure viewer could not be launched.
"""
import subprocess
+
# check if executable has been set
if not self.executable:
emsg = "StructureViewer program has not been set."
@@ -145,24 +142,23 @@ def plot(self, stru):
try:
subprocess.Popen(args)
except OSError as err:
- emsg = ('Error executing StructureViewer %s: %s' %
- (self.executable, err))
+ emsg = "Error executing StructureViewer %s: %s" % (self.executable, err)
raise ControlConfigError(emsg)
return
-
def __del__(self):
- """Remove temporary files created by this instance of StructureViewer.
- """
+ """Remove temporary files created by this instance of StructureViewer."""
# short circuit if nothing has been created
- if self._tmpdir is None: return
+ if self._tmpdir is None:
+ return
# Function for showing unremovable files
def onerror(fnc, path, error):
- print(('Cannot remove %s - %s' % (path, error)), file=sys.stderr)
+ print(("Cannot remove %s - %s" % (path, error)), file=sys.stderr)
return
+
# For safety remove _tmpdir subdirectories by their names
for i in range(self._plotcount):
- di = os.path.join(self._tmpdir, '%04i' % i)
+ di = os.path.join(self._tmpdir, "%04i" % i)
shutil.rmtree(di, True, onerror)
# finally remove _tmpdir, which should now be empty
try:
@@ -172,7 +168,6 @@ def onerror(fnc, path, error):
pass
return
-
def _getArgumentList(self, strupath):
"""Convert self.argstr to a list of string arguments.
@@ -183,12 +178,13 @@ def _getArgumentList(self, strupath):
"""
import shlex
import re
+
# make sure shlex.split is not called with None, because
# it would read standard input
- s = self.argstr and self.argstr or ''
+ s = self.argstr and self.argstr or ""
args = shlex.split(s)
# substitute strupath in args using % operator
- pat = re.compile(r'(?'
+eqmark = ""
##############################################################################
# business
@@ -21,6 +21,8 @@
import re
eqcnt = 0
+
+
def eqreplace(mx):
"""helper function to replace equation marks.
@@ -31,10 +33,11 @@ def eqreplace(mx):
global eqcnt
eqcnt += 1
imgfile = "eq-%02i.png" % eqcnt
- imgurl = os.path.join(rc['directory'], imgfile)
+ imgurl = os.path.join(rc["directory"], imgfile)
s = '
' % (imgurl, imgurl)
return s
+
def replaceEquationMarks(s):
"""Replace equation marks in given string.
Return modified string.
@@ -42,13 +45,14 @@ def replaceEquationMarks(s):
s1 = re.sub(eqmark, eqreplace, s)
return s1
+
def main():
for f in sys.argv[1:]:
with open(f) as fp:
s = fp.read()
s1 = replaceEquationMarks(s)
if s1 != s:
- with open(f, 'w') as fpout:
+ with open(f, "w") as fpout:
fpout.write(s1)
diff --git a/src/diffpy/pdfgui/doc/tutorial/tui_mno_bond_lengths.py b/src/diffpy/pdfgui/doc/tutorial/tui_mno_bond_lengths.py
index db20e57b..d6d4e4bd 100755
--- a/src/diffpy/pdfgui/doc/tutorial/tui_mno_bond_lengths.py
+++ b/src/diffpy/pdfgui/doc/tutorial/tui_mno_bond_lengths.py
@@ -1,15 +1,15 @@
#!/usr/bin/env python
-'''Extract the shortest Mn-O bond lengths from all fits in PDFgui project.
+"""Extract the shortest Mn-O bond lengths from all fits in PDFgui project.
This script loops through all refined phases in PDFgui project and calculates
their shortest Mn-O bond lengths using diffpy.pdffit2 library. The results
are plotted versus temperature and saved to "mno-bond-lengths.dat" file.
-'''
+"""
# PDFgui project file
-project_file = 'lmo-template.ddp3'
-output_file = 'mno-bond-lengths.dat'
+project_file = "lmo-template.ddp3"
+output_file = "mno-bond-lengths.dat"
# Import tui (Text User Interface) functions from diffpy.pdfgui
from diffpy.pdfgui import tui
@@ -22,19 +22,22 @@
# Create a PDF calculator object that will be used in that function.
from diffpy.pdffit2 import PdfFit
+
pf = PdfFit()
+
def shortestBond_MnO(stru):
"""extract the shortest MnO bond length in a structure.
-
+
stru -- initial or refined phase from a PDFgui project
-
+
Return the shortest bond length.
"""
pf.reset()
pf.add_structure(stru)
- bnds = pf.bond_length_types('Mn', 'O', 0.01, 3)
- return bnds['dij'][0]
+ bnds = pf.bond_length_types("Mn", "O", 0.01, 3)
+ return bnds["dij"][0]
+
# Extract temperatures from PDFgui project to Python list.
# Temperature needs to be defined per each dataset in the project.
@@ -47,18 +50,20 @@ def shortestBond_MnO(stru):
print("Cannot find phase refinement results in", project_file)
print("Open the file in PDFgui, run refinement, save and try again.")
# terminate the script by raising error condition
- raise RuntimeError('Missing refinement results.')
+ raise RuntimeError("Missing refinement results.")
MnO_bond_lengths.append(shortestBond_MnO(phase.refined))
# Save bond lengths to a file
-outfile = open(output_file, 'w')
-print("# Shortest Mn-O bond length extracted from {}".format(project_file), file = outfile)
-print("# temperature(K) bond_length(A)", file = outfile)
+outfile = open(output_file, "w")
+print(
+ "# Shortest Mn-O bond length extracted from {}".format(project_file), file=outfile
+)
+print("# temperature(K) bond_length(A)", file=outfile)
for t, b in zip(temperatures, MnO_bond_lengths):
- print("{}, {}".format(t, b), file = outfile)
+ print("{}, {}".format(t, b), file=outfile)
outfile.close()
-dashline = 78 * '-'
+dashline = 78 * "-"
print(dashline)
print("Mn-O bond lengths saved to {}".format(output_file))
print(dashline)
@@ -67,10 +72,11 @@ def shortestBond_MnO(stru):
# provides MATLAB-like plotting functions.
import pylab
-pylab.plot(temperatures, MnO_bond_lengths, 'o--')
-pylab.title('Data from refined phases in PDFgui project %s' % project_file)
-pylab.xlabel('temperature (K)')
-pylab.ylabel('shortest Mn-O bond (A)')
+
+pylab.plot(temperatures, MnO_bond_lengths, "o--")
+pylab.title("Data from refined phases in PDFgui project %s" % project_file)
+pylab.xlabel("temperature (K)")
+pylab.ylabel("shortest Mn-O bond (A)")
# Show the plot window. This must be the last command in the script.
pylab.show()
diff --git a/src/diffpy/pdfgui/gui/aboutdialog.py b/src/diffpy/pdfgui/gui/aboutdialog.py
index c015e80f..cef633f1 100644
--- a/src/diffpy/pdfgui/gui/aboutdialog.py
+++ b/src/diffpy/pdfgui/gui/aboutdialog.py
@@ -20,7 +20,7 @@
from diffpy.pdfgui.version import __version__, __date__
-_acknowledgement = '''\
+_acknowledgement = """\
This software was developed by the Billinge-group as part of the Distributed
Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US
National Science Foundation under grant DMR-0520547. Developments of PDFfit2
@@ -37,36 +37,43 @@
C. L. Farrow, P. Juhas, J. W. Liu, D. Bryndin, E. S. Bozin,
J. Bloch, Th. Proffen and S. J. L. Billinge, PDFfit2 and PDFgui:
computer programs for studying nanostructure in crystals,
- J. Phys.: Condens. Matter 19, 335219 (2007).'''
+ J. Phys.: Condens. Matter 19, 335219 (2007)."""
-_copyright = "(c) 2005-{year},".format(year= __date__[:4])
+_copyright = "(c) 2005-{year},".format(year=__date__[:4])
_homepage = "https://www.diffpy.org"
# authors list is shuffled randomly every time
-_authors = ["S. J. L. Billinge", "E. S. Bozin", "D. Bryndin",
- "C. L. Farrow", "P. Juhas", "J. W. Liu"]
+_authors = [
+ "S. J. L. Billinge",
+ "E. S. Bozin",
+ "D. Bryndin",
+ "C. L. Farrow",
+ "P. Juhas",
+ "J. W. Liu",
+]
_paper = "https://stacks.iop.org/0953-8984/19/335219"
_license = ""
def launchBrowser(url):
- '''Launches browser and opens specified url
+ """Launches browser and opens specified url
In some cases may require BROWSER environment variable to be set up.
@param url: URL to open
- '''
+ """
import webbrowser
+
webbrowser.open(url)
class DialogAbout(wx.Dialog):
- '''"About" Dialog
+ """ "About" Dialog
Shows product name, current version, authors, and link to the product page.
Current version is taken from version.py
- '''
+ """
def __init__(self, *args, **kwds):
@@ -74,23 +81,39 @@ def __init__(self, *args, **kwds):
kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
self.SetSize((600, 595))
- self.bitmap_logo = wx.StaticBitmap(self, wx.ID_ANY, wx.Bitmap(iconpath("logo.png")))
+ self.bitmap_logo = wx.StaticBitmap(
+ self, wx.ID_ANY, wx.Bitmap(iconpath("logo.png"))
+ )
self.label_title = wx.StaticText(self, wx.ID_ANY, "PDFgui")
self.label_version = wx.StaticText(self, wx.ID_ANY, "")
self.label_build = wx.StaticText(self, wx.ID_ANY, "Build:")
self.label_svnrevision = wx.StaticText(self, wx.ID_ANY, "")
self.label_copyright = wx.StaticText(self, wx.ID_ANY, "")
self.label_author = wx.StaticText(self, wx.ID_ANY, "author")
- self.hyperlink = wx.lib.agw.hyperlink.HyperLinkCtrl(self, wx.ID_ANY, _homepage, URL=_homepage)
- self.hyperlink_license = wx.lib.agw.hyperlink.HyperLinkCtrl(self, wx.ID_ANY, _license, URL=_license)
+ self.hyperlink = wx.lib.agw.hyperlink.HyperLinkCtrl(
+ self, wx.ID_ANY, _homepage, URL=_homepage
+ )
+ self.hyperlink_license = wx.lib.agw.hyperlink.HyperLinkCtrl(
+ self, wx.ID_ANY, _license, URL=_license
+ )
self.static_line_1 = wx.StaticLine(self, wx.ID_ANY)
self.label_acknowledgement = wx.StaticText(self, wx.ID_ANY, "")
- self.hyperlink_paper = wx.lib.agw.hyperlink.HyperLinkCtrl(self, wx.ID_ANY, _paper, URL=_paper)
+ self.hyperlink_paper = wx.lib.agw.hyperlink.HyperLinkCtrl(
+ self, wx.ID_ANY, _paper, URL=_paper
+ )
self.static_line_2 = wx.StaticLine(self, wx.ID_ANY)
- self.bitmap_button_nsf = wx.BitmapButton(self, wx.ID_ANY, wx.NullBitmap, style=wx.BU_AUTODRAW)
- self.bitmap_button_danse = wx.BitmapButton(self, wx.ID_ANY, wx.NullBitmap, style=wx.BU_AUTODRAW)
- self.bitmap_button_msu = wx.BitmapButton(self, wx.ID_ANY, wx.NullBitmap, style=wx.BU_AUTODRAW)
- self.bitmap_button_columbia = wx.BitmapButton(self, wx.ID_ANY, wx.NullBitmap, style=wx.BU_AUTODRAW)
+ self.bitmap_button_nsf = wx.BitmapButton(
+ self, wx.ID_ANY, wx.NullBitmap, style=wx.BU_AUTODRAW
+ )
+ self.bitmap_button_danse = wx.BitmapButton(
+ self, wx.ID_ANY, wx.NullBitmap, style=wx.BU_AUTODRAW
+ )
+ self.bitmap_button_msu = wx.BitmapButton(
+ self, wx.ID_ANY, wx.NullBitmap, style=wx.BU_AUTODRAW
+ )
+ self.bitmap_button_columbia = wx.BitmapButton(
+ self, wx.ID_ANY, wx.NullBitmap, style=wx.BU_AUTODRAW
+ )
self.static_line_3 = wx.StaticLine(self, wx.ID_ANY)
self.button_OK = wx.Button(self, wx.ID_OK, "OK")
@@ -111,9 +134,9 @@ def __init__(self, *args, **kwds):
self.label_acknowledgement.SetLabel(_acknowledgement)
self.label_copyright.SetLabel(_copyright)
# display version and svn revison numbers
- verwords = __version__.split('.post', 1)
+ verwords = __version__.split(".post", 1)
version = verwords[0]
- revision = '0' if len(verwords) == 1 else verwords[1]
+ revision = "0" if len(verwords) == 1 else verwords[1]
self.label_version.SetLabel(version)
self.label_svnrevision.SetLabel(revision)
@@ -131,13 +154,30 @@ def __init__(self, *args, **kwds):
self.Fit()
return
-
def __set_properties(self):
# begin wxGlade: DialogAbout.__set_properties
self.SetTitle("About")
self.SetSize((600, 595))
- self.label_title.SetFont(wx.Font(26, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
- self.label_version.SetFont(wx.Font(26, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, ""))
+ self.label_title.SetFont(
+ wx.Font(
+ 26,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
+ self.label_version.SetFont(
+ wx.Font(
+ 26,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_NORMAL,
+ 0,
+ "",
+ )
+ )
self.hyperlink_license.Enable(False)
self.hyperlink_license.Hide()
self.bitmap_button_nsf.SetSize(self.bitmap_button_nsf.GetBestSize())
@@ -189,22 +229,23 @@ def __do_layout(self):
self.Centre()
# end wxGlade
- def onNsfLogo(self, event): # wxGlade: DialogAbout.
+ def onNsfLogo(self, event): # wxGlade: DialogAbout.
launchBrowser("https://www.nsf.gov")
event.Skip()
- def onDanseLogo(self, event): # wxGlade: DialogAbout.
+ def onDanseLogo(self, event): # wxGlade: DialogAbout.
launchBrowser("http://danse.us")
event.Skip()
- def onMsuLogo(self, event): # wxGlade: DialogAbout.
+ def onMsuLogo(self, event): # wxGlade: DialogAbout.
launchBrowser("https://www.msu.edu")
event.Skip()
- def onColumbiaLogo(self, event): # wxGlade: DialogAbout.
+ def onColumbiaLogo(self, event): # wxGlade: DialogAbout.
launchBrowser("https://www.columbia.edu")
event.Skip()
+
# end of class DialogAbout
##### testing code ###########################################################
diff --git a/src/diffpy/pdfgui/gui/adddatapanel.py b/src/diffpy/pdfgui/gui/adddatapanel.py
index 9359e996..29ca3247 100644
--- a/src/diffpy/pdfgui/gui/adddatapanel.py
+++ b/src/diffpy/pdfgui/gui/adddatapanel.py
@@ -20,6 +20,7 @@
from diffpy.pdfgui.gui.fittree import incrementName
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class AddDataPanel(wx.Panel, PDFPanel):
"""Panel for adding or changing data.
@@ -45,7 +46,16 @@ def __init__(self, *args, **kwds):
sizer_1.Add(sizer_4, 0, wx.BOTTOM | wx.EXPAND | wx.TOP, 5)
self.textLoadData = wx.StaticText(self, wx.ID_ANY, "Load a data set from file.")
- self.textLoadData.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Sans"))
+ self.textLoadData.SetFont(
+ wx.Font(
+ 12,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_NORMAL,
+ 0,
+ "Sans",
+ )
+ )
sizer_4.Add(self.textLoadData, 1, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
self.buttonOpen = wx.Button(self, wx.ID_OPEN, "Open")
@@ -74,9 +84,9 @@ def __init__(self, *args, **kwds):
def __customProperties(self):
"""Custom Properties go here."""
self.entrypoint = None # The entrypoint on the tree
- self.entryfit = None # The fit under which to insert an item
- self.entryset = None # The dataset in which to insert an item
- self.fullpath = "" # The last loaded dataset
+ self.entryfit = None # The fit under which to insert an item
+ self.entryset = None # The dataset in which to insert an item
+ self.fullpath = "" # The last loaded dataset
return
def readConfiguration(self):
@@ -96,10 +106,11 @@ def readConfiguration(self):
if self.cP.has_option("DATASET", "last"):
self.fullpath = self.cP.getquoted("DATASET", "last")
import os.path
+
if not os.path.exists(self.fullpath):
- self.fullpath = ''
+ self.fullpath = ""
else:
- self.fullpath = ''
+ self.fullpath = ""
return
def updateConfiguration(self):
@@ -111,22 +122,32 @@ def updateConfiguration(self):
# EVENT CODE ####
- def onOpen(self, event): # wxGlade: AddDataPanel.
+ def onOpen(self, event): # wxGlade: AddDataPanel.
"""Add a dataset to the tree from a file."""
import os.path
+
newnode = None
dir, filename = os.path.split(self.fullpath)
if not dir:
dir = self.mainFrame.workpath
- matchstring = "|".join((
- "PDF files", "*.gr;*.fgr;*.fit;*.cgr;*.calc",
- "PDF data files (*.gr)", "*.gr",
- "PDF fit files (*.fgr)", "*.fgr",
- "PDF fit files (*.fit)", "*.fit",
- "PDF calculation files (*.cgr)", "*.cgr",
- "PDF calculation files (*.calc)", "*.calc",
- "All Files", "*"
- ))
+ matchstring = "|".join(
+ (
+ "PDF files",
+ "*.gr;*.fgr;*.fit;*.cgr;*.calc",
+ "PDF data files (*.gr)",
+ "*.gr",
+ "PDF fit files (*.fgr)",
+ "*.fgr",
+ "PDF fit files (*.fit)",
+ "*.fit",
+ "PDF calculation files (*.cgr)",
+ "*.cgr",
+ "PDF calculation files (*.calc)",
+ "*.calc",
+ "All Files",
+ "*",
+ )
+ )
d = wx.FileDialog(None, "Choose a file", dir, "", matchstring)
if d.ShowModal() == wx.ID_OK:
self.fullpath = d.GetPath()
@@ -142,8 +163,9 @@ def onOpen(self, event): # wxGlade: AddDataPanel.
siblings = self.treeCtrlMain.GetChildren(self.entryfit)
names = [self.treeCtrlMain.GetItemText(i) for i in siblings]
name = incrementName(name, names)
- newnode = self.treeCtrlMain.AddDataSet(self.entryfit, name,
- insertafter=self.entryset, filename=self.fullpath)
+ newnode = self.treeCtrlMain.AddDataSet(
+ self.entryfit, name, insertafter=self.entryset, filename=self.fullpath
+ )
self.mainFrame.setMode("fitting")
self.treeCtrlMain.SetItemBold(self.entrypoint, False)
@@ -152,10 +174,10 @@ def onOpen(self, event): # wxGlade: AddDataPanel.
d.Destroy()
return
-
- def onCancel(self, event): # wxGlade: AddDataPanel.
+ def onCancel(self, event): # wxGlade: AddDataPanel.
"""Cancel this addition. Go back to the last panel."""
- if self.entrypoint is None: return
+ if self.entrypoint is None:
+ return
self.mainFrame.setMode("fitting")
self.treeCtrlMain.SetItemBold(self.entrypoint, False)
self.treeCtrlMain.UnselectAll()
@@ -194,4 +216,5 @@ def refresh(self):
self.treeCtrlMain.UnselectAll()
return
+
# end of class AddDataPanel
diff --git a/src/diffpy/pdfgui/gui/addphasepanel.py b/src/diffpy/pdfgui/gui/addphasepanel.py
index 5ae51f34..92ab70d7 100644
--- a/src/diffpy/pdfgui/gui/addphasepanel.py
+++ b/src/diffpy/pdfgui/gui/addphasepanel.py
@@ -20,6 +20,7 @@
from diffpy.pdfgui.gui.fittree import incrementName
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class AddPhasePanel(wx.Panel, PDFPanel):
"""Panel for adding a phase
@@ -32,6 +33,7 @@ class AddPhasePanel(wx.Panel, PDFPanel):
None, which means the new phase is appended to the end of
the phase section of the entryfit.
"""
+
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
# begin wxGlade: AddPhasePanel.__init__
@@ -43,8 +45,19 @@ def __init__(self, *args, **kwds):
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(sizer_4, 0, wx.BOTTOM | wx.EXPAND | wx.TOP, 5)
- self.labelOpenPhase = wx.StaticText(self, wx.ID_ANY, "Load a structure from file.")
- self.labelOpenPhase.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Sans"))
+ self.labelOpenPhase = wx.StaticText(
+ self, wx.ID_ANY, "Load a structure from file."
+ )
+ self.labelOpenPhase.SetFont(
+ wx.Font(
+ 12,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_NORMAL,
+ 0,
+ "Sans",
+ )
+ )
sizer_4.Add(self.labelOpenPhase, 1, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
self.buttonOpen = wx.Button(self, wx.ID_OPEN, "Open")
@@ -56,8 +69,19 @@ def __init__(self, *args, **kwds):
sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(sizer_5, 0, wx.BOTTOM | wx.EXPAND | wx.TOP, 5)
- self.labelCreatePhase = wx.StaticText(self, wx.ID_ANY, "Create a structure from scratch.")
- self.labelCreatePhase.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Sans"))
+ self.labelCreatePhase = wx.StaticText(
+ self, wx.ID_ANY, "Create a structure from scratch."
+ )
+ self.labelCreatePhase.SetFont(
+ wx.Font(
+ 12,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_NORMAL,
+ 0,
+ "Sans",
+ )
+ )
sizer_5.Add(self.labelCreatePhase, 1, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
self.buttonNew = wx.Button(self, wx.ID_NEW, "New")
@@ -86,10 +110,10 @@ def __init__(self, *args, **kwds):
def __customProperties(self):
"""Custom Properties go here."""
- self.entrypoint = None # The entrypoint on the tree
- self.entryfit = None # The fit in which to insert an item
- self.entryphase = None # The phase under which to insert an item
- self.fullpath = "" # The last loaded structure
+ self.entrypoint = None # The entrypoint on the tree
+ self.entryfit = None # The fit in which to insert an item
+ self.entryphase = None # The phase under which to insert an item
+ self.fullpath = "" # The last loaded structure
return
def readConfiguration(self):
@@ -109,10 +133,11 @@ def readConfiguration(self):
if self.cP.has_option("PHASE", "last"):
self.fullpath = self.cP.getquoted("PHASE", "last")
import os.path
+
if not os.path.exists(self.fullpath):
- self.fullpath = ''
+ self.fullpath = ""
else:
- self.fullpath = ''
+ self.fullpath = ""
return
def updateConfiguration(self):
@@ -124,7 +149,7 @@ def updateConfiguration(self):
# EVENT CODE ####
- def onOpen(self, event): # wxGlade: AddPhasePanel.
+ def onOpen(self, event): # wxGlade: AddPhasePanel.
"""Add a the new phase to the tree.
The phase is added as a child of entryfit, right after the
@@ -132,19 +157,27 @@ def onOpen(self, event): # wxGlade: AddPhasePanel.
appended to the end of the children of entryfit.
"""
import os.path
+
newnode = None
dir, filename = os.path.split(self.fullpath)
if not dir:
dir = self.mainFrame.workpath
- matchstring = "|".join((
- "Structure file",
- "*.cif;*CIF;*.stru;*.STRU;*.pdb;*.PDB;*.xyz;*.XYZ",
- "Crystallographic Information File (*.cif)", "*.cif;*.CIF",
- "PDFfit structure files (*.stru)", "*.stru;*.STRU",
- "Protein Data Bank files (*.pdb)", "*.pdb;*.PDB",
- "Coordinate files (*.xyz)", "*.xyz;*.XYZ",
- "All Files", "*",
- ))
+ matchstring = "|".join(
+ (
+ "Structure file",
+ "*.cif;*CIF;*.stru;*.STRU;*.pdb;*.PDB;*.xyz;*.XYZ",
+ "Crystallographic Information File (*.cif)",
+ "*.cif;*.CIF",
+ "PDFfit structure files (*.stru)",
+ "*.stru;*.STRU",
+ "Protein Data Bank files (*.pdb)",
+ "*.pdb;*.PDB",
+ "Coordinate files (*.xyz)",
+ "*.xyz;*.XYZ",
+ "All Files",
+ "*",
+ )
+ )
d = wx.FileDialog(None, "Choose a file", dir, "", matchstring)
if d.ShowModal() == wx.ID_OK:
self.fullpath = d.GetPath()
@@ -161,8 +194,9 @@ def onOpen(self, event): # wxGlade: AddPhasePanel.
names = [self.treeCtrlMain.GetItemText(i) for i in siblings]
name = incrementName(name, names)
- newnode = self.treeCtrlMain.AddPhase(self.entryfit, name,
- insertafter=self.entryphase, filename=self.fullpath)
+ newnode = self.treeCtrlMain.AddPhase(
+ self.entryfit, name, insertafter=self.entryphase, filename=self.fullpath
+ )
self.mainFrame.setMode("fitting")
self.treeCtrlMain.SetItemBold(self.entrypoint, False)
@@ -172,7 +206,7 @@ def onOpen(self, event): # wxGlade: AddPhasePanel.
d.Destroy()
return
- def onNew(self, event): # wxGlade: AddPhasePanel.
+ def onNew(self, event): # wxGlade: AddPhasePanel.
"""Add a new item to be created from scratch."""
# Set the name of the new phase
siblings = self.treeCtrlMain.GetChildren(self.entryfit)
@@ -181,8 +215,9 @@ def onNew(self, event): # wxGlade: AddPhasePanel.
label = incrementName(label, names)
# Create the phase
- newnode = self.treeCtrlMain.AddPhase(self.entryfit, label,
- insertafter=self.entryphase)
+ newnode = self.treeCtrlMain.AddPhase(
+ self.entryfit, label, insertafter=self.entryphase
+ )
# Go to the new node
self.mainFrame.setMode("fitting")
@@ -192,7 +227,7 @@ def onNew(self, event): # wxGlade: AddPhasePanel.
self.treeCtrlMain.EditLabel(newnode)
return
- def onCancel(self, event): # wxGlade: AddPhasePanel.
+ def onCancel(self, event): # wxGlade: AddPhasePanel.
"""Cancel this addition. Go back to the last panel."""
self.mainFrame.setMode("fitting")
self.treeCtrlMain.SetItemBold(self.entrypoint, False)
@@ -203,6 +238,7 @@ def onCancel(self, event): # wxGlade: AddPhasePanel.
def validateStructure(self, node):
"""Make sure that the structure is valid."""
from diffpy.pdfgui.control.controlerrors import ControlError
+
dataobject = self.treeCtrlMain.GetControlData(node)
stru = dataobject.initial
for a in stru:
@@ -223,7 +259,7 @@ def refresh(self):
selections = self.treeCtrlMain.GetSelections()
entrypoint = selections[0]
- entryphase = entrypoint
+ entryphase = entrypoint
entryfit = self.treeCtrlMain.GetFitRoot(entrypoint)
entrytype = self.treeCtrlMain.GetNodeType(entryphase)
@@ -240,4 +276,5 @@ def refresh(self):
self.treeCtrlMain.UnselectAll()
return
+
# end of class AddPhasePanel
diff --git a/src/diffpy/pdfgui/gui/blankpanel.py b/src/diffpy/pdfgui/gui/blankpanel.py
index 3f1b9683..1393452e 100644
--- a/src/diffpy/pdfgui/gui/blankpanel.py
+++ b/src/diffpy/pdfgui/gui/blankpanel.py
@@ -18,8 +18,10 @@
import wx
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class BlankPanel(wx.Panel, PDFPanel):
"""A blank panel needed as a right panel in mainframe.py."""
+
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
wx.Panel.__init__(self, *args, **kwds)
@@ -27,4 +29,5 @@ def __init__(self, *args, **kwds):
def refresh(self):
return
+
# end of class BlankPanel
diff --git a/src/diffpy/pdfgui/gui/bondangledialog.py b/src/diffpy/pdfgui/gui/bondangledialog.py
index 67a947f9..376c62c7 100644
--- a/src/diffpy/pdfgui/gui/bondangledialog.py
+++ b/src/diffpy/pdfgui/gui/bondangledialog.py
@@ -18,13 +18,16 @@
import wx
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class BondAngleDialog(wx.Dialog, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
self.sizer_2_staticbox = wx.StaticBox(self, -1, "Bond Angle Calculation")
- self.instructionsLabel = wx.StaticText(self, -1, "Calculate the angle defined by three atoms.")
+ self.instructionsLabel = wx.StaticText(
+ self, -1, "Calculate the angle defined by three atoms."
+ )
self.atomsLabel = wx.StaticText(self, -1, "Atom Indices")
self.aSpinCtrl = wx.SpinCtrl(self, -1, "1", min=1, max=1)
self.bSpinCtrl = wx.SpinCtrl(self, -1, "1", min=1, max=1)
@@ -53,17 +56,24 @@ def __do_layout(self):
sizer_4_copy = wx.BoxSizer(wx.HORIZONTAL)
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
- sizer_2.Add(self.instructionsLabel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 5)
+ sizer_2.Add(
+ self.instructionsLabel,
+ 0,
+ wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ADJUST_MINSIZE,
+ 5,
+ )
sizer_2.Add(sizer_3, 0, wx.EXPAND, 0)
- sizer_4.Add(self.atomsLabel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 5)
- sizer_4.Add(self.aSpinCtrl, 0, wx.ALL|wx.ADJUST_MINSIZE, 5)
- sizer_4.Add(self.bSpinCtrl, 0, wx.ALL|wx.ADJUST_MINSIZE, 5)
- sizer_4.Add(self.cSpinCtrl, 0, wx.ALL|wx.ADJUST_MINSIZE, 5)
+ sizer_4.Add(
+ self.atomsLabel, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.ADJUST_MINSIZE, 5
+ )
+ sizer_4.Add(self.aSpinCtrl, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)
+ sizer_4.Add(self.bSpinCtrl, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)
+ sizer_4.Add(self.cSpinCtrl, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)
sizer_2.Add(sizer_4, 0, wx.EXPAND, 0)
sizer_2.Add(self.static_line_1, 0, wx.EXPAND, 0)
- sizer_4_copy.Add((0, 0), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
- sizer_4_copy.Add(self.cancelButton, 0, wx.ALL|wx.ADJUST_MINSIZE, 5)
- sizer_4_copy.Add(self.okButton, 0, wx.ALL|wx.ADJUST_MINSIZE, 5)
+ sizer_4_copy.Add((0, 0), 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0)
+ sizer_4_copy.Add(self.cancelButton, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)
+ sizer_4_copy.Add(self.okButton, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)
sizer_2.Add(sizer_4_copy, 0, wx.EXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer_2)
@@ -72,7 +82,6 @@ def __do_layout(self):
self.Layout()
# end wxGlade
-
###########################################################################
def __customProperties(self):
@@ -92,9 +101,9 @@ def setStructure(self, structure):
self.aSpinCtrl.SetRange(1, natoms)
self.bSpinCtrl.SetRange(1, natoms)
self.cSpinCtrl.SetRange(1, natoms)
- self.aSpinCtrl.SetValue(min(1,natoms))
- self.bSpinCtrl.SetValue(min(2,natoms))
- self.cSpinCtrl.SetValue(min(3,natoms))
+ self.aSpinCtrl.SetValue(min(1, natoms))
+ self.bSpinCtrl.SetValue(min(2, natoms))
+ self.cSpinCtrl.SetValue(min(3, natoms))
self.okButton.Enable(True)
if natoms < 3:
self.okButton.Enable(False)
@@ -102,8 +111,10 @@ def setStructure(self, structure):
def getCtrlLetter(self, ctrl):
"""Get the letter associated with the control."""
- if ctrl is self.aSpinCtrl: return "a"
- if ctrl is self.bSpinCtrl: return "b"
+ if ctrl is self.aSpinCtrl:
+ return "a"
+ if ctrl is self.bSpinCtrl:
+ return "b"
return "c"
def onSpin(self, event):
@@ -120,7 +131,8 @@ def onSpin(self, event):
# Check to see if the value is increasing or decreasing
increasing = True
oldval = getattr(self, atomLetter)
- if val < oldval: increasing = False
+ if val < oldval:
+ increasing = False
# Check to see if the value is equal to another. If so, move it along in
# the direction it was going.
@@ -146,13 +158,13 @@ def onSpin(self, event):
wx.CallAfter(ctrl.SetValue, oldval)
return
-
def onOk(self, event):
event.Skip()
return
- def onCancel(self, event): # wxGlade: SGStructureDialog.
+ def onCancel(self, event): # wxGlade: SGStructureDialog.
event.Skip()
return
+
# end of class SGStructureDialog
diff --git a/src/diffpy/pdfgui/gui/bondlengthdialog.py b/src/diffpy/pdfgui/gui/bondlengthdialog.py
index 28d84fde..53f91700 100644
--- a/src/diffpy/pdfgui/gui/bondlengthdialog.py
+++ b/src/diffpy/pdfgui/gui/bondlengthdialog.py
@@ -22,6 +22,7 @@
# begin wxGlade: extracode
# end wxGlade
+
class BondLengthDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: BondLengthDialog.__init__
@@ -31,7 +32,9 @@ def __init__(self, *args, **kwds):
sizer_2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.VERTICAL)
- self.instructionsLabel = wx.StaticText(self, wx.ID_ANY, "Enter the indices of two atoms.")
+ self.instructionsLabel = wx.StaticText(
+ self, wx.ID_ANY, "Enter the indices of two atoms."
+ )
sizer_2.Add(self.instructionsLabel, 0, wx.ALL, 5)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
@@ -51,7 +54,11 @@ def __init__(self, *args, **kwds):
self.static_line_2 = wx.StaticLine(self, wx.ID_ANY)
sizer_2.Add(self.static_line_2, 0, wx.BOTTOM | wx.EXPAND, 5)
- self.instructionsLabel2 = wx.StaticText(self, wx.ID_ANY, "Or enter the elemental symbols of two atoms and\nthe range over which to calculate the bond lengths.")
+ self.instructionsLabel2 = wx.StaticText(
+ self,
+ wx.ID_ANY,
+ "Or enter the elemental symbols of two atoms and\nthe range over which to calculate the bond lengths.",
+ )
sizer_2.Add(self.instructionsLabel2, 0, wx.ALL, 5)
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
@@ -148,8 +155,8 @@ def setStructure(self, structure):
# Fill the spin controls
self.aSpinCtrl.SetRange(1, natoms)
self.bSpinCtrl.SetRange(1, natoms)
- self.aSpinCtrl.SetValue(min(1,natoms))
- self.bSpinCtrl.SetValue(min(2,natoms))
+ self.aSpinCtrl.SetValue(min(1, natoms))
+ self.bSpinCtrl.SetValue(min(2, natoms))
# Fill the combo boxes
self.eList = sorted(set(a.element for a in structure))
@@ -189,10 +196,11 @@ def onComboKillFocus(self, event):
def getCtrlLetter(self, ctrl):
"""Get the letter associated with the control."""
- if ctrl is self.aSpinCtrl: return "a"
+ if ctrl is self.aSpinCtrl:
+ return "a"
return "b"
- def onSpin(self, event): # wxGlade: BondLengthDialog.
+ def onSpin(self, event): # wxGlade: BondLengthDialog.
letters = ["a", "b"]
ctrl = event.GetEventObject()
val = event.GetSelection()
@@ -202,7 +210,8 @@ def onSpin(self, event): # wxGlade: BondLengthDialog.
# Check to see if the value is increasing or decreasing
increasing = True
oldval = getattr(self, atomLetter)
- if val < oldval: increasing = False
+ if val < oldval:
+ increasing = False
# Check to see if the value is equal to another. If so, move it along in
# the direction it was going.
@@ -228,10 +237,10 @@ def onSpin(self, event): # wxGlade: BondLengthDialog.
wx.CallAfter(ctrl.SetValue, oldval)
return
- def onCancel(self, event): # wxGlade: BondLengthDialog.
+ def onCancel(self, event): # wxGlade: BondLengthDialog.
event.Skip()
- def onOk(self, event): # wxGlade: BondLengthDialog.
+ def onOk(self, event): # wxGlade: BondLengthDialog.
self.onTextKillFocus(event)
self.onComboKillFocus(event)
event.Skip()
diff --git a/src/diffpy/pdfgui/gui/calculationpanel.py b/src/diffpy/pdfgui/gui/calculationpanel.py
index 72bed173..541433fc 100644
--- a/src/diffpy/pdfgui/gui/calculationpanel.py
+++ b/src/diffpy/pdfgui/gui/calculationpanel.py
@@ -21,6 +21,7 @@
from diffpy.pdfgui.gui.wxextensions.textctrlutils import textCtrlAsGridCell
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class CalculationPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -33,16 +34,38 @@ def __init__(self, *args, **kwds):
outerSizer = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(outerSizer, 1, wx.EXPAND, 0)
- sizer_panelname = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizer_panelname = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
outerSizer.Add(sizer_panelname, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
- self.panelNameLabel = wx.StaticText(self, wx.ID_ANY, "Calculation Configuration")
- self.panelNameLabel.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
- sizer_panelname.Add(self.panelNameLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
+ self.panelNameLabel = wx.StaticText(
+ self, wx.ID_ANY, "Calculation Configuration"
+ )
+ self.panelNameLabel.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
+ sizer_panelname.Add(
+ self.panelNameLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5
+ )
outerSizer.Add((450, 5), 0, 0, 0)
- self.radioBoxStype = wx.RadioBox(self, wx.ID_ANY, "Scatterer Type", choices=["Neutron", "X-ray"], majorDimension=2, style=wx.RA_SPECIFY_COLS)
+ self.radioBoxStype = wx.RadioBox(
+ self,
+ wx.ID_ANY,
+ "Scatterer Type",
+ choices=["Neutron", "X-ray"],
+ majorDimension=2,
+ style=wx.RA_SPECIFY_COLS,
+ )
self.radioBoxStype.SetMinSize((330, 43))
self.radioBoxStype.SetSelection(0)
outerSizer.Add(self.radioBoxStype, 0, wx.ALL, 5)
@@ -50,32 +73,54 @@ def __init__(self, *args, **kwds):
grid_sizer_1 = wx.FlexGridSizer(4, 6, 5, 10)
outerSizer.Add(grid_sizer_1, 0, wx.ALL | wx.EXPAND, 5)
- self.labelCalcRange = wx.StaticText(self, wx.ID_ANY, "Range", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelCalcRange, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ self.labelCalcRange = wx.StaticText(
+ self, wx.ID_ANY, "Range", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelCalcRange,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 5,
+ )
self.textCtrlCalcFrom = wx.TextCtrl(self, wx.ID_ANY, "1.0")
grid_sizer_1.Add(self.textCtrlCalcFrom, 0, wx.ALIGN_CENTER_VERTICAL, 0)
self.labelTo = wx.StaticText(self, wx.ID_ANY, "to", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelTo, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ grid_sizer_1.Add(
+ self.labelTo, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20
+ )
self.textCtrlCalcTo = wx.TextCtrl(self, wx.ID_ANY, "10.0")
grid_sizer_1.Add(self.textCtrlCalcTo, 0, wx.ALIGN_CENTER_VERTICAL, 0)
- self.labelRStep = wx.StaticText(self, wx.ID_ANY, "spacing", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelRStep, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ self.labelRStep = wx.StaticText(
+ self, wx.ID_ANY, "spacing", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelRStep, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5
+ )
self.textCtrlRStep = wx.TextCtrl(self, wx.ID_ANY, "0.01")
grid_sizer_1.Add(self.textCtrlRStep, 0, wx.ALIGN_CENTER_VERTICAL, 0)
- self.labelScaleFactor = wx.StaticText(self, wx.ID_ANY, "Scale Factor", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ self.labelScaleFactor = wx.StaticText(
+ self, wx.ID_ANY, "Scale Factor", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelScaleFactor,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 5,
+ )
self.textCtrlScaleFactor = wx.TextCtrl(self, wx.ID_ANY, "1.0")
grid_sizer_1.Add(self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL, 0)
self.labelQmax = wx.StaticText(self, wx.ID_ANY, "Qmax", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelQmax, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ grid_sizer_1.Add(
+ self.labelQmax, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20
+ )
self.textCtrlQmax = wx.TextCtrl(self, wx.ID_ANY, "25.0")
grid_sizer_1.Add(self.textCtrlQmax, 0, wx.ALIGN_CENTER_VERTICAL, 0)
@@ -87,13 +132,19 @@ def __init__(self, *args, **kwds):
grid_sizer_1.Add(self.label_1_copy, 0, 0, 0)
self.labelQdamp = wx.StaticText(self, wx.ID_ANY, "Qdamp", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ grid_sizer_1.Add(
+ self.labelQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5
+ )
self.textCtrlQdamp = wx.TextCtrl(self, wx.ID_ANY, "0.0")
grid_sizer_1.Add(self.textCtrlQdamp, 0, wx.ALIGN_CENTER_VERTICAL, 0)
- self.labelQbroad = wx.StaticText(self, wx.ID_ANY, "Qbroad", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ self.labelQbroad = wx.StaticText(
+ self, wx.ID_ANY, "Qbroad", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5
+ )
self.textCtrlQbroad = wx.TextCtrl(self, wx.ID_ANY, "0.0")
grid_sizer_1.Add(self.textCtrlQbroad, 0, wx.ALIGN_CENTER_VERTICAL, 0)
@@ -131,16 +182,17 @@ def __customProperties(self):
"""Set up the custom properites."""
self._focusedText = None
self.calculation = None
- self.stypeMap = {0: 'N', 1: 'X'}
-
- self.ctrlMap = {'rmin' : 'textCtrlCalcFrom',
- 'rmax' : 'textCtrlCalcTo',
- 'qmax' : 'textCtrlQmax',
- 'qdamp' : 'textCtrlQdamp',
- 'qbroad' : 'textCtrlQbroad',
- 'rstep' : 'textCtrlRStep',
- 'dscale' : 'textCtrlScaleFactor',
- }
+ self.stypeMap = {0: "N", 1: "X"}
+
+ self.ctrlMap = {
+ "rmin": "textCtrlCalcFrom",
+ "rmax": "textCtrlCalcTo",
+ "qmax": "textCtrlQmax",
+ "qdamp": "textCtrlQdamp",
+ "qbroad": "textCtrlQbroad",
+ "rstep": "textCtrlRStep",
+ "dscale": "textCtrlScaleFactor",
+ }
# Give each textCtrl a name that can be referenced and setup the
# validator
@@ -175,9 +227,9 @@ def setConfigurationData(self):
if self.calculation:
stype = self.calculation.stype
- if stype == 'N':
+ if stype == "N":
self.radioBoxStype.SetSelection(0)
- elif stype == 'X':
+ elif stype == "X":
self.radioBoxStype.SetSelection(1)
for (key, value) in self.ctrlMap.items():
@@ -188,27 +240,30 @@ def setConfigurationData(self):
if value is not None:
textCtrl.SetValue(str(value))
else:
- textCtrl.SetValue('0.0')
+ textCtrl.SetValue("0.0")
return
def __coerseText(self, value):
if not value:
- value = '0'
- if value[-1].lower() in ('-', 'e'):
- value += '0'
+ value = "0"
+ if value[-1].lower() in ("-", "e"):
+ value += "0"
return float(value)
+
# EVENT CODE #############################################################
- def onStype(self, event): # wxGlade: CalculationPanel.
+ def onStype(self, event): # wxGlade: CalculationPanel.
value = event.GetInt()
self.calculation.stype = self.stypeMap[value]
self.mainFrame.needsSave()
return
- def onCalcRange(self, event): # wxGlade: CalculationPanel.
+ def onCalcRange(self, event): # wxGlade: CalculationPanel.
event.Skip()
- if self.calculation is None: return
+ if self.calculation is None:
+ return
from diffpy.pdfgui.control.controlerrors import ControlValueError
+
# Since calculation.rmax gets adjusted by setRGrid,
# always obtain all range parameters.
rminvalue = self.textCtrlCalcFrom.GetValue()
@@ -252,7 +307,7 @@ def onKillFocus(self, event):
event.Skip()
return
- def onExport(self, event): # wxGlade: CalculationPanel.
+ def onExport(self, event): # wxGlade: CalculationPanel.
event.Skip()
# Methods overloaded from PDFPanel
@@ -261,4 +316,5 @@ def refresh(self):
self.setConfigurationData()
return
+
# end of class CalculationPanel
diff --git a/src/diffpy/pdfgui/gui/datasetconfigurepanel.py b/src/diffpy/pdfgui/gui/datasetconfigurepanel.py
index d73888ce..5e635025 100644
--- a/src/diffpy/pdfgui/gui/datasetconfigurepanel.py
+++ b/src/diffpy/pdfgui/gui/datasetconfigurepanel.py
@@ -22,6 +22,7 @@
from diffpy.pdfgui.gui import tooltips
from diffpy.pdfgui.gui.wxextensions.textctrlutils import textCtrlAsGridCell
+
class DataSetConfigurePanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -34,21 +35,48 @@ def __init__(self, *args, **kwds):
outerSizer = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(outerSizer, 1, wx.EXPAND, 0)
- sizer_panelname = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizer_panelname = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
outerSizer.Add(sizer_panelname, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
self.panelNameLabel = wx.StaticText(self, wx.ID_ANY, "Data Set Configuration")
- self.panelNameLabel.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
- sizer_panelname.Add(self.panelNameLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
+ self.panelNameLabel.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
+ sizer_panelname.Add(
+ self.panelNameLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5
+ )
outerSizer.Add((450, 5), 0, 0, 0)
- self.radioBoxStype = wx.RadioBox(self, wx.ID_ANY, "Scatterer Type", choices=["Neutron", "X-ray"], majorDimension=2, style=wx.RA_SPECIFY_COLS)
+ self.radioBoxStype = wx.RadioBox(
+ self,
+ wx.ID_ANY,
+ "Scatterer Type",
+ choices=["Neutron", "X-ray"],
+ majorDimension=2,
+ style=wx.RA_SPECIFY_COLS,
+ )
self.radioBoxStype.SetMinSize((330, 43))
self.radioBoxStype.SetSelection(0)
outerSizer.Add(self.radioBoxStype, 0, wx.ALL, 5)
- self.radioBoxSampling = wx.RadioBox(self, wx.ID_ANY, "Data Sampling", choices=["Data", "Nyquist", "Custom"], majorDimension=3, style=wx.RA_SPECIFY_COLS)
+ self.radioBoxSampling = wx.RadioBox(
+ self,
+ wx.ID_ANY,
+ "Data Sampling",
+ choices=["Data", "Nyquist", "Custom"],
+ majorDimension=3,
+ style=wx.RA_SPECIFY_COLS,
+ )
self.radioBoxSampling.SetMinSize((232, 44))
self.radioBoxSampling.SetSelection(0)
outerSizer.Add(self.radioBoxSampling, 0, wx.ALL, 5)
@@ -57,52 +85,93 @@ def __init__(self, *args, **kwds):
outerSizer.Add(grid_sizer_1, 0, wx.ALL | wx.EXPAND, 5)
self.labelDataRange = wx.StaticText(self, wx.ID_ANY, "Data Range")
- grid_sizer_1.Add(self.labelDataRange, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ grid_sizer_1.Add(
+ self.labelDataRange,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 5,
+ )
self.textCtrlDataFrom = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
- self.textCtrlDataFrom.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ self.textCtrlDataFrom.SetBackgroundColour(
+ wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
+ )
grid_sizer_1.Add(self.textCtrlDataFrom, 0, 0, 0)
self.labelDataTo = wx.StaticText(self, wx.ID_ANY, "to")
- grid_sizer_1.Add(self.labelDataTo, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ grid_sizer_1.Add(
+ self.labelDataTo, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20
+ )
self.textCtrlDataTo = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
- self.textCtrlDataTo.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ self.textCtrlDataTo.SetBackgroundColour(
+ wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
+ )
grid_sizer_1.Add(self.textCtrlDataTo, 0, 0, 0)
self.labelDataStep = wx.StaticText(self, wx.ID_ANY, "spacing")
- grid_sizer_1.Add(self.labelDataStep, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ grid_sizer_1.Add(
+ self.labelDataStep,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 20,
+ )
self.textCtrlDataStep = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
- self.textCtrlDataStep.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ self.textCtrlDataStep.SetBackgroundColour(
+ wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
+ )
grid_sizer_1.Add(self.textCtrlDataStep, 0, 0, 0)
- self.labelFitRange = wx.StaticText(self, wx.ID_ANY, "Fit Range", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelFitRange, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ self.labelFitRange = wx.StaticText(
+ self, wx.ID_ANY, "Fit Range", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelFitRange,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 5,
+ )
self.textCtrlFitFrom = wx.TextCtrl(self, wx.ID_ANY, "1.0")
grid_sizer_1.Add(self.textCtrlFitFrom, 0, wx.ALIGN_CENTER_VERTICAL, 0)
self.labelFitTo = wx.StaticText(self, wx.ID_ANY, "to", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelFitTo, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ grid_sizer_1.Add(
+ self.labelFitTo, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20
+ )
self.textCtrlFitTo = wx.TextCtrl(self, wx.ID_ANY, "10.0")
grid_sizer_1.Add(self.textCtrlFitTo, 0, wx.ALIGN_CENTER_VERTICAL, 0)
self.labelFitStep = wx.StaticText(self, wx.ID_ANY, "spacing")
- grid_sizer_1.Add(self.labelFitStep, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ grid_sizer_1.Add(
+ self.labelFitStep,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 20,
+ )
self.textCtrlFitStep = wx.TextCtrl(self, wx.ID_ANY, "0")
grid_sizer_1.Add(self.textCtrlFitStep, 0, wx.ALIGN_CENTER_VERTICAL, 0)
- self.labelScaleFactor = wx.StaticText(self, wx.ID_ANY, "Scale Factor", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ self.labelScaleFactor = wx.StaticText(
+ self, wx.ID_ANY, "Scale Factor", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelScaleFactor,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 5,
+ )
self.textCtrlScaleFactor = wx.TextCtrl(self, wx.ID_ANY, "1.0")
grid_sizer_1.Add(self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL, 0)
self.labelQmax = wx.StaticText(self, wx.ID_ANY, "Qmax", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelQmax, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ grid_sizer_1.Add(
+ self.labelQmax, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20
+ )
self.textCtrlQmax = wx.TextCtrl(self, wx.ID_ANY, "25.0")
grid_sizer_1.Add(self.textCtrlQmax, 0, wx.ALIGN_CENTER_VERTICAL, 0)
@@ -114,13 +183,19 @@ def __init__(self, *args, **kwds):
grid_sizer_1.Add(self.blank1_copy_4, 0, 0, 0)
self.labelQdamp = wx.StaticText(self, wx.ID_ANY, "Qdamp", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ grid_sizer_1.Add(
+ self.labelQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5
+ )
self.textCtrlQdamp = wx.TextCtrl(self, wx.ID_ANY, "0.0")
grid_sizer_1.Add(self.textCtrlQdamp, 0, wx.ALIGN_CENTER_VERTICAL, 0)
- self.labelQbroad = wx.StaticText(self, wx.ID_ANY, "Qbroad", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ self.labelQbroad = wx.StaticText(
+ self, wx.ID_ANY, "Qbroad", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20
+ )
self.textCtrlQbroad = wx.TextCtrl(self, wx.ID_ANY, "0.0")
grid_sizer_1.Add(self.textCtrlQbroad, 0, wx.ALIGN_CENTER_VERTICAL, 0)
@@ -131,14 +206,25 @@ def __init__(self, *args, **kwds):
self.blank1_copy_5 = wx.StaticText(self, wx.ID_ANY, "")
grid_sizer_1.Add(self.blank1_copy_5, 0, 0, 0)
- self.labelTemperature = wx.StaticText(self, wx.ID_ANY, "Temperature", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelTemperature, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ self.labelTemperature = wx.StaticText(
+ self, wx.ID_ANY, "Temperature", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelTemperature,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 5,
+ )
self.textCtrlTemperature = wx.TextCtrl(self, wx.ID_ANY, "300.0")
grid_sizer_1.Add(self.textCtrlTemperature, 0, wx.ALIGN_CENTER_VERTICAL, 0)
- self.labelDoping = wx.StaticText(self, wx.ID_ANY, "Doping", style=wx.ALIGN_RIGHT)
- grid_sizer_1.Add(self.labelDoping, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20)
+ self.labelDoping = wx.StaticText(
+ self, wx.ID_ANY, "Doping", style=wx.ALIGN_RIGHT
+ )
+ grid_sizer_1.Add(
+ self.labelDoping, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 20
+ )
self.textCtrlDoping = wx.TextCtrl(self, wx.ID_ANY, "1.0")
grid_sizer_1.Add(self.textCtrlDoping, 0, wx.ALIGN_CENTER_VERTICAL, 0)
@@ -165,24 +251,25 @@ def __customProperties(self):
# Set some reasonable defaults
self.configuration = None
self.constraints = {}
- self.stypeMap = {0: 'N', 1: 'X'}
- self.metaNames = ['doping', 'temperature']
- self.constrainables = ['dscale', 'qdamp', 'qbroad']
+ self.stypeMap = {0: "N", 1: "X"}
+ self.metaNames = ["doping", "temperature"]
+ self.constrainables = ["dscale", "qdamp", "qbroad"]
self.sampList = ["data", "Nyquist", "custom"]
self._focusedText = None
# Note that the rstep and fitrstep attributes are special cases, so they
# are handled separately. Qmax is also handled with these.
- self.ctrlMap = {'fitrmin' : 'textCtrlFitFrom',
- 'fitrmax' : 'textCtrlFitTo',
- 'rmin' : 'textCtrlDataFrom',
- 'rmax' : 'textCtrlDataTo',
- 'dscale' : 'textCtrlScaleFactor',
- 'qdamp' : 'textCtrlQdamp',
- 'qbroad' : 'textCtrlQbroad',
- 'temperature' : 'textCtrlTemperature',
- 'doping' : 'textCtrlDoping',
- }
+ self.ctrlMap = {
+ "fitrmin": "textCtrlFitFrom",
+ "fitrmax": "textCtrlFitTo",
+ "rmin": "textCtrlDataFrom",
+ "rmax": "textCtrlDataTo",
+ "dscale": "textCtrlScaleFactor",
+ "qdamp": "textCtrlQdamp",
+ "qbroad": "textCtrlQbroad",
+ "temperature": "textCtrlTemperature",
+ "doping": "textCtrlDoping",
+ }
# Give each textCtrl a name that can be referenced and setup the
# validator
@@ -234,16 +321,17 @@ def setConfigurationData(self):
temperature -- float
doping -- float
"""
- if not self.configuration: return
+ if not self.configuration:
+ return
stype = self.configuration.stype
- if stype == 'N':
+ if stype == "N":
self.radioBoxStype.SetSelection(0)
- elif stype == 'X':
+ elif stype == "X":
self.radioBoxStype.SetSelection(1)
else:
- self.configuration.stype = 'N'
+ self.configuration.stype = "N"
self.radioBoxStype.SetSelection(0)
# iterate over all configurable items
@@ -258,7 +346,7 @@ def setConfigurationData(self):
if value is not None:
textCtrl.SetValue(str(value))
else:
- textCtrl.SetValue('0.0')
+ textCtrl.SetValue("0.0")
# Set qmax
val = self.configuration.qmax
@@ -281,7 +369,8 @@ def setConfigurationData(self):
def restrictConstrainedParameters(self):
"""Set 'read-only' boxes that correspond to constrained parameters."""
- if not self.configuration: return
+ if not self.configuration:
+ return
self.setToolTips(tooltips.datasetconfigurepanel)
txtbg = self.textCtrlScaleFactor.DefaultStyle.BackgroundColour
@@ -291,7 +380,9 @@ def restrictConstrainedParameters(self):
textCtrl = getattr(self, value)
if key in self.constraints:
textCtrl.SetEditable(False)
- textCtrl.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ textCtrl.SetBackgroundColour(
+ wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
+ )
tt = textCtrl.GetToolTip()
tt.SetTip(self.constraints[key].formula)
else:
@@ -303,9 +394,9 @@ def restrictConstrainedParameters(self):
def __coerseText(self, value):
"""Turn the text representation of a float into a float."""
if not value:
- value = '0'
- if value[-1].lower() in ('-', 'e'):
- value += '0'
+ value = "0"
+ if value[-1].lower() in ("-", "e"):
+ value += "0"
return float(value)
def __adjustFitRange(self, name, value):
@@ -314,28 +405,26 @@ def __adjustFitRange(self, name, value):
The fit range values are set to their defaults (the data range) when the
fit range is nonsensical.
"""
- if name == 'fitrmin':
- if value < self.configuration.rmin or\
- value >= self.configuration.fitrmax:
+ if name == "fitrmin":
+ if value < self.configuration.rmin or value >= self.configuration.fitrmax:
value = self.configuration.rmin
self.textCtrlFitFrom.SetValue(str(value))
- elif name == 'fitrmax':
- if value < self.configuration.fitrmin or\
- value >= self.configuration.rmax:
+ elif name == "fitrmax":
+ if value < self.configuration.fitrmin or value >= self.configuration.rmax:
value = self.configuration.rmax
self.textCtrlFitTo.SetValue(str(value))
return value
# EVENT CODE #############################################################
- def onStype(self, event): # wxGlade: DataSetConfigurePanel.
+ def onStype(self, event): # wxGlade: DataSetConfigurePanel.
"""Record the user's selection for stype."""
value = event.GetInt()
self.configuration.stype = self.stypeMap[value]
self.mainFrame.needsSave()
return
- def onSampling(self, event): # wxGlade: DataSetConfigurePanel.
+ def onSampling(self, event): # wxGlade: DataSetConfigurePanel.
"""Record how the data is to be sampled during the fit.
This does not use the event argument, so feel free to call this method
@@ -346,7 +435,7 @@ def onSampling(self, event): # wxGlade: DataSetConfigurePanel.
sampling = self.sampList[si]
oldstep = self.configuration.fitrstep
# Get the value of the custom sampling and enable/disable status
- if sampling == "custom": # "custom"
+ if sampling == "custom": # "custom"
txtbg = self.textCtrlFitStep.DefaultStyle.BackgroundColour
step = self.__coerseText(self.textCtrlFitStep.GetValue())
self.textCtrlFitStep.SetEditable(True)
@@ -355,7 +444,8 @@ def onSampling(self, event): # wxGlade: DataSetConfigurePanel.
step = None
self.textCtrlFitStep.SetEditable(False)
self.textCtrlFitStep.SetBackgroundColour(
- wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
+ )
# Set the value of qmax
val = self.__coerseText(self.textCtrlQmax.GetValue())
@@ -365,8 +455,7 @@ def onSampling(self, event): # wxGlade: DataSetConfigurePanel.
self.mainFrame.needsSave()
# Set the configured value
- if oldsampling != sampling or (sampling == "custom" and oldstep !=
- step):
+ if oldsampling != sampling or (sampling == "custom" and oldstep != step):
self.configuration.setFitSamplingType(sampling, step)
self.mainFrame.needsSave()
# Update the text control
@@ -385,7 +474,8 @@ def onSetFocus(self, event):
def onLoseFocus(self, event):
"""Record the user's selection for the text ctrl data."""
event.Skip()
- if not self.configuration: return
+ if not self.configuration:
+ return
textCtrl = event.GetEventObject()
value = textCtrl.GetValue()
value = self.__coerseText(value)
diff --git a/src/diffpy/pdfgui/gui/datasetconstraintpanel.py b/src/diffpy/pdfgui/gui/datasetconstraintpanel.py
index 9af15c6b..3bcd42d3 100644
--- a/src/diffpy/pdfgui/gui/datasetconstraintpanel.py
+++ b/src/diffpy/pdfgui/gui/datasetconstraintpanel.py
@@ -22,6 +22,7 @@
from diffpy.pdfgui.control.constraint import Constraint
from diffpy.pdfgui.gui.wxextensions.textctrlutils import textCtrlAsGridCell
+
class DataSetConstraintPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -43,21 +44,45 @@ def __init__(self, *args, **kwds):
def __set_properties(self):
# begin wxGlade: DataSetConstraintPanel.__set_properties
- self.panelNameLabel.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
+ self.panelNameLabel.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
# end wxGlade
def __do_layout(self):
# begin wxGlade: DataSetConstraintPanel.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
grid_sizer_1 = wx.FlexGridSizer(3, 2, 5, 10)
- sizer_panelname = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
- sizer_panelname.Add(self.panelNameLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
+ sizer_panelname = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
+ sizer_panelname.Add(
+ self.panelNameLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5
+ )
sizer_1.Add(sizer_panelname, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
- grid_sizer_1.Add(self.labelScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
- grid_sizer_1.Add(self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
- grid_sizer_1.Add(self.labelQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ grid_sizer_1.Add(
+ self.labelScaleFactor,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 5,
+ )
+ grid_sizer_1.Add(
+ self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0
+ )
+ grid_sizer_1.Add(
+ self.labelQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5
+ )
grid_sizer_1.Add(self.textCtrlQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
- grid_sizer_1.Add(self.labelQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ grid_sizer_1.Add(
+ self.labelQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5
+ )
grid_sizer_1.Add(self.textCtrlQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
sizer_1.Add(grid_sizer_1, 0, wx.ALL | wx.EXPAND, 5)
self.SetSizer(sizer_1)
@@ -71,10 +96,10 @@ def __customProperties(self):
self._focusedText = None
self.constraints = {}
self.ctrlMap = {
- 'dscale' : 'textCtrlScaleFactor',
- 'qdamp' : 'textCtrlQdamp',
- 'qbroad' : 'textCtrlQbroad',
- }
+ "dscale": "textCtrlScaleFactor",
+ "qdamp": "textCtrlQdamp",
+ "qbroad": "textCtrlQbroad",
+ }
# Give each textCtrl a name that can be referenced
for (key, value) in self.ctrlMap.items():
@@ -110,7 +135,7 @@ def setConstraintsData(self):
val = self.constraints[par].formula
textCtrl.SetValue(val)
else:
- textCtrl.SetValue('')
+ textCtrl.SetValue("")
return
def processFormula(self, value, parname):
@@ -146,7 +171,7 @@ def onLoseFocus(self, event):
val = self.constraints[par].formula
textCtrl.SetValue(val)
else:
- textCtrl.SetValue('')
+ textCtrl.SetValue("")
event.Skip()
return
@@ -157,4 +182,5 @@ def refresh(self):
self.setConstraintsData()
return
+
# end of class DataSetConstraintPanel
diff --git a/src/diffpy/pdfgui/gui/datasetpanel.py b/src/diffpy/pdfgui/gui/datasetpanel.py
index f73a285c..c0ebf88c 100644
--- a/src/diffpy/pdfgui/gui/datasetpanel.py
+++ b/src/diffpy/pdfgui/gui/datasetpanel.py
@@ -22,6 +22,7 @@
from diffpy.pdfgui.gui.datasetresultspanel import DataSetResultsPanel
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class DataSetPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -39,7 +40,9 @@ def __init__(self, *args, **kwds):
self.__set_properties()
self.__do_layout()
- self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onNotebookChanged, self.dataSetNotebook)
+ self.Bind(
+ wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onNotebookChanged, self.dataSetNotebook
+ )
# end wxGlade
self.__customProperties()
@@ -95,9 +98,9 @@ def refresh(self):
def refreshSelectedPage(self):
"""Refresh the panel corresponding to the currently selected page."""
- #self.configurePanel.refresh()
- #self.constraintPanel.refresh()
- #self.resultsPanel.refresh()
+ # self.configurePanel.refresh()
+ # self.constraintPanel.refresh()
+ # self.resultsPanel.refresh()
id = self.dataSetNotebook.GetCurrentPage().GetId()
if id == self.configurePage.GetId():
self.configurePanel.refresh()
@@ -109,13 +112,13 @@ def refreshSelectedPage(self):
# EVENT CODE #############################################################
- def onNotebookChanged(self, event): # wxGlade: DataSetPanel.
+ def onNotebookChanged(self, event): # wxGlade: DataSetPanel.
"""Refresh the selected panel."""
self.refreshSelectedPage()
return
# Overloaded from Panel.
- def Enable(self, enable = True):
+ def Enable(self, enable=True):
"""Keep the notebook enabled, just not the panels."""
self.configurePanel.Enable(enable)
self.constraintPanel.Enable(enable)
diff --git a/src/diffpy/pdfgui/gui/datasetresultspanel.py b/src/diffpy/pdfgui/gui/datasetresultspanel.py
index 515ed8c0..cfd050fe 100644
--- a/src/diffpy/pdfgui/gui/datasetresultspanel.py
+++ b/src/diffpy/pdfgui/gui/datasetresultspanel.py
@@ -31,30 +31,54 @@ def __init__(self, *args, **kwds):
sizer_7 = wx.BoxSizer(wx.VERTICAL)
- sizer_panelname = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizer_panelname = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizer_7.Add(sizer_panelname, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
self.panelNameLabel = wx.StaticText(self, wx.ID_ANY, "Data Set Results")
- self.panelNameLabel.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
- sizer_panelname.Add(self.panelNameLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
+ self.panelNameLabel.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
+ sizer_panelname.Add(
+ self.panelNameLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5
+ )
grid_sizer_1 = wx.FlexGridSizer(3, 2, 5, 10)
sizer_7.Add(grid_sizer_1, 0, wx.ALL | wx.EXPAND, 5)
self.labelScaleFactor = wx.StaticText(self, wx.ID_ANY, "Scale Factor")
- grid_sizer_1.Add(self.labelScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
-
- self.textCtrlScaleFactor = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
+ grid_sizer_1.Add(
+ self.labelScaleFactor,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ 5,
+ )
+
+ self.textCtrlScaleFactor = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
+ )
grid_sizer_1.Add(self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL, 20)
self.labelQdamp = wx.StaticText(self, wx.ID_ANY, "Qdamp")
- grid_sizer_1.Add(self.labelQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ grid_sizer_1.Add(
+ self.labelQdamp, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5
+ )
self.textCtrlQdamp = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_1.Add(self.textCtrlQdamp, 0, wx.ALIGN_CENTER_VERTICAL, 20)
self.labelQbroad = wx.StaticText(self, wx.ID_ANY, "Qbroad")
- grid_sizer_1.Add(self.labelQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5)
+ grid_sizer_1.Add(
+ self.labelQbroad, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, 5
+ )
self.textCtrlQbroad = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_1.Add(self.textCtrlQbroad, 0, wx.ALIGN_CENTER_VERTICAL, 20)
@@ -76,10 +100,11 @@ def __init__(self, *args, **kwds):
def __customProperties(self):
self.results = {}
- self.ctrlMap = {'dscale' : 'textCtrlScaleFactor',
- 'qdamp' : 'textCtrlQdamp',
- 'qbroad' : 'textCtrlQbroad',
- }
+ self.ctrlMap = {
+ "dscale": "textCtrlScaleFactor",
+ "qdamp": "textCtrlQdamp",
+ "qbroad": "textCtrlQbroad",
+ }
# Define tooltips.
self.setToolTips(tooltips.datasetresultspanel)
return
@@ -99,12 +124,12 @@ def setResultsData(self):
if value is not None:
textCtrl.SetValue(str(value))
else:
- textCtrl.SetValue('')
+ textCtrl.SetValue("")
return
# EVENT CODE #############################################################
- def onExport(self, event): # wxGlade: DataSetResultsPanel.
+ def onExport(self, event): # wxGlade: DataSetResultsPanel.
print("Event handler `onExport' not implemented")
event.Skip()
@@ -116,5 +141,4 @@ def refresh(self):
return
-
# end of class DataSetResultsPanel
diff --git a/src/diffpy/pdfgui/gui/debugoptions.py b/src/diffpy/pdfgui/gui/debugoptions.py
index 7e37a301..0404eefa 100644
--- a/src/diffpy/pdfgui/gui/debugoptions.py
+++ b/src/diffpy/pdfgui/gui/debugoptions.py
@@ -18,6 +18,7 @@
There should be exactly one instance of DebugOptions in pdfguiglobals module.
"""
+
class DebugOptions:
"""DebugOptions is a place to store various debugging options.
There should be just one instance defined in pdfguiglobals module.
@@ -31,26 +32,25 @@ class DebugOptions:
pdb, pythondebugger -- use python debugger to handle error exceptions
instead of ErrorReportDialog
"""
+
# global list of all options
alldebugoptions = (
- ('noed', 'noerrordialog'),
- ('nocf', 'noconfirm'),
- ('pdb', 'pythondebugger'),
+ ("noed", "noerrordialog"),
+ ("nocf", "noconfirm"),
+ ("pdb", "pythondebugger"),
)
# global dictionary for converting long options to short
short2long = dict(alldebugoptions)
def __init__(self):
- """Initialize DebugOptions, by default all of them are off.
- """
+ """Initialize DebugOptions, by default all of them are off."""
self.noerrordialog = False
self.noconfirm = False
self.pythondebugger = False
return
def __setattr__(self, name, value):
- """Map short options to their long equivalents.
- """
+ """Map short options to their long equivalents."""
if name in DebugOptions.short2long:
longname = DebugOptions.short2long[name]
else:
@@ -68,9 +68,10 @@ def __getattr__(self, name):
longname = DebugOptions.short2long[name]
value = getattr(self, longname)
else:
- raise AttributeError('An instance has no attribute %r' % name)
+ raise AttributeError("An instance has no attribute %r" % name)
return value
+
# End of class DebugOptions
# End of file
diff --git a/src/diffpy/pdfgui/gui/dopingseriespanel.py b/src/diffpy/pdfgui/gui/dopingseriespanel.py
index 577ad23e..288944c7 100644
--- a/src/diffpy/pdfgui/gui/dopingseriespanel.py
+++ b/src/diffpy/pdfgui/gui/dopingseriespanel.py
@@ -27,7 +27,8 @@
from diffpy.pdfgui.gui.wxextensions.listctrls import AutoWidthListCtrl
from diffpy.pdfgui.gui.wxextensions.validators import TextValidator, ALPHA_ONLY
-class DopingSeriesPanel(wx.Panel,PDFPanel):
+
+class DopingSeriesPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
# begin wxGlade: DopingSeriesPanel.__init__
@@ -36,8 +37,21 @@ def __init__(self, *args, **kwds):
sizer_1 = wx.BoxSizer(wx.VERTICAL)
- self.instructionsLabel = wx.StaticText(self, wx.ID_ANY, "Select a fit from the tree on the left then add datasets and assign\ndoping elements and values below. If you have not set up a fit to be\nthe template for the series, hit cancel and rerun this macro once a\nfit has been created.")
- self.instructionsLabel.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Sans"))
+ self.instructionsLabel = wx.StaticText(
+ self,
+ wx.ID_ANY,
+ "Select a fit from the tree on the left then add datasets and assign\ndoping elements and values below. If you have not set up a fit to be\nthe template for the series, hit cancel and rerun this macro once a\nfit has been created.",
+ )
+ self.instructionsLabel.SetFont(
+ wx.Font(
+ 10,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_NORMAL,
+ 0,
+ "Sans",
+ )
+ )
sizer_1.Add(self.instructionsLabel, 0, wx.ALL | wx.EXPAND, 5)
sizer_6 = wx.BoxSizer(wx.HORIZONTAL)
@@ -61,7 +75,9 @@ def __init__(self, *args, **kwds):
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(sizer_4, 1, wx.EXPAND, 0)
- self.listCtrlFiles = AutoWidthListCtrl(self, wx.ID_ANY, style=wx.BORDER_SUNKEN | wx.LC_EDIT_LABELS | wx.LC_REPORT)
+ self.listCtrlFiles = AutoWidthListCtrl(
+ self, wx.ID_ANY, style=wx.BORDER_SUNKEN | wx.LC_EDIT_LABELS | wx.LC_REPORT
+ )
sizer_4.Add(self.listCtrlFiles, 1, wx.ALL | wx.EXPAND, 5)
sizer_5 = wx.BoxSizer(wx.VERTICAL)
@@ -121,14 +137,14 @@ def __init__(self, *args, **kwds):
def __customProperties(self):
"""Set the custom properties."""
self.fit = None
- self.reverse = False # Reverse the sort?
+ self.reverse = False # Reverse the sort?
self.fullpath = ""
- self.datasets = [] # Contains (doping, filename) tuples
- # doping comes first for easy sorting
+ self.datasets = [] # Contains (doping, filename) tuples
+ # doping comes first for easy sorting
self.listCtrlFiles.InsertColumn(0, "Doping")
self.listCtrlFiles.InsertColumn(1, "Data Set")
- self.listCtrlFiles.SetColumnWidth(0,-2)
+ self.listCtrlFiles.SetColumnWidth(0, -2)
# Set the validators
self.textCtrlBaseElement.SetValidator(TextValidator(ALPHA_ONLY))
@@ -138,7 +154,7 @@ def __customProperties(self):
self.setToolTips(tooltips.dopingseriespanel)
return
- def onColClick(self, event): # wxGlade: DopingSeriesPanel.
+ def onColClick(self, event): # wxGlade: DopingSeriesPanel.
"""Sort by doping."""
self.datasets.sort()
if self.reverse:
@@ -147,7 +163,7 @@ def onColClick(self, event): # wxGlade: DopingSeriesPanel.
self.fillList()
return
- def onEndLabelEdit(self, event): # wxGlade: DopingSeriesPanel.
+ def onEndLabelEdit(self, event): # wxGlade: DopingSeriesPanel.
"""Update the doping in the datasets."""
index = event.GetIndex()
text = event.GetText()
@@ -165,37 +181,43 @@ def onEndLabelEdit(self, event): # wxGlade: DopingSeriesPanel.
self.reverse = False
return
- def onUp(self, event): # wxGlade: DopingSeriesPanel.
+ def onUp(self, event): # wxGlade: DopingSeriesPanel.
"""Move an item in the list up."""
index = self.listCtrlFiles.GetFirstSelected()
if index > 0:
temp = self.datasets[index]
- self.datasets[index] = self.datasets[index-1]
- self.datasets[index-1] = temp
+ self.datasets[index] = self.datasets[index - 1]
+ self.datasets[index - 1] = temp
self.fillList()
- self.listCtrlFiles.Select(index-1)
+ self.listCtrlFiles.Select(index - 1)
return
- def onDown(self, event): # wxGlade: DopingSeriesPanel.
+ def onDown(self, event): # wxGlade: DopingSeriesPanel.
"""Move an item in the list down."""
index = self.listCtrlFiles.GetFirstSelected()
- if index > -1 and index != len(self.datasets)-1:
+ if index > -1 and index != len(self.datasets) - 1:
temp = self.datasets[index]
- self.datasets[index] = self.datasets[index+1]
- self.datasets[index+1] = temp
+ self.datasets[index] = self.datasets[index + 1]
+ self.datasets[index + 1] = temp
self.fillList()
- self.listCtrlFiles.Select(index+1)
+ self.listCtrlFiles.Select(index + 1)
return
- def onAdd(self, event): # wxGlade: DopingSeriesPanel.
+ def onAdd(self, event): # wxGlade: DopingSeriesPanel.
"""Append files to the list."""
dir, filename = os.path.split(self.fullpath)
if not dir:
dir = self.mainFrame.workpath
matchstring = "PDF data files (*.gr)|*.gr|PDF fit files (*.fgr)|*.fgr|PDF fit files (*.fit)|*.fit|PDF calculation files (*.cgr)|*.cgr|PDF calculation files (*.calc)|*.calc|All Files|*"
- d = wx.FileDialog(None, "Choose files", dir, "", matchstring,
- wx.FD_OPEN|wx.FD_FILE_MUST_EXIST|wx.FD_MULTIPLE)
+ d = wx.FileDialog(
+ None,
+ "Choose files",
+ dir,
+ "",
+ matchstring,
+ wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE,
+ )
paths = []
if d.ShowModal() == wx.ID_OK:
paths = d.GetPaths()
@@ -209,7 +231,7 @@ def onAdd(self, event): # wxGlade: DopingSeriesPanel.
# Look for the doping in the filename
doping = 0.0
- rx = {'f' : r'(?:\d+(?:\.\d*)?|\d*\.\d+)' }
+ rx = {"f": r"(?:\d+(?:\.\d*)?|\d*\.\d+)"}
# Search for x123, X123, doping123, Doping123.
# Is there a better regexp? Probably...
regexp = r"(?:X|x|Doping|doping)(%(f)s)" % rx
@@ -218,16 +240,16 @@ def onAdd(self, event): # wxGlade: DopingSeriesPanel.
doping = float(res.groups()[0])
else:
# Look in the file
- infile = open(path, 'r')
+ infile = open(path, "r")
datastring = infile.read()
infile.close()
# Look for it first in the file
- res = re.search(r'^#+ start data\s*(?:#.*\s+)*', datastring, re.M)
+ res = re.search(r"^#+ start data\s*(?:#.*\s+)*", datastring, re.M)
# start_data is position where the first data line starts
if res:
start_data = res.end()
else:
- res = re.search(r'^[^#]', datastring, re.M)
+ res = re.search(r"^[^#]", datastring, re.M)
if res:
start_data = res.start()
else:
@@ -239,14 +261,15 @@ def onAdd(self, event): # wxGlade: DopingSeriesPanel.
if res:
doping = float(res.groups()[0])
# Add the new path
- if doping < 0: doping = 0.0
+ if doping < 0:
+ doping = 0.0
newdatasets.append([doping, path])
self.datasets.extend(newdatasets)
self.fillList()
return
- def onDelete(self, event): # wxGlade: DopingSeriesPanel.
+ def onDelete(self, event): # wxGlade: DopingSeriesPanel.
"""Delete selected files from the list."""
idxlist = []
item = self.listCtrlFiles.GetFirstSelected()
@@ -260,21 +283,22 @@ def onDelete(self, event): # wxGlade: DopingSeriesPanel.
self.fillList()
return
- def onOK(self, event): # wxGlade: DopingSeriesPanel.
+ def onOK(self, event): # wxGlade: DopingSeriesPanel.
"""Let's go!"""
dvals = [tp[0] for tp in self.datasets]
paths = [tp[1] for tp in self.datasets]
base = self.textCtrlBaseElement.GetValue()
dopant = self.textCtrlDopant.GetValue()
# Value checks will take place in makeDopingSeries
- org = makeDopingSeries(self.mainFrame.control, self.fit, base, dopant,
- paths, dvals)
+ org = makeDopingSeries(
+ self.mainFrame.control, self.fit, base, dopant, paths, dvals
+ )
self.treeCtrlMain.ExtendProjectTree(org, clear=False)
self.mainFrame.needsSave()
self.onCancel(event)
return
- def onCancel(self, event): # wxGlade: DopingSeriesPanel.
+ def onCancel(self, event): # wxGlade: DopingSeriesPanel.
"""Let's go, but not actually do anything."""
self.mainFrame.setMode("fitting")
self.treeCtrlMain.UnselectAll()
@@ -289,15 +313,16 @@ def checkConfiguration(self):
"""
from diffpy.pdfgui.control.controlerrors import ControlValueError
from diffpy.pdffit2 import is_element
+
base = self.textCtrlBaseElement.GetValue()
dopant = self.textCtrlDopant.GetValue()
# Make sure that the base and dopant are actual elements
base = base.title()
dopant = dopant.title()
if not is_element(base):
- raise ControlValueError("'%s' is not an element!"%base)
+ raise ControlValueError("'%s' is not an element!" % base)
if not is_element(dopant):
- raise ControlValueError("'%s' is not an element!"%dopant)
+ raise ControlValueError("'%s' is not an element!" % dopant)
return
def fillList(self):
@@ -307,11 +332,14 @@ def fillList(self):
cp = os.path.commonprefix(names)
# We want to break at the last path/separator in the common prefix
idx = cp.rfind(os.path.sep)
- if idx == -1: idx = len(cp)
+ if idx == -1:
+ idx = len(cp)
for doping, filename in self.datasets:
shortname = "..." + filename[idx:]
# index = self.listCtrlFiles.InsertItem(sys.maxsize, str(doping)) #doesn't work for windows
- index = self.listCtrlFiles.InsertItem(100000, str(doping)) #doesn't work for windows
+ index = self.listCtrlFiles.InsertItem(
+ 100000, str(doping)
+ ) # doesn't work for windows
self.listCtrlFiles.SetItem(index, 1, shortname)
return
@@ -319,7 +347,7 @@ def fillList(self):
def treeSelectionUpdate(self, node):
"""Set the current fit when the tree selection changes."""
nodetype = self.treeCtrlMain.GetNodeType(node)
- if nodetype == 'fit':
+ if nodetype == "fit":
self.fit = self.treeCtrlMain.GetControlData(node)
self.refresh()
return
@@ -339,12 +367,17 @@ def refresh(self):
node = selections[0]
nodetype = self.treeCtrlMain.GetNodeType(node)
- if node and nodetype == "fit" \
- and self.fit and self.fit.hasDataSets() \
- and self.fit.hasStructures():
+ if (
+ node
+ and nodetype == "fit"
+ and self.fit
+ and self.fit.hasDataSets()
+ and self.fit.hasStructures()
+ ):
self.goButton.Enable()
else:
self.goButton.Enable(False)
return
+
# end of class DopingSeriesPanel
diff --git a/src/diffpy/pdfgui/gui/errorreportdialog.py b/src/diffpy/pdfgui/gui/errorreportdialog.py
index 93d890ca..84c54e92 100644
--- a/src/diffpy/pdfgui/gui/errorreportdialog.py
+++ b/src/diffpy/pdfgui/gui/errorreportdialog.py
@@ -38,31 +38,48 @@
Discuss PDFgui and learn about new developments and features at
{mlist}.
-""".format(issues=ISSUESTRACKER, mlist=USERSMAILINGLIST)
+""".format(
+ issues=ISSUESTRACKER, mlist=USERSMAILINGLIST
+)
-_MSG_FEATURE_REQUEST = """
+_MSG_FEATURE_REQUEST = (
+ """
Share you thoughts about PDFgui!
-""" + _MSG_TRAILER
+"""
+ + _MSG_TRAILER
+)
-_MSG_ERROR_REPORT = """
+_MSG_ERROR_REPORT = (
+ """
PDFgui has encountered a problem. We are sorry for the inconvenience.
-""" + _MSG_TRAILER
+"""
+ + _MSG_TRAILER
+)
# ----------------------------------------------------------------------------
+
class ErrorReportDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: ErrorReportDialog.__init__
- kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX | wx.RESIZE_BORDER
+ kwds["style"] = (
+ kwds.get("style", 0)
+ | wx.DEFAULT_DIALOG_STYLE
+ | wx.MAXIMIZE_BOX
+ | wx.MINIMIZE_BOX
+ | wx.RESIZE_BORDER
+ )
wx.Dialog.__init__(self, *args, **kwds)
self.SetSize((540, 600))
self.label_header = wx.html.HtmlWindow(self, wx.ID_ANY)
self.label_log = wx.StaticText(self, wx.ID_ANY, "Error Log:")
- self.text_ctrl_log = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_MULTILINE | wx.TE_READONLY)
+ self.text_ctrl_log = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_MULTILINE | wx.TE_READONLY
+ )
self.static_line_1 = wx.StaticLine(self, wx.ID_ANY)
self.button_google = wx.Button(self, wx.ID_ANY, "Google This Error")
self.button_copyErrorLog = wx.Button(self, wx.ID_ANY, "Copy Error Log")
@@ -94,7 +111,9 @@ def __do_layout(self):
sizer_log.Add(self.label_log, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 5)
sizer_log.Add(self.text_ctrl_log, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
sizer_main.Add(sizer_log, 3, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
- sizer_main.Add(self.static_line_1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 5)
+ sizer_main.Add(
+ self.static_line_1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 5
+ )
sizer_buttons.Add((20, 20), 1, 0, 0)
sizer_buttons.Add(self.button_google, 0, wx.ALL, 5)
sizer_buttons.Add(self.button_copyErrorLog, 0, wx.ALL, 5)
@@ -116,7 +135,7 @@ def ShowModal(self):
if self.text_ctrl_log.GetValue().strip() == "":
self.SetTitle("Feature Request / Bug Report")
self.label_header.SetPage(_MSG_FEATURE_REQUEST)
- self.label_header.SetBackgroundColour('')
+ self.label_header.SetBackgroundColour("")
self.label_log.Hide()
self.text_ctrl_log.Hide()
self.button_google.Hide()
@@ -126,7 +145,7 @@ def ShowModal(self):
else:
self.SetTitle("Problem Report for PDFgui")
self.label_header.SetPage(_MSG_ERROR_REPORT)
- self.label_header.SetBackgroundColour('')
+ self.label_header.SetBackgroundColour("")
self.text_ctrl_log.Show()
self.errorReport = True
@@ -140,6 +159,7 @@ def onGoogle(self, event): # wxGlade: ErrorReportDialog.
error message extracted from exception traceback.
"""
from six.moves.urllib.parse import quote_plus
+
traceback = self.text_ctrl_log.GetValue()
terms = _extractSearchTerms(traceback)
str_to_search = " ".join(terms) if terms else traceback.strip()
@@ -165,10 +185,12 @@ def onURL(self, event): # wxGlade: ErrorReportDialog.
link = event.GetLinkInfo()
webbrowser.open(link.GetHref())
+
# end of class ErrorReportDialog
# Helper functions -----------------------------------------------------------
+
def _extractSearchTerms(tbtext):
"""
Extract search words from a Python exception traceback.
@@ -185,14 +207,15 @@ def _extractSearchTerms(tbtext):
"""
# extract module names and function names from a traceback
modfncpairs = re.findall(
- r'File.*?([^/\\]*[.]py).*?, line \d+, in (\w+)',
- tbtext, re.MULTILINE)
+ r"File.*?([^/\\]*[.]py).*?, line \d+, in (\w+)", tbtext, re.MULTILINE
+ )
modfnc = list(sum(modfncpairs, ()))
# find the last line starting with "SomeError: ...".
- lasterr = re.findall(r'^\w+Error:.*', tbtext, re.MULTILINE)
+ lasterr = re.findall(r"^\w+Error:.*", tbtext, re.MULTILINE)
rv = modfnc + lasterr[-1:]
return rv
+
##### testing code ############################################################
_EXAMPLE_TRACEBACK = r"""
@@ -206,6 +229,7 @@ def _extractSearchTerms(tbtext):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 115: ordinal not in range(128)
""".strip()
+
class MyApp(wx.App):
def OnInit(self):
self.dialog = ErrorReportDialog(None, -1, "")
@@ -216,10 +240,11 @@ def OnInit(self):
return True
def test(self):
- '''Testing code goes here.'''
+ """Testing code goes here."""
self.dialog.text_ctrl_log.SetValue(_EXAMPLE_TRACEBACK)
return
+
# end of class MyApp
if __name__ == "__main__":
diff --git a/src/diffpy/pdfgui/gui/errorreportdialog_control_fix.py b/src/diffpy/pdfgui/gui/errorreportdialog_control_fix.py
index cf2e5863..216d71d9 100644
--- a/src/diffpy/pdfgui/gui/errorreportdialog_control_fix.py
+++ b/src/diffpy/pdfgui/gui/errorreportdialog_control_fix.py
@@ -40,10 +40,17 @@
# ----------------------------------------------------------------------------
+
class ErrorReportDialogControlFix(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: ErrorReportDialog.__init__
- kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX | wx.RESIZE_BORDER
+ kwds["style"] = (
+ kwds.get("style", 0)
+ | wx.DEFAULT_DIALOG_STYLE
+ | wx.MAXIMIZE_BOX
+ | wx.MINIMIZE_BOX
+ | wx.RESIZE_BORDER
+ )
wx.Dialog.__init__(self, *args, **kwds)
self.SetSize((540, 200))
self.label_header = wx.html.HtmlWindow(self, wx.ID_ANY)
@@ -102,7 +109,7 @@ def ShowModal(self):
self.SetTitle("Problem Report for PDFgui")
self.label_header.SetPage(_MSG_ERROR_REPORT)
- self.label_header.SetBackgroundColour('')
+ self.label_header.SetBackgroundColour("")
# self.text_ctrl_log.Show()
self.errorReport = True
@@ -113,6 +120,7 @@ def ShowModal(self):
# Helper functions -----------------------------------------------------------
+
def _extractSearchTerms(tbtext):
"""
Extract search words from a Python exception traceback.
@@ -129,14 +137,15 @@ def _extractSearchTerms(tbtext):
"""
# extract module names and function names from a traceback
modfncpairs = re.findall(
- r'File.*?([^/\\]*[.]py).*?, line \d+, in (\w+)',
- tbtext, re.MULTILINE)
+ r"File.*?([^/\\]*[.]py).*?, line \d+, in (\w+)", tbtext, re.MULTILINE
+ )
modfnc = list(sum(modfncpairs, ()))
# find the last line starting with "SomeError: ...".
- lasterr = re.findall(r'^\w+Error:.*', tbtext, re.MULTILINE)
+ lasterr = re.findall(r"^\w+Error:.*", tbtext, re.MULTILINE)
rv = modfnc + lasterr[-1:]
return rv
+
##### testing code ############################################################
_EXAMPLE_TRACEBACK = r"""
@@ -150,6 +159,7 @@ def _extractSearchTerms(tbtext):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 115: ordinal not in range(128)
""".strip()
+
class MyApp(wx.App):
def OnInit(self):
self.dialog = ErrorReportDialog(None, -1, "")
@@ -160,10 +170,11 @@ def OnInit(self):
return True
def test(self):
- '''Testing code goes here.'''
+ """Testing code goes here."""
# self.dialog.text_ctrl_log.SetValue(_EXAMPLE_TRACEBACK)
return
+
# end of class MyApp
if __name__ == "__main__":
diff --git a/src/diffpy/pdfgui/gui/errorwrapper.py b/src/diffpy/pdfgui/gui/errorwrapper.py
index 4eb465f1..df3f04d0 100644
--- a/src/diffpy/pdfgui/gui/errorwrapper.py
+++ b/src/diffpy/pdfgui/gui/errorwrapper.py
@@ -33,6 +33,7 @@
# these methods will not be wrapped in catchFunctionErrors
_EXCLUDED_METHODS = dict.fromkeys(dir(wx.Panel) + dir(wx.Dialog))
+
def catchFunctionErrors(obj, funcName):
"""Wrap a function so its errors get transferred to a dialog.
@@ -61,7 +62,7 @@ def _f(*args, **kwargs):
try:
return func(*args, **kwargs)
- #to be deleted. temporarily used for show the select-control error.
+ # to be deleted. temporarily used for show the select-control error.
except TempControlSelectError:
dlg = ErrorReportDialogControlFix(obj.mainFrame)
dlg.ShowModal()
@@ -72,13 +73,14 @@ def _f(*args, **kwargs):
if not hasmf:
raise
message = str(e)
- obj.mainFrame.showMessage(message, 'Oops!')
+ obj.mainFrame.showMessage(message, "Oops!")
return rvpass
# Everything else
except:
if pdfguiglobals.dbopts.pythondebugger:
import pdb
+
tb = sys.exc_info()[2]
pdb.post_mortem(tb)
return rvpass
@@ -88,7 +90,7 @@ def _f(*args, **kwargs):
message = "".join(msglines)
if obj.mainFrame.quitting:
sys.stderr.write(message)
- sys.stderr.write('\n')
+ sys.stderr.write("\n")
else:
dlg = ErrorReportDialog(obj.mainFrame)
dlg.text_ctrl_log.SetValue(message)
@@ -119,11 +121,16 @@ def catchObjectErrors(obj, exclude=None):
else:
extra_excludes = {}
- funcNames = [item for item in dir(obj) if not item.startswith('_')
- and item not in _EXCLUDED_METHODS and item not in extra_excludes]
+ funcNames = [
+ item
+ for item in dir(obj)
+ if not item.startswith("_")
+ and item not in _EXCLUDED_METHODS
+ and item not in extra_excludes
+ ]
for name in funcNames:
- if hasattr( getattr(obj, name), '__call__'):
+ if hasattr(getattr(obj, name), "__call__"):
setattr(obj, name, catchFunctionErrors(obj, name))
return
diff --git a/src/diffpy/pdfgui/gui/extendedplotframe.py b/src/diffpy/pdfgui/gui/extendedplotframe.py
index f4ed05ff..b34a722f 100644
--- a/src/diffpy/pdfgui/gui/extendedplotframe.py
+++ b/src/diffpy/pdfgui/gui/extendedplotframe.py
@@ -20,7 +20,8 @@
import os.path
import matplotlib
-matplotlib.use('WXAgg')
+
+matplotlib.use("WXAgg")
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavToolbar
from matplotlib.figure import Figure
@@ -31,26 +32,28 @@
from diffpy.pdfgui.gui.wxextensions import wx12
from diffpy.pdfgui.gui.pdfguiglobals import iconpath
-DATA_SAVE_ID = wx12.NewIdRef()
+DATA_SAVE_ID = wx12.NewIdRef()
+
class ExtendedToolbar(NavToolbar):
"""An extended plotting toolbar with a save and close button."""
# override NavToolbar.toolitems to exclude the subplots tool.
- toolitems = tuple(el for el in NavToolbar.toolitems
- if el[0] != 'Subplots')
+ toolitems = tuple(el for el in NavToolbar.toolitems if el[0] != "Subplots")
def __init__(self, canvas):
NavToolbar.__init__(self, canvas)
wx12.patchToolBarMethods(self)
# Load customized icon image
- save_icon_fp = iconpath('exportplotdata.png')
+ save_icon_fp = iconpath("exportplotdata.png")
save_icon = wx.Bitmap(save_icon_fp)
# Add new buttons
- self.AddTool(DATA_SAVE_ID, "Export data", save_icon,
- shortHelp='Export plot data to file')
+ self.AddTool(
+ DATA_SAVE_ID, "Export data", save_icon, shortHelp="Export plot data to file"
+ )
return
+
# End class ExtendedToolbar
@@ -65,9 +68,9 @@ class ExtendedPlotFrame(wx.Frame):
"""
# keyboard shortcut(s) for closing plot window
- close_keys = set(matplotlib.rcParamsDefault['keymap.quit'])
+ close_keys = set(matplotlib.rcParamsDefault["keymap.quit"])
- def __init__(self, parent = None, *args, **kwargs):
+ def __init__(self, parent=None, *args, **kwargs):
"""Initialize the CanvasFrame.
The frame uses ExtendedToolbar as a toolbar, which has a save data
@@ -77,45 +80,45 @@ def __init__(self, parent = None, *args, **kwargs):
args -- argument list
kwargs -- keyword argument list
"""
- wx.Frame.__init__(self,parent,-1,'ExtendedPlotFrame',size=(550,350))
+ wx.Frame.__init__(self, parent, -1, "ExtendedPlotFrame", size=(550, 350))
# figsize in inches
- self.figure = Figure(figsize=(0.5,0.5), dpi=72)
+ self.figure = Figure(figsize=(0.5, 0.5), dpi=72)
# we will manage view scale ourselves
self.subplot = self.figure.add_subplot(111, autoscale_on=False)
self.canvas = FigureCanvas(self, -1, self.figure)
# Introspection data
- self.dirname = ''
- self.filename = ''
+ self.dirname = ""
+ self.filename = ""
self.sizer = wx.BoxSizer(wx.VERTICAL)
- self.sizer.Add(self.canvas, 1, wx.TOP|wx.LEFT|wx.EXPAND)
+ self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
self.toolbar = ExtendedToolbar(self.canvas)
self.toolbar.Realize()
- self.coordLabel = wx.StaticText(self,-1,style = wx.ALIGN_RIGHT|wx.NO_BORDER)
+ self.coordLabel = wx.StaticText(self, -1, style=wx.ALIGN_RIGHT | wx.NO_BORDER)
# Place coordinates textbox in a horizontal sizer next to the toolbar.
barSizer = wx.BoxSizer(wx.HORIZONTAL)
- self.sizer.Add(barSizer, 0, wx.EXPAND|wx.CENTER)
+ self.sizer.Add(barSizer, 0, wx.EXPAND | wx.CENTER)
barSizer.Add(self.toolbar, 0, wx.CENTER)
- barSizer.Add((20,10),0)
+ barSizer.Add((20, 10), 0)
barSizer.Add(self.coordLabel, 0, wx.CENTER)
# update the axes menu on the toolbar
self.toolbar.update()
self.SetSizer(self.sizer)
self.Fit()
- self.SetSize((600,400))
+ self.SetSize((600, 400))
# Use toolbar's color for coordinates label background.
self.SetBackgroundColour(self.toolbar.GetBackgroundColour())
# FIXME -- toolbar background color does not match on Mac OS X.
# Use GIMP - picked color until a proper way is found.
- if wx.Platform == '__WXMAC__':
+ if wx.Platform == "__WXMAC__":
self.SetBackgroundColour((200, 200, 200, 255))
- self.canvas.mpl_connect('motion_notify_event', self.UpdateStatusBar)
- self.canvas.mpl_connect('key_press_event', self.mplKeyPress)
+ self.canvas.mpl_connect("motion_notify_event", self.UpdateStatusBar)
+ self.canvas.mpl_connect("key_press_event", self.mplKeyPress)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_TOOL, self.savePlotData, id=DATA_SAVE_ID)
self.Bind(wx.EVT_CLOSE, self.onClose)
@@ -127,7 +130,7 @@ def __init__(self, parent = None, *args, **kwargs):
# EVENT CODE #############################################################
def onClose(self, evt):
"""Close the frame."""
- if hasattr(self, 'plotter'):
+ if hasattr(self, "plotter"):
self.plotter.onWindowClose()
self.Destroy()
return
@@ -138,12 +141,18 @@ def OnPaint(self, event):
def savePlotData(self, evt):
"""Save the data in the plot in columns."""
- d = wx.FileDialog(None, "Save as...", self.dirname, self.filename,
- "(*.dat)|*.dat|(*.txt)|*.txt|(*)|*", wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
+ d = wx.FileDialog(
+ None,
+ "Save as...",
+ self.dirname,
+ self.filename,
+ "(*.dat)|*.dat|(*.txt)|*.txt|(*)|*",
+ wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
+ )
if d.ShowModal() == wx.ID_OK:
fullname = d.GetPath()
self.dirname = os.path.dirname(fullname)
- self.filename = os.path.basename(fullname)
+ self.filename = os.path.basename(fullname)
self.plotter.export(fullname)
d.Destroy()
@@ -155,7 +164,6 @@ def UpdateStatusBar(self, event):
xystr = "x = %g, y = %g" % (x, y)
self.coordLabel.SetLabel(xystr)
-
def mplKeyPress(self, event):
"""Process keyboard input in matplotlib plot window.
@@ -165,10 +173,8 @@ def mplKeyPress(self, event):
self.Close()
return
-
def replot(self):
- """officially call function in matplotlib to do drawing
- """
+ """officially call function in matplotlib to do drawing"""
self.canvas.draw()
def insertCurve(self, xData, yData, style):
@@ -178,7 +184,7 @@ def insertCurve(self, xData, yData, style):
style -- the way curve should be plotted
return: internal reference to the newly added curve
"""
- stylestr,properties = self.__translateStyles(style)
+ stylestr, properties = self.__translateStyles(style)
curveRef = self.subplot.plot(xData, yData, stylestr, **properties)[0]
self.subplot.legend(**legendBoxProperties())
try:
@@ -208,7 +214,7 @@ def changeStyle(self, curveRef, style):
style -- style dictionary
"""
stylestr, properties = self.__translateStyles(style)
- #FIXME: we discard stylestr because it seems there's no way
+ # FIXME: we discard stylestr because it seems there's no way
# it can be changed afterwards.
setp((curveRef,), **properties)
self.subplot.legend(**legendBoxProperties())
@@ -224,13 +230,12 @@ def removeCurve(self, curveRef):
self.__updateViewLimits()
def __updateViewLimits(self):
- """adjust the subplot range in order to show all curves correctly.
- """
+ """adjust the subplot range in order to show all curves correctly."""
# NOTE:
# we need to adjust view limits by ourselves because Matplotlib can't
# set the legend nicely when there are multiple curves in the plot.
# Beside, autoscale can not automatically respond to data change.
- if len(self.datalims) == 0 :
+ if len(self.datalims) == 0:
return
# ignore previous range
self.subplot.dataLim.ignore(True)
@@ -242,7 +247,7 @@ def __updateViewLimits(self):
# If multiple curve, we need calculate new x limits because legend box
# take up some space
- #NOTE: 3 and 0.33 is our best estimation for a good view
+ # NOTE: 3 and 0.33 is our best estimation for a good view
# 2007-10-25 PJ: it is better to use full plot area
# if len(self.datalims) > 3:
# # leave extra room for legend by shift the upper bound for x axis
@@ -258,46 +263,68 @@ def __translateStyles(self, style):
style -- general curve style dictionary (defined in demoplot)
"""
- #Translation dictionary
- lineStyleDict ={'solid':'-','dash':'--','dot':':','dashDot':'-.'}
- symbolDict ={'diamond':'d','square':'s','circle':'o',
- 'cross':'+','xCross':'x','triangle':'^'}
- colorDict = {'blue':'b','green':'g','red':'r','cyan':'c',
- 'magenta':'m','yellow':'y','black':'k','white':'w',
- 'darkRed':'#8B0000', 'darkGreen':'#006400', 'darkCyan':'#008B8B',
- 'darkYellow':'#FFD700','darkBlue':'#00008B','darkMagenta':'#8B008B'}
+ # Translation dictionary
+ lineStyleDict = {"solid": "-", "dash": "--", "dot": ":", "dashDot": "-."}
+ symbolDict = {
+ "diamond": "d",
+ "square": "s",
+ "circle": "o",
+ "cross": "+",
+ "xCross": "x",
+ "triangle": "^",
+ }
+ colorDict = {
+ "blue": "b",
+ "green": "g",
+ "red": "r",
+ "cyan": "c",
+ "magenta": "m",
+ "yellow": "y",
+ "black": "k",
+ "white": "w",
+ "darkRed": "#8B0000",
+ "darkGreen": "#006400",
+ "darkCyan": "#008B8B",
+ "darkYellow": "#FFD700",
+ "darkBlue": "#00008B",
+ "darkMagenta": "#8B008B",
+ }
properties = {}
- #NOTE: matplotlib takes additional string for plotting. It's
+ # NOTE: matplotlib takes additional string for plotting. It's
# purpose is like 'with' in Gnuplot
- stylestr = ''
+ stylestr = ""
# color is universal for either lines, points or linepoints
- color = colorDict.get(style['color'], 'k')
+ color = colorDict.get(style["color"], "k")
- if style['with'] in ('points', 'linespoints'):
+ if style["with"] in ("points", "linespoints"):
# require symbol properties
- stylestr = '.'
- symbol = symbolDict.get(style['symbol'],'s') # prefer square
- symbolSize = style['symbolSize']
- symbolColor = colorDict.get(style['symbolColor'], 'k')
- properties.update({#'linewidth':0.0, # doesn't affect any
- 'markerfacecolor':symbolColor,
- 'markeredgecolor':color,
- 'marker':symbol,'markersize':symbolSize})
- if style['with'] != 'points':
+ stylestr = "."
+ symbol = symbolDict.get(style["symbol"], "s") # prefer square
+ symbolSize = style["symbolSize"]
+ symbolColor = colorDict.get(style["symbolColor"], "k")
+ properties.update(
+ { #'linewidth':0.0, # doesn't affect any
+ "markerfacecolor": symbolColor,
+ "markeredgecolor": color,
+ "marker": symbol,
+ "markersize": symbolSize,
+ }
+ )
+ if style["with"] != "points":
# not 'points', so line properties are required as well
- lineStyle = lineStyleDict.get(style['line'],'-') #prefer solid
- lineWidth = style['width']
+ lineStyle = lineStyleDict.get(style["line"], "-") # prefer solid
+ lineWidth = style["width"]
stylestr += lineStyle
- properties.update({'color':color,'linestyle':lineStyle,
- 'linewidth':lineWidth})
+ properties.update(
+ {"color": color, "linestyle": lineStyle, "linewidth": lineWidth}
+ )
- if 'legend' in style:
- properties['label'] = style['legend']
+ if "legend" in style:
+ properties["label"] = style["legend"]
return stylestr, properties
-
def setTitle(self, wt, gt):
"""set graph labels
@@ -324,9 +351,10 @@ def setYLabel(self, y):
def clear(self):
"""erase all curves"""
self.subplot.clear()
- self.curverefs =[]
+ self.curverefs = []
self.replot()
+
# End class ExtendedPlotFrame
@@ -340,32 +368,35 @@ def legendBoxProperties():
"""
global _lbp
# return immediately if properties have already been cached
- if len(_lbp) > 0: return _lbp
+ if len(_lbp) > 0:
+ return _lbp
# figure out matplotlib version and appropriate names
from pkg_resources import parse_version
from matplotlib import __version__ as mplver
- if parse_version(mplver) >= parse_version('0.98.5'):
+
+ if parse_version(mplver) >= parse_version("0.98.5"):
_lbp = {
- 'loc' : 'upper right',
- 'numpoints' : 3, # number of points in the legend line
- 'borderpad' : 0.25, # whitespace in the legend border
- 'labelspacing' : 0, # space between legend entries
- 'handlelength' : 1.5, # the length of the legend lines
- 'handletextpad' : 0.5, # separation between line and text
- 'prop' : FontProperties(size='medium'),
+ "loc": "upper right",
+ "numpoints": 3, # number of points in the legend line
+ "borderpad": 0.25, # whitespace in the legend border
+ "labelspacing": 0, # space between legend entries
+ "handlelength": 1.5, # the length of the legend lines
+ "handletextpad": 0.5, # separation between line and text
+ "prop": FontProperties(size="medium"),
}
else:
_lbp = {
- 'loc' : 'upper right',
- 'numpoints' : 3, # number of points in the legend line
- 'pad' : 0.20, # whitespace in the legend border
- 'labelsep' : 0.005, # space between legend entries
- 'handlelen' : 0.03, # the length of the legend lines
- 'handletextsep' : 0.02, # separation between line and text
- 'prop' : FontProperties(size='medium'),
+ "loc": "upper right",
+ "numpoints": 3, # number of points in the legend line
+ "pad": 0.20, # whitespace in the legend border
+ "labelsep": 0.005, # space between legend entries
+ "handlelen": 0.03, # the length of the legend lines
+ "handletextsep": 0.02, # separation between line and text
+ "prop": FontProperties(size="medium"),
}
return _lbp
+
_lbp = {}
# End of legendBoxProperties
@@ -376,21 +407,22 @@ def legendBoxProperties():
class MyApp(wx.App):
def OnInit(self):
from numpy import arange, sin, pi, cos
- 'Create the main window and insert the custom frame'
- x = arange(0.0,3.0,0.01)
- s = sin(2*pi*x)
- c = cos(2*pi*x)
- t = sin(2*pi*x) + cos(2*pi*x)
+
+ "Create the main window and insert the custom frame"
+ x = arange(0.0, 3.0, 0.01)
+ s = sin(2 * pi * x)
+ c = cos(2 * pi * x)
+ t = sin(2 * pi * x) + cos(2 * pi * x)
frame = ExtendedPlotFrame(None)
- style = {'with':'lines', 'color':'blue','line':'solid','width':2}
- style['legend'] = 'sin(x)'
- frame.insertCurve(x,s, style)
- style = {'with':'lines', 'color':'red','line':'solid','width':2}
- style['legend'] = 'cos(x)'
- frame.insertCurve(x,c, style)
- style = {'with':'lines', 'color':'black','line':'solid','width':2}
- #style['legend'] = 'sin(x)+cos(x)'
- frame.insertCurve(x,t, style)
+ style = {"with": "lines", "color": "blue", "line": "solid", "width": 2}
+ style["legend"] = "sin(x)"
+ frame.insertCurve(x, s, style)
+ style = {"with": "lines", "color": "red", "line": "solid", "width": 2}
+ style["legend"] = "cos(x)"
+ frame.insertCurve(x, c, style)
+ style = {"with": "lines", "color": "black", "line": "solid", "width": 2}
+ # style['legend'] = 'sin(x)+cos(x)'
+ frame.insertCurve(x, t, style)
frame.Show(True)
return True
diff --git a/src/diffpy/pdfgui/gui/fitnotebookpanel.py b/src/diffpy/pdfgui/gui/fitnotebookpanel.py
index e93ccf03..77b5634b 100644
--- a/src/diffpy/pdfgui/gui/fitnotebookpanel.py
+++ b/src/diffpy/pdfgui/gui/fitnotebookpanel.py
@@ -21,6 +21,7 @@
from diffpy.pdfgui.gui.parameterspanel import ParametersPanel
from diffpy.pdfgui.gui.resultspanel import ResultsPanel
+
class FitNotebookPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
# begin wxGlade: FitNotebookPanel.__init__
@@ -60,17 +61,18 @@ def __customProperties(self):
self.mainFrame = None
return
- def onPageChanged(self, event): # wxGlade: FitNotebookPanel.
+ def onPageChanged(self, event): # wxGlade: FitNotebookPanel.
"""Refresh the panel visible panel."""
self.refresh()
return
- def onPageChanging(self, event): # wxGlade: FitNotebookPanel.
+ def onPageChanging(self, event): # wxGlade: FitNotebookPanel.
event.Skip()
def refresh(self):
"""Refresh the panels."""
- if not self.fit: return
+ if not self.fit:
+ return
panel = self.fitnotebook.GetCurrentPage()
panel.mainFrame = self.mainFrame
panel.refresh()
@@ -79,7 +81,7 @@ def refresh(self):
panel.refresh()
# Overloaded from Panel.
- def Enable(self, enable = True):
+ def Enable(self, enable=True):
"""Keep the notebook enabled, just not the panels.
outputPanel is immune from this, since it needs to be interacted with.
@@ -87,4 +89,5 @@ def Enable(self, enable = True):
self.parametersPanel.Enable(enable)
return
+
# end of class FitNotebookPanel
diff --git a/src/diffpy/pdfgui/gui/fittree.py b/src/diffpy/pdfgui/gui/fittree.py
index af50df8c..51cf15e3 100644
--- a/src/diffpy/pdfgui/gui/fittree.py
+++ b/src/diffpy/pdfgui/gui/fittree.py
@@ -32,6 +32,7 @@
from diffpy.pdfgui.utils import safeCPickleDumps, pickle_loads
from diffpy.pdfgui.gui.wxextensions import wx12
+
class FitTree(wx12.TreeCtrl):
"""TreeCtrl designed to organize pdffit fits.
@@ -60,10 +61,16 @@ class FitTree(wx12.TreeCtrl):
"""
- def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
- size=wx.DefaultSize,
- style=wx.TR_HAS_BUTTONS|wx.TR_HIDE_ROOT|wx.TR_MULTIPLE,
- validator=wx.DefaultValidator, name="FitTree"):
+ def __init__(
+ self,
+ parent,
+ id=-1,
+ pos=wx.DefaultPosition,
+ size=wx.DefaultSize,
+ style=wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_MULTIPLE,
+ validator=wx.DefaultValidator,
+ name="FitTree",
+ ):
wx.TreeCtrl.__init__(self, parent, id, pos, size, style)
# Define the control
@@ -75,7 +82,7 @@ def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
phasebmp = wx.Bitmap(iconpath("phaseitem.png"))
fitbmp = wx.Bitmap(iconpath("fititem.png"))
calcbmp = wx.Bitmap(iconpath("calculationitem.png"))
- isz = (16,16)
+ isz = (16, 16)
il = wx.ImageList(isz[0], isz[1])
self.fitbmid = il.Add(fitbmp)
self.dtsbmid = il.Add(datasetbmp)
@@ -84,7 +91,6 @@ def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
self.SetImageList(il)
self.treeImageList = il
-
return
def InitializeTree(self):
@@ -92,12 +98,12 @@ def InitializeTree(self):
self.root = self.AddRoot("The Root Item")
self.SetNodeType(self.root, "root")
# Testing code
- #fit1 = self.AddFit()
- #self.AddPhase(fit1, "Phase 1")
- #self.AddPhase(fit1, "Phase 2")
- #self.AddDataSet(fit1, "Data 1")
- #self.AddCalc(fit1, "Calc 1")
- #self.Expand(fit1)
+ # fit1 = self.AddFit()
+ # self.AddPhase(fit1, "Phase 1")
+ # self.AddPhase(fit1, "Phase 2")
+ # self.AddDataSet(fit1, "Data 1")
+ # self.AddCalc(fit1, "Calc 1")
+ # self.Expand(fit1)
return
def GetTreeItemDict(self, node):
@@ -106,7 +112,8 @@ def GetTreeItemDict(self, node):
def GetFitRoot(self, node):
"""Return the id of the fit in which the passed node resides."""
- if not node: return
+ if not node:
+ return
fitId = node
nextId = self.GetItemParent(node)
while nextId != self.root:
@@ -136,14 +143,15 @@ def GetAllType(self, node):
"""Get the id of each item in the tree of the same type as node."""
nodetype = self.GetNodeType(node)
fits = self.GetChildren(self.root)
- if nodetype == 'fit':
+ if nodetype == "fit":
return fits
else:
sametype = []
for fit in fits:
children = self.GetChildren(fit)
- sametype.extend( [child for child in children if
- self.GetNodeType(child) == nodetype] )
+ sametype.extend(
+ [child for child in children if self.GetNodeType(child) == nodetype]
+ )
return sametype
def GetPhases(self, node):
@@ -152,7 +160,7 @@ def GetPhases(self, node):
node is either the fit-root or a node in the fit-branch of interest.
"""
nodes = self.GetChildren(self.GetFitRoot(node))
- ids = [id for id in nodes if self.GetNodeType(id) == 'phase']
+ ids = [id for id in nodes if self.GetNodeType(id) == "phase"]
return ids
def GetDataSets(self, node):
@@ -161,7 +169,7 @@ def GetDataSets(self, node):
node is either the fit-root or a node in the fit-branch of interest.
"""
nodes = self.GetChildren(self.GetFitRoot(node))
- ids = [id for id in nodes if self.GetNodeType(id) == 'dataset']
+ ids = [id for id in nodes if self.GetNodeType(id) == "dataset"]
return ids
def GetCalculations(self, node):
@@ -170,7 +178,7 @@ def GetCalculations(self, node):
node is either the fit-root or a node in the fit-branch of interest.
"""
nodes = self.GetChildren(self.GetFitRoot(node))
- ids = [id for id in nodes if self.GetNodeType(id) == 'calculation']
+ ids = [id for id in nodes if self.GetNodeType(id) == "calculation"]
return ids
def GetNodeType(self, node):
@@ -183,16 +191,17 @@ def GetNodeType(self, node):
datadict = self.GetTreeItemDict(node)
if datadict is None:
return None
- return datadict['type']
+ return datadict["type"]
def SetNodeType(self, node, tp):
"""Set the node type of a node."""
- if not node: return
+ if not node:
+ return
datadict = self.GetTreeItemDict(node)
if datadict is None:
datadict = {}
self.SetItemData(node, datadict)
- datadict['type'] = tp
+ datadict["type"] = tp
return
def GetBranchName(self, node):
@@ -210,9 +219,12 @@ def GetLastPhase(self, node):
siblings = self.GetChildren(node)
lastphase = None
for sib in siblings:
- if self.GetNodeType(sib) == "dataset": break
- elif self.GetNodeType(sib) == "calculation": break
- else: lastphase = sib
+ if self.GetNodeType(sib) == "dataset":
+ break
+ elif self.GetNodeType(sib) == "calculation":
+ break
+ else:
+ lastphase = sib
return lastphase
def GetLastDataSet(self, node):
@@ -225,8 +237,10 @@ def GetLastDataSet(self, node):
siblings = self.GetChildren(node)
lastdata = None
for sib in siblings:
- if self.GetNodeType(sib) == "calculation": break
- else: lastdata = sib
+ if self.GetNodeType(sib) == "calculation":
+ break
+ else:
+ lastdata = sib
return lastdata
def GetNumPhases(self, node):
@@ -236,7 +250,7 @@ def GetNumPhases(self, node):
"""
parent = self.GetFitRoot(node)
family = self.GetChildren(parent)
- phases = [item for item in family if self.GetNodeType(item) == 'phase']
+ phases = [item for item in family if self.GetNodeType(item) == "phase"]
return len(phases)
def GetNumDataSets(self, node):
@@ -246,7 +260,7 @@ def GetNumDataSets(self, node):
"""
parent = self.GetFitRoot(node)
family = self.GetChildren(parent)
- phases = [item for item in family if self.GetNodeType(item) == 'dataset']
+ phases = [item for item in family if self.GetNodeType(item) == "dataset"]
return len(phases)
def GetPositionInSubtree(self, node):
@@ -263,11 +277,12 @@ def GetPositionInSubtree(self, node):
for sib in brood:
if sib == node:
break
- else: pos += 1
+ else:
+ pos += 1
nodetype = self.GetNodeType(node)
- if nodetype == 'dataset':
+ if nodetype == "dataset":
pos -= self.GetNumPhases(node)
- if nodetype == 'calculation':
+ if nodetype == "calculation":
pos -= self.GetNumPhases(node) + self.GetNumDataSets(node)
return pos
@@ -280,11 +295,11 @@ def SetControlData(self, node, data):
example, for a 'phase' node, it contains a Structure object.
"""
nodetype = self.GetNodeType(node)
- if nodetype != 'fit':
- message = 'Node type %s does not hold its own data' % nodetype
+ if nodetype != "fit":
+ message = "Node type %s does not hold its own data" % nodetype
raise FitTreeError(message)
- self.GetTreeItemDict(node)['cdata'] = data
+ self.GetTreeItemDict(node)["cdata"] = data
return
def GetControlData(self, node):
@@ -295,16 +310,16 @@ def GetControlData(self, node):
"""
nodetype = self.GetNodeType(node)
parent = self.GetFitRoot(node)
- pdata = self.GetTreeItemDict(parent)['cdata']
- if nodetype == 'fit':
+ pdata = self.GetTreeItemDict(parent)["cdata"]
+ if nodetype == "fit":
return pdata
- elif nodetype == 'phase':
+ elif nodetype == "phase":
pos = self.GetPositionInSubtree(node)
return pdata.getStructure(pos)
- elif nodetype == 'dataset':
+ elif nodetype == "dataset":
pos = self.GetPositionInSubtree(node)
return pdata.getDataSet(pos)
- elif nodetype == 'calculation':
+ elif nodetype == "calculation":
pos = self.GetPositionInSubtree(node)
return pdata.getCalculation(pos)
else:
@@ -312,7 +327,7 @@ def GetControlData(self, node):
raise FitTreeError(message)
return
- def AddFit(self, fitname = "Fit 1", cdata = None, paste = False):
+ def AddFit(self, fitname="Fit 1", cdata=None, paste=False):
"""Append a new fit tree to the end of the current fits.
fitname -- The name of the fit. This is incremented if it already
@@ -330,7 +345,7 @@ def AddFit(self, fitname = "Fit 1", cdata = None, paste = False):
fitname = incrementName(fitname, names)
newfit = self.AppendItem(self.root, fitname)
- self.SetNodeType(newfit, 'fit')
+ self.SetNodeType(newfit, "fit")
self.SetItemImage(newfit, self.fitbmid, wx.TreeItemIcon_Normal)
pos = self.GetPositionInSubtree(newfit)
@@ -347,8 +362,9 @@ def AddFit(self, fitname = "Fit 1", cdata = None, paste = False):
raise
return
- def AddPhase(self, node, label, insertafter=None, filename=None,
- makedata = True, cdata=None):
+ def AddPhase(
+ self, node, label, insertafter=None, filename=None, makedata=True, cdata=None
+ ):
"""Add a new blank Phase to the tree as a child of node.
node -- The parent 'fit' node.
@@ -419,8 +435,9 @@ def AddPhase(self, node, label, insertafter=None, filename=None,
raise
return
- def AddDataSet(self, node, label, insertafter=None, filename=None,
- makedata=True, cdata=None):
+ def AddDataSet(
+ self, node, label, insertafter=None, filename=None, makedata=True, cdata=None
+ ):
"""Add a new DataSet to the tree as a child of fit.
node -- The parent node of the dataset. Must be 'fit' type.
@@ -558,13 +575,14 @@ def CopyBranch(self, startnode):
cdata = cdata.stripped()
cdata.type = nodetype
cdatabytes = safeCPickleDumps(cdata)
- cdatabytes = 'pdfgui_cliboard='.encode() + cdatabytes
- #wxpython only accepts str, use base64 to convert bytes to str
+ cdatabytes = "pdfgui_cliboard=".encode() + cdatabytes
+ # wxpython only accepts str, use base64 to convert bytes to str
cdatastring = base64.b64encode(cdatabytes)
textdata = wx.TextDataObject(cdatastring)
if not wx.TheClipboard.IsOpened():
opened = wx.TheClipboard.Open()
- if not opened: raise FitTreeError("Cannot open the clipboard.")
+ if not opened:
+ raise FitTreeError("Cannot open the clipboard.")
wx.TheClipboard.SetData(textdata)
wx.TheClipboard.Close()
return
@@ -582,10 +600,12 @@ def GetClipboard(self):
textdata = wx.TextDataObject()
if not wx.TheClipboard.IsOpened():
opened = wx.TheClipboard.Open()
- if not opened: return None
+ if not opened:
+ return None
success = wx.TheClipboard.GetData(textdata)
wx.TheClipboard.Close()
- if not success: return None
+ if not success:
+ return None
cdatastring = textdata.GetText()
cdata = None
@@ -593,14 +613,14 @@ def GetClipboard(self):
try:
cdatabytes = base64.b64decode(cdatastring.encode())
- if cdatabytes[:16] == 'pdfgui_cliboard='.encode():
+ if cdatabytes[:16] == "pdfgui_cliboard=".encode():
cdatabytes = cdatabytes[16:]
cdata = pickle_loads(cdatabytes)
except:
pass
return cdata
- def PasteBranch(self, entrypoint = None):
+ def PasteBranch(self, entrypoint=None):
"""Paste the branch from the clipboard into tree at the given node.
A certain type of branch can only be copied to specific places.
@@ -657,7 +677,7 @@ def PasteBranch(self, entrypoint = None):
elif entrytype == "fit":
insertafter = entrypoint
entrypoint = self.root
- else: # Just in case
+ else: # Just in case
raise FitTreeError("Cannot paste a fit branch here.")
if branchtype == "phase":
@@ -682,7 +702,7 @@ def PasteBranch(self, entrypoint = None):
if not insertafter:
# Put the branch at the beginning of the phases
prepend = True
- else: # Just in case
+ else: # Just in case
raise FitTreeError("Cannot paste a phase branch here.")
if branchtype == "dataset":
@@ -720,16 +740,14 @@ def PasteBranch(self, entrypoint = None):
insertafter = self.GetLastDataSet(entrypoint)
elif entrytype == "fit":
insertafter = self.GetLastDataSet(entrypoint)
- else: # Just in case
+ else: # Just in case
raise FitTreeError("Cannot paste a calculation branch here.")
-
# Now set the name of the item to be inserted.
label = self.__copyLabel(cdata.name, entrypoint)
# Now we have a label. We must insert the item into the tree.
- newnode = self.__InsertBranch(cdata, entrypoint, label, insertafter,
- prepend)
+ newnode = self.__InsertBranch(cdata, entrypoint, label, insertafter, prepend)
return newnode
@@ -740,13 +758,12 @@ def __copyLabel(self, oldlabel, entrypoint):
siblings = self.GetChildren(entrypoint)
labels = [self.GetItemText(sb) for sb in siblings]
match = r"_copy\d*$"
- label = re.sub(match, '', oldlabel)
+ label = re.sub(match, "", oldlabel)
label += "_copy"
label = incrementName(label, labels)
return label
- def __InsertBranch(self, cdata, entrypoint, label, insertafter = None,
- prepend = False):
+ def __InsertBranch(self, cdata, entrypoint, label, insertafter=None, prepend=False):
"""Instert control data into the tree.
cdata -- The control data that goes with the branch
@@ -765,20 +782,24 @@ def __InsertBranch(self, cdata, entrypoint, label, insertafter = None,
raise FitTreeError(message)
branchtype = cdata.type
- #cdata.name = label
- if branchtype == 'fit':
+ # cdata.name = label
+ if branchtype == "fit":
cdata.name = label
- newnode = self.ExtendProjectTree([cdata.organization()],
- clear=False, paste=True)
- elif branchtype == 'phase':
- newnode = self.AddPhase(entrypoint, label, insertafter=insertafter,
- makedata=False, cdata=cdata)
- elif branchtype == 'dataset':
- newnode = self.AddDataSet(entrypoint, label, insertafter=insertafter,
- makedata=False, cdata=cdata)
- elif branchtype == 'calculation':
- newnode = self.AddCalc(entrypoint, label, insertafter=insertafter,
- makedata=False, cdata=cdata)
+ newnode = self.ExtendProjectTree(
+ [cdata.organization()], clear=False, paste=True
+ )
+ elif branchtype == "phase":
+ newnode = self.AddPhase(
+ entrypoint, label, insertafter=insertafter, makedata=False, cdata=cdata
+ )
+ elif branchtype == "dataset":
+ newnode = self.AddDataSet(
+ entrypoint, label, insertafter=insertafter, makedata=False, cdata=cdata
+ )
+ elif branchtype == "calculation":
+ newnode = self.AddCalc(
+ entrypoint, label, insertafter=insertafter, makedata=False, cdata=cdata
+ )
else:
raise FitTreeError("Unrecognized node type: %s" % branchtype)
@@ -787,8 +808,7 @@ def __InsertBranch(self, cdata, entrypoint, label, insertafter = None,
def DeleteBranches(self, selections):
"""Remove the subtree starting from the selected node(s)."""
# Get a list of branch heads
- branchset = [node for node in selections if self.GetNodeType(node) ==\
- "fit"]
+ branchset = [node for node in selections if self.GetNodeType(node) == "fit"]
# Get their children
childset = []
@@ -815,7 +835,7 @@ def SelectAll(self):
self.SelectItem(child)
return
- def SelectAllType(self, node = None):
+ def SelectAllType(self, node=None):
"""Select all nodes of same type as passed node.
node -- Node whose type to select. If node is None (default), then
@@ -825,7 +845,8 @@ def SelectAllType(self, node = None):
if node is None:
# Get the first fit node
fits = self.GetChildren(self.root)
- if not fits: return
+ if not fits:
+ return
node = fits[0]
typelist = self.GetAllType(node)
for item in typelist:
@@ -859,13 +880,14 @@ def ExtendProjectTree(self, treelist, clear=True, paste=False):
roots = []
# Return if the treelist is empty
- if not treelist: return
+ if not treelist:
+ return
# Build the tree
for item in treelist:
broot = item[0]
name = broot.name
- node = self.AddFit(name, cdata = broot, paste = paste)
+ node = self.AddFit(name, cdata=broot, paste=paste)
if node is None:
message = "Cannot insert data. Malformed tree list."
@@ -877,18 +899,19 @@ def ExtendProjectTree(self, treelist, clear=True, paste=False):
# the fit root.
phases = item[2]
for (name, phase) in phases:
- self.AddPhase(node, name, makedata = False)
+ self.AddPhase(node, name, makedata=False)
dsets = item[1]
for (name, set) in dsets:
- self.AddDataSet(node, name, makedata = False)
+ self.AddDataSet(node, name, makedata=False)
calcs = item[3]
for (name, calc) in calcs:
- self.AddCalc(node, name, makedata = False)
+ self.AddCalc(node, name, makedata=False)
for item in roots:
self.Expand(item)
return node
+
# End class FitTree
@@ -897,11 +920,13 @@ class FitTreeError(ControlError):
def __init__(self, *args):
ControlError.__init__(self, *args)
return
+
+
# End class FitTreeError
# Utility functions
-def incrementName(name, namelist, start = 1):
+def incrementName(name, namelist, start=1):
"""Increment the name by assigning the lowest number to the end such
that the name does not appear in the namelist.
"""
@@ -909,7 +934,7 @@ def incrementName(name, namelist, start = 1):
match = r"\d+$"
counter = start
while newname in namelist:
- newname = re.sub(match, '', name)
+ newname = re.sub(match, "", name)
counter += 1
newname = "%s%i" % (newname, counter)
return newname
diff --git a/src/diffpy/pdfgui/gui/insertrowsdialog.py b/src/diffpy/pdfgui/gui/insertrowsdialog.py
index 29c55262..6f9389ae 100644
--- a/src/diffpy/pdfgui/gui/insertrowsdialog.py
+++ b/src/diffpy/pdfgui/gui/insertrowsdialog.py
@@ -18,6 +18,7 @@
import wx
+
class InsertRowsDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: InsertRowsDialog.__init__
@@ -25,7 +26,14 @@ def __init__(self, *args, **kwds):
wx.Dialog.__init__(self, *args, **kwds)
self.Rows = wx.StaticText(self, wx.ID_ANY, "Rows:")
self.spin_ctrl_Rows = wx.SpinCtrl(self, wx.ID_ANY, "1", min=0, max=100, style=0)
- self.radio_box_where = wx.RadioBox(self, wx.ID_ANY, "", choices=["Above", "Below"], majorDimension=2, style=wx.RA_SPECIFY_ROWS)
+ self.radio_box_where = wx.RadioBox(
+ self,
+ wx.ID_ANY,
+ "",
+ choices=["Above", "Below"],
+ majorDimension=2,
+ style=wx.RA_SPECIFY_ROWS,
+ )
self.button_OK = wx.Button(self, wx.ID_OK, "OK")
self.button_Cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
@@ -58,4 +66,5 @@ def __do_layout(self):
self.Layout()
# end wxGlade
+
# end of class InsertRowsDialog
diff --git a/src/diffpy/pdfgui/gui/journalpanel.py b/src/diffpy/pdfgui/gui/journalpanel.py
index 9e4a1073..c4f6ee63 100644
--- a/src/diffpy/pdfgui/gui/journalpanel.py
+++ b/src/diffpy/pdfgui/gui/journalpanel.py
@@ -20,6 +20,7 @@
import wx
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class JournalPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -66,7 +67,7 @@ def __customProperties(self):
self.textCtrlJournal.Bind(wx.EVT_KEY_DOWN, self.onKey)
return
- def onText(self, event): # wxGlade: JournalPanel.
+ def onText(self, event): # wxGlade: JournalPanel.
"""Record anything that is written into the journal."""
text = self.textCtrlJournal.GetValue()
if text != self.mainFrame.control.journal:
@@ -74,25 +75,31 @@ def onText(self, event): # wxGlade: JournalPanel.
self.mainFrame.needsSave()
return
- def onExport(self, event): # wxGlade: JournalPanel.
+ def onExport(self, event): # wxGlade: JournalPanel.
"""Export the journal to an external file."""
matchstring = "Text files (*.txt)|*.txt|All Files|*"
dir, filename = os.path.split(self.fullpath)
- if not dir: dir = self.mainFrame.workpath
- d = wx.FileDialog(None, "Export to...",
- dir, filename, matchstring,
- wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
+ if not dir:
+ dir = self.mainFrame.workpath
+ d = wx.FileDialog(
+ None,
+ "Export to...",
+ dir,
+ filename,
+ matchstring,
+ wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
+ )
if d.ShowModal() == wx.ID_OK:
self.fullpath = d.GetPath()
self.mainFrame.workpath = os.path.dirname(self.fullpath)
- outfile = open(self.fullpath, 'w')
+ outfile = open(self.fullpath, "w")
outfile.write(self.mainFrame.control.journal)
outfile.close()
d.Destroy()
return
- def onClose(self, event): # wxGlade: JournalPanel.
+ def onClose(self, event): # wxGlade: JournalPanel.
self._close()
return
diff --git a/src/diffpy/pdfgui/gui/main.py b/src/diffpy/pdfgui/gui/main.py
index 138d7b4f..a3d37917 100644
--- a/src/diffpy/pdfgui/gui/main.py
+++ b/src/diffpy/pdfgui/gui/main.py
@@ -18,16 +18,20 @@
import wx
+
class PDFGuiApp(wx.App):
def OnInit(self):
from diffpy.pdfgui.gui.mainframe import MainFrame
+
self.frame = MainFrame(None, -1, "")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
+
# end of class PDFGuiApp
+
def main():
"""Kick starter for the PDFgui graphical user interface.
This function is normally called from a light-weight console
@@ -39,5 +43,6 @@ def main():
app.MainLoop()
return
+
if __name__ == "__main__":
main()
diff --git a/src/diffpy/pdfgui/gui/mainframe.py b/src/diffpy/pdfgui/gui/mainframe.py
index dc33a9fc..558431c2 100644
--- a/src/diffpy/pdfgui/gui/mainframe.py
+++ b/src/diffpy/pdfgui/gui/mainframe.py
@@ -71,6 +71,7 @@
# selection sends two selection events on windows. One for an empty selection
# and one with the new selections.
+
class MainFrame(wx.Frame):
"""The left pane is a FitTree (from fittree.py), the right is a dynamic
panel, accessed via the data member rightPanel, which can hold one of any
@@ -170,15 +171,27 @@ class MainFrame(wx.Frame):
flag tells the error handlers to ignore any errors that take
place during shutdown.
"""
+
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
- self.SetMinSize((700,500))
+ self.SetMinSize((700, 500))
self.auiManager = wx.aui.AuiManager(self)
- self.treeCtrlMain = FitTree(self, -1, style=wx.TR_HAS_BUTTONS|wx.TR_NO_LINES|wx.TR_EDIT_LABELS|wx.TR_MULTIPLE|wx.TR_HIDE_ROOT|wx.TR_MULTIPLE|wx.TR_DEFAULT_STYLE|wx.SUNKEN_BORDER)
+ self.treeCtrlMain = FitTree(
+ self,
+ -1,
+ style=wx.TR_HAS_BUTTONS
+ | wx.TR_NO_LINES
+ | wx.TR_EDIT_LABELS
+ | wx.TR_MULTIPLE
+ | wx.TR_HIDE_ROOT
+ | wx.TR_MULTIPLE
+ | wx.TR_DEFAULT_STYLE
+ | wx.SUNKEN_BORDER,
+ )
self.plotPanel = PlotPanel(self, -1)
self.outputPanel = OutputPanel(self, -1)
self.journalPanel = JournalPanel(self, -1)
@@ -186,14 +199,12 @@ def __init__(self, *args, **kwds):
self.__customProperties()
- self.Bind(wx.EVT_TREE_SEL_CHANGING, self.onTreeSelChanging,
- self.treeCtrlMain)
- self.Bind(wx.EVT_TREE_SEL_CHANGED, self.onTreeSelChanged,
- self.treeCtrlMain)
- self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.onEndLabelEdit,
- self.treeCtrlMain)
- self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.onBeginLabelEdit,
- self.treeCtrlMain)
+ self.Bind(wx.EVT_TREE_SEL_CHANGING, self.onTreeSelChanging, self.treeCtrlMain)
+ self.Bind(wx.EVT_TREE_SEL_CHANGED, self.onTreeSelChanged, self.treeCtrlMain)
+ self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.onEndLabelEdit, self.treeCtrlMain)
+ self.Bind(
+ wx.EVT_TREE_BEGIN_LABEL_EDIT, self.onBeginLabelEdit, self.treeCtrlMain
+ )
self.__customBindings()
self.__cmdLineLoad()
self.updateTitle()
@@ -202,7 +213,6 @@ def __init__(self, *args, **kwds):
self.switchRightPanel("welcome")
return
-
# USER CONFIGURATION CODE #################################################
def __cmdLineLoad(self):
@@ -231,34 +241,34 @@ def __defineLocalIds(self):
"""
# Functions that modify the tree.
# These are used in the fitting right-click menu and the main menu.
- self.newFitId = wx12.NewIdRef() # New Fit
- self.newCalcId = wx12.NewIdRef() # New Calculation
- self.newPhaseId = wx12.NewIdRef() # New Phase
- self.newDataId = wx12.NewIdRef() # New Data Set
- self.deleteId = wx.ID_DELETE # Delete tree item
- self.copyId = wx.ID_COPY # Copy a tree item
- self.pasteId = wx.ID_PASTE # Paste a tree item into tree
+ self.newFitId = wx12.NewIdRef() # New Fit
+ self.newCalcId = wx12.NewIdRef() # New Calculation
+ self.newPhaseId = wx12.NewIdRef() # New Phase
+ self.newDataId = wx12.NewIdRef() # New Data Set
+ self.deleteId = wx.ID_DELETE # Delete tree item
+ self.copyId = wx.ID_COPY # Copy a tree item
+ self.pasteId = wx.ID_PASTE # Paste a tree item into tree
self.pasteLinkId = wx12.NewIdRef() # Paste and link a fit node
# Misc. functions, these are exclusive to the main menu.
- self.newId = wx.ID_NEW # Start a new Project
- self.openId = wx.ID_OPEN # Open a project
- self.recentId = None # Open a recent project (set later)
- self.saveId = wx.ID_SAVE # Save the project
- self.saveAsId = wx.ID_SAVEAS # Save the project as...
- self.quitId = wx.ID_CLOSE # Quit the program
- self.runFitId = wx12.NewIdRef() # Run a fit
- self.stopFitId = wx12.NewIdRef() # Stop a fit
+ self.newId = wx.ID_NEW # Start a new Project
+ self.openId = wx.ID_OPEN # Open a project
+ self.recentId = None # Open a recent project (set later)
+ self.saveId = wx.ID_SAVE # Save the project
+ self.saveAsId = wx.ID_SAVEAS # Save the project as...
+ self.quitId = wx.ID_CLOSE # Quit the program
+ self.runFitId = wx12.NewIdRef() # Run a fit
+ self.stopFitId = wx12.NewIdRef() # Stop a fit
self.quickPlotId = wx12.NewIdRef() # Quick plot a fit
- self.exportFitPDFId = wx12.NewIdRef() # Save a fit PDF
+ self.exportFitPDFId = wx12.NewIdRef() # Save a fit PDF
self.exportFitStruId = wx12.NewIdRef() # Save a fit structure
self.exportNewStruId = wx12.NewIdRef() # Export a 'new' structure
- self.plotIStructId = wx12.NewIdRef() # Plot initial structure
- self.plotFStructId = wx12.NewIdRef() # Plot final structure
- self.printBLId = wx12.NewIdRef() # Print the bond lengths of a structure
- self.printBAId = wx12.NewIdRef() # Print the bond angles of a structure
+ self.plotIStructId = wx12.NewIdRef() # Plot initial structure
+ self.plotFStructId = wx12.NewIdRef() # Plot final structure
+ self.printBLId = wx12.NewIdRef() # Print the bond lengths of a structure
+ self.printBAId = wx12.NewIdRef() # Print the bond angles of a structure
self.exportResId = wx12.NewIdRef() # Save the results file
- self.runCalcId = wx12.NewIdRef() # Run a calculation
+ self.runCalcId = wx12.NewIdRef() # Run a calculation
self.exportCalcPDFId = wx12.NewIdRef() # Save a calculated PDF
return
@@ -279,20 +289,20 @@ def __customProperties(self):
# Constants needed for communication with the control
self.ERROR = 1
- self.UPDATE = 1<<1
- self.OUTPUT = 1<<2
- self.PLOTNOW = 1<<3
+ self.UPDATE = 1 << 1
+ self.OUTPUT = 1 << 2
+ self.PLOTNOW = 1 << 3
# Needed for the error checker so it doesn't throw errors at quit time
self.quitting = False
# Wrap the events to use an event handler
- self.mainFrame = self # needed by error wrapper
+ self.mainFrame = self # needed by error wrapper
catchObjectErrors(self)
# Needed for loading and saving
self.fullpath = ""
- self.workpath = os.path.abspath('.')
+ self.workpath = os.path.abspath(".")
# The dictionary of running fits/calculations
self.runningDict = {}
@@ -310,31 +320,32 @@ def __customProperties(self):
# data type (fit, dataset, phase, calculation). This allows for
# automatic switching of panels.
self.dynamicPanels = {
- "blank" : self.panelDynamic,
- "welcome" : WelcomePanel(self, -1),
- "fit" : FitNotebookPanel(self, -1),
- "phase" : PhaseNotebookPanel(self, -1),
- "dataset" : DataSetPanel(self, -1),
- "calculation" : CalculationPanel(self, -1),
- "adddata" : AddDataPanel(self, -1),
- "addphase" : AddPhasePanel(self, -1),
- "preferences" : PreferencesPanel(self, -1),
- "rseries" : RSeriesPanel(self, -1),
- "tseries" : TemperatureSeriesPanel(self, -1),
- "dseries" : DopingSeriesPanel(self, -1),
- }
+ "blank": self.panelDynamic,
+ "welcome": WelcomePanel(self, -1),
+ "fit": FitNotebookPanel(self, -1),
+ "phase": PhaseNotebookPanel(self, -1),
+ "dataset": DataSetPanel(self, -1),
+ "calculation": CalculationPanel(self, -1),
+ "adddata": AddDataPanel(self, -1),
+ "addphase": AddPhasePanel(self, -1),
+ "preferences": PreferencesPanel(self, -1),
+ "rseries": RSeriesPanel(self, -1),
+ "tseries": TemperatureSeriesPanel(self, -1),
+ "dseries": DopingSeriesPanel(self, -1),
+ }
# Prepare the right pane. Display the welcome screen.
self.rightPanel = self.panelDynamic
for key in self.dynamicPanels:
- self.auiManager.AddPane(self.dynamicPanels[key],
- wx.aui.AuiPaneInfo().
- Name(key).
- CenterPane().
- BestSize(wx.Size(400,380)).
- MinSize(wx.Size(190,200)).
- Hide()
- )
+ self.auiManager.AddPane(
+ self.dynamicPanels[key],
+ wx.aui.AuiPaneInfo()
+ .Name(key)
+ .CenterPane()
+ .BestSize(wx.Size(400, 380))
+ .MinSize(wx.Size(190, 200))
+ .Hide(),
+ )
self.dynamicPanels[key].mainFrame = self
self.dynamicPanels[key].treeCtrlMain = self.treeCtrlMain
self.dynamicPanels[key].cP = self.cP
@@ -353,59 +364,70 @@ def __customProperties(self):
# Position other panels. Note that currently MinimizeButton does not do
# anything. It is to be implemented in future versions of wx.aui
- self.auiManager.AddPane(self.outputPanel, wx.aui.AuiPaneInfo().
- Name("outputPanel").Caption("PDFfit2 Output").
- Bottom().
- TopDockable().
- BottomDockable().
- LeftDockable().
- RightDockable().
- MinimizeButton().
- BestSize(wx.Size(400,40)).
- MinSize(wx.Size(200,40))
- )
- self.auiManager.AddPane(self.treeCtrlMain, wx.aui.AuiPaneInfo().
- Name("treeCtrlMain").Caption("Fit Tree").
- Left().
- TopDockable().
- BottomDockable().
- LeftDockable().
- RightDockable().
- MinimizeButton().
- BestSize(wx.Size(200,100)).
- MinSize(wx.Size(200,40))
- )
- self.auiManager.AddPane(self.plotPanel, wx.aui.AuiPaneInfo().
- Name("plotPanel").Caption("Plot Control").
- Left().
- TopDockable().
- BottomDockable().
- LeftDockable().
- RightDockable().
- MinimizeButton().
- BestSize(wx.Size(200,250)).
- MinSize(wx.Size(200,150))
- )
- self.auiManager.AddPane(self.journalPanel, wx.aui.AuiPaneInfo().
- Name("journalPanel").Caption("Project Journal").
- TopDockable().
- BottomDockable().
- LeftDockable().
- RightDockable().
- MinimizeButton().
- Hide().
- BestSize(wx.Size(450,450)).
- MinSize(wx.Size(200,200)).
- FloatingSize(wx.Size(450, 450)).
- Float()
- )
-
+ self.auiManager.AddPane(
+ self.outputPanel,
+ wx.aui.AuiPaneInfo()
+ .Name("outputPanel")
+ .Caption("PDFfit2 Output")
+ .Bottom()
+ .TopDockable()
+ .BottomDockable()
+ .LeftDockable()
+ .RightDockable()
+ .MinimizeButton()
+ .BestSize(wx.Size(400, 40))
+ .MinSize(wx.Size(200, 40)),
+ )
+ self.auiManager.AddPane(
+ self.treeCtrlMain,
+ wx.aui.AuiPaneInfo()
+ .Name("treeCtrlMain")
+ .Caption("Fit Tree")
+ .Left()
+ .TopDockable()
+ .BottomDockable()
+ .LeftDockable()
+ .RightDockable()
+ .MinimizeButton()
+ .BestSize(wx.Size(200, 100))
+ .MinSize(wx.Size(200, 40)),
+ )
+ self.auiManager.AddPane(
+ self.plotPanel,
+ wx.aui.AuiPaneInfo()
+ .Name("plotPanel")
+ .Caption("Plot Control")
+ .Left()
+ .TopDockable()
+ .BottomDockable()
+ .LeftDockable()
+ .RightDockable()
+ .MinimizeButton()
+ .BestSize(wx.Size(200, 250))
+ .MinSize(wx.Size(200, 150)),
+ )
+ self.auiManager.AddPane(
+ self.journalPanel,
+ wx.aui.AuiPaneInfo()
+ .Name("journalPanel")
+ .Caption("Project Journal")
+ .TopDockable()
+ .BottomDockable()
+ .LeftDockable()
+ .RightDockable()
+ .MinimizeButton()
+ .Hide()
+ .BestSize(wx.Size(450, 450))
+ .MinSize(wx.Size(200, 200))
+ .FloatingSize(wx.Size(450, 450))
+ .Float(),
+ )
# Continue with initialization
- self.__defineLocalIds() # Ids for menu items
- self.__setupMainMenu() # Make the main menu
- self.__setupToolBar() # Make the toolbar
- self.treeCtrlMain.InitializeTree() # Initialize the tree
+ self.__defineLocalIds() # Ids for menu items
+ self.__setupMainMenu() # Make the main menu
+ self.__setupToolBar() # Make the toolbar
+ self.treeCtrlMain.InitializeTree() # Initialize the tree
# Load the configuration
self.loadConfiguration()
@@ -424,98 +446,124 @@ def __setupMainMenu(self):
# File Menu
self.fileMenu = wx12.Menu()
- self.newItem = wx.MenuItem(self.fileMenu, self.newId,
- "&New Project\tCtrl+n", "", wx.ITEM_NORMAL)
+ self.newItem = wx.MenuItem(
+ self.fileMenu, self.newId, "&New Project\tCtrl+n", "", wx.ITEM_NORMAL
+ )
self.fileMenu.Append(self.newItem)
- self.openItem = wx.MenuItem(self.fileMenu, self.openId,
- "&Open Project\tCtrl+o", "", wx.ITEM_NORMAL)
+ self.openItem = wx.MenuItem(
+ self.fileMenu, self.openId, "&Open Project\tCtrl+o", "", wx.ITEM_NORMAL
+ )
self.fileMenu.Append(self.openItem)
self.recentMenu = wx12.Menu()
msub = self.fileMenu.AppendSubMenu(self.recentMenu, "&Recent Files")
self.recentId = msub.Id
self.fileMenu.AppendSeparator()
- self.saveItem = wx.MenuItem(self.fileMenu, self.saveId,
- "&Save Project\tCtrl+s", "", wx.ITEM_NORMAL)
+ self.saveItem = wx.MenuItem(
+ self.fileMenu, self.saveId, "&Save Project\tCtrl+s", "", wx.ITEM_NORMAL
+ )
self.fileMenu.Append(self.saveItem)
- self.saveAsItem = wx.MenuItem(self.fileMenu, self.saveAsId,
- "Save Project &as\tCtrl+Shift+s", "", wx.ITEM_NORMAL)
+ self.saveAsItem = wx.MenuItem(
+ self.fileMenu,
+ self.saveAsId,
+ "Save Project &as\tCtrl+Shift+s",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.fileMenu.Append(self.saveAsItem)
self.fileMenu.AppendSeparator()
- self.quitItem = wx.MenuItem(self.fileMenu, self.quitId,
- "&Quit\tCtrl+q", "", wx.ITEM_NORMAL)
+ self.quitItem = wx.MenuItem(
+ self.fileMenu, self.quitId, "&Quit\tCtrl+q", "", wx.ITEM_NORMAL
+ )
self.fileMenu.Append(self.quitItem)
self.menuBar.Append(self.fileMenu, "&File")
# End File Menu
# Edit Menu
self.editMenu = wx12.Menu()
- self.delItem = wx.MenuItem(self.editMenu, self.deleteId,
- "&Delete Item(s)\tCtrl+X", "", wx.ITEM_NORMAL)
+ self.delItem = wx.MenuItem(
+ self.editMenu, self.deleteId, "&Delete Item(s)\tCtrl+X", "", wx.ITEM_NORMAL
+ )
self.editMenu.Append(self.delItem)
- self.copyItem = wx.MenuItem(self.editMenu, self.copyId,
- "&Copy Item\tCtrl+C", "", wx.ITEM_NORMAL)
+ self.copyItem = wx.MenuItem(
+ self.editMenu, self.copyId, "&Copy Item\tCtrl+C", "", wx.ITEM_NORMAL
+ )
self.editMenu.Append(self.copyItem)
- self.pasteItem = wx.MenuItem(self.editMenu, self.pasteId,
- "&Paste Item\tCtrl+V", "", wx.ITEM_NORMAL)
+ self.pasteItem = wx.MenuItem(
+ self.editMenu, self.pasteId, "&Paste Item\tCtrl+V", "", wx.ITEM_NORMAL
+ )
self.editMenu.Append(self.pasteItem)
- self.pasteLinkItem = wx.MenuItem(self.editMenu, self.pasteLinkId,
- "Paste &Linked Fit", "", wx.ITEM_NORMAL)
+ self.pasteLinkItem = wx.MenuItem(
+ self.editMenu, self.pasteLinkId, "Paste &Linked Fit", "", wx.ITEM_NORMAL
+ )
self.editMenu.Append(self.pasteLinkItem)
self.editMenu.AppendSeparator()
- self.prefItem = wx.MenuItem(self.editMenu, wx12.NewIdRef(),
- "&Preferences", "", wx.ITEM_NORMAL)
+ self.prefItem = wx.MenuItem(
+ self.editMenu, wx12.NewIdRef(), "&Preferences", "", wx.ITEM_NORMAL
+ )
self.editMenu.Append(self.prefItem)
self.menuBar.Append(self.editMenu, "&Edit")
# End Edit Menu
# View Menu
self.viewMenu = wx12.Menu()
- self.defaultLayoutItem = wx.MenuItem(self.editMenu, wx12.NewIdRef(),
- "Default Window Layout", "", wx.ITEM_NORMAL)
+ self.defaultLayoutItem = wx.MenuItem(
+ self.editMenu, wx12.NewIdRef(), "Default Window Layout", "", wx.ITEM_NORMAL
+ )
self.viewMenu.Append(self.defaultLayoutItem)
self.viewMenu.AppendSeparator()
# These items are context sensitive.
- self.showFitItem = wx.MenuItem(self.viewMenu, wx12.NewIdRef(),
- "Show Fit Tree", "", wx.ITEM_NORMAL)
+ self.showFitItem = wx.MenuItem(
+ self.viewMenu, wx12.NewIdRef(), "Show Fit Tree", "", wx.ITEM_NORMAL
+ )
self.viewMenu.Append(self.showFitItem)
- self.showPlotItem = wx.MenuItem(self.viewMenu, wx12.NewIdRef(),
- "Show Plot Control", "", wx.ITEM_NORMAL)
+ self.showPlotItem = wx.MenuItem(
+ self.viewMenu, wx12.NewIdRef(), "Show Plot Control", "", wx.ITEM_NORMAL
+ )
self.viewMenu.Append(self.showPlotItem)
- self.showOutputItem = wx.MenuItem(self.viewMenu, wx12.NewIdRef(),
- "Show Output", "", wx.ITEM_NORMAL)
+ self.showOutputItem = wx.MenuItem(
+ self.viewMenu, wx12.NewIdRef(), "Show Output", "", wx.ITEM_NORMAL
+ )
self.viewMenu.Append(self.showOutputItem)
- self.showJournalItem = wx.MenuItem(self.viewMenu, wx12.NewIdRef(),
- "Show Journal\tCtrl+j", "", wx.ITEM_NORMAL)
+ self.showJournalItem = wx.MenuItem(
+ self.viewMenu, wx12.NewIdRef(), "Show Journal\tCtrl+j", "", wx.ITEM_NORMAL
+ )
self.viewMenu.Append(self.showJournalItem)
self.menuBar.Append(self.viewMenu, "&View")
# Fits Menu
self.fitsMenu = wx12.Menu()
- self.newFitItem = wx.MenuItem(self.fitsMenu, self.newFitId,
- "&New Fit\tCtrl+t", "", wx.ITEM_NORMAL)
+ self.newFitItem = wx.MenuItem(
+ self.fitsMenu, self.newFitId, "&New Fit\tCtrl+t", "", wx.ITEM_NORMAL
+ )
self.fitsMenu.Append(self.newFitItem)
self.fitsMenu.AppendSeparator()
- self.runFitItem = wx.MenuItem(self.fitsMenu, self.runFitId,
- "&Run Selected Fits", "", wx.ITEM_NORMAL)
+ self.runFitItem = wx.MenuItem(
+ self.fitsMenu, self.runFitId, "&Run Selected Fits", "", wx.ITEM_NORMAL
+ )
self.fitsMenu.Append(self.runFitItem)
- self.stopFitItem = wx.MenuItem(self.fitsMenu, self.stopFitId,
- "&Stop Fitting", "", wx.ITEM_NORMAL)
+ self.stopFitItem = wx.MenuItem(
+ self.fitsMenu, self.stopFitId, "&Stop Fitting", "", wx.ITEM_NORMAL
+ )
self.fitsMenu.Append(self.stopFitItem)
self.fitsMenu.AppendSeparator()
- self.expResItem = wx.MenuItem(self.fitsMenu, self.exportResId,
- "Export Resu<s File", "", wx.ITEM_NORMAL)
+ self.expResItem = wx.MenuItem(
+ self.fitsMenu, self.exportResId, "Export Resu<s File", "", wx.ITEM_NORMAL
+ )
self.fitsMenu.Append(self.expResItem)
self.fitsMenu.AppendSeparator()
# Macros sub-menu
self.macrosMenu = wx12.Menu()
- self.rseriesItem = wx.MenuItem(self.macrosMenu, wx12.NewIdRef(),
- "r-Series", "", wx.ITEM_NORMAL)
+ self.rseriesItem = wx.MenuItem(
+ self.macrosMenu, wx12.NewIdRef(), "r-Series", "", wx.ITEM_NORMAL
+ )
self.macrosMenu.Append(self.rseriesItem)
- self.tseriesItem = wx.MenuItem(self.macrosMenu, wx12.NewIdRef(),
- "Temperature Series", "", wx.ITEM_NORMAL)
+ self.tseriesItem = wx.MenuItem(
+ self.macrosMenu, wx12.NewIdRef(), "Temperature Series", "", wx.ITEM_NORMAL
+ )
self.macrosMenu.Append(self.tseriesItem)
- self.dseriesItem = wx.MenuItem(self.macrosMenu, wx12.NewIdRef(),
- "Doping Series", "", wx.ITEM_NORMAL)
+ self.dseriesItem = wx.MenuItem(
+ self.macrosMenu, wx12.NewIdRef(), "Doping Series", "", wx.ITEM_NORMAL
+ )
self.macrosMenu.Append(self.dseriesItem)
self.fitsMenu.AppendSubMenu(self.macrosMenu, "Macros")
self.menuBar.Append(self.fitsMenu, "Fi&ts")
@@ -523,81 +571,127 @@ def __setupMainMenu(self):
# Phases Menu
self.phasesMenu = wx12.Menu()
- self.newPhaseItem = wx.MenuItem(self.phasesMenu, self.newPhaseId,
- "&New Phase\tCtrl+p", "", wx.ITEM_NORMAL)
+ self.newPhaseItem = wx.MenuItem(
+ self.phasesMenu, self.newPhaseId, "&New Phase\tCtrl+p", "", wx.ITEM_NORMAL
+ )
self.phasesMenu.Append(self.newPhaseItem)
self.phasesMenu.AppendSeparator()
- self.printBLItem = wx.MenuItem(self.phasesMenu, self.printBLId,
- "Calculate bond lengths", "", wx.ITEM_NORMAL)
+ self.printBLItem = wx.MenuItem(
+ self.phasesMenu,
+ self.printBLId,
+ "Calculate bond lengths",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.phasesMenu.Append(self.printBLItem)
- self.printBAItem = wx.MenuItem(self.phasesMenu, self.printBAId,
- "Calculate bond angles", "", wx.ITEM_NORMAL)
+ self.printBAItem = wx.MenuItem(
+ self.phasesMenu, self.printBAId, "Calculate bond angles", "", wx.ITEM_NORMAL
+ )
self.phasesMenu.Append(self.printBAItem)
self.phasesMenu.AppendSeparator()
- self.expNewPhaseItem = wx.MenuItem(self.phasesMenu,
- self.exportNewStruId, "Export &Selected Phase", "",
- wx.ITEM_NORMAL)
+ self.expNewPhaseItem = wx.MenuItem(
+ self.phasesMenu,
+ self.exportNewStruId,
+ "Export &Selected Phase",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.phasesMenu.Append(self.expNewPhaseItem)
- self.expStruItem = wx.MenuItem(self.fitsMenu, self.exportFitStruId,
- "&Export Fit Structure", "", wx.ITEM_NORMAL)
+ self.expStruItem = wx.MenuItem(
+ self.fitsMenu,
+ self.exportFitStruId,
+ "&Export Fit Structure",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.phasesMenu.Append(self.expStruItem)
self.phasesMenu.AppendSeparator()
- self.plotIStructItem = wx.MenuItem(self.phasesMenu,
- self.plotIStructId, "&Plot Initial Structure", "",
- wx.ITEM_NORMAL)
+ self.plotIStructItem = wx.MenuItem(
+ self.phasesMenu,
+ self.plotIStructId,
+ "&Plot Initial Structure",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.phasesMenu.Append(self.plotIStructItem)
- self.plotFStructItem = wx.MenuItem(self.phasesMenu,
- self.plotFStructId, "&Plot Final Structure", "",
- wx.ITEM_NORMAL)
+ self.plotFStructItem = wx.MenuItem(
+ self.phasesMenu,
+ self.plotFStructId,
+ "&Plot Final Structure",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.phasesMenu.Append(self.plotFStructItem)
-
-
self.menuBar.Append(self.phasesMenu, "&Phases")
# End Phases Menu
# Data Menu
self.dataMenu = wx12.Menu()
- self.newDataItem = wx.MenuItem(self.dataMenu, self.newDataId,
- "&New Data Set\tCtrl+d", "", wx.ITEM_NORMAL)
+ self.newDataItem = wx.MenuItem(
+ self.dataMenu, self.newDataId, "&New Data Set\tCtrl+d", "", wx.ITEM_NORMAL
+ )
self.dataMenu.Append(self.newDataItem)
self.dataMenu.AppendSeparator()
- self.expFitPDFItem = wx.MenuItem(self.fitsMenu, self.exportFitPDFId,
- "&Export Fit PDF", "", wx.ITEM_NORMAL)
+ self.expFitPDFItem = wx.MenuItem(
+ self.fitsMenu, self.exportFitPDFId, "&Export Fit PDF", "", wx.ITEM_NORMAL
+ )
self.dataMenu.Append(self.expFitPDFItem)
self.menuBar.Append(self.dataMenu, "&Data")
# End Data Menu
# Calculations Menu
self.calcMenu = wx12.Menu()
- self.newCalcItem = wx.MenuItem(self.calcMenu, self.newCalcId,
- "&New Calculation\tCtrl+l", "", wx.ITEM_NORMAL)
+ self.newCalcItem = wx.MenuItem(
+ self.calcMenu,
+ self.newCalcId,
+ "&New Calculation\tCtrl+l",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.calcMenu.Append(self.newCalcItem)
self.calcMenu.AppendSeparator()
- self.runCalcItem = wx.MenuItem(self.calcMenu, self.runCalcId,
- "&Run Selected Calculation", "", wx.ITEM_NORMAL)
+ self.runCalcItem = wx.MenuItem(
+ self.calcMenu,
+ self.runCalcId,
+ "&Run Selected Calculation",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.calcMenu.Append(self.runCalcItem)
self.calcMenu.AppendSeparator()
- self.expCalcPDFItem = wx.MenuItem(self.calcMenu, self.exportCalcPDFId,
- "&Export Selected Calculation", "", wx.ITEM_NORMAL)
+ self.expCalcPDFItem = wx.MenuItem(
+ self.calcMenu,
+ self.exportCalcPDFId,
+ "&Export Selected Calculation",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.calcMenu.Append(self.expCalcPDFItem)
self.menuBar.Append(self.calcMenu, "Ca&lculations")
# End Calculations Menu
-
# Help Menu
self.helpMenu = wx12.Menu()
- self.docItem = wx.MenuItem(self.helpMenu, wx12.NewIdRef(),
- "&Documentation\tF1", "", wx.ITEM_NORMAL)
+ self.docItem = wx.MenuItem(
+ self.helpMenu, wx12.NewIdRef(), "&Documentation\tF1", "", wx.ITEM_NORMAL
+ )
self.helpMenu.Append(self.docItem)
- self.requestItem = wx.MenuItem(self.helpMenu, wx12.NewIdRef(),
- "Request a Feature / Report a Bug", "", wx.ITEM_NORMAL)
+ self.requestItem = wx.MenuItem(
+ self.helpMenu,
+ wx12.NewIdRef(),
+ "Request a Feature / Report a Bug",
+ "",
+ wx.ITEM_NORMAL,
+ )
self.helpMenu.Append(self.requestItem)
- self.communityItem = wx.MenuItem(self.helpMenu, wx12.NewIdRef(),
- "PDFgui Community", "", wx.ITEM_NORMAL)
+ self.communityItem = wx.MenuItem(
+ self.helpMenu, wx12.NewIdRef(), "PDFgui Community", "", wx.ITEM_NORMAL
+ )
self.helpMenu.Append(self.communityItem)
- self.aboutItem = wx.MenuItem(self.helpMenu, wx12.NewIdRef(),
- "&About", "", wx.ITEM_NORMAL)
+ self.aboutItem = wx.MenuItem(
+ self.helpMenu, wx12.NewIdRef(), "&About", "", wx.ITEM_NORMAL
+ )
self.helpMenu.Append(self.aboutItem)
self.menuBar.Append(self.helpMenu, "&Help")
# End Help Menu
@@ -615,18 +709,31 @@ def __setupToolBar(self):
size = (16, 16)
bitmap = wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR, size)
self.toolBar.AddTool(
- self.newId, "New Project", bitmap, wx.NullBitmap, wx.ITEM_NORMAL,
- "Start a new project")
- bitmap = wx.ArtProvider.GetBitmap(
- wx.ART_FILE_OPEN, wx.ART_TOOLBAR, size)
+ self.newId,
+ "New Project",
+ bitmap,
+ wx.NullBitmap,
+ wx.ITEM_NORMAL,
+ "Start a new project",
+ )
+ bitmap = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, size)
self.toolBar.AddTool(
- self.openId, "Open Project", bitmap, wx.NullBitmap, wx.ITEM_NORMAL,
- "Open an existing project")
- bitmap = wx.ArtProvider.GetBitmap(
- wx.ART_FILE_SAVE, wx.ART_TOOLBAR, size)
+ self.openId,
+ "Open Project",
+ bitmap,
+ wx.NullBitmap,
+ wx.ITEM_NORMAL,
+ "Open an existing project",
+ )
+ bitmap = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR, size)
self.toolBar.AddTool(
- self.saveId, "Save Project", bitmap, wx.NullBitmap, wx.ITEM_NORMAL,
- "Save this project")
+ self.saveId,
+ "Save Project",
+ bitmap,
+ wx.NullBitmap,
+ wx.ITEM_NORMAL,
+ "Save this project",
+ )
self.toolBar.AddSeparator()
# This fixes the shadowing problem on Windows.
# The bitmap has a white transparency color (mask)
@@ -636,21 +743,36 @@ def __setupToolBar(self):
mask = wx.Mask(bitmap, maskcolor)
bitmap.SetMask(mask)
self.toolBar.AddTool(
- self.runFitId, "Start", bitmap, wx.NullBitmap, wx.ITEM_NORMAL,
- "Start a fit or calculation")
+ self.runFitId,
+ "Start",
+ bitmap,
+ wx.NullBitmap,
+ wx.ITEM_NORMAL,
+ "Start a fit or calculation",
+ )
bitmap = wx.Bitmap(iconpath("stop.png"))
bitmap.SetSize(size)
mask = wx.Mask(bitmap, maskcolor)
bitmap.SetMask(mask)
self.toolBar.AddTool(
- self.stopFitId, "Stop", bitmap, wx.NullBitmap, wx.ITEM_NORMAL,
- "Stop running fits or calculations")
+ self.stopFitId,
+ "Stop",
+ bitmap,
+ wx.NullBitmap,
+ wx.ITEM_NORMAL,
+ "Stop running fits or calculations",
+ )
self.toolBar.AddSeparator()
bitmap = wx.Bitmap(iconpath("datasetitem.png"))
bitmap.SetSize(size)
self.toolBar.AddTool(
- self.quickPlotId, "Quick plot", bitmap, wx.NullBitmap,
- wx.ITEM_NORMAL, "Plot PDF or structure")
+ self.quickPlotId,
+ "Quick plot",
+ bitmap,
+ wx.NullBitmap,
+ wx.ITEM_NORMAL,
+ "Plot PDF or structure",
+ )
self.toolBar.Realize()
return
@@ -664,8 +786,8 @@ def __customBindings(self):
# Double-click select all type on tree
# FIXME - this doesn't work, I suspect the problem is with the tree
# selection code.
- #self.treeCtrlMain.Bind(wx.EVT_LEFT_DCLICK, self.onDoubleClick2)
- #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.onDoubleClick, self.treeCtrlMain)
+ # self.treeCtrlMain.Bind(wx.EVT_LEFT_DCLICK, self.onDoubleClick2)
+ # self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.onDoubleClick, self.treeCtrlMain)
# Middle-click quickplot
self.Bind(wx.EVT_TREE_ITEM_MIDDLE_CLICK, self.onMiddleClick, self.treeCtrlMain)
# Catch key events for the tree
@@ -692,8 +814,7 @@ def __menuBindings(self):
self.Bind(wx.EVT_MENU, self.onSaveAs, id=self.saveAsId)
self.Bind(wx.EVT_MENU, self.onQuit, id=self.quitId)
# For recent items
- self.Bind(wx.EVT_MENU_RANGE, self.onMRUFile,
- id=wx.ID_FILE1, id2=wx.ID_FILE5)
+ self.Bind(wx.EVT_MENU_RANGE, self.onMRUFile, id=wx.ID_FILE1, id2=wx.ID_FILE5)
## Edit Menu
self.Bind(wx.EVT_MENU, self.onDelete, id=self.deleteId)
@@ -783,8 +904,8 @@ def switchRightPanel(self, paneltype):
self.auiManager.GetPane(key).Hide()
# Why doesn't this work?
- #key = self.rightPanel.key
- #self.auiManager.GetPane(key).Hide()
+ # key = self.rightPanel.key
+ # self.auiManager.GetPane(key).Hide()
if paneltype is None:
paneltype = "blank"
@@ -836,24 +957,24 @@ def setPanelSpecificData(self, paneltype):
node = selections[0]
dataobject = self.treeCtrlMain.GetControlData(node)
- if paneltype == 'phase':
+ if paneltype == "phase":
self.rightPanel.configuration = dataobject.initial
self.rightPanel.constraints = dataobject.constraints
self.rightPanel.results = dataobject.refined
- elif paneltype == 'dataset':
+ elif paneltype == "dataset":
self.rightPanel.configuration = dataobject
self.rightPanel.constraints = dataobject.constraints
self.rightPanel.results = dataobject.refined
- elif paneltype == 'fit':
+ elif paneltype == "fit":
dataobject.updateParameters()
self.rightPanel.fit = dataobject
- elif paneltype == 'calculation':
+ elif paneltype == "calculation":
self.rightPanel.calculation = dataobject
- elif paneltype == 'rseries':
+ elif paneltype == "rseries":
self.rightPanel.fit = dataobject
- elif paneltype == 'tseries':
+ elif paneltype == "tseries":
self.rightPanel.fit = dataobject
- elif paneltype == 'dseries':
+ elif paneltype == "dseries":
self.rightPanel.fit = dataobject
return
@@ -888,7 +1009,7 @@ def setMode(self, mode):
* menuBar is disabled
"""
self.mode = mode
- if mode == 'fitting':
+ if mode == "fitting":
self.treeCtrlMain.Enable(True)
self.plotPanel.Enable(True)
self.toolBar.Enable(True)
@@ -932,6 +1053,7 @@ def loadConfiguration(self):
self.auiManager.LoadPerspective(perspective)
else:
from diffpy.pdfgui.gui.windowperspective import default
+
self.auiManager.LoadPerspective(default)
# Load the window dimensions
@@ -943,7 +1065,7 @@ def loadConfiguration(self):
if self.cP.has_option("SIZE", "height"):
h = self.cP.get("SIZE", "height")
h = int(h)
- self.SetSize((w,h))
+ self.SetSize((w, h))
# Load structure viewer information and put this in the configure panel
viewerconfig = {}
@@ -965,13 +1087,13 @@ def updateConfiguration(self):
for i in range(self.fileHistory.GetCount()):
item = self.fileHistory.GetHistoryFile(i)
- self.cP.setquoted("MRU", str(i+1), item)
+ self.cP.setquoted("MRU", str(i + 1), item)
# Window size
if not self.cP.has_section("SIZE"):
self.cP.add_section("SIZE")
- w,h = self.GetSize()
+ w, h = self.GetSize()
self.cP.set("SIZE", "width", str(w))
self.cP.set("SIZE", "height", str(h))
@@ -997,7 +1119,7 @@ def writeConfiguration(self):
filename = os.path.expanduser(pdfguiglobals.configfilename)
oflags = os.O_CREAT | os.O_WRONLY
try:
- with os.fdopen(os.open(filename, oflags, 0o600), 'w') as outfile:
+ with os.fdopen(os.open(filename, oflags, 0o600), "w") as outfile:
self.cP.write(outfile)
except IOError:
emsg = "Cannot write configuration file %r" % filename
@@ -1017,8 +1139,12 @@ def checkForSave(self):
if pdfguiglobals.dbopts.noconfirm:
return code
if pdfguiglobals.isAltered:
- d = wx.MessageDialog( self, "Would you like to save this session?",
- "Save?", wx.YES_NO|wx.CANCEL)
+ d = wx.MessageDialog(
+ self,
+ "Would you like to save this session?",
+ "Save?",
+ wx.YES_NO | wx.CANCEL,
+ )
code = d.ShowModal()
if code == wx.ID_YES:
code = self.onSave(None)
@@ -1054,7 +1180,8 @@ def makeTreeSelection(self, node):
If node is None, this does nothing.
"""
- if node is None: return
+ if node is None:
+ return
self.treeCtrlMain.SelectItem(node)
@@ -1088,7 +1215,7 @@ def treeSelectionUpdate(self, node):
if len(selections) == 0:
self.switchRightPanel("blank")
self.plotPanel.Enable(False)
- #return
+ # return
elif len(selections) == 1:
self.rightPanel.Enable()
selectiontype = self.treeCtrlMain.GetNodeType(selections[0])
@@ -1122,7 +1249,7 @@ def onTreeSelChanged(self, event):
self.treeSelectionUpdate(node)
return
- def onTreeSelChanging(self, event): # wxGlade: MainPanel.
+ def onTreeSelChanging(self, event): # wxGlade: MainPanel.
"""Set the click behavior for each mode.
Note that this doesn't work on Windows. Be sure to build in redundancy
@@ -1150,7 +1277,8 @@ def onTreeSelChanging(self, event): # wxGlade: MainPanel.
"""
# THIS DOESNT WORK ON WINDOWS!
node = event.GetItem()
- if not node: return
+ if not node:
+ return
if self.mode in ["addingdata", "addingphase", "config"]:
event.Veto()
elif self.mode in ["rseries", "tseries", "dseries"]:
@@ -1160,7 +1288,7 @@ def onTreeSelChanging(self, event): # wxGlade: MainPanel.
return
- def onBeginLabelEdit(self, event): # wxGlade: MainPanel.
+ def onBeginLabelEdit(self, event): # wxGlade: MainPanel.
"""Veto editing of some items and in some modes.
The following editing attempts are Veto()'d
@@ -1173,7 +1301,7 @@ def onBeginLabelEdit(self, event): # wxGlade: MainPanel.
event.Veto()
return
- def onEndLabelEdit(self, event): # wxGlade: MainPanel.
+ def onEndLabelEdit(self, event): # wxGlade: MainPanel.
"""Allow only certain types of renaming.
The following rename attempts are Veto()'d
@@ -1189,8 +1317,10 @@ def onEndLabelEdit(self, event): # wxGlade: MainPanel.
# No sibling's sharing the same name. (Sorry, George Foreman.)
node = event.GetItem()
- siblings = [self.treeCtrlMain.GetItemText(id) for
- id in self.treeCtrlMain.GetSiblings(node)]
+ siblings = [
+ self.treeCtrlMain.GetItemText(id)
+ for id in self.treeCtrlMain.GetSiblings(node)
+ ]
if label in siblings:
event.Veto()
return
@@ -1201,7 +1331,7 @@ def onEndLabelEdit(self, event): # wxGlade: MainPanel.
self.needsSave()
return
- def onRightClick(self, event): # wxGlade: MainPanel.
+ def onRightClick(self, event): # wxGlade: MainPanel.
"""Bring up the right-click menu.
This menu can give a different menu depending upon which mode the
@@ -1258,14 +1388,16 @@ def onRightClick(self, event): # wxGlade: MainPanel.
itemtype = None
x = event.GetX()
y = event.GetY()
- node, flags = self.treeCtrlMain.HitTest((x,y))
-
+ node, flags = self.treeCtrlMain.HitTest((x, y))
if flags in [
- wx.TREE_HITTEST_ABOVE,wx.TREE_HITTEST_BELOW,wx.TREE_HITTEST_NOWHERE]:
+ wx.TREE_HITTEST_ABOVE,
+ wx.TREE_HITTEST_BELOW,
+ wx.TREE_HITTEST_NOWHERE,
+ ]:
# The hit is not on an item.
self.treeCtrlMain.UnselectAll()
- self.switchRightPanel('blank')
+ self.switchRightPanel("blank")
selections = []
# Select the item with a right click, but don't add it to an
# existing selection.
@@ -1293,7 +1425,7 @@ def onRightClick(self, event): # wxGlade: MainPanel.
(x0, y0) = self.treeCtrlMain.GetPosition()
if pane.IsFloating():
(x0, y0) = self.ScreenToClient(pane.floating_pos)
- self.PopupMenu(menu, (x0+x,y0+y))
+ self.PopupMenu(menu, (x0 + x, y0 + y))
menu.Destroy()
return
@@ -1309,9 +1441,13 @@ def onDoubleClick2(self, event):
"""Select-all type on item double click."""
x = event.GetX()
y = event.GetY()
- node, flags = self.treeCtrlMain.HitTest((x,y))
+ node, flags = self.treeCtrlMain.HitTest((x, y))
- if flags not in [ wx.TREE_HITTEST_ABOVE,wx.TREE_HITTEST_BELOW,wx.TREE_HITTEST_NOWHERE]:
+ if flags not in [
+ wx.TREE_HITTEST_ABOVE,
+ wx.TREE_HITTEST_BELOW,
+ wx.TREE_HITTEST_NOWHERE,
+ ]:
if self.mode == "fitting":
wx.CallAfter(self.treeCtrlMain.SelectAllType, node)
wx.CallAfter(self.treeSelectionUpdate, node)
@@ -1352,7 +1488,7 @@ def onKey(self, event):
# XXX - removed - Without undo functionality, this is too dangerous.
# Delete
# "fitting" mode -- Delete selected noded
- #elif key == 127:
+ # elif key == 127:
# if self.mode == "fitting":
# self.onDelete(None)
@@ -1370,20 +1506,20 @@ def onKey(self, event):
def updateToolbar(self):
"""Update the toolbar based upon the status of the program."""
- self.toolBar.EnableTool(self.saveId, (pdfguiglobals.isAltered and
- self.runningDict == {}))
+ self.toolBar.EnableTool(
+ self.saveId, (pdfguiglobals.isAltered and self.runningDict == {})
+ )
itemtype = None
selections = self.treeCtrlMain.GetSelections()
if selections:
itemtype = self.treeCtrlMain.GetNodeType(selections[0])
-
# This is redundant, but easy to maintain
- if self.mode == 'fitting':
+ if self.mode == "fitting":
# Quickplot
- if len(selections) ==1 and itemtype and itemtype != "fit":
+ if len(selections) == 1 and itemtype and itemtype != "fit":
self.toolBar.EnableTool(self.quickPlotId, True)
else:
self.toolBar.EnableTool(self.quickPlotId, False)
@@ -1515,7 +1651,7 @@ def disableSharedMenuItems(self, menu):
menu.Enable(self.newDataId, False)
menu.Enable(self.newPhaseId, False)
menu.Enable(self.newCalcId, False)
- if clipbranchtype != 'fit':
+ if clipbranchtype != "fit":
menu.Enable(self.pasteId, False)
menu.Enable(self.pasteLinkId, False)
@@ -1625,7 +1761,6 @@ def disableMainMenuItems(self):
menu.Enable(self.exportFitStruId, False)
menu.Enable(self.plotFStructId, False)
-
# DATASET
if itemtype != "dataset":
menu.Enable(self.exportFitPDFId, False)
@@ -1657,7 +1792,6 @@ def disableMainMenuItems(self):
else:
menu.Enable(self.stopFitId, False)
-
# Show/Hide fitTree
if self.auiManager.GetPane("treeCtrlMain").IsShown():
self.showFitItem.SetItemLabel("Hide Fit Tree")
@@ -1684,7 +1818,6 @@ def disableMainMenuItems(self):
return
-
# Shared menu items
## The bulk of the code for these methods is in the FitTree class.
def onNewFit(self, event):
@@ -1738,7 +1871,8 @@ def onPasteLink(self, event):
fitname = cdata.name
fits = self.treeCtrlMain.GetChildren(self.treeCtrlMain.root)
fitnames = set(map(self.treeCtrlMain.GetItemText, fits))
- if fitname not in fitnames: return
+ if fitname not in fitnames:
+ return
ep = None
if selections:
@@ -1797,8 +1931,9 @@ def onInsCalc(self, event):
if len(selections) == 1:
node = selections[0]
fitroot = self.treeCtrlMain.GetFitRoot(node)
- newcalc = self.treeCtrlMain.AddCalc(fitroot, "Calculation 1",
- insertafter=node)
+ newcalc = self.treeCtrlMain.AddCalc(
+ fitroot, "Calculation 1", insertafter=node
+ )
# Select the calculation item so that the name can be edited
self.treeCtrlMain.UnselectAll()
self.treeCtrlMain.EditLabel(newcalc)
@@ -1854,10 +1989,18 @@ def onRun(self, event):
selections = self.treeCtrlMain.GetSelections()
# Get the calculation nodes and fit parent nodes from the selections.
- nodes = [self.treeCtrlMain.GetFitRoot(sel) for sel in selections if
- self.treeCtrlMain.GetNodeType(sel) != "calculation"]
- nodes.extend( [sel for sel in selections if
- self.treeCtrlMain.GetNodeType(sel) == "calculation"])
+ nodes = [
+ self.treeCtrlMain.GetFitRoot(sel)
+ for sel in selections
+ if self.treeCtrlMain.GetNodeType(sel) != "calculation"
+ ]
+ nodes.extend(
+ [
+ sel
+ for sel in selections
+ if self.treeCtrlMain.GetNodeType(sel) == "calculation"
+ ]
+ )
# Add calculation nodes that are children of fit nodes, and order them
# as if walking down the fit tree
@@ -1865,7 +2008,7 @@ def onRun(self, event):
for node in nodes:
if node not in allnodes:
allnodes.append(node)
- if self.treeCtrlMain.GetNodeType(node) == 'fit':
+ if self.treeCtrlMain.GetNodeType(node) == "fit":
allnodes.extend(self.treeCtrlMain.GetChildren(node))
# Disable the current panel
@@ -1876,7 +2019,7 @@ def onRun(self, event):
# updateFittingStatus for the color scheme. Create a dictionary of fits
# for ease of use.
for sel in allnodes:
- if self.treeCtrlMain.GetNodeType(sel) == 'fit':
+ if self.treeCtrlMain.GetNodeType(sel) == "fit":
self.treeCtrlMain.SetItemBackgroundColour(sel, wx.LIGHT_GREY)
name = self.treeCtrlMain.GetItemText(sel)
self.runningDict[name] = sel
@@ -1908,6 +2051,7 @@ def onPreferences(self, event):
def onDefaultLayout(self, event):
"""Place the fit tree and plot panel in default locations."""
from diffpy.pdfgui.gui.windowperspective import default
+
self.auiManager.LoadPerspective(default)
self.auiManager.Update()
return
@@ -1979,9 +2123,9 @@ def _plotStruct(self, stype):
return
def onPrintBL(self, event):
- """Print the bond lengths of a selected structure to the output panel.
- """
+ """Print the bond lengths of a selected structure to the output panel."""
from diffpy.pdfgui.gui.bondlengthdialog import BondLengthDialog
+
selections = self.treeCtrlMain.GetSelections()
if selections:
node = selections[0]
@@ -1990,7 +2134,8 @@ def onPrintBL(self, event):
# panel = self.dynamicPanels['phase']
cdata = self.treeCtrlMain.GetControlData(node)
S = cdata.refined
- if not S: S = cdata.initial
+ if not S:
+ S = cdata.initial
dlg = BondLengthDialog(self)
dlg.setStructure(S)
@@ -2020,11 +2165,10 @@ def onPrintBL(self, event):
dlg.Destroy()
return
-
def onPrintBA(self, event):
- """Print the bond angles of a selected structure to the output panel.
- """
+ """Print the bond angles of a selected structure to the output panel."""
from diffpy.pdfgui.gui.bondangledialog import BondAngleDialog
+
selections = self.treeCtrlMain.GetSelections()
if selections:
node = selections[0]
@@ -2033,7 +2177,8 @@ def onPrintBA(self, event):
# panel = self.dynamicPanels['phase']
cdata = self.treeCtrlMain.GetControlData(node)
S = cdata.refined
- if not S: S = cdata.initial
+ if not S:
+ S = cdata.initial
dlg = BondAngleDialog(self)
dlg.setStructure(S)
@@ -2049,22 +2194,23 @@ def onPrintBA(self, event):
def onQuickPlot(self, event):
"""Quickly plot information for the selected node."""
selections = self.treeCtrlMain.GetSelections()
- if len(selections) != 1: return
+ if len(selections) != 1:
+ return
node = selections[0]
refs = [self.treeCtrlMain.GetControlData(node)]
nodetype = self.treeCtrlMain.GetNodeType(selections[0])
if nodetype == "dataset":
- xval = 'r'
+ xval = "r"
# For quick plotting, keep this order. Gdiff must be the last.
- yvals = ['Gtrunc', 'Gcalc', 'Gdiff']
+ yvals = ["Gtrunc", "Gcalc", "Gdiff"]
soffset = self.plotPanel.offsetTextCtrl.GetValue()
offset = 0
if soffset:
offset = float(self.plotPanel.offsetTextCtrl.GetValue())
self.control.plot(xval, yvals, refs, shift=offset)
elif nodetype == "calculation":
- xval = 'r'
- yvals = ['Gcalc']
+ xval = "r"
+ yvals = ["Gcalc"]
self.control.plot(xval, yvals, refs, shift=0)
elif nodetype == "phase":
cdata = self.treeCtrlMain.GetControlData(node)
@@ -2076,22 +2222,22 @@ def onQuickPlot(self, event):
def onAbout(self, event):
dlg = DialogAbout(self)
-# dlg.CenterOnScreen()
+ # dlg.CenterOnScreen()
dlg.ShowModal()
dlg.Destroy()
return
def onRequest(self, event):
dlg = ErrorReportDialog(self)
- #dlg.errorReport = True
+ # dlg.errorReport = True
dlg.ShowModal()
dlg.Destroy()
return
def onCommunity(self, event):
- """Open the brower and go to the diffpy-users Google Group.
- """
+ """Open the brower and go to the diffpy-users Google Group."""
import webbrowser
+
try:
webbrowser.open(USERSMAILINGLIST)
except Exception as e:
@@ -2099,7 +2245,6 @@ def onCommunity(self, event):
raise ControlError(errorinfo)
return
-
def onNew(self, event):
"""Create a new project."""
retval = self.checkForSave()
@@ -2108,7 +2253,7 @@ def onNew(self, event):
self.control.close()
self.treeCtrlMain.DeleteAllItems()
self.treeCtrlMain.InitializeTree()
- self.switchRightPanel('welcome')
+ self.switchRightPanel("welcome")
self.plotPanel.refresh()
self.needsSave(False)
self.fullpath = ""
@@ -2133,8 +2278,8 @@ def onOpen(self, event):
self.control.close()
treelist = self.control.load(fullpath)
self.treeCtrlMain.ExtendProjectTree(treelist)
- self.setMode('fitting')
- self.switchRightPanel('welcome')
+ self.setMode("fitting")
+ self.switchRightPanel("welcome")
self.fullpath = fullpath
self.workpath = os.path.dirname(fullpath)
@@ -2173,13 +2318,19 @@ def onSaveAs(self, event):
dir, filename = os.path.split(self.fullpath)
if not dir:
dir = self.workpath
- d = wx.FileDialog(None, "Save as...", dir, filename or "project.ddp3",
- matchstring, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
+ d = wx.FileDialog(
+ None,
+ "Save as...",
+ dir,
+ filename or "project.ddp3",
+ matchstring,
+ wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
+ )
code = d.ShowModal()
if code == wx.ID_OK:
self.fullpath = d.GetPath()
- if len(self.fullpath) < 5 or self.fullpath[-5:] != '.ddp3':
- self.fullpath += '.ddp3'
+ if len(self.fullpath) < 5 or self.fullpath[-5:] != ".ddp3":
+ self.fullpath += ".ddp3"
self.workpath = os.path.dirname(self.fullpath)
self.fileHistory.AddFileToHistory(self.fullpath)
# Save the file
@@ -2214,8 +2365,8 @@ def onMRUFile(self, event):
try:
treelist = self.control.load(filename)
self.treeCtrlMain.ExtendProjectTree(treelist)
- self.setMode('fitting')
- self.switchRightPanel('welcome')
+ self.setMode("fitting")
+ self.switchRightPanel("welcome")
self.needsSave(False)
self.outputPanel.clearText()
self.journalPanel.refresh()
@@ -2233,16 +2384,24 @@ def onMRUFile(self, event):
def onExportRes(self, event):
"""Export the results file for the selected calculation."""
selections = self.treeCtrlMain.GetSelections()
- if not selections: return
+ if not selections:
+ return
node = selections[0]
nodetype = self.treeCtrlMain.GetNodeType(node)
- if nodetype != 'fit': return
+ if nodetype != "fit":
+ return
cdata = self.treeCtrlMain.GetControlData(node)
name = self.treeCtrlMain.GetItemText(node)
- basename = '.'.join(name.split('.')[:-1]) or name
+ basename = ".".join(name.split(".")[:-1]) or name
matchstring = "PDFgui results files (*.res)|*.res|All Files|*"
- d = wx.FileDialog(None, "Save as...", self.workpath, basename,
- matchstring, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
+ d = wx.FileDialog(
+ None,
+ "Save as...",
+ self.workpath,
+ basename,
+ matchstring,
+ wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
+ )
if d.ShowModal() == wx.ID_OK:
path = d.GetPath()
self.workpath, savename = os.path.split(path)
@@ -2250,7 +2409,7 @@ def onExportRes(self, event):
if len(savename) < 3 or savename[-3:] != "res":
savename += ".res"
path = os.path.join(self.workpath, savename)
- outfile = open(path, 'w')
+ outfile = open(path, "w")
outfile.write(cdata.res)
outfile.close()
d.Destroy()
@@ -2276,31 +2435,38 @@ def onDSeries(self, event):
def onExportNewStruct(self, event):
"""Export a structure that was created from scratch."""
- extlist = ['stru', 'cif', 'pdb', 'xyz', 'xyz', '']
- fmtlist = ['pdffit', 'cif', 'pdb', 'xyz', 'rawxyz', 'xcfg']
+ extlist = ["stru", "cif", "pdb", "xyz", "xyz", ""]
+ fmtlist = ["pdffit", "cif", "pdb", "xyz", "rawxyz", "xcfg"]
selections = self.treeCtrlMain.GetSelections()
- if not selections: return
+ if not selections:
+ return
node = selections[0]
nodetype = self.treeCtrlMain.GetNodeType(node)
- if nodetype != 'phase': return
+ if nodetype != "phase":
+ return
cdata = self.treeCtrlMain.GetControlData(node)
# branchname = self.treeCtrlMain.GetBranchName(node)
name = self.treeCtrlMain.GetItemText(node)
- basename = '.'.join(name.split('.')[:-1]) or name
+ basename = ".".join(name.split(".")[:-1]) or name
matchstring = "PDFfit structure file (*.stru)|*.stru|Crystallographic Information File (*.cif)|*.cif|Protein Data Bank file (*.pdb)|*.pdb|Labeled coordinate file (*.xyz)|*.xyz|Raw corrdinate file (*.xyz)|*.xyz|AtomEye configuration file|*"
- d = wx.FileDialog(None, "Save as...", self.workpath, basename,
- matchstring, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
+ d = wx.FileDialog(
+ None,
+ "Save as...",
+ self.workpath,
+ basename,
+ matchstring,
+ wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
+ )
if d.ShowModal() == wx.ID_OK:
i = d.GetFilterIndex()
path = d.GetPath()
self.workpath, savename = os.path.split(path)
# Add the right extention if the file needs it.
- if len(savename) < 3 or \
- (extlist[i] and savename[-3:] != extlist[i][-3:]):
+ if len(savename) < 3 or (extlist[i] and savename[-3:] != extlist[i][-3:]):
savename += ".%s" % extlist[i]
path = os.path.join(self.workpath, savename)
text = cdata.initial.writeStr(fmtlist[i])
- outfile = open(path, 'w')
+ outfile = open(path, "w")
outfile.write(text)
outfile.close()
d.Destroy()
@@ -2308,31 +2474,38 @@ def onExportNewStruct(self, event):
def onExportStruct(self, event):
"""Export a fit structure."""
- extlist = ['stru', 'cif', 'pdb', 'xyz', 'xyz', '']
- fmtlist = ['pdffit', 'cif', 'pdb', 'xyz', 'rawxyz', 'xcfg']
+ extlist = ["stru", "cif", "pdb", "xyz", "xyz", ""]
+ fmtlist = ["pdffit", "cif", "pdb", "xyz", "rawxyz", "xcfg"]
selections = self.treeCtrlMain.GetSelections()
- if not selections: return
+ if not selections:
+ return
node = selections[0]
nodetype = self.treeCtrlMain.GetNodeType(node)
- if nodetype != 'phase': return
+ if nodetype != "phase":
+ return
cdata = self.treeCtrlMain.GetControlData(node)
# branchname = self.treeCtrlMain.GetBranchName(node)
name = self.treeCtrlMain.GetItemText(node)
- basename = '.'.join(name.split('.')[:-1]) or name
+ basename = ".".join(name.split(".")[:-1]) or name
matchstring = "PDFfit structure file (*.stru)|*.stru|Crystallographic Information File (*.cif)|*.cif|Protein Data Bank file (*.pdb)|*.pdb|Labeled coordinate file (*.xyz)|*.xyz|Raw corrdinate file (*.xyz)|*.xyz|AtomEye configuration file|*"
- d = wx.FileDialog(None, "Save as...", self.workpath, basename,
- matchstring, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
+ d = wx.FileDialog(
+ None,
+ "Save as...",
+ self.workpath,
+ basename,
+ matchstring,
+ wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
+ )
if d.ShowModal() == wx.ID_OK:
i = d.GetFilterIndex()
path = d.GetPath()
self.workpath, savename = os.path.split(path)
# Add the right extention if the file needs it.
- if len(savename) < 3 or \
- (extlist[i] and savename[-3:] != extlist[i][-3:]):
+ if len(savename) < 3 or (extlist[i] and savename[-3:] != extlist[i][-3:]):
savename += ".%s" % extlist[i]
path = os.path.join(self.workpath, savename)
text = cdata.refined.writeStr(fmtlist[i])
- outfile = open(path, 'w')
+ outfile = open(path, "w")
outfile.write(text)
outfile.close()
d.Destroy()
@@ -2341,17 +2514,25 @@ def onExportStruct(self, event):
def onExportPDF(self, event):
"""Export a fit PDF."""
selections = self.treeCtrlMain.GetSelections()
- if not selections: return
+ if not selections:
+ return
node = selections[0]
nodetype = self.treeCtrlMain.GetNodeType(node)
- if nodetype != 'dataset': return
+ if nodetype != "dataset":
+ return
cdata = self.treeCtrlMain.GetControlData(node)
# branchname = self.treeCtrlMain.GetBranchName(node)
name = self.treeCtrlMain.GetItemText(node)
- basename = '.'.join(name.split('.')[:-1]) or name
+ basename = ".".join(name.split(".")[:-1]) or name
matchstring = "PDF fit data file (*.fgr)|*.fgr|All Files|*"
- d = wx.FileDialog(None, "Save as...", self.workpath, basename,
- matchstring, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
+ d = wx.FileDialog(
+ None,
+ "Save as...",
+ self.workpath,
+ basename,
+ matchstring,
+ wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
+ )
if d.ShowModal() == wx.ID_OK:
path = d.GetPath()
self.workpath, savename = os.path.split(path)
@@ -2366,16 +2547,24 @@ def onExportPDF(self, event):
def onSaveCalc(self, event):
"""Export a calculated PDF."""
selections = self.treeCtrlMain.GetSelections()
- if not selections: return
+ if not selections:
+ return
node = selections[0]
nodetype = self.treeCtrlMain.GetNodeType(node)
- if nodetype != 'calculation': return
+ if nodetype != "calculation":
+ return
cdata = self.treeCtrlMain.GetControlData(node)
name = self.treeCtrlMain.GetItemText(node)
- basename = '.'.join(name.split('.')[:-1]) or name
+ basename = ".".join(name.split(".")[:-1]) or name
matchstring = "PDF calculated data file (*.cgr)|*.cgr|All Files|*"
- d = wx.FileDialog(None, "Save as...", self.workpath, basename,
- matchstring, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
+ d = wx.FileDialog(
+ None,
+ "Save as...",
+ self.workpath,
+ basename,
+ matchstring,
+ wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
+ )
if d.ShowModal() == wx.ID_OK:
path = d.GetPath()
self.workpath, savename = os.path.split(path)
@@ -2391,18 +2580,19 @@ def onDocumentation(self, event):
"""Show information about the documentation."""
import webbrowser
from six.moves.urllib.request import pathname2url
- url = 'file://' + pathname2url(docMainFile)
+
+ url = "file://" + pathname2url(docMainFile)
webbrowser.open(url)
return
# MISC INTERACTION ITEMS
- def showMessage(self, info, title = "PDF Control Error"):
+ def showMessage(self, info, title="PDF Control Error"):
"""showMessage(self, info) --> tell user about an exception and so on
title -- window title
info -- message
"""
- dlg = wx.MessageDialog(self, info, title, wx.OK|wx.ICON_ERROR)
+ dlg = wx.MessageDialog(self, info, title, wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
@@ -2467,6 +2657,7 @@ def updateFittingStatus(self, job):
PAUSED
"""
from diffpy.pdfgui.control.fitting import Fitting
+
if isinstance(job, Fitting):
name = job.name
fitStatus = job.fitStatus
@@ -2477,8 +2668,7 @@ def updateFittingStatus(self, job):
return
if jobStatus == Fitting.RUNNING:
if fitStatus == Fitting.INITIALIZED:
- self.treeCtrlMain.SetItemBackgroundColour(
- node, wx.LIGHT_GREY)
+ self.treeCtrlMain.SetItemBackgroundColour(node, wx.LIGHT_GREY)
elif fitStatus in (Fitting.CONNECTED, Fitting.CONFIGURED):
self.treeCtrlMain.SetItemBackgroundColour(node, wx.GREEN)
elif jobStatus == Fitting.VOID:
@@ -2502,4 +2692,5 @@ def updateOutput(self):
self.outputPanel.updateText(self.control.getEngineOutput())
return
+
# end of class MainPanel
diff --git a/src/diffpy/pdfgui/gui/outputpanel.py b/src/diffpy/pdfgui/gui/outputpanel.py
index 7e4e8f05..7a1d68ca 100644
--- a/src/diffpy/pdfgui/gui/outputpanel.py
+++ b/src/diffpy/pdfgui/gui/outputpanel.py
@@ -19,12 +19,15 @@
import wx
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
-class OutputPanel(wx.Panel,PDFPanel):
+
+class OutputPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
# begin wxGlade: OutputPanel.__init__
kwds["style"] = kwds.get("style", 0) | wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
- self.outputTextCtrl = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.HSCROLL | wx.TE_MULTILINE | wx.TE_READONLY)
+ self.outputTextCtrl = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.HSCROLL | wx.TE_MULTILINE | wx.TE_READONLY
+ )
self.__set_properties()
self.__do_layout()
@@ -50,8 +53,12 @@ def __customProperties(self):
"""Set the custom properties."""
# Set the font to monospace
ftxt = self.outputTextCtrl.GetFont()
- font = wx.Font(ftxt.GetPointSize(), wx.FONTFAMILY_TELETYPE,
- ftxt.GetStyle(), ftxt.GetWeight())
+ font = wx.Font(
+ ftxt.GetPointSize(),
+ wx.FONTFAMILY_TELETYPE,
+ ftxt.GetStyle(),
+ ftxt.GetWeight(),
+ )
self.outputTextCtrl.SetFont(font)
return
@@ -68,4 +75,5 @@ def updateText(self, text):
def refresh(self):
pass
+
# end of class OutputPanel
diff --git a/src/diffpy/pdfgui/gui/paneltest.py b/src/diffpy/pdfgui/gui/paneltest.py
index b49313be..5adda3b9 100644
--- a/src/diffpy/pdfgui/gui/paneltest.py
+++ b/src/diffpy/pdfgui/gui/paneltest.py
@@ -17,23 +17,25 @@
# generated by wxGlade 0.4 on Tue Feb 21 12:00:30 2006
import wx
-#from diffpy.pdfgui.gui.mainframe import MainPanel
-#from diffpy.pdfgui.gui.journalpanel import JournalPanel
-#from diffpy.pdfgui.gui.datasetconfigurepanel import DataSetConfigurePanel
-#from diffpy.pdfgui.gui.fitnotebookpanel import FitNotebookPanel
-#from diffpy.pdfgui.gui.rseriespanel import RSeriesPanel
+
+# from diffpy.pdfgui.gui.mainframe import MainPanel
+# from diffpy.pdfgui.gui.journalpanel import JournalPanel
+# from diffpy.pdfgui.gui.datasetconfigurepanel import DataSetConfigurePanel
+# from diffpy.pdfgui.gui.fitnotebookpanel import FitNotebookPanel
+# from diffpy.pdfgui.gui.rseriespanel import RSeriesPanel
from diffpy.pdfgui.gui.temperatureseriespanel import TemperatureSeriesPanel
+
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
- #self.window_1 = MainPanel(self, -1)
- #self.window_1 = JournalPanel(self, -1)
- #self.window_1 = DataSetConfigurePanel(self, -1)
- #self.window_1 = FitNotebookPanel(self, -1)
- #self.window_1 = RSeriesPanel(self, -1)
+ # self.window_1 = MainPanel(self, -1)
+ # self.window_1 = JournalPanel(self, -1)
+ # self.window_1 = DataSetConfigurePanel(self, -1)
+ # self.window_1 = FitNotebookPanel(self, -1)
+ # self.window_1 = RSeriesPanel(self, -1)
self.window_1 = TemperatureSeriesPanel(self, -1)
self.__set_properties()
@@ -57,6 +59,7 @@ def __do_layout(self):
# end wxGlade
self.SetSize((700, 120))
+
# end of class MyFrame
@@ -67,6 +70,7 @@ def OnInit(self):
frame_1.Show()
return True
+
# end of class MyApp
if __name__ == "__main__":
diff --git a/src/diffpy/pdfgui/gui/parameterspanel.py b/src/diffpy/pdfgui/gui/parameterspanel.py
index b5305a21..804e714f 100644
--- a/src/diffpy/pdfgui/gui/parameterspanel.py
+++ b/src/diffpy/pdfgui/gui/parameterspanel.py
@@ -24,18 +24,18 @@
import wx.grid
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
from diffpy.pdfgui.gui.wxextensions import wx12
-from diffpy.pdfgui.gui.wxextensions.autowidthlabelsgrid import \
- AutoWidthLabelsGrid
+from diffpy.pdfgui.gui.wxextensions.autowidthlabelsgrid import AutoWidthLabelsGrid
from diffpy.utils.wx import gridutils
class ParametersPanel(wx.Panel, PDFPanel):
- '''GUI Panel, parameters viewer/editor
+ """GUI Panel, parameters viewer/editor
Data members:
parameters -- parameters dictionary
_focusedText -- value of a cell before it changes
- '''
+ """
+
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
# begin wxGlade: ParametersPanel.__init__
@@ -47,17 +47,32 @@ def __init__(self, *args, **kwds):
self.__set_properties()
self.__do_layout()
- self.Bind(wx.grid.EVT_GRID_CMD_CELL_CHANGED, self.onCellChange, self.grid_parameters)
- self.Bind(wx.grid.EVT_GRID_CMD_CELL_LEFT_CLICK, self.onCellLeftClick, self.grid_parameters)
- self.Bind(wx.grid.EVT_GRID_CMD_CELL_RIGHT_CLICK, self.onCellRightClick, self.grid_parameters)
- self.Bind(wx.grid.EVT_GRID_CMD_EDITOR_SHOWN, self.onEditorShown, self.grid_parameters)
- self.Bind(wx.grid.EVT_GRID_CMD_RANGE_SELECT, self.onGridRangeSelect, self.grid_parameters)
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_CELL_CHANGED, self.onCellChange, self.grid_parameters
+ )
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_CELL_LEFT_CLICK,
+ self.onCellLeftClick,
+ self.grid_parameters,
+ )
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_CELL_RIGHT_CLICK,
+ self.onCellRightClick,
+ self.grid_parameters,
+ )
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_EDITOR_SHOWN, self.onEditorShown, self.grid_parameters
+ )
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_RANGE_SELECT,
+ self.onGridRangeSelect,
+ self.grid_parameters,
+ )
self.Bind(wx.EVT_BUTTON, self.onApplyParameters, self.button_applyparameters)
# end wxGlade
self.__customProperties()
return
-
def __set_properties(self):
# begin wxGlade: ParametersPanel.__set_properties
self.grid_parameters.CreateGrid(0, 3)
@@ -73,7 +88,6 @@ def __set_properties(self):
attr.SetRenderer(wx.grid.GridCellBoolRenderer())
self.grid_parameters.SetColAttr(1, attr)
-
def __do_layout(self):
# begin wxGlade: ParametersPanel.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
@@ -99,20 +113,20 @@ def __customProperties(self):
return
def refresh(self):
- ''' Refreshes wigets on the panel'''
-# # Update the parameters dictionary
-# self.fitting.updateParameters()
+ """Refreshes wigets on the panel"""
+ # # Update the parameters dictionary
+ # self.fitting.updateParameters()
nRows = len(self.parameters)
### update the grid
- #remove all rows and create new ones
+ # remove all rows and create new ones
self.grid_parameters.BeginBatch()
gridrows = self.grid_parameters.GetNumberRows()
if gridrows != 0:
- self.grid_parameters.DeleteRows( numRows = gridrows )
- self.grid_parameters.InsertRows( numRows = nRows )
- #self.grid_parameters.SetColFormatBool(1)
+ self.grid_parameters.DeleteRows(numRows=gridrows)
+ self.grid_parameters.InsertRows(numRows=nRows)
+ # self.grid_parameters.SetColFormatBool(1)
i = 0
keys = sorted(self.parameters.keys())
@@ -120,31 +134,40 @@ def refresh(self):
# parameter index
self.grid_parameters.SetRowLabelValue(i, str(self.parameters[key].idx))
# initial value
- self.grid_parameters.SetCellValue(i,0, str(self.parameters[key].initialStr()) )
+ self.grid_parameters.SetCellValue(
+ i, 0, str(self.parameters[key].initialStr())
+ )
# flag "fixed"
- #NOTE: for bool type of cells use '0' or '1' as False and True
- self.grid_parameters.SetCellValue(i,1, str(int(self.parameters[key].fixed)) )
+ # NOTE: for bool type of cells use '0' or '1' as False and True
+ self.grid_parameters.SetCellValue(
+ i, 1, str(int(self.parameters[key].fixed))
+ )
# refined value
- self.grid_parameters.SetReadOnly(i,2)
+ self.grid_parameters.SetReadOnly(i, 2)
if self.parameters[key].refined is None:
- self.grid_parameters.SetCellValue(i,2, "" )
+ self.grid_parameters.SetCellValue(i, 2, "")
else:
- self.grid_parameters.SetCellValue(i,2, str(self.parameters[key].refined) )
+ self.grid_parameters.SetCellValue(
+ i, 2, str(self.parameters[key].refined)
+ )
i += 1
self.grid_parameters.AutosizeLabels()
self.grid_parameters.AutoSizeColumns()
self.grid_parameters.EndBatch()
-
- def onCellLeftClick(self, event): # wxGlade: ParametersPanel.
+ def onCellLeftClick(self, event): # wxGlade: ParametersPanel.
"""Toggle a fix/free cell when clicked."""
r = event.GetRow()
c = event.GetCol()
# Only proceed if there is no selection and
# this click has no keyboard modifiers.
- ignorethis = (c != 1 or self.grid_parameters.IsSelection() or
- event.ShiftDown() or event.ControlDown())
+ ignorethis = (
+ c != 1
+ or self.grid_parameters.IsSelection()
+ or event.ShiftDown()
+ or event.ControlDown()
+ )
if ignorethis:
# do standard click event handling
event.Skip()
@@ -155,8 +178,7 @@ def onCellLeftClick(self, event): # wxGlade: ParametersPanel.
self.applyCellChange(r, c, not state)
return
-
- def onGridRangeSelect(self, event): # wxGlade: ParametersPanel.
+ def onGridRangeSelect(self, event): # wxGlade: ParametersPanel.
"""Handle range selections.
This is needed to properly handle simple left-clicking of fix/free
@@ -165,7 +187,7 @@ def onGridRangeSelect(self, event): # wxGlade: ParametersPanel.
event.Skip()
return
- def onCellRightClick(self, event): # wxGlade: ParametersPanel.
+ def onCellRightClick(self, event): # wxGlade: ParametersPanel.
# Popup the menu. If an item is selected then its handler
# will be called before PopupMenu returns.
r = event.GetRow()
@@ -173,23 +195,24 @@ def onCellRightClick(self, event): # wxGlade: ParametersPanel.
# If the right-clicked node is not part of a group, then make sure that
# it is the only selected cell.
append = False
- if self.grid_parameters.IsInSelection(r,c):
+ if self.grid_parameters.IsInSelection(r, c):
append = True
- self.grid_parameters.SelectBlock(r,c,r,c,append)
- self.popupMenu(self.grid_parameters, event.GetPosition().x,
- event.GetPosition().y)
+ self.grid_parameters.SelectBlock(r, c, r, c, append)
+ self.popupMenu(
+ self.grid_parameters, event.GetPosition().x, event.GetPosition().y
+ )
event.Skip()
return
- def onEditorShown(self, event): # wxGlade: ParametersPanel.
+ def onEditorShown(self, event): # wxGlade: ParametersPanel.
i = event.GetRow()
j = event.GetCol()
- self._focusedText = self.grid_parameters.GetCellValue(i,j)
+ self._focusedText = self.grid_parameters.GetCellValue(i, j)
self._selectedCells = gridutils.getSelectedCells(self.grid_parameters)
event.Skip()
return
- def onCellChange(self, event): # wxGlade: ParametersPanel.
+ def onCellChange(self, event): # wxGlade: ParametersPanel.
# NOTE: be careful with refresh() => recursion! operations on grid will
# call onCellChange
# Note that this method does not get called when a fix/free cell is
@@ -197,10 +220,11 @@ def onCellChange(self, event): # wxGlade: ParametersPanel.
i = event.GetRow()
j = event.GetCol()
- if self._focusedText is None: return
+ if self._focusedText is None:
+ return
self._focusedText = None
- value = self.grid_parameters.GetCellValue(i,j)
+ value = self.grid_parameters.GetCellValue(i, j)
# Verify the value. This is done here since if it is allowed to be done
# in fillCells, then an error dialog will be thrown for each point
# in the loop.
@@ -222,7 +246,7 @@ def onCellChange(self, event): # wxGlade: ParametersPanel.
self.fillCells(self._selectedCells, value)
self.grid_parameters.AutoSizeColumns(0)
finally:
- #self.refresh()
+ # self.refresh()
event.Skip()
return
@@ -244,7 +268,7 @@ def applyCellChange(self, row, col, value):
temp = self.parameters[key].initialValue()
if temp != value:
self.parameters[key].setInitial(value)
- self.grid_parameters.SetCellValue(row,0,str(float(value)))
+ self.grid_parameters.SetCellValue(row, 0, str(float(value)))
self.mainFrame.needsSave()
elif col == 1: # flag "fixed"
@@ -252,12 +276,11 @@ def applyCellChange(self, row, col, value):
value = bool(int(value))
if temp is not value:
self.parameters[key].fixed = value
- self.grid_parameters.SetCellValue(row,1,str(int(value)))
+ self.grid_parameters.SetCellValue(row, 1, str(int(value)))
self.mainFrame.needsSave()
return
-
def popupMenu(self, window, x, y):
"""Opens a popup menu
@@ -272,9 +295,9 @@ def popupMenu(self, window, x, y):
self.popupID2 = wx12.NewIdRef()
self.popupID3 = wx12.NewIdRef()
- self.Bind(wx.EVT_MENU, self.onPopupFixFree, id=self.popupID1)
- self.Bind(wx.EVT_MENU, self.onPopupCopyRefinedToInitial, id=self.popupID2)
- self.Bind(wx.EVT_MENU, self.onPopupRenameParameters, id=self.popupID3)
+ self.Bind(wx.EVT_MENU, self.onPopupFixFree, id=self.popupID1)
+ self.Bind(wx.EVT_MENU, self.onPopupCopyRefinedToInitial, id=self.popupID2)
+ self.Bind(wx.EVT_MENU, self.onPopupRenameParameters, id=self.popupID3)
# make a menu
menu = wx.Menu()
@@ -286,17 +309,17 @@ def popupMenu(self, window, x, y):
# Popup the menu. If an item is selected then its handler
# will be called before PopupMenu returns.
- window.PopupMenu(menu, wx.Point(x,y))
+ window.PopupMenu(menu, wx.Point(x, y))
menu.Destroy()
return
##### Popup menu events ##################################################
def onPopupFill(self, event):
- '''Fills cells selected in the grid with a new value'''
+ """Fills cells selected in the grid with a new value"""
# NOTE: GetSelectedCells returns only SINGLE selected cells, not blocks or row/columns !
if self.grid_parameters.IsSelection():
- dlg = wx.TextEntryDialog(self, 'New value:','Fill Selected Cells', '')
+ dlg = wx.TextEntryDialog(self, "New value:", "Fill Selected Cells", "")
if dlg.ShowModal() == wx.ID_OK:
value = dlg.GetValue()
@@ -306,18 +329,18 @@ def onPopupFill(self, event):
for i in range(rows):
for j in range(cols):
- inSelection = self.grid_parameters.IsInSelection(i,j)
- valueChanged = (value != self.grid_parameters.GetCellValue(i,j))
+ inSelection = self.grid_parameters.IsInSelection(i, j)
+ valueChanged = value != self.grid_parameters.GetCellValue(i, j)
if inSelection and valueChanged:
self.applyCellChange(i, j, value)
- #self.refresh()
+ # self.refresh()
dlg.Destroy()
event.Skip()
def onPopupFixFree(self, event):
- '''Fixes parameters with selected cells'''
+ """Fixes parameters with selected cells"""
# NOTE: GetSelectedCells returns only SINGLE selected cells, not blocks
# or row/columns !
seldict = {}
@@ -325,14 +348,14 @@ def onPopupFixFree(self, event):
indices = self.getSelectedParameters()
for row in indices:
- state = self.grid_parameters.GetCellValue(row,1)
+ state = self.grid_parameters.GetCellValue(row, 1)
state = bool(int(state.strip() or "0"))
seldict[row] = state
# Find the majority state
nfixed = sum(1 for st in seldict.values() if st)
nfree = len(seldict) - nfixed
- newstate = True # fixed
+ newstate = True # fixed
if nfree < nfixed:
# free all parameters
newstate = False
@@ -343,14 +366,14 @@ def onPopupFixFree(self, event):
return
def onPopupCopyRefinedToInitial(self, event):
- """Copy refined parameter to initial value.
- """
+ """Copy refined parameter to initial value."""
if not self.grid_parameters.IsSelection():
event.Skip()
return
for row in self.getSelectedParameters():
refined = self.grid_parameters.GetCellValue(row, 2)
- if refined == "": continue
+ if refined == "":
+ continue
self.applyCellChange(row, 0, refined)
# Resize the first column
self.grid_parameters.AutoSizeColumn(0)
@@ -361,8 +384,9 @@ def onPopupRenameParameters(self, event):
"""Rename parameters."""
if self.grid_parameters.IsSelection():
- dlg = wx.TextEntryDialog(self, 'New index:',
- 'Rename Selected Parameters', '')
+ dlg = wx.TextEntryDialog(
+ self, "New index:", "Rename Selected Parameters", ""
+ )
value = None
if dlg.ShowModal() == wx.ID_OK:
@@ -381,11 +405,10 @@ def onPopupRenameParameters(self, event):
for i in range(rows):
key = int(self.grid_parameters.GetRowLabelValue(i))
for j in range(cols):
- if self.grid_parameters.IsInSelection(i,j):
+ if self.grid_parameters.IsInSelection(i, j):
selpars.append(key)
break
-
for key in selpars:
if key != value:
self.fit.changeParameterIndex(key, value)
@@ -397,10 +420,9 @@ def onPopupRenameParameters(self, event):
event.Skip()
return
-
##### end of Popup menu events ###########################################
- def onApplyParameters(self, event): # wxGlade: ParametersPanel.
+ def onApplyParameters(self, event): # wxGlade: ParametersPanel.
self.fit.applyParameters()
self.mainFrame.needsSave()
event.Skip()
@@ -415,7 +437,7 @@ def getSelectedParameters(self):
for i in range(rows):
for j in range(cols):
- if self.grid_parameters.IsInSelection(i,j):
+ if self.grid_parameters.IsInSelection(i, j):
selection.append(i)
break
@@ -432,10 +454,12 @@ def fillCells(self, indices, value):
self.applyCellChange(i, j, value)
return
+
# end of class ParametersPanel
##### testing code ############################################################
if __name__ == "__main__":
+
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_FRAME_STYLE
@@ -452,17 +476,20 @@ def dummy(self):
pass
def test(self):
- '''Testing code goes here'''
+ """Testing code goes here"""
from diffpy.pdfgui.control.parameter import Parameter
- self.window.parameters = {3:Parameter(3), 17:Parameter(17), 11:Parameter(11)}
+ self.window.parameters = {
+ 3: Parameter(3),
+ 17: Parameter(17),
+ 11: Parameter(11),
+ }
self.window.parameters[3].setInitial(1)
self.window.parameters[17].setInitial(0.55)
self.window.parameters[11].setInitial(5.532)
self.window.refresh()
-
class MyApp(wx.App):
def onInit(self):
frame_1 = MyFrame(None, -1, "")
diff --git a/src/diffpy/pdfgui/gui/pdfguiglobals.py b/src/diffpy/pdfgui/gui/pdfguiglobals.py
index 17199879..f1b592c4 100644
--- a/src/diffpy/pdfgui/gui/pdfguiglobals.py
+++ b/src/diffpy/pdfgui/gui/pdfguiglobals.py
@@ -28,20 +28,19 @@
isAltered = False
# Resolve APPDATADIR base path to application data files.
-_mydir = os.path.abspath(resource_filename(__name__, ''))
-_upbasedir = os.path.normpath(_mydir + '/../../..')
-_development_mode = (
- os.path.basename(_upbasedir) == "src" and
- os.path.isfile(os.path.join(_upbasedir, "../setup.py"))
+_mydir = os.path.abspath(resource_filename(__name__, ""))
+_upbasedir = os.path.normpath(_mydir + "/../../..")
+_development_mode = os.path.basename(_upbasedir) == "src" and os.path.isfile(
+ os.path.join(_upbasedir, "../setup.py")
)
# Requirement must have egg-info. Do not use in _development_mode.
_req = Requirement.parse("diffpy.pdfgui")
-#pavol
+# pavol
# APPDATADIR = (os.path.dirname(_upbasedir) if _development_mode
# else resource_filename(_req, ""))
-#long
+# long
if _development_mode:
APPDATADIR = os.path.dirname(_mydir)
else:
@@ -50,7 +49,7 @@
APPDATADIR = os.path.abspath(APPDATADIR)
# Location of the HTML manual
-docMainFile = os.path.join(APPDATADIR, 'doc/manual/pdfgui.html')
+docMainFile = os.path.join(APPDATADIR, "doc/manual/pdfgui.html")
del _upbasedir
del _development_mode
@@ -66,7 +65,7 @@ def iconpath(iconfilename):
Return string.
"""
- rv = os.path.join(APPDATADIR, 'icons', iconfilename)
+ rv = os.path.join(APPDATADIR, "icons", iconfilename)
assert os.path.isfile(rv), "icon file does not exist"
return rv
@@ -77,6 +76,7 @@ def iconpath(iconfilename):
# debugging options:
from diffpy.pdfgui.gui import debugoptions
+
dbopts = debugoptions.DebugOptions()
# End of file
diff --git a/src/diffpy/pdfgui/gui/pdfpanel.py b/src/diffpy/pdfgui/gui/pdfpanel.py
index 9dc622cf..4e83cb76 100644
--- a/src/diffpy/pdfgui/gui/pdfpanel.py
+++ b/src/diffpy/pdfgui/gui/pdfpanel.py
@@ -17,6 +17,7 @@
from diffpy.pdfgui.gui.errorwrapper import catchObjectErrors
+
class PDFPanel(object):
"""Mix-in class for all PDF gui panels.
@@ -24,6 +25,7 @@ class PDFPanel(object):
wx.Panel. It defines methods and member variables necessary to all panels in
the PDFgui.
"""
+
def __init__(self, *args, **kwds):
self.mainFrame = None
self.treeCtrlMain = None
@@ -42,17 +44,17 @@ def refresh(self):
This method must be overloaded in the derived class or else a
NotImplementedError will be raised when this method is called.
"""
- raise NotImplementedError('refresh() must be implemented in subclass')
+ raise NotImplementedError("refresh() must be implemented in subclass")
def setToolTips(self, toolTips):
- '''Sets tooltips for controls
+ """Sets tooltips for controls
@param toolTips: dictionary of the form {'controlname' : 'tooltip'}
- '''
+ """
for (controlName, tooltip) in toolTips.items():
control = getattr(self, controlName)
if control.GetToolTip() is None:
- control.SetToolTip(wx.ToolTip(''))
+ control.SetToolTip(wx.ToolTip(""))
tt = control.GetToolTip()
tt.SetTip(tooltip)
return
diff --git a/src/diffpy/pdfgui/gui/phaseconfigurepanel.py b/src/diffpy/pdfgui/gui/phaseconfigurepanel.py
index ed4b9a5a..499f63b6 100644
--- a/src/diffpy/pdfgui/gui/phaseconfigurepanel.py
+++ b/src/diffpy/pdfgui/gui/phaseconfigurepanel.py
@@ -23,8 +23,7 @@
from diffpy.pdfgui.gui.insertrowsdialog import InsertRowsDialog
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
from diffpy.pdfgui.gui import tooltips
-from diffpy.pdfgui.gui.wxextensions.autowidthlabelsgrid import \
- AutoWidthLabelsGrid
+from diffpy.pdfgui.gui.wxextensions.autowidthlabelsgrid import AutoWidthLabelsGrid
from diffpy.pdfgui.gui.wxextensions.validators import TextValidator, FLOAT_ONLY
from diffpy.pdfgui.gui.wxextensions.textctrlutils import textCtrlAsGridCell
from diffpy.pdfgui.gui.wxextensions import wx12
@@ -33,6 +32,7 @@
from diffpy.pdfgui.control.controlerrors import TempControlSelectError
+
class PhaseConfigurePanel(wx.Panel, PDFPanel):
"""Panel for configuring a phase.
@@ -43,6 +43,7 @@ class PhaseConfigurePanel(wx.Panel, PDFPanel):
_row -- row, where rightclick occured
_col -- column, where rightclick occured
"""
+
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
# begin wxGlade: PhaseConfigurePanel.__init__
@@ -52,66 +53,104 @@ def __init__(self, *args, **kwds):
sizerMain = wx.BoxSizer(wx.VERTICAL)
- sizerPanelName = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizerPanelName = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerPanelName, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
self.labelPanelName = wx.StaticText(self, wx.ID_ANY, "Phase Configuration")
- self.labelPanelName.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
- sizerPanelName.Add(self.labelPanelName, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
-
- sizerLatticeParameters = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ self.labelPanelName.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
+ sizerPanelName.Add(
+ self.labelPanelName, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5
+ )
+
+ sizerLatticeParameters = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerLatticeParameters, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
grid_sizer_3 = wx.FlexGridSizer(2, 6, 0, 0)
sizerLatticeParameters.Add(grid_sizer_3, 1, wx.EXPAND, 0)
self.labelA = wx.StaticText(self, wx.ID_ANY, "a")
- grid_sizer_3.Add(self.labelA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlA = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelB = wx.StaticText(self, wx.ID_ANY, "b")
- grid_sizer_3.Add(self.labelB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlB = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelC = wx.StaticText(self, wx.ID_ANY, "c")
- grid_sizer_3.Add(self.labelC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlC = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelAlpha = wx.StaticText(self, wx.ID_ANY, "alpha")
- grid_sizer_3.Add(self.labelAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlAlpha = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelBeta = wx.StaticText(self, wx.ID_ANY, "beta")
- grid_sizer_3.Add(self.labelBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlBeta = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelGamma = wx.StaticText(self, wx.ID_ANY, "gamma")
- grid_sizer_3.Add(self.labelGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlGamma = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
- sizerAdditionalParameters = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizerAdditionalParameters = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerAdditionalParameters, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
grid_sizer_4 = wx.FlexGridSizer(3, 6, 0, 0)
sizerAdditionalParameters.Add(grid_sizer_4, 1, wx.EXPAND, 0)
self.labelScaleFactor = wx.StaticText(self, wx.ID_ANY, "Scale Factor")
- grid_sizer_4.Add(self.labelScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
-
- self.textCtrlScaleFactor = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
- grid_sizer_4.Add(self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
+ grid_sizer_4.Add(
+ self.labelScaleFactor,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
+ 5,
+ )
+
+ self.textCtrlScaleFactor = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
+ grid_sizer_4.Add(
+ self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0
+ )
grid_sizer_4.Add((20, 10), 0, 0, 0)
@@ -122,39 +161,66 @@ def __init__(self, *args, **kwds):
grid_sizer_4.Add((20, 10), 0, 0, 0)
self.labelDelta1 = wx.StaticText(self, wx.ID_ANY, "delta1")
- grid_sizer_4.Add(self.labelDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlDelta1 = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
+ self.textCtrlDelta1 = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
grid_sizer_4.Add(self.textCtrlDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelDelta2 = wx.StaticText(self, wx.ID_ANY, "delta2")
- grid_sizer_4.Add(self.labelDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlDelta2 = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
+ self.textCtrlDelta2 = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
grid_sizer_4.Add(self.textCtrlDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelSpdiameter = wx.StaticText(self, wx.ID_ANY, "spdiameter")
- grid_sizer_4.Add(self.labelSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
-
- self.textCtrlSpdiameter = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
- grid_sizer_4.Add(self.textCtrlSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
+ grid_sizer_4.Add(
+ self.labelSpdiameter,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
+ 5,
+ )
+
+ self.textCtrlSpdiameter = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
+ grid_sizer_4.Add(
+ self.textCtrlSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0
+ )
self.labelSratio = wx.StaticText(self, wx.ID_ANY, "sratio")
- grid_sizer_4.Add(self.labelSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlSratio = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
+ self.textCtrlSratio = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
grid_sizer_4.Add(self.textCtrlSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelRcut = wx.StaticText(self, wx.ID_ANY, "rcut")
- grid_sizer_4.Add(self.labelRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlRcut = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_4.Add(self.textCtrlRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelStepcut = wx.StaticText(self, wx.ID_ANY, "stepcut")
- grid_sizer_4.Add(self.labelStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlStepcut = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
+ self.textCtrlStepcut = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
grid_sizer_4.Add(self.textCtrlStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
sizerAtoms = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.VERTICAL)
@@ -192,9 +258,15 @@ def __init__(self, *args, **kwds):
self.Layout()
self.Bind(wx.grid.EVT_GRID_CMD_CELL_CHANGED, self.onCellChange, self.gridAtoms)
- self.Bind(wx.grid.EVT_GRID_CMD_CELL_RIGHT_CLICK, self.onCellRightClick, self.gridAtoms)
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_CELL_RIGHT_CLICK, self.onCellRightClick, self.gridAtoms
+ )
self.Bind(wx.grid.EVT_GRID_CMD_EDITOR_SHOWN, self.onEditorShown, self.gridAtoms)
- self.Bind(wx.grid.EVT_GRID_CMD_LABEL_RIGHT_CLICK, self.onLabelRightClick, self.gridAtoms)
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_LABEL_RIGHT_CLICK,
+ self.onLabelRightClick,
+ self.gridAtoms,
+ )
# end wxGlade
self.__customProperties()
@@ -211,24 +283,34 @@ def __customProperties(self):
self._focusedText = None
self._selectedCells = []
- self.lAtomConstraints = ['x','y','z',
- 'u11','u22','u33','u12','u13','u23','occ']
+ self.lAtomConstraints = [
+ "x",
+ "y",
+ "z",
+ "u11",
+ "u22",
+ "u33",
+ "u12",
+ "u13",
+ "u23",
+ "occ",
+ ]
# pdffit internal naming
self.lConstraintsMap = {
- 'textCtrlA' : 'lat(1)',
- 'textCtrlB' : 'lat(2)',
- 'textCtrlC' : 'lat(3)',
- 'textCtrlAlpha' : 'lat(4)',
- 'textCtrlBeta' : 'lat(5)',
- 'textCtrlGamma' : 'lat(6)',
- 'textCtrlScaleFactor' : 'pscale',
- 'textCtrlDelta1' : 'delta1',
- 'textCtrlDelta2' : 'delta2',
- 'textCtrlSratio' : 'sratio',
- 'textCtrlRcut' : 'rcut',
- 'textCtrlStepcut' : 'stepcut',
- 'textCtrlSpdiameter' : 'spdiameter',
- }
+ "textCtrlA": "lat(1)",
+ "textCtrlB": "lat(2)",
+ "textCtrlC": "lat(3)",
+ "textCtrlAlpha": "lat(4)",
+ "textCtrlBeta": "lat(5)",
+ "textCtrlGamma": "lat(6)",
+ "textCtrlScaleFactor": "pscale",
+ "textCtrlDelta1": "delta1",
+ "textCtrlDelta2": "delta2",
+ "textCtrlSratio": "sratio",
+ "textCtrlRcut": "rcut",
+ "textCtrlStepcut": "stepcut",
+ "textCtrlSpdiameter": "spdiameter",
+ }
# bind onSetFocus onKillFocus events to text controls
for tname in self.lConstraintsMap:
@@ -260,7 +342,6 @@ def _cache(self):
"""Cache the current structure and constraints for future comparison."""
pass
-
__this_is_first_refresh = True
def refresh(self):
@@ -295,12 +376,13 @@ def restrictConstrainedParameters(self):
if var in self.constraints:
textCtrl.SetEditable(False)
textCtrl.SetBackgroundColour(
- wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
+ )
tt = textCtrl.GetToolTip()
tt.SetTip(self.constraints[var].formula)
else:
textCtrl.SetEditable(True)
- #textCtrl.SetBackgroundColour(txtbg)
+ # textCtrl.SetBackgroundColour(txtbg)
textCtrl.SetBackgroundColour(wx.WHITE)
# Now the grid
@@ -309,12 +391,13 @@ def restrictConstrainedParameters(self):
for i in range(rows):
for j in range(1, cols):
- var = self.lAtomConstraints[j-1]
- var += '(%i)'%(i+1)
+ var = self.lAtomConstraints[j - 1]
+ var += "(%i)" % (i + 1)
if var in self.constraints:
self.gridAtoms.SetReadOnly(i, j, True)
- self.gridAtoms.SetCellBackgroundColour(i, j,
- wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ self.gridAtoms.SetCellBackgroundColour(
+ i, j, wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
+ )
else:
self.gridAtoms.SetReadOnly(i, j, False)
self.gridAtoms.SetCellBackgroundColour(i, j, wx.NullColour)
@@ -327,36 +410,37 @@ def applyTextCtrlChange(self, id, value):
id -- textctrl id
value -- new value
"""
- if self.structure is None: return
+ if self.structure is None:
+ return
try:
value = float(value)
- if id == self.textCtrlA.GetId():
- self.structure.lattice.setLatPar(a = value)
+ if id == self.textCtrlA.GetId():
+ self.structure.lattice.setLatPar(a=value)
elif id == self.textCtrlB.GetId():
- self.structure.lattice.setLatPar(b = value)
+ self.structure.lattice.setLatPar(b=value)
elif id == self.textCtrlC.GetId():
- self.structure.lattice.setLatPar(c = value)
+ self.structure.lattice.setLatPar(c=value)
elif id == self.textCtrlAlpha.GetId():
- self.structure.lattice.setLatPar(alpha = value)
+ self.structure.lattice.setLatPar(alpha=value)
elif id == self.textCtrlBeta.GetId():
- self.structure.lattice.setLatPar(beta = value)
+ self.structure.lattice.setLatPar(beta=value)
elif id == self.textCtrlGamma.GetId():
- self.structure.lattice.setLatPar(gamma = value)
+ self.structure.lattice.setLatPar(gamma=value)
elif id == self.textCtrlScaleFactor.GetId():
- self.structure.pdffit['scale'] = value
+ self.structure.pdffit["scale"] = value
elif id == self.textCtrlDelta1.GetId():
- self.structure.pdffit['delta1'] = value
+ self.structure.pdffit["delta1"] = value
elif id == self.textCtrlDelta2.GetId():
- self.structure.pdffit['delta2'] = value
+ self.structure.pdffit["delta2"] = value
elif id == self.textCtrlSratio.GetId():
- self.structure.pdffit['sratio'] = value
+ self.structure.pdffit["sratio"] = value
elif id == self.textCtrlRcut.GetId():
- self.structure.pdffit['rcut'] = value
+ self.structure.pdffit["rcut"] = value
elif id == self.textCtrlStepcut.GetId():
- self.structure.pdffit['stepcut'] = value
+ self.structure.pdffit["stepcut"] = value
elif id == self.textCtrlSpdiameter.GetId():
- self.structure.pdffit['spdiameter'] = value
+ self.structure.pdffit["spdiameter"] = value
return value
@@ -370,12 +454,14 @@ def applyCellChange(self, i, j, value):
j -- cell position
value -- new value
"""
- if not self.mainFrame or self.structure is None: return
+ if not self.mainFrame or self.structure is None:
+ return
# The element name
if j == 0:
value = value.title()
- if not is_element(value): return
+ if not is_element(value):
+ return
self.structure[i].element = value # element
return value
@@ -383,27 +469,28 @@ def applyCellChange(self, i, j, value):
# ignore the change if the value is not valid
try:
value = float(value)
- if value == "": value = 0.0
+ if value == "":
+ value = 0.0
if j == 1:
- self.structure[i].xyz[0] = value # x
+ self.structure[i].xyz[0] = value # x
elif j == 2:
- self.structure[i].xyz[1] = value # y
+ self.structure[i].xyz[1] = value # y
elif j == 3:
- self.structure[i].xyz[2] = value # z
+ self.structure[i].xyz[2] = value # z
elif j == 4:
- self.structure[i].U[0,0] = value # U(1,1)
+ self.structure[i].U[0, 0] = value # U(1,1)
elif j == 5:
- self.structure[i].U[1,1] = value # U(2,2)
+ self.structure[i].U[1, 1] = value # U(2,2)
elif j == 6:
- self.structure[i].U[2,2] = value # U(3,3)
+ self.structure[i].U[2, 2] = value # U(3,3)
elif j == 7:
- self.structure[i].U[0,1] = self.structure[i].U[1,0] = value # U(1,2)
+ self.structure[i].U[0, 1] = self.structure[i].U[1, 0] = value # U(1,2)
elif j == 8:
- self.structure[i].U[0,2] = self.structure[i].U[2,0] = value # U(1,3)
+ self.structure[i].U[0, 2] = self.structure[i].U[2, 0] = value # U(1,3)
elif j == 9:
- self.structure[i].U[1,2] = self.structure[i].U[2,1] = value # U(2,3)
+ self.structure[i].U[1, 2] = self.structure[i].U[2, 1] = value # U(2,3)
elif j == 10:
- self.structure[i].occupancy = value # occupancy
+ self.structure[i].occupancy = value # occupancy
self.mainFrame.needsSave()
return value
@@ -423,7 +510,8 @@ def onSetFocus(self, event):
def onKillFocus(self, event):
"""Check value of TextCtrl and update structure if necessary."""
- if not self.mainFrame: return
+ if not self.mainFrame:
+ return
textctrl = event.GetEventObject()
value = textctrl.GetValue()
if value != self._focusedText:
@@ -436,7 +524,8 @@ def onKillFocus(self, event):
def onSelectedPairs(self, event):
"""Check to see if the value of the selected pairs is valid."""
- if not self.mainFrame: return
+ if not self.mainFrame:
+ return
value = self.textCtrlIncludedPairs.GetValue()
self.structure.setSelectedPairs(value)
value = self.structure.getSelectedPairs()
@@ -444,9 +533,8 @@ def onSelectedPairs(self, event):
event.Skip()
return
-
# Grid Events
- def onLabelRightClick(self, event): # wxGlade: PhaseConfigurePanel.
+ def onLabelRightClick(self, event): # wxGlade: PhaseConfigurePanel.
"""Bring up right-click menu."""
if self.structure is not None:
dx = dy = 0
@@ -457,12 +545,15 @@ def onLabelRightClick(self, event): # wxGlade: PhaseConfigurePanel.
+ def onCellRightClick(self, event): # wxGlade: PhaseConfigurePanel.
"""Bring up right-click menu."""
self._row = event.GetRow()
self._col = event.GetCol()
@@ -472,28 +563,28 @@ def onCellRightClick(self, event): # wxGlade: PhaseConfigurePanel.
+ def onEditorShown(self, event): # wxGlade: PhaseConfigurePanel.
"""Capture the focused text when the grid editor is shown."""
i = event.GetRow()
j = event.GetCol()
- self._focusedText = self.gridAtoms.GetCellValue(i,j)
+ self._focusedText = self.gridAtoms.GetCellValue(i, j)
# self._selectedCells = gridutils.getSelectedCells(self.gridAtoms)
- #TODO: temporary show the error message for control-select.
+ # TODO: temporary show the error message for control-select.
try:
self._selectedCells = gridutils.getSelectedCells(self.gridAtoms)
except TypeError:
raise TempControlSelectError("controlselecterror")
return
- def onCellChange(self, event): # wxGlade: PhaseConfigurePanel.
+ def onCellChange(self, event): # wxGlade: PhaseConfigurePanel.
"""Update focused and selected text when a cell changes."""
# NOTE: be careful with refresh(). It calls Grid.AutoSizeColumns, which
# creates a EVT_GRID_CMD_CELL_CHANGED event, which causes a recursion
@@ -501,11 +592,11 @@ def onCellChange(self, event): # wxGlade: PhaseConfigurePanel.
i = event.GetRow()
j = event.GetCol()
- value = self.gridAtoms.GetCellValue(i,j)
- while (i,j) in self._selectedCells:
- self._selectedCells.remove((i,j))
+ value = self.gridAtoms.GetCellValue(i, j)
+ while (i, j) in self._selectedCells:
+ self._selectedCells.remove((i, j))
# We need the edited cell to be at the front of the list
- self._selectedCells.insert(0,(i,j))
+ self._selectedCells.insert(0, (i, j))
self.fillCells(value)
self._focusedText = None
return
@@ -518,17 +609,18 @@ def fillCells(self, value):
This uses the member variable _selectedCells, a list of (i,j) tuples for
the selected cells.
"""
- for (i,j) in self._selectedCells:
- if not self.gridAtoms.IsReadOnly(i,j):
+ for (i, j) in self._selectedCells:
+ if not self.gridAtoms.IsReadOnly(i, j):
# Get the last valid text from the cell. For the cell that triggered
# this method, that is the _focusedText, for other cells it is the
# value returned by GetCellValue
- oldvalue = self._focusedText or self.gridAtoms.GetCellValue(i,j)
+ oldvalue = self._focusedText or self.gridAtoms.GetCellValue(i, j)
self._focusedText = None
- newvalue = self.applyCellChange(i,j, value)
- #print i, j, value, oldvalue, newvalue
- if newvalue is None: newvalue = oldvalue
- self.gridAtoms.SetCellValue(i,j,str(newvalue))
+ newvalue = self.applyCellChange(i, j, value)
+ # print i, j, value, oldvalue, newvalue
+ if newvalue is None:
+ newvalue = oldvalue
+ self.gridAtoms.SetCellValue(i, j, str(newvalue))
gridutils.quickResizeColumns(self.gridAtoms, self._selectedCells)
return
@@ -542,12 +634,11 @@ def onKey(self, event):
if event.ControlDown() and key == 65:
rows = self.gridAtoms.GetNumberRows()
cols = self.gridAtoms.GetNumberCols()
- self.gridAtoms.SelectBlock(0,0,rows,cols)
+ self.gridAtoms.SelectBlock(0, 0, rows, cols)
# context menu key
elif key == wx.WXK_MENU:
- self.popupMenu(self.gridAtoms,
- event.GetPosition().x, event.GetPosition().y)
+ self.popupMenu(self.gridAtoms, event.GetPosition().x, event.GetPosition().y)
# Vim-like search for atom selection
elif key == 47:
@@ -575,7 +666,7 @@ def onKey(self, event):
indices = gridutils.getSelectionRows(self.gridAtoms)
pos = 0
if indices:
- pos = 1+indices[-1]
+ pos = 1 + indices[-1]
elif self.structure:
pos = len(self.structure)
# insert "rows" atoms into the structure
@@ -634,14 +725,14 @@ def popupMenu(self, window, x, y):
# Disable some items if there are no atoms selected
indices = gridutils.getSelectionRows(self.gridAtoms)
if not indices:
- menu.Enable(self.deleteID, False);
- menu.Enable(self.spaceGroupID, False);
+ menu.Enable(self.deleteID, False)
+ menu.Enable(self.spaceGroupID, False)
# Disable some items if there is no structure
if self.structure is None or len(self.structure) == 0:
- menu.Enable(self.deleteID, False);
- menu.Enable(self.supercellID, False);
- menu.Enable(self.spaceGroupID, False);
+ menu.Enable(self.deleteID, False)
+ menu.Enable(self.supercellID, False)
+ menu.Enable(self.spaceGroupID, False)
# Check for copy/paste
if not phasepanelutils.canCopySelectedCells(self):
@@ -651,7 +742,7 @@ def popupMenu(self, window, x, y):
# Popup the menu. If an item is selected then its handler
# will be called before PopupMenu returns.
- window.PopupMenu(menu, wx.Point(x,y))
+ window.PopupMenu(menu, wx.Point(x, y))
menu.Destroy()
return
@@ -664,7 +755,7 @@ def onPopupInsert(self, event):
if len(self.structure) == 0:
self._row = 0
- elif (dlg.radio_box_where.GetSelection() == 1): # if selected "below"
+ elif dlg.radio_box_where.GetSelection() == 1: # if selected "below"
self._row += 1
# insert "rows" atoms into the structure
@@ -676,7 +767,7 @@ def onPopupInsert(self, event):
# Highlight the elements of the new rows so that they can be
# changed by the user.
self.gridAtoms.SetFocus()
- self.gridAtoms.SelectBlock(self._row,0,self._row+len(atoms)-1,0)
+ self.gridAtoms.SelectBlock(self._row, 0, self._row + len(atoms) - 1, 0)
self.gridAtoms.SetGridCursor(self._row, 0)
dlg.Destroy()
@@ -692,8 +783,7 @@ def onPopupDelete(self, event):
return
def onPopupSelect(self, event):
- """Limit cell selection to specified atom selection string.
- """
+ """Limit cell selection to specified atom selection string."""
phasepanelutils.showSelectAtomsDialog(self)
return
@@ -710,6 +800,7 @@ def onPopupPaste(self, event):
def onPopupSupercell(self, event):
"""Create a supercell with the supercell dialog."""
from diffpy.pdfgui.gui.supercelldialog import SupercellDialog
+
if self.structure is not None:
dlg = SupercellDialog(self)
if dlg.ShowModal() == wx.ID_OK:
@@ -723,6 +814,7 @@ def onPopupSupercell(self, event):
def onPopupSpaceGroup(self, event):
"""Create a supercell with the supercell dialog."""
from diffpy.pdfgui.gui.sgstructuredialog import SGStructureDialog
+
if self.structure is not None:
indices = gridutils.getSelectionRows(self.gridAtoms)
@@ -739,14 +831,14 @@ def onPopupSpaceGroup(self, event):
dlg.Destroy()
return
+
# end of class PhaseConfigurePanel
# Local helpers --------------------------------------------------------------
+
def _defaultNewAtom():
- """Create new atom instance with non-zero initial U.
- """
+ """Create new atom instance with non-zero initial U."""
uii = 0.003
- rv = Atom("C", [0.0, 0.0, 0.0],
- U=[[uii, 0, 0], [0, uii, 0], [0, 0, uii]])
+ rv = Atom("C", [0.0, 0.0, 0.0], U=[[uii, 0, 0], [0, uii, 0], [0, 0, uii]])
return rv
diff --git a/src/diffpy/pdfgui/gui/phaseconstraintspanel.py b/src/diffpy/pdfgui/gui/phaseconstraintspanel.py
index b0486a52..26f1f347 100644
--- a/src/diffpy/pdfgui/gui/phaseconstraintspanel.py
+++ b/src/diffpy/pdfgui/gui/phaseconstraintspanel.py
@@ -23,8 +23,7 @@
from diffpy.pdfgui.control.controlerrors import ControlValueError
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
from diffpy.pdfgui.gui import tooltips
-from diffpy.pdfgui.gui.wxextensions.autowidthlabelsgrid import \
- AutoWidthLabelsGrid
+from diffpy.pdfgui.gui.wxextensions.autowidthlabelsgrid import AutoWidthLabelsGrid
from diffpy.pdfgui.gui.wxextensions.textctrlutils import textCtrlAsGridCell
from diffpy.pdfgui.gui.sgconstraindialog import SGConstrainDialog
from diffpy.pdfgui.gui import phasepanelutils
@@ -41,66 +40,104 @@ def __init__(self, *args, **kwds):
sizerMain = wx.BoxSizer(wx.VERTICAL)
- sizerPanelName = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizerPanelName = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerPanelName, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
self.labelPanelName = wx.StaticText(self, wx.ID_ANY, "Phase Constraints")
- self.labelPanelName.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
- sizerPanelName.Add(self.labelPanelName, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
-
- sizerLatticeParameters = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ self.labelPanelName.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
+ sizerPanelName.Add(
+ self.labelPanelName, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5
+ )
+
+ sizerLatticeParameters = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerLatticeParameters, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
grid_sizer_3 = wx.FlexGridSizer(2, 6, 0, 0)
sizerLatticeParameters.Add(grid_sizer_3, 1, wx.EXPAND, 0)
self.labelA = wx.StaticText(self, wx.ID_ANY, "a")
- grid_sizer_3.Add(self.labelA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlA = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelB = wx.StaticText(self, wx.ID_ANY, "b")
- grid_sizer_3.Add(self.labelB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlB = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelC = wx.StaticText(self, wx.ID_ANY, "c")
- grid_sizer_3.Add(self.labelC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlC = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelAlpha = wx.StaticText(self, wx.ID_ANY, "alpha")
- grid_sizer_3.Add(self.labelAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlAlpha = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelBeta = wx.StaticText(self, wx.ID_ANY, "beta")
- grid_sizer_3.Add(self.labelBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlBeta = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelGamma = wx.StaticText(self, wx.ID_ANY, "gamma")
- grid_sizer_3.Add(self.labelGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlGamma = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
grid_sizer_3.Add(self.textCtrlGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
- sizerAdditionalParameters = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizerAdditionalParameters = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerAdditionalParameters, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
grid_sizer_4 = wx.FlexGridSizer(3, 6, 0, 0)
sizerAdditionalParameters.Add(grid_sizer_4, 1, wx.EXPAND, 0)
self.labelScaleFactor = wx.StaticText(self, wx.ID_ANY, "Scale Factor")
- grid_sizer_4.Add(self.labelScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
-
- self.textCtrlScaleFactor = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
- grid_sizer_4.Add(self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
+ grid_sizer_4.Add(
+ self.labelScaleFactor,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
+ 5,
+ )
+
+ self.textCtrlScaleFactor = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
+ grid_sizer_4.Add(
+ self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0
+ )
grid_sizer_4.Add((20, 10), 0, 0, 0)
@@ -111,39 +148,68 @@ def __init__(self, *args, **kwds):
grid_sizer_4.Add((20, 10), 0, 0, 0)
self.labelDelta1 = wx.StaticText(self, wx.ID_ANY, "delta1")
- grid_sizer_4.Add(self.labelDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlDelta1 = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
+ self.textCtrlDelta1 = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
grid_sizer_4.Add(self.textCtrlDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelDelta2 = wx.StaticText(self, wx.ID_ANY, "delta2")
- grid_sizer_4.Add(self.labelDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlDelta2 = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
+ self.textCtrlDelta2 = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
grid_sizer_4.Add(self.textCtrlDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelSpdiameter = wx.StaticText(self, wx.ID_ANY, "spdiameter")
- grid_sizer_4.Add(self.labelSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
-
- self.textCtrlSpdiameter = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
- grid_sizer_4.Add(self.textCtrlSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
+ grid_sizer_4.Add(
+ self.labelSpdiameter,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
+ 5,
+ )
+
+ self.textCtrlSpdiameter = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
+ grid_sizer_4.Add(
+ self.textCtrlSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0
+ )
self.labelSratio = wx.StaticText(self, wx.ID_ANY, "sratio")
- grid_sizer_4.Add(self.labelSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlSratio = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER)
+ self.textCtrlSratio = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER
+ )
grid_sizer_4.Add(self.textCtrlSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelRcut = wx.StaticText(self, wx.ID_ANY, "rcut")
- grid_sizer_4.Add(self.labelRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlRcut = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER | wx.TE_READONLY)
+ self.textCtrlRcut = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER | wx.TE_READONLY
+ )
grid_sizer_4.Add(self.textCtrlRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelStepcut = wx.StaticText(self, wx.ID_ANY, "stepcut")
- grid_sizer_4.Add(self.labelStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
- self.textCtrlStepcut = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER | wx.TE_READONLY)
+ self.textCtrlStepcut = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER | wx.TE_READONLY
+ )
grid_sizer_4.Add(self.textCtrlStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
sizerAtoms = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.VERTICAL)
@@ -155,7 +221,9 @@ def __init__(self, *args, **kwds):
self.labelIncludedPairs = wx.StaticText(self, wx.ID_ANY, "Included Pairs")
sizer_1.Add(self.labelIncludedPairs, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
- self.textCtrlIncludedPairs = wx.TextCtrl(self, wx.ID_ANY, "all-all", style=wx.TE_READONLY)
+ self.textCtrlIncludedPairs = wx.TextCtrl(
+ self, wx.ID_ANY, "all-all", style=wx.TE_READONLY
+ )
self.textCtrlIncludedPairs.SetMinSize((240, 25))
sizer_1.Add(self.textCtrlIncludedPairs, 0, wx.ALL, 5)
@@ -181,9 +249,15 @@ def __init__(self, *args, **kwds):
self.Layout()
self.Bind(wx.grid.EVT_GRID_CMD_CELL_CHANGED, self.onCellChange, self.gridAtoms)
- self.Bind(wx.grid.EVT_GRID_CMD_CELL_RIGHT_CLICK, self.onCellRightClick, self.gridAtoms)
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_CELL_RIGHT_CLICK, self.onCellRightClick, self.gridAtoms
+ )
self.Bind(wx.grid.EVT_GRID_CMD_EDITOR_SHOWN, self.onEditorShown, self.gridAtoms)
- self.Bind(wx.grid.EVT_GRID_CMD_LABEL_RIGHT_CLICK, self.onLabelRightClick, self.gridAtoms)
+ self.Bind(
+ wx.grid.EVT_GRID_CMD_LABEL_RIGHT_CLICK,
+ self.onLabelRightClick,
+ self.gridAtoms,
+ )
# end wxGlade
self.__customProperties()
@@ -195,10 +269,19 @@ def __customProperties(self):
self.structure = None
self.constraints = {}
self.results = None
- self._textctrls = ['textCtrlA', 'textCtrlB', 'textCtrlC',
- 'textCtrlAlpha', 'textCtrlBeta', 'textCtrlGamma',
- 'textCtrlScaleFactor', 'textCtrlDelta1', 'textCtrlDelta2',
- 'textCtrlSratio', 'textCtrlSpdiameter']
+ self._textctrls = [
+ "textCtrlA",
+ "textCtrlB",
+ "textCtrlC",
+ "textCtrlAlpha",
+ "textCtrlBeta",
+ "textCtrlGamma",
+ "textCtrlScaleFactor",
+ "textCtrlDelta1",
+ "textCtrlDelta2",
+ "textCtrlSratio",
+ "textCtrlSpdiameter",
+ ]
self._row = 0
self._col = 0
self._focusedText = None
@@ -210,12 +293,32 @@ def __customProperties(self):
self.__dict__[widget].Bind(wx.EVT_KEY_DOWN, self.onTextCtrlKey)
# set up grid
- self.lAtomConstraints = ['x','y','z',
- 'u11','u22','u33','u12','u13','u23','occ']
+ self.lAtomConstraints = [
+ "x",
+ "y",
+ "z",
+ "u11",
+ "u22",
+ "u33",
+ "u12",
+ "u13",
+ "u23",
+ "occ",
+ ]
# pdffit internal naming
self.lConstraints = [
- 'lat(1)', 'lat(2)', 'lat(3)', 'lat(4)', 'lat(5)', 'lat(6)',
- 'pscale', 'delta1', 'delta2', 'sratio', 'spdiameter']
+ "lat(1)",
+ "lat(2)",
+ "lat(3)",
+ "lat(4)",
+ "lat(5)",
+ "lat(6)",
+ "pscale",
+ "delta1",
+ "delta2",
+ "sratio",
+ "spdiameter",
+ ]
textCtrlIds = [getattr(self, n).GetId() for n in self._textctrls]
self._id2varname = dict(zip(textCtrlIds, self.lConstraints))
@@ -268,9 +371,9 @@ def refresh(self):
self.gridAtoms.BeginBatch()
# make sure grid has correct number of rows
if natoms > nrows:
- self.gridAtoms.InsertRows(numRows = natoms - nrows)
+ self.gridAtoms.InsertRows(numRows=natoms - nrows)
elif natoms < nrows:
- self.gridAtoms.DeleteRows(numRows = nrows - natoms)
+ self.gridAtoms.DeleteRows(numRows=nrows - natoms)
# start with clean grid
self.gridAtoms.ClearGrid()
@@ -280,22 +383,26 @@ def refresh(self):
self.gridAtoms.SetCellValue(row, 0, atom.element)
# update constraints
- bareAtomVarColumn = dict( zip(self.lAtomConstraints,
- range(1, 1 + len(self.lAtomConstraints))) )
- avpat = re.compile(r'(\w+)\((\d+)\)$')
+ bareAtomVarColumn = dict(
+ zip(self.lAtomConstraints, range(1, 1 + len(self.lAtomConstraints)))
+ )
+ avpat = re.compile(r"(\w+)\((\d+)\)$")
for var, con in self.constraints.items():
m = avpat.match(var)
- if not m: continue
+ if not m:
+ continue
barevar = m.group(1)
- if not barevar in bareAtomVarColumn: continue
+ if not barevar in bareAtomVarColumn:
+ continue
column = bareAtomVarColumn[barevar]
row = int(m.group(2)) - 1
if not 0 <= row < natoms:
emsg = "Invalid variable index for %r" % var
raise ControlValueError(emsg)
self.gridAtoms.SetCellValue(row, column, con.formula)
- barevar = re.sub(r'\(\d+\)$', '', var)
- if not barevar in bareAtomVarColumn: continue
+ barevar = re.sub(r"\(\d+\)$", "", var)
+ if not barevar in bareAtomVarColumn:
+ continue
self.gridAtoms.AutosizeLabels()
self.gridAtoms.AutoSizeColumns()
@@ -306,7 +413,7 @@ def refresh(self):
return
def refreshTextCtrls(self):
- """Refreshes the TextCtrls. """
+ """Refreshes the TextCtrls."""
for widget, var in zip(self._textctrls, self.lConstraints):
wobj = getattr(self, widget)
@@ -320,7 +427,6 @@ def refreshTextCtrls(self):
self.textCtrlIncludedPairs.SetValue(pairs)
return
-
def applyTextCtrlChange(self, id, value):
"""Update a structure according to a change in a TextCtrl.
@@ -348,7 +454,7 @@ def applyCellChange(self, i, j, value):
somehow invalid.
"""
self.mainFrame.needsSave()
- key = self.lAtomConstraints[j-1] + '({})'.format(i + 1)
+ key = self.lAtomConstraints[j - 1] + "({})".format(i + 1)
formula = value.strip()
if formula != "":
self.constraints[key] = Constraint(formula)
@@ -358,7 +464,6 @@ def applyCellChange(self, i, j, value):
return ""
return
-
##########################################################################
# Event Handlers
@@ -372,7 +477,8 @@ def onSetFocus(self, event):
def onKillFocus(self, event):
"""Check value of TextCtrl and update structure if necessary."""
event.Skip()
- if not self.mainFrame: return
+ if not self.mainFrame:
+ return
textctrl = event.GetEventObject()
value = textctrl.GetValue()
if value != self._focusedText:
@@ -383,7 +489,9 @@ def onKillFocus(self, event):
return
# Grid Events
- def onLabelRightClick(self, event): # wxGlade: PhaseConstraintsPanel.
+ def onLabelRightClick(
+ self, event
+ ): # wxGlade: PhaseConstraintsPanel.
"""Bring up right-click menu."""
if self.structure is not None:
dx = dy = 0
@@ -394,12 +502,15 @@ def onLabelRightClick(self, event): # wxGlade: PhaseConstraintsPanel.
+ def onCellRightClick(self, event): # wxGlade: PhaseConstraintsPanel.
"""Bring up right-click menu."""
self._row = event.GetRow()
self._col = event.GetCol()
@@ -409,23 +520,23 @@ def onCellRightClick(self, event): # wxGlade: PhaseConstraintsPanel.
+ def onEditorShown(self, event): # wxGlade: PhaseConstraintsPanel.
"""Capture the focused text when the grid editor is shown."""
i = event.GetRow()
j = event.GetCol()
- self._focusedText = self.gridAtoms.GetCellValue(i,j)
+ self._focusedText = self.gridAtoms.GetCellValue(i, j)
self._selectedCells = gridutils.getSelectedCells(self.gridAtoms)
return
- def onCellChange(self, event): # wxGlade: PhaseConstraintsPanel.
+ def onCellChange(self, event): # wxGlade: PhaseConstraintsPanel.
"""Update focused and selected text when a cell changes."""
# NOTE: be careful with refresh(). It calls Grid.AutoSizeColumns, which
# creates a EVT_GRID_CMD_CELL_CHANGED event, which causes a recursion
@@ -433,11 +544,11 @@ def onCellChange(self, event): # wxGlade: PhaseConstraintsPanel.
i = event.GetRow()
j = event.GetCol()
- value = self.gridAtoms.GetCellValue(i,j)
- while (i,j) in self._selectedCells:
- self._selectedCells.remove((i,j))
+ value = self.gridAtoms.GetCellValue(i, j)
+ while (i, j) in self._selectedCells:
+ self._selectedCells.remove((i, j))
# We need the edited cell to be at the front of the list
- self._selectedCells.insert(0,(i,j))
+ self._selectedCells.insert(0, (i, j))
self.fillCells(value)
self._focusedText = None
return
@@ -450,30 +561,29 @@ def fillCells(self, value):
This uses the member variable _selectedCells, a list of (i,j) tuples for
the selected cells.
"""
- for (i,j) in self._selectedCells:
- if not self.gridAtoms.IsReadOnly(i,j):
+ for (i, j) in self._selectedCells:
+ if not self.gridAtoms.IsReadOnly(i, j):
# Get the last valid text from the cell. For the cell that triggered
# this method, that is the _focusedText, for other cells it is the
# value returned by GetCellValue
oldvalue = self._focusedText
if oldvalue is None:
- oldvalue = self.gridAtoms.GetCellValue(i,j)
+ oldvalue = self.gridAtoms.GetCellValue(i, j)
self._focusedText = None
- newvalue = self.applyCellChange(i,j, value)
- #print i, j, value, oldvalue, newvalue
+ newvalue = self.applyCellChange(i, j, value)
+ # print i, j, value, oldvalue, newvalue
if newvalue is None:
# Get out of here. If the value is invalid, it won't be valid
# for any cells.
newvalue = oldvalue
- self.gridAtoms.SetCellValue(i,j,str(newvalue))
+ self.gridAtoms.SetCellValue(i, j, str(newvalue))
break
else:
- self.gridAtoms.SetCellValue(i,j,str(newvalue))
+ self.gridAtoms.SetCellValue(i, j, str(newvalue))
gridutils.quickResizeColumns(self.gridAtoms, self._selectedCells)
return
-
def onKey(self, event):
"""Catch key events in the panel."""
key = event.GetKeyCode()
@@ -482,12 +592,11 @@ def onKey(self, event):
if event.ControlDown() and key == 65:
rows = self.gridAtoms.GetNumberRows()
cols = self.gridAtoms.GetNumberCols()
- self.gridAtoms.SelectBlock(0,0,rows,cols)
+ self.gridAtoms.SelectBlock(0, 0, rows, cols)
# context menu key
elif key == wx.WXK_MENU:
- self.popupMenu(self.gridAtoms,
- event.GetPosition().x, event.GetPosition().y)
+ self.popupMenu(self.gridAtoms, event.GetPosition().x, event.GetPosition().y)
# Vim-like search for atom selection
elif key == 47:
@@ -501,12 +610,12 @@ def onKey(self, event):
# Can't get these to work. Maybe later.
## Copy - Ctrl+C / Ctrl+Insert
- #if event.ControlDown() and (key == 67 or key == wx.WXK_INSERT):
+ # if event.ControlDown() and (key == 67 or key == wx.WXK_INSERT):
# if phasepanelutils.canCopySelectedCells(self):
# phasepanelutils.copySelectedCells(self)
## Paste - Ctrl+V / Shift+Insert
- #if (event.ControlDown() and key == 86) or\
+ # if (event.ControlDown() and key == 86) or\
# (event.ShiftDown() and key == wx.WXK_INSERT):
# if phasepanelutils.canPasteIntoCells(self):
# phasepanelutils.pasteIntoCells(self)
@@ -550,7 +659,7 @@ def popupMenu(self, window, x, y):
# Disable some items if there are no atoms selected
indices = gridutils.getSelectionRows(self.gridAtoms)
if not indices:
- menu.Enable(self.spaceGroupID, False);
+ menu.Enable(self.spaceGroupID, False)
# Check for copy/paste
if not phasepanelutils.canCopySelectedCells(self):
@@ -560,7 +669,7 @@ def popupMenu(self, window, x, y):
# Popup the menu. If an item is selected then its handler
# will be called before PopupMenu returns.
- window.PopupMenu(menu, wx.Point(x,y))
+ window.PopupMenu(menu, wx.Point(x, y))
menu.Destroy()
return
@@ -579,16 +688,16 @@ def onPopupSpaceGroup(self, event):
offset = dlg.getOffset()
posflag = dlg.getPosFlag()
tempflag = dlg.getTempFlag()
- self.structure.applySymmetryConstraints(spcgrp,
- indices, posflag, tempflag, offset)
+ self.structure.applySymmetryConstraints(
+ spcgrp, indices, posflag, tempflag, offset
+ )
self.refresh()
dlg.Destroy()
self.mainFrame.needsSave()
return
def onPopupSelect(self, event):
- """Limit cell selection to specified atom selection string.
- """
+ """Limit cell selection to specified atom selection string."""
phasepanelutils.showSelectAtomsDialog(self)
return
@@ -602,4 +711,5 @@ def onPopupPaste(self, event):
phasepanelutils.pasteIntoCells(self)
return
+
# end of class PhaseConstraintsPanel
diff --git a/src/diffpy/pdfgui/gui/phasenotebookpanel.py b/src/diffpy/pdfgui/gui/phasenotebookpanel.py
index fa6de8e5..9c303135 100644
--- a/src/diffpy/pdfgui/gui/phasenotebookpanel.py
+++ b/src/diffpy/pdfgui/gui/phasenotebookpanel.py
@@ -30,50 +30,56 @@
from diffpy.pdfgui.gui.phaseresultspanel import PhaseResultsPanel
-
class PhaseNotebookPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
kwds["style"] = wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
self.notebook_phase = wx.Notebook(self, -1, style=0)
- self.notebook_phase_pane_Configure = PhaseConfigurePanel(self.notebook_phase, -1)
- self.notebook_phase_pane_Constraints = PhaseConstraintsPanel(self.notebook_phase, -1)
- self.notebook_phase_pane_Results = PhaseResultsPanel(self.notebook_phase, -1)
+ self.notebook_phase_pane_Configure = PhaseConfigurePanel(
+ self.notebook_phase, -1
+ )
+ self.notebook_phase_pane_Constraints = PhaseConstraintsPanel(
+ self.notebook_phase, -1
+ )
+ self.notebook_phase_pane_Results = PhaseResultsPanel(self.notebook_phase, -1)
self.__set_properties()
self.__do_layout()
- self.notebook_phase.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onNotebookPageChanged )
- self.notebook_phase.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.onNotebookPageChanging )
+ self.notebook_phase.Bind(
+ wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onNotebookPageChanged
+ )
+ self.notebook_phase.Bind(
+ wx.EVT_NOTEBOOK_PAGE_CHANGING, self.onNotebookPageChanging
+ )
self.configuration = None
- self.constraints = {}
- self.results = None
- self.mainFrame = None
- self.focusedId = 0
-
+ self.constraints = {}
+ self.results = None
+ self.mainFrame = None
+ self.focusedId = 0
def __set_properties(self):
pass
-
def __do_layout(self):
sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
- self.notebook_phase.AddPage(self.notebook_phase_pane_Configure, "Configure")
+ self.notebook_phase.AddPage(self.notebook_phase_pane_Configure, "Configure")
self.notebook_phase.AddPage(self.notebook_phase_pane_Constraints, "Constraints")
- self.notebook_phase.AddPage(self.notebook_phase_pane_Results, "Results")
+ self.notebook_phase.AddPage(self.notebook_phase_pane_Results, "Results")
sizer_1.Add(self.notebook_phase, 1, wx.EXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
sizer_1.SetSizeHints(self)
-
def refresh(self):
"""Refreshes the currently shown panel."""
- if self.mainFrame.quitting: return
- if self.focusedId == -1: return
+ if self.mainFrame.quitting:
+ return
+ if self.focusedId == -1:
+ return
panel = self.notebook_phase.GetPage(self.focusedId)
@@ -102,7 +108,7 @@ def onNotebookPageChanged(self, event):
return
# Overloaded from Panel.
- def Enable(self, enable = True):
+ def Enable(self, enable=True):
"""Keep the notebook enabled, just not the panels."""
self.notebook_phase_pane_Configure.Enable(enable)
self.notebook_phase_pane_Constraints.Enable(enable)
diff --git a/src/diffpy/pdfgui/gui/phasepanelutils.py b/src/diffpy/pdfgui/gui/phasepanelutils.py
index 9f79327a..00d4d941 100644
--- a/src/diffpy/pdfgui/gui/phasepanelutils.py
+++ b/src/diffpy/pdfgui/gui/phasepanelutils.py
@@ -22,15 +22,17 @@
clipcells = []
# String describing what atoms should be selected.
-selected_atoms = ''
+selected_atoms = ""
+
def float2str(x):
"""compact string representation of float"""
s = "%g" % x
- if s.find('.') == -1 and s.find('e') == -1:
+ if s.find(".") == -1 and s.find("e") == -1:
s = s + ".0"
return s
+
def refreshTextCtrls(panel):
"""Refreshes the TextCtrls on the panel.
@@ -77,22 +79,18 @@ def refreshTextCtrls(panel):
panel.textCtrlAlpha.SetValue(float2str(panel.structure.lattice.alpha))
panel.textCtrlBeta.SetValue(float2str(panel.structure.lattice.beta))
panel.textCtrlGamma.SetValue(float2str(panel.structure.lattice.gamma))
- panel.textCtrlScaleFactor.SetValue(
- float2str(panel.structure.pdffit['scale']))
- panel.textCtrlDelta1.SetValue(
- float2str(panel.structure.pdffit['delta1']))
- panel.textCtrlDelta2.SetValue(
- float2str(panel.structure.pdffit['delta2']))
- panel.textCtrlSratio.SetValue(
- float2str(panel.structure.pdffit['sratio']))
- panel.textCtrlRcut.SetValue(
- float2str(panel.structure.pdffit['rcut']))
- panel.textCtrlStepcut.SetValue(
- float2str(panel.structure.pdffit['stepcut']))
+ panel.textCtrlScaleFactor.SetValue(float2str(panel.structure.pdffit["scale"]))
+ panel.textCtrlDelta1.SetValue(float2str(panel.structure.pdffit["delta1"]))
+ panel.textCtrlDelta2.SetValue(float2str(panel.structure.pdffit["delta2"]))
+ panel.textCtrlSratio.SetValue(float2str(panel.structure.pdffit["sratio"]))
+ panel.textCtrlRcut.SetValue(float2str(panel.structure.pdffit["rcut"]))
+ panel.textCtrlStepcut.SetValue(float2str(panel.structure.pdffit["stepcut"]))
panel.textCtrlSpdiameter.SetValue(
- float2str(panel.structure.pdffit['spdiameter']))
+ float2str(panel.structure.pdffit["spdiameter"])
+ )
return
+
def refreshGrid(panel):
"""Refreshes grid on the panel.
@@ -105,7 +103,7 @@ def refreshGrid(panel):
# remove all rows from grid
panel.gridAtoms.BeginBatch()
if panel.gridAtoms.GetNumberRows() != 0:
- panel.gridAtoms.DeleteRows( numRows = panel.gridAtoms.GetNumberRows() )
+ panel.gridAtoms.DeleteRows(numRows=panel.gridAtoms.GetNumberRows())
panel.gridAtoms.EndBatch()
else:
@@ -129,22 +127,22 @@ def refreshGrid(panel):
natoms = len(panel.structure)
nrows = panel.gridAtoms.GetNumberRows()
if natoms > nrows:
- panel.gridAtoms.InsertRows(numRows = natoms - nrows)
+ panel.gridAtoms.InsertRows(numRows=natoms - nrows)
elif natoms < nrows:
- panel.gridAtoms.DeleteRows(numRows = nrows - natoms)
+ panel.gridAtoms.DeleteRows(numRows=nrows - natoms)
panel.gridAtoms.ClearGrid()
for i, atom in enumerate(panel.structure):
- panel.gridAtoms.SetCellValue(i,0, str(atom.element)) # element
- panel.gridAtoms.SetCellValue(i,1, float2str(atom.xyz[0])) # x
- panel.gridAtoms.SetCellValue(i,2, float2str(atom.xyz[1])) # y
- panel.gridAtoms.SetCellValue(i,3, float2str(atom.xyz[2])) # z
- panel.gridAtoms.SetCellValue(i,4, float2str(atom.U[0,0])) # U(1,1)
- panel.gridAtoms.SetCellValue(i,5, float2str(atom.U[1,1])) # U(2,2)
- panel.gridAtoms.SetCellValue(i,6, float2str(atom.U[2,2])) # U(3,3)
- panel.gridAtoms.SetCellValue(i,7, float2str(atom.U[0,1])) # U(1,2)
- panel.gridAtoms.SetCellValue(i,8, float2str(atom.U[0,2])) # U(1,3)
- panel.gridAtoms.SetCellValue(i,9, float2str(atom.U[1,2])) # U(2,3)
- panel.gridAtoms.SetCellValue(i,10,float2str(atom.occupancy)) # occupancy
+ panel.gridAtoms.SetCellValue(i, 0, str(atom.element)) # element
+ panel.gridAtoms.SetCellValue(i, 1, float2str(atom.xyz[0])) # x
+ panel.gridAtoms.SetCellValue(i, 2, float2str(atom.xyz[1])) # y
+ panel.gridAtoms.SetCellValue(i, 3, float2str(atom.xyz[2])) # z
+ panel.gridAtoms.SetCellValue(i, 4, float2str(atom.U[0, 0])) # U(1,1)
+ panel.gridAtoms.SetCellValue(i, 5, float2str(atom.U[1, 1])) # U(2,2)
+ panel.gridAtoms.SetCellValue(i, 6, float2str(atom.U[2, 2])) # U(3,3)
+ panel.gridAtoms.SetCellValue(i, 7, float2str(atom.U[0, 1])) # U(1,2)
+ panel.gridAtoms.SetCellValue(i, 8, float2str(atom.U[0, 2])) # U(1,3)
+ panel.gridAtoms.SetCellValue(i, 9, float2str(atom.U[1, 2])) # U(2,3)
+ panel.gridAtoms.SetCellValue(i, 10, float2str(atom.occupancy)) # occupancy
panel.gridAtoms.AutosizeLabels()
panel.gridAtoms.AutoSizeColumns()
@@ -153,8 +151,10 @@ def refreshGrid(panel):
panel.gridAtoms.AdjustScrollbars()
return
+
# Utility functions
+
def showSelectAtomsDialog(panel):
"""Extend or limit selection to a string atom selection.
@@ -163,11 +163,14 @@ def showSelectAtomsDialog(panel):
No return value.
"""
# do nothing for non-existant or empty structure
- if not panel.structure: return
- msg = '\n'.join([
- 'Specify index, symbol or "all", use "!" to subtract selection.',
- 'Examples: "Na", "1:4, 6, 9:10", "all, !Na".',
- ])
+ if not panel.structure:
+ return
+ msg = "\n".join(
+ [
+ 'Specify index, symbol or "all", use "!" to subtract selection.',
+ 'Examples: "Na", "1:4, 6, 9:10", "all, !Na".',
+ ]
+ )
global selected_atoms
dlg = wx.TextEntryDialog(panel, msg, "Select Atoms", selected_atoms)
if dlg.ShowModal() == wx.ID_OK:
@@ -179,6 +182,7 @@ def showSelectAtomsDialog(panel):
dlg.Destroy()
return
+
def canCopySelectedCells(panel):
"""Check to see if we can copy selected cells.
@@ -194,6 +198,7 @@ def canCopySelectedCells(panel):
numsel = len(topleft) + len(individuals)
return numsel == 1
+
def canPasteIntoCells(panel):
"""Check if clipboard contents are formatted for grid insertion.
@@ -203,7 +208,8 @@ def canPasteIntoCells(panel):
individuals = grid.GetSelectedCells()
topleft = grid.GetSelectionBlockTopLeft()
- if len(individuals) + len(topleft) != 1: return False
+ if len(individuals) + len(topleft) != 1:
+ return False
# Get the text
if not wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
@@ -212,21 +218,23 @@ def canPasteIntoCells(panel):
textdata = wx.TextDataObject()
if not wx.TheClipboard.IsOpened():
opened = wx.TheClipboard.Open()
- if not opened: return False
+ if not opened:
+ return False
success = wx.TheClipboard.GetData(textdata)
wx.TheClipboard.Close()
- if not success: return False
+ if not success:
+ return False
copytext = textdata.GetText()
# Remove any trailing newline
- copytext = copytext.rstrip('\n')
+ copytext = copytext.rstrip("\n")
# Make sure it is of the appropriate format
try:
- rowlist = copytext.split('\n')
+ rowlist = copytext.split("\n")
# Strip any trailing tabs
- rowlist = [r.rstrip('\t') for r in rowlist]
- celllist = [r.split('\t') for r in rowlist]
+ rowlist = [r.rstrip("\t") for r in rowlist]
+ celllist = [r.split("\t") for r in rowlist]
except:
return False
@@ -234,13 +242,16 @@ def canPasteIntoCells(panel):
return False
ncol = len(celllist[0])
for row in celllist:
- if len(row) != ncol: return False
- if ncol == 0: return False
+ if len(row) != ncol:
+ return False
+ if ncol == 0:
+ return False
global clipcells
clipcells = celllist
return True
+
def copySelectedCells(panel):
"""Copy block of selected cells or individual cell into clipboard.
@@ -267,21 +278,23 @@ def copySelectedCells(panel):
rbr = bottomright[0][0]
cbr = bottomright[0][1]
- for row in range(rtl, rbr+1):
- for col in range(ctl, cbr+1):
- copytext += str(grid.GetCellValue(row,col))
- copytext += '\t'
- copytext += '\n'
+ for row in range(rtl, rbr + 1):
+ for col in range(ctl, cbr + 1):
+ copytext += str(grid.GetCellValue(row, col))
+ copytext += "\t"
+ copytext += "\n"
# Place the copytext into the clipboard
if not wx.TheClipboard.IsOpened():
opened = wx.TheClipboard.Open()
- if not opened: raise IOError("Cannot open the clipboard.")
+ if not opened:
+ raise IOError("Cannot open the clipboard.")
textdata = wx.TextDataObject(copytext)
wx.TheClipboard.SetData(textdata)
wx.TheClipboard.Close()
return
+
def pasteIntoCells(panel):
"""Paste clipboard contents into cells.
@@ -289,8 +302,10 @@ def pasteIntoCells(panel):
clipboard text for pasting.
"""
# Double check the clipcells
- if len(clipcells) == 0: return
- if len(clipcells[0]) == 0: return
+ if len(clipcells) == 0:
+ return
+ if len(clipcells[0]) == 0:
+ return
grid = panel.gridAtoms
individuals = grid.GetSelectedCells()
@@ -311,24 +326,28 @@ def pasteIntoCells(panel):
cbr = min(ncols, ctl + len(clipcells[0])) - 1
selections = []
- for row in range(rtl, rbr+1):
- for col in range(ctl, cbr+1):
+ for row in range(rtl, rbr + 1):
+ for col in range(ctl, cbr + 1):
if not grid.IsReadOnly(row, col):
oldvalue = panel.gridAtoms.GetCellValue(row, col)
- newvalue = panel.applyCellChange(row, col, clipcells[row-rtl][col-ctl])
- if newvalue is None: newvalue = oldvalue
- panel.gridAtoms.SetCellValue(row,col,str(newvalue))
- selections.append((row,col))
+ newvalue = panel.applyCellChange(
+ row, col, clipcells[row - rtl][col - ctl]
+ )
+ if newvalue is None:
+ newvalue = oldvalue
+ panel.gridAtoms.SetCellValue(row, col, str(newvalue))
+ selections.append((row, col))
gridutils.quickResizeColumns(panel.gridAtoms, selections)
# Clear the grid and select the inserted entries
grid.ClearSelection()
- #panel.refresh()
- for row in range(rtl, rbr+1):
- for col in range(ctl, cbr+1):
+ # panel.refresh()
+ for row in range(rtl, rbr + 1):
+ for col in range(ctl, cbr + 1):
if not grid.IsReadOnly(row, col):
- grid.SelectBlock(row,col,row,col,True)
+ grid.SelectBlock(row, col, row, col, True)
return
+
# End of file
diff --git a/src/diffpy/pdfgui/gui/phaseresultspanel.py b/src/diffpy/pdfgui/gui/phaseresultspanel.py
index ba805991..7b97fa29 100644
--- a/src/diffpy/pdfgui/gui/phaseresultspanel.py
+++ b/src/diffpy/pdfgui/gui/phaseresultspanel.py
@@ -22,11 +22,12 @@
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
from diffpy.pdfgui.gui import tooltips
from diffpy.pdfgui.gui import phasepanelutils
-from diffpy.pdfgui.gui.wxextensions.autowidthlabelsgrid import \
- AutoWidthLabelsGrid
+from diffpy.pdfgui.gui.wxextensions.autowidthlabelsgrid import AutoWidthLabelsGrid
+
class PhaseResultsPanel(wx.Panel, PDFPanel):
"""GUI Panel, holds phase (structure) related constraints."""
+
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
# begin wxGlade: PhaseResultsPanel.__init__
@@ -35,66 +36,104 @@ def __init__(self, *args, **kwds):
sizerMain = wx.BoxSizer(wx.VERTICAL)
- sizerPanelName = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizerPanelName = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerPanelName, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
self.labelPanelName = wx.StaticText(self, wx.ID_ANY, "Phase Results")
- self.labelPanelName.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
- sizerPanelName.Add(self.labelPanelName, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
-
- sizerLatticeParameters = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ self.labelPanelName.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
+ sizerPanelName.Add(
+ self.labelPanelName, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5
+ )
+
+ sizerLatticeParameters = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerLatticeParameters, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
grid_sizer_3 = wx.FlexGridSizer(2, 6, 0, 0)
sizerLatticeParameters.Add(grid_sizer_3, 1, wx.EXPAND, 0)
self.labelA = wx.StaticText(self, wx.ID_ANY, "a")
- grid_sizer_3.Add(self.labelA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlA = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_3.Add(self.textCtrlA, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelB = wx.StaticText(self, wx.ID_ANY, "b")
- grid_sizer_3.Add(self.labelB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlB = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_3.Add(self.textCtrlB, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelC = wx.StaticText(self, wx.ID_ANY, "c")
- grid_sizer_3.Add(self.labelC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlC = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_3.Add(self.textCtrlC, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelAlpha = wx.StaticText(self, wx.ID_ANY, "alpha")
- grid_sizer_3.Add(self.labelAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlAlpha = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_3.Add(self.textCtrlAlpha, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelBeta = wx.StaticText(self, wx.ID_ANY, "beta")
- grid_sizer_3.Add(self.labelBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlBeta = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_3.Add(self.textCtrlBeta, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelGamma = wx.StaticText(self, wx.ID_ANY, "gamma")
- grid_sizer_3.Add(self.labelGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_3.Add(
+ self.labelGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlGamma = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_3.Add(self.textCtrlGamma, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
- sizerAdditionalParameters = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizerAdditionalParameters = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizerMain.Add(sizerAdditionalParameters, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
grid_sizer_4 = wx.FlexGridSizer(3, 6, 0, 0)
sizerAdditionalParameters.Add(grid_sizer_4, 1, wx.EXPAND, 0)
self.labelScaleFactor = wx.StaticText(self, wx.ID_ANY, "Scale Factor")
- grid_sizer_4.Add(self.labelScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
-
- self.textCtrlScaleFactor = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
- grid_sizer_4.Add(self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
+ grid_sizer_4.Add(
+ self.labelScaleFactor,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
+ 5,
+ )
+
+ self.textCtrlScaleFactor = wx.TextCtrl(
+ self, wx.ID_ANY, "", style=wx.TE_READONLY
+ )
+ grid_sizer_4.Add(
+ self.textCtrlScaleFactor, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0
+ )
grid_sizer_4.Add((20, 10), 0, 0, 0)
@@ -105,37 +144,54 @@ def __init__(self, *args, **kwds):
grid_sizer_4.Add((20, 10), 0, 0, 0)
self.labelDelta1 = wx.StaticText(self, wx.ID_ANY, "delta1")
- grid_sizer_4.Add(self.labelDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlDelta1 = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_4.Add(self.textCtrlDelta1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelDelta2 = wx.StaticText(self, wx.ID_ANY, "delta2")
- grid_sizer_4.Add(self.labelDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlDelta2 = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_4.Add(self.textCtrlDelta2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelSpdiameter = wx.StaticText(self, wx.ID_ANY, "spdiameter")
- grid_sizer_4.Add(self.labelSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelSpdiameter,
+ 0,
+ wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
+ 5,
+ )
self.textCtrlSpdiameter = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
- grid_sizer_4.Add(self.textCtrlSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
+ grid_sizer_4.Add(
+ self.textCtrlSpdiameter, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0
+ )
self.labelSratio = wx.StaticText(self, wx.ID_ANY, "sratio")
- grid_sizer_4.Add(self.labelSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlSratio = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_4.Add(self.textCtrlSratio, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelRcut = wx.StaticText(self, wx.ID_ANY, "rcut")
- grid_sizer_4.Add(self.labelRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlRcut = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_4.Add(self.textCtrlRcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
self.labelStepcut = wx.StaticText(self, wx.ID_ANY, "stepcut")
- grid_sizer_4.Add(self.labelStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
+ grid_sizer_4.Add(
+ self.labelStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5
+ )
self.textCtrlStepcut = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
grid_sizer_4.Add(self.textCtrlStepcut, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 0)
@@ -149,7 +205,9 @@ def __init__(self, *args, **kwds):
self.labelIncludedPairs = wx.StaticText(self, wx.ID_ANY, "Included Pairs")
sizer_1.Add(self.labelIncludedPairs, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
- self.textCtrlIncludedPairs = wx.TextCtrl(self, wx.ID_ANY, "all-all", style=wx.TE_READONLY)
+ self.textCtrlIncludedPairs = wx.TextCtrl(
+ self, wx.ID_ANY, "all-all", style=wx.TE_READONLY
+ )
self.textCtrlIncludedPairs.SetMinSize((240, 25))
sizer_1.Add(self.textCtrlIncludedPairs, 0, wx.ALL, 5)
@@ -206,4 +264,5 @@ def refresh(self):
phasepanelutils.refreshGrid(self)
return
+
# end of class PhaseResultsPanel
diff --git a/src/diffpy/pdfgui/gui/plotpanel.py b/src/diffpy/pdfgui/gui/plotpanel.py
index 60bbb7d8..346c4447 100644
--- a/src/diffpy/pdfgui/gui/plotpanel.py
+++ b/src/diffpy/pdfgui/gui/plotpanel.py
@@ -25,6 +25,7 @@
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
from diffpy.pdfgui.control.controlerrors import ControlConfigError
+
class PlotPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -44,16 +45,22 @@ def __init__(self, *args, **kwds):
sizer_4 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, "Y"), wx.HORIZONTAL)
sizer_1.Add(sizer_4, 1, wx.EXPAND, 0)
- self.yDataList = KeyEventsListCtrl(self, wx.ID_ANY, style=wx.BORDER_SUNKEN | wx.LC_NO_HEADER | wx.LC_REPORT)
+ self.yDataList = KeyEventsListCtrl(
+ self, wx.ID_ANY, style=wx.BORDER_SUNKEN | wx.LC_NO_HEADER | wx.LC_REPORT
+ )
sizer_4.Add(self.yDataList, 1, wx.ALL | wx.EXPAND, 5)
sizer_6 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(sizer_6, 0, wx.EXPAND, 0)
- self.offsetLabel = wx.StaticText(self, wx.ID_ANY, "offset", style=wx.ALIGN_RIGHT)
+ self.offsetLabel = wx.StaticText(
+ self, wx.ID_ANY, "offset", style=wx.ALIGN_RIGHT
+ )
sizer_6.Add(self.offsetLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
- self.offsetTextCtrl = wx.TextCtrl(self, wx.ID_ANY, "-5", style=wx.TE_PROCESS_ENTER)
+ self.offsetTextCtrl = wx.TextCtrl(
+ self, wx.ID_ANY, "-5", style=wx.TE_PROCESS_ENTER
+ )
sizer_6.Add(self.offsetTextCtrl, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
self.static_line_1 = wx.StaticLine(self, wx.ID_ANY)
@@ -77,28 +84,28 @@ def __init__(self, *args, **kwds):
self.Bind(wx.EVT_BUTTON, self.onReset, self.resetButton)
# end wxGlade
self.Bind(wx.EVT_COMBOBOX, self._check, self.xDataCombo)
- self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._check, self.yDataList)
- self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._check, self.yDataList)
+ self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._check, self.yDataList)
+ self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._check, self.yDataList)
self.__customProperties()
# USER CONFIGURATION CODE #################################################
def __customProperties(self):
"""Custom Properties go here."""
self.yDataList.InsertColumn(0, "Y data")
- self.offsetTextCtrl.SetValidator(TextValidator(FLOAT_ONLY,allowNeg=True))
+ self.offsetTextCtrl.SetValidator(TextValidator(FLOAT_ONLY, allowNeg=True))
# Define tooltips.
self.setToolTips(tooltips.plotpanel)
# Testing Code. Comment or delete this block when finished.
- #self.yDataList.InsertStringItem(sys.maxint, "y1")
- #self.yDataList.InsertStringItem(sys.maxint, "y2")
- #self.yDataList.InsertStringItem(sys.maxint, "y3")
- #self.yDataList.InsertStringItem(sys.maxint, "y4")
- #self.yDataList.InsertStringItem(sys.maxint, "y5")
+ # self.yDataList.InsertStringItem(sys.maxint, "y1")
+ # self.yDataList.InsertStringItem(sys.maxint, "y2")
+ # self.yDataList.InsertStringItem(sys.maxint, "y3")
+ # self.yDataList.InsertStringItem(sys.maxint, "y4")
+ # self.yDataList.InsertStringItem(sys.maxint, "y5")
# Initialize the sorter.
- #self.yDataList.makeIDM()
- #self.yDataList.initializeSorter()
+ # self.yDataList.makeIDM()
+ # self.yDataList.initializeSorter()
return
@@ -124,20 +131,24 @@ def updateWidgets(self):
self.enableWidgets(False)
return
self.enableWidgets(True)
- fits = dict.fromkeys([self.treeCtrlMain.GetControlData(self.treeCtrlMain.GetFitRoot(sel))
- for sel in selections])
+ fits = dict.fromkeys(
+ [
+ self.treeCtrlMain.GetControlData(self.treeCtrlMain.GetFitRoot(sel))
+ for sel in selections
+ ]
+ )
refs = [self.treeCtrlMain.GetControlData(sel) for sel in selections]
xdata = []
# step is added if selections include type other than calculation
- for type in [ self.treeCtrlMain.GetNodeType(sel) for sel in selections ]:
- if type != 'calculation':
- xdata.append('step')
+ for type in [self.treeCtrlMain.GetNodeType(sel) for sel in selections]:
+ if type != "calculation":
+ xdata.append("step")
break
# index is added if mutiple selections are chosen from different fits
if len(fits) > 1:
- xdata.append('index')
+ xdata.append("index")
for ref in refs:
xdata.extend(ref.getXNames())
@@ -152,15 +163,15 @@ def updateWidgets(self):
# Make the parameter entries a bit more presentable.
def _represent(mixedNames):
- vals = ["@%i"%item for item in mixedNames if isinstance(item, int)]
- others = [item for item in mixedNames if not isinstance(item, int)]
+ vals = ["@%i" % item for item in mixedNames if isinstance(item, int)]
+ others = [item for item in mixedNames if not isinstance(item, int)]
vals.extend(others)
numericStringSort(vals)
return vals
xvals = _represent(xdata)
try:
- xvals.remove('rw')
+ xvals.remove("rw")
except:
pass
numericStringSort(xvals)
@@ -177,7 +188,7 @@ def _represent(mixedNames):
# Set default value for xDataCombo
# Either keep the current plot value selected, select 'r', or the
# first in the list.
- defaultOrders = [ 'r', 'step', 'index']
+ defaultOrders = ["r", "step", "index"]
if current:
defaultOrders.insert(0, current)
for item in defaultOrders:
@@ -191,7 +202,8 @@ def _represent(mixedNames):
ydata = refs[0].getYNames()
for ref in refs[1:]:
for name in ydata[:]:
- if name not in ref.getYNames(): ydata.remove(name)
+ if name not in ref.getYNames():
+ ydata.remove(name)
yvals = _represent(ydata)
@@ -205,7 +217,7 @@ def _represent(mixedNames):
if yvals:
self.yDataList.Select(0)
- #self.prevSelectionType = selectiontype
+ # self.prevSelectionType = selectiontype
self._check(None)
return
@@ -220,30 +232,32 @@ def getSelectedYVals(self):
item = self.yDataList.GetNextSelected(item)
return yvals
-
# EVENT CODE #############################################################
- def onPlot(self, event): # wxGlade: PlotPanel.
+ def onPlot(self, event): # wxGlade: PlotPanel.
"""Plot some stuff."""
self._plot(event)
return
- def _plot (self,event):
+ def _plot(self, event):
"""This function is not wrapped"""
selections = self.treeCtrlMain.GetSelections()
refs = [self.treeCtrlMain.GetControlData(node) for node in selections]
xval = self.xDataCombo.GetValue()
- if xval[0] == '@': xval = int(xval[1:])
+ if xval[0] == "@":
+ xval = int(xval[1:])
temp = self.getSelectedYVals()
# Clean up some formatting so the control can understand this.
- yvals = [ int(par[1:]) for par in temp if par[0] == '@']
- yvals.extend([val for val in temp if val[0] != '@'])
+ yvals = [int(par[1:]) for par in temp if par[0] == "@"]
+ yvals.extend([val for val in temp if val[0] != "@"])
offset = self.offsetTextCtrl.GetValue()
try:
offset = float(offset)
- except ValueError: # offset can be empty string
+ except ValueError: # offset can be empty string
offset = 0.0
- self.mainFrame.control.plot(xval, yvals, refs, shift=offset, dry=(event is None))
+ self.mainFrame.control.plot(
+ xval, yvals, refs, shift=offset, dry=(event is None)
+ )
return
def onEnter(self, event):
@@ -251,8 +265,7 @@ def onEnter(self, event):
self.onPlot(event)
return
-
- def onReset(self, event): # wxGlade: PlotPanel.
+ def onReset(self, event): # wxGlade: PlotPanel.
"""Reset everything."""
self.offsetTextCtrl.SetValue("-5")
self.refresh()
diff --git a/src/diffpy/pdfgui/gui/preferencespanel.py b/src/diffpy/pdfgui/gui/preferencespanel.py
index 35d14778..4680015c 100644
--- a/src/diffpy/pdfgui/gui/preferencespanel.py
+++ b/src/diffpy/pdfgui/gui/preferencespanel.py
@@ -22,6 +22,7 @@
from diffpy.pdfgui.gui import tooltips
from diffpy.pdfgui.control import structureviewer
+
class PreferencesPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -31,18 +32,31 @@ def __init__(self, *args, **kwds):
sizer_1 = wx.BoxSizer(wx.VERTICAL)
- sizerPanelName = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL)
+ sizerPanelName = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, ""), wx.HORIZONTAL
+ )
sizer_1.Add(sizerPanelName, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
self.labelPanelName = wx.StaticText(self, wx.ID_ANY, "Preferences")
- self.labelPanelName.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, "Bitstream Vera Sans"))
+ self.labelPanelName.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "Bitstream Vera Sans",
+ )
+ )
sizerPanelName.Add(self.labelPanelName, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
grid_sizer_1 = wx.GridSizer(3, 3, 10, 10)
sizer_1.Add(grid_sizer_1, 0, wx.ALL, 5)
self.labelViewer = wx.StaticText(self, wx.ID_ANY, "Structure viewer executable")
- grid_sizer_1.Add(self.labelViewer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 0)
+ grid_sizer_1.Add(
+ self.labelViewer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 0
+ )
self.textCtrlViewer = wx.TextCtrl(self, wx.ID_ANY, "")
grid_sizer_1.Add(self.textCtrlViewer, 0, wx.EXPAND, 0)
@@ -51,7 +65,9 @@ def __init__(self, *args, **kwds):
grid_sizer_1.Add(self.buttonViewerBrowse, 0, 0, 0)
self.labelArgStr = wx.StaticText(self, wx.ID_ANY, "Argument string")
- grid_sizer_1.Add(self.labelArgStr, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 0)
+ grid_sizer_1.Add(
+ self.labelArgStr, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 0
+ )
self.textCtrlArgument = wx.TextCtrl(self, wx.ID_ANY, "")
grid_sizer_1.Add(self.textCtrlArgument, 0, wx.EXPAND, 0)
@@ -59,17 +75,23 @@ def __init__(self, *args, **kwds):
grid_sizer_1.Add((20, 20), 0, 0, 0)
self.labelFormat = wx.StaticText(self, wx.ID_ANY, "Structure format")
- grid_sizer_1.Add(self.labelFormat, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 0)
+ grid_sizer_1.Add(
+ self.labelFormat, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 0
+ )
self.choiceFormat = wx.Choice(self, wx.ID_ANY, choices=[])
grid_sizer_1.Add(self.choiceFormat, 0, wx.EXPAND, 0)
grid_sizer_1.Add((20, 20), 0, 0, 0)
- self.structureDirCheckBox = wx.CheckBox(self, wx.ID_ANY, "Remember path to structure files")
+ self.structureDirCheckBox = wx.CheckBox(
+ self, wx.ID_ANY, "Remember path to structure files"
+ )
sizer_1.Add(self.structureDirCheckBox, 0, wx.ALL, 5)
- self.dataDirCheckBox = wx.CheckBox(self, wx.ID_ANY, "Remember path to data sets")
+ self.dataDirCheckBox = wx.CheckBox(
+ self, wx.ID_ANY, "Remember path to data sets"
+ )
sizer_1.Add(self.dataDirCheckBox, 0, wx.ALL, 5)
sizer_1.Add((0, 0), 1, wx.EXPAND, 0)
@@ -112,8 +134,7 @@ def __customProperties(self):
self.setToolTips(tooltips.preferencespanel)
return
-
- def onCancel(self, event): # wxGlade: PreferencesPanel.
+ def onCancel(self, event): # wxGlade: PreferencesPanel.
"""Cancel the changes. Go back to the last panel."""
selections = self.treeCtrlMain.GetSelections()
if selections:
@@ -125,7 +146,7 @@ def onCancel(self, event): # wxGlade: PreferencesPanel.
self.mainFrame.switchRightPanel(entrytype)
return
- def onOK(self, event): # wxGlade: PreferencesPanel.
+ def onOK(self, event): # wxGlade: PreferencesPanel.
"""Record all of the preferences and return to fitting mode."""
# Record structure viewer stuff
@@ -133,10 +154,10 @@ def onOK(self, event): # wxGlade: PreferencesPanel.
argstr = str(self.textCtrlArgument.GetValue()).strip()
fileformat = str(self.choiceFormat.GetStringSelection())
config = {
- "executable" : executable,
- "argstr" : argstr,
- "fileformat" : fileformat,
- }
+ "executable": executable,
+ "argstr": argstr,
+ "fileformat": fileformat,
+ }
viewer = structureviewer.getStructureViewer()
viewer.setConfig(config)
@@ -178,12 +199,19 @@ def refresh(self):
self.structureDirCheckBox.SetValue(remember)
return
- def onBrowse(self, event): # wxGlade: PreferencesPanel.
- d = wx.FileDialog(None, "Choose structure viewer", ".", "",
- "All Files|*", wx.FD_OPEN|wx.FD_FILE_MUST_EXIST)
+ def onBrowse(self, event): # wxGlade: PreferencesPanel.
+ d = wx.FileDialog(
+ None,
+ "Choose structure viewer",
+ ".",
+ "",
+ "All Files|*",
+ wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
+ )
if d.ShowModal() == wx.ID_OK:
fullpath = d.GetPath()
self.textCtrlViewer.SetValue(fullpath)
return
+
# end of class PreferencesPanel
diff --git a/src/diffpy/pdfgui/gui/resultspanel.py b/src/diffpy/pdfgui/gui/resultspanel.py
index c74e1916..e2ec7cff 100644
--- a/src/diffpy/pdfgui/gui/resultspanel.py
+++ b/src/diffpy/pdfgui/gui/resultspanel.py
@@ -19,13 +19,19 @@
import wx
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class ResultsPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
# begin wxGlade: ResultsPanel.__init__
kwds["style"] = kwds.get("style", 0) | wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
self.fitResLabel = wx.StaticText(self, wx.ID_ANY, "Fit Summary")
- self.resultsTextCtrl = wx.TextCtrl(self, wx.ID_ANY, "Fit results will display here once the fit is complete.", style=wx.HSCROLL | wx.TE_MULTILINE | wx.TE_READONLY)
+ self.resultsTextCtrl = wx.TextCtrl(
+ self,
+ wx.ID_ANY,
+ "Fit results will display here once the fit is complete.",
+ style=wx.HSCROLL | wx.TE_MULTILINE | wx.TE_READONLY,
+ )
self.__set_properties()
self.__do_layout()
@@ -34,7 +40,16 @@ def __init__(self, *args, **kwds):
def __set_properties(self):
# begin wxGlade: ResultsPanel.__set_properties
- self.fitResLabel.SetFont(wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, 0, ""))
+ self.fitResLabel.SetFont(
+ wx.Font(
+ 18,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_BOLD,
+ 0,
+ "",
+ )
+ )
# end wxGlade
def __do_layout(self):
@@ -58,8 +73,12 @@ def __customProperties(self):
# Set the font to monospace
ftxt = self.resultsTextCtrl.GetFont()
- font = wx.Font(ftxt.GetPointSize(), wx.FONTFAMILY_TELETYPE,
- ftxt.GetStyle(), ftxt.GetWeight())
+ font = wx.Font(
+ ftxt.GetPointSize(),
+ wx.FONTFAMILY_TELETYPE,
+ ftxt.GetStyle(),
+ ftxt.GetWeight(),
+ )
self.resultsTextCtrl.SetFont(font)
return
@@ -69,7 +88,7 @@ def refresh(self):
if self.fit:
self.results = self.fit.res
else:
- self.results = ''
+ self.results = ""
if not self.results:
self.results = self.defres
displayed = self.resultsTextCtrl.GetValue()
@@ -78,4 +97,5 @@ def refresh(self):
self.resultsTextCtrl.Replace(0, lastpos, self.results)
return
+
# end of class ResultsPanel
diff --git a/src/diffpy/pdfgui/gui/rseriespanel.py b/src/diffpy/pdfgui/gui/rseriespanel.py
index 517ce416..0b8bf820 100644
--- a/src/diffpy/pdfgui/gui/rseriespanel.py
+++ b/src/diffpy/pdfgui/gui/rseriespanel.py
@@ -21,13 +21,18 @@
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
from diffpy.pdfgui.gui.wxextensions.validators import TextValidator, FLOAT_ONLY
+
class RSeriesPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
# begin wxGlade: RSeriesPanel.__init__
kwds["style"] = kwds.get("style", 0) | wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
- self.instructionsLabel = wx.StaticText(self, wx.ID_ANY, "Select a fit from the tree on the left and set the first value, last value, \nand the step size of the maximum and/or minimum of the fit range\nbelow. If you have not set up a fit to be the template for the series, hit\ncancel and rerun this macro once a fit has been created.")
+ self.instructionsLabel = wx.StaticText(
+ self,
+ wx.ID_ANY,
+ "Select a fit from the tree on the left and set the first value, last value, \nand the step size of the maximum and/or minimum of the fit range\nbelow. If you have not set up a fit to be the template for the series, hit\ncancel and rerun this macro once a fit has been created.",
+ )
self.maxFirstLabel = wx.StaticText(self, wx.ID_ANY, "first")
self.maxFirstTextCtrl = wx.TextCtrl(self, wx.ID_ANY, "")
self.maxLastLabel = wx.StaticText(self, wx.ID_ANY, "last")
@@ -53,15 +58,28 @@ def __init__(self, *args, **kwds):
def __set_properties(self):
# begin wxGlade: RSeriesPanel.__set_properties
- self.instructionsLabel.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Sans"))
+ self.instructionsLabel.SetFont(
+ wx.Font(
+ 10,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_NORMAL,
+ 0,
+ "Sans",
+ )
+ )
# end wxGlade
def __do_layout(self):
# begin wxGlade: RSeriesPanel.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
- sizer_4_copy = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, "fit minimum"), wx.HORIZONTAL)
- sizer_4 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, "fit maximum"), wx.HORIZONTAL)
+ sizer_4_copy = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, "fit minimum"), wx.HORIZONTAL
+ )
+ sizer_4 = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, "fit maximum"), wx.HORIZONTAL
+ )
sizer_1.Add(self.instructionsLabel, 0, wx.ALL | wx.EXPAND, 5)
sizer_4.Add(self.maxFirstLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
sizer_4.Add(self.maxFirstTextCtrl, 0, wx.ALL, 5)
@@ -90,13 +108,14 @@ def __do_layout(self):
def __customProperties(self):
"""Set the custom properties of this panel."""
self.fit = None
- self.ctrlMap = {'maxfirst' : 'maxFirstTextCtrl',
- 'maxlast' : 'maxLastTextCtrl',
- 'maxstep' : 'maxStepTextCtrl',
- 'minfirst' : 'minFirstTextCtrl',
- 'minlast' : 'minLastTextCtrl',
- 'minstep' : 'minStepTextCtrl',
- }
+ self.ctrlMap = {
+ "maxfirst": "maxFirstTextCtrl",
+ "maxlast": "maxLastTextCtrl",
+ "maxstep": "maxStepTextCtrl",
+ "minfirst": "minFirstTextCtrl",
+ "minlast": "minLastTextCtrl",
+ "minstep": "minStepTextCtrl",
+ }
for var in self.ctrlMap:
setattr(self, var, None)
@@ -106,26 +125,33 @@ def __customProperties(self):
textCtrl.SetValidator(TextValidator(FLOAT_ONLY))
return
- def onOK(self, event): # wxGlade: RSeriesPanel.
+ def onOK(self, event): # wxGlade: RSeriesPanel.
"""Add make a temperature series and add it to the project."""
for (varname, ctrlname) in self.ctrlMap.items():
textCtrl = getattr(self, ctrlname)
value = textCtrl.GetValue()
- if value == '':
+ if value == "":
value = None
else:
value = float(value)
setattr(self, varname, value)
- org = makeRSeries(self.mainFrame.control, self.fit,
- self.maxfirst, self.maxlast, self.maxstep,
- self.minfirst, self.minlast, self.minstep)
+ org = makeRSeries(
+ self.mainFrame.control,
+ self.fit,
+ self.maxfirst,
+ self.maxlast,
+ self.maxstep,
+ self.minfirst,
+ self.minlast,
+ self.minstep,
+ )
self.treeCtrlMain.ExtendProjectTree(org, clear=False)
self.mainFrame.needsSave()
self.onCancel(event)
return
- def onCancel(self, event): # wxGlade: RSeriesPanel.
+ def onCancel(self, event): # wxGlade: RSeriesPanel.
"""Return to the main panel."""
self.mainFrame.setMode("fitting")
self.treeCtrlMain.UnselectAll()
@@ -135,7 +161,7 @@ def onCancel(self, event): # wxGlade: RSeriesPanel.
def treeSelectionUpdate(self, node):
"""Set the current fit when the tree selection changes."""
nodetype = self.treeCtrlMain.GetNodeType(node)
- if nodetype == 'fit':
+ if nodetype == "fit":
self.fit = self.treeCtrlMain.GetControlData(node)
self.refresh()
return
@@ -154,12 +180,17 @@ def refresh(self):
node = selections[0]
nodetype = self.treeCtrlMain.GetNodeType(node)
- if node and nodetype == "fit" \
- and self.fit and self.fit.hasDataSets() \
- and self.fit.hasStructures():
+ if (
+ node
+ and nodetype == "fit"
+ and self.fit
+ and self.fit.hasDataSets()
+ and self.fit.hasStructures()
+ ):
self.goButton.Enable()
else:
self.goButton.Enable(False)
return
+
# end of class RSeriesPanel
diff --git a/src/diffpy/pdfgui/gui/sgconstraindialog.py b/src/diffpy/pdfgui/gui/sgconstraindialog.py
index 3bc63391..0a10015e 100644
--- a/src/diffpy/pdfgui/gui/sgconstraindialog.py
+++ b/src/diffpy/pdfgui/gui/sgconstraindialog.py
@@ -21,6 +21,7 @@
from diffpy.pdfgui.control.controlerrors import ControlValueError
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class SGConstrainDialog(wx.Dialog, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -29,7 +30,9 @@ def __init__(self, *args, **kwds):
wx.Dialog.__init__(self, *args, **kwds)
self.SetTitle("Space Group Constraints")
- sizer_2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, "Space Group Constraints"), wx.VERTICAL)
+ sizer_2 = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, "Space Group Constraints"), wx.VERTICAL
+ )
self.numConstrainedLabel = wx.StaticText(self, wx.ID_ANY, "")
sizer_2.Add(self.numConstrainedLabel, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5)
@@ -104,14 +107,17 @@ def __customProperties(self):
"""Set the custom properties."""
# setting of combo box items was deferred to updateSpaceGroupList()
self.spacegroup = None
- self.offset = [0.0,0.0,0.0]
+ self.offset = [0.0, 0.0, 0.0]
self.posflag = True
self.tempflag = True
self.structure = None
self.indices = []
- self.textCtrls = [self.offsetTextCtrlX, self.offsetTextCtrlY,
- self.offsetTextCtrlZ]
+ self.textCtrls = [
+ self.offsetTextCtrlX,
+ self.offsetTextCtrlY,
+ self.offsetTextCtrlZ,
+ ]
# Set the focus events.
for textctrl in self.textCtrls:
@@ -126,7 +132,7 @@ def updateSpaceGroupList(self):
"""
self.sgComboBox.Clear()
sglist = self.structure.getSpaceGroupList()
- self.spacegroup = self.structure.getSpaceGroup('P1')
+ self.spacegroup = self.structure.getSpaceGroup("P1")
for sg in sglist:
self.sgComboBox.Append(sg.short_name)
return
@@ -180,23 +186,22 @@ def updateWidgets(self):
val = textctrl.GetValue()
# make sure the value is meaningful
try:
- val = float(eval("1.0*"+val, dict(math.__dict__)))
+ val = float(eval("1.0*" + val, dict(math.__dict__)))
except (NameError, TypeError, SyntaxError):
val = 0
- textctrl.SetValue("%s"%val)
+ textctrl.SetValue("%s" % val)
self.offset[i] = val
- #newatoms = len(stemp) - len(self.structure)
+ # newatoms = len(stemp) - len(self.structure)
s = ""
if len(self.indices) != 1:
s = "s"
- message = "%i atom%s selected." %\
- (len(self.indices), s)
+ message = "%i atom%s selected." % (len(self.indices), s)
self.numConstrainedLabel.SetLabel(message)
# Raise an error if we had to change the space group
if error:
- raise ControlValueError(error);
+ raise ControlValueError(error)
return
### Events
@@ -207,34 +212,33 @@ def onKillFocus(self, event):
event.Skip()
return
- def onSGTextEnter(self, event): # wxGlade: SGConstrainDialog.
+ def onSGTextEnter(self, event): # wxGlade: SGConstrainDialog.
self.updateWidgets()
return
- def onOXTextEnter(self, event): # wxGlade: SGConstrainDialog.
+ def onOXTextEnter(self, event): # wxGlade: SGConstrainDialog.
self.updateWidgets()
return
- def onOYTextEnter(self, event): # wxGlade: SGConstrainDialog.
+ def onOYTextEnter(self, event): # wxGlade: SGConstrainDialog.
self.updateWidgets()
return
- def onOZTextEnter(self, event): # wxGlade: SGConstrainDialog.
+ def onOZTextEnter(self, event): # wxGlade: SGConstrainDialog.
self.updateWidgets()
return
- def onSGSelect(self, event): # wxGlade: SGConstrainDialog.
+ def onSGSelect(self, event): # wxGlade: SGConstrainDialog.
self.updateWidgets()
return
- def onOk(self, event): # wxGlade: SGConstrainDialog.
+ def onOk(self, event): # wxGlade: SGConstrainDialog.
# check to see if the space group is consistant
if not self.structure.isSpaceGroupPossible(self.spacegroup):
- message = "The chosen space group is not consistent\n"
+ message = "The chosen space group is not consistent\n"
message += "with the lattice parameters.\n"
message += "Would you like to proceed anyways?"
- d = wx.MessageDialog( self, message,
- "Inconsistent space group", wx.YES_NO)
+ d = wx.MessageDialog(self, message, "Inconsistent space group", wx.YES_NO)
code = d.ShowModal()
if code == wx.ID_YES:
self.EndModal(wx.ID_OK)
@@ -242,16 +246,17 @@ def onOk(self, event): # wxGlade: SGConstrainDialog.
self.EndModal(wx.ID_OK)
return
- def onCancel(self, event): # wxGlade: SGConstrainDialog.
+ def onCancel(self, event): # wxGlade: SGConstrainDialog.
event.Skip()
return
- def onPosFlag(self, event): # wxGlade: SGConstrainDialog.
+ def onPosFlag(self, event): # wxGlade: SGConstrainDialog.
self.posflag = self.positionCheckBox.GetValue()
return
- def onTempFlag(self, event): # wxGlade: SGConstrainDialog.
+ def onTempFlag(self, event): # wxGlade: SGConstrainDialog.
self.tempflag = self.tfCheckBox.GetValue()
return
+
# end of class SGConstrainDialog
diff --git a/src/diffpy/pdfgui/gui/sgstructuredialog.py b/src/diffpy/pdfgui/gui/sgstructuredialog.py
index 8a6ea4c5..cd1e627f 100644
--- a/src/diffpy/pdfgui/gui/sgstructuredialog.py
+++ b/src/diffpy/pdfgui/gui/sgstructuredialog.py
@@ -21,6 +21,7 @@
from diffpy.pdfgui.control.controlerrors import ControlValueError
from diffpy.pdfgui.gui.pdfpanel import PDFPanel
+
class SGStructureDialog(wx.Dialog, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -29,7 +30,9 @@ def __init__(self, *args, **kwds):
wx.Dialog.__init__(self, *args, **kwds)
self.SetTitle("Space Group Expansion")
- sizer_2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, "Space Group Expansion"), wx.VERTICAL)
+ sizer_2 = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, "Space Group Expansion"), wx.VERTICAL
+ )
self.numConstrainedLabel = wx.StaticText(self, wx.ID_ANY, "")
sizer_2.Add(self.numConstrainedLabel, 0, wx.ALL, 5)
@@ -50,13 +53,19 @@ def __init__(self, *args, **kwds):
self.offsetLabel = wx.StaticText(self, wx.ID_ANY, "Origin Offset")
sizer_4.Add(self.offsetLabel, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
- self.offsetTextCtrlX = wx.TextCtrl(self, wx.ID_ANY, "0", style=wx.TE_PROCESS_ENTER)
+ self.offsetTextCtrlX = wx.TextCtrl(
+ self, wx.ID_ANY, "0", style=wx.TE_PROCESS_ENTER
+ )
sizer_4.Add(self.offsetTextCtrlX, 0, wx.ALL, 5)
- self.offsetTextCtrlY = wx.TextCtrl(self, wx.ID_ANY, "0", style=wx.TE_PROCESS_ENTER)
+ self.offsetTextCtrlY = wx.TextCtrl(
+ self, wx.ID_ANY, "0", style=wx.TE_PROCESS_ENTER
+ )
sizer_4.Add(self.offsetTextCtrlY, 0, wx.ALL, 5)
- self.offsetTextCtrlZ = wx.TextCtrl(self, wx.ID_ANY, "0", style=wx.TE_PROCESS_ENTER)
+ self.offsetTextCtrlZ = wx.TextCtrl(
+ self, wx.ID_ANY, "0", style=wx.TE_PROCESS_ENTER
+ )
sizer_4.Add(self.offsetTextCtrlZ, 0, wx.ALL, 5)
self.static_line_1 = wx.StaticLine(self, wx.ID_ANY)
@@ -94,12 +103,15 @@ def __customProperties(self):
"""Set the custom properties."""
# setting of combo box items was deferred to updateSpaceGroupList()
self.spacegroup = None
- self.offset = [0.0,0.0,0.0]
+ self.offset = [0.0, 0.0, 0.0]
self.structure = None
self.indices = []
- self.textCtrls = [self.offsetTextCtrlX, self.offsetTextCtrlY,
- self.offsetTextCtrlZ]
+ self.textCtrls = [
+ self.offsetTextCtrlX,
+ self.offsetTextCtrlY,
+ self.offsetTextCtrlZ,
+ ]
# Set the focus events.
for textctrl in self.textCtrls:
@@ -114,7 +126,7 @@ def updateSpaceGroupList(self):
"""
self.sgComboBox.Clear()
sglist = self.structure.getSpaceGroupList()
- self.spacegroup = self.structure.getSpaceGroup('P1')
+ self.spacegroup = self.structure.getSpaceGroup("P1")
for sg in sglist:
self.sgComboBox.Append(sg.short_name)
return
@@ -161,29 +173,34 @@ def updateWidgets(self):
val = textctrl.GetValue()
# make sure the value is meaningful
try:
- val = float(eval("1.0*"+val, dict(math.__dict__)))
+ val = float(eval("1.0*" + val, dict(math.__dict__)))
except (NameError, TypeError, SyntaxError):
val = 0.0
- textctrl.SetValue("%s"%val)
+ textctrl.SetValue("%s" % val)
self.offset[i] = val
# find how many new atoms would be generated
from diffpy.structure.symmetryutilities import ExpandAsymmetricUnit
- corepos = [ self.structure[i].xyz for i in self.indices ]
+
+ corepos = [self.structure[i].xyz for i in self.indices]
symposeps = self.structure.symposeps
- eau = ExpandAsymmetricUnit(self.spacegroup, corepos,
- sgoffset=self.offset, eps=symposeps)
+ eau = ExpandAsymmetricUnit(
+ self.spacegroup, corepos, sgoffset=self.offset, eps=symposeps
+ )
newsize = sum(eau.multiplicity)
s = ""
if len(self.indices) != 1:
s = "s"
- message = "%i atom%s selected. Expanding to %i positions." %\
- (len(self.indices), s, newsize)
+ message = "%i atom%s selected. Expanding to %i positions." % (
+ len(self.indices),
+ s,
+ newsize,
+ )
self.numConstrainedLabel.SetLabel(message)
# Raise an error if we had to change the space group
if error:
- raise ControlValueError(error);
+ raise ControlValueError(error)
return
### Events
@@ -193,38 +210,37 @@ def onKillFocus(self, event):
event.Skip()
return
- def onSGTextEnter(self, event): # wxGlade: SGStructureDialog.
+ def onSGTextEnter(self, event): # wxGlade: SGStructureDialog.
self.updateWidgets()
self.onOk(None)
return
- def onSGSelect(self, event): # wxGlade: SGStructureDialog.
+ def onSGSelect(self, event): # wxGlade: SGStructureDialog.
self.updateWidgets()
return
- def onOXTextEnter(self, event): # wxGlade: SGStructureDialog.
+ def onOXTextEnter(self, event): # wxGlade: SGStructureDialog.
self.updateWidgets()
self.onOk(None)
return
- def onOYTextEnter(self, event): # wxGlade: SGStructureDialog.
+ def onOYTextEnter(self, event): # wxGlade: SGStructureDialog.
self.updateWidgets()
self.onOk(None)
return
- def onOZTextEnter(self, event): # wxGlade: SGStructureDialog.
+ def onOZTextEnter(self, event): # wxGlade: SGStructureDialog.
self.updateWidgets()
self.onOk(None)
return
- def onOk(self, event): # wxGlade: SGStructureDialog.
+ def onOk(self, event): # wxGlade: SGStructureDialog.
# check to see if the space group is consistant
if not self.structure.isSpaceGroupPossible(self.spacegroup):
- message = "The chosen space group is not consistent\n"
+ message = "The chosen space group is not consistent\n"
message += "with the lattice parameters.\n"
message += "Would you like to proceed anyways?"
- d = wx.MessageDialog( self, message,
- "Inconsistent space group", wx.YES_NO)
+ d = wx.MessageDialog(self, message, "Inconsistent space group", wx.YES_NO)
code = d.ShowModal()
if code == wx.ID_YES:
self.EndModal(wx.ID_OK)
@@ -232,8 +248,9 @@ def onOk(self, event): # wxGlade: SGStructureDialog.
self.EndModal(wx.ID_OK)
return
- def onCancel(self, event): # wxGlade: SGStructureDialog.
+ def onCancel(self, event): # wxGlade: SGStructureDialog.
event.Skip()
return
+
# end of class SGStructureDialog
diff --git a/src/diffpy/pdfgui/gui/supercelldialog.py b/src/diffpy/pdfgui/gui/supercelldialog.py
index c0fade3a..a883ca60 100644
--- a/src/diffpy/pdfgui/gui/supercelldialog.py
+++ b/src/diffpy/pdfgui/gui/supercelldialog.py
@@ -18,6 +18,7 @@
import wx
+
class SupercellDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: SupercellDialog.__init__
@@ -48,7 +49,9 @@ def __set_properties(self):
def __do_layout(self):
# begin wxGlade: SupercellDialog.__do_layout
- sizer_1 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, "Supercell Expansion"), wx.VERTICAL)
+ sizer_1 = wx.StaticBoxSizer(
+ wx.StaticBox(self, wx.ID_ANY, "Supercell Expansion"), wx.VERTICAL
+ )
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2_copy_1 = wx.BoxSizer(wx.HORIZONTAL)
@@ -73,7 +76,7 @@ def __do_layout(self):
self.Layout()
# end wxGlade
- ############################################################################
+ ############################################################################
def __customProperties(self):
"""Set custom properties."""
@@ -87,7 +90,7 @@ def getMNO(self):
"""Get the [m, n, o] expansion parameters from the dialog."""
return [self.m, self.n, self.o]
- def onOk(self, event): # wxGlade: SupercellDialog.
+ def onOk(self, event): # wxGlade: SupercellDialog.
"""Accept the expansion."""
self.m = self.aSpinCtrl.GetValue()
self.n = self.bSpinCtrl.GetValue()
@@ -95,9 +98,10 @@ def onOk(self, event): # wxGlade: SupercellDialog.
event.Skip()
return
- def onCancel(self, event): # wxGlade: SupercellDialog.
+ def onCancel(self, event): # wxGlade: SupercellDialog.
"""Get out of here."""
event.Skip()
return
+
# end of class SupercellDialog
diff --git a/src/diffpy/pdfgui/gui/temperatureseriespanel.py b/src/diffpy/pdfgui/gui/temperatureseriespanel.py
index 3d48fe1a..5d4cdb9a 100644
--- a/src/diffpy/pdfgui/gui/temperatureseriespanel.py
+++ b/src/diffpy/pdfgui/gui/temperatureseriespanel.py
@@ -26,6 +26,7 @@
from diffpy.pdfgui.gui.wxextensions.listctrls import AutoWidthListCtrl
from diffpy.pdfgui.utils import numericStringSort
+
class TemperatureSeriesPanel(wx.Panel, PDFPanel):
def __init__(self, *args, **kwds):
PDFPanel.__init__(self)
@@ -35,8 +36,21 @@ def __init__(self, *args, **kwds):
sizer_1 = wx.BoxSizer(wx.VERTICAL)
- self.instructionsLabel = wx.StaticText(self, wx.ID_ANY, "Select a fit from the tree on the left then add datasets and assign\ntemperatues below. If you have not set up a fit to be the template\nfor the series, hit cancel and rerun this macro once a fit has been\ncreated.")
- self.instructionsLabel.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Sans"))
+ self.instructionsLabel = wx.StaticText(
+ self,
+ wx.ID_ANY,
+ "Select a fit from the tree on the left then add datasets and assign\ntemperatues below. If you have not set up a fit to be the template\nfor the series, hit cancel and rerun this macro once a fit has been\ncreated.",
+ )
+ self.instructionsLabel.SetFont(
+ wx.Font(
+ 10,
+ wx.FONTFAMILY_DEFAULT,
+ wx.FONTSTYLE_NORMAL,
+ wx.FONTWEIGHT_NORMAL,
+ 0,
+ "Sans",
+ )
+ )
sizer_1.Add(self.instructionsLabel, 0, wx.ALL | wx.EXPAND, 5)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
@@ -45,7 +59,9 @@ def __init__(self, *args, **kwds):
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(sizer_4, 1, wx.EXPAND, 0)
- self.listCtrlFiles = AutoWidthListCtrl(self, wx.ID_ANY, style=wx.BORDER_SUNKEN | wx.LC_EDIT_LABELS | wx.LC_REPORT)
+ self.listCtrlFiles = AutoWidthListCtrl(
+ self, wx.ID_ANY, style=wx.BORDER_SUNKEN | wx.LC_EDIT_LABELS | wx.LC_REPORT
+ )
sizer_4.Add(self.listCtrlFiles, 1, wx.ALL | wx.EXPAND, 5)
sizer_5 = wx.BoxSizer(wx.VERTICAL)
@@ -107,20 +123,20 @@ def __init__(self, *args, **kwds):
def __customProperties(self):
"""Set the custom properties."""
self.fit = None
- self.reverse = False # Reverse the sort?
- self.fullpath = '.'
- self.datasets = [] # Contains (temperature, filename) tuples
- # temperature is a float and comes first for easy sorting
+ self.reverse = False # Reverse the sort?
+ self.fullpath = "."
+ self.datasets = [] # Contains (temperature, filename) tuples
+ # temperature is a float and comes first for easy sorting
self.listCtrlFiles.InsertColumn(0, "Temperature")
self.listCtrlFiles.InsertColumn(1, "Data Set")
- self.listCtrlFiles.SetColumnWidth(0,-2)
+ self.listCtrlFiles.SetColumnWidth(0, -2)
# Define tooltips.
self.setToolTips(tooltips.temperatureseriespanel)
return
- def onEndLabelEdit(self, event): # wxGlade: TemperatureSeriesPanel.
+ def onEndLabelEdit(self, event): # wxGlade: TemperatureSeriesPanel.
"""Update the temperature in the datasets."""
index = event.GetIndex()
text = event.GetText()
@@ -138,55 +154,62 @@ def onEndLabelEdit(self, event): # wxGlade: TemperatureSeriesPanel.
+ def onOK(self, event): # wxGlade: TemperatureSeriesPanel.
"""Let's go!"""
paths = [tp[1] for tp in self.datasets]
temperatures = [tp[0] for tp in self.datasets]
- org = makeTemperatureSeries(self.mainFrame.control, self.fit,
- paths, temperatures)
+ org = makeTemperatureSeries(
+ self.mainFrame.control, self.fit, paths, temperatures
+ )
self.treeCtrlMain.ExtendProjectTree(org, clear=False)
self.mainFrame.needsSave()
self.onCancel(event)
return
- def onCancel(self, event): # wxGlade: TemperatureSeriesPanel.
+ def onCancel(self, event): # wxGlade: TemperatureSeriesPanel.
"""Let's go, but not actually do anything."""
self.mainFrame.setMode("fitting")
self.treeCtrlMain.UnselectAll()
self.mainFrame.switchRightPanel("blank")
return
- def onUp(self, event): # wxGlade: TemperatureSeriesPanel.
+ def onUp(self, event): # wxGlade: TemperatureSeriesPanel.
"""Move an item in the list up."""
index = self.listCtrlFiles.GetFirstSelected()
if index > 0:
temp = self.datasets[index]
- self.datasets[index] = self.datasets[index-1]
- self.datasets[index-1] = temp
+ self.datasets[index] = self.datasets[index - 1]
+ self.datasets[index - 1] = temp
self.fillList()
- self.listCtrlFiles.Select(index-1)
+ self.listCtrlFiles.Select(index - 1)
return
- def onDown(self, event): # wxGlade: TemperatureSeriesPanel.
+ def onDown(self, event): # wxGlade: TemperatureSeriesPanel.
"""Move an item in the list down."""
index = self.listCtrlFiles.GetFirstSelected()
- if index > -1 and index != len(self.datasets)-1:
+ if index > -1 and index != len(self.datasets) - 1:
temp = self.datasets[index]
- self.datasets[index] = self.datasets[index+1]
- self.datasets[index+1] = temp
+ self.datasets[index] = self.datasets[index + 1]
+ self.datasets[index + 1] = temp
self.fillList()
- self.listCtrlFiles.Select(index+1)
+ self.listCtrlFiles.Select(index + 1)
return
- def onAdd(self, event): # wxGlade: TemperatureSeriesPanel.
+ def onAdd(self, event): # wxGlade: TemperatureSeriesPanel.
"""Append files to the list."""
dir, filename = os.path.split(self.fullpath)
if not dir:
dir = self.mainFrame.workpath
matchstring = "PDF data files (*.gr)|*.gr|PDF fit files (*.fgr)|*.fgr|PDF fit files (*.fit)|*.fit|PDF calculation files (*.cgr)|*.cgr|PDF calculation files (*.calc)|*.calc|All Files|*"
- d = wx.FileDialog(None, "Choose files", dir, "", matchstring,
- wx.FD_OPEN|wx.FD_FILE_MUST_EXIST|wx.FD_MULTIPLE)
+ d = wx.FileDialog(
+ None,
+ "Choose files",
+ dir,
+ "",
+ matchstring,
+ wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE,
+ )
paths = []
if d.ShowModal() == wx.ID_OK:
paths = d.GetPaths()
@@ -200,14 +223,17 @@ def onAdd(self, event): # wxGlade: TemperatureSeriesPanel.
# Look for the temperature in the filename
temperature = 300.0
- rx = {'f' : r'(?:\d+(?:\.\d*)?|\d*\.\d+)' }
+ rx = {"f": r"(?:\d+(?:\.\d*)?|\d*\.\d+)"}
# Search for T123, t123, Temp123, temp123, 123k, 123K.
# Some filenames fool this, e.g. "test1.dat" will match '1' since it
# is preceeded by a 't'.
# Is there a better regexp? Probably...
- regexp = r"""(?:[Tt](?:emp(?:erature)?)?(%(f)s))|
+ regexp = (
+ r"""(?:[Tt](?:emp(?:erature)?)?(%(f)s))|
(?:(?
temperature = float(res.groups()[1])
else:
# Look in the file
- infile = open(path, 'r')
+ infile = open(path, "r")
datastring = infile.read()
infile.close()
# Look for it first in the file
- res = re.search(r'^#+ start data\s*(?:#.*\s+)*', datastring, re.M)
+ res = re.search(r"^#+ start data\s*(?:#.*\s+)*", datastring, re.M)
# start_data is position where the first data line starts
if res:
start_data = res.end()
else:
- res = re.search(r'^[^#]', datastring, re.M)
+ res = re.search(r"^[^#]", datastring, re.M)
if res:
start_data = res.start()
else:
@@ -238,16 +264,17 @@ def onAdd(self, event): # wxGlade: TemperatureSeriesPanel.
if res:
temperature = float(res.groups()[0])
# Add the new path
- if temperature <= 0: temperature = 300.0
+ if temperature <= 0:
+ temperature = 300.0
newdatasets.append([temperature, path])
# DONT Sort the new paths according to temperature
- #newdatasets.sort()
+ # newdatasets.sort()
self.datasets.extend(newdatasets)
self.fillList()
return
- def onDelete(self, event): # wxGlade: TemperatureSeriesPanel.
+ def onDelete(self, event): # wxGlade: TemperatureSeriesPanel.
"""Delete selected files from the list."""
idxlist = []
item = self.listCtrlFiles.GetFirstSelected()
@@ -261,18 +288,18 @@ def onDelete(self, event): # wxGlade: TemperatureSeriesPanel.
self.fillList()
return
- def onColClick(self, event): # wxGlade: TemperatureSeriesPanel.
+ def onColClick(self, event): # wxGlade: TemperatureSeriesPanel.
"""Sort by temperature."""
column = event.GetColumn()
# sort by temperature
if column == 0:
- sortkey = lambda tf : float(tf[0])
+ sortkey = lambda tf: float(tf[0])
# sort by filename with numerical comparison of digits
elif column == 1:
filenames = [f for t, f in self.datasets]
numericStringSort(filenames)
order = dict(zip(filenames, range(len(filenames))))
- sortkey = lambda tf : order[tf[1]]
+ sortkey = lambda tf: order[tf[1]]
# ignore unhandled columns
else:
return
@@ -289,7 +316,8 @@ def fillList(self):
cp = os.path.commonprefix(names)
# We want to break at the last path/separator in the common prefix
idx = cp.rfind(os.path.sep)
- if idx == -1: idx = len(cp)
+ if idx == -1:
+ idx = len(cp)
for temperature, filename in self.datasets:
shortname = "..." + filename[idx:]
# index = self.listCtrlFiles.InsertItem(sys.maxsize, str(temperature)) #doesn't work for windows
@@ -301,7 +329,7 @@ def fillList(self):
def treeSelectionUpdate(self, node):
"""Set the current fit when the tree selection changes."""
nodetype = self.treeCtrlMain.GetNodeType(node)
- if nodetype == 'fit':
+ if nodetype == "fit":
self.fit = self.treeCtrlMain.GetControlData(node)
self.refresh()
return
@@ -321,12 +349,17 @@ def refresh(self):
node = selections[0]
nodetype = self.treeCtrlMain.GetNodeType(node)
- if node and nodetype == "fit" \
- and self.fit and self.fit.hasDataSets() \
- and self.fit.hasStructures():
+ if (
+ node
+ and nodetype == "fit"
+ and self.fit
+ and self.fit.hasDataSets()
+ and self.fit.hasStructures()
+ ):
self.goButton.Enable()
else:
self.goButton.Enable(False)
return
+
# end of class TemperatureSeriesPanel
diff --git a/src/diffpy/pdfgui/gui/tooltips.py b/src/diffpy/pdfgui/gui/tooltips.py
index dc3fc59a..804c988d 100644
--- a/src/diffpy/pdfgui/gui/tooltips.py
+++ b/src/diffpy/pdfgui/gui/tooltips.py
@@ -16,10 +16,12 @@
"""Tooltips for pdfgui panels.
"""
+
def _expand_tooltip_aliases(ttps):
"Replace aliased equivalent values {other} in tooltip strings."
- isalias = lambda s: (s[1:-1] and s[::len(s) - 1] == '{}' and
- s[1:-1].replace('_', '').isalnum())
+ isalias = lambda s: (
+ s[1:-1] and s[:: len(s) - 1] == "{}" and s[1:-1].replace("_", "").isalnum()
+ )
for n, t in list(ttps.items()):
if not isalias(t):
continue
@@ -30,105 +32,104 @@ def _expand_tooltip_aliases(ttps):
datasetconfigurepanel = {
-# 'panelNameLabel' : '', # StaticText "Data Set Configuration"
- 'radioBoxStype' : 'Radiation type', # RadioBox "Scatterer Type", choices=["Neutron", "X-ray"]
- 'radioBoxSampling' : 'Fit sampling type', # RadioBox "Scatterer Type", choices=["Default", "Nyquist", "Custom"]
-# 'labelDataRange' : '', # StaticText "Data Range"
- 'textCtrlDataFrom' : 'Data r_min', # TextCtrl
-# 'labelDataTo' : '', # StaticText "to"
- 'textCtrlDataTo' : 'Data r_max', # TextCtrl
-# 'labelFitRange' : '', # StaticText "Fit Range"
- 'textCtrlDataStep' : 'Step size in the data', # TextCtrl
- 'textCtrlFitFrom' : 'Fit r_min', # TextCtrl
-# 'labelFitTo' : '', # StaticText "to"
- 'textCtrlFitTo' : 'Fit r_max', # TextCtrl
- 'textCtrlFitStep' : 'Step size in the fit', # TextCtrl
-# 'labelScaleFactor' : '', # StaticText "Scale Factor"
- 'textCtrlScaleFactor' : 'Data scale factor', # TextCtrl
-# 'labelQmax' : '', # StaticText "Qmax"
- 'textCtrlQmax' : 'Upper limit used for Fourier transform to obtain data PDF', # TextCtrl
-# 'labelQdamp' : '', # StaticText "Qdamp"
- 'textCtrlQdamp' : 'Resolution dampening factor', # TextCtrl
-# 'labelQbroad' : '', # StaticText "Qbroad"
- 'textCtrlQbroad' : 'Resolution peak broadening factor', # TextCtrl
-# 'labelTemperature' : '', # StaticText "Temperature"
- 'textCtrlTemperature' : 'Temperature at which the data were collected', # TextCtrl
-# 'labelDoping' : '', # StaticText "Doping"
- 'textCtrlDoping' : 'Sample characteristic doping level (if applicable)', # TextCtrl
- }
+ # 'panelNameLabel' : '', # StaticText "Data Set Configuration"
+ "radioBoxStype": "Radiation type", # RadioBox "Scatterer Type", choices=["Neutron", "X-ray"]
+ "radioBoxSampling": "Fit sampling type", # RadioBox "Scatterer Type", choices=["Default", "Nyquist", "Custom"]
+ # 'labelDataRange' : '', # StaticText "Data Range"
+ "textCtrlDataFrom": "Data r_min", # TextCtrl
+ # 'labelDataTo' : '', # StaticText "to"
+ "textCtrlDataTo": "Data r_max", # TextCtrl
+ # 'labelFitRange' : '', # StaticText "Fit Range"
+ "textCtrlDataStep": "Step size in the data", # TextCtrl
+ "textCtrlFitFrom": "Fit r_min", # TextCtrl
+ # 'labelFitTo' : '', # StaticText "to"
+ "textCtrlFitTo": "Fit r_max", # TextCtrl
+ "textCtrlFitStep": "Step size in the fit", # TextCtrl
+ # 'labelScaleFactor' : '', # StaticText "Scale Factor"
+ "textCtrlScaleFactor": "Data scale factor", # TextCtrl
+ # 'labelQmax' : '', # StaticText "Qmax"
+ "textCtrlQmax": "Upper limit used for Fourier transform to obtain data PDF", # TextCtrl
+ # 'labelQdamp' : '', # StaticText "Qdamp"
+ "textCtrlQdamp": "Resolution dampening factor", # TextCtrl
+ # 'labelQbroad' : '', # StaticText "Qbroad"
+ "textCtrlQbroad": "Resolution peak broadening factor", # TextCtrl
+ # 'labelTemperature' : '', # StaticText "Temperature"
+ "textCtrlTemperature": "Temperature at which the data were collected", # TextCtrl
+ # 'labelDoping' : '', # StaticText "Doping"
+ "textCtrlDoping": "Sample characteristic doping level (if applicable)", # TextCtrl
+}
datasetconstraintpanel = {
- 'panelNameLabel' : '', # StaticText "Data Set Constraints"
- 'labelScaleFactor' : '', # StaticText "Scale Factor"
- 'textCtrlScaleFactor' : 'Data scale factor', # TextCtrl
- 'labelQdamp' : '', # StaticText "Qdamp"
- 'textCtrlQdamp' : 'Resolution dampening factor', # TextCtrl
- 'labelQbroad' : '', # StaticText "Qbroad"
- 'textCtrlQbroad' : 'Resolution peak broadening factor', # TextCtrl
- }
+ "panelNameLabel": "", # StaticText "Data Set Constraints"
+ "labelScaleFactor": "", # StaticText "Scale Factor"
+ "textCtrlScaleFactor": "Data scale factor", # TextCtrl
+ "labelQdamp": "", # StaticText "Qdamp"
+ "textCtrlQdamp": "Resolution dampening factor", # TextCtrl
+ "labelQbroad": "", # StaticText "Qbroad"
+ "textCtrlQbroad": "Resolution peak broadening factor", # TextCtrl
+}
datasetresultspanel = {
- 'panelNameLabel' : '', # StaticText "Data Set Results"
- 'labelScaleFactor' : '', # StaticText "Scale Factor"
- 'textCtrlScaleFactor' : 'Data scale factor', # TextCtrl
- 'labelQdamp' : '', # StaticText "Qdamp"
- 'textCtrlQdamp' : 'Resolution dampening factor', # TextCtrl
- 'labelQbroad' : '', # StaticText "Qbroad"
- 'textCtrlQbroad' : 'Resolution peak broadening factor', # TextCtrl
- }
-
+ "panelNameLabel": "", # StaticText "Data Set Results"
+ "labelScaleFactor": "", # StaticText "Scale Factor"
+ "textCtrlScaleFactor": "Data scale factor", # TextCtrl
+ "labelQdamp": "", # StaticText "Qdamp"
+ "textCtrlQdamp": "Resolution dampening factor", # TextCtrl
+ "labelQbroad": "", # StaticText "Qbroad"
+ "textCtrlQbroad": "Resolution peak broadening factor", # TextCtrl
+}
dopingseriespanel = {
-# 'instructionsLabel' : '', # StaticText "Select a fit from the tree on the left then add datasets and assign\ndoping elements and values below. If you have not set up a fit to be\nthe template for the series, hit cancel and rerun this macro once a\nfit has been created."
-# 'labelBaseElement' : '', # StaticText "Base element"
-# 'textCtrlBaseElement' : '', # TextCtrl
-# 'labelDopant' : '', # StaticText "Dopant"
-# 'textCtrlDopant' : '', # TextCtrl
- 'listCtrlFiles' : 'Click header to sort by doping', # AutoWidthListCtrl
-# 'buttonUp' : '', # BitmapButton
-# 'buttonDown' : '', # BitmapButton
-# 'buttonAdd' : '', # Button "Add"
-# 'buttonDelete' : '', # Button "Delete"
-# 'goButton' : '', # Button "OK"
-# 'cancelButton' : '', # Button "Cancel"
- }
+ # 'instructionsLabel' : '', # StaticText "Select a fit from the tree on the left then add datasets and assign\ndoping elements and values below. If you have not set up a fit to be\nthe template for the series, hit cancel and rerun this macro once a\nfit has been created."
+ # 'labelBaseElement' : '', # StaticText "Base element"
+ # 'textCtrlBaseElement' : '', # TextCtrl
+ # 'labelDopant' : '', # StaticText "Dopant"
+ # 'textCtrlDopant' : '', # TextCtrl
+ "listCtrlFiles": "Click header to sort by doping", # AutoWidthListCtrl
+ # 'buttonUp' : '', # BitmapButton
+ # 'buttonDown' : '', # BitmapButton
+ # 'buttonAdd' : '', # Button "Add"
+ # 'buttonDelete' : '', # Button "Delete"
+ # 'goButton' : '', # Button "OK"
+ # 'cancelButton' : '', # Button "Cancel"
+}
-phasepanel = _expand_tooltip_aliases({
-# 'sizerLatticeParameters_staticbox' : '', # StaticBox
-# 'sizerAdditionalParameters_staticbox' : '', # StaticBox
-# 'sizerAtoms_staticbox' : '', # StaticBox
-# 'sizerPanelName_staticbox' : '', # StaticBox
-# 'labelPanelName' : '', # StaticText "Phase Configuration"
- 'labelA' : '{textCtrlA}', # StaticText "a"
- 'textCtrlA' : 'Lattice parameter a', # TextCtrl
- 'labelB' : '{textCtrlB}', # StaticText "b"
- 'textCtrlB' : 'Lattice parameter b', # TextCtrl
- 'labelC' : '{textCtrlC}', # StaticText "c"
- 'textCtrlC' : 'Lattice parameter c', # TextCtrl
- 'labelAlpha' : '{textCtrlAlpha}', # StaticText "alpha"
- 'textCtrlAlpha' : 'Lattice angle alpha', # TextCtrl
- 'labelBeta' : '{textCtrlBeta}', # StaticText "beta"
- 'textCtrlBeta' : 'Lattice angle beta', # TextCtrl
- 'labelGamma' : '{textCtrlGamma}', # StaticText "gamma"
- 'textCtrlGamma' : 'Lattice angle gamma', # TextCtrl
- 'labelScaleFactor' : '{textCtrlScaleFactor}', # StaticText "Scale Factor"
- 'textCtrlScaleFactor' : 'Phase scale factor', # TextCtrl
- 'labelDelta1' : '{textCtrlDelta1}', # StaticText "delta1"
- 'textCtrlDelta1' : 'Linear atomic correlation factor', # TextCtrl
- 'labelDelta2' : '{textCtrlDelta2}', # StaticText "delta2"
- 'textCtrlDelta2' : 'Quadratic atomic correlation factor', # TextCtrl
- 'labelSratio' : '{textCtrlSratio}', # StaticText "sratio"
- 'textCtrlSratio' : 'Low r peak sharpening', # TextCtrl
- 'labelRcut' : '{textCtrlRcut}', # StaticText "rcut"
- 'textCtrlRcut' : 'Peak sharpening cutoff', # TextCtrl
- 'labelStepcut' : '{textCtrlStepcut}', # StaticText "stepcut"
- 'textCtrlStepcut' : 'Cutoff for profile step-function', #TextCtrl
- 'labelSpdiameter' : '{textCtrlSpdiameter}', # StaticText "Spdiameter"
- 'textCtrlSpdiameter' : 'Spherical nanoparticle amplitude correction',
-# 'labelIncludedPairs' : '', # StaticText "Included Pairs"
- 'textCtrlIncludedPairs' :
-"""[!]{element|indexOrRange|all}-[!]{element|indexOrRange|all}
+phasepanel = _expand_tooltip_aliases(
+ {
+ # 'sizerLatticeParameters_staticbox' : '', # StaticBox
+ # 'sizerAdditionalParameters_staticbox' : '', # StaticBox
+ # 'sizerAtoms_staticbox' : '', # StaticBox
+ # 'sizerPanelName_staticbox' : '', # StaticBox
+ # 'labelPanelName' : '', # StaticText "Phase Configuration"
+ "labelA": "{textCtrlA}", # StaticText "a"
+ "textCtrlA": "Lattice parameter a", # TextCtrl
+ "labelB": "{textCtrlB}", # StaticText "b"
+ "textCtrlB": "Lattice parameter b", # TextCtrl
+ "labelC": "{textCtrlC}", # StaticText "c"
+ "textCtrlC": "Lattice parameter c", # TextCtrl
+ "labelAlpha": "{textCtrlAlpha}", # StaticText "alpha"
+ "textCtrlAlpha": "Lattice angle alpha", # TextCtrl
+ "labelBeta": "{textCtrlBeta}", # StaticText "beta"
+ "textCtrlBeta": "Lattice angle beta", # TextCtrl
+ "labelGamma": "{textCtrlGamma}", # StaticText "gamma"
+ "textCtrlGamma": "Lattice angle gamma", # TextCtrl
+ "labelScaleFactor": "{textCtrlScaleFactor}", # StaticText "Scale Factor"
+ "textCtrlScaleFactor": "Phase scale factor", # TextCtrl
+ "labelDelta1": "{textCtrlDelta1}", # StaticText "delta1"
+ "textCtrlDelta1": "Linear atomic correlation factor", # TextCtrl
+ "labelDelta2": "{textCtrlDelta2}", # StaticText "delta2"
+ "textCtrlDelta2": "Quadratic atomic correlation factor", # TextCtrl
+ "labelSratio": "{textCtrlSratio}", # StaticText "sratio"
+ "textCtrlSratio": "Low r peak sharpening", # TextCtrl
+ "labelRcut": "{textCtrlRcut}", # StaticText "rcut"
+ "textCtrlRcut": "Peak sharpening cutoff", # TextCtrl
+ "labelStepcut": "{textCtrlStepcut}", # StaticText "stepcut"
+ "textCtrlStepcut": "Cutoff for profile step-function", # TextCtrl
+ "labelSpdiameter": "{textCtrlSpdiameter}", # StaticText "Spdiameter"
+ "textCtrlSpdiameter": "Spherical nanoparticle amplitude correction",
+ # 'labelIncludedPairs' : '', # StaticText "Included Pairs"
+ "textCtrlIncludedPairs": """[!]{element|indexOrRange|all}-[!]{element|indexOrRange|all}
Examples:
all-all all possible pairs
Na-Na only Na-Na pairs
@@ -137,58 +138,53 @@ def _expand_tooltip_aliases(ttps):
Na-1:4 pairs of Na and first 4 atoms
all-all, !Cl-!Cl exclude any pairs containing Cl
all-all, !Cl-, -!Cl same as previous
-1-all only pairs including the first atom""", # TextCtrl "all-all"
-# 'gridAtoms' : '', # AutoWidthLabelsGrid
-})
+1-all only pairs including the first atom""", # TextCtrl "all-all"
+ # 'gridAtoms' : '', # AutoWidthLabelsGrid
+ }
+)
plotpanel = {
-# 'xDataCombo' : '', # ComboBox
-# 'yDataList' : '', # KeyEventsListCtrl
- 'offsetLabel' : 'The vertical gap between stacked plots', # StaticText "offset"
-# 'offsetTextCtrl' : '', # TextCtrl
- 'plotButton' : 'Plot the selected data', # Button "Plot"
- 'resetButton' : 'Reset the plot configuration', # Button "Reset"
- }
+ # 'xDataCombo' : '', # ComboBox
+ # 'yDataList' : '', # KeyEventsListCtrl
+ "offsetLabel": "The vertical gap between stacked plots", # StaticText "offset"
+ # 'offsetTextCtrl' : '', # TextCtrl
+ "plotButton": "Plot the selected data", # Button "Plot"
+ "resetButton": "Reset the plot configuration", # Button "Reset"
+}
preferencespanel = {
- 'structureDirCheckBox' : (
+ "structureDirCheckBox": (
"Remember the structures directory across sessions. "
"If unchecked, the initial structures directory will "
"default to the current path."
),
-
- 'dataDirCheckBox' : (
+ "dataDirCheckBox": (
"Remember the data set directory across sessions. "
"If unchecked, the initial data set directory will "
"default to the current path."
),
-
- 'textCtrlViewer' : (
- "The name of the structure viewer executable, "
- "e.g., 'atomeye' or 'pymol'."
+ "textCtrlViewer": (
+ "The name of the structure viewer executable, " "e.g., 'atomeye' or 'pymol'."
),
-
- 'textCtrlArgument' : \
- """\
+ "textCtrlArgument": """\
The command-line arguments to the structure viewer.
'%s' represents the file name that will be passed to the viewer.
Command-line switches placed here will be passed as well.
E. g. '%s' or '-c %s' (for pymol).\
""",
-
- 'choiceFormat' : 'Choose a file format the structure viewer accepts.'
+ "choiceFormat": "Choose a file format the structure viewer accepts.",
}
temperatureseriespanel = {
-# 'instructionsLabel' : '', # StaticText "Select a fit from the tree on the left then add datasets and assign\ntemperatues below. If you have not set up a fit to be the template\nfor the series, hit cancel and rerun this macro once a fit has been\ncreated."
- 'listCtrlFiles' : 'Click header to sort by temperature', # AutoWidthListCtrl
-# 'buttonUp' : '', # BitmapButton
-# 'buttonDown' : '', # BitmapButton
-# 'buttonAdd' : '', # Button "Add"
-# 'buttonDelete' : '', # Button "Delete"
-# 'goButton' : '', # Button "OK"
-# 'cancelButton' : '', # Button "Cancel"
- }
+ # 'instructionsLabel' : '', # StaticText "Select a fit from the tree on the left then add datasets and assign\ntemperatues below. If you have not set up a fit to be the template\nfor the series, hit cancel and rerun this macro once a fit has been\ncreated."
+ "listCtrlFiles": "Click header to sort by temperature", # AutoWidthListCtrl
+ # 'buttonUp' : '', # BitmapButton
+ # 'buttonDown' : '', # BitmapButton
+ # 'buttonAdd' : '', # Button "Add"
+ # 'buttonDelete' : '', # Button "Delete"
+ # 'goButton' : '', # Button "OK"
+ # 'cancelButton' : '', # Button "Cancel"
+}
diff --git a/src/diffpy/pdfgui/gui/welcomepanel.py b/src/diffpy/pdfgui/gui/welcomepanel.py
index 048aa027..bd64844c 100644
--- a/src/diffpy/pdfgui/gui/welcomepanel.py
+++ b/src/diffpy/pdfgui/gui/welcomepanel.py
@@ -39,10 +39,12 @@ def __set_properties(self):
def __do_layout(self):
sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
- sizer_2.Add(self.bitmap_1, 0,
- wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
- sizer_1.Add(sizer_2, 1,
- wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
+ sizer_2.Add(
+ self.bitmap_1, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0
+ )
+ sizer_1.Add(
+ sizer_2, 1, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0
+ )
self.SetSizer(sizer_1)
sizer_1.Fit(self)
return
@@ -51,4 +53,5 @@ def __do_layout(self):
def refresh(self):
return
+
# end of class WelcomePanel
diff --git a/src/diffpy/pdfgui/gui/wxextensions/autowidthlabelsgrid.py b/src/diffpy/pdfgui/gui/wxextensions/autowidthlabelsgrid.py
index f722ed41..a980d764 100644
--- a/src/diffpy/pdfgui/gui/wxextensions/autowidthlabelsgrid.py
+++ b/src/diffpy/pdfgui/gui/wxextensions/autowidthlabelsgrid.py
@@ -21,12 +21,14 @@
import wx
import wx.grid
+
class AutoWidthLabelsGrid(wx.grid.Grid):
- '''wx grid which allows lables auto sizing'''
-# def __init__(self, parent, state, size):
-# wx.grid.Grid.__init__(self, parent, state, size)
+ """wx grid which allows lables auto sizing"""
+
+ # def __init__(self, parent, state, size):
+ # wx.grid.Grid.__init__(self, parent, state, size)
- def AutosizeLabels(self,rows=True,cols=False):
+ def AutosizeLabels(self, rows=True, cols=False):
# Common setup.
devContext = wx.ScreenDC()
devContext.SetFont(self.GetLabelFont())
@@ -36,7 +38,9 @@ def AutosizeLabels(self,rows=True,cols=False):
maxWidth = 0
curRow = self.GetNumberRows() - 1
while curRow >= 0:
- curWidth = devContext.GetTextExtent("M%s"%(self.GetRowLabelValue(curRow)))[0]
+ curWidth = devContext.GetTextExtent(
+ "M%s" % (self.GetRowLabelValue(curRow))
+ )[0]
if curWidth > maxWidth:
maxWidth = curWidth
curRow = curRow - 1
@@ -47,7 +51,9 @@ def AutosizeLabels(self,rows=True,cols=False):
maxHeight = 0
curCol = self.GetNumberCols() - 1
while curCol >= 0:
- (w,h,d,l) = devContext.GetFullTextExtent(self.GetColLabelValue(curCol))
+ (w, h, d, l) = devContext.GetFullTextExtent(
+ self.GetColLabelValue(curCol)
+ )
curHeight = h + d + l + 4
if curHeight > maxHeight:
maxHeight = curHeight
@@ -55,4 +61,5 @@ def AutosizeLabels(self,rows=True,cols=False):
self.SetColLabelSize(maxHeight)
return
+
# End of class AutoWidthLabelsGrid
diff --git a/src/diffpy/pdfgui/gui/wxextensions/listctrls.py b/src/diffpy/pdfgui/gui/wxextensions/listctrls.py
index 90f04d71..2ecb100b 100644
--- a/src/diffpy/pdfgui/gui/wxextensions/listctrls.py
+++ b/src/diffpy/pdfgui/gui/wxextensions/listctrls.py
@@ -30,18 +30,27 @@
class AutoWidthListCtrl(wx12.ListCtrl, listmix.ListCtrlAutoWidthMixin):
"""wxListCtrl subclass that automatically adjusts its column width."""
- def __init__(self, parent, ID, pos=wx.DefaultPosition,
- size=wx.DefaultSize, style=0, *args, **kwargs):
+
+ def __init__(
+ self,
+ parent,
+ ID,
+ pos=wx.DefaultPosition,
+ size=wx.DefaultSize,
+ style=0,
+ *args,
+ **kwargs
+ ):
wx12.ListCtrl.__init__(self, parent, ID, pos, size, style, *args, **kwargs)
listmix.ListCtrlAutoWidthMixin.__init__(self)
def clearSelections(self):
"""Clear all selections in the list."""
- for item in range( self.GetItemCount() ):
+ for item in range(self.GetItemCount()):
self.Select(item, on=0)
return
- def setSelection(self, itemtext = None):
+ def setSelection(self, itemtext=None):
"""Convenience function for simple selection of a list item by label.
itemtext -- The label of the item to select. If itemtext is None
@@ -57,8 +66,11 @@ def setSelection(self, itemtext = None):
self.Select(item)
self.Focus(item)
return item
+
+
# end AutoWidthListCtrl
+
class ColumnSortListCtrl(AutoWidthListCtrl, listmix.ColumnSorterMixin):
"""AutoWidthListCtrl subclass that sorts its columns when the column header
is pressed.
@@ -71,10 +83,18 @@ class ColumnSortListCtrl(AutoWidthListCtrl, listmix.ColumnSorterMixin):
columns. The sorting routine sorts the items in the ListCtrl by the entries
in this tuple.
"""
- def __init__(self, parent, ID, pos=wx.DefaultPosition,
- size=wx.DefaultSize, style=0, *args, **kwargs):
- AutoWidthListCtrl.__init__(self, parent, ID, pos, size, style,
- *args, **kwargs)
+
+ def __init__(
+ self,
+ parent,
+ ID,
+ pos=wx.DefaultPosition,
+ size=wx.DefaultSize,
+ style=0,
+ *args,
+ **kwargs
+ ):
+ AutoWidthListCtrl.__init__(self, parent, ID, pos, size, style, *args, **kwargs)
listmix.ListCtrlAutoWidthMixin.__init__(self)
def GetListCtrl(self):
@@ -104,24 +124,34 @@ def makeIDM(self):
for i in range(numrow):
infolist = []
for j in range(numcol):
- infolist.append( self.GetItem(i,j).GetText() )
- self.itemDataMap[i+1] = tuple(infolist)
- self.SetItemData(i, i+1)
+ infolist.append(self.GetItem(i, j).GetText())
+ self.itemDataMap[i + 1] = tuple(infolist)
+ self.SetItemData(i, i + 1)
return
+
# end ColumnSortListCtrl
+
class KeyEventsListCtrl(ColumnSortListCtrl):
"""ColumnSortListCtrl that catches key events and selects the item that
matches.
It only searches for items in the first column.
"""
- def __init__(self, parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize,
- style=0, *args, **kwargs):
- ColumnSortListCtrl.__init__(self, parent, id, pos, size, style, *args,
- **kwargs)
- self.typedText = ''
+
+ def __init__(
+ self,
+ parent,
+ id,
+ pos=wx.DefaultPosition,
+ size=wx.DefaultSize,
+ style=0,
+ *args,
+ **kwargs
+ ):
+ ColumnSortListCtrl.__init__(self, parent, id, pos, size, style, *args, **kwargs)
+ self.typedText = ""
self.Bind(wx.EVT_KEY_DOWN, self.OnKey)
def findPrefix(self, prefix):
@@ -138,7 +168,6 @@ def findPrefix(self, prefix):
return -1
-
def OnKey(self, evt):
key = evt.GetKeyCode()
@@ -171,12 +200,13 @@ def OnKey(self, evt):
self.setSelection(itemtext)
else:
- self.typedText = ''
+ self.typedText = ""
evt.Skip()
def OnKeyDown(self, evt):
pass
+
# End of class KeyEventsListCtrl
# verify inheritance of all ListCtrl classes
diff --git a/src/diffpy/pdfgui/gui/wxextensions/paneldialog.py b/src/diffpy/pdfgui/gui/wxextensions/paneldialog.py
index 136711d4..2106c15f 100644
--- a/src/diffpy/pdfgui/gui/wxextensions/paneldialog.py
+++ b/src/diffpy/pdfgui/gui/wxextensions/paneldialog.py
@@ -22,11 +22,13 @@
import wx
+
class PanelDialog(wx.Dialog):
"""This class will turn any panel into a dialog. Using this makes for
quicker development and encourages the developer to design a gui as a
collection of panels, instead of a monolithic mega-panel.
"""
+
def __init__(self, *args, **kwds):
"""Initialize the PanelDialog.
@@ -43,11 +45,10 @@ def __init__(self, *args, **kwds):
the argument.
"""
if not hasattr(kwds, "style"):
- kwds["style"] = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER
+ kwds["style"] = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
wx.Dialog.__init__(self, *args, **kwds)
return
-
def setPanel(self, panel):
"""Call this method to add the panel to the dialog."""
self.panel = panel
@@ -68,4 +69,5 @@ def __do_layout(self):
self.Layout()
return
+
# End of class PanelDialog
diff --git a/src/diffpy/pdfgui/gui/wxextensions/textctrlutils.py b/src/diffpy/pdfgui/gui/wxextensions/textctrlutils.py
index 7eaa0847..496b117f 100644
--- a/src/diffpy/pdfgui/gui/wxextensions/textctrlutils.py
+++ b/src/diffpy/pdfgui/gui/wxextensions/textctrlutils.py
@@ -20,6 +20,7 @@
import wx
+
def textCtrlAsGridCell(panel, event):
"""Process a textCtrl key event as if the textCtrl was a grid cell.
diff --git a/src/diffpy/pdfgui/gui/wxextensions/validators.py b/src/diffpy/pdfgui/gui/wxextensions/validators.py
index e2ac04dc..51688889 100644
--- a/src/diffpy/pdfgui/gui/wxextensions/validators.py
+++ b/src/diffpy/pdfgui/gui/wxextensions/validators.py
@@ -26,6 +26,7 @@
import wx
import string
+
class TextValidator(wx.Validator):
"""This validator is designed to check text input for wxTextCtrls. (It might
have uses in other widgets.) It can validate for letters only, digits only,
@@ -60,7 +61,7 @@ def Validate(self, win):
elif self.flag == DIGIT_ONLY:
if self.allowNeg:
- val1 = val[:1].lstrip('-') + val[1:]
+ val1 = val[:1].lstrip("-") + val[1:]
else:
val1 = val
return val1.isdigit()
@@ -99,14 +100,14 @@ def OnChar(self, event):
if self.flag == DIGIT_ONLY:
newval1 = newval
if self.allowNeg:
- newval1 = newval[:1].lstrip('-') + newval[1:]
+ newval1 = newval[:1].lstrip("-") + newval[1:]
if newval1.isdigit():
event.Skip()
return
if self.flag == FLOAT_ONLY:
try:
- x = float(newval+"1") # Catches "1e", a float to be
+ x = float(newval + "1") # Catches "1e", a float to be
if x >= 0 or self.allowNeg:
event.Skip()
return
@@ -128,4 +129,5 @@ def TransferToWindow(self):
def TransferFromWindow(self):
return True
+
# End of class TextValidator
diff --git a/src/diffpy/pdfgui/gui/wxextensions/wx12.py b/src/diffpy/pdfgui/gui/wxextensions/wx12.py
index 127adc51..4db4b455 100644
--- a/src/diffpy/pdfgui/gui/wxextensions/wx12.py
+++ b/src/diffpy/pdfgui/gui/wxextensions/wx12.py
@@ -25,51 +25,57 @@
import types
import wx
-WX3 = (wx.VERSION[0] == 3)
-WX4 = (wx.VERSION[0] == 4)
+WX3 = wx.VERSION[0] == 3
+WX4 = wx.VERSION[0] == 4
# ----------------------------------------------------------------------------
-class Menu(wx.Menu):
+class Menu(wx.Menu):
def Append(self, *args, **kwargs):
na = len(args)
if isinstance(args[0], wx.MenuItem):
return super(Menu, self).AppendItem(*args, **kwargs)
if na > 2 and isinstance(args[2], wx.Menu):
return super(Menu, self).AppendMenu(*args, **kwargs)
- plain_append = (
- isinstance(args[0], int) and
- (na > 1 and isinstance(args[1], str) or 'item' in kwargs))
+ plain_append = isinstance(args[0], int) and (
+ na > 1 and isinstance(args[1], str) or "item" in kwargs
+ )
if plain_append:
return super(Menu, self).Append(*args, **kwargs)
assert False, "unexpected argument types"
+
if WX4:
Menu = wx.Menu
# ----------------------------------------------------------------------------
+
class ListCtrl(wx.ListCtrl):
InsertItem = wx.ListCtrl.InsertStringItem
SetItem = wx.ListCtrl.SetStringItem
+
if WX4:
ListCtrl = wx.ListCtrl
# ----------------------------------------------------------------------------
+
class TreeCtrl(wx.TreeCtrl):
GetItemData = wx.TreeCtrl.GetPyData
SetItemData = wx.TreeCtrl.SetPyData
+
if WX4:
TreeCtrl = wx.TreeCtrl
# wx.ToolBar -----------------------------------------------------------------
+
def AddTool(self, *args, **kwargs):
return super(wx.ToolBar, self).AddLabelTool(*args, **kwargs)
@@ -79,6 +85,7 @@ def patchToolBarMethods(toolbar):
toolbar.AddTool = types.MethodType(AddTool, toolbar)
return
+
# Functions ------------------------------------------------------------------
IsMainThread = wx.Thread_IsMain if WX3 else wx.IsMainThread
diff --git a/src/diffpy/pdfgui/tests/__init__.py b/src/diffpy/pdfgui/tests/__init__.py
index d6f9b866..6de8a6d6 100644
--- a/src/diffpy/pdfgui/tests/__init__.py
+++ b/src/diffpy/pdfgui/tests/__init__.py
@@ -19,8 +19,8 @@
import unittest
-def testsuite(pattern=''):
- '''Create a unit tests suite for diffpy.pdfgui package.
+def testsuite(pattern=""):
+ """Create a unit tests suite for diffpy.pdfgui package.
Parameters
----------
@@ -33,14 +33,15 @@ def testsuite(pattern=''):
-------
suite : `unittest.TestSuite`
The TestSuite object containing the matching tests.
- '''
+ """
import re
from os.path import dirname
from itertools import chain
from pkg_resources import resource_filename
+
loader = unittest.defaultTestLoader
- thisdir = resource_filename(__name__, '')
- depth = __name__.count('.') + 1
+ thisdir = resource_filename(__name__, "")
+ depth = __name__.count(".") + 1
topdir = thisdir
for i in range(depth):
topdir = dirname(topdir)
@@ -50,12 +51,12 @@ def testsuite(pattern=''):
rx = re.compile(pattern)
tsuites = list(chain.from_iterable(suite_all))
tsok = all(isinstance(ts, unittest.TestSuite) for ts in tsuites)
- if not tsok: # pragma: no cover
+ if not tsok: # pragma: no cover
return suite_all
tcases = chain.from_iterable(tsuites)
for tc in tcases:
- tcwords = tc.id().split('.')
- shortname = '.'.join(tcwords[-3:])
+ tcwords = tc.id().split(".")
+ shortname = ".".join(tcwords[-3:])
if rx.search(shortname):
suite.addTest(tc)
# verify all tests are found for an empty pattern.
@@ -64,12 +65,12 @@ def testsuite(pattern=''):
def test():
- '''Execute all unit tests for the diffpy.pdfgui package.
+ """Execute all unit tests for the diffpy.pdfgui package.
Returns
-------
result : `unittest.TestResult`
- '''
+ """
suite = testsuite()
runner = unittest.TextTestRunner()
result = runner.run(suite)
@@ -77,19 +78,20 @@ def test():
def testdeps():
- '''Execute all unit tests for diffpy.pdfgui and its dependencies.
+ """Execute all unit tests for diffpy.pdfgui and its dependencies.
Returns
-------
result : `unittest.TestResult`
- '''
+ """
from importlib import import_module
- modulenames = '''
+
+ modulenames = """
diffpy.pdfgui.tests
diffpy.structure.tests
diffpy.pdffit2.tests
diffpy.utils.tests
- '''.split()
+ """.split()
suite = unittest.TestSuite()
for mname in modulenames:
mod = import_module(mname)
@@ -98,4 +100,5 @@ def testdeps():
result = runner.run(suite)
return result
+
# End of file
diff --git a/src/diffpy/pdfgui/tests/debug.py b/src/diffpy/pdfgui/tests/debug.py
index b80846c9..5dd08480 100644
--- a/src/diffpy/pdfgui/tests/debug.py
+++ b/src/diffpy/pdfgui/tests/debug.py
@@ -22,10 +22,11 @@
"""
-if __name__ == '__main__':
+if __name__ == "__main__":
import sys
from diffpy.pdfgui.tests import testsuite
- pattern = sys.argv[1] if len(sys.argv) > 1 else ''
+
+ pattern = sys.argv[1] if len(sys.argv) > 1 else ""
suite = testsuite(pattern)
suite.debug()
diff --git a/src/diffpy/pdfgui/tests/run.py b/src/diffpy/pdfgui/tests/run.py
index de665b3e..e3ea564d 100644
--- a/src/diffpy/pdfgui/tests/run.py
+++ b/src/diffpy/pdfgui/tests/run.py
@@ -19,15 +19,18 @@
"""
-if __name__ == '__main__':
+if __name__ == "__main__":
import sys
+
# show warnings by default
if not sys.warnoptions:
import os, warnings
+
warnings.simplefilter("default")
# also affect subprocesses
os.environ["PYTHONWARNINGS"] = "default"
from diffpy.pdfgui.tests import test
+
# produce zero exit code for a successful test
sys.exit(not test().wasSuccessful())
diff --git a/src/diffpy/pdfgui/tests/rundeps.py b/src/diffpy/pdfgui/tests/rundeps.py
index 31e02fee..6d2aabbd 100644
--- a/src/diffpy/pdfgui/tests/rundeps.py
+++ b/src/diffpy/pdfgui/tests/rundeps.py
@@ -19,9 +19,10 @@
"""
-if __name__ == '__main__':
+if __name__ == "__main__":
import sys
from diffpy.pdfgui.tests import testdeps
+
# produce zero exit code for a successful test
sys.exit(not testdeps().wasSuccessful())
diff --git a/src/diffpy/pdfgui/tests/showphasenotebookpanel.py b/src/diffpy/pdfgui/tests/showphasenotebookpanel.py
index 4a5381b2..18fb52ed 100644
--- a/src/diffpy/pdfgui/tests/showphasenotebookpanel.py
+++ b/src/diffpy/pdfgui/tests/showphasenotebookpanel.py
@@ -37,11 +37,10 @@ def __init__(self, *args, **kwds):
# choke, treeCtrlMain.GetSelections() emulation
self.window.treeCtrlMain = self.window
self.window.treeCtrlMain.GetSelections = self.dummy_dict
- #self.window.treeCtrlMain.GetBranchType = self.dummy_true
+ # self.window.treeCtrlMain.GetBranchType = self.dummy_true
self.window.quitting = False
self.test()
-
def dummy(self, *args, **kwds):
pass
@@ -51,10 +50,9 @@ def dummy_dict(self, *args, **kwds):
def dummy_true(self, *args, **kwds):
return True
-
def test(self):
- '''Testing code goes here'''
- project = LoadProject(datafile('lcmo.ddp'))
+ """Testing code goes here"""
+ project = LoadProject(datafile("lcmo.ddp"))
fstru = project.getPhases()[0]
self.window.configuration = fstru
self.window.results = fstru.refined
@@ -70,7 +68,7 @@ def OnInit(self):
return True
-if __name__ == '__main__':
+if __name__ == "__main__":
app = MyApp(0)
app.MainLoop()
diff --git a/src/diffpy/pdfgui/tests/testaboutdialog.py b/src/diffpy/pdfgui/tests/testaboutdialog.py
index 1e1131f9..df2d011c 100644
--- a/src/diffpy/pdfgui/tests/testaboutdialog.py
+++ b/src/diffpy/pdfgui/tests/testaboutdialog.py
@@ -26,8 +26,8 @@
# ----------------------------------------------------------------------------
-class TestDialogAbout(GUITestCase):
+class TestDialogAbout(GUITestCase):
def setUp(self):
self.app = wx.App()
self.dialog = aboutdialog.DialogAbout(None)
@@ -38,31 +38,30 @@ def tearDown(self):
self.app.Destroy()
return
-
def _clickbutton(self, button):
e = wx.CommandEvent(wx.EVT_BUTTON.typeId, button.Id)
self.dialog.ProcessEvent(e)
return
-
def test_LogoClicks(self):
"Check handling of clicks on various logos"
d = self.dialog
- stealurl = lambda u: setattr(self, 'url', u)
+ stealurl = lambda u: setattr(self, "url", u)
with overridewebbrowser(stealurl):
self._clickbutton(d.bitmap_button_nsf)
- self.assertTrue(self.url.endswith('www.nsf.gov'))
+ self.assertTrue(self.url.endswith("www.nsf.gov"))
self._clickbutton(d.bitmap_button_danse)
- self.assertTrue(self.url.endswith('danse.us'))
+ self.assertTrue(self.url.endswith("danse.us"))
self._clickbutton(d.bitmap_button_msu)
- self.assertTrue(self.url.endswith('www.msu.edu'))
+ self.assertTrue(self.url.endswith("www.msu.edu"))
self._clickbutton(d.bitmap_button_columbia)
- self.assertTrue(self.url.endswith('www.columbia.edu'))
+ self.assertTrue(self.url.endswith("www.columbia.edu"))
return
+
# End of class TestDialogAbout
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testcalculation.py b/src/diffpy/pdfgui/tests/testcalculation.py
index 6a3cfc1c..6ab9e7c9 100644
--- a/src/diffpy/pdfgui/tests/testcalculation.py
+++ b/src/diffpy/pdfgui/tests/testcalculation.py
@@ -24,44 +24,38 @@
##############################################################################
class TestCalculation(unittest.TestCase):
-
def setUp(self):
- self.calc = Calculation('calc')
+ self.calc = Calculation("calc")
return
def tearDown(self):
return
-# def test___init__(self):
-# """check Calculation.__init__()
-# """
-# return
-#
-# def test__getStrId(self):
-# """check Calculation._getStrId()
-# """
-# return
+ # def test___init__(self):
+ # """check Calculation.__init__()
+ # """
+ # return
+ #
+ # def test__getStrId(self):
+ # """check Calculation._getStrId()
+ # """
+ # return
def test_setRGrid(self):
- """check Calculation.setRGrid()
- """
+ """check Calculation.setRGrid()"""
# helper function
def rgriddata(calc):
rv = (calc.rmin, calc.rstep, calc.rmax, calc.rlen)
return rv
+
# original data:
rgd0 = rgriddata(self.calc)
# test input argument checks
- self.assertRaises(ControlValueError,
- self.calc.setRGrid, rmin=-1)
- self.assertRaises(ControlValueError,
- self.calc.setRGrid, rmin=0)
- self.assertRaises(ControlValueError,
- self.calc.setRGrid, rmin=500)
- self.assertRaises(ControlValueError,
- self.calc.setRGrid, rstep=0)
- self.assertRaises(ControlValueError,
- self.calc.setRGrid, rmax=1e-10)
+ self.assertRaises(ControlValueError, self.calc.setRGrid, rmin=-1)
+ self.assertRaises(ControlValueError, self.calc.setRGrid, rmin=0)
+ self.assertRaises(ControlValueError, self.calc.setRGrid, rmin=500)
+ self.assertRaises(ControlValueError, self.calc.setRGrid, rstep=0)
+ self.assertRaises(ControlValueError, self.calc.setRGrid, rmax=1e-10)
# data should be the same
self.assertEqual(rgd0, rgriddata(self.calc))
# check round-offs for very close values
@@ -77,6 +71,7 @@ def rgriddata(calc):
self.assertEqual(0.7, self.calc.rstep)
return
+
# def test_start(self):
# """check Calculation.start()
# """
@@ -145,7 +140,7 @@ def rgriddata(calc):
# End of class TestCalculation
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testconstraint.py b/src/diffpy/pdfgui/tests/testconstraint.py
index 6425e391..e81bc05b 100644
--- a/src/diffpy/pdfgui/tests/testconstraint.py
+++ b/src/diffpy/pdfgui/tests/testconstraint.py
@@ -27,58 +27,52 @@ class TestConstraint(unittest.TestCase):
"""test methods of TestConstraint"""
def setUp(self):
- self.c = Constraint('@1')
+ self.c = Constraint("@1")
return
def test___init__(self):
- """check Constraint.__init__()
- """
+ """check Constraint.__init__()"""
self.assertTrue(1 in self.c.parguess)
self.assertEqual(1, len(self.c.parguess))
- c1 = Constraint('2*@2 + 3.0', 13.0)
+ c1 = Constraint("2*@2 + 3.0", 13.0)
self.assertEqual(1, len(c1.parguess))
self.assertEqual(5.0, c1.parguess[2])
return
def test_guess(self):
- """check Constraint.guess()
- """
+ """check Constraint.guess()"""
self.c.guess(9)
self.assertEqual(1, len(self.c.parguess))
self.assertEqual(9, self.c.parguess[1])
return
def test___setattr__(self):
- """check Constraint.__setattr__()
- """
+ """check Constraint.__setattr__()"""
self.c.guess(9)
- self.c.formula = '9*@7 +18'
+ self.c.formula = "9*@7 +18"
self.assertEqual(1, len(self.c.parguess))
self.assertEqual(-1.0, self.c.parguess[7])
- self.assertRaises(ControlSyntaxError, setattr,
- self.c, 'formula', '')
- self.assertRaises(ControlSyntaxError, setattr,
- self.c, 'formula', '@@1')
- self.assertRaises(ControlSyntaxError, setattr, self.c,
- 'formula', '@1*/55')
- self.assertRaises(ControlSyntaxError, setattr, self.c,
- 'formula', '@1**3')
+ self.assertRaises(ControlSyntaxError, setattr, self.c, "formula", "")
+ self.assertRaises(ControlSyntaxError, setattr, self.c, "formula", "@@1")
+ self.assertRaises(ControlSyntaxError, setattr, self.c, "formula", "@1*/55")
+ self.assertRaises(ControlSyntaxError, setattr, self.c, "formula", "@1**3")
return
def test_evalFormula(self):
- """check Constraint.evalFormula()
- """
- value = self.c.evalFormula({1 : 5.0})
+ """check Constraint.evalFormula()"""
+ value = self.c.evalFormula({1: 5.0})
self.assertEqual(5.0, value)
- self.c.formula = 'sin(@3)'
+ self.c.formula = "sin(@3)"
from math import pi, sqrt
- value = self.c.evalFormula({3 : pi/3.0})
+
+ value = self.c.evalFormula({3: pi / 3.0})
self.assertAlmostEqual(sqrt(0.75), value, 8)
return
+
# End of class TestConstraint
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testdatasetpanels.py b/src/diffpy/pdfgui/tests/testdatasetpanels.py
index d748c22c..8d01dd40 100644
--- a/src/diffpy/pdfgui/tests/testdatasetpanels.py
+++ b/src/diffpy/pdfgui/tests/testdatasetpanels.py
@@ -26,8 +26,8 @@
# ----------------------------------------------------------------------------
-class TestDataSetPanel(GUITestCase):
+class TestDataSetPanel(GUITestCase):
@classmethod
def setUpClass(cls):
GUITestCase.setUpClass()
@@ -40,7 +40,6 @@ def setUpClass(cls):
cls.frame.makeTreeSelection(dsids[0])
return
-
@classmethod
def tearDownClass(cls):
cls.frame.Close()
@@ -48,20 +47,17 @@ def tearDownClass(cls):
GUITestCase.tearDownClass()
return
-
def setUp(self):
self.pconfigure = self.frame.rightPanel.configurePanel
self.pconstraints = self.frame.rightPanel.constraintPanel
self.presults = self.frame.rightPanel.resultsPanel
return
-
def _selectpage(self, page):
nb = self.frame.rightPanel.dataSetNotebook
nb.SetSelection(page)
return
-
def _selectsampling(self, selection):
"select specified item in sampling radio box"
rbxid = self.pconfigure.radioBoxSampling.Id
@@ -71,24 +67,21 @@ def _selectsampling(self, selection):
self.pconfigure.ProcessEvent(e)
return
-
def test_refreshSelectedPage(self):
"check DataSetPanel.refreshSelectedPage method"
# cover all if branches in refreshSelectedPage
self._selectpage(2)
return
-
def test_restrictConstrainedParameters(self):
"check DataSetConfigurePanel.restrictConstrainedParameters method"
self._selectpage(0)
panel = self.pconfigure
self.assertFalse(panel.textCtrlScaleFactor.IsEditable())
self.assertTrue(panel.textCtrlQbroad.IsEditable())
- self.assertEqual('@100', tooltiptext(panel.textCtrlScaleFactor))
+ self.assertEqual("@100", tooltiptext(panel.textCtrlScaleFactor))
return
-
def test_onSampling(self):
"check DataSetConfigurePanel.onSampling method"
self._selectpage(0)
@@ -105,19 +98,18 @@ def test_onSampling(self):
self.assertEqual(27, panel.configuration.qmax)
return
-
def test_setConstraintsData(self):
"check DataSetConstraintPanel.setConstraintsData method"
self._selectpage(1)
panel = self.pconstraints
- self.assertEqual('@100', panel.textCtrlScaleFactor.GetValue())
- self.assertEqual('Data scale factor',
- tooltiptext(panel.textCtrlScaleFactor))
+ self.assertEqual("@100", panel.textCtrlScaleFactor.GetValue())
+ self.assertEqual("Data scale factor", tooltiptext(panel.textCtrlScaleFactor))
return
+
# End of class TestDataSetPanel
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testdopingseriespanel.py b/src/diffpy/pdfgui/tests/testdopingseriespanel.py
index 12fafdd6..be8721dd 100644
--- a/src/diffpy/pdfgui/tests/testdopingseriespanel.py
+++ b/src/diffpy/pdfgui/tests/testdopingseriespanel.py
@@ -27,14 +27,14 @@
# ----------------------------------------------------------------------------
-class TestDopingSeriesPanel(GUITestCase):
+class TestDopingSeriesPanel(GUITestCase):
def setUp(self):
self.app = wx.App()
self.frame = wx.Frame(None)
self.panel = DopingSeriesPanel(self.frame)
self.panel.mainFrame = self._mockUpMainFrame()
- self.panel.mainFrame.workpath = datafile('')
+ self.panel.mainFrame.workpath = datafile("")
return
def tearDown(self):
@@ -42,11 +42,10 @@ def tearDown(self):
self.app.Destroy()
return
-
def test_onAdd(self):
"Check DopingSeriesPanel.onAdd"
panel = self.panel
- paths = ['x000.gr', 'x020.gr', 'lcmo_00.gr', 'lcmo_20.gr']
+ paths = ["x000.gr", "x020.gr", "lcmo_00.gr", "lcmo_20.gr"]
paths = [datafile(p) for p in paths]
with overridefiledialog(wx.ID_OK, paths):
panel.onAdd(None)
@@ -54,9 +53,10 @@ def test_onAdd(self):
self.assertEqual([0, 20, 0, 0.2], [xf[0] for xf in panel.datasets])
return
+
# End of class TestDopingSeriesPanel
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testextendedplotframe.py b/src/diffpy/pdfgui/tests/testextendedplotframe.py
index 7c9ffec8..6d3c2d6a 100644
--- a/src/diffpy/pdfgui/tests/testextendedplotframe.py
+++ b/src/diffpy/pdfgui/tests/testextendedplotframe.py
@@ -29,8 +29,8 @@
# ----------------------------------------------------------------------------
-class TestExtendedPlotFrame(GUITestCase):
+class TestExtendedPlotFrame(GUITestCase):
def setUp(self):
self.app = wx.App()
self.frame = ExtendedPlotFrame(None)
@@ -46,35 +46,33 @@ def _clicktoolbar(self, tbid):
self.frame.toolbar.ProcessEvent(e)
return
-
def test_insertCurve(self):
"Check ExtendedPlotFrame.insertCurve"
x = numpy.linspace(-5, 5)
ys = numpy.sin(x)
- style = {'with': 'lines', 'color': 'blue',
- 'line': 'solid', 'width': 2.3}
+ style = {"with": "lines", "color": "blue", "line": "solid", "width": 2.3}
line = self.frame.insertCurve(x, ys, style)
self.assertEqual(2.3, line.get_linewidth())
return
-
def test_savePlotData(self):
self.frame.plotter = Plotter()
# intercept plotter.export to avoid plot setup and temporary files
- self.frame.plotter.export = lambda fn: setattr(self, 'spd', fn)
- self.spd = ''
- with overridefiledialog(wx.ID_OK, ['testfile.dat']):
+ self.frame.plotter.export = lambda fn: setattr(self, "spd", fn)
+ self.spd = ""
+ with overridefiledialog(wx.ID_OK, ["testfile.dat"]):
self._clicktoolbar(epf.DATA_SAVE_ID)
- self.assertEqual('testfile.dat', self.spd)
- self.spd = ''
- with overridefiledialog(wx.ID_CANCEL, ['testfile2.dat']):
+ self.assertEqual("testfile.dat", self.spd)
+ self.spd = ""
+ with overridefiledialog(wx.ID_CANCEL, ["testfile2.dat"]):
self._clicktoolbar(epf.DATA_SAVE_ID)
- self.assertEqual('', self.spd)
+ self.assertEqual("", self.spd)
return
+
# End of class TestExtendedPlotFrame
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testfitdataset.py b/src/diffpy/pdfgui/tests/testfitdataset.py
index 64c3b6dd..906b9dad 100644
--- a/src/diffpy/pdfgui/tests/testfitdataset.py
+++ b/src/diffpy/pdfgui/tests/testfitdataset.py
@@ -26,8 +26,8 @@
# ----------------------------------------------------------------------------
-class TestRoutines(unittest.TestCase):
+class TestRoutines(unittest.TestCase):
def setUp(self):
return
@@ -35,8 +35,7 @@ def tearDown(self):
return
def test_grid_interpolation(self):
- """check grid_interpolation()
- """
+ """check grid_interpolation()"""
x0 = numpy.arange(-5, 5, 0.25)
y0 = numpy.sin(x0)
x1 = [-6, x0[0], -0.2, x0[-1], 37]
@@ -69,128 +68,129 @@ def test_grid_interpolation(self):
self.assertEqual(0, y4[2])
return
+
# End of class TestRoutines
# ----------------------------------------------------------------------------
+
class TestFitDataSet(unittest.TestCase):
-# def setUp(self):
-# return
-#
-# def tearDown(self):
-# return
-#
-# def test___init__(self):
-# """check FitDataSet.__init__()
-# """
-# return
-#
-# def test___setattr__(self):
-# """check FitDataSet.__setattr__()
-# """
-# return
-#
-# def test___getattr__(self):
-# """check FitDataSet.__getattr__()
-# """
-# return
-#
-# def test__getStrId(self):
-# """check FitDataSet._getStrId()
-# """
-# return
-#
-# def test_getYNames(self):
-# """check FitDataSet.getYNames()
-# """
-# return
-#
-# def test_getXNames(self):
-# """check FitDataSet.getXNames()
-# """
-# return
-#
-# def test_getData(self):
-# """check FitDataSet.getData()
-# """
-# return
-#
-# def test_clear(self):
-# """check FitDataSet.clear()
-# """
-# return
-#
-# def test_clearRefined(self):
-# """check FitDataSet.clearRefined()
-# """
-# return
-#
-# def test_obtainRefined(self):
-# """check FitDataSet.obtainRefined()
-# """
-# return
-#
-# def test_read(self):
-# """check FitDataSet.read()
-# """
-# return
-#
-# def test__updateRcalcRange(self):
-# """check FitDataSet._updateRcalcRange()
-# """
-# return
-#
-# def test_readObs(self):
-# """check FitDataSet.readObs()
-# """
-# return
-#
-# def test_readStr(self):
-# """check FitDataSet.readStr()
-# """
-# return
-#
-# def test_readObsStr(self):
-# """check FitDataSet.readObsStr()
-# """
-# return
-#
-# def test_write(self):
-# """check FitDataSet.write()
-# """
-# return
-#
-# def test_writeCalc(self):
-# """check FitDataSet.writeCalc()
-# """
-# return
-#
-# def test_writeStr(self):
-# """check FitDataSet.writeStr()
-# """
-# return
-#
-# def test_writeCalcStr(self):
-# """check FitDataSet.writeCalcStr()
-# """
-# return
-#
-# def test_writeObs(self):
-# """check FitDataSet.writeObs()
-# """
-# return
-#
-# def test_writeObsStr(self):
-# """check FitDataSet.writeObsStr()
-# """
-# return
+ # def setUp(self):
+ # return
+ #
+ # def tearDown(self):
+ # return
+ #
+ # def test___init__(self):
+ # """check FitDataSet.__init__()
+ # """
+ # return
+ #
+ # def test___setattr__(self):
+ # """check FitDataSet.__setattr__()
+ # """
+ # return
+ #
+ # def test___getattr__(self):
+ # """check FitDataSet.__getattr__()
+ # """
+ # return
+ #
+ # def test__getStrId(self):
+ # """check FitDataSet._getStrId()
+ # """
+ # return
+ #
+ # def test_getYNames(self):
+ # """check FitDataSet.getYNames()
+ # """
+ # return
+ #
+ # def test_getXNames(self):
+ # """check FitDataSet.getXNames()
+ # """
+ # return
+ #
+ # def test_getData(self):
+ # """check FitDataSet.getData()
+ # """
+ # return
+ #
+ # def test_clear(self):
+ # """check FitDataSet.clear()
+ # """
+ # return
+ #
+ # def test_clearRefined(self):
+ # """check FitDataSet.clearRefined()
+ # """
+ # return
+ #
+ # def test_obtainRefined(self):
+ # """check FitDataSet.obtainRefined()
+ # """
+ # return
+ #
+ # def test_read(self):
+ # """check FitDataSet.read()
+ # """
+ # return
+ #
+ # def test__updateRcalcRange(self):
+ # """check FitDataSet._updateRcalcRange()
+ # """
+ # return
+ #
+ # def test_readObs(self):
+ # """check FitDataSet.readObs()
+ # """
+ # return
+ #
+ # def test_readStr(self):
+ # """check FitDataSet.readStr()
+ # """
+ # return
+ #
+ # def test_readObsStr(self):
+ # """check FitDataSet.readObsStr()
+ # """
+ # return
+ #
+ # def test_write(self):
+ # """check FitDataSet.write()
+ # """
+ # return
+ #
+ # def test_writeCalc(self):
+ # """check FitDataSet.writeCalc()
+ # """
+ # return
+ #
+ # def test_writeStr(self):
+ # """check FitDataSet.writeStr()
+ # """
+ # return
+ #
+ # def test_writeCalcStr(self):
+ # """check FitDataSet.writeCalcStr()
+ # """
+ # return
+ #
+ # def test_writeObs(self):
+ # """check FitDataSet.writeObs()
+ # """
+ # return
+ #
+ # def test_writeObsStr(self):
+ # """check FitDataSet.writeObsStr()
+ # """
+ # return
def test__resampledPDFDataSet(self):
- """check FitDataSet._resampledPDFDataSet()
- """
+ """check FitDataSet._resampledPDFDataSet()"""
fNi_data = datafile("Ni_2-8.chi.gr")
- fds = FitDataSet('Ni')
+ fds = FitDataSet("Ni")
fds.read(fNi_data)
npts = len(fds.rcalc)
rds = fds._resampledPDFDataSet()
@@ -209,6 +209,7 @@ def test__resampledPDFDataSet(self):
self.assertEqual(npts1, len(rds1.dGobs))
return
+
# def test_writeResampledObs(self):
# """check FitDataSet.writeResampledObs()
# """
@@ -378,7 +379,7 @@ def test__resampledPDFDataSet(self):
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testfitstructure.py b/src/diffpy/pdfgui/tests/testfitstructure.py
index f7d8256b..24976e6d 100644
--- a/src/diffpy/pdfgui/tests/testfitstructure.py
+++ b/src/diffpy/pdfgui/tests/testfitstructure.py
@@ -15,100 +15,84 @@
# ----------------------------------------------------------------------------
-class TestFitStructure(unittest.TestCase):
-
+class TestFitStructure(unittest.TestCase):
def setUp(self):
- self.stru = FitStructure('noname')
+ self.stru = FitStructure("noname")
return
-
def tearDown(self):
return
-
def test___init__(self):
- """check FitStructure.__init__()
- """
+ """check FitStructure.__init__()"""
stru = self.stru
- self.assertEqual('noname', stru.name)
- self.assertEqual('all-all', stru.selected_pairs)
+ self.assertEqual("noname", stru.name)
+ self.assertEqual("all-all", stru.selected_pairs)
return
+ # def test__update_custom_spacegroup(self):
+ # """check FitStructure._update_custom_spacegroup()
+ # """
+ # return
-# def test__update_custom_spacegroup(self):
-# """check FitStructure._update_custom_spacegroup()
-# """
-# return
-
-
-# def test_read(self):
-# """check FitStructure.read()
-# """
-# return
-
-
-# def test_readStr(self):
-# """check FitStructure.readStr()
-# """
-# return
+ # def test_read(self):
+ # """check FitStructure.read()
+ # """
+ # return
+ # def test_readStr(self):
+ # """check FitStructure.readStr()
+ # """
+ # return
def test___getattr__(self):
- """check FitStructure.__getattr__()
- """
+ """check FitStructure.__getattr__()"""
stru = self.stru
self.assertTrue(stru is stru.initial)
- self.assertRaises(AttributeError, eval,
- 'stru.notdefined', locals())
+ self.assertRaises(AttributeError, eval, "stru.notdefined", locals())
return
-
def test__getStrId(self):
- """check FitStructure._getStrId()
- """
+ """check FitStructure._getStrId()"""
stru = self.stru
- self.assertEqual('p_noname', stru._getStrId())
+ self.assertEqual("p_noname", stru._getStrId())
return
+ # def test_clearRefined(self):
+ # """check FitStructure.clearRefined()
+ # """
+ # return
-# def test_clearRefined(self):
-# """check FitStructure.clearRefined()
-# """
-# return
-
-
-# def test_obtainRefined(self):
-# """check FitStructure.obtainRefined()
-# """
-# return
-
+ # def test_obtainRefined(self):
+ # """check FitStructure.obtainRefined()
+ # """
+ # return
def test_findParameters(self):
- """check FitStructure.findParameters()
- """
+ """check FitStructure.findParameters()"""
stru = self.stru
- stru.read(datafile('Ni.stru'), format='pdffit')
- for a in stru.initial: a.Uiso = 0.00126651
- stru.constraints['lat(4)'] = Constraint('@1')
- stru.constraints['y(2)'] = Constraint('@3 + 0.4')
- stru.constraints['u11(3)'] = Constraint('@7 * 3.0')
+ stru.read(datafile("Ni.stru"), format="pdffit")
+ for a in stru.initial:
+ a.Uiso = 0.00126651
+ stru.constraints["lat(4)"] = Constraint("@1")
+ stru.constraints["y(2)"] = Constraint("@3 + 0.4")
+ stru.constraints["u11(3)"] = Constraint("@7 * 3.0")
pd = stru.findParameters()
self.assertEqual([1, 3, 7], sorted(pd.keys()))
self.assertEqual(90, pd[1].initialValue())
self.assertEqual(0.5 - 0.4, pd[3].initialValue())
- self.assertEqual(0.00126651/3.0, pd[7].initialValue())
+ self.assertEqual(0.00126651 / 3.0, pd[7].initialValue())
return
-
def test_applyParameters(self):
- """check FitStructure.applyParameters()
- """
+ """check FitStructure.applyParameters()"""
stru = self.stru
- stru.read(datafile('Ni.stru'), format='pdffit')
- for a in stru.initial: a.Uiso = 0.00126651
- stru.constraints['lat(4)'] = Constraint('@1')
- stru.constraints['u11(3)'] = Constraint('@7 * 3.0')
+ stru.read(datafile("Ni.stru"), format="pdffit")
+ for a in stru.initial:
+ a.Uiso = 0.00126651
+ stru.constraints["lat(4)"] = Constraint("@1")
+ stru.constraints["u11(3)"] = Constraint("@7 * 3.0")
pd = stru.findParameters()
# adjust Parameter instances in pd
pd[1].setInitial(99)
@@ -122,165 +106,152 @@ def test_applyParameters(self):
self.assertEqual(89, stru.lattice.alpha)
return
-
def test_changeParameterIndex(self):
- """check FitStructure.changeParameterIndex()
- """
+ """check FitStructure.changeParameterIndex()"""
stru = self.stru
- stru.constraints['pscale'] = Constraint('@7+3')
+ stru.constraints["pscale"] = Constraint("@7+3")
stru.changeParameterIndex(7, 13)
- self.assertEqual('@13+3', stru.constraints['pscale'].formula)
+ self.assertEqual("@13+3", stru.constraints["pscale"].formula)
stru.changeParameterIndex(2, 19)
- self.assertEqual('@13+3', stru.constraints['pscale'].formula)
+ self.assertEqual("@13+3", stru.constraints["pscale"].formula)
return
-
# tested in insertAtoms and deleteAtoms
-# def test__popAtomConstraints(self):
-# """check FitStructure._popAtomConstraints()
-# """
-# return
-
-
-# def test__restoreAtomConstraints(self):
-# """check FitStructure._restoreAtomConstraints()
-# """
-# return
+ # def test__popAtomConstraints(self):
+ # """check FitStructure._popAtomConstraints()
+ # """
+ # return
+ # def test__restoreAtomConstraints(self):
+ # """check FitStructure._restoreAtomConstraints()
+ # """
+ # return
def test_insertAtoms(self):
- """check FitStructure.insertAtoms()
- """
+ """check FitStructure.insertAtoms()"""
from diffpy.structure import Atom
+
stru = self.stru
- stru.read(datafile('Ni.stru'), format='pdffit')
- cns = Constraint('@1')
- stru.constraints['x(2)'] = cns
- stru.insertAtoms(0, [Atom('Na', (0, 0, 0))])
+ stru.read(datafile("Ni.stru"), format="pdffit")
+ cns = Constraint("@1")
+ stru.constraints["x(2)"] = cns
+ stru.insertAtoms(0, [Atom("Na", (0, 0, 0))])
self.assertEqual(5, len(stru))
self.assertEqual(1, len(stru.constraints))
- self.assertTrue(cns is stru.constraints['x(3)'])
- stru.insertAtoms(5, [Atom('Cl', (0, 0, 0))])
- self.assertTrue(['x(3)'] == list(stru.constraints.keys()))
+ self.assertTrue(cns is stru.constraints["x(3)"])
+ stru.insertAtoms(5, [Atom("Cl", (0, 0, 0))])
+ self.assertTrue(["x(3)"] == list(stru.constraints.keys()))
return
-
def test_deleteAtoms(self):
- """check FitStructure.deleteAtoms()
- """
+ """check FitStructure.deleteAtoms()"""
stru = self.stru
- stru.read(datafile('Ni.stru'), format='pdffit')
- cns = Constraint('@1')
- stru.constraints['x(2)'] = cns
+ stru.read(datafile("Ni.stru"), format="pdffit")
+ cns = Constraint("@1")
+ stru.constraints["x(2)"] = cns
stru.deleteAtoms([3])
- self.assertEqual(['x(2)'], list(stru.constraints.keys()))
+ self.assertEqual(["x(2)"], list(stru.constraints.keys()))
self.assertTrue(cns is next(iter(stru.constraints.values())))
stru.deleteAtoms([0])
- self.assertEqual(['x(1)'], list(stru.constraints.keys()))
+ self.assertEqual(["x(1)"], list(stru.constraints.keys()))
self.assertTrue(cns is next(iter(stru.constraints.values())))
stru.deleteAtoms([0])
self.assertEqual({}, stru.constraints)
return
-
-# def test_expandSuperCell(self):
-# """check FitStructure.expandSuperCell()
-# """
-# return
-#
-#
-# def test_isSpaceGroupPossible(self):
-# """check FitStructure.isSpaceGroupPossible()
-# """
-# return
-#
-#
-# def test_getSpaceGroupList(self):
-# """check FitStructure.getSpaceGroupList()
-# """
-# return
-#
-#
-# def test_getSpaceGroup(self):
-# """check FitStructure.getSpaceGroup()
-# """
-# return
-#
-#
-# def test_expandAsymmetricUnit(self):
-# """check FitStructure.expandAsymmetricUnit()
-# """
-# return
-#
-#
-# def test_applySymmetryConstraints(self):
-# """check FitStructure.applySymmetryConstraints()
-# """
-# return
-#
-#
-# def test_setSelectedPairs(self):
-# """check FitStructure.setSelectedPairs()
-# """
-# return
-#
-#
-# def test_getSelectedPairs(self):
-# """check FitStructure.getSelectedPairs()
-# """
-# return
-
+ # def test_expandSuperCell(self):
+ # """check FitStructure.expandSuperCell()
+ # """
+ # return
+ #
+ #
+ # def test_isSpaceGroupPossible(self):
+ # """check FitStructure.isSpaceGroupPossible()
+ # """
+ # return
+ #
+ #
+ # def test_getSpaceGroupList(self):
+ # """check FitStructure.getSpaceGroupList()
+ # """
+ # return
+ #
+ #
+ # def test_getSpaceGroup(self):
+ # """check FitStructure.getSpaceGroup()
+ # """
+ # return
+ #
+ #
+ # def test_expandAsymmetricUnit(self):
+ # """check FitStructure.expandAsymmetricUnit()
+ # """
+ # return
+ #
+ #
+ # def test_applySymmetryConstraints(self):
+ # """check FitStructure.applySymmetryConstraints()
+ # """
+ # return
+ #
+ #
+ # def test_setSelectedPairs(self):
+ # """check FitStructure.setSelectedPairs()
+ # """
+ # return
+ #
+ #
+ # def test_getSelectedPairs(self):
+ # """check FitStructure.getSelectedPairs()
+ # """
+ # return
def test_getPairSelectionFlags(self):
- """check FitStructure.getPairSelectionFlags()
- """
+ """check FitStructure.getPairSelectionFlags()"""
cdse = self.stru
- cdse.read(datafile('CdSe_bulk_wur.stru'), format='pdffit')
- self.assertEqual('all-all', cdse.getSelectedPairs())
+ cdse.read(datafile("CdSe_bulk_wur.stru"), format="pdffit")
+ self.assertEqual("all-all", cdse.getSelectedPairs())
psf = cdse.getPairSelectionFlags()
- self.assertEqual(4 * [True], psf['firstflags'])
- self.assertEqual(4 * [True], psf['secondflags'])
- psf = cdse.getPairSelectionFlags('Cd-Cd')
- self.assertEqual(2 * [True] + 2 * [False], psf['firstflags'])
- self.assertEqual(psf['firstflags'], psf['secondflags'])
- psf = cdse.getPairSelectionFlags('all-all, !Cd-')
- self.assertEqual(2 * [False] + 2 * [True], psf['firstflags'])
- self.assertEqual(4 * [True], psf['secondflags'])
- psf = cdse.getPairSelectionFlags('all-all, -!Cd')
- self.assertEqual(4 * [True], psf['firstflags'])
- self.assertEqual(2 * [False] + 2 * [True], psf['secondflags'])
- psf = cdse.getPairSelectionFlags('Cd-3:4')
- self.assertEqual(2 * [True] + 2 * [False], psf['firstflags'])
- self.assertEqual(2 * [False] + 2 * [True], psf['secondflags'])
- psf = cdse.getPairSelectionFlags('all-all, !Se-!Se')
- self.assertEqual(2 * [True] + 2 * [False], psf['firstflags'])
- self.assertEqual(2 * [True] + 2 * [False], psf['secondflags'])
- psf = cdse.getPairSelectionFlags('all-all, !Se-, -!Se')
- self.assertEqual(2 * [True] + 2 * [False], psf['firstflags'])
- self.assertEqual(2 * [True] + 2 * [False], psf['secondflags'])
- psf = cdse.getPairSelectionFlags('1-all')
- self.assertEqual([True] + 3 * [False], psf['firstflags'])
- self.assertEqual(4 * [True], psf['secondflags'])
+ self.assertEqual(4 * [True], psf["firstflags"])
+ self.assertEqual(4 * [True], psf["secondflags"])
+ psf = cdse.getPairSelectionFlags("Cd-Cd")
+ self.assertEqual(2 * [True] + 2 * [False], psf["firstflags"])
+ self.assertEqual(psf["firstflags"], psf["secondflags"])
+ psf = cdse.getPairSelectionFlags("all-all, !Cd-")
+ self.assertEqual(2 * [False] + 2 * [True], psf["firstflags"])
+ self.assertEqual(4 * [True], psf["secondflags"])
+ psf = cdse.getPairSelectionFlags("all-all, -!Cd")
+ self.assertEqual(4 * [True], psf["firstflags"])
+ self.assertEqual(2 * [False] + 2 * [True], psf["secondflags"])
+ psf = cdse.getPairSelectionFlags("Cd-3:4")
+ self.assertEqual(2 * [True] + 2 * [False], psf["firstflags"])
+ self.assertEqual(2 * [False] + 2 * [True], psf["secondflags"])
+ psf = cdse.getPairSelectionFlags("all-all, !Se-!Se")
+ self.assertEqual(2 * [True] + 2 * [False], psf["firstflags"])
+ self.assertEqual(2 * [True] + 2 * [False], psf["secondflags"])
+ psf = cdse.getPairSelectionFlags("all-all, !Se-, -!Se")
+ self.assertEqual(2 * [True] + 2 * [False], psf["firstflags"])
+ self.assertEqual(2 * [True] + 2 * [False], psf["secondflags"])
+ psf = cdse.getPairSelectionFlags("1-all")
+ self.assertEqual([True] + 3 * [False], psf["firstflags"])
+ self.assertEqual(4 * [True], psf["secondflags"])
return
-
-# def test_applyPairSelection(self):
-# """check FitStructure.applyPairSelection()
-# """
-# return
-
+ # def test_applyPairSelection(self):
+ # """check FitStructure.applyPairSelection()
+ # """
+ # return
def test_copy(self):
- """check FitStructure.copy()
- """
+ """check FitStructure.copy()"""
stru2 = self.stru.copy()
- self.assertEqual('noname', stru2.name)
+ self.assertEqual("noname", stru2.name)
stru3 = Structure()
self.assertRaises(ControlTypeError, stru2.copy, stru3)
- self.stru.refined = PDFStructure('refined-name')
+ self.stru.refined = PDFStructure("refined-name")
stru4 = self.stru.copy()
self.assertIsNot(self.stru.refined, stru4.refined)
- self.assertEqual('refined-name', stru4.refined.name)
+ self.assertEqual("refined-name", stru4.refined.name)
return
@@ -318,7 +289,7 @@ def test_copy(self):
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testinsertrowsdialog.py b/src/diffpy/pdfgui/tests/testinsertrowsdialog.py
index 504a5980..05bc0fbf 100644
--- a/src/diffpy/pdfgui/tests/testinsertrowsdialog.py
+++ b/src/diffpy/pdfgui/tests/testinsertrowsdialog.py
@@ -25,8 +25,8 @@
# ----------------------------------------------------------------------------
-class TestInsertRowsDialog(GUITestCase):
+class TestInsertRowsDialog(GUITestCase):
def setUp(self):
self.app = wx.App()
self.dialog = InsertRowsDialog(None)
@@ -37,16 +37,16 @@ def tearDown(self):
self.app.Destroy()
return
-
def test_spin_ctrl_rows(self):
"Check default number of rows to insert"
d = self.dialog
self.assertEqual(1, d.spin_ctrl_Rows.GetValue())
return
+
# End of class TestInsertRowsDialog
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testloadproject.py b/src/diffpy/pdfgui/tests/testloadproject.py
index b9ba2836..13d08ad3 100644
--- a/src/diffpy/pdfgui/tests/testloadproject.py
+++ b/src/diffpy/pdfgui/tests/testloadproject.py
@@ -25,6 +25,7 @@
# ----------------------------------------------------------------------------
+
class TestLoadProject(GUITestCase):
prj_lcmo = None
@@ -34,10 +35,9 @@ class TestLoadProject(GUITestCase):
def setUp(self):
# load project files once
if TestLoadProject.prj_lcmo is None:
- TestLoadProject.prj_lcmo = LoadProject(datafile('lcmo.ddp'))
- TestLoadProject.prj_lcmo_full = LoadProject(
- datafile('lcmo_full.ddp'))
- TestLoadProject.prj_ni = LoadProject(datafile('ni.ddp'))
+ TestLoadProject.prj_lcmo = LoadProject(datafile("lcmo.ddp"))
+ TestLoadProject.prj_lcmo_full = LoadProject(datafile("lcmo_full.ddp"))
+ TestLoadProject.prj_ni = LoadProject(datafile("ni.ddp"))
# assign them to this instance
self.prj_lcmo = TestLoadProject.prj_lcmo
self.prj_lcmo_full = TestLoadProject.prj_lcmo_full
@@ -48,15 +48,13 @@ def tearDown(self):
return
def test___init__(self):
- """check LoadProject.__init__()
- """
+ """check LoadProject.__init__()"""
self.assertEqual(1, len(self.prj_ni.getFits()))
self.assertRaises(ControlFileError, LoadProject, "does/not/exist.ddp")
return
def test_getFits(self):
- """check LoadProject.getFits()
- """
+ """check LoadProject.getFits()"""
lcmofits = self.prj_lcmo.getFits()
lcmofullfits = self.prj_lcmo_full.getFits()
self.assertEqual(1, len(lcmofits))
@@ -67,8 +65,7 @@ def test_getFits(self):
return
def test_getDataSets(self):
- """check LoadProject.getDataSets()
- """
+ """check LoadProject.getDataSets()"""
lcmofullfits = self.prj_lcmo_full.getFits()
datasets = self.prj_lcmo_full.getDataSets()
self.assertEqual(10, len(datasets))
@@ -79,8 +76,7 @@ def test_getDataSets(self):
return
def test_getPhases(self):
- """check LoadProject.getPhases()
- """
+ """check LoadProject.getPhases()"""
lcmofullfits = self.prj_lcmo_full.getFits()
phases = self.prj_lcmo_full.getPhases()
self.assertAlmostEqual(5.53884, phases[0].refined.lattice.a, 4)
@@ -91,8 +87,7 @@ def test_getPhases(self):
return
def test_getTemperatures(self):
- """check LoadProject.getTemperatures()
- """
+ """check LoadProject.getTemperatures()"""
temps = self.prj_lcmo_full.getTemperatures()
self.assertEqual(10, len(temps))
self.assertEqual(300, temps[0])
@@ -103,20 +98,20 @@ def test_getTemperatures(self):
return
def test_getDopings(self):
- """check LoadProject.getDopings()
- """
+ """check LoadProject.getDopings()"""
dopings = self.prj_lcmo_full.getDopings()
- self.assertEqual(10*[None], dopings)
+ self.assertEqual(10 * [None], dopings)
datasets3 = self.prj_lcmo_full.getDataSets()[:3]
dopings3 = self.prj_lcmo_full.getDopings(datasets3)
- self.assertEqual(3*[None], dopings3)
+ self.assertEqual(3 * [None], dopings3)
return
+
# End of class TestLoadProject
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testmainframe.py b/src/diffpy/pdfgui/tests/testmainframe.py
index e64c9520..32922c74 100644
--- a/src/diffpy/pdfgui/tests/testmainframe.py
+++ b/src/diffpy/pdfgui/tests/testmainframe.py
@@ -26,8 +26,8 @@
# ----------------------------------------------------------------------------
-class TestMainFrame(GUITestCase):
+class TestMainFrame(GUITestCase):
@classmethod
def setUpClass(cls):
GUITestCase.setUpClass()
@@ -35,7 +35,6 @@ def setUpClass(cls):
cls.frame = MainFrame(None, -1, "")
return
-
@classmethod
def tearDownClass(cls):
cls.frame.Close()
@@ -43,7 +42,6 @@ def tearDownClass(cls):
GUITestCase.tearDownClass()
return
-
def test_onRightClick(self):
"check MainFrame.onRightClick method for context menu"
# just instantiate the context menu
@@ -57,15 +55,15 @@ def test_onRightClick(self):
self.assertIsNotNone(self.frame.PopupMenu)
return
-
def test_disableMainMenuItems(self):
"cover MainFrame.disableMainMenuItems method."
self.frame.disableMainMenuItems()
return
+
# End of class TestMainFrame
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testparameter.py b/src/diffpy/pdfgui/tests/testparameter.py
index 1aeafdca..176548da 100644
--- a/src/diffpy/pdfgui/tests/testparameter.py
+++ b/src/diffpy/pdfgui/tests/testparameter.py
@@ -29,8 +29,8 @@
# ----------------------------------------------------------------------------
-class TestParameter(GUITestCase):
+class TestParameter(GUITestCase):
@classmethod
def setUpClass(cls):
GUITestCase.setUpClass()
@@ -42,7 +42,6 @@ def setUpClass(cls):
cls.frame.makeTreeSelection(fits[0])
return
-
@classmethod
def tearDownClass(cls):
cls.frame.Close()
@@ -50,12 +49,10 @@ def tearDownClass(cls):
GUITestCase.tearDownClass()
return
-
def setUp(self):
self.fitting = self.frame.rightPanel.fit
return
-
def test___init__(self):
"check Parameter.__init__"
p = Parameter(3, 2.2)
@@ -69,7 +66,6 @@ def test___init__(self):
self.assertRaises(ControlTypeError, Parameter, 1, None)
return
-
def test_initialValue(self):
"check Parameter.initialValue"
p1 = Parameter(1, 0.25)
@@ -80,9 +76,10 @@ def test_initialValue(self):
self.assertEqual("=undefined:7", px.initialStr())
return
+
# End of class TestParameter
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testparameterspanel.py b/src/diffpy/pdfgui/tests/testparameterspanel.py
index 2bb91a39..465bb486 100644
--- a/src/diffpy/pdfgui/tests/testparameterspanel.py
+++ b/src/diffpy/pdfgui/tests/testparameterspanel.py
@@ -27,16 +27,18 @@
# ----------------------------------------------------------------------------
-class TestParametersPanel(GUITestCase):
+class TestParametersPanel(GUITestCase):
def setUp(self):
self.app = wx.App()
self.frame = wx.Frame(None)
self.panel = ParametersPanel(self.frame, -1)
- self.panel.parameters.update([
- (1, Parameter(1, 0.1)),
- (5, Parameter(5, 0.5)),
- ])
+ self.panel.parameters.update(
+ [
+ (1, Parameter(1, 0.1)),
+ (5, Parameter(5, 0.5)),
+ ]
+ )
self.panel.refresh()
self.panel.mainFrame = self._mockUpMainFrame()
self.frame.window = self.panel
@@ -47,7 +49,6 @@ def tearDown(self):
self.app.Destroy()
return
-
def test_onPopupFixFree(self):
"Check ParametersPanel.onPopupFixFree"
# event is not used, we just generate and reuse dummy event.
@@ -69,7 +70,6 @@ def test_onPopupFixFree(self):
self.assertTrue(plist[1].fixed)
return
-
def test_applyCellChange(self):
"Check ParametersPanel.applyCellChange"
gp = self.panel.grid_parameters
@@ -84,7 +84,6 @@ def test_applyCellChange(self):
self.assertEqual(1.5, panel.parameters[1].initialValue())
return
-
def test_onCellLeftClick(self):
"Check click handling on the Parameters grid."
gp = self.panel.grid_parameters
@@ -110,7 +109,6 @@ def test_onCellLeftClick(self):
self.assertEqual("1", gp.GetCellValue(0, 1))
return
-
def test_onCellRightClick(self):
"Check right-click handling on the Parameters grid."
# disable modal grid_parameters.PopupMenu
@@ -123,9 +121,10 @@ def test_onCellRightClick(self):
self.assertTrue(self.panel.did_popupIDs)
return
+
# End of class TestParametersPanel
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testpdfdataset.py b/src/diffpy/pdfgui/tests/testpdfdataset.py
index f358f359..d3172865 100644
--- a/src/diffpy/pdfgui/tests/testpdfdataset.py
+++ b/src/diffpy/pdfgui/tests/testpdfdataset.py
@@ -25,81 +25,79 @@
##############################################################################
class TestPDFDataSet(unittest.TestCase):
-
def setUp(self):
- self.pdfds = PDFDataSet('test data set')
+ self.pdfds = PDFDataSet("test data set")
return
def tearDown(self):
self.pdfds = None
return
-# def test___init__(self):
-# """check PDFDataSet.__init__()
-# """
-# return
-#
-# def test_clear(self):
-# """check PDFDataSet.clear()
-# """
-# return
-#
-# def test_setvar(self):
-# """check PDFDataSet.setvar()
-# """
-# return
-#
-# def test_getvar(self):
-# """check PDFDataSet.getvar()
-# """
-# return
-#
+ # def test___init__(self):
+ # """check PDFDataSet.__init__()
+ # """
+ # return
+ #
+ # def test_clear(self):
+ # """check PDFDataSet.clear()
+ # """
+ # return
+ #
+ # def test_setvar(self):
+ # """check PDFDataSet.setvar()
+ # """
+ # return
+ #
+ # def test_getvar(self):
+ # """check PDFDataSet.getvar()
+ # """
+ # return
+ #
def test_read(self):
- """check PDFDataSet.read()
- """
+ """check PDFDataSet.read()"""
# neutron data -------------------------------------------------
- fn_550K = datafile('550K.gr')
+ fn_550K = datafile("550K.gr")
self.pdfds.read(fn_550K)
- self.assertEqual('N', self.pdfds.stype)
+ self.assertEqual("N", self.pdfds.stype)
self.assertEqual(32.0, self.pdfds.qmax)
# there are 2000 points in the file
npts = len(self.pdfds.robs)
self.assertEqual(2000, npts)
# drobs are all zero
- self.assertEqual(npts*[0.0], self.pdfds.drobs)
+ self.assertEqual(npts * [0.0], self.pdfds.drobs)
# dGobs should be defined
self.assertTrue(min(self.pdfds.dGobs) > 0)
# x-ray data ---------------------------------------------------
- fx_Ni = datafile('Ni_2-8.chi.gr')
+ fx_Ni = datafile("Ni_2-8.chi.gr")
self.pdfds.read(fx_Ni)
- self.assertEqual('X', self.pdfds.stype)
+ self.assertEqual("X", self.pdfds.stype)
self.assertEqual(40.0, self.pdfds.qmax)
# there are 2000 points in the file
npts = len(self.pdfds.robs)
self.assertEqual(2000, npts)
# drobs are all zero
- self.assertEqual(npts*[0.0], self.pdfds.drobs)
+ self.assertEqual(npts * [0.0], self.pdfds.drobs)
# dGobs should be defined
self.assertTrue(min(self.pdfds.dGobs) > 0)
return
def test_readStr(self):
- """check PDFDataSet.readStr()
- """
+ """check PDFDataSet.readStr()"""
# read Ni xray data, but invalidate the last dGobs
- fx_Ni = datafile('Ni_2-8.chi.gr')
+ fx_Ni = datafile("Ni_2-8.chi.gr")
with open(fx_Ni) as fp:
sNi = fp.read()
- lastdGobs = sNi.rstrip().rindex(' ')
+ lastdGobs = sNi.rstrip().rindex(" ")
sNi_no_dGobs = sNi[:lastdGobs] + " -1.3e-3"
self.pdfds.readStr(sNi_no_dGobs)
# there are 2000 points in the file
npts = len(self.pdfds.robs)
self.assertEqual(2000, npts)
# dGobs should be all zero
- self.assertEqual(npts*[0.0], self.pdfds.dGobs)
+ self.assertEqual(npts * [0.0], self.pdfds.dGobs)
return
+
# def test_write(self):
# """check PDFDataSet.write()
# """
@@ -123,7 +121,7 @@ def test_readStr(self):
# End of class TestPDFDataSet
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testpdfguicontrol.py b/src/diffpy/pdfgui/tests/testpdfguicontrol.py
index 753d3cf8..737d5c05 100644
--- a/src/diffpy/pdfgui/tests/testpdfguicontrol.py
+++ b/src/diffpy/pdfgui/tests/testpdfguicontrol.py
@@ -23,6 +23,7 @@
# ----------------------------------------------------------------------------
+
class TestPDFGuiControl(unittest.TestCase):
"""test methods of PDFGuiControl"""
@@ -34,18 +35,18 @@ def tearDown(self):
del self.control
return
-
def test___init__(self):
"check PDFGuiControl.__init__"
- self.assertEqual('', self.control.journal)
+ self.assertEqual("", self.control.journal)
self.assertIsNone(self.control.projfile)
return
+
# End of class TestPDFGuiControl
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testpdfstructure.py b/src/diffpy/pdfgui/tests/testpdfstructure.py
index db48a95e..680e7391 100644
--- a/src/diffpy/pdfgui/tests/testpdfstructure.py
+++ b/src/diffpy/pdfgui/tests/testpdfstructure.py
@@ -13,108 +13,97 @@
# ----------------------------------------------------------------------------
-class TestPDFStructure(unittest.TestCase):
-
+class TestPDFStructure(unittest.TestCase):
def setUp(self):
- self.stru = PDFStructure('noname')
+ self.stru = PDFStructure("noname")
return
-
def tearDown(self):
return
-
def test___init__(self):
- """check PDFStructure.__init__()
- """
- self.assertEqual('noname', self.stru.name)
+ """check PDFStructure.__init__()"""
+ self.assertEqual("noname", self.stru.name)
return
-
def test_read(self):
- """check PDFStructure.read()
- """
+ """check PDFStructure.read()"""
stru = self.stru
- notastructurefile = datafile('300K.gr')
- self.assertRaises(ControlFileError,
- stru.read, notastructurefile, format='pdffit')
+ notastructurefile = datafile("300K.gr")
+ self.assertRaises(
+ ControlFileError, stru.read, notastructurefile, format="pdffit"
+ )
return
-
def test_copy(self):
- """check PDFStructure.copy()
- """
+ """check PDFStructure.copy()"""
stru2 = self.stru.copy()
- self.assertEqual('noname', stru2.name)
+ self.assertEqual("noname", stru2.name)
self.assertEqual(self.stru.pdffit, stru2.pdffit)
- self.assertIsNot(self.stru.pdffit['ncell'], stru2.pdffit['ncell'])
+ self.assertIsNot(self.stru.pdffit["ncell"], stru2.pdffit["ncell"])
return
-
def test_setvar(self):
- """check PDFStructure.setvar()
- """
+ """check PDFStructure.setvar()"""
stru = self.stru
- stru.addNewAtom('C', [0, 0, 0], anisotropy=True)
- stru.setvar('pscale', 1.5)
- self.assertEqual(1.5, stru.pdffit['scale'])
- stru.setvar('lat(1)', 4)
- stru.setvar('lat(2)', 5)
- stru.setvar('lat(3)', 7)
+ stru.addNewAtom("C", [0, 0, 0], anisotropy=True)
+ stru.setvar("pscale", 1.5)
+ self.assertEqual(1.5, stru.pdffit["scale"])
+ stru.setvar("lat(1)", 4)
+ stru.setvar("lat(2)", 5)
+ stru.setvar("lat(3)", 7)
self.assertEqual(4, stru.lattice.a)
self.assertEqual(5, stru.lattice.b)
self.assertEqual(7, stru.lattice.c)
- stru.setvar('lat(4)', 91)
- stru.setvar('lat(5)', 92)
- stru.setvar('lat(6)', 93)
+ stru.setvar("lat(4)", 91)
+ stru.setvar("lat(5)", 92)
+ stru.setvar("lat(6)", 93)
self.assertEqual(91, stru.lattice.alpha)
self.assertEqual(92, stru.lattice.beta)
self.assertEqual(93, stru.lattice.gamma)
- stru.setvar('spdiameter', 17)
- self.assertEqual(17, stru.pdffit['spdiameter'])
- stru.setvar('stepcut', 19)
- self.assertEqual(19, stru.pdffit['stepcut'])
- self.assertRaises(ControlKeyError,
- stru.setvar, 'sstepcut', 6)
- stru.setvar('x(1)', 0.1)
- stru.setvar('y(1)', 0.2)
- stru.setvar('z(1)', 0.3)
- stru.setvar('occ(1)', 0.9)
- stru.setvar('u23(1)', 0.004)
+ stru.setvar("spdiameter", 17)
+ self.assertEqual(17, stru.pdffit["spdiameter"])
+ stru.setvar("stepcut", 19)
+ self.assertEqual(19, stru.pdffit["stepcut"])
+ self.assertRaises(ControlKeyError, stru.setvar, "sstepcut", 6)
+ stru.setvar("x(1)", 0.1)
+ stru.setvar("y(1)", 0.2)
+ stru.setvar("z(1)", 0.3)
+ stru.setvar("occ(1)", 0.9)
+ stru.setvar("u23(1)", 0.004)
self.assertEqual([0.1, 0.2, 0.3], stru[0].xyz.tolist())
self.assertEqual(0.9, stru[0].occupancy)
self.assertEqual(0.004, stru[0].U[1, 2])
- self.assertRaises(ControlKeyError, stru.setvar, 'invalid(1)', 7)
+ self.assertRaises(ControlKeyError, stru.setvar, "invalid(1)", 7)
return
-
def test_getvar(self):
- """check PDFStructure.getvar()
- """
+ """check PDFStructure.getvar()"""
from diffpy.structure import Atom
+
stru = self.stru
abcABG = (3.0, 4.0, 5.0, 81, 82, 83)
stru.lattice.setLatPar(*abcABG)
for i in range(6):
- self.assertEqual(abcABG[i], stru.getvar('lat(%i)' % (i + 1)))
- stru.append(Atom('Ni', [0.1, 0.2, 0.3]))
- self.assertEqual(0.1, stru.getvar('x(1)'))
- self.assertEqual(0.2, stru.getvar('y(1)'))
- self.assertEqual(0.3, stru.getvar('z(1)'))
- self.assertEqual(1.0, stru.getvar('occ(1)'))
+ self.assertEqual(abcABG[i], stru.getvar("lat(%i)" % (i + 1)))
+ stru.append(Atom("Ni", [0.1, 0.2, 0.3]))
+ self.assertEqual(0.1, stru.getvar("x(1)"))
+ self.assertEqual(0.2, stru.getvar("y(1)"))
+ self.assertEqual(0.3, stru.getvar("z(1)"))
+ self.assertEqual(1.0, stru.getvar("occ(1)"))
# pscale
- self.assertEqual(1.0, stru.getvar('pscale'))
+ self.assertEqual(1.0, stru.getvar("pscale"))
# spdiameter
- self.assertEqual(0.0, stru.getvar('spdiameter'))
- stru.pdffit['spdiameter'] = 37.7
- self.assertEqual(37.7, stru.getvar('spdiameter'))
+ self.assertEqual(0.0, stru.getvar("spdiameter"))
+ stru.pdffit["spdiameter"] = 37.7
+ self.assertEqual(37.7, stru.getvar("spdiameter"))
# stepcut
- self.assertEqual(0.0, stru.getvar('stepcut'))
- stru.pdffit['stepcut'] = 17.7
- self.assertEqual(17.7, stru.getvar('stepcut'))
- self.assertRaises(ControlKeyError, stru.getvar, 'invalid(1)')
- self.assertRaises(ControlKeyError, stru.getvar, 'invalid')
+ self.assertEqual(0.0, stru.getvar("stepcut"))
+ stru.pdffit["stepcut"] = 17.7
+ self.assertEqual(17.7, stru.getvar("stepcut"))
+ self.assertRaises(ControlKeyError, stru.getvar, "invalid(1)")
+ self.assertRaises(ControlKeyError, stru.getvar, "invalid")
return
@@ -122,7 +111,7 @@ def test_getvar(self):
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testphaseconfigurepanel.py b/src/diffpy/pdfgui/tests/testphaseconfigurepanel.py
index e0b516cf..f07c8661 100644
--- a/src/diffpy/pdfgui/tests/testphaseconfigurepanel.py
+++ b/src/diffpy/pdfgui/tests/testphaseconfigurepanel.py
@@ -28,8 +28,8 @@
# ----------------------------------------------------------------------------
-class TestPhaseConfigurePanel(GUITestCase):
+class TestPhaseConfigurePanel(GUITestCase):
@classmethod
def setUpClass(cls):
GUITestCase.setUpClass()
@@ -42,7 +42,6 @@ def setUpClass(cls):
cls.frame.makeTreeSelection(phases[0])
return
-
@classmethod
def tearDownClass(cls):
cls.frame.Close()
@@ -50,13 +49,11 @@ def tearDownClass(cls):
GUITestCase.tearDownClass()
return
-
def setUp(self):
self.panel = self.frame.rightPanel.notebook_phase.GetPage(0)
assert isinstance(self.panel, PhaseConfigurePanel)
return
-
def test_restrictConstrainedParameters(self):
"check restrictConstrainedParameters function"
panel = self.panel
@@ -65,10 +62,9 @@ def test_restrictConstrainedParameters(self):
self.assertFalse(panel.textCtrlDelta1.IsEditable())
self.assertTrue(grid.IsReadOnly(0, 1))
self.assertFalse(grid.IsReadOnly(0, 3))
- self.assertEqual('@1', tooltiptext(panel.textCtrlA))
+ self.assertEqual("@1", tooltiptext(panel.textCtrlA))
return
-
def test_onCellRightClick(self):
"check right-click handling over the atoms grid."
# disable modal gridAtoms.PopupMenu
@@ -82,9 +78,10 @@ def test_onCellRightClick(self):
self.assertIsNotNone(self.panel.insertID)
return
+
# End of class TestPhaseConfigurePanel
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/teststructureviewer.py b/src/diffpy/pdfgui/tests/teststructureviewer.py
index c0de1003..bb2f4f8f 100644
--- a/src/diffpy/pdfgui/tests/teststructureviewer.py
+++ b/src/diffpy/pdfgui/tests/teststructureviewer.py
@@ -15,10 +15,8 @@
##############################################################################
class TestRoutines(unittest.TestCase):
-
def test_getStructureViewer(self):
- """check getStructureViewer() returns a singleton.
- """
+ """check getStructureViewer() returns a singleton."""
sv0 = getStructureViewer()
uid0 = id(sv0)
del sv0
@@ -27,63 +25,54 @@ def test_getStructureViewer(self):
self.assertEqual(uid0, uid1)
return
+
# End of class TestRoutines
##############################################################################
class TestStructureViewer(unittest.TestCase):
-
-
def setUp(self):
return
-
def tearDown(self):
return
-
def test___init__(self):
- """check StructureViewer.__init__()
- """
+ """check StructureViewer.__init__()"""
sv = StructureViewer()
- self.assertEqual('%s', sv.argstr)
+ self.assertEqual("%s", sv.argstr)
return
-
def test_getConfig(self):
- """check StructureViewer.getConfig()
- """
+ """check StructureViewer.getConfig()"""
sv = StructureViewer()
- self.assertEqual('%s', sv.getConfig()['argstr'])
- sv.argstr = 'foooo'
- self.assertEqual('foooo', sv.getConfig()['argstr'])
+ self.assertEqual("%s", sv.getConfig()["argstr"])
+ sv.argstr = "foooo"
+ self.assertEqual("foooo", sv.getConfig()["argstr"])
return
-
def test_setConfig(self):
- """check StructureViewer.setConfig()
- """
+ """check StructureViewer.setConfig()"""
sv = StructureViewer()
cfg0 = sv.getConfig()
- sv.setConfig({'asdf' : 7})
+ sv.setConfig({"asdf": 7})
self.assertEqual(cfg0, sv.getConfig())
- sv.setConfig({'executable' : None})
+ sv.setConfig({"executable": None})
self.assertNotEqual(cfg0, sv.getConfig())
return
-
def test_plot(self):
- """check StructureViewer.plot()
- """
+ """check StructureViewer.plot()"""
from diffpy.pdfgui.control.fitstructure import FitStructure
+
sv = StructureViewer()
# default executable is empty string
- self.assertEqual('', sv.executable)
+ self.assertEqual("", sv.executable)
# and so plot raises ControlConfigError
- fs = FitStructure('s1')
- fs.read(datafile('LaMnO3.stru'))
+ fs = FitStructure("s1")
+ fs.read(datafile("LaMnO3.stru"))
self.assertRaises(ControlConfigError, sv.plot, fs)
- sv.executable = 'does/not/exist'
+ sv.executable = "does/not/exist"
self.assertTrue(None is sv._tmpdir)
self.assertEqual(0, sv._plotcount)
self.assertRaises(ControlConfigError, sv.plot, fs)
@@ -91,16 +80,15 @@ def test_plot(self):
self.assertEqual(1, sv._plotcount)
return
-
def test___del__(self):
- """check StructureViewer.__del__()
- """
+ """check StructureViewer.__del__()"""
import gc
from diffpy.pdfgui.control.fitstructure import FitStructure
+
sv = StructureViewer()
- sv.executable = 'does/not/exist'
- fs = FitStructure('s1')
- fs.read(datafile('LaMnO3.stru'))
+ sv.executable = "does/not/exist"
+ fs = FitStructure("s1")
+ fs.read(datafile("LaMnO3.stru"))
self.assertRaises(ControlConfigError, sv.plot, fs)
tmpd = sv._tmpdir
self.assertTrue(os.path.isdir(tmpd))
@@ -109,6 +97,7 @@ def test___del__(self):
self.assertFalse(os.path.isdir(tmpd))
return
+
# def test__writeTemporaryStructure(self):
# """check StructureViewer._writeTemporaryStructure()
# """
@@ -121,7 +110,7 @@ def test___del__(self):
# End of class TestStructureViewer
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
# End of file
diff --git a/src/diffpy/pdfgui/tests/testtemperatureseriespanel.py b/src/diffpy/pdfgui/tests/testtemperatureseriespanel.py
index 866687c1..a37425ed 100644
--- a/src/diffpy/pdfgui/tests/testtemperatureseriespanel.py
+++ b/src/diffpy/pdfgui/tests/testtemperatureseriespanel.py
@@ -27,14 +27,14 @@
# ----------------------------------------------------------------------------
-class TestTemperatureSeriesPanel(GUITestCase):
+class TestTemperatureSeriesPanel(GUITestCase):
def setUp(self):
self.app = wx.App()
self.frame = wx.Frame(None)
self.panel = TemperatureSeriesPanel(self.frame)
self.panel.mainFrame = self._mockUpMainFrame()
- self.panel.mainFrame.workpath = datafile('')
+ self.panel.mainFrame.workpath = datafile("")
return
def tearDown(self):
@@ -42,11 +42,10 @@ def tearDown(self):
self.app.Destroy()
return
-
def test_onAdd(self):
"Check TemperatureSeriesPanel.onAdd"
panel = self.panel
- paths = ['T017K.gr', '137K.gr', 'lcmo_00.gr', 'lcmo_20.gr']
+ paths = ["T017K.gr", "137K.gr", "lcmo_00.gr", "lcmo_20.gr"]
paths = [datafile(p) for p in paths]
with overridefiledialog(wx.ID_OK, paths):
panel.onAdd(None)
@@ -54,9 +53,10 @@ def test_onAdd(self):
self.assertEqual([17, 137, 10, 10], [tf[0] for tf in panel.datasets])
return
+
# End of class TestTemperatureSeriesPanel
# ----------------------------------------------------------------------------
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/src/diffpy/pdfgui/tests/testutils.py b/src/diffpy/pdfgui/tests/testutils.py
index 1b6cb442..faba9364 100644
--- a/src/diffpy/pdfgui/tests/testutils.py
+++ b/src/diffpy/pdfgui/tests/testutils.py
@@ -28,8 +28,10 @@
# helper functions
+
def datafile(filename):
from pkg_resources import resource_filename
+
rv = resource_filename(__name__, "testdata/" + filename)
return rv
@@ -38,11 +40,14 @@ def datafile(filename):
def overridewebbrowser(fnc_open):
"Temporarily replace `webbrowser.open` with given function."
import webbrowser
+
controller = webbrowser.get()
save_open = controller.open
+
def open_override(url, new=0, autoraise=True):
fnc_open(url)
return True
+
controller.open = open_override
try:
yield save_open
@@ -56,14 +61,19 @@ def open_override(url, new=0, autoraise=True):
def overridefiledialog(status, paths):
"Temporarily replace wx.FileDialog with non-blocking ShowModal()."
save_filedialog = wx.FileDialog
+
class NBFileDialog(wx.FileDialog):
def ShowModal(self):
return status
+
def GetPath(self):
- return paths[-1] if paths else ''
+ return paths[-1] if paths else ""
+
def GetPaths(self):
return paths
+
pass
+
wx.FileDialog = NBFileDialog
try:
yield
@@ -76,10 +86,13 @@ def GetPaths(self):
def overrideclipboard():
"Temporarily replace wx.TheClipboard with a dummy object."
save_theclipboard = wx.TheClipboard
+
class _TTheClipboard(object):
def IsSupported(self, fmt):
return False
+
pass
+
wx.TheClipboard = _TTheClipboard()
try:
yield wx.TheClipboard
@@ -110,21 +123,23 @@ def clickcell(grid, leftright, row, col, **kw):
Keyword arguments for the wx.GridEvent constructor.
Typically a keyboard modifier for the click.
"""
- assert leftright in ('left', 'right')
+ assert leftright in ("left", "right")
if leftright == "left":
eventtype = wx.grid.EVT_GRID_CELL_LEFT_CLICK.typeId
else:
eventtype = wx.grid.EVT_GRID_CELL_RIGHT_CLICK.typeId
- kbd = {'kbd': wx.KeyboardState(**kw)}
+ kbd = {"kbd": wx.KeyboardState(**kw)}
# TODO: remove this after deprecations of wxpython 3
if wx.VERSION[0] == 3:
- kbd = {k.replace('Down', ''): v for k, v in kw.items()}
+ kbd = {k.replace("Down", ""): v for k, v in kw.items()}
e = wx.grid.GridEvent(grid.Id, eventtype, grid, row, col, **kbd)
grid.ProcessEvent(e)
return
+
# GUI-specialized TestCase ---------------------------------------------------
+
class GUITestCase(TestCase):
"Test GUI widgets without invoking ErrorReportDialog."
@@ -152,16 +167,16 @@ def tearDownClass(cls):
pdfguiglobals.dbopts.noconfirm = cls._save_noconfirm
pdfguiglobals.cmdargs[:] = cls._save_cmdargs
pdfguiglobals.configfilename = cls._save_configfilename
- pdfguicontrol.PDFGuiControl.QueueManager.run, = cls._save_qmrun
- mainframe.pdfguicontrol, = cls._save_factory
- pdfguicontrol.pdfguicontrol, = cls._save_factory
+ (pdfguicontrol.PDFGuiControl.QueueManager.run,) = cls._save_qmrun
+ (mainframe.pdfguicontrol,) = cls._save_factory
+ (pdfguicontrol.pdfguicontrol,) = cls._save_factory
assert mainframe.pdfguicontrol is pdfguicontrol.pdfguicontrol
cls.__pdfguicontrol = None
return
@classmethod
def setCmdArgs(cls, args):
- assert hasattr(cls, '_save_cmdargs')
+ assert hasattr(cls, "_save_cmdargs")
pdfguiglobals.cmdargs[:] = args
return
@@ -176,10 +191,12 @@ def pdfguicontrol(cls, *args, **kwargs):
def _mockUpMainFrame():
return _TMainFrame()
+
# end of class GUITestCase
# Helper for GUITestCase -----------------------------------------------------
+
class _TMainFrame(object):
"Thin mockup of the used MainFrame methods."
@@ -189,6 +206,7 @@ def needsSave(self):
self.altered = True
return
+
# end of class _TMainFrame
# End of file
diff --git a/src/diffpy/pdfgui/tui.py b/src/diffpy/pdfgui/tui.py
index fb35e13c..a75933ea 100644
--- a/src/diffpy/pdfgui/tui.py
+++ b/src/diffpy/pdfgui/tui.py
@@ -33,13 +33,13 @@ def __init__(self, filename=None):
filename -- path to PDFgui project file.
"""
from diffpy.pdfgui.control.pdfguicontrol import PDFGuiControl
+
self._project = PDFGuiControl()
# business
if filename is not None:
self.load(filename)
return
-
def load(self, filename):
"""Load a project.
@@ -50,7 +50,6 @@ def load(self, filename):
self._project.load(filename)
return
-
def save(self, filename):
"""Save the project.
@@ -61,7 +60,6 @@ def save(self, filename):
self._project.save(filename)
return
-
def getFits(self):
"""Get all fits defined in the project file.
@@ -70,7 +68,6 @@ def getFits(self):
rv = self._project.fits[:]
return rv
-
def getDataSets(self, fits=None):
"""Return a list of all datasets contained in specified fits.
@@ -87,7 +84,6 @@ def getDataSets(self, fits=None):
rv = sum([fit.datasets for fit in fitlist], [])
return rv
-
def getCalculations(self, fits=None):
"""Return list of all calculations contained in specified fits.
@@ -104,7 +100,6 @@ def getCalculations(self, fits=None):
rv = sum([fit.calcs for fit in fitlist], [])
return rv
-
def getPhases(self, fits=None):
"""Collect all phases contained in specified fits.
@@ -121,7 +116,6 @@ def getPhases(self, fits=None):
rv = sum([fit.strucs for fit in fitlist], [])
return rv
-
def getTemperatures(self, datasets=None):
"""Extract temperatures from a list of datasets.
@@ -136,10 +130,9 @@ def getTemperatures(self, datasets=None):
dslist = self.getDataSets()
else:
dslist = datasets
- temperatures = [ds.metadata.get('temperature') for ds in dslist]
+ temperatures = [ds.metadata.get("temperature") for ds in dslist]
return temperatures
-
def getDopings(self, datasets=None):
"""Extract doping values from a list of datasets.
@@ -154,7 +147,7 @@ def getDopings(self, datasets=None):
dslist = self.getDataSets()
else:
dslist = datasets
- dopings = [ds.metadata.get('doping') for ds in dslist]
+ dopings = [ds.metadata.get("doping") for ds in dslist]
return dopings
diff --git a/src/diffpy/pdfgui/utils.py b/src/diffpy/pdfgui/utils.py
index 20828c36..9a6a15e5 100644
--- a/src/diffpy/pdfgui/utils.py
+++ b/src/diffpy/pdfgui/utils.py
@@ -37,13 +37,16 @@ def numericStringSort(lst):
No return value to highlight inplace sorting.
"""
import re
- rx = re.compile(r'(\d+)')
- keys = [ rx.split(s) for s in lst ]
- for k in keys: k[1::2] = [ int(i) for i in k[1::2] ]
+
+ rx = re.compile(r"(\d+)")
+ keys = [rx.split(s) for s in lst]
+ for k in keys:
+ k[1::2] = [int(i) for i in k[1::2]]
newlst = sorted(zip(keys, lst))
lst[:] = [kv[1] for kv in newlst]
return
+
def pickle_loads(sdata, encoding="latin1"):
"""Mimic interface of Python 3 pickle.loads.
@@ -52,8 +55,7 @@ def pickle_loads(sdata, encoding="latin1"):
Return the reconstructed object hierarchy.
"""
- rv = (pickle.loads(sdata, encoding=encoding) if six.PY3
- else pickle.loads(sdata))
+ rv = pickle.loads(sdata, encoding=encoding) if six.PY3 else pickle.loads(sdata)
return rv
@@ -77,29 +79,30 @@ def safeCPickleDumps(obj):
# This should be unnecessary in Python 3
# TODO - replace getquoted/setquoted with get/set after dropping Python 2
-class QuotedConfigParser(RawConfigParser):
+class QuotedConfigParser(RawConfigParser):
def getquoted(self, section, option):
"""Retrieve option value previously set with setquoted.
This allows to work with unicode strings.
"""
vq = self.get(section, option)
- rv = vq.decode('utf-8') if six.PY2 else vq
+ rv = vq.decode("utf-8") if six.PY2 else vq
return rv
-
def setquoted(self, section, option, value):
"""Set option to a value encoded with urllib.quote.
This allows to store and write out unicode strings.
Use getquoted to recover the decoded value.
"""
- vq = value.encode('utf-8') if six.PY2 else value
+ vq = value.encode("utf-8") if six.PY2 else value
return self.set(section, option, vq)
+
# class QuotedConfigParser
+
def quote_plain(s):
"""Return a possibly Unicode string quoted as plain ASCII.
@@ -107,27 +110,29 @@ def quote_plain(s):
project file format.
"""
from six.moves.urllib.parse import quote_plus
- rv = quote_plus(asunicode(s).encode('utf-8'))
+
+ rv = quote_plus(asunicode(s).encode("utf-8"))
return rv
def unquote_plain(s):
- """Unquote string previously encoded with quote_plain.
- """
+ """Unquote string previously encoded with quote_plain."""
from six.moves.urllib.parse import unquote_plus
+
u = unquote_plus(s)
rv = asunicode(u)
return rv
def asunicode(s):
- '''Convert string or bytes object to a text type.
+ """Convert string or bytes object to a text type.
This is `unicode` in Python 2 and `str` in Python 3.
- '''
+ """
rv = s
if not isinstance(s, six.text_type):
- rv = s.decode('utf-8')
+ rv = s.decode("utf-8")
return rv
+
# End of file
diff --git a/src/diffpy/pdfgui/version.py b/src/diffpy/pdfgui/version.py
index 54f94826..a851246e 100644
--- a/src/diffpy/pdfgui/version.py
+++ b/src/diffpy/pdfgui/version.py
@@ -22,7 +22,7 @@
Use `__git_commit__` instead.
"""
-__all__ = ['__date__', '__git_commit__', '__timestamp__', '__version__']
+__all__ = ["__date__", "__git_commit__", "__timestamp__", "__version__"]
import os.path
@@ -30,22 +30,26 @@
# obtain version information from the version.cfg file
-cp = dict(version='', date='', commit='', timestamp='0')
-fcfg = resource_filename(__name__, 'version.cfg')
-if not os.path.isfile(fcfg): # pragma: no cover
+cp = dict(version="", date="", commit="", timestamp="0")
+fcfg = resource_filename(__name__, "version.cfg")
+if not os.path.isfile(fcfg): # pragma: no cover
from warnings import warn
+
warn('Package metadata not found, execute "./setup.py egg_info".')
fcfg = os.devnull
with open(fcfg) as fp:
- kwords = [[w.strip() for w in line.split(' = ', 1)]
- for line in fp if line[:1].isalpha() and ' = ' in line]
+ kwords = [
+ [w.strip() for w in line.split(" = ", 1)]
+ for line in fp
+ if line[:1].isalpha() and " = " in line
+ ]
assert all(w[0] in cp for w in kwords), "received unrecognized keyword"
cp.update(kwords)
-__version__ = cp['version']
-__date__ = cp['date']
-__git_commit__ = cp['commit']
-__timestamp__ = int(cp['timestamp'])
+__version__ = cp["version"]
+__date__ = cp["date"]
+__git_commit__ = cp["commit"]
+__timestamp__ = int(cp["timestamp"])
# TODO remove deprecated __gitsha__ in version 1.3.
__gitsha__ = __git_commit__