--- /dev/null
+[autopeak]\r
+ [[auto_fit_nm]]\r
+ default = 5\r
+ minimum = 0\r
+ type = float\r
+ value = 5\r
+\r
+ [[auto_fit_points]]\r
+ default = 50\r
+ minimum = 0\r
+ type = integer\r
+ value = 50\r
+\r
+ [[auto_left_baseline]]\r
+ default = 20\r
+ minimum = 0\r
+ type = float\r
+ value = 20\r
+\r
+ [[auto_max_p]]\r
+ default = 10\r
+ minimum = 0\r
+ type = float\r
+ value = 10\r
+\r
+ [[auto_min_p]]\r
+ default = 0.005\r
+ minimum = 0\r
+ type = float\r
+ value = 0.005\r
+\r
+ [[auto_right_baseline]]\r
+ default = 20\r
+ minimum = 0\r
+ type = float\r
+ value = 20\r
+\r
+ [[auto_slope_span]]\r
+ default = 20\r
+ minimum = 0\r
+ type = integer\r
+ value = 20\r
+\r
+ [[baseline_clicks]]\r
+ default = 0\r
+ maximum = 20\r
+ minimum = 0\r
+ type = integer\r
+ value = 0\r
+\r
+ [[noauto]]\r
+ default = False\r
+ type = boolean\r
+ value = False\r
+\r
+ [[noflatten]]\r
+ default = False\r
+ type = boolean\r
+ value = False\r
+\r
+ [[pl]]\r
+ default = 5\r
+ minimum = 0\r
+ type = float\r
+ value = 5\r
+\r
+ [[rebase]]\r
+ default = True\r
+ type = boolean\r
+ value = False\r
+\r
+ [[reclick]]\r
+ default = False\r
+ type = boolean\r
+ value = False\r
+\r
+ [[temperature]]\r
+ default = 293\r
+ minimum = 0\r
+ type = float\r
+ value = 293\r
+\r
+ [[usepl]]\r
+ default = False\r
+ type = boolean\r
+ value = False\r
+\r
+ [[usepoints]]\r
+ default = False\r
+ type = boolean\r
+ value = False\r
--- /dev/null
+[fit]\r
+flatten = 1\r
+temperature = 301
\ No newline at end of file
--- /dev/null
+[convfilt]\r
+ [[blindwindow]]\r
+ default = 20\r
+ maximum = 10000\r
+ minimum = 0\r
+ type = float\r
+ value = 20\r
+\r
+ [[convolution]]\r
+ default = '[6.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]'\r
+ type = string\r
+ #value = '[6.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]'\r
+ value = '[11.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]'\r
+\r
+ [[maxcut]]\r
+ default = 0.2\r
+ maximum = 1\r
+ minimum = 0\r
+ type = float\r
+ value = 0.2\r
+ visible = False\r
+\r
+ [[medianfilter]]\r
+ default = 7\r
+ maximum = 100\r
+ minimum = 0\r
+ type = integer\r
+ value = 7\r
+\r
+ [[mindeviation]]\r
+ default = 5\r
+ maximum = 100\r
+ minimum = 0\r
+ type = float\r
+ value = 5\r
+\r
+ [[minpeaks]]\r
+ default = 5\r
+ maximum = 20\r
+ minimum = 0\r
+ type = integer\r
+ value = 1\r
+\r
+ [[positive]]\r
+ default = False\r
+ type = boolean\r
+ value = False\r
+\r
+ [[seedouble]]\r
+ default = 10\r
+ maximum = 1000\r
+ minimum = 0\r
+ type = integer\r
+ value = 10\r
+\r
+ [[stable]]\r
+ default = 0.005\r
+ maximum = 1\r
+ minimum = 0\r
+ type = float\r
+ value = 0.005\r
+\r
+[flatfilt]\r
+ #[[median_filter]]\r
+ #default = 7\r
+ #maximum = 100\r
+ #minimum = 0\r
+ #type = integer\r
+ #value = 7\r
+\r
+ [[min_npks]]\r
+ default = 4\r
+ maximum = 10000\r
+ minimum = 1\r
+ type = integer\r
+ value = 4\r
+\r
+ [[min_deviation]]\r
+ default = 9\r
+ maximum = 100\r
+ minimum = 1\r
+ type = float\r
+ value = 9\r
+\r
--- /dev/null
+[genlist]\r
+ [[folder]]\r
+ default = ''\r
+ type = folder\r
+ value = 'R:\Programming\Python\Gui\data\dwell'\r
+\r
+ [[filemask]]\r
+ default = '*.*'\r
+ type = string\r
+ value = '*.*'\r
+\r
+[loadlist]\r
+ [[filename]]\r
+ default = 'test.hkp'\r
+ type = filename\r
+ value = 'R:\Programming\Python\Gui\untitled.hkp'\r
+\r
+[savelist]\r
+ [[filename]]\r
+ default = 'untitled.hkp'\r
+ type = filename\r
+ value = 'R:\Programming\Python\Gui\untitled.hkp'
\ No newline at end of file
--- /dev/null
+[generalvclamp]\r
+ [[flatten]]\r
+ default = True\r
+ type = boolean\r
+ value = True\r
+\r
+ [[max_cycles]]\r
+ default = 1\r
+ maximum = 100\r
+ minimum = 0\r
+ type = integer\r
+ value = 1\r
+\r
+ [[force_multiplier]]\r
+ default = 1\r
+ maximum = 100\r
+ minimum = 0\r
+ type = float\r
+ value = 1
\ No newline at end of file
--- /dev/null
+[drivers]\r
+csvdriver = boolean(default = False)\r
+hemingclamp = boolean(default = False)\r
+jpk = boolean(default = False)\r
+mcs = boolean(default = False)\r
+mfp1dexport = boolean(default = True)\r
+picoforce = boolean(default = True)\r
+picoforcealt = boolean(default = False)\r
+tutorialdriver = boolean(default = False)\r
+\r
+[folder]\r
+filterindex = integer(default = 0)\r
+filters = string(default = 'Playlist files (*.hkp)|*.hkp|Text files (*.txt)|*.txt|All files (*.*)|*.*')\r
+\r
+[general]\r
+list = string(default = 'test.hkp')\r
+workdir = string(default = '')\r
+\r
+[main]\r
+height = integer(default = 500)\r
+left = integer(default = 50)\r
+top = integer(default = 50)\r
+width = integer(default = 700)\r
+\r
+[plotmanipulators]\r
+names(default = list(correct, median, absvalue, flatten, multiplier, clamp, threshold, coincident))\r
+absvalue = boolean(default = False)\r
+clamp = boolean(default = True)\r
+coincident = boolean(default = True)\r
+correct = boolean(default = True)\r
+flatten = boolean(default = True)\r
+median = boolean(default = True)\r
+multiplier = boolean(default = True)\r
+threshold = boolean(default = True)\r
+\r
+[perspectives]\r
+active = string(default = Default)\r
+\r
+[plugins]\r
+autopeak = boolean(default = True)\r
+dummyguiplug = boolean(default = False)\r
+fit = boolean(default = True)\r
+flatfilts = boolean(default = True)\r
+generalclamp = boolean(default = True)\r
+generaltccd = boolean(default = True)\r
+generalvclamp = boolean(default = True)\r
+macro = boolean(default = True)\r
+massanalysis = boolean(default = True)\r
+pcluster = boolean(default = True)\r
+procplots = boolean(default = True)\r
+superimpose = boolean(default = False)\r
+tutorial = boolean(default = False)\r
+viewer = boolean(default = True)\r
+\r
+[splashscreen]\r
+#duration in milliseconds\r
+duration = integer(default = 1000)\r
+show = boolean(default = True)\r
+\r
+#name = string\r
+#age = float\r
+#attributes = string_list\r
+#likes_cheese = boolean\r
+#favourite_color = string
\ No newline at end of file
--- /dev/null
+#prefix with '#' to add a comment
+
+#Internal variables
+[display]
+colour_ext = None
+colour_ret = None
+ext = 1
+ret = 1
+correct = 1
+colour_correct = None
+contact_point = 0
+medfilt = 0
+xaxes = 0
+yaxes = 0
+flatten = 1
+temperature = 301
+auto_fit_points = 50
+auto_slope_span = 20
+auto_delta_force = 10
+auto_fit_nm = 5
+auto_min_p = 0.005
+auto_max_p = 10
+baseline_clicks = 0
+auto_left_baseline = 20
+auto_right_baseline = 20
+force_multiplier = 1
+fc_showphase = 0
+fc_showimposed = 0
+fc_interesting = 0
+tccd_threshold = 0
+tccd_coincident = 0
+
+[folders]
+filterindex = 0
+filters = Playlist files (*.hkp)|*.hkp|Text files (*.txt)|*.txt|All files (*.*)|*.*')
+
+[general]
+#substitute your work directory
+#workdir = D:\hooke
+workdir = R:\Programming\Python\Gui\
+#the default playlist to load at startup
+list = test.hkp
+#the default perspective to load at startup
+perspective = Default
+#splashscreen
+splash = 1
+splashduration = 1000
+
+#this section defines which plugins have to be loaded by Hooke
+[plugins]
+autopeak = True
+dummyguiplug = False
+fit = True
+flatfilts = True
+generalclamp = False
+generaltccd = False
+generalvclamp = True
+macro = False
+massanalysis = False
+pcluster = False
+procplots = True
+showconvoluted = True
+superimpose = False
+tutorial = False
+viewer = False
+#autopeak = True
+#dummyguiplug = False
+#fit = True
+#flatfilts = True
+#generalclamp = True
+#generaltccd = True
+#generalvclamp = True
+#macro = True
+#massanalysis = True
+#pcluster = True
+#procplots = True
+#superimpose = False
+#tutorial = False
+#viewer = True
+
+#this section defines which drivers have to be loaded by Hooke
+[drivers]
+csvdriver = False
+hemingclamp = False
+jpk = False
+mcs = False
+mfp1dexport = True
+picoforce = True
+picoforcealt = False
+tutorialdriver = False
+
+##this section defines which plot manipulators have to be loaded by Hooke,
+##and -IMPORTANTLY- their order.
+[plotmanipulators]
+absvalue = False
+clamp = False
+coincident = False
+correct = True
+flatten = False
+median = False
+multiplier = False
+names = correct, median, absvalue, flatten, multiplier, clamp, threshold, coincident, showconvoluted
+showconvoluted = False
+threshold = False
+
+#this section defines the window size and position
+[main]
+height = 797
+left = 536
+top = 20
+width = 1092
+
+[splashscreen]
+#duration in milliseconds
+duration = 1000
+show = False
+
+[perspectives]
+active = Default
+
+[folder]
--- /dev/null
+[pcluster]\r
+auto_fit_nm = 5\r
+auto_fit_points = 50\r
+auto_left_baseline = 20\r
+auto_max_p = 10\r
+auto_min_p = 0.005\r
+auto_right_baseline = 20\r
+auto_slope_span = 20\r
+baseline_clicks = 0\r
+temperature = 301
\ No newline at end of file
--- /dev/null
+[procplots]\r
+ [[median]]\r
+ default = 0\r
+ maximum = 100\r
+ minimum = 0\r
+ type = integer\r
+ value = 0\r
+\r
+ [[correct]]\r
+ default = True\r
+ type = boolean\r
+ value = True
\ No newline at end of file
--- /dev/null
+# Interface
+by Rolf Schmidt <rschmidt@alcor.concordia.ca>
+
+You can dock/undock all windows except for plot tab (I would like to
+disable docking above the menubar and instead have the windows dock
+beneath the menubar)
+
+You can save perspectives (delete perspectives however does not work yet).
+
+The 'Navigation' menubar works, the 'Main' menubar does not work yet.
+
+Closing plot tabs does not work properly, feedback on specific
+examples and error messages would be much appreciated
+
+In the 'Folders' pane you can double-click playlists (with hkp
+extension) to open them (you cannot double-click curves to open them)
+
+Commands in the 'Commands'-pane that work
+- autopeak (only partially, everything that has to do with clicking on the plot does not work)
+- genlist
+- loadlist
+- convfilt
+- flatfilt
+
+When you open or generate a playlist, Hooke seems to hang. This is
+actually not the case, just wait. Hooke loads all the curves into
+memory and applies all the plotmanipulators. In the future, there will
+be a progressbar to indicate the progress.
--- /dev/null
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+'''
+libhooke.py
+
+General library of internal objects and utilities for Hooke.
+
+Copyright (C) 2006 Massimo Sandal (University of Bologna, Italy).
+With algorithms contributed by Francesco Musiani (University of Bologna, Italy)
+
+This program is released under the GNU General Public License version 2.
+'''
+
+import scipy
+import numpy
+import xml.dom.minidom
+import os
+import os.path
+import string
+
+#import ConfigParser
+
+def config_file_path(filename, config_dir=None):
+ if config_dir == None:
+ config_dir = os.path.abspath(
+ os.path.join(os.path.dirname(os.path.dirname(__file__)), 'conf'))
+ return os.path.join(config_dir, filename)
+
+class HookeConfig(object):
+ '''
+ Handling of Hooke configuration file
+
+ Mostly based on the simple-yet-useful examples of the Python Library Reference
+ about xml.dom.minidom
+
+ FIXME: starting to look a mess, should require refactoring
+ '''
+
+ def __init__(self, config_dir=None):
+ self.config={}
+ self.config['install']={}
+ self.config['plugins']=[]
+ self.config['drivers']=[]
+ self.config['plotmanips']=[]
+ self.config_dir = config_dir
+
+ def load_config(self, filename):
+ myconfig=file(config_file_path(filename, config_dir=self.config_dir))
+
+ #the following 3 lines are needed to strip newlines. otherwise, since newlines
+ #are XML elements too, the parser would read them (and re-save them, multiplying
+ #newlines...)
+ #yes, I'm an XML n00b
+ the_file=myconfig.read()
+ the_file_lines=the_file.split('\n')
+ the_file=''.join(the_file_lines)
+
+ self.config_tree=xml.dom.minidom.parseString(the_file)
+
+ def getText(nodelist):
+ #take the text from a nodelist
+ #from Python Library Reference 13.7.2
+ rc = ''
+ for node in nodelist:
+ if node.nodeType == node.TEXT_NODE:
+ rc += node.data
+ return rc
+
+ def handleConfig(config):
+ install_elements=config.getElementsByTagName("install")
+ display_elements=config.getElementsByTagName("display")
+ plugins_elements=config.getElementsByTagName("plugins")
+ drivers_elements=config.getElementsByTagName("drivers")
+ defaultlist_elements=config.getElementsByTagName("defaultlist")
+ plotmanip_elements=config.getElementsByTagName("plotmanips")
+ handleInstall(install_elements)
+ handleDisplay(display_elements)
+ handlePlugins(plugins_elements)
+ handleDrivers(drivers_elements)
+ handleDefaultlist(defaultlist_elements)
+ handlePlotmanip(plotmanip_elements)
+
+ def handleInstall(install_elements):
+ for install in install_elements:
+ for node in install.childNodes:
+ if node.nodeType == node.TEXT_NODE:
+ continue
+ path = os.path.abspath(getText(node.childNodes).strip())
+ self.config['install'][str(node.tagName)] = path
+
+ def handleDisplay(display_elements):
+ for element in display_elements:
+ for attribute in element.attributes.keys():
+ self.config[attribute]=element.getAttribute(attribute)
+
+ def handlePlugins(plugins):
+ for plugin in plugins[0].childNodes:
+ try:
+ self.config['plugins'].append(str(plugin.tagName))
+ except: #if we allow fancy formatting of xml, there is a text node, so tagName fails for it...
+ pass
+ #FIXME: code duplication
+ def handleDrivers(drivers):
+ for driver in drivers[0].childNodes:
+ try:
+ self.config['drivers'].append(str(driver.tagName))
+ except: #if we allow fancy formatting of xml, there is a text node, so tagName fails for it...
+ pass
+
+ def handlePlotmanip(plotmanips):
+ for plotmanip in plotmanips[0].childNodes:
+ try:
+ self.config['plotmanips'].append(str(plotmanip.tagName))
+ except: #if we allow fancy formatting of xml, there is a text node, so tagName fails for it...
+ pass
+
+ def handleDefaultlist(defaultlist):
+ '''
+ default playlist
+ '''
+ dflist=getText(defaultlist[0].childNodes)
+ self.config['defaultlist']=dflist.strip()
+
+ handleConfig(self.config_tree)
+ #making items in the dictionary more machine-readable
+ for item in self.config.keys():
+ try:
+ self.config[item]=float(self.config[item])
+ except TypeError: #we are dealing with a list, probably. keep it this way.
+ try:
+ self.config[item]=eval(self.config[item])
+ except: #not a list, not a tuple, probably a string?
+ pass
+ except ValueError: #if we can't get it to a number, it must be None or a string
+ if string.lower(self.config[item])=='none':
+ self.config[item]=None
+ else:
+ pass
+
+ return self.config
+
+
+ def save_config(self, config_filename):
+ print 'Not Implemented.'
+ pass
+
+
+def debug():
+ '''
+ debug stuff from latest rewrite of hooke_playlist.py
+ should be removed sooner or later (or substituted with new debug code!)
+ '''
+ confo=HookeConfig()
+ print confo.load_config('hooke.conf')
Massimo Sandal (c) 2009
'''
-from .. import libhookecurve as lhc
+import os
+
from .. import libhooke as lh
+from .. import libhookecurve as lhc
+
+
+__version__='0.0.0.20090923'
+
class mfp1dexportDriver(lhc.Driver):
def __init__(self, filename):
-
- self.filename=filename
- self.filedata=open(filename,'rU')
- self.lines=list(self.filedata.readlines())
+ '''
+ This is a driver to import Asylum Research MFP 1D data.
+ Status: experimental
+ '''
+ self.filename = filename
+ self.filedata = open(filename,'rU')
+ self.lines = list(self.filedata.readlines())
self.filedata.close()
self.filetype='mfp1dexport'
def is_me(self):
try:
- self.raw_header=self.lines[0:38]
+ self.raw_header = self.lines[0:38]
except:
#Not enough lines for a header; not a good file
return False
#FIXME: We want a more reasonable header recognition
- if self.raw_header[0][0:4]=='Wave':
+ if self.raw_header[0].startswith('Wave'):
return True
else:
return False
#self.k=float(self.raw_header[23][8:])
self.k=float(kline[1])
-
xext=[]
xret=[]
yext=[]
return [[xext,yext],[xret,yret]]
def deflection(self):
- self.data=self._read_columns()
- return self.data[0][1],self.data[1][1]
-
+ self.data = self._read_columns()
+ return self.data[0][1], self.data[1][1]
def default_plots(self):
- main_plot=lhc.PlotObject()
- defl_ext,defl_ret=self.deflection()
- yextforce=[i*self.k for i in defl_ext]
- yretforce=[i*self.k for i in defl_ret]
- main_plot.add_set(self.data[0][0],yextforce)
- main_plot.add_set(self.data[1][0],yretforce)
+ main_plot = lhc.PlotObject()
+ defl_ext,defl_ret = self.deflection()
+ yextforce = [i*self.k for i in defl_ext]
+ yretforce = [i*self.k for i in defl_ret]
+ main_plot.add_set(self.data[0][0], yextforce)
+ main_plot.add_set(self.data[1][0], yretforce)
main_plot.normalize_vectors()
- main_plot.units=['Z','force'] #FIXME: if there's an header saying something about the time count, should be used
- main_plot.destination=0
- main_plot.title=self.filename
- #main_plot.colors=['red','blue']
+ #main_plot.units = ['Z','force'] #FIXME: if there's an header saying something about the time count, should be used
+ main_plot.units = ['m','N']
+ main_plot.destination = 0
+ main_plot.filename = self.filename
+ main_plot.title = os.path.basename(self.filename)
+ main_plot.colors = ['red','blue']
+ main_plot.style = ['plot','plot']
return [main_plot]
This program is released under the GNU General Public License version 2.
'''
-import re, struct
+import re
+import struct
from scipy import arange
+#from .. import libhooke as lh
from .. import libhookecurve as lhc
-__version__='0.0.0.20080404'
+
+__version__='0.0.0.20090923'
class DataChunk(list):
'''
constructor method
'''
-
+ filename = lh.get_file_path(filename)
self.textfile=file(filename)
self.binfile=file(filename,'rb')
main_plot=lhc.PlotObject()
- main_plot.vectors=[[zdomain.ext()[0:samples], force.ext()[0:samples]],[zdomain.ret()[0:samples], force.ret()[0:samples]]]
+ main_plot.vectors = [[zdomain.ext()[0:samples], force.ext()[0:samples]],[zdomain.ret()[0:samples], force.ret()[0:samples]]]
main_plot.normalize_vectors()
- main_plot.units=['meters','newton']
- main_plot.destination=0
- main_plot.title=self.filepath
-
+ main_plot.units = ['meters','newton']
+ main_plot.destination = 0
+ main_plit.filename = self.filepath
+ main_plot.title = self.filepath
+ main_plot.colors = ['red', 'blue']
+ main_plit.styles = ['plot', 'plot']
return [main_plot]
--- /dev/null
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+'''
+formatter.py
+
+Number formatting utilities for Hooke.
+
+Copyright (C) 2006 Massimo Sandal (University of Bologna, Italy).
+With algorithms contributed by Francesco Musiani (University of Bologna, Italy)
+
+This program is released under the GNU General Public License version 2.
+'''
+
+from matplotlib.ticker import ScalarFormatter
+
+from . import libhookecurve as lhc
+
+
+class EngrFormatter(ScalarFormatter):
+ """A variation of the standard ScalarFormatter, using only multiples of
+three
+in the mantissa. A fixed number of decimals can be displayed with the optional
+parameter `ndec` . If `ndec` is None (default), the number of decimals is
+defined
+from the current ticks.
+ """
+ def __init__(self, ndec=None, useOffset=True, useMathText=False):
+ ScalarFormatter.__init__(self, useOffset, useMathText)
+ if ndec is None or ndec < 0:
+ self.format = None
+ elif ndec == 0:
+ self.format = "%d"
+ else:
+ self.format = "%%1.%if" % ndec
+
+ def _set_orderOfMagnitude(self, mrange):
+ """Sets the order of magnitude."""
+ locs = numpy.absolute(self.locs)
+ if self.offset:
+ oom = numpy.floor(numpy.log10(mrange))
+ else:
+ if locs[0] > locs[-1]:
+ val = locs[0]
+ else:
+ val = locs[-1]
+ if val == 0:
+ oom = 0
+ else:
+ oom = numpy.floor(numpy.log10(val))
+ if oom <= -3:
+ self.orderOfMagnitude = 3*(oom//3)
+ elif oom <= -1:
+ self.orderOfMagnitude = -3
+ elif oom >= 4:
+ self.orderOfMagnitude = 3*(oom//3)
+ else:
+ self.orderOfMagnitude = 0
+
+ def _set_format(self):
+ """Sets the format string to format all ticklabels."""
+ # set the format string to format all the ticklabels
+ locs = (numpy.array(self.locs)-self.offset) / 10**self.orderOfMagnitude+1e-15
+ sigfigs = [len(str('%1.3f'% loc).split('.')[1].rstrip('0')) \
+ for loc in locs]
+ sigfigs.sort()
+ if self.format is None:
+ self.format = '%1.' + str(sigfigs[-1]) + 'f'
+ if self._usetex or self._useMathText: self.format = '$%s$'%self.format
#!/usr/bin/env python\r
-# -*- coding: utf-8 -*-\r
\r
'''\r
HOOKE - A force spectroscopy review & analysis tool\r
\r
-(C) 2008 Massimo Sandal\r
-\r
-Copyright (C) 2008 Massimo Sandal (University of Bologna, Italy).\r
+Copyright (C) 2008-2010 Massimo Sandal (University of Bologna, Italy).\r
+ Rolf Schmidt (Concordia University, Canada).\r
\r
This program is released under the GNU General Public License version 2.\r
'''\r
\r
-from .libhooke import HOOKE_VERSION, WX_GOOD\r
-\r
-import os\r
+from libhooke import WX_GOOD\r
\r
import wxversion\r
wxversion.select(WX_GOOD)\r
+import copy\r
+import cStringIO\r
+import os\r
+import os.path\r
+import sys\r
+import glob\r
+import time\r
+\r
+import imp\r
import wx\r
+import wx.html\r
+import wx.aui\r
import wxmpl\r
-from wx.lib.newevent import NewEvent\r
-\r
-import matplotlib.numerix as nx\r
-import scipy as sp\r
-\r
-from threading import Thread\r
-import Queue\r
-\r
-from .hooke_cli import HookeCli\r
-from .libhooke import HookeConfig, ClickedPoint\r
-from . import libhookecurve as lhc\r
-\r
-#import file versions, just to know with what we're working...\r
-from hooke_cli import __version__ as hookecli_version\r
+import wx.lib.agw.aui as aui\r
+import wx.propgrid as wxpg\r
+\r
+import libhooke as lh\r
+from config import config\r
+import drivers\r
+import plugins\r
+import hookecommands\r
+import hookeplaylist\r
+import hookepropertyeditor\r
+import hookeresults\r
+import playlist\r
\r
global __version__\r
-global events_from_gui\r
-global config\r
-global CLI_PLUGINS\r
-global GUI_PLUGINS\r
-global LOADED_PLUGINS\r
-global PLOTMANIP_PLUGINS\r
-global FILE_DRIVERS\r
-\r
-__version__=HOOKE_VERSION[0]\r
-__release_name__=HOOKE_VERSION[1]\r
-\r
-events_from_gui=Queue.Queue() #GUI ---> CLI COMMUNICATION\r
-\r
-print 'Starting Hooke.'\r
-#CONFIGURATION FILE PARSING\r
-config_obj=HookeConfig()\r
-config=config_obj.load_config('hooke.conf')\r
-\r
-#IMPORTING PLUGINS\r
-\r
-CLI_PLUGINS=[]\r
-GUI_PLUGINS=[]\r
-PLOTMANIP_PLUGINS=[]\r
-LOADED_PLUGINS=[]\r
-\r
-plugin_commands_namespaces=[]\r
-plugin_gui_namespaces=[]\r
-for plugin_name in config['plugins']:\r
- try:\r
- hooke_module=__import__('hooke.plugin.'+plugin_name)\r
- plugin = getattr(hooke_module.plugin, plugin_name)\r
- try:\r
- #take Command plugin classes\r
- commands = getattr(plugin, plugin_name+'Commands')\r
- CLI_PLUGINS.append(commands)\r
- plugin_commands_namespaces.append(dir(commands))\r
- except:\r
- pass\r
- try:\r
- #take Gui plugin classes\r
- gui = getattr(plugin, plugin_name+'Gui')\r
- GUI_PLUGINS.append(gui)\r
- plugin_gui_namespaces.append(dir(gui))\r
- except:\r
- pass\r
- except ImportError:\r
- print 'Cannot find plugin ',plugin_name\r
- else:\r
- LOADED_PLUGINS.append(plugin_name)\r
- print 'Imported plugin ',plugin_name\r
-\r
-#eliminate names common to all namespaces\r
-for i,namespace in enumerate(plugin_commands_namespaces):\r
- plugin_commands_namespaces[i] = \\r
- filter(lambda item : not (item.startswith('__')\r
- or item == '_plug_init'),\r
- namespace)\r
-#check for conflicts in namespaces between plugins\r
-#FIXME: only in commands now, because I don't have Gui plugins to check\r
-#FIXME: how to check for plugin-defined variables (self.stuff) ??\r
-plugin_commands_names=[]\r
-whatplugin_defines=[]\r
-plugin_gui_names=[]\r
-for namespace,plugin_name in zip(plugin_commands_namespaces, config['plugins']):\r
- for item in namespace:\r
- if item in plugin_commands_names:\r
- i=plugin_commands_names.index(item) #we exploit the fact index gives the *first* occurrence of a name...\r
- print 'Error. Plugin %s defines a function %s already defined by %s!' \\r
- % (plugin_name, item, whatplugin_defines[i])\r
- print 'This should not happen. Please disable one or both plugins and contact the plugin authors to solve the conflict.'\r
- print 'Hooke cannot continue.'\r
- exit()\r
- else:\r
- plugin_commands_names.append(item)\r
- whatplugin_defines.append(plugin_name)\r
-\r
-\r
-config['loaded_plugins']=LOADED_PLUGINS #FIXME: kludge -this should be global but not in config!\r
-#IMPORTING DRIVERS\r
-#FIXME: code duplication\r
-FILE_DRIVERS=[]\r
-LOADED_DRIVERS=[]\r
-for driver_name in config['drivers']:\r
- try:\r
- hooke_module=__import__('hooke.driver.'+driver_name)\r
- driver = getattr(hooke_module.driver, driver_name)\r
- try:\r
- FILE_DRIVERS.append(getattr(driver, driver_name+'Driver'))\r
- except:\r
- pass\r
- except ImportError:\r
- print 'Cannot find driver ',driver_name\r
- else:\r
- LOADED_DRIVERS.append(driver_name)\r
- print 'Imported driver ',driver_name\r
-config['loaded_drivers']=LOADED_DRIVERS\r
-\r
-#LIST OF CUSTOM WX EVENTS FOR CLI ---> GUI COMMUNICATION\r
-#FIXME: do they need to be here?\r
-list_of_events={}\r
-\r
-plot_graph, EVT_PLOT = NewEvent()\r
-list_of_events['plot_graph']=plot_graph\r
-\r
-plot_contact, EVT_PLOT_CONTACT = NewEvent()\r
-list_of_events['plot_contact']=plot_contact\r
-\r
-measure_points, EVT_MEASURE_POINTS = NewEvent()\r
-list_of_events['measure_points']=measure_points\r
-\r
-export_image, EVT_EXPORT_IMAGE = NewEvent()\r
-list_of_events['export_image']=export_image\r
-\r
-close_plot, EVT_CLOSE_PLOT = NewEvent()\r
-list_of_events['close_plot'] = close_plot\r
-\r
-show_plots, EVT_SHOW_PLOTS = NewEvent()\r
-list_of_events['show_plots'] = show_plots\r
-\r
-get_displayed_plot, EVT_GET_DISPLAYED_PLOT = NewEvent()\r
-list_of_events['get_displayed_plot'] = get_displayed_plot\r
-#------------\r
-\r
-class CliThread(Thread):\r
-\r
- def __init__(self,frame,list_of_events):\r
- Thread.__init__(self)\r
-\r
- #here we have to put temporary references to pass to the cli object.\r
- self.frame=frame\r
- self.list_of_events=list_of_events\r
-\r
- self.debug=0 #to be used in the future\r
-\r
- def run(self):\r
- print '\n\nThis is Hooke, version',__version__ , __release_name__\r
- print\r
- print '(c) Massimo Sandal & others, 2006-2008. Released under the GNU Lesser General Public License Version 3'\r
- print 'Hooke is Free software.'\r
- print '----'\r
- print ''\r
-\r
- def make_command_class(*bases):\r
- #FIXME: perhaps redundant\r
- return type(HookeCli)("HookeCliPlugged", bases + (HookeCli,), {})\r
- cli = make_command_class(*CLI_PLUGINS)(self.frame,self.list_of_events,events_from_gui,config,FILE_DRIVERS)\r
- cli.cmdloop()\r
\r
-'''\r
-GUI CODE\r
+__version__ = lh.HOOKE_VERSION[0]\r
+__release_name__ = lh.HOOKE_VERSION[1]\r
+\r
+#TODO: order menu items, get rid of all unused IDs\r
+ID_ExportText = wx.NewId()\r
+ID_ExportImage = wx.NewId()\r
+ID_Config = wx.NewId()\r
+ID_About = wx.NewId()\r
+ID_Next = wx.NewId()\r
+ID_Previous = wx.NewId()\r
+\r
+ID_ViewAssistant = wx.NewId()\r
+ID_ViewCommands = wx.NewId()\r
+ID_ViewFolders = wx.NewId()\r
+ID_ViewOutput = wx.NewId()\r
+ID_ViewPlaylists = wx.NewId()\r
+ID_ViewProperties = wx.NewId()\r
+ID_ViewResults = wx.NewId()\r
+\r
+ID_CommandsList = wx.NewId()\r
+ID_CommandsListBox = wx.NewId()\r
+\r
+ID_TextContent = wx.NewId()\r
+ID_TreeContent = wx.NewId()\r
+ID_HTMLContent = wx.NewId()\r
+ID_SizeReportContent = wx.NewId()\r
+ID_DeletePerspective = wx.NewId()\r
+ID_SavePerspective = wx.NewId()\r
+\r
+ID_FirstPerspective = ID_SavePerspective + 1000\r
+#I hope we'll never have more than 1000 perspectives\r
+ID_FirstPlot = ID_SavePerspective + 2000\r
+\r
+class Hooke(wx.App):\r
+\r
+ def OnInit(self):\r
+ self.SetAppName('Hooke')\r
+ self.SetVendorName('')\r
+\r
+ #set the Hooke directory\r
+ lh.hookeDir = os.path.abspath(os.path.dirname(__file__))\r
+\r
+ windowPosition = (config['main']['left'], config['main']['top'])\r
+ windowSize = (config['main']['width'], config['main']['height'])\r
+\r
+ #setup the splashscreen\r
+ if config['splashscreen']['show']:\r
+ filename = lh.get_file_path('hooke.jpg', ['resources'])\r
+ if os.path.isfile(filename):\r
+ bitmap = wx.Image(filename).ConvertToBitmap()\r
+ splashStyle = wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT\r
+ splashDuration = config['splashscreen']['duration']\r
+ wx.SplashScreen(bitmap, splashStyle, splashDuration, None, -1)\r
+ wx.Yield()\r
+ '''\r
+ we need for the splash screen to disappear\r
+ for whatever reason splashDuration and sleep do not correspond to each other\r
+ at least not on Windows\r
+ maybe it's because duration is in milliseconds and sleep in seconds\r
+ thus we need to increase the sleep time a bit\r
+ a factor of 1.2 seems to work quite well\r
+ '''\r
+ sleepFactor = 1.2\r
+ time.sleep(sleepFactor * splashDuration / 1000)\r
+\r
+ plugin_objects = []\r
+ for plugin in config['plugins']:\r
+ if config['plugins'][plugin]:\r
+ filename = ''.join([plugin, '.py'])\r
+ path = lh.get_file_path(filename, ['plugins'])\r
+ if os.path.isfile(path):\r
+ #get the corresponding filename and path\r
+ plugin_name = ''.join(['plugins.', plugin])\r
+ module = __import__(plugin_name)\r
+ #get the file that contains the plugin\r
+ class_file = getattr(plugins, plugin)\r
+ #get the class that contains the commands\r
+ class_object = getattr(class_file, plugin + 'Commands')\r
+ plugin_objects.append(class_object)\r
\r
-FIXME: put it in a separate module in the future?\r
-'''\r
-class MainMenuBar(wx.MenuBar):\r
- '''\r
- Creates the menu bar\r
- '''\r
- def __init__(self):\r
- wx.MenuBar.__init__(self)\r
- '''the menu description. the key of the menu is XX&Menu, where XX is a number telling\r
- the order of the menus on the menubar.\r
- &Menu is the Menu text\r
- the corresponding argument is ('&Item', 'itemname'), where &Item is the item text and itemname\r
- the inner reference to use in the self.menu_items dictionary.\r
-\r
- See create_menus() to see how it works\r
-\r
- Note: the mechanism on page 124 of "wxPython in Action" is less awkward, maybe, but I want\r
- binding to be performed later. Perhaps I'm wrong :)\r
- ''' \r
-\r
- self.menu_desc={'00&File':[('&Open playlist','openplaymenu'),('&Exit','exitmenu')], \r
- '01&Edit':[('&Export text...','exporttextmenu'),('&Export image...','exportimagemenu')],\r
- '02&Help':[('&About Hooke','aboutmenu')]}\r
- self.create_menus()\r
-\r
- def create_menus(self):\r
+ def make_command_class(*bases):\r
+ #create metaclass with plugins and plotmanipulators\r
+ return type(HookeFrame)("HookeFramePlugged", bases + (HookeFrame,), {})\r
+ frame = make_command_class(*plugin_objects)(parent=None, id=wx.ID_ANY, title='Hooke', pos=windowPosition, size=windowSize)\r
+ frame.Show(True)\r
+ self.SetTopWindow(frame)\r
+\r
+ return True\r
+\r
+ def OnExit(self):\r
+ #TODO: write values to ini file if necessary\r
+ return True\r
+\r
+\r
+class HookeFrame(wx.Frame):\r
+\r
+ def __init__(self, parent, id=-1, title='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN):\r
+ #call parent constructor\r
+ wx.Frame.__init__(self, parent, id, title, pos, size, style)\r
+ self.config = config\r
+ self.CreateApplicationIcon()\r
+ #self.configs contains: {the name of the Commands file: corresponding ConfigObj}\r
+ self.configs = {}\r
+ ##self.playlists contains: {the name of the playlist: [playlist, tabIndex, plotID]}\r
+ #self.playlists = {}\r
+ #self.plugins contains: {the name of the plugin: [caption, function]}\r
+ self.plugins = {}\r
+ #self.plotmanipulators list contains: [the name of the plotmanip, function, name of the module]\r
+ self.plotmanipulators = []\r
+\r
+ #tell FrameManager to manage this frame\r
+ self._mgr = aui.AuiManager()\r
+ self._mgr.SetManagedWindow(self)\r
+ #set the gradient style\r
+ self._mgr.GetArtProvider().SetMetric(aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_NONE)\r
+ #set transparent drag\r
+ self._mgr.SetFlags(self._mgr.GetFlags() ^ aui.AUI_MGR_TRANSPARENT_DRAG)\r
+\r
+ # set up default notebook style\r
+ self._notebook_style = aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.NO_BORDER\r
+ self._notebook_theme = 0\r
+\r
+ #holds the perspectives: {name, [index, perspectiveStr]}\r
+ self._perspectives = {}\r
+\r
+ # min size for the frame itself isn't completely done.\r
+ # see the end up FrameManager::Update() for the test\r
+ # code. For now, just hard code a frame minimum size\r
+ self.SetMinSize(wx.Size(400, 300))\r
+ #create panels here\r
+ self.panelAssistant = self.CreatePanelAssistant()\r
+ self.panelCommands = self.CreatePanelCommands()\r
+ self.panelFolders = self.CreatePanelFolders()\r
+ self.panelPlaylists = self.CreatePanelPlaylists()\r
+ self.panelProperties = self.CreatePanelProperties()\r
+ self.panelOutput = self.CreatePanelOutput()\r
+ self.panelResults = self.CreatePanelResults()\r
+ self.plotNotebook = self.CreateNotebook()\r
+ #self.textCtrlCommandLine=self.CreateCommandLine()\r
+\r
+ # add panes\r
+ self._mgr.AddPane(self.panelFolders, aui.AuiPaneInfo().Name('Folders').Caption('Folders').Left().CloseButton(True).MaximizeButton(False))\r
+ self._mgr.AddPane(self.panelPlaylists, aui.AuiPaneInfo().Name('Playlists').Caption('Playlists').Left().CloseButton(True).MaximizeButton(False))\r
+ self._mgr.AddPane(self.plotNotebook, aui.AuiPaneInfo().Name('Plots').CenterPane().PaneBorder(False))\r
+ self._mgr.AddPane(self.panelCommands, aui.AuiPaneInfo().Name('Commands').Caption('Settings and commands').Right().CloseButton(True).MaximizeButton(False))\r
+ self._mgr.AddPane(self.panelProperties, aui.AuiPaneInfo().Name('Properties').Caption('Properties').Right().CloseButton(True).MaximizeButton(False))\r
+ self._mgr.AddPane(self.panelAssistant, aui.AuiPaneInfo().Name('Assistant').Caption('Assistant').Right().CloseButton(True).MaximizeButton(False))\r
+ self._mgr.AddPane(self.panelOutput, aui.AuiPaneInfo().Name('Output').Caption('Output').Bottom().CloseButton(True).MaximizeButton(False))\r
+ self._mgr.AddPane(self.panelResults, aui.AuiPaneInfo().Name('Results').Caption('Results').Bottom().CloseButton(True).MaximizeButton(False))\r
+ #self._mgr.AddPane(self.textCtrlCommandLine, aui.AuiPaneInfo().Name('CommandLine').CaptionVisible(False).Fixed().Bottom().Layer(2).CloseButton(False).MaximizeButton(False))\r
+ #self._mgr.AddPane(panelBottom, aui.AuiPaneInfo().Name("panelCommandLine").Bottom().Position(1).CloseButton(False).MaximizeButton(False))\r
+\r
+ # add the toolbars to the manager\r
+ self.toolbar=self.CreateToolBar()\r
+ self.toolbarNavigation=self.CreateToolBarNavigation()\r
+ self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Name('toolbar').Caption('Toolbar').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))\r
+ self._mgr.AddPane(self.toolbarNavigation, aui.AuiPaneInfo().Name('toolbarNavigation').Caption('Navigation').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))\r
+ # "commit" all changes made to FrameManager\r
+ self._mgr.Update()\r
+ #create the menubar after the panes so that the default perspective\r
+ #is created with all panes open\r
+ self.CreateMenuBar()\r
+ self.statusbar = self.CreateStatusBar()\r
+ self._BindEvents()\r
+ #TODO: select item on startup (whatever item)\r
+ #self.listCtrlCommands.Select(0)\r
+ #self.OnListboxSelect(None)\r
+ name = self.config['perspectives']['active']\r
+ menu_item = self.GetPerspectiveMenuItem(name)\r
+ self.OnRestorePerspective(menu_item)\r
+ self.playlists = self.panelPlaylists.Playlists\r
+ #define the list of active drivers\r
+ self.drivers = []\r
+ for driver in self.config['drivers']:\r
+ if self.config['drivers'][driver]:\r
+ #get the corresponding filename and path\r
+ filename = ''.join([driver, '.py'])\r
+ path = lh.get_file_path(filename, ['drivers'])\r
+ #the driver is active for driver[1] == 1\r
+ if os.path.isfile(path):\r
+ #driver files are located in the 'drivers' subfolder\r
+ driver_name = ''.join(['drivers.', driver])\r
+ module = __import__(driver_name)\r
+ class_file = getattr(drivers, driver)\r
+ for command in dir(class_file):\r
+ if command.endswith('Driver'):\r
+ self.drivers.append(getattr(class_file, command))\r
+ #import all active plugins and plotmanips\r
+ #the plotmanip_functions contains: {the name of the plotmanip: [method, class_object]}\r
+ plotmanip_functions = {}\r
+ #add 'general.ini' to self.configs (this is not a plugin and thus must be imported seperately)\r
+ ini_path = lh.get_file_path('general.ini', ['plugins'])\r
+ plugin_config = ConfigObj(ini_path)\r
+ #self.config.merge(plugin_config)\r
+ self.configs['general'] = plugin_config\r
+ #make sure we execute _plug_init() for every command line plugin we import\r
+ for plugin in self.config['plugins']:\r
+ if self.config['plugins'][plugin]:\r
+ filename = ''.join([plugin, '.py'])\r
+ path = lh.get_file_path(filename, ['plugins'])\r
+ if os.path.isfile(path):\r
+ #get the corresponding filename and path\r
+ plugin_name = ''.join(['plugins.', plugin])\r
+ try:\r
+ #import the module\r
+ module = __import__(plugin_name)\r
+ #prepare the ini file for inclusion\r
+ ini_path = path.replace('.py', '.ini')\r
+ #include ini file\r
+ plugin_config = ConfigObj(ini_path)\r
+ #self.config.merge(plugin_config)\r
+ self.configs[plugin] = plugin_config\r
+ #add to plugins\r
+ commands = eval('dir(module.' + plugin+ '.' + plugin + 'Commands)')\r
+ #keep only commands (ie names that start with 'do_')\r
+ commands = [command for command in commands if command.startswith('do_')]\r
+ if commands:\r
+ self.plugins[plugin] = commands\r
+ try:\r
+ #initialize the plugin\r
+ eval('module.' + plugin+ '.' + plugin + 'Commands._plug_init(self)')\r
+ except AttributeError:\r
+ pass\r
+ except ImportError:\r
+ pass\r
+ #initialize the commands tree\r
+ commands = dir(HookeFrame)\r
+ commands = [command for command in commands if command.startswith('do_')]\r
+ if commands:\r
+ self.plugins['general'] = commands\r
+ self.panelCommands.Initialize(self.plugins)\r
+ for command in dir(self):\r
+ if command.startswith('plotmanip_'):\r
+ plotmanip_functions[command] = [command, getattr(self, command)]\r
+ for name in self.config['plotmanipulators']['names']:\r
+ if self.config['plotmanipulators'].as_bool(name):\r
+ command_name = ''.join(['plotmanip_', name])\r
+ if command_name in plotmanip_functions:\r
+ self.plotmanipulators.append(plotmanip_functions[command_name])\r
+ #load default list, if possible\r
+ self.do_loadlist(self.config['general']['list'])\r
+\r
+ def _BindEvents(self):\r
+ self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\r
+ self.Bind(wx.EVT_SIZE, self.OnSize)\r
+ self.Bind(wx.EVT_CLOSE, self.OnClose)\r
+ # Show How To Use The Closing Panes Event\r
+ self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)\r
+ self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnNotebookPageClose)\r
+ #menu\r
+ self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_EXIT)\r
+ self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)\r
+ #view\r
+ self.Bind(wx.EVT_MENU_RANGE, self.OnView, id=ID_ViewAssistant, id2=ID_ViewResults)\r
+ #perspectives\r
+ self.Bind(wx.EVT_MENU, self.OnDeletePerspective, id=ID_DeletePerspective)\r
+ self.Bind(wx.EVT_MENU, self.OnSavePerspective, id=ID_SavePerspective)\r
+ self.Bind(wx.EVT_MENU_RANGE, self.OnRestorePerspective, id=ID_FirstPerspective, id2=ID_FirstPerspective+1000)\r
+ #toolbar\r
+ self.Bind(wx.EVT_TOOL, self.OnExportImage, id=ID_ExportImage)\r
+ self.Bind(wx.EVT_TOOL, self.OnNext, id=ID_Next)\r
+ self.Bind(wx.EVT_TOOL, self.OnPrevious, id=ID_Previous)\r
+ #self.Bind(.EVT_AUITOOLBAR_TOOL_DROPDOWN, self.OnDropDownToolbarItem, id=ID_DropDownToolbarItem)\r
+ #dir control\r
+ treeCtrl = self.panelFolders.GetTreeCtrl()\r
+ #tree.Bind(wx.EVT_LEFT_UP, self.OnDirCtrl1LeftUp)\r
+ #tree.Bind(wx.EVT_LEFT_DOWN, self.OnGenericDirCtrl1LeftDown)\r
+ treeCtrl.Bind(wx.EVT_LEFT_DCLICK, self.OnDirCtrlLeftDclick)\r
+ #playlist tree\r
+ self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DOWN, self.OnPlaylistsLeftDown)\r
+ self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DCLICK, self.OnPlaylistsLeftDclick)\r
+ #commands tree\r
+ self.panelCommands.ExecuteButton.Bind(wx.EVT_BUTTON, self.OnExecute)\r
+ self.panelCommands.CommandsTree.Bind(wx.EVT_LEFT_DOWN, self.OnTreeCtrlCommandsLeftDown)\r
+ #property editor\r
+ self.panelProperties.pg.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChanged)\r
+ self.panelProperties.pg.Bind(wxpg.EVT_PG_SELECTED, self.OnPropGridSelect)\r
+ #results panel\r
+ self.panelResults.results_list.OnCheckItem = self.OnResultsCheck\r
+\r
+ def _GetActiveCurveIndex(self):\r
+ playlist = self.GetActivePlaylist()\r
+ #get the selected item from the tree\r
+ selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
+ #test if a playlist or a curve was double-clicked\r
+ if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):\r
+ return -1\r
+ else:\r
+ count = 0\r
+ selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)\r
+ while selected_item.IsOk():\r
+ count += 1\r
+ selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)\r
+ return count\r
+\r
+ def _GetActivePlaylistName(self):\r
+ #get the selected item from the tree\r
+ selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
+ #test if a playlist or a curve was double-clicked\r
+ if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):\r
+ playlist_item = selected_item\r
+ else:\r
+ #get the name of the playlist\r
+ playlist_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)\r
+ #now we have a playlist\r
+ return self.panelPlaylists.PlaylistsTree.GetItemText(playlist_item)\r
+\r
+ def _GetPlaylistTab(self, name):\r
+ for index, page in enumerate(self.plotNotebook._tabs._pages):\r
+ if page.caption == name:\r
+ return index\r
+ return -1\r
+\r
+ def _GetUniquePlaylistName(self, name):\r
+ playlist_name = name\r
+ count = 1\r
+ while playlist_name in self.playlists:\r
+ playlist_name = ''.join([name, str(count)])\r
+ count += 1\r
+ return playlist_name\r
+\r
+ def _SavePerspectiveToFile(self, name, perspective):\r
+ filename = ''.join([name, '.txt'])\r
+ filename = lh.get_file_path(filename, ['perspectives'])\r
+ perspectivesFile = open(filename, 'w')\r
+ perspectivesFile.write(perspective)\r
+ perspectivesFile.close()\r
+\r
+ def AddPlaylist(self, playlist=None, name='Untitled'):\r
+ #TODO: change cursor or progressbar (maybe in statusbar)\r
+ #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
+ if playlist and playlist.count > 0:\r
+ playlist.name = self._GetUniquePlaylistName(name)\r
+ playlist.reset()\r
+ self.AddToPlaylists(playlist)\r
+\r
+ def AddPlaylistFromFiles(self, files=[], name='Untitled'):\r
+ #TODO: change cursor or progressbar (maybe in statusbar)\r
+ #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
+ if files:\r
+ playlist = Playlist.Playlist(self.drivers)\r
+ for item in files:\r
+ playlist.add_curve(item)\r
+ if playlist.count > 0:\r
+ playlist.name = self._GetUniquePlaylistName(name)\r
+ playlist.reset()\r
+ self.AddToPlaylists(playlist)\r
+\r
+ def AddToPlaylists(self, playlist):\r
+ if playlist.has_curves:\r
+ #setup the playlist in the Playlist tree\r
+ tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()\r
+ playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)\r
+ #add all curves to the Playlist tree\r
+ curves = {}\r
+ for index, curve in enumerate(playlist.curves):\r
+ ##remove the extension from the name of the curve\r
+ ##TODO: optional?\r
+ #item_text, extension = os.path.splitext(curve.name)\r
+ #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)\r
+ curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)\r
+ if index == playlist.index:\r
+ self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)\r
+ playlist.reset()\r
+ #create the plot tab and add playlist to the dictionary\r
+ plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))\r
+ notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)\r
+ tab_index = self.plotNotebook.GetSelection()\r
+ figure = plotPanel.get_figure()\r
+ self.playlists[playlist.name] = [playlist, figure]\r
+ self.panelPlaylists.PlaylistsTree.Expand(playlist_root)\r
+ self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
+ self.UpdatePlot()\r
+\r
+ def AppendToOutput(self, text):\r
+ self.panelOutput.AppendText(''.join([text, '\n']))\r
+\r
+ def CreateApplicationIcon(self):\r
+ iconFile = 'resources' + os.sep + 'microscope.ico'\r
+ icon = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)\r
+ self.SetIcon(icon)\r
+\r
+ def CreateCommandLine(self):\r
+ return wx.TextCtrl(self, -1, '', style=wx.NO_BORDER|wx.EXPAND)\r
+\r
+ def CreatePanelAssistant(self):\r
+ panel = wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)\r
+ panel.SetEditable(False)\r
+ return panel\r
+\r
+ def CreatePanelCommands(self):\r
+ return hookecommands.Commands(self)\r
+\r
+ def CreatePanelFolders(self):\r
+ #set file filters\r
+ filters = self.config['folders']['filters']\r
+ index = self.config['folders'].as_int('filterindex')\r
+ #set initial directory\r
+ folder = self.config['general']['workdir']\r
+ return wx.GenericDirCtrl(self, -1, dir=folder, size=(200, 250), style=wx.DIRCTRL_SHOW_FILTERS, filter=filters, defaultFilter=index)\r
+\r
+ def CreatePanelOutput(self):\r
+ return wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)\r
+\r
+ def CreatePanelPlaylists(self):\r
+ return hookeplaylist.Playlists(self)\r
+\r
+ def CreatePanelProperties(self):\r
+ return hookepropertyeditor.PropertyEditor(self)\r
+\r
+ def CreatePanelResults(self):\r
+ return hookeresults.Results(self)\r
+\r
+ def CreatePanelWelcome(self):\r
+ ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300))\r
+ introStr = '<h1>Welcome to Hooke</h1>' + \\r
+ '<h3>Features</h3>' + \\r
+ '<ul>' + \\r
+ '<li>View, annotate, measure force curves</li>' + \\r
+ '<li>Worm-like chain fit of force peaks</li>' + \\r
+ '<li>Automatic convolution-based filtering of empty curves</li>' + \\r
+ '<li>Automatic fit and measurement of multiple force peaks</li>' + \\r
+ '<li>Handles force-clamp force experiments (experimental)</li>' + \\r
+ '<li>It is extensible by users by means of plugins and drivers</li>' + \\r
+ '</ul>' + \\r
+ '<p>See the <a href="/p/hooke/wiki/DocumentationIndex">DocumentationIndex</a> for more information</p>'\r
+ ctrl.SetPage(introStr)\r
+ return ctrl\r
+\r
+ def CreateMenuBar(self):\r
+ menu_bar = wx.MenuBar()\r
+ #file\r
+ file_menu = wx.Menu()\r
+ file_menu.Append(wx.ID_OPEN, '&Open playlist\tCtrl-O')\r
+ file_menu.Append(wx.ID_SAVE, 'Save playlist\tCtrl-S')\r
+ file_menu.AppendSeparator()\r
+ file_menu.Append(wx.ID_EXIT, 'Exit\tCtrl-Q')\r
+ #edit\r
+ edit_menu = wx.Menu()\r
+ edit_menu.Append(ID_ExportText, 'Export text...')\r
+ edit_menu.Append(ID_ExportImage, 'Export image...')\r
+ edit_menu.AppendSeparator();\r
+ edit_menu.Append(ID_Config, 'Preferences')\r
+ #view\r
+ view_menu = wx.Menu()\r
+ view_menu.AppendCheckItem(ID_ViewFolders, 'Folders\tF5')\r
+ view_menu.AppendCheckItem(ID_ViewPlaylists, 'Playlists\tF6')\r
+ view_menu.AppendCheckItem(ID_ViewCommands, 'Commands\tF7')\r
+ view_menu.AppendCheckItem(ID_ViewProperties, 'Properties\tF8')\r
+ view_menu.AppendCheckItem(ID_ViewAssistant, 'Assistant\tF9')\r
+ view_menu.AppendCheckItem(ID_ViewResults, 'Results\tF10')\r
+ view_menu.AppendCheckItem(ID_ViewOutput, 'Output\tF11')\r
+ #perspectives\r
+ self._perspectives_menu = self.CreatePerspectivesMenu()\r
+ #help\r
+ help_menu = wx.Menu()\r
+ help_menu.Append(wx.ID_ABOUT, 'About Hooke')\r
+ #put it all together\r
+ menu_bar.Append(file_menu, 'File')\r
+ menu_bar.Append(edit_menu, 'Edit')\r
+ menu_bar.Append(view_menu, 'View')\r
+ menu_bar.Append(self._perspectives_menu, "Perspectives")\r
+ menu_bar.Append(help_menu, 'Help')\r
+\r
+ self.SetMenuBar(menu_bar)\r
+\r
+ def CreateNotebook(self):\r
+ # create the notebook off-window to avoid flicker\r
+ client_size = self.GetClientSize()\r
+ ctrl = aui.AuiNotebook(self, -1, wx.Point(client_size.x, client_size.y), wx.Size(430, 200), self._notebook_style)\r
+ arts = [aui.AuiDefaultTabArt, aui.AuiSimpleTabArt, aui.VC71TabArt, aui.FF2TabArt, aui.VC8TabArt, aui.ChromeTabArt]\r
+ art = arts[self._notebook_theme]()\r
+ ctrl.SetArtProvider(art)\r
+ #uncomment if we find a nice icon\r
+ #page_bmp = wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))\r
+ ctrl.AddPage(self.CreatePanelWelcome(), "Welcome", False)\r
+ return ctrl\r
+\r
+ def CreatePerspectivesMenu(self):\r
+ menu = wx.Menu()\r
+ menu.Append(ID_SavePerspective, "Save Perspective")\r
+ menu.Append(ID_DeletePerspective, "Delete Perspective")\r
+ menu.AppendSeparator()\r
+ #add perspectives to menubar and _perspectives\r
+ perspectivesDirectory = os.path.join(lh.hookeDir, 'perspectives')\r
+ if os.path.isdir(perspectivesDirectory):\r
+ perspectiveFileNames = os.listdir(perspectivesDirectory)\r
+ for perspectiveFilename in perspectiveFileNames:\r
+ filename = lh.get_file_path(perspectiveFilename, ['perspectives'])\r
+ if os.path.isfile(filename):\r
+ perspectiveFile = open(filename, 'rU')\r
+ perspective = perspectiveFile.readline()\r
+ perspectiveFile.close()\r
+ if perspective != '':\r
+ name, extension = os.path.splitext(perspectiveFilename)\r
+ if extension == '.txt':\r
+ menuItem = menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)\r
+ self._perspectives[name] = [len(self._perspectives), perspective]\r
+ if self.config['perspectives']['active'] == name:\r
+ menuItem.Check()\r
+ #in case there are no perspectives\r
+ if not self._perspectives:\r
+ perspective = self._mgr.SavePerspective()\r
+ self.config['perspectives']['default'] = 'Default'\r
+ self._perspectives['Default'] = [0, perspective]\r
+ menuItem = menu.AppendRadioItem(ID_FirstPerspective, 'Default')\r
+ menuItem.Check()\r
+ self._SavePerspectiveToFile('Default', perspective)\r
+ return menu\r
+\r
+ def CreateStatusbar(self):\r
+ statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)\r
+ statusbar.SetStatusWidths([-2, -3])\r
+ statusbar.SetStatusText('Ready', 0)\r
+ welcomeString=u'Welcome to Hooke (version '+__version__+', '+__release_name__+')!'\r
+ statusbar.SetStatusText(welcomeString, 1)\r
+ return statusbar\r
+\r
+ def CreateToolBar(self):\r
+ toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)\r
+ toolbar.SetToolBitmapSize(wx.Size(16,16))\r
+ toolbar_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(16, 16))\r
+ toolbar_bmpOpen = wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, wx.Size(16, 16))\r
+ toolbar_bmpSave = wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, wx.Size(16, 16))\r
+ toolbar_bmpExportText = wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))\r
+ toolbar_bmpExportImage = wx.ArtProvider_GetBitmap(wx.ART_MISSING_IMAGE, wx.ART_OTHER, wx.Size(16, 16))\r
+ toolbar.AddLabelTool(101, 'Open', toolbar_bmpOpen)\r
+ toolbar.AddLabelTool(102, 'Save', toolbar_bmpSave)\r
+ toolbar.AddSeparator()\r
+ toolbar.AddLabelTool(ID_ExportText, 'Export text...', toolbar_bmpExportText)\r
+ toolbar.AddLabelTool(ID_ExportImage, 'Export image...', toolbar_bmpExportImage)\r
+ toolbar.Realize()\r
+ return toolbar\r
+\r
+ def CreateToolBarNavigation(self):\r
+ toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)\r
+ toolbar.SetToolBitmapSize(wx.Size(16,16))\r
+ toolbar_bmpBack = wx.ArtProvider_GetBitmap(wx.ART_GO_BACK, wx.ART_OTHER, wx.Size(16, 16))\r
+ toolbar_bmpForward = wx.ArtProvider_GetBitmap(wx.ART_GO_FORWARD, wx.ART_OTHER, wx.Size(16, 16))\r
+ toolbar.AddLabelTool(ID_Previous, 'Previous', toolbar_bmpBack, shortHelp='Previous curve')\r
+ toolbar.AddLabelTool(ID_Next, 'Next', toolbar_bmpForward, shortHelp='Next curve')\r
+ toolbar.Realize()\r
+ return toolbar\r
+\r
+ def DeleteFromPlaylists(self, name):\r
+ if name in self.playlists:\r
+ del self.playlists[name]\r
+ tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()\r
+ item, cookie = self.panelPlaylists.PlaylistsTree.GetFirstChild(tree_root)\r
+ while item.IsOk():\r
+ playlist_name = self.panelPlaylists.PlaylistsTree.GetItemText(item)\r
+ if playlist_name == name:\r
+ try:\r
+ self.panelPlaylists.PlaylistsTree.Delete(item)\r
+ except:\r
+ pass\r
+ item = self.panelPlaylists.PlaylistsTree.GetNextSibling(item)\r
+ self.OnPlaylistsLeftDclick(None)\r
+\r
+ def DeletePlotPage(self, name):\r
+ index = self._GetPlaylistTab(name)\r
+ plot = self.playlists[name][1]\r
+ plot = None\r
+ self.plotNotebook.RemovePage(index)\r
+ self.DeleteFromPlaylists(name)\r
+\r
+ def GetActiveCurve(self):\r
+ playlist = self.GetActivePlaylist()\r
+ if playlist is not None:\r
+ return playlist.get_active_curve()\r
+ return None\r
+\r
+ def GetActivePlaylist(self):\r
+ playlist_name = self._GetActivePlaylistName()\r
+ if playlist_name in self.playlists:\r
+ return self.playlists[playlist_name][0]\r
+ return None\r
+\r
+ def GetActivePlot(self):\r
+ curve = self.GetActiveCurve()\r
+ if curve is not None:\r
+ return curve.plots[0]\r
+ return None\r
+\r
+ def GetDockArt(self):\r
+ return self._mgr.GetArtProvider()\r
+\r
+ def GetBoolFromConfig(self, *args):\r
+ if len(args) == 2:\r
+ plugin = args[0]\r
+ section = args[0]\r
+ key = args[1]\r
+ elif len(args) == 3:\r
+ plugin = args[0]\r
+ section = args[1]\r
+ key = args[2]\r
+ if self.configs.has_key(plugin):\r
+ config = self.configs[plugin]\r
+ return config[section][key].as_bool('value')\r
+ return None\r
+\r
+ def GetFloatFromConfig(self, *args):\r
+ if len(args) == 2:\r
+ plugin = args[0]\r
+ section = args[0]\r
+ key = args[1]\r
+ elif len(args) == 3:\r
+ plugin = args[0]\r
+ section = args[1]\r
+ key = args[2]\r
+ if self.configs.has_key(plugin):\r
+ config = self.configs[plugin]\r
+ return config[section][key].as_float('value')\r
+ return None\r
+\r
+ def GetIntFromConfig(self, *args):\r
+ if len(args) == 2:\r
+ plugin = args[0]\r
+ section = args[0]\r
+ key = args[1]\r
+ elif len(args) == 3:\r
+ plugin = args[0]\r
+ section = args[1]\r
+ key = args[2]\r
+ if self.configs.has_key(plugin):\r
+ config = self.configs[plugin]\r
+ return config[section][key].as_int('value')\r
+ return None\r
+\r
+ def GetStringFromConfig(self, *args):\r
+ if len(args) == 2:\r
+ plugin = args[0]\r
+ section = args[0]\r
+ key = args[1]\r
+ elif len(args) == 3:\r
+ plugin = args[0]\r
+ section = args[1]\r
+ key = args[2]\r
+ if self.configs.has_key(plugin):\r
+ config = self.configs[plugin]\r
+ return config[section][key]['value']\r
+ return None\r
+\r
+ def GetPerspectiveMenuItem(self, name):\r
+ index = self._perspectives[name][0]\r
+ perspective_Id = ID_FirstPerspective + index\r
+ menu_item = self.MenuBar.FindItemById(perspective_Id)\r
+ return menu_item\r
+\r
+ def HasPlotmanipulator(self, name):\r
'''\r
- Smartish routine to create the menu from the self.menu_desc dictionary\r
- Hope it's a workable solution for the future.\r
+ returns True if the plotmanipulator 'name' is loaded, False otherwise\r
'''\r
- self.menus=[] #the menu objects to append to the menubar\r
- self.menu_items={} #the single menu items dictionary, to bind to events\r
-\r
- names=self.menu_desc.keys() #we gotta sort, because iterating keys goes in odd order\r
- names.sort()\r
-\r
- for name in names:\r
- self.menus.append(wx.Menu())\r
- for menu_item in self.menu_desc[name]:\r
- self.menu_items[menu_item[1]]=self.menus[-1].Append(-1, menu_item[0])\r
-\r
- for menu,name in zip(self.menus,names):\r
- self.Append(menu,name[2:])\r
-\r
-class MainPanel(wx.Panel):\r
- def __init__(self,parent,id): \r
-\r
- wx.Panel.__init__(self,parent,id)\r
- self.splitter = wx.SplitterWindow(self)\r
-\r
-ID_FRAME=100 \r
-class MainWindow(wx.Frame):\r
- '''we make a frame inheriting wx.Frame and setting up things on the init'''\r
- def __init__(self,parent,id,title):\r
-\r
- #-----------------------------\r
- #WX WIDGETS INITIALIZATION\r
-\r
- wx.Frame.__init__(self,parent,ID_FRAME,title,size=(800,600),style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)\r
-\r
- self.mainpanel=MainPanel(self,-1)\r
- self.cpanels=[]\r
-\r
- self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))\r
- self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))\r
-\r
- self.statusbar=wx.StatusBar(self,-1)\r
- self.SetStatusBar(self.statusbar)\r
-\r
- self.mainmenubar=MainMenuBar()\r
- self.SetMenuBar(self.mainmenubar)\r
-\r
- self.controls=[]\r
- self.figures=[]\r
- self.axes=[]\r
-\r
- #This is our matplotlib plot\r
- self.controls.append(wxmpl.PlotPanel(self.cpanels[0],-1))\r
- self.controls.append(wxmpl.PlotPanel(self.cpanels[1],-1))\r
- #These are our figure and axes, so to have easy references\r
- #Also, we initialize\r
- self.figures=[control.get_figure() for control in self.controls]\r
- self.axes=[figure.gca() for figure in self.figures]\r
+ for plotmanipulator in self.plotmanipulators:\r
+ if plotmanipulator[0] == name:\r
+ return True\r
+ return False\r
+\r
+ def OnAbout(self, event):\r
+ msg = 'Hooke\n\n'+\\r
+ 'A free, open source data analysis platform\n'+\\r
+ '(c) 2006-2008 Massimo Sandal\n\n'+\\r
+ '(c) 2009 Dr. Rolf Schmidt\n\n'+\\r
+ 'Released under the GNU GPL v2'\r
+ dialog = wx.MessageDialog(self, msg, "About Hooke", wx.OK | wx.ICON_INFORMATION)\r
+ dialog.ShowModal()\r
+ dialog.Destroy()\r
+\r
+ def OnClose(self, event):\r
+ #apply changes\r
+ self.config['main']['height'] = str(self.GetSize().GetHeight())\r
+ self.config['main']['left'] = str(self.GetPosition()[0])\r
+ self.config['main']['top'] = str(self.GetPosition()[1])\r
+ self.config['main']['width'] = str(self.GetSize().GetWidth())\r
+ # Writing the configuration file to 'hooke.ini'\r
+ self.config.write()\r
+ self._mgr.UnInit()\r
+ del self._mgr\r
+ self.Destroy()\r
+\r
+ def OnDeletePerspective(self, event):\r
+ pass\r
\r
- for i in range(len(self.axes)):\r
- self.axes[i].xaxis.set_major_formatter(EngrFormatter())\r
- self.axes[i].yaxis.set_major_formatter(EngrFormatter(2))\r
+ def OnDirCtrlLeftDclick(self, event):\r
+ file_path = self.panelFolders.GetPath()\r
+ if os.path.isfile(file_path):\r
+ if file_path.endswith('.hkp'):\r
+ self.do_loadlist(file_path)\r
+ else:\r
+ pass\r
+ event.Skip()\r
\r
+ def OnEraseBackground(self, event):\r
+ event.Skip()\r
\r
- self.cpanels[1].Hide()\r
- self.mainpanel.splitter.Initialize(self.cpanels[0])\r
+ def OnExecute(self, event):\r
+ item = self.panelCommands.CommandsTree.GetSelection()\r
+ if item.IsOk():\r
+ if self.panelCommands.CommandsTree.ItemHasChildren(item):\r
+ pass\r
+ else:\r
+ #get the plugin\r
+ parent = self.panelCommands.CommandsTree.GetItemParent(item)\r
+ if not self.panelCommands.CommandsTree.ItemHasChildren(item):\r
+ parent_text = self.panelCommands.CommandsTree.GetItemText(parent)\r
+ item_text = self.panelCommands.CommandsTree.GetItemText(item)\r
+ if item_text in ['genlist', 'loadlist', 'savelist']:\r
+ property_values = self.panelProperties.GetPropertyValues()\r
+ arg_str = ''\r
+ for item in property_values:\r
+ arg_str = ''.join([arg_str, item, '=r"', str(property_values[item]), '", '])\r
+ command = ''.join(['self.do_', item_text, '(', arg_str, ')'])\r
+ else:\r
+ command = ''.join(['self.do_', item_text, '()'])\r
+ exec(command)\r
+ pass\r
\r
- self.sizer_dance() #place/size the widgets\r
+ def OnExit(self, event):\r
+ self.Close()\r
\r
- self.controls[0].SetSize(self.cpanels[0].GetSize())\r
- self.controls[1].SetSize(self.cpanels[1].GetSize())\r
+ def OnExportImage(self, event):\r
+ pass\r
\r
- #resize the frame to properly draw on Windows\r
- frameSize=self.GetSize()\r
- frameSize.DecBy(1, 1)\r
- self.SetSize(frameSize)\r
+ def OnNext(self, event):\r
'''\r
- #if you need the exact same size as before DecBy, uncomment this block\r
- frameSize.IncBy(1, 1)\r
- self.SetSize(frameSize)\r
+ NEXT\r
+ Go to the next curve in the playlist.\r
+ If we are at the last curve, we come back to the first.\r
+ -----\r
+ Syntax: next, n\r
'''\r
-\r
- #-------------------------------------------\r
- #NON-WX WIDGETS INITIALIZATION\r
-\r
- #Flags.\r
- self.click_plot=0\r
-\r
- #FIXME: These could become a single flag with different (string?) values\r
- #self.on_measure_distance=False\r
- #self.on_measure_force=False\r
-\r
- self.plot_fit=False\r
-\r
- #Number of points to be clicked\r
- self.num_of_points = 2\r
-\r
- #Data.\r
+ selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
+ if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):\r
+ #GetFirstChild returns a tuple\r
+ #we only need the first element\r
+ next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(selected_item)[0]\r
+ else:\r
+ next_item = self.panelPlaylists.PlaylistsTree.GetNextSibling(selected_item)\r
+ if not next_item.IsOk():\r
+ parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)\r
+ #GetFirstChild returns a tuple\r
+ #we only need the first element\r
+ next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(parent_item)[0]\r
+ self.panelPlaylists.PlaylistsTree.SelectItem(next_item, True)\r
+ playlist = self.playlists[self._GetActivePlaylistName()][0]\r
+ if playlist.count > 1:\r
+ playlist.next()\r
+ self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
+ self.UpdatePlot()\r
+\r
+ def OnNotebookPageClose(self, event):\r
+ ctrl = event.GetEventObject()\r
+ playlist_name = ctrl.GetPageText(ctrl._curpage)\r
+ self.DeleteFromPlaylists(playlist_name)\r
+\r
+ def OnPaneClose(self, event):\r
+ event.Skip()\r
+\r
+ def OnPlaylistsLeftDclick(self, event):\r
+ playlist_name = self._GetActivePlaylistName()\r
+ #if that playlist already exists\r
+ #we check if it is the active playlist (ie selected in panelPlaylists)\r
+ #and switch to it if necessary\r
+ if playlist_name in self.playlists:\r
+ index = self.plotNotebook.GetSelection()\r
+ current_playlist = self.plotNotebook.GetPageText(index)\r
+ #new_playlist = self.playlists[playlist_name][0]\r
+ #if current_playlist != new_playlist:\r
+ if current_playlist != playlist_name:\r
+ index = self._GetPlaylistTab(playlist_name)\r
+ self.plotNotebook.SetSelection(index)\r
+ #if a curve was double-clicked\r
+ item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
+ #TODO: fix with get_active_curve\r
+ if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):\r
+ index = self._GetActiveCurveIndex()\r
+ else:\r
+ index = 0\r
+ if index >= 0:\r
+ playlist = self.playlists[playlist_name][0]\r
+ playlist.index = index\r
+ self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
+ self.UpdatePlot()\r
+ #if you uncomment the following line, the tree will collapse/expand as well\r
+ #event.Skip()\r
+\r
+ def OnPlaylistsLeftDown(self, event):\r
+ hit_item, hit_flags = self.panelPlaylists.PlaylistsTree.HitTest(event.GetPosition())\r
+ if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:\r
+ #self.SetFocus()\r
+ self.panelPlaylists.PlaylistsTree.SelectItem(hit_item)\r
+ playlist_name = self._GetActivePlaylistName()\r
+ playlist = self.playlists[playlist_name][0]\r
+ #if a curve was clicked\r
+ item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
+ if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):\r
+ #TODO: fix with get_active_curve\r
+ index = self._GetActiveCurveIndex()\r
+ if index >= 0:\r
+ #playlist = self.playlists[playlist_name][0]\r
+ playlist.index = index\r
+ #self.playlists[playlist_name][0].index = index\r
+ #else:\r
+ ##self.playlists[playlist_name][0].index = 0\r
+ #playlist.index = index\r
+ self.playlists[playlist_name][0] = playlist\r
+ event.Skip()\r
+\r
+ def OnPrevious(self, event):\r
'''\r
- self.current_x_ext=[[],[]]\r
- self.current_y_ext=[[],[]]\r
- self.current_x_ret=[[],[]]\r
- self.current_y_ret=[[],[]]\r
-\r
-\r
- self.current_x_unit=[None,None]\r
- self.current_y_unit=[None,None]\r
- '''\r
-\r
- #Initialize xaxes, yaxes\r
- #FIXME: should come from config\r
- self.current_xaxes=0\r
- self.current_yaxes=0\r
-\r
- #Other\r
-\r
-\r
- self.index_buffer=[]\r
+ PREVIOUS\r
+ Go to the previous curve in the playlist.\r
+ If we are at the first curve, we jump to the last.\r
+ -------\r
+ Syntax: previous, p\r
+ '''\r
+ #playlist = self.playlists[self._GetActivePlaylistName()][0]\r
+ #select the previous curve and tell the user if we wrapped around\r
+ #self.AppendToOutput(playlist.previous())\r
+ selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
+ if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):\r
+ previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(selected_item)\r
+ else:\r
+ previous_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)\r
+ if not previous_item.IsOk():\r
+ parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)\r
+ previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(parent_item)\r
+ self.panelPlaylists.PlaylistsTree.SelectItem(previous_item, True)\r
+ playlist = self.playlists[self._GetActivePlaylistName()][0]\r
+ if playlist.count > 1:\r
+ playlist.previous()\r
+ self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
+ self.UpdatePlot()\r
+\r
+ def OnPropGridChanged (self, event):\r
+ prop = event.GetProperty()\r
+ if prop:\r
+ item_section = self.panelProperties.SelectedTreeItem\r
+ item_plugin = self.panelCommands.CommandsTree.GetItemParent(item_section)\r
+ plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)\r
+ config = self.configs[plugin]\r
+ property_section = self.panelCommands.CommandsTree.GetItemText(item_section)\r
+ property_key = prop.GetName()\r
+ property_value = prop.GetValue()\r
+ config[property_section][property_key]['value'] = property_value\r
+\r
+ def OnPropGridSelect(self, event):\r
+ pass\r
\r
- self.clicked_points=[]\r
+ def OnRestorePerspective(self, event):\r
+ name = self.MenuBar.FindItemById(event.GetId()).GetLabel()\r
+ self._mgr.LoadPerspective(self._perspectives[name][1])\r
+ self.config['perspectives']['active'] = name\r
+ self._mgr.Update()\r
+ all_panes = self._mgr.GetAllPanes()\r
+ for pane in all_panes:\r
+ if not pane.name.startswith('toolbar'):\r
+ if pane.name == 'Assistant':\r
+ self.MenuBar.FindItemById(ID_ViewAssistant).Check(pane.window.IsShown())\r
+ if pane.name == 'Folders':\r
+ self.MenuBar.FindItemById(ID_ViewFolders).Check(pane.window.IsShown())\r
+ if pane.name == 'Playlists':\r
+ self.MenuBar.FindItemById(ID_ViewPlaylists).Check(pane.window.IsShown())\r
+ if pane.name == 'Commands':\r
+ self.MenuBar.FindItemById(ID_ViewCommands).Check(pane.window.IsShown())\r
+ if pane.name == 'Properties':\r
+ self.MenuBar.FindItemById(ID_ViewProperties).Check(pane.window.IsShown())\r
+ if pane.name == 'Output':\r
+ self.MenuBar.FindItemById(ID_ViewOutput).Check(pane.window.IsShown())\r
+ if pane.name == 'Results':\r
+ self.MenuBar.FindItemById(ID_ViewResults).Check(pane.window.IsShown())\r
+\r
+ def OnResultsCheck(self, index, flag):\r
+ curve = self.GetActiveCurve()\r
+ result = curve.data['results'][index]['visible'] = flag\r
+ self.UpdatePlot()\r
+\r
+ def OnSavePerspective(self, event):\r
+ def nameExists(name):\r
+ for item in self._perspectives_menu.GetMenuItems():\r
+ if item.GetText() == name:\r
+ return True\r
+ return False\r
+\r
+ done = False\r
+ while not done:\r
+ dialog = wx.TextEntryDialog(self, 'Enter a name for the new perspective:', 'Save perspective')\r
+ dialog.SetValue('New perspective')\r
+ if dialog.ShowModal() != wx.ID_OK:\r
+ return\r
+ else:\r
+ name = dialog.GetValue()\r
\r
- self.measure_set=None\r
+ if nameExists(name):\r
+ dialogConfirm = wx.MessageDialog(self, 'A file with this name already exists.\n\nDo you want to replace it?', 'Confirm', wx.YES_NO|wx.ICON_QUESTION|wx.CENTER)\r
+ if dialogConfirm.ShowModal() == wx.ID_YES:\r
+ done = True\r
+ else:\r
+ done = True\r
\r
- self.events_from_gui = events_from_gui\r
+ perspective = self._mgr.SavePerspective()\r
\r
+ if nameExists(name):\r
+ #check the corresponding menu item\r
+ menuItem = self.GetPerspectiveMenuItem(name)\r
+ #replace the perspectiveStr in _pespectives\r
+ index = self._perspectives[name][0]\r
+ self._perspectives[name] = [index, perspective]\r
+ else:\r
+ #simply add the new perspective to _perspectives\r
+ index = len(self._perspectives)\r
+ self._perspectives[name] = [len(self._perspectives), perspective]\r
+ menuItem = self._perspectives_menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)\r
+\r
+ menuItem.Check()\r
+ self._SavePerspectiveToFile(name, perspective)\r
+ #uncheck all perspective menu items\r
+ #as these are radio items, one item has to be checked at all times\r
+ #the line 'menuItem.Check()' above actually checks a second item\r
+ #but does not toggle\r
+ #so we need to uncheck all other items afterwards\r
+ #weirdly enough, menuitem.Toggle() doesn't do this properly either\r
+ for item in self._perspectives_menu.GetMenuItems():\r
+ if item.IsCheckable():\r
+ if item.GetLabel() != name:\r
+ item.Check(False)\r
+\r
+ def OnView(self, event):\r
+ menu_id = event.GetId()\r
+ menu_item = self.MenuBar.FindItemById(menu_id)\r
+ menu_label = menu_item.GetLabel()\r
+\r
+ pane = self._mgr.GetPane(menu_label)\r
+ pane.Show(not pane.IsShown())\r
+ #if we don't do the following, the Folders pane does not resize properly on hide/show\r
+ if pane.caption == 'Folders' and pane.IsShown() and pane.IsDocked():\r
+ #folders_size = pane.GetSize()\r
+ self.panelFolders.Fit()\r
+ self._mgr.Update()\r
+\r
+ def OnSize(self, event):\r
+ event.Skip()\r
+\r
+ def OnTreeCtrlCommandsLeftDown(self, event):\r
+ hit_item, hit_flags = self.panelCommands.CommandsTree.HitTest(event.GetPosition())\r
+ if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:\r
+ self.panelCommands.CommandsTree.SelectItem(hit_item)\r
+ self.panelProperties.SelectedTreeItem = hit_item\r
+ #if a command was clicked\r
+ properties = []\r
+ if not self.panelCommands.CommandsTree.ItemHasChildren(hit_item):\r
+ item_plugin = self.panelCommands.CommandsTree.GetItemParent(hit_item)\r
+ plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)\r
+ if self.configs.has_key(plugin):\r
+ #config = self.panelCommands.CommandsTree.GetPyData(item_plugin)\r
+ config = self.configs[plugin]\r
+ section = self.panelCommands.CommandsTree.GetItemText(hit_item)\r
+ #display docstring in help window\r
+ doc_string = eval('self.do_' + section + '.__doc__')\r
+ if section in config:\r
+ for option in config[section]:\r
+ properties.append([option, config[section][option]])\r
+ else:\r
+ module = self.panelCommands.CommandsTree.GetItemText(hit_item)\r
+ if module != 'general':\r
+ doc_string = eval('plugins.' + module + '.' + module + 'Commands.__doc__')\r
+ else:\r
+ doc_string = 'The module "general" contains Hooke core functionality'\r
+ if doc_string is not None:\r
+ self.panelAssistant.ChangeValue(doc_string)\r
+ hookepropertyeditor.PropertyEditor.Initialize(self.panelProperties, properties)\r
+ event.Skip()\r
+\r
+ def UpdatePlaylists(self):\r
+ #setup the playlist in the Playlist tree\r
+ tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()\r
+ playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)\r
+ #add all curves to the Playlist tree\r
+ curves = {}\r
+ for index, curve in enumerate(playlist.curves):\r
+ ##remove the extension from the name of the curve\r
+ ##TODO: optional?\r
+ #item_text, extension = os.path.splitext(curve.name)\r
+ #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)\r
+ curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)\r
+ if index == playlist.index:\r
+ self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)\r
+ #create the plot tab and add playlist to the dictionary\r
+ plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))\r
+ notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)\r
+ #tab_index = self.plotNotebook.GetSelection()\r
+ figure = plotPanel.get_figure()\r
+ #self.playlists[playlist.name] = [playlist, tab_index, figure]\r
+ self.playlists[playlist.name] = [playlist, figure]\r
+ self.panelPlaylists.PlaylistsTree.Expand(playlist_root)\r
+ self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
+ self.UpdatePlot()\r
+\r
+#HELPER FUNCTIONS\r
+#Everything sending an event should be here\r
+ def _measure_N_points(self, N, whatset=1):\r
'''\r
- This dictionary keeps all the flags and the relative functon names that\r
- have to be called when a point is clicked.\r
- That is:\r
- - if point is clicked AND foo_flag=True\r
- - foo()\r
-\r
- Conversely, foo_flag is True if a corresponding event is launched by the CLI.\r
-\r
- self.ClickedPoints() takes care of handling this\r
- '''\r
-\r
- self.click_flags_functions={'measure_points':[False, 'MeasurePoints']}\r
-\r
- #Binding of custom events from CLI --> GUI functions! \r
- #FIXME: Should use the self.Bind() syntax\r
- EVT_PLOT(self, self.PlotCurve)\r
- EVT_PLOT_CONTACT(self, self.PlotContact)\r
- EVT_GET_DISPLAYED_PLOT(self, self.OnGetDisplayedPlot)\r
- EVT_MEASURE_POINTS(self, self.OnMeasurePoints)\r
- EVT_EXPORT_IMAGE(self,self.ExportImage)\r
- EVT_CLOSE_PLOT(self, self.OnClosePlot)\r
- EVT_SHOW_PLOTS(self, self.OnShowPlots)\r
-\r
- #This event and control decide what happens when I click on the plot 0.\r
- wxmpl.EVT_POINT(self, self.controls[0].GetId(), self.ClickPoint0)\r
- wxmpl.EVT_POINT(self, self.controls[1].GetId(), self.ClickPoint1)\r
-\r
- #RUN PLUGIN-SPECIFIC INITIALIZATION\r
- #make sure we execute _plug_init() for every command line plugin we import\r
- for plugin_name in config['plugins']:\r
+ general helper function for N-points measures\r
+ '''\r
+ wx.PostEvent(self.frame,self.list_of_events['measure_points'](num_of_points=N, set=whatset))\r
+ while 1:\r
try:\r
- hooke_module=__import__('hooke.plugin.'+plugin_name)\r
- plugin = getattr(hooke_module.plugin, plugin_name)\r
- try:\r
- eval('plugin.'+plugin_name+'Gui._plug_init(self)')\r
- pass\r
- except AttributeError:\r
- pass\r
- except ImportError:\r
+ points=self.frame.events_from_gui.get()\r
+ break\r
+ except Empty:\r
pass\r
+ return points\r
\r
-\r
-\r
- #WX-SPECIFIC FUNCTIONS\r
- def sizer_dance(self):\r
+ def _clickize(self, xvector, yvector, index):\r
'''\r
- adjust size and placement of wxpython widgets.\r
- '''\r
- self.splittersizer = wx.BoxSizer(wx.VERTICAL)\r
- self.splittersizer.Add(self.mainpanel.splitter, 1, wx.EXPAND)\r
-\r
- self.plot1sizer = wx.BoxSizer()\r
- self.plot1sizer.Add(self.controls[0], 1, wx.EXPAND)\r
-\r
- self.plot2sizer = wx.BoxSizer()\r
- self.plot2sizer.Add(self.controls[1], 1, wx.EXPAND)\r
-\r
- self.panelsizer=wx.BoxSizer()\r
- self.panelsizer.Add(self.mainpanel, -1, wx.EXPAND)\r
-\r
- self.cpanels[0].SetSizer(self.plot1sizer)\r
- self.cpanels[1].SetSizer(self.plot2sizer)\r
-\r
- self.mainpanel.SetSizer(self.splittersizer)\r
- self.SetSizer(self.panelsizer)\r
-\r
- def binding_dance(self):\r
- self.Bind(wx.EVT_MENU, self.OnOpenPlayMenu, self.menubar.menu_items['openplaymenu'])\r
- self.Bind(wx.EVT_MENU, self.OnExitMenu, self.menubar.menu_items['exitmenu'])\r
- self.Bind(wx.EVT_MENU, self.OnExportText, self.menubar.menu_items['exporttextmenu'])\r
- self.Bind(wx.EVT_MENU, self.OnExportImage, self.menubar.menu_items['exportimagemenu'])\r
- self.Bind(wx.EVT_MENU, self.OnAboutMenu, self.menubar.menu_items['aboutmenu'])\r
-\r
- # DOUBLE PLOT MANAGEMENT\r
- #----------------------\r
- def show_both(self):\r
+ returns a ClickedPoint() object from an index and vectors of x, y coordinates\r
'''\r
- Shows both plots.\r
- '''\r
- self.mainpanel.splitter.SplitHorizontally(self.cpanels[0],self.cpanels[1])\r
- self.mainpanel.splitter.SetSashGravity(0.5)\r
- self.mainpanel.splitter.SetSashPosition(300) #FIXME: we should get it and restore it\r
- self.mainpanel.splitter.UpdateSize()\r
-\r
- def close_plot(self,plot):\r
+ point = lh.ClickedPoint()\r
+ point.index = index\r
+ point.absolute_coords = xvector[index], yvector[index]\r
+ point.find_graph_coords(xvector, yvector)\r
+ return point\r
+\r
+#PLAYLIST INTERACTION COMMANDS\r
+#-------------------------------\r
+ def do_genlist(self, folder=lh.hookeDir, filemask='*.*'):\r
'''\r
- Closes one plot - only if it's open\r
- '''\r
- if not self.cpanels[plot].IsShown():\r
- return\r
- if plot != 0:\r
- self.current_plot_dest = 0\r
+ GENLIST\r
+ Generates a file playlist.\r
+ Note it doesn't *save* it: see savelist for this.\r
+\r
+ If [input files] is a directory, it will use all files in the directory for playlist.\r
+ So:\r
+ genlist dir\r
+ genlist dir/\r
+ genlist dir/*.*\r
+\r
+ are all equivalent syntax.\r
+ ------------\r
+ Syntax: genlist [input files]\r
+ '''\r
+ #args list is: input folder, file mask\r
+ if os.path.isdir(folder):\r
+ path = os.path.join(folder, filemask)\r
+ #expanding correctly the input list with the glob module :)\r
+ files = glob.glob(path)\r
+ files.sort()\r
+ #TODO: change cursor or progressbar (maybe in statusbar)\r
+ #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
+ playlist = playlist.Playlist(self.drivers)\r
+ for item in files:\r
+ curve = playlist.add_curve(item)\r
+ plot = copy.deepcopy(curve.plots[0])\r
+ #add the 'raw' data\r
+ curve.add_data('raw', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')\r
+ curve.add_data('raw', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')\r
+ #apply all active plotmanipulators and add the 'manipulated' data\r
+ for plotmanipulator in self.plotmanipulators:\r
+ plot = plotmanipulator[1](plot, curve)\r
+ curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')\r
+ curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')\r
+ if playlist.count > 0:\r
+ playlist.name = self._GetUniquePlaylistName(os.path.basename(folder))\r
+ playlist.reset()\r
+ self.AddToPlaylists(playlist)\r
+ self.AppendToOutput(playlist.get_status_string())\r
else:\r
- self.current_plot_dest = 1\r
- self.cpanels[plot].Hide()\r
- self.mainpanel.splitter.Unsplit(self.cpanels[plot])\r
- self.mainpanel.splitter.UpdateSize()\r
-\r
-\r
- def OnClosePlot(self,event):\r
- self.close_plot(event.to_close) \r
-\r
- def OnShowPlots(self,event):\r
- self.show_both()\r
+ self.AppendToOutput(''.join(['Cannot find folder ', folder]))\r
\r
-\r
- #FILE MENU FUNCTIONS\r
- #--------------------\r
- def OnOpenPlayMenu(self, event):\r
- pass \r
-\r
- def OnExitMenu(self,event):\r
- pass\r
-\r
- def OnExportText(self,event):\r
- pass\r
-\r
- def OnExportImage(self,event):\r
- pass\r
-\r
- def OnAboutMenu(self,event):\r
- pass\r
-\r
- #PLOT INTERACTION \r
- #---------------- \r
- def PlotCurve(self,event):\r
+ def do_loadlist(self, filename):\r
+ '''\r
+ LOADLIST\r
+ Loads a file playlist\r
+ -----------\r
+ Syntax: loadlist [playlist file]\r
'''\r
- plots the current ext,ret curve.\r
- '''\r
- dest=0\r
-\r
- #FIXME: BAD kludge following. There should be a well made plot queue mechanism, with replacements etc.\r
- #---\r
- #If we have only one plot in the event, we already have one in self.plots and this is a secondary plot,\r
- #do not erase self.plots but append the new plot to it.\r
- if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) == 1:\r
- self.plots.append(event.plots[0])\r
- #if we already have two plots and a new secondary plot comes, we substitute the previous\r
- if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) > 1:\r
- self.plots[1] = event.plots[0]\r
+ #TODO: check for duplicate playlists, ask the user for a unique name\r
+ #if self.playlist_name in self.playlists:\r
+\r
+ #add hkp extension if necessary\r
+ if not filename.endswith('.hkp'):\r
+ filename = ''.join([filename, '.hkp'])\r
+ #prefix with 'hookeDir' if just a filename or a relative path\r
+ filename = lh.get_file_path(filename)\r
+ if os.path.isfile(filename):\r
+ #TODO: change cursor\r
+ #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
+ playlist_new = playlist.Playlist(self.drivers)\r
+ playlist_new.load(filename)\r
+ if playlist_new.count > 0:\r
+ for curve in playlist_new.curves:\r
+ plot = copy.deepcopy(curve.plots[0])\r
+ for plotmanip in self.plotmanipulators:\r
+ #to_plot = plotmanip[1](to_plot, curve)\r
+ plot = plotmanip[1](plot, curve)\r
+ curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')\r
+ curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')\r
+ self.AddToPlaylists(playlist_new)\r
+ #else:\r
+ ##TODO: display dialog\r
+ self.AppendToOutput(playlist_new.get_status_string())\r
+ #TODO: change cursor\r
+ #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
else:\r
- self.plots = event.plots\r
-\r
- #FIXME. Should be in PlotObject, somehow\r
- c=0\r
- for plot in self.plots:\r
- if self.plots[c].styles==[]:\r
- self.plots[c].styles=[None for item in plot.vectors] \r
- if self.plots[c].colors==[]:\r
- self.plots[c].colors=[None for item in plot.vectors] \r
-\r
- for plot in self.plots:\r
- '''\r
- MAIN LOOP FOR ALL PLOTS (now only 2 are allowed but...)\r
- '''\r
- if 'destination' in dir(plot):\r
- dest=plot.destination\r
-\r
- #if the requested panel is not shown, show it\r
- if not ( self.cpanels[dest].IsShown() ):\r
- self.show_both()\r
-\r
- self.axes[dest].hold(False)\r
- self.current_vectors=plot.vectors\r
- self.current_title=plot.title\r
- self.current_plot_dest=dest #let's try this way to take into account the destination plot...\r
-\r
- c=0\r
-\r
- if len(plot.colors)==0:\r
- plot.colors=[None] * len(plot.vectors)\r
- if len(plot.styles)==0:\r
- plot.styles=[None] * len(plot.vectors) \r
-\r
- for vectors_to_plot in self.current_vectors: \r
- if plot.styles[c]=='scatter':\r
- if plot.colors[c]==None:\r
- self.axes[dest].scatter(vectors_to_plot[0], vectors_to_plot[1])\r
- else:\r
- self.axes[dest].scatter(vectors_to_plot[0], vectors_to_plot[1],color=plot.colors[c])\r
- else:\r
- if plot.colors[c]==None:\r
- self.axes[dest].plot(vectors_to_plot[0], vectors_to_plot[1])\r
- else:\r
- self.axes[dest].plot(vectors_to_plot[0], vectors_to_plot[1], color=plot.colors[c])\r
- self.axes[dest].hold(True)\r
- c+=1\r
-\r
- '''\r
- for vectors_to_plot in self.current_vectors:\r
- if len(vectors_to_plot)==2: #3d plots are to come...\r
- if len(plot.styles) > 0 and plot.styles[c] == 'scatter':\r
- self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1])\r
- elif len(plot.styles) > 0 and plot.styles[c] == 'scatter_red':\r
- self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1],color='red')\r
- else:\r
- self.axes[dest].plot(vectors_to_plot[0],vectors_to_plot[1])\r
-\r
- self.axes[dest].hold(True)\r
- c+=1\r
- else:\r
- pass\r
- ''' \r
- #FIXME: tackles only 2d plots\r
- self.axes[dest].set_xlabel(plot.units[0])\r
- self.axes[dest].set_ylabel(plot.units[1])\r
-\r
- #FIXME: set smaller fonts\r
- self.axes[dest].set_title(plot.title)\r
-\r
- if plot.xaxes: \r
- #swap X axis\r
- xlim=self.axes[dest].get_xlim()\r
- self.axes[dest].set_xlim((xlim[1],xlim[0])) \r
- if plot.yaxes:\r
- #swap Y axis\r
- ylim=self.axes[dest].get_ylim() \r
- self.axes[dest].set_ylim((ylim[1],ylim[0])) \r
+ #TODO: display dialog\r
+ self.AppendToOutput(''.join['File ', filename, ' not found.\n'])\r
+ pass\r
\r
- for i in range(len(self.axes)):\r
- self.axes[i].xaxis.set_major_formatter(EngrFormatter())\r
- self.axes[i].yaxis.set_major_formatter(EngrFormatter(2))\r
+ def do_savelist(self, filename):\r
+ '''\r
+ SAVELIST\r
+ Saves the current file playlist on disk.\r
+ ------------\r
+ Syntax: savelist [filename]\r
+ '''\r
\r
+ #self.playlist_generics['pointer'] = self._GetActiveCurveIndex\r
+ pointer = self._GetActiveCurveIndex()\r
+ #autocomplete filename if not specified\r
+ if not filename.endswith('.hkp'):\r
+ filename = filename.join(['.hkp'])\r
+\r
+ playlist = self.GetActivePlaylist()\r
+ playlist.set_XML()\r
+ playlist.save(filename)\r
+\r
+#PLOT INTERACTION COMMANDS\r
+#-------------------------------\r
+ def UpdatePlot(self):\r
+ def add_plot(plot):\r
+ if plot['visible'] and plot['x'] and plot['y']:\r
+ color = plot['color']\r
+ style = plot['style']\r
+ if style == 'plot':\r
+ axes.plot(plot['x'], plot['y'], color=color, zorder=1)\r
+ if style == 'scatter':\r
+ axes.scatter(plot['x'], plot['y'], color=color, s=0.5, zorder=2)\r
+\r
+ def add_plot2(plot):\r
+ if plot.visible and plot.x and plot.y:\r
+ if plot.style == 'plot':\r
+ axes.plot(plot.x, plot.y, color=plot.color, zorder=1)\r
+ if plot.style == 'scatter':\r
+ axes.scatter(plot.x, plot.y, color=plot.color, s=0.5, zorder=2)\r
+\r
+ playlist_name = self._GetActivePlaylistName()\r
+ index = self._GetActiveCurveIndex()\r
+ playlist = self.playlists[playlist_name][0]\r
+ curve = playlist.get_active_curve()\r
+ plot = playlist.get_active_plot()\r
+ figure = self.playlists[playlist_name][1]\r
+\r
+ figure.clf()\r
+ exclude = None\r
+ if curve.data.has_key('manipulated'):\r
+ exclude = 'raw'\r
+ elif curve.data.has_key('raw'):\r
+ exclude = 'manipulated'\r
+\r
+ if exclude is not None:\r
+ #TODO: what is this good for?\r
+ if not hasattr(self, 'subplot'):\r
+ axes = figure.add_subplot(111)\r
+\r
+ axes.set_title(plot.title)\r
+ axes.set_xlabel(plot.units[0])\r
+ axes.set_ylabel(plot.units[1])\r
+\r
+ for set_of_plots in curve.data:\r
+ if set_of_plots != exclude:\r
+ plots = curve.data[set_of_plots]\r
+ for each_plot in plots:\r
+ add_plot(each_plot)\r
+\r
+ #TODO: add multiple results support\r
+ #for fit in curve.fits:\r
+ if curve.fits.has_key('wlc'):\r
+ for plot in curve.fits['wlc'].results:\r
+ add_plot2(plot)\r
+ self.panelResults.DisplayResults(curve.fits['wlc'])\r
+ else:\r
+ self.panelResults.ClearResults()\r
\r
- self.controls[dest].draw()\r
+ axes.figure.canvas.draw()\r
+ else:\r
+ self.AppendToOutput('Not able to plot.')\r
\r
\r
- def PlotContact(self,event):\r
- '''\r
- plots the contact point\r
- DEPRECATED!\r
- '''\r
- self.axes[0].hold(True)\r
- self.current_contact_index=event.contact_index\r
+ID_PaneBorderSize = wx.ID_HIGHEST + 1\r
+ID_SashSize = ID_PaneBorderSize + 1\r
+ID_CaptionSize = ID_PaneBorderSize + 2\r
+ID_BackgroundColor = ID_PaneBorderSize + 3\r
+ID_SashColor = ID_PaneBorderSize + 4\r
+ID_InactiveCaptionColor = ID_PaneBorderSize + 5\r
+ID_InactiveCaptionGradientColor = ID_PaneBorderSize + 6\r
+ID_InactiveCaptionTextColor = ID_PaneBorderSize + 7\r
+ID_ActiveCaptionColor = ID_PaneBorderSize + 8\r
+ID_ActiveCaptionGradientColor = ID_PaneBorderSize + 9\r
+ID_ActiveCaptionTextColor = ID_PaneBorderSize + 10\r
+ID_BorderColor = ID_PaneBorderSize + 11\r
+ID_GripperColor = ID_PaneBorderSize + 12\r
\r
- #now we fake a clicked point \r
- self.clicked_points.append(ClickedPoint())\r
- self.clicked_points[-1].absolute_coords=self.current_x_ret[dest][self.current_contact_index], self.current_y_ret[dest][self.current_contact_index]\r
- self.clicked_points[-1].is_marker=True \r
\r
- self._replot()\r
- self.clicked_points=[]\r
+#----------------------------------------------------------------------\r
\r
- def OnMeasurePoints(self,event):\r
- '''\r
- trigger flags to measure N points\r
- '''\r
- self.click_flags_functions['measure_points'][0]=True\r
- if 'num_of_points' in dir(event):\r
- self.num_of_points=event.num_of_points\r
- if 'set' in dir(event): \r
- self.measure_set=event.set \r
-\r
- def ClickPoint0(self,event):\r
- self.current_plot_dest=0\r
- self.ClickPoint(event)\r
- def ClickPoint1(self,event):\r
- self.current_plot_dest=1\r
- self.ClickPoint(event)\r
-\r
- def ClickPoint(self,event):\r
- '''\r
- this function decides what to do when we receive a left click on the axes.\r
- We trigger other functions:\r
- - the action chosen by the CLI sends an event\r
- - the event raises a flag : self.click_flags_functions['foo'][0]\r
- - the raised flag wants the function in self.click_flags_functions[1] to be called after a click\r
- '''\r
- for key, value in self.click_flags_functions.items():\r
- if value[0]:\r
- eval('self.'+value[1]+'(event)')\r
-\r
-\r
-\r
- def MeasurePoints(self,event,current_set=1):\r
- dest=self.current_plot_dest\r
- try:\r
- current_set=self.measure_set\r
- except AttributeError:\r
- pass\r
-\r
- #find the current plot matching the clicked destination\r
- plot=self._plot_of_dest()\r
- if len(plot.vectors)-1 < current_set: #what happens if current_set is 1 and we have only 1 vector?\r
- current_set=current_set-len(plot.vectors)\r
-\r
- xvector=plot.vectors[current_set][0]\r
- yvector=plot.vectors[current_set][1]\r
-\r
- self.clicked_points.append(ClickedPoint()) \r
- self.clicked_points[-1].absolute_coords=event.xdata, event.ydata\r
- self.clicked_points[-1].find_graph_coords(xvector,yvector)\r
- self.clicked_points[-1].is_marker=True \r
- self.clicked_points[-1].is_line_edge=True\r
- self.clicked_points[-1].dest=dest \r
-\r
- self._replot()\r
-\r
- if len(self.clicked_points)==self.num_of_points:\r
- self.events_from_gui.put(self.clicked_points)\r
- #restore to default state:\r
- self.clicked_points=[]\r
- self.click_flags_functions['measure_points'][0]=False \r
-\r
-\r
- def OnGetDisplayedPlot(self,event):\r
- if 'dest' in dir(event):\r
- self.GetDisplayedPlot(event.dest)\r
- else:\r
- self.GetDisplayedPlot(self.current_plot_dest)\r
+if __name__ == '__main__':\r
\r
- def GetDisplayedPlot(self,dest):\r
- '''\r
- returns to the CLI the currently displayed plot for the given destination\r
- '''\r
- displayed_plot=self._plot_of_dest(dest)\r
- events_from_gui.put(displayed_plot)\r
+ ## now, silence a deprecation warning for py2.3\r
+ #import warnings\r
+ #warnings.filterwarnings("ignore", "integer", DeprecationWarning, "wxPython.gdi")\r
\r
- def ExportImage(self,event):\r
- '''\r
- exports an image as a file.\r
- Current supported file formats: png, eps\r
- (matplotlib docs say that jpeg should be supported too, but with .jpg it doesn't work for me!)\r
- '''\r
- #dest=self.current_plot_dest\r
- dest=event.dest\r
- filename=event.name\r
- self.figures[dest].savefig(filename)\r
-\r
- '''\r
- def _find_nearest_point(self, mypoint, dataset=1):\r
-\r
- #Given a clicked point on the plot, finds the nearest point in the dataset (in X) that\r
- #corresponds to the clicked point.\r
-\r
- dest=self.current_plot_dest\r
-\r
- xvector=plot.vectors[dataset][0]\r
- yvector=plot.vectors[dataset][1]\r
-\r
- #Ye Olde sorting algorithm...\r
- #FIXME: is there a better solution?\r
- index=0\r
- best_index=0\r
- best_diff=10^9 #hope we never go over this magic number :(\r
- for point in xvector:\r
- diff=abs(point-mypoint)\r
- if diff<best_diff:\r
- best_index=index\r
- best_diff=diff\r
- index+=1\r
-\r
- return best_index,xvector[best_index],yvector[best_index]\r
- ''' \r
-\r
- def _plot_of_dest(self,dest=None):\r
- '''\r
- returns the plot that has the current destination\r
- '''\r
- if dest==None:\r
- dest=self.current_plot_dest\r
- try:\r
- plot=None\r
- for aplot in self.plots:\r
- if aplot.destination == dest:\r
- plot=aplot\r
- return plot\r
- except:\r
- print "No curve available"\r
- return None\r
-\r
- def _replot(self):\r
- '''\r
- this routine is needed for a fresh clean-and-replot of interface\r
- otherwise, refreshing works very badly :(\r
-\r
- thanks to Ken McIvor, wxmpl author!\r
- '''\r
- dest=self.current_plot_dest\r
- #we get current zoom limits\r
- xlim=self.axes[dest].get_xlim()\r
- ylim=self.axes[dest].get_ylim() \r
- #clear axes\r
- self.axes[dest].cla()\r
-\r
- #Plot curve: \r
- #find the current plot matching the clicked destination\r
- plot=self._plot_of_dest()\r
- #plot all superimposed plots \r
- c=0 \r
- if len(plot.colors)==0:\r
- plot.colors=[None] * len(plot.vectors)\r
- if len(plot.styles)==0:\r
- plot.styles=[None] * len(plot.vectors) \r
- for plotset in plot.vectors: \r
- if plot.styles[c]=='scatter':\r
- if plot.colors[c]==None:\r
- self.axes[dest].scatter(plotset[0], plotset[1])\r
- else:\r
- self.axes[dest].scatter(plotset[0], plotset[1],color=plot.colors[c])\r
- else:\r
- if plot.colors[c]==None:\r
- self.axes[dest].plot(plotset[0], plotset[1])\r
- else:\r
- self.axes[dest].plot(plotset[0], plotset[1], color=plot.colors[c])\r
- ''' \r
- if len(plot.styles) > 0 and plot.styles[c]=='scatter':\r
- self.axes[dest].scatter(plotset[0], plotset[1],color=plot.colors[c])\r
- elif len(plot.styles) > 0 and plot.styles[c] == 'scatter_red':\r
- self.axes[dest].scatter(plotset[0],plotset[1],color='red')\r
- else:\r
- self.axes[dest].plot(plotset[0], plotset[1])\r
- '''\r
- c+=1\r
- #plot points we have clicked\r
- for item in self.clicked_points:\r
- if item.is_marker:\r
- if item.graph_coords==(None,None): #if we have no graph coords, we display absolute coords\r
- self.axes[dest].scatter([item.absolute_coords[0]],[item.absolute_coords[1]])\r
- else:\r
- self.axes[dest].scatter([item.graph_coords[0]],[item.graph_coords[1]]) \r
-\r
- if self.plot_fit:\r
- print 'DEBUGGING WARNING: use of self.plot_fit is deprecated!'\r
- self.axes[dest].plot(self.plot_fit[0],self.plot_fit[1])\r
-\r
- self.axes[dest].hold(True) \r
- #set old axes again\r
- self.axes[dest].set_xlim(xlim)\r
- self.axes[dest].set_ylim(ylim)\r
- #set title and names again...\r
- self.axes[dest].set_title(self.current_title) \r
- self.axes[dest].set_xlabel(plot.units[0])\r
- self.axes[dest].set_ylabel(plot.units[1])\r
- #and redraw!\r
- self.controls[dest].draw()\r
-\r
-\r
-class MySplashScreen(wx.SplashScreen):\r
- """\r
- Create a splash screen widget.\r
- That's just a fancy addition... every serious application has a splash screen!\r
- """\r
- def __init__(self, frame):\r
- # This is a recipe to a the screen.\r
- # Modify the following variables as necessary.\r
- #aBitmap = wx.Image(name = "wxPyWiki.jpg").ConvertToBitmap()\r
- aBitmap=wx.Image(name=os.path.join(\r
- config['install']['docpath'],\r
- 'hooke.jpg')).ConvertToBitmap()\r
- splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT\r
- splashDuration = 2000 # milliseconds\r
- splashCallback = None\r
- # Call the constructor with the above arguments in exactly the\r
- # following order.\r
- wx.SplashScreen.__init__(self, aBitmap, splashStyle,\r
- splashDuration, None, -1)\r
- wx.EVT_CLOSE(self, self.OnExit)\r
- self.frame=frame\r
- wx.Yield()\r
-\r
- def OnExit(self, evt):\r
- self.Hide()\r
-\r
- self.frame.Show()\r
- # The program will freeze without this line.\r
- evt.Skip() # Make sure the default handler runs too...\r
-\r
-\r
-#------------------------------------------------------------------------------\r
-\r
-def main():\r
- app=wx.PySimpleApp()\r
-\r
- def make_gui_class(*bases):\r
- return type(MainWindow)("MainWindowPlugged", bases + (MainWindow,), {})\r
-\r
- main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Hooke '+__version__))\r
-\r
- #FIXME. The frame.Show() is called by the splashscreen here! Ugly as hell.\r
-\r
- mysplash=MySplashScreen(main_frame)\r
- mysplash.Show()\r
-\r
- my_cmdline=CliThread(main_frame, list_of_events)\r
- my_cmdline.start()\r
+ redirect=True\r
+ if __debug__:\r
+ redirect=False\r
+ app = Hooke(redirect=redirect)\r
\r
app.MainLoop()\r
\r
-if __name__ == '__main__':\r
- main()\r
+\r
import os.path
import string
import csv
-from matplotlib.ticker import ScalarFormatter
-from . import libhookecurve as lhc
-
-HOOKE_VERSION=['0.8.3_devel', 'Seinei', '2008-04-16']
+HOOKE_VERSION=['0.9.0_devel', 'Kenzo', '2009-09-xx']
WX_GOOD=['2.6','2.8']
+hookeDir=''
-class PlaylistXML(object):
- '''
- This module allows for import/export of an XML playlist into/out of a list of HookeCurve objects
- '''
-
- def __init__(self):
-
- self.playlist=None #the DOM object representing the playlist data structure
- self.playpath=None #the path of the playlist XML file
- self.plaything=None
- self.hidden_attributes=['curve'] #This list contains hidden attributes that we don't want to go into the playlist.
-
- def export(self, list_of_hooke_curves, generics):
- '''
- Creates an initial playlist from a list of files.
- A playlist is an XML document with the following syntaxis:
- <playlist>
- <element path="/my/file/path/"/ attribute="attribute">
- <element path="...">
- </playlist>
- '''
-
- #create the output playlist, a simple XML document
- impl=xml.dom.minidom.getDOMImplementation()
- #create the document DOM object and the root element
- newdoc=impl.createDocument(None, "playlist",None)
- top_element=newdoc.documentElement
-
- #save generics variables
- playlist_generics=newdoc.createElement("generics")
- top_element.appendChild(playlist_generics)
- for key in generics.keys():
- newdoc.createAttribute(key)
- playlist_generics.setAttribute(key,str(generics[key]))
-
- #save curves and their attributes
- for item in list_of_hooke_curves:
- #playlist_element=newdoc.createElement("curve")
- playlist_element=newdoc.createElement("element")
- top_element.appendChild(playlist_element)
- for key in item.__dict__:
- if not (key in self.hidden_attributes):
- newdoc.createAttribute(key)
- playlist_element.setAttribute(key,str(item.__dict__[key]))
-
- self.playlist=newdoc
-
- def load(self,filename):
- '''
- loads a playlist file
- '''
- myplay=file(filename)
- self.playpath=filename
-
- #the following 3 lines are needed to strip newlines. otherwise, since newlines
- #are XML elements too (why?), the parser would read them (and re-save them, multiplying
- #newlines...)
- #yes, I'm an XML n00b
- the_file=myplay.read()
- the_file_lines=the_file.split('\n')
- the_file=''.join(the_file_lines)
-
- self.playlist=xml.dom.minidom.parseString(the_file)
- #inner parsing functions
- def handlePlaylist(playlist):
- list_of_files=playlist.getElementsByTagName("element")
- generics=playlist.getElementsByTagName("generics")
- return handleFiles(list_of_files), handleGenerics(generics)
+def get_file_path(filename, folders = []):
+ if os.path.dirname(filename) == '' or os.path.isabs(filename) == False:
+ path = ''
+ for folder in folders:
+ path = os.path.join(path, folder)
+ filename = os.path.join(hookeDir, path, filename)
- def handleGenerics(generics):
- generics_dict={}
- if len(generics)==0:
- return generics_dict
+ return filename
- for attribute in generics[0].attributes.keys():
- generics_dict[attribute]=generics[0].getAttribute(attribute)
- return generics_dict
-
- def handleFiles(list_of_files):
- new_playlist=[]
- for myfile in list_of_files:
- #rebuild a data structure from the xml attributes
- the_curve=lhc.HookeCurve(
- os.path.join(os.path.dirname(self.playpath),
- myfile.getAttribute('path')))
- for attribute in myfile.attributes.keys():
- #extract attributes for the single curve
- if attribute == 'path':
- continue # we already added this attribute
- the_curve.__dict__[attribute]=myfile.getAttribute(attribute)
- new_playlist.append(the_curve)
-
- return new_playlist #this is the true thing returned at the end of this function...(FIXME: clarity)
-
- return handlePlaylist(self.playlist)
-
-
- def save(self,output_filename):
- '''
- saves the playlist in a XML file.
- '''
- try:
- outfile=file(output_filename,'w')
- except IOError:
- print 'libhooke.py : Cannot save playlist. Wrong path or filename'
- return
-
- self.playlist.writexml(outfile,indent='\n')
- outfile.close()
-
-def config_file_path(filename, config_dir=None):
- if config_dir == None:
- config_dir = os.path.abspath(
- os.path.join(os.path.dirname(os.path.dirname(__file__)), 'conf'))
- return os.path.join(config_dir, filename)
-
-class HookeConfig(object):
- '''
- Handling of Hooke configuration file
-
- Mostly based on the simple-yet-useful examples of the Python Library Reference
- about xml.dom.minidom
-
- FIXME: starting to look a mess, should require refactoring
- '''
-
- def __init__(self, config_dir=None):
- self.config={}
- self.config['install']={}
- self.config['plugins']=[]
- self.config['drivers']=[]
- self.config['plotmanips']=[]
- self.config_dir = config_dir
-
- def load_config(self, filename):
- myconfig=file(config_file_path(filename, config_dir=self.config_dir))
-
- #the following 3 lines are needed to strip newlines. otherwise, since newlines
- #are XML elements too, the parser would read them (and re-save them, multiplying
- #newlines...)
- #yes, I'm an XML n00b
- the_file=myconfig.read()
- the_file_lines=the_file.split('\n')
- the_file=''.join(the_file_lines)
-
- self.config_tree=xml.dom.minidom.parseString(the_file)
-
- def getText(nodelist):
- #take the text from a nodelist
- #from Python Library Reference 13.7.2
- rc = ''
- for node in nodelist:
- if node.nodeType == node.TEXT_NODE:
- rc += node.data
- return rc
-
- def handleConfig(config):
- install_elements=config.getElementsByTagName("install")
- display_elements=config.getElementsByTagName("display")
- plugins_elements=config.getElementsByTagName("plugins")
- drivers_elements=config.getElementsByTagName("drivers")
- defaultlist_elements=config.getElementsByTagName("defaultlist")
- plotmanip_elements=config.getElementsByTagName("plotmanips")
- handleInstall(install_elements)
- handleDisplay(display_elements)
- handlePlugins(plugins_elements)
- handleDrivers(drivers_elements)
- handleDefaultlist(defaultlist_elements)
- handlePlotmanip(plotmanip_elements)
-
- def handleInstall(install_elements):
- for install in install_elements:
- for node in install.childNodes:
- if node.nodeType == node.TEXT_NODE:
- continue
- path = os.path.abspath(getText(node.childNodes).strip())
- self.config['install'][str(node.tagName)] = path
-
- def handleDisplay(display_elements):
- for element in display_elements:
- for attribute in element.attributes.keys():
- self.config[attribute]=element.getAttribute(attribute)
-
- def handlePlugins(plugins):
- for plugin in plugins[0].childNodes:
- try:
- self.config['plugins'].append(str(plugin.tagName))
- except: #if we allow fancy formatting of xml, there is a text node, so tagName fails for it...
- pass
- #FIXME: code duplication
- def handleDrivers(drivers):
- for driver in drivers[0].childNodes:
- try:
- self.config['drivers'].append(str(driver.tagName))
- except: #if we allow fancy formatting of xml, there is a text node, so tagName fails for it...
- pass
-
- def handlePlotmanip(plotmanips):
- for plotmanip in plotmanips[0].childNodes:
- try:
- self.config['plotmanips'].append(str(plotmanip.tagName))
- except: #if we allow fancy formatting of xml, there is a text node, so tagName fails for it...
- pass
-
- def handleDefaultlist(defaultlist):
- '''
- default playlist
- '''
- dflist=getText(defaultlist[0].childNodes)
- self.config['defaultlist']=dflist.strip()
-
- handleConfig(self.config_tree)
- #making items in the dictionary more machine-readable
- for item in self.config.keys():
- try:
- self.config[item]=float(self.config[item])
- except TypeError: #we are dealing with a list, probably. keep it this way.
- try:
- self.config[item]=eval(self.config[item])
- except: #not a list, not a tuple, probably a string?
- pass
- except ValueError: #if we can't get it to a number, it must be None or a string
- if string.lower(self.config[item])=='none':
- self.config[item]=None
- else:
- pass
-
- return self.config
-
-
- def save_config(self, config_filename):
- print 'Not Implemented.'
- pass
-
-
-class EngrFormatter(ScalarFormatter):
- """A variation of the standard ScalarFormatter, using only multiples of
-three
-in the mantissa. A fixed number of decimals can be displayed with the optional
-parameter `ndec` . If `ndec` is None (default), the number of decimals is
-defined
-from the current ticks.
- """
- def __init__(self, ndec=None, useOffset=True, useMathText=False):
- ScalarFormatter.__init__(self, useOffset, useMathText)
- if ndec is None or ndec < 0:
- self.format = None
- elif ndec == 0:
- self.format = "%d"
- else:
- self.format = "%%1.%if" % ndec
- #........................
-
- def _set_orderOfMagnitude(self, mrange):
- """Sets the order of magnitude."""
- locs = numpy.absolute(self.locs)
- if self.offset:
- oom = numpy.floor(numpy.log10(mrange))
- else:
- if locs[0] > locs[-1]:
- val = locs[0]
- else:
- val = locs[-1]
- if val == 0:
- oom = 0
- else:
- oom = numpy.floor(numpy.log10(val))
- if oom <= -3:
- self.orderOfMagnitude = 3*(oom//3)
- elif oom <= -1:
- self.orderOfMagnitude = -3
- elif oom >= 4:
- self.orderOfMagnitude = 3*(oom//3)
- else:
- self.orderOfMagnitude = 0
-
-
- #........................
- def _set_format(self):
- """Sets the format string to format all ticklabels."""
- # set the format string to format all the ticklabels
- locs = (numpy.array(self.locs)-self.offset) / 10**self.orderOfMagnitude+1e-15
- sigfigs = [len(str('%1.3f'% loc).split('.')[1].rstrip('0')) \
- for loc in locs]
- sigfigs.sort()
- if self.format is None:
- self.format = '%1.' + str(sigfigs[-1]) + 'f'
- if self._usetex or self._useMathText: self.format = '$%s$'%self.format
-
-
-
-class ClickedPoint:
+class ClickedPoint(object):
'''
this class defines what a clicked point on the curve plot is
'''
'''
#FIXME: a general algorithm using min() is needed!
- #print '---DEPRECATED FIND_GRAPH_COORDS_OLD---'
best_index=0
best_dist=10**9 #should be more than enough given the scale
for index in scipy.arange(1,len(xvector),1):
dist=((self.absolute_coords[0]-xvector[index])**2)+(100*((self.absolute_coords[1]-yvector[index])))**2
- #TODO, generalize? y coordinate is multiplied by 100 due to scale differences in the plot
+ #TODO, generalize? y coordinate is multiplied by 100 due to scale differences in the plot
if dist<best_dist:
best_index=index
best_dist=dist
def find_graph_coords(self,xvector,yvector):
'''
- Given a clicked point on the plot, finds the nearest point in the dataset that
+ Given a clicked point on the plot, finds the nearest point in the dataset (in X) that
corresponds to the clicked point.
'''
dists=[]
+import os.path
+
class HookeCurve(object):
- def __init__(self,path):
- self.path=path
- self.curve=Driver()
- self.notes=''
+ def __init__(self, path):
+ #the data dictionary contains: {name of data: list of data sets [{[x], [y]}]
+ self.data = {}
+ self.driver = Driver()
+ self.path = path
+ self.fits = {}
+ self.name = os.path.basename(path)
+ self.notes = ''
+ self.plots = None
+
+ def add_data(self, name, x, y, color=None, result=None, style=None, visible=True):
+ data = {'x': x, 'y': y, 'color': color, 'result': result, 'style': style, 'visible': visible}
+ if self.data.has_key(name):
+ #get the existing list of xydata
+ list_data = self.data[name]
+ else:
+ #we need a new list of xydata
+ list_data = []
+ #append the xydata to the list
+ list_data.append(data)
+ #append or change the corresponding dictionary entry
+ self.data[name] = list_data
+
+ #def add_result(self, name, index, result):
+ #if self.data.has_key(name):
+ ##get the existing list of xydata
+ #list_data = self.data[name][index]
+ #list_data['result'] = result
+
+ def delete_data(self, name):
+ if self.data.has_key(name):
+ del self.data[name]
def identify(self, drivers):
'''
identifies a curve and returns the corresponding object
'''
for driver in drivers:
- tempcurve=driver(self.path)
- if tempcurve.is_me():
- #bring on all the driver, with his load of methods etc.
+ current_driver = driver(self.filename)
+ if current_driver.is_me():
+ #bring on all the driver, with its load of methods etc.
#so we can access the whole of it.
- self.curve=tempcurve
+ self.driver = current_driver
return True
print 'Not a recognizable curve format: ', self.path
return False
+ def set_data(self, name, x, y, color=None, result=None, style=None, visible=True):
+ data = {'x': x, 'y': y, 'color': color, 'result': result, 'style': style, 'visible': visible}
+ #append the xydata to the list
+ list_data = [data]
+ #append or change the corresponding dictionary entry
+ self.data[name] = list_data
+
class Driver(object):
'''
To be overridden
'''
def __init__(self):
- self.experiment=''
- self.filetype=''
+ self.experiment = ''
+ self.filetype = ''
def is_me(self):
'''
return None
def default_plots(self):
- dummy_default=PlotObject()
+ dummy_default = PlotObject()
dummy_default.vectors.append([[[0]],[[0]]])
return [dummy_default]
units are strings
'''
- self.units=['','']
+ self.units=['', '']
'''
- xaxes and yaxes directions. 0,0 means the common +X=right, +Y=top directions
+ xaxes and yaxes directions. 0, 0 means the common +X=right, +Y=top directions
'''
- self.xaxes=0
- self.yaxes=0
+ self.xaxes = 0
+ self.yaxes = 0
- self.title='' #title
+ self.filename = ''
+ self.title = '' #title
'''
styles: defines what is the style of the current plots. If undefined or None, it is line plot.
If an element of the list is 'scatter', the corresponding dataset
is drawn with scattered points and not a continuous line.
'''
- self.styles=[]
+ self.styles = []
'''
colors: define what is the colour of the current plots
'''
- self.colors=[]
+ self.colors = []
- def add_set(self,x,y):
+ def add_set(self, x, y):
'''
- Adds an x,y data set to the vectors.
+ Adds an x, y data set to the vectors.
'''
self.vectors.append([])
self.vectors[-1].append(x)
self.vectors[-1].append(y)
- return
- def remove_set(self,whichset):
+ def remove_set(self, whichset):
'''
Removes a set
'''
- waste=self.vectors.pop(whichset)
- return
+ #TODO: do we need 'waste' here?
+ waste = self.vectors.pop(whichset)
def normalize_vectors(self):
'''
Trims the vector lengths as to be equal in a plot.
'''
-
for index in range(0,len(self.vectors)):
vectors_to_plot=self.vectors[index]
lengths=[len(vector) for vector in vectors_to_plot]
--- /dev/null
+import copy\r
+import os\r
+import os.path\r
+import xml.dom.minidom\r
+\r
+from . import hooke as hooke\r
+from . import libhookecurve as lhc\r
+from . import libhooke as lh\r
+\r
+class Playlist(object):\r
+ def __init__(self, drivers):\r
+ self._saved = False\r
+ self.count = 0\r
+ self.curves = []\r
+ self.drivers = drivers\r
+ self.path = ''\r
+ self.genericsDict = {}\r
+ self.hiddenAttributes = ['curve', 'driver', 'name', 'plots']\r
+ self.index = -1\r
+ self.name = 'Untitled'\r
+ self.plotPanel = None\r
+ self.plotTab = None\r
+ self.xml = None\r
+\r
+ def add_curve(self, path, attributes={}):\r
+ curve = lhc.HookeCurve(path)\r
+ for key,value in attribures.items():\r
+ setattr(curve, key, value)\r
+ curve.identify(self.drivers)\r
+ curve.plots = curve.driver.default_plots()\r
+ self.curves.append(curve)\r
+ self._saved = False\r
+ self.count = len(self.curves)\r
+ return curve\r
+\r
+ def close_curve(self, index):\r
+ if index >= 0 and index < self.count:\r
+ self.curves.remove(index)\r
+\r
+ def filter_curves(self, keeper_fn=labmda curve:True):\r
+ playlist = copy.deepcopy(self)\r
+ for curve in reversed(playlist.curves):\r
+ if not keeper_fn(curve):\r
+ playlist.curves.remove(curve)\r
+ try: # attempt to maintain the same active curve\r
+ playlist.index = playlist.curves.index(self.get_active_curve())\r
+ except ValueError:\r
+ playlist.index = 0\r
+ playlist._saved = False\r
+ playlist.count = len(playlist.curves)\r
+ return playlist\r
+\r
+ def get_active_curve(self):\r
+ return self.curves[self.index]\r
+\r
+ #TODO: do we need this?\r
+ def get_active_plot(self):\r
+ return self.curves[self.index].plots[0]\r
+\r
+ def get_status_string(self):\r
+ if self.has_curves()\r
+ return '%s (%s/%s)' % (self.name, self.index + 1, self.count)\r
+ return 'The file %s does not contain any valid force curve data.' \\r
+ % self.name\r
+\r
+ def has_curves(self):\r
+ if self.count > 0:\r
+ return True\r
+ return False\r
+\r
+ def is_saved(self):\r
+ return self._saved\r
+\r
+ def load(self, path):\r
+ '''\r
+ loads a playlist file\r
+ '''\r
+ self.path = path\r
+ self.name = os.path.basename(path)\r
+ playlist = lh.delete_empty_lines_from_xmlfile(path)\r
+ self.xml = xml.dom.minidom.parse(path)\r
+ # Strip blank spaces:\r
+ self._removeWhitespaceNodes()\r
+\r
+ generics_list = self.xml.getElementsByTagName('generics')\r
+ curve_list = self.xml.getElementsByTagName('curve')\r
+ self._loadGenerics(generics_list)\r
+ self._loadCurves(curve_list)\r
+ self._saved = True\r
+\r
+ def _removeWhitespaceNodes(self, root_node=None):\r
+ if root_node == None:\r
+ root_node = self.xml\r
+ for node in root_node.childNodes:\r
+ if node.nodeType == node.TEXT_NODE and node.data.strip() == '':\r
+ root_node.removeChild(node) # drop this whitespace node\r
+ else:\r
+ _removeWhitespaceNodes(root_node=node) # recurse down a level\r
+\r
+ def _loadGenerics(self, generics_list, clear=True):\r
+ if clear:\r
+ self.genericsDict = {}\r
+ #populate generics\r
+ generics_list = self.xml.getElementsByTagName('generics')\r
+ for generics in generics_list:\r
+ for attribute in generics.attributes.keys():\r
+ self.genericsDict[attribute] = generics_list[0].getAttribute(attribute)\r
+ if self.genericsDict.has_key('pointer'):\r
+ index = int(self.genericsDict['pointer'])\r
+ if index >= 0 and index < len(self.curves):\r
+ self.index = index\r
+ else:\r
+ index = 0\r
+\r
+ def _loadCurves(self, curve_list, clear=True):\r
+ if clear:\r
+ self.curves = []\r
+ #populate playlist with curves\r
+ for curve in curve_list:\r
+ #rebuild a data structure from the xml attributes\r
+ curve_path = lh.get_file_path(element.getAttribute('path'))\r
+ #extract attributes for the single curve\r
+ attributes = dict([(k,curve.getAttribute(k))\r
+ for k in curve.attributes.keys()])\r
+ attributes.pop('path')\r
+ curve = self.add_curve(os.path.join(path, curve_path), attributes)\r
+ if curve is not None:\r
+ for plot in curve.plots:\r
+ curve.add_data('raw', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')\r
+ curve.add_data('raw', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')\r
+\r
+ def next(self):\r
+ self.index += 1\r
+ if self.index > self.count - 1:\r
+ self.index = 0\r
+\r
+ def previous(self):\r
+ self.index -= 1\r
+ if self.index < 0:\r
+ self.index = self.count - 1\r
+\r
+ def reset(self):\r
+ if self.has_curves():\r
+ self.index = 0\r
+ else:\r
+ self.index = None\r
+\r
+ def save(self, path):\r
+ '''\r
+ saves the playlist in a XML file.\r
+ '''\r
+ try:\r
+ output_file = file(path, 'w')\r
+ except IOError, e:\r
+ #TODO: send message\r
+ print 'Cannot save playlist: %s' % e\r
+ return\r
+ self.xml.writexml(output_file, indent='\n')\r
+ output_file.close()\r
+ self._saved = True\r
+\r
+ def set_XML(self):\r
+ '''\r
+ Creates an initial playlist from a list of files.\r
+ A playlist is an XML document with the following syntax:\r
+ <?xml version="1.0" encoding="utf-8"?>\r
+ <playlist>\r
+ <generics pointer="0"/>\r
+ <curve path="/my/file/path/"/ attribute="value" ...>\r
+ <curve path="...">\r
+ </playlist>\r
+ Relative paths are interpreted relative to the location of the\r
+ playlist file.\r
+ '''\r
+ #create the output playlist, a simple XML document\r
+ implementation = xml.dom.minidom.getDOMImplementation()\r
+ #create the document DOM object and the root element\r
+ self.xml = implementation.createDocument(None, 'playlist', None)\r
+ root = self.xml.documentElement\r
+\r
+ #save generics variables\r
+ playlist_generics = self.xml.createElement('generics')\r
+ root.appendChild(playlist_generics)\r
+ self.genericsDict['pointer'] = self.index\r
+ for key in self.genericsDict.keys():\r
+ self.xml.createAttribute(key)\r
+ playlist_generics.setAttribute(key, str(self.genericsDict[key]))\r
+ \r
+ #save curves and their attributes\r
+ for item in self.curves:\r
+ playlist_curve = self.xml.createElement('curve')\r
+ root.appendChild(playlist_curve)\r
+ for key in item.__dict__:\r
+ if not (key in self.hiddenAttributes):\r
+ self.xml.createAttribute(key)\r
+ playlist_curve.setAttribute(key, str(item.__dict__[key]))\r
+ self._saved = False\r
+#!/usr/bin/env python\r
+'''\r
+Commands and settings panel for Hooke\r
+\r
+Displays commands and settings for Hooke in a tree control\r
+(c) Dr. Rolf Schmidt, 2009\r
+'''\r
+\r
+from configobj import ConfigObj\r
+import os.path\r
+from validate import Validator\r
+import wx\r
+\r
+import libhooke as lh\r
+\r
+class Commands(wx.Panel):\r
+\r
+ def __init__(self, parent):\r
+ # Use the WANTS_CHARS style so the panel doesn't eat the Return key.\r
+ wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS|wx.NO_BORDER, size=(160, 200))\r
+\r
+ self.CommandsTree = wx.TreeCtrl(self, -1, wx.Point(0, 0), wx.Size(160, 250), wx.TR_DEFAULT_STYLE|wx.NO_BORDER|wx.TR_HIDE_ROOT)\r
+ imglist = wx.ImageList(16, 16, True, 2)\r
+ imglist.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16, 16)))\r
+ imglist.Add(wx.ArtProvider.GetBitmap(wx.ART_EXECUTABLE_FILE, wx.ART_OTHER, wx.Size(16, 16)))\r
+ self.CommandsTree.AssignImageList(imglist)\r
+ self.CommandsTree.AddRoot('Commands and Settings', 0)\r
+\r
+ self.ExecuteButton = wx.Button(self, -1, 'Execute')\r
+\r
+ sizer = wx.BoxSizer(wx.VERTICAL)\r
+ sizer.Add(self.CommandsTree, 1, wx.EXPAND)\r
+ sizer.Add(self.ExecuteButton, 0, wx.EXPAND)\r
+\r
+ self.SetSizer(sizer)\r
+ sizer.Fit(self)\r
+\r
+ def Initialize(self, plugins):\r
+ tree_root = self.CommandsTree.GetRootItem()\r
+ for plugin in plugins:\r
+ filename = ''.join([plugin, '.ini'])\r
+ path = lh.get_file_path(filename, ['plugins'])\r
+ config = ConfigObj()\r
+ if os.path.isfile(path):\r
+ config.filename = path\r
+ config.reload()\r
+ #append the ini file to the plugin\r
+ plugin_root = self.CommandsTree.AppendItem(tree_root, plugin, 0, data=wx.TreeItemData(config))\r
+ else:\r
+ plugin_root = self.CommandsTree.AppendItem(tree_root, plugin, 0)\r
+\r
+ #add all commands to the tree\r
+ for command in plugins[plugin]:\r
+ command_label = command.replace('do_', '')\r
+ #do not add the ini file to the command (we'll access the ini file of the plugin (ie parent) instead, see above)\r
+ self.CommandsTree.AppendItem(plugin_root, command_label, 1)\r
+ self.CommandsTree.Expand(plugin_root)\r
# -*- coding: utf-8 -*-
-from hooke.libhooke import WX_GOOD, ClickedPoint
+from hooke.libhooke import WX_GOOD
import wxversion
wxversion.select(WX_GOOD)
import warnings
warnings.simplefilter('ignore',np.RankWarning)
+#from .. import ui.gui.results as results
-class autopeakCommands(object):
- def do_autopeak(self,args):
+class autopeakCommands(object):
+ '''
+ TODO: autopeak docstring.
+ '''
+ def do_autopeak(self, args):
'''
AUTOPEAK
(autopeak.py)
--- /dev/null
+#!/usr/bin/env python
+
+'''
+FLATFILTS
+
+Force spectroscopy curves filtering of flat curves
+Licensed under the GNU LGPL version 2
+
+Other plugin dependencies:
+procplots.py (plot processing plugin)
+'''
+
+import xml.dom.minidom
+
+import wx
+#import scipy
+import numpy
+from numpy import diff
+import os.path
+
+#import pickle
+
+import libpeakspot as lps
+#import libhookecurve as lhc
+import hookecurve as lhc
+import libhooke as lh
+import wxversion
+wxversion.select(lh.WX_GOOD)
+
+
+class flatfiltsCommands:
+
+ def do_flatfilt(self):
+ '''
+ FLATFILT
+ (flatfilts.py)
+ Filters out flat (featureless) curves of the current playlist,
+ creating a playlist containing only the curves with potential
+ features.
+ ------------
+ Syntax:
+ flatfilt [min_npks min_deviation]
+
+ min_npks = minmum number of points over the deviation
+ (default=4)
+
+ min_deviation = minimum signal/noise ratio
+ (default=9)
+
+ If called without arguments, it uses default values, that
+ should work most of the times.
+ '''
+ #TODO: should this be optional?
+ medianfilter = 7
+
+ self.AppendToOutput('Processing playlist...')
+ self.AppendToOutput('(Please wait)')
+ features = []
+ playlist = self.GetActivePlaylist()
+ curves = playlist.curves
+ curve_index = 0
+ for curve in curves:
+ curve_index += 1
+ try:
+ notflat = self.has_features(curve)
+ feature_string = ''
+ if notflat != 1:
+ if notflat > 0:
+ feature_string = str(notflat) + ' features'
+ else:
+ feature_string = 'no features'
+ else:
+ feature_string = '1 feature'
+ output_string = ''.join(['Curve ', curve.name, '(', str(curve_index), '/', str(len(curves)), '): ', feature_string])
+ except:
+ notflat = False
+ output_string = ''.join(['Curve ', curve.name, '(', str(curve_index), '/', str(len(curves)), '): cannot be filtered. Probably unable to retrieve force data from corrupt file.'])
+ self.AppendToOutput(output_string)
+ if notflat:
+ curve.features = notflat
+ features.append(curve_index - 1)
+ if not features:
+ self.AppendToOutput('Found nothing interesting. Check the playlist, could be a bug or criteria could be too stringent.')
+ else:
+ if len(features) < playlist.count:
+ self.AppendToOutput(''.join(['Found ', str(len(features)), ' potentially interesting curves.']))
+ self.AppendToOutput('Regenerating playlist...')
+ playlist_filtered = playlist.filter_curves(features)
+ self.AddPlaylist(playlist_filtered, name='flatfilt')
+ else:
+ self.AppendToOutput('No curves filtered. Try different filtering criteria.')
+
+ def has_features(self, curve):
+ '''
+ decides if a curve is flat enough to be rejected from analysis: it sees if there
+ are at least min_npks points that are higher than min_deviation times the absolute value
+ of noise.
+
+ Algorithm original idea by Francesco Musiani, with my tweaks and corrections.
+ '''
+ medianfilter = 7
+ mindeviation = self.GetIntFromConfig('flatfilts', 'flatfilt', 'min_deviation')
+ minpeaks = self.GetIntFromConfig('flatfilts', 'flatfilt', 'min_npks')
+ #medianfilter = self.GetIntFromConfig('flatfilt', 'median_filter')
+ #mindeviation = self.GetIntFromConfig('convfilt', 'mindeviation')
+ #minpeaks = self.GetIntFromConfig('convfilt', 'minpeaks')
+
+ retvalue = 0
+
+ #item.identify(self.drivers)
+ #we assume the first is the plot with the force curve
+ #do the median to better resolve features from noise
+ flat_plot = self.plotmanip_median(curve.driver.default_plots()[0], curve, customvalue=medianfilter)
+ flat_vects = flat_plot.vectors
+ curve.driver.close_all()
+ #needed to avoid *big* memory leaks!
+ #del item.driver
+ #del item
+
+ #absolute value of derivate
+ yretdiff=diff(flat_vects[1][1])
+ yretdiff=[abs(value) for value in yretdiff]
+ #average of derivate values
+ diffmean=numpy.mean(yretdiff)
+ yretdiff.sort()
+ yretdiff.reverse()
+ c_pks=0
+ for value in yretdiff:
+ if value/diffmean > mindeviation:
+ c_pks += 1
+ else:
+ break
+
+ if c_pks >= minpeaks:
+ retvalue = c_pks
+
+ del flat_plot, flat_vects, yretdiff
+
+ return retvalue
+
+ ################################################################
+ #-----CONVFILT-------------------------------------------------
+ #-----Convolution-based peak recognition and filtering.
+ #Requires the libpeakspot.py library
+
+ def has_peaks(self, plot, curve=None):
+ '''
+ Finds peak position in a force curve.
+ FIXME: should be moved to libpeakspot.py
+ '''
+
+ blindwindow = self.GetFloatFromConfig('flatfilts', 'convfilt', 'blindwindow')
+ #need to convert the string that contains the list into a list
+ convolution = eval(self.GetStringFromConfig('flatfilts', 'convfilt', 'convolution'))
+ maxcut = self.GetFloatFromConfig('flatfilts', 'convfilt', 'maxcut')
+ mindeviation = self.GetFloatFromConfig('flatfilts', 'convfilt', 'mindeviation')
+ positive = self.GetBoolFromConfig('flatfilts', 'convfilt', 'positive')
+ seedouble = self.GetIntFromConfig('flatfilts', 'convfilt', 'seedouble')
+ stable = self.GetFloatFromConfig('flatfilts', 'convfilt', 'stable')
+
+ xret = plot.vectors[1][0]
+ yret = plot.vectors[1][1]
+ #Calculate convolution
+ convoluted = lps.conv_dx(yret, convolution)
+
+ #surely cut everything before the contact point
+ cut_index = self.find_contact_point(plot, curve)
+ #cut even more, before the blind window
+ start_x = xret[cut_index]
+ blind_index = 0
+ for value in xret[cut_index:]:
+ if abs((value) - (start_x)) > blindwindow * (10 ** -9):
+ break
+ blind_index += 1
+ cut_index += blind_index
+ #do the dirty convolution-peak finding stuff
+ noise_level = lps.noise_absdev(convoluted[cut_index:], positive, maxcut, stable)
+ above = lps.abovenoise(convoluted, noise_level, cut_index, mindeviation)
+ peak_location, peak_size = lps.find_peaks(above, seedouble=seedouble)
+ #take the maximum
+ for i in range(len(peak_location)):
+ peak = peak_location[i]
+ maxpk = min(yret[peak - 10:peak + 10])
+ index_maxpk = yret[peak - 10:peak + 10].index(maxpk) + (peak - 10)
+ peak_location[i] = index_maxpk
+
+ return peak_location, peak_size
+
+ def exec_has_peaks(self, curve):
+ '''
+ encapsulates has_peaks for the purpose of correctly treating the curve objects in the convfilt loop,
+ to avoid memory leaks
+ '''
+ #item.identify(self.drivers)
+ #we assume the first is the plot with the force curve
+ plot = curve.driver.default_plots()[0]
+
+ if self.HasPlotmanipulator('plotmanip_flatten'):
+ #If flatten is present, use it for better recognition of peaks...
+ #flatten = self._find_plotmanip('flatten') #extract flatten plot manipulator
+ #plot = flatten(plot, item, customvalue=1)
+ plot = self.plotmanip_flatten(plot, curve, customvalue=1)
+
+ peak_location, peak_size = self.has_peaks(plot, curve)
+ #close all open files
+ curve.driver.close_all()
+ #needed to avoid *big* memory leaks!
+ #del item.driver
+ #del item
+ return peak_location, peak_size
+
+ #------------------------
+ #------commands----------
+ #------------------------
+ def do_peaks(self):
+ '''
+ PEAKS
+ (flatfilts.py)
+ Test command for convolution filter / test.
+ ----
+ Syntax: peaks [deviations]
+ absolute deviation = number of times the convolution signal is above the noise absolute deviation.
+ Default is 5.
+ '''
+
+ #TODO: check if the following line gives us what we need
+ curve = self.GetActiveCurve()
+ defplots = curve.driver.default_plots()[0] #we need the raw, uncorrected plots
+
+ #if 'flatten' in self.config['plotmanips']:
+ if self.HasPlotmanipulator('plotmanip_flatten'):
+ #flatten=self._find_plotmanip('flatten') #extract flatten plot manipulator
+ #defplots=flatten(defplots, self.current)
+ defplots = self.plotmanip_flatten(defplots, curve, customvalue=0)
+ else:
+ self.AppendToOutput('The flatten plot manipulator is not loaded. Enabling it could give better results.')
+
+ peak_location, peak_size = self.has_peaks(defplots, curve)
+ self.AppendToOutput('Found ' + str(len(peak_location)) + ' peaks.')
+ self.AppendToOutput('peaks ' + curve.filename + ' ' + str(len(peak_location)))
+ #to_dump = 'peaks ' + current_curve.filename + ' ' + str(len(peak_location))
+ #self.outlet.push(to_dump)
+
+ #if no peaks, we have nothing to plot. exit.
+ if peak_location:
+ #otherwise, we plot the peak locations.
+ xplotted_ret = curve.plots[0].vectors[1][0]
+ yplotted_ret = curve.plots[0].vectors[1][1]
+ xgood = [xplotted_ret[index] for index in peak_location]
+ ygood = [yplotted_ret[index] for index in peak_location]
+
+ curve.plots[0].add_set(xgood, ygood)
+ curve.plots[0].styles.append('scatter')
+ curve.plots[0].colors.append('indigo')
+
+ #recplot = self._get_displayed_plot()
+ #recplot.vectors.append([xgood,ygood])
+ #if recplot.styles == []:
+ #recplot.styles = [None, None, 'scatter']
+ #recplot.colors = [None, None, None]
+ #else:
+ #recplot.styles += ['scatter']
+ #recplot.colors += [None]
+
+ #self._send_plot([recplot])
+ self.UpdatePlot()
+
+ def do_convfilt(self):
+ '''
+ CONVFILT
+ (flatfilts.py)
+ Filters out flat (featureless) curves of the current playlist,
+ creating a playlist containing only the curves with potential
+ features.
+ ------------
+ Syntax:
+ convfilt [min_npks min_deviation]
+
+ min_npks = minmum number of peaks
+ (to set the default, see convfilt.conf file; CONVCONF and SETCONF commands)
+
+ min_deviation = minimum signal/noise ratio *in the convolution*
+ (to set the default, see convfilt.conf file; CONVCONF and SETCONF commands)
+
+ If called without arguments, it uses default values.
+ '''
+
+ self.AppendToOutput('Processing playlist...')
+ self.AppendToOutput('(Please wait)')
+ minpeaks = self.GetIntFromConfig('flatfilts', 'convfilt', 'minpeaks')
+ features = []
+ playlist = self.GetActivePlaylist()
+
+ curves = self.GetActivePlaylist().curves
+ curve_index = 0
+ for curve in curves:
+ curve_index += 1
+ try:
+ peak_location, peak_size = self.exec_has_peaks(curve)
+ number_of_peaks = len(peak_location)
+ if number_of_peaks != 1:
+ if number_of_peaks > 0:
+ feature_string = str(number_of_peaks) + ' features'
+ else:
+ feature_string = 'no features'
+ else:
+ feature_string = '1 feature'
+ if number_of_peaks >= minpeaks:
+ feature_string += '+'
+ output_string = ''.join(['Curve ', curve.name, '(', str(curve_index), '/', str(len(curves)), '): ', feature_string])
+ except:
+ peak_location = []
+ peak_size = []
+ output_string = ''.join(['Curve ', curve.name, '(', str(curve_index), '/', str(len(curves)), '): cannot be filtered. Probably unable to retrieve force data from corrupt file.'])
+ self.AppendToOutput(output_string)
+ if number_of_peaks >= minpeaks:
+ curve.peak_location = peak_location
+ curve.peak_size = peak_size
+ features.append(curve_index - 1)
+
+ #TODO: do we need this? Flattening might not be necessary/desired
+ #Warn that no flattening had been done.
+ if not self.HasPlotmanipulator('plotmanip_flatten'):
+ self.AppendToOutput('Flatten manipulator was not found. Processing was done without flattening.')
+ self.AppendToOutput('Try to enable it in the configuration file for better results.')
+ if not features:
+ self.AppendToOutput('Found nothing interesting. Check the playlist, could be a bug or criteria could be too stringent.')
+ else:
+ if len(features) < playlist.count:
+ self.AppendToOutput(''.join(['Found ', str(len(features)), ' potentially interesting curves.']))
+ self.AppendToOutput('Regenerating playlist...')
+ playlist_filtered = playlist.filter_curves(features)
+ self.AddPlaylist(playlist_filtered, name='convfilt')
+ else:
+ self.AppendToOutput('No curves filtered. Try different filtering criteria.')
+
return
else:
print 'Found',len(notflat_list),'potentially interesting curves.'
- print 'Regenerating Playlist...'
+ print 'Regenerating playlist...'
self.pointer=0
self.current_list=notflat_list
self.current=self.current_list[self.pointer]
print 'Cannot fit. Did you click twice the same point?'
return
+ # Outputs the relevant slope parameter
+ print 'Slope:'
+ print str(parameters[0])
+ to_dump='slope '+self.curve.path+' '+str(parameters[0])
+ self.outlet.push(to_dump)
+
# Makes a vector with the fitted parameters and sends it to the GUI
xtoplot=parameters[2]
ytoplot=[]
return dplot
- def do_subtplot(self,args):
+ def do_subtplot(self, args):
'''
SUBTPLOT
(procplots.py plugin)
--- /dev/null
+#!/usr/bin/env python\r
+\r
+'''\r
+SHOW CONVOLUTED CURVE PLUGIN FOR HOOKE\r
+\r
+This plugin contains a plotmanipulator to show the convoluted curve.\r
+(c) Dr. Rolf Schmidt, 2009\r
+'''\r
+\r
+import libpeakspot\r
+\r
+class showconvolutedCommands:\r
+\r
+ #def _plug_init(self):\r
+ #pass\r
+\r
+ def plotmanip_showconvoluted(self, plot, curve):\r
+ '''\r
+ BEGIN: taken from procplots.py\r
+ might need some tweaking\r
+ '''\r
+ #use only for force spectroscopy experiments!\r
+ if curve.driver.experiment != 'smfs':\r
+ return plot\r
+\r
+ '''\r
+ END: taken from procplots.py\r
+ '''\r
+\r
+ #need to convert the string that contains the list into a list\r
+ #convolution = eval(self.config['convfilt']['convolution']['value'])\r
+ convolution = eval(self.GetStringFromConfig('flatfilts', 'convfilt', 'convolution'))\r
+\r
+ xRet = plot.vectors[1][0]\r
+ yRet = plot.vectors[1][1]\r
+ convoluted = libpeakspot.conv_dx(yRet, convolution)\r
+ #convoluted=libpeakspot.conv_dx(yRet, [-20, -10, -6, 0, 12, 12, 12])\r
+ plot.add_set(xRet, convoluted)\r
+ #plot.vectors[1][1]=[i for i in convoluted]\r
+ #set contact point plot style to 'plot'\r
+ #and the color to red\r
+ plot.styles.append('plot')\r
+ plot.colors.append('black')\r
+ #peak_location, peak_size = self.has_peaks(plot, blindwindow, convolution, minpeaks)\r
+ peak_locations, peak_sizes = self.has_peaks(plot, curve)\r
+\r
+ if peak_locations:\r
+ peak_locations_x = []\r
+ peak_locations_y = []\r
+ for location in peak_locations:\r
+ peak_locations_x.append(xRet[location])\r
+ peak_locations_y.append(yRet[location])\r
+ plot.add_set(peak_locations_x, peak_locations_y)\r
+ plot.styles.append('scatter')\r
+ plot.colors.append('green')\r
+ plot.add_set(peak_locations_x, peak_sizes)\r
+ plot.styles.append('scatter')\r
+ plot.colors.append('magenta')\r
+\r
+ #Return the plot object.\r
+ return plot\r
-<?xml version="1.0" ?>
+<?xml version="1.0" encoding="utf-8"?>
<playlist>
-<generics pointer="0"/>
-<element notes="" path="default.000"/>
+ <generics pointer="0"/>
+ <curve notes="" path="default.000"/>
</playlist>
--- /dev/null
+#import os\r
+#import os.path\r
+import wx\r
+#import xml.dom.minidom\r
+\r
+class Playlists(wx.Panel):\r
+\r
+ def __init__(self, parent):\r
+ # Use the WANTS_CHARS style so the panel doesn't eat the Return key.\r
+ wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS|wx.NO_BORDER, size=(160, 200))\r
+\r
+ self.PlaylistsTree = wx.TreeCtrl(self, -1, wx.Point(0, 0), wx.Size(160, 250), wx.TR_DEFAULT_STYLE | wx.NO_BORDER | wx.TR_HIDE_ROOT)\r
+ imglist = wx.ImageList(16, 16, True, 2)\r
+ imglist.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16, 16)))\r
+ imglist.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16)))\r
+ self.PlaylistsTree.AssignImageList(imglist)\r
+ self.PlaylistsTree.AddRoot('Playlists', 0)\r
+ self.PlaylistsTree.Bind(wx.EVT_RIGHT_DOWN , self.OnContextMenu)\r
+\r
+ self.Playlists = {}\r
+\r
+ sizer = wx.BoxSizer(wx.VERTICAL)\r
+ sizer.Add(self.PlaylistsTree, 1, wx.EXPAND)\r
+ self.SetSizer(sizer)\r
+ sizer.Fit(self)\r
+\r
+ #def add_playlist(self, files=[], name='Untitled'):\r
+ ##TODO: change cursor or progressbar (maybe in statusbar)\r
+ ##self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
+ #if files:\r
+ #playlist = hookeplaylist.Playlist(self.drivers)\r
+ #for item in files:\r
+ #playlist.add_curve(item)\r
+ #if playlist.count > 0:\r
+ #playlist_name = name\r
+ #count = 1\r
+ #while playlist_name in self.Playlists:\r
+ #playlist_name = ''.join([name, str(count)])\r
+ #count += 1\r
+ #playlist.name = playlist_name\r
+ #playlist.reset()\r
+ #self.AddToPlaylists(playlist)\r
+\r
+ #def FilterPlaylist(self, curves_to_keep=[]):\r
+ #playlist_active = self.GetActivePlaylist()\r
+ #playlist_new = Playlist(self.drivers)\r
+ #for curve_index in curves_to_keep:\r
+ #playlist_new.curves.append(playlist_active.curves[curve_index])\r
+ #return playlist_new\r
+\r
+ def GetActivePlaylist(self):\r
+ playlist_name = self.GetActivePlaylistName()\r
+ if playlist_name in self.playlists:\r
+ return self.playlists[playlist_name][0]\r
+ else:\r
+ return None\r
+\r
+ def GetActivePlaylistName(self):\r
+ #get the selected item from the tree\r
+ selected_item = self.PlaylistsTree.GetSelection()\r
+ #test if a playlist or a curve was double-clicked\r
+ if self.PlaylistsTree.ItemHasChildren(selected_item):\r
+ playlist_item = selected_item\r
+ else:\r
+ #get the name of the playlist\r
+ playlist_item = self.PlaylistsTree.GetItemParent(selected_item)\r
+ #now we have a playlist\r
+ return self.PlaylistsTree.GetItemText(playlist_item)\r
+\r
+ def OnContextMenu(self, event):\r
+ hit_item, hit_flags = self.PlaylistsTree.HitTest(event.GetPosition())\r
+ if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:\r
+ self.PlaylistsTree.SelectItem(hit_item)\r
+ # only do this part the first time so the events are only bound once\r
+ #\r
+ # Yet another alternate way to do IDs. Some prefer them up top to\r
+ # avoid clutter, some prefer them close to the object of interest\r
+ # for clarity.\r
+ if not hasattr(self, 'ID_popupAdd'):\r
+ self.ID_popupAdd = wx.NewId()\r
+ self.ID_popupClose = wx.NewId()\r
+ self.Bind(wx.EVT_MENU, self.OnPopupAdd, id=self.ID_popupAdd)\r
+ self.Bind(wx.EVT_MENU, self.OnPopupClose, id=self.ID_popupClose)\r
+ # make a menu\r
+ menu = wx.Menu()\r
+ items = [['Add', self.ID_popupAdd] , ['Close', self.ID_popupClose]]\r
+ for item in items:\r
+ menu.Append(item[1], item[0])\r
+ # Popup the menu. If an item is selected then its handler\r
+ # will be called before PopupMenu returns.\r
+ self.PopupMenu(menu)\r
+ menu.Destroy()\r
+\r
+ def OnPopupAdd(self, event):\r
+ pass\r
+\r
+ def OnPopupClose(self, event):\r
+ item = self.PlaylistsTree.GetSelection()\r
+ if self.PlaylistsTree.ItemHasChildren(item):\r
+ playlist_name = self.PlaylistsTree.GetItemText(item)\r
+ self.Parent.DeletePlotPage(playlist_name)\r
+ #del self.Playlists[playlist_name]\r
+ #TODO: delete playlist, close notebook tab\r
+ #self.Parent.AddToPlaylists()\r
+ else:\r
+ pass\r
--- /dev/null
+import sys\r
+import time\r
+import math\r
+import os.path\r
+import pdb\r
+\r
+import wx\r
+import wx.propgrid as wxpg\r
+import wx.stc\r
+\r
+\r
+class Display:\r
+ property_descriptor = []\r
+ def __init__(self):\r
+ pass\r
+\r
+\r
+class ValueObject:\r
+ def __init__(self):\r
+ pass\r
+\r
+\r
+class IntProperty2(wxpg.PyProperty):\r
+ """\\r
+ This is a simple re-implementation of wxIntProperty.\r
+ """\r
+ def __init__(self, label, name = wxpg.LABEL_AS_NAME, value=0):\r
+ wxpg.PyProperty.__init__(self, label, name)\r
+ self.SetValue(value)\r
+\r
+ def GetClassName(self):\r
+ """\\r
+ This is not 100% necessary and in future is probably going to be\r
+ automated to return class name.\r
+ """\r
+ return "IntProperty2"\r
+\r
+ def GetEditor(self):\r
+ return "TextCtrl"\r
+\r
+ def GetValueAsString(self, flags):\r
+ return str(self.GetValue())\r
+\r
+ def PyStringToValue(self, s, flags):\r
+ try:\r
+ v = int(s)\r
+ if self.GetValue() != v:\r
+ return v\r
+ except TypeError:\r
+ if flags & wxpg.PG_REPORT_ERROR:\r
+ wx.MessageBox("Cannot convert '%s' into a number."%s, "Error")\r
+ return False\r
+\r
+ def PyIntToValue(self, v, flags):\r
+ if (self.GetValue() != v):\r
+ return v\r
+\r
+\r
+class PyFilesProperty(wxpg.PyArrayStringProperty):\r
+ def __init__(self, label, name = wxpg.LABEL_AS_NAME, value=[]):\r
+ wxpg.PyArrayStringProperty.__init__(self, label, name, value)\r
+ self.SetValue(value)\r
+\r
+ def OnSetValue(self, v):\r
+ self.value = v\r
+ self.display = ', '.join(self.value)\r
+\r
+ def GetValueAsString(self, argFlags):\r
+ return self.display\r
+\r
+ def PyStringToValue(self, s, flags):\r
+ return [a.strip() for a in text.split(',')]\r
+\r
+ def OnEvent(self, propgrid, ctrl, event):\r
+ if event.GetEventType() == wx.wxEVT_COMMAND_BUTTON_CLICKED:\r
+ # Show dialog to select a string, call DoSetValue and\r
+ # return True, if value changed.\r
+ return True\r
+\r
+ return False\r
+\r
+\r
+class PyObjectPropertyValue:\r
+ """\\r
+ Value type of our sample PyObjectProperty. We keep a simple dash-delimited\r
+ list of string given as argument to constructor.\r
+ """\r
+ def __init__(self, s=None):\r
+ try:\r
+ self.ls = [a.strip() for a in s.split('-')]\r
+ except:\r
+ self.ls = []\r
+\r
+ def __repr__(self):\r
+ return ' - '.join(self.ls)\r
+\r
+\r
+\r
+class PyObjectProperty(wxpg.PyProperty):\r
+ """\\r
+ Another simple example. This time our value is a PyObject (NOTE: we can't\r
+ return an arbitrary python object in DoGetValue. It cannot be a simple\r
+ type such as int, bool, double, or string, nor an array or wxObject based.\r
+ Dictionary, None, or any user-specified Python object is allowed).\r
+ """\r
+ def __init__(self, label, name = wxpg.LABEL_AS_NAME, value=None):\r
+ wxpg.PyProperty.__init__(self, label, name)\r
+ self.SetValue(value)\r
+\r
+ def GetClassName(self):\r
+ return self.__class__.__name__\r
+\r
+ def GetEditor(self):\r
+ return "TextCtrl"\r
+\r
+ def GetValueAsString(self, flags):\r
+ return repr(self.GetValue())\r
+\r
+ def PyStringToValue(self, s, flags):\r
+ return PyObjectPropertyValue(s)\r
+\r
+\r
+class ShapeProperty(wxpg.PyEnumProperty):\r
+ """\\r
+ Demonstrates use of OnCustomPaint method.\r
+ """\r
+ def __init__(self, label, name = wxpg.LABEL_AS_NAME, value=-1):\r
+ wxpg.PyEnumProperty.__init__(self, label, name, ['Line','Circle','Rectangle'], [0,1,2], value)\r
+\r
+ def OnMeasureImage(self, index):\r
+ return wxpg.DEFAULT_IMAGE_SIZE\r
+\r
+ def OnCustomPaint(self, dc, rect, paint_data):\r
+ """\\r
+ paint_data.m_choiceItem is -1 if we are painting the control,\r
+ in which case we need to get the drawn item using DoGetValue.\r
+ """\r
+ item = paint_data.m_choiceItem\r
+ if item == -1:\r
+ item = self.DoGetValue()\r
+\r
+ dc.SetPen(wx.Pen(wx.BLACK))\r
+ dc.SetBrush(wx.Brush(wx.BLACK))\r
+\r
+ if item == 0:\r
+ dc.DrawLine(rect.x,rect.y,rect.x+rect.width,rect.y+rect.height)\r
+ elif item == 1:\r
+ half_width = rect.width / 2\r
+ dc.DrawCircle(rect.x+half_width,rect.y+half_width,half_width-3)\r
+ elif item == 2:\r
+ dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\r
+\r
+\r
+class LargeImagePickerCtrl(wx.Window):\r
+ """\\r
+ Control created and used by LargeImageEditor.\r
+ """\r
+ def __init__(self):\r
+ pre = wx.PreWindow()\r
+ self.PostCreate(pre)\r
+\r
+ def Create(self, parent, id_, pos, size, style = 0):\r
+ wx.Window.Create(self, parent, id_, pos, size, style | wx.BORDER_SIMPLE)\r
+ img_spc = size[1]\r
+ self.tc = wx.TextCtrl(self, -1, "", (img_spc,0), (2048,size[1]), wx.BORDER_NONE)\r
+ self.SetBackgroundColour(wx.WHITE)\r
+ self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)\r
+ self.property = None\r
+ self.bmp = None\r
+ self.Bind(wx.EVT_PAINT, self.OnPaint)\r
+\r
+ def OnPaint(self, event):\r
+ dc = wx.BufferedPaintDC(self)\r
+\r
+ whiteBrush = wx.Brush(wx.WHITE)\r
+ dc.SetBackground(whiteBrush)\r
+ dc.Clear()\r
+\r
+ bmp = self.bmp\r
+ if bmp:\r
+ dc.DrawBitmap(bmp, 2, 2)\r
+ else:\r
+ dc.SetPen(wx.Pen(wx.BLACK))\r
+ dc.SetBrush(whiteBrush)\r
+ dc.DrawRectangle(2, 2, 64, 64)\r
+\r
+ def RefreshThumbnail(self):\r
+ """\\r
+ We use here very simple image scaling code.\r
+ """\r
+ if not self.property:\r
+ self.bmp = None\r
+ return\r
+\r
+ path = self.property.DoGetValue()\r
+\r
+ if not os.path.isfile(path):\r
+ self.bmp = None\r
+ return\r
+\r
+ image = wx.Image(path)\r
+ image.Rescale(64, 64)\r
+ self.bmp = wx.BitmapFromImage(image)\r
+\r
+ def SetProperty(self, property):\r
+ self.property = property\r
+ self.tc.SetValue(property.GetDisplayedString())\r
+ self.RefreshThumbnail()\r
+\r
+ def SetValue(self, s):\r
+ self.RefreshThumbnail()\r
+ self.tc.SetValue(s)\r
+\r
+ def GetLastPosition(self):\r
+ return self.tc.GetLastPosition()\r
+\r
+\r
+class LargeImageEditor(wxpg.PyEditor):\r
+ """\\r
+ Double-height text-editor with image in front.\r
+ """\r
+ def __init__(self):\r
+ wxpg.PyEditor.__init__(self)\r
+\r
+ def CreateControls(self, propgrid, property, pos, sz):\r
+ try:\r
+ h = 64 + 6\r
+ x = propgrid.GetSplitterPosition()\r
+ x2 = propgrid.GetClientSize().x\r
+ bw = propgrid.GetRowHeight()\r
+ lipc = LargeImagePickerCtrl()\r
+ if sys.platform == 'win32':\r
+ lipc.Hide()\r
+ lipc.Create(propgrid, wxpg.PG_SUBID1, (x,pos[1]), (x2-x-bw,h))\r
+ lipc.SetProperty(property)\r
+ # Hmmm.. how to have two-stage creation without subclassing?\r
+ #btn = wx.PreButton()\r
+ #pre = wx.PreWindow()\r
+ #self.PostCreate(pre)\r
+ #if sys.platform == 'win32':\r
+ # btn.Hide()\r
+ #btn.Create(propgrid, wxpg.PG_SUBID2, '...', (x2-bw,pos[1]), (bw,h), wx.WANTS_CHARS)\r
+ btn = wx.Button(propgrid, wxpg.PG_SUBID2, '...', (x2-bw,pos[1]), (bw,h), wx.WANTS_CHARS)\r
+ return (lipc, btn)\r
+ except:\r
+ import traceback\r
+ print traceback.print_exc()\r
+\r
+ def UpdateControl(self, property, ctrl):\r
+ ctrl.SetValue(property.GetDisplayedString())\r
+\r
+ def DrawValue(self, dc, property, rect):\r
+ if not (property.GetFlags() & wxpg.PG_PROP_UNSPECIFIED):\r
+ dc.DrawText( property.GetDisplayedString(), rect.x+5, rect.y );\r
+\r
+ def OnEvent(self, propgrid, ctrl, event):\r
+ if not ctrl:\r
+ return False\r
+\r
+ evtType = event.GetEventType()\r
+\r
+ if evtType == wx.wxEVT_COMMAND_TEXT_ENTER:\r
+ if propgrid.IsEditorsValueModified():\r
+ return True\r
+\r
+ elif evtType == wx.wxEVT_COMMAND_TEXT_UPDATED:\r
+ if not property.HasFlag(wxpg.PG_PROP_UNSPECIFIED) or not ctrl or \\r
+ ctrl.GetLastPosition() > 0:\r
+\r
+ # We must check this since an 'empty' text event\r
+ # may be triggered when creating the property.\r
+ PG_FL_IN_SELECT_PROPERTY = 0x00100000\r
+ if not (propgrid.GetInternalFlags() & PG_FL_IN_SELECT_PROPERTY):\r
+ event.Skip();\r
+ event.SetId(propGrid.GetId());\r
+\r
+ propgrid.EditorsValueWasModified();\r
+\r
+ return False\r
+\r
+\r
+ def CopyValueFromControl(self, property, ctrl):\r
+ tc = ctrl.tc\r
+ res = property.SetValueFromString(tc.GetValue(),0)\r
+ # Changing unspecified always causes event (returning\r
+ # true here should be enough to trigger it).\r
+ if not res and property.IsFlagSet(wxpg.PG_PROP_UNSPECIFIED):\r
+ res = true\r
+\r
+ return res\r
+\r
+ def SetValueToUnspecified(self, ctrl):\r
+ ctrl.tc.Remove(0,len(ctrl.tc.GetValue()));\r
+\r
+ def SetControlStringValue(self, ctrl, txt):\r
+ ctrl.SetValue(txt)\r
+\r
+ def OnFocus(self, property, ctrl):\r
+ ctrl.tc.SetSelection(-1,-1)\r
+ ctrl.tc.SetFocus()\r
+\r
+\r
+class PropertyEditor(wx.Panel):\r
+\r
+ def __init__(self, parent):\r
+ # Use the WANTS_CHARS style so the panel doesn't eat the Return key.\r
+ wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS, size=(160, 200))\r
+\r
+ sizer = wx.BoxSizer(wx.VERTICAL)\r
+\r
+ self.pg = wxpg.PropertyGrid(self, style=wxpg.PG_SPLITTER_AUTO_CENTER|wxpg.PG_AUTO_SORT)\r
+\r
+ # Show help as tooltips\r
+ self.pg.SetExtraStyle(wxpg.PG_EX_HELP_AS_TOOLTIPS)\r
+\r
+ #pg.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChange)\r
+ #pg.Bind(wxpg.EVT_PG_SELECTED, self.OnPropGridSelect)\r
+ #self.pg.Bind(wxpg.EVT_PG_RIGHT_CLICK, self.OnPropGridRightClick)\r
+\r
+ # Needed by custom image editor\r
+ wx.InitAllImageHandlers()\r
+\r
+ #\r
+ # Let's create a simple custom editor\r
+ #\r
+ # NOTE: Editor must be registered *before* adding a property that uses it.\r
+ self.pg.RegisterEditor(LargeImageEditor)\r
+\r
+ '''\r
+ #\r
+ # Add properties\r
+ #\r
+\r
+ pg.Append( wxpg.PropertyCategory("1 - Basic Properties") )\r
+ pg.Append( wxpg.StringProperty("String",value="Some Text") )\r
+ pg.Append( wxpg.IntProperty("Int",value=100) )\r
+ pg.Append( wxpg.FloatProperty("Float",value=100.0) )\r
+ pg.Append( wxpg.BoolProperty("Bool",value=True) )\r
+ pg.Append( wxpg.BoolProperty("Bool_with_Checkbox",value=True) )\r
+ pg.SetPropertyAttribute("Bool_with_Checkbox", "UseCheckbox", True)\r
+\r
+ pg.Append( wxpg.PropertyCategory("2 - More Properties") )\r
+ pg.Append( wxpg.LongStringProperty("LongString",value="This is a\\nmulti-line string\\nwith\\ttabs\\nmixed\\tin.") )\r
+ pg.Append( wxpg.DirProperty("Dir",value="C:\\Windows") )\r
+ pg.Append( wxpg.FileProperty("File",value="C:\\Windows\\system.ini") )\r
+ pg.Append( wxpg.ArrayStringProperty("ArrayString",value=['A','B','C']) )\r
+\r
+ pg.Append( wxpg.EnumProperty("Enum","Enum",\r
+ ['wxPython Rules','wxPython Rocks','wxPython Is The Best'],\r
+ [10,11,12],0) )\r
+ pg.Append( wxpg.EditEnumProperty("EditEnum","EditEnumProperty",['A','B','C'],[0,1,2],"Text Not in List") )\r
+\r
+ pg.Append( wxpg.PropertyCategory("3 - Advanced Properties") )\r
+ pg.Append( wxpg.DateProperty("Date",value=wx.DateTime_Now()) )\r
+ pg.Append( wxpg.FontProperty("Font",value=self.GetFont()) )\r
+ pg.Append( wxpg.ColourProperty("Colour",value=self.GetBackgroundColour()) )\r
+ pg.Append( wxpg.SystemColourProperty("SystemColour") )\r
+ pg.Append( wxpg.ImageFileProperty("ImageFile") )\r
+ pg.Append( wxpg.MultiChoiceProperty("MultiChoice",choices=['wxWidgets','QT','GTK+']) )\r
+\r
+ pg.Append( wxpg.PropertyCategory("4 - Additional Properties") )\r
+ pg.Append( wxpg.PointProperty("Point",value=self.GetPosition()) )\r
+ pg.Append( wxpg.SizeProperty("Size",value=self.GetSize()) )\r
+ pg.Append( wxpg.FontDataProperty("FontData") )\r
+ pg.Append( wxpg.IntProperty("IntWithSpin",value=256) )\r
+ pg.SetPropertyEditor("IntWithSpin","SpinCtrl")\r
+ pg.Append( wxpg.DirsProperty("Dirs",value=['C:/Lib','C:/Bin']) )\r
+ pg.SetPropertyHelpString( "String", "String Property help string!" )\r
+ pg.SetPropertyHelpString( "Dirs", "Dirs Property help string!" )\r
+\r
+ pg.SetPropertyAttribute( "File", wxpg.PG_FILE_SHOW_FULL_PATH, 0 )\r
+ pg.SetPropertyAttribute( "File", wxpg.PG_FILE_INITIAL_PATH, "C:\\Program Files\\Internet Explorer" )\r
+ pg.SetPropertyAttribute( "Date", wxpg.PG_DATE_PICKER_STYLE, wx.DP_DROPDOWN|wx.DP_SHOWCENTURY )\r
+\r
+ pg.Append( wxpg.PropertyCategory("5 - Custom Properties") )\r
+ pg.Append( IntProperty2("IntProperty2", value=1024) )\r
+\r
+ pg.Append( ShapeProperty("ShapeProperty", value=0) )\r
+ pg.Append( PyObjectProperty("PyObjectProperty") )\r
+\r
+ pg.Append( wxpg.ImageFileProperty("ImageFileWithLargeEditor") )\r
+ pg.SetPropertyEditor("ImageFileWithLargeEditor", "LargeImageEditor")\r
+\r
+\r
+ pg.SetPropertyClientData( "Point", 1234 )\r
+ if pg.GetPropertyClientData( "Point" ) != 1234:\r
+ raise ValueError("Set/GetPropertyClientData() failed")\r
+\r
+ # Test setting unicode string\r
+ pg.GetPropertyByName("String").SetValue(u"Some Unicode Text")\r
+\r
+ #\r
+ # Test some code that *should* fail (but not crash)\r
+ #try:\r
+ #a_ = pg.GetPropertyValue( "NotARealProperty" )\r
+ #pg.EnableProperty( "NotAtAllRealProperty", False )\r
+ #pg.SetPropertyHelpString( "AgaintNotARealProperty", "Dummy Help String" )\r
+ #except:\r
+ #pass\r
+ #raise\r
+\r
+ '''\r
+ sizer.Add(self.pg, 1, wx.EXPAND)\r
+ self.SetSizer(sizer)\r
+ sizer.SetSizeHints(self)\r
+\r
+ self.SelectedTreeItem = None\r
+\r
+ def GetPropertyValues(self):\r
+ #return self.pg.GetPropertyValues(as_strings=True)\r
+ return self.pg.GetPropertyValues()\r
+\r
+\r
+ def Initialize(self, properties):\r
+ pg = self.pg\r
+ pg.Clear()\r
+\r
+ if properties:\r
+ for element in properties:\r
+ if element[1]['type'] == 'integer':\r
+ if 'value' in element[1]:\r
+ property_value = element[1].as_int('value')\r
+ else:\r
+ property_value = element[1].as_int('default')\r
+ property_control = wxpg.IntProperty(element[0], value=property_value)\r
+ if 'maximum' in element[1]:\r
+ property_control.SetAttribute('Max', element[1].as_int('maximum'))\r
+ if 'minimum' in element[1]:\r
+ property_control.SetAttribute('Min', element[1].as_int('minimum'))\r
+ property_control.SetAttribute('Wrap', True)\r
+ pg.Append(property_control)\r
+ pg.SetPropertyEditor(element[0], 'SpinCtrl')\r
+\r
+ if element[1]['type'] == 'float':\r
+ if 'value' in element[1]:\r
+ property_value = element[1].as_float('value')\r
+ else:\r
+ property_value = element[1].as_float('default')\r
+ property_control = wxpg.FloatProperty(element[0], value=property_value)\r
+ if 'maximum' in element[1]:\r
+ property_control.SetAttribute('Max', element[1].as_float('maximum'))\r
+ if 'minimum' in element[1]:\r
+ property_control.SetAttribute('Min', element[1].as_float('minimum'))\r
+ property_control.SetAttribute('Wrap', True)\r
+ pg.Append(property_control)\r
+ pg.SetPropertyEditor(element[0], 'SpinCtrl')\r
+\r
+ if element[1]['type'] == 'boolean':\r
+ if 'value' in element[1]:\r
+ property_value = element[1].as_bool('value')\r
+ else:\r
+ property_value = element[1].as_bool('default')\r
+ property_control = wxpg.BoolProperty(element[0], value=property_value)\r
+ pg.Append(property_control)\r
+ pg.SetPropertyAttribute(element[0], 'UseCheckbox', True)\r
+ if element[1]['type'] == 'string':\r
+ if 'value' in element[1]:\r
+ property_value = element[1]['value']\r
+ else:\r
+ property_value = element[1]['default']\r
+ pg.Append(wxpg.StringProperty(element[0], value=property_value))\r
+ if element[1]['type'] == 'folder':\r
+ if 'value' in element[1]:\r
+ property_value = element[1]['value']\r
+ else:\r
+ property_value = element[1]['default']\r
+ pg.Append(wxpg.DirProperty(element[0], value=property_value))\r
+ if element[1]['type'] == 'filename':\r
+ if 'value' in element[1]:\r
+ property_value = element[1]['value']\r
+ else:\r
+ property_value = element[1]['default']\r
+ pg.Append(wxpg.FileProperty(element[0], value=property_value))\r
+ #if element[0] == 'category':\r
+ #pg.Append(wxpg.PropertyCategory(element[1]))\r
+ #if element[0] == 'folder':\r
+ #pg.Append(wxpg.DirProperty(element[1], value=element[2]))\r
+ #if element[0] == 'string':\r
+ #pg.Append(wxpg.StringProperty(element[1], value=element[2]))\r
+\r
+ pg.Refresh()\r
+\r
+ def OnReserved(self, event):\r
+ pass\r
+\r
+\r
+#---------------------------------------------------------------------------\r
+\r
+\r
+class MemoDialog(wx.Dialog):\r
+ """\\r
+ Dialog for multi-line text editing.\r
+ """\r
+ def __init__(self, parent=None, title='', text='', pos=None, size=(500,500)):\r
+ wx.Dialog.__init__(self, parent, -1, title, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)\r
+\r
+ sizer = wx.BoxSizer(wx.VERTICAL)\r
+\r
+ tc = wx.TextCtrl(self, 11, text, style=wx.TE_MULTILINE)\r
+ self.tc = tc\r
+ topsizer.Add(tc,1,wx.EXPAND|wx.ALL,8)\r
+\r
+ rowsizer = wx.BoxSizer( wx.HORIZONTAL )\r
+ rowsizer.Add(wx.Button(self,wx.ID_OK,'Ok'),0,wx.ALIGN_RIGHT|wx.ALIGN_CENTRE_VERTICAL,8)\r
+ rowsizer.Add((0,0),1,wx.ALIGN_RIGHT|wx.ALIGN_CENTRE_VERTICAL,8)\r
+ rowsizer.Add(wx.Button(self,wx.ID_CANCEL,'Cancel'),0,wx.ALIGN_RIGHT|wx.ALIGN_CENTRE_VERTICAL,8)\r
+ topsizer.Add(rowsizer,0,wx.EXPAND|wx.ALL,8)\r
+\r
+ self.SetSizer( topsizer )\r
+ topsizer.Layout()\r
+\r
+ self.SetSize( size )\r
+ if not pos:\r
+ self.CenterOnScreen()\r
+ else:\r
+ self.Move(pos)\r
+\r
+\r
+#---------------------------------------------------------------------------\r
--- /dev/null
+#!/usr/bin/env python\r
+\r
+import sys\r
+import wx\r
+from wx.lib.mixins.listctrl import CheckListCtrlMixin\r
+\r
+import prettyformat\r
+\r
+class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin):\r
+ def __init__(self, parent):\r
+ wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)\r
+ CheckListCtrlMixin.__init__(self)\r
+ self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)\r
+\r
+ def OnItemActivated(self, evt):\r
+ self.ToggleItem(evt.m_itemIndex)\r
+\r
+\r
+class Results(wx.Panel):\r
+ def __init__(self, parent):\r
+ wx.Panel.__init__(self, parent, -1)\r
+ self.results_list = CheckListCtrl(self)\r
+ sizer = wx.BoxSizer()\r
+ sizer.Add(self.results_list, 1, wx.EXPAND)\r
+ self.SetSizer(sizer)\r
+ self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.results_list)\r
+ self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected, self.results_list)\r
+ #self.results_list.OnCheckItem = self.OnCheckItem\r
+\r
+ def _GetWidthInPixels(self, text):\r
+ #TODO:\r
+ #Returns the width of a string in pixels\r
+ #Unfortunately, it does not work terribly well (although it should).\r
+ #Thus, we have to add a bit afterwards.\r
+ #Annoys the heck out of me.\r
+ font = self.results_list.GetFont()\r
+ dc = wx.WindowDC(self.results_list)\r
+ dc.SetFont(font)\r
+ width, height = dc.GetTextExtent(text)\r
+ return width\r
+\r
+ def ClearResults(self):\r
+ self.results_list.ClearAll()\r
+\r
+ def DisplayResults(self, results):\r
+ self.ClearResults()\r
+ header = results.header_as_list()\r
+ self.results_list.InsertColumn(0, 'Show')\r
+ for index, column in enumerate(header):\r
+ self.results_list.InsertColumn(index + 1, column, wx.LIST_FORMAT_RIGHT)\r
+\r
+ for result in results.results:\r
+ done = False\r
+ for index, column in enumerate(results.columns):\r
+ value_str = results.get_pretty_value(column, result.result[column])\r
+ if not done:\r
+ index_col = self.results_list.InsertStringItem(sys.maxint, '')\r
+ done = True\r
+ column_width = len(self.results_list.GetColumn(index + 1).GetText())\r
+ value_str = value_str.center(column_width)\r
+ self.results_list.SetStringItem(index_col, index + 1, value_str)\r
+ #self.results_list.SetItemData(index, result)\r
+\r
+ for index, result in enumerate(results.results):\r
+ if result.visible:\r
+ #if we use 'CheckItem' then 'UpdatePlot' is called (ie repeated updates)\r
+ self.results_list.SetItemImage(index, 1)\r
+ #self.results_list.CheckItem(index)\r
+ for index in range(self.results_list.GetColumnCount()):\r
+ column_text = self.results_list.GetColumn(index).GetText()\r
+ column_width = self._GetWidthInPixels(column_text)\r
+ self.results_list.SetColumnWidth(index, column_width + 15)\r
+\r
+ def OnItemSelected(self, evt):\r
+ pass\r
+\r
+ def OnItemDeselected(self, evt):\r
+ pass\r
--- /dev/null
+layout2|name=Folders;caption=Folders;state=33818620;dir=4;layer=0;row=0;pos=0;prop=100000;bestw=196;besth=246;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=Playlists;caption=Playlists;state=33818620;dir=4;layer=0;row=0;pos=1;prop=100000;bestw=160;besth=250;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=Plots;caption=;state=256;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=430;besth=200;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=Commands;caption=Settings and commands;state=33818620;dir=2;layer=0;row=0;pos=0;prop=100000;bestw=160;besth=273;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=Properties;caption=Properties;state=33818620;dir=2;layer=0;row=0;pos=1;prop=100000;bestw=60;besth=58;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=Assistant;caption=Assistant;state=33818620;dir=2;layer=0;row=0;pos=2;prop=100000;bestw=133;besth=90;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=Output;caption=Output;state=33818620;dir=3;layer=0;row=0;pos=0;prop=100000;bestw=133;besth=90;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=Results;caption=Results;state=33818620;dir=3;layer=0;row=0;pos=1;prop=100000;bestw=20;besth=20;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=toolbar;caption=Toolbar;state=33827568;dir=1;layer=1;row=1;pos=0;prop=100000;bestw=100;besth=23;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|name=toolbarNavigation;caption=Navigation;state=33827568;dir=1;layer=1;row=1;pos=111;prop=100000;bestw=46;besth=23;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1;notebookid=-1;transparent=255|dock_size(4,0,0)=198|dock_size(5,0,0)=325|dock_size(2,0,0)=162|dock_size(3,0,0)=111|dock_size(1,1,1)=25|
\ No newline at end of file
--- /dev/null
+'''\r
+//\r
+// prettyformat.py - simple Python function to format values with nice prefixes\r
+// Version 1.0.1\r
+//\r
+// History\r
+// 2009 07 16: added negative number support\r
+// added decimal-formatted output\r
+//\r
+// Copyright (c) 2009 Rolf Schmidt, Montreal\r
+// rschmidt@alcor.concordia.ca\r
+//\r
+// This procedure is released under the GNU General Public License version 2\r
+//\r
+'''\r
+\r
+import math\r
+from numpy import isnan\r
+\r
+def pretty_format(fValue, sUnit='', iDecimals=-1, iMultiplier=1, bLeadingSpaces=False):\r
+ if fValue != 0:\r
+ iLeadingSpaces = 0\r
+ if bLeadingSpaces:\r
+ iLeadingSpaces = 5\r
+ if iMultiplier == 1:\r
+ iMultiplier=get_multiplier(fValue)\r
+ sUnitString = ''\r
+ if sUnit != '':\r
+ sUnitString = ' ' + get_prefix(iMultiplier) + sUnit\r
+ if iDecimals >= 0:\r
+ formatString = '% ' + repr(iLeadingSpaces + iDecimals) + '.' + repr(iDecimals) + 'f'\r
+ return formatString % (fValue / iMultiplier) + sUnitString\r
+ else:\r
+ return str(fValue / iMultiplier) + sUnitString\r
+ else:\r
+ return '0'\r
+ return str(fValue / iMultiplier) + ' ' + get_prefix(fValue / iMultiplier) + sUnit\r
+\r
+def get_multiplier(fValue):\r
+ return pow(10, get_power(fValue))\r
+\r
+def get_power(fValue):\r
+ if fValue != 0 and not isnan(fValue):\r
+ #get the log10 from fValue (make sure the value is not negative)\r
+ dHelp = math.floor(math.log10(math.fabs(fValue)))\r
+ #reduce the log10 to a multiple of 3 and return it\r
+ return dHelp-(dHelp % 3)\r
+ else:\r
+ return 0\r
+\r
+def get_prefix(fValue):\r
+ #set up a dictionary to find the prefix\r
+ prefix = {\r
+ 24: lambda: 'Y',\r
+ 21: lambda: 'Z',\r
+ 18: lambda: 'E',\r
+ 15: lambda: 'P',\r
+ 12: lambda: 'T',\r
+ 9: lambda: 'G',\r
+ 6: lambda: 'M',\r
+ 3: lambda: 'k',\r
+ 0: lambda: '',\r
+ -3: lambda: 'm',\r
+ -6: lambda: u'\u00B5',\r
+ -9: lambda: 'n',\r
+ -12: lambda: 'p',\r
+ -15: lambda: 'f',\r
+ -18: lambda: 'a',\r
+ -21: lambda: 'z',\r
+ -24: lambda: 'y',\r
+ }\r
+ if fValue != 0 and not isnan(fValue):\r
+ #get the log10 from fValue\r
+ dHelp = math.floor(math.log10(math.fabs(fValue)))\r
+ else:\r
+ dHelp = 0\r
+ #reduce the log10 to a multiple of 3 and create the return string\r
+ return prefix.get(dHelp - (dHelp % 3))()\r
+\r
+'''\r
+dTestValue=-2.4115665714484597e-008\r
+print 'Value: '+str(dTestValue)+')'\r
+print 'pretty_format example (value, unit)'\r
+print pretty_format(dTestValue, 'N')\r
+print'-----------------------'\r
+print 'pretty_format example (value, unit, decimals)'\r
+print pretty_format(dTestValue, 'N', 3)\r
+print'-----------------------'\r
+print 'pretty_format example (value, unit, decimals, multiplier)'\r
+print pretty_format(dTestValue, 'N', 5, 0.000001)\r
+print'-----------------------'\r
+print 'pretty_format example (value, unit, decimals, multiplier, leading spaces)'\r
+print pretty_format(0.0166276297705, 'N', 3, 0.001, True)\r
+print pretty_format(0.00750520813323, 'N', 3, 0.001, True)\r
+print pretty_format(0.0136453282825, 'N', 3, 0.001, True)\r
+'''\r
+'''\r
+#example use autoFormatValue\r
+dTestValue=0.00000000567\r
+print 'autoFormatValue example ('+str(dTestValue)+')'\r
+print autoFormatValue(dTestValue, 'N')\r
+#outputs 5.67 nN\r
+'''\r
+'''\r
+#example use of decimalFormatValue(fValue, iDecimals, sUnit):\r
+dTestValue=-2.4115665714484597e-008\r
+iDecimals=3\r
+print 'decimalFormatValue example ('+str(dTestValue)+')'\r
+print decimalFormatValue(dTestValue, iDecimals, 'N')\r
+#outputs -24.116 nN\r
+#change iDecimals to see the effect\r
+'''\r
+'''\r
+#example use formatValue\r
+dTestValue=0.000000000567\r
+print 'formatValue example ('+str(dTestValue)+')'\r
+#find the (common) multiplier\r
+iMultiplier=get_multiplier(dTestValue)\r
+#use the multiplier and a unit to format the value\r
+print formatValue(dTestValue, iMultiplier, 'N')\r
+#outputs 567.0 pN\r
+'''\r
+'''\r
+#to output a scale:\r
+#choose any value on the axis and find the multiplier and prefix for it\r
+#use those to format the rest of the scale\r
+#as values can span several orders of magnitude, you have to decide what units to use\r
+\r
+#tuple of values:\r
+scaleValues=0.000000000985, 0.000000001000, 0.000000001015\r
+#use this element (change to 1 or 2 to see the effect on the scale and label)\r
+iIndex=0\r
+#get the multiplier from the value at iIndex\r
+iMultiplier=get_multiplier(scaleValues[iIndex])\r
+print '\nScale example'\r
+iDecimals=3\r
+#print the scale\r
+for aValue in scaleValues: print decimalFormat(aValue/iMultiplier, iDecimals),\r
+#print the scale label using the value at iIndex\r
+print '\n'+get_prefix(scaleValues[iIndex])+'N'\r
+'''
\ No newline at end of file
--- /dev/null
+import prettyformat\r
+\r
+DEFAULT_COLOR = 'orange'\r
+DEFAULT_DECIMAL = 2\r
+DEFAULT_STYLE = 'plot'\r
+\r
+class Result:\r
+ def __init__(self):\r
+ self.color = DEFAULT_COLOR\r
+ self.result = {}\r
+ self.style = DEFAULT_STYLE\r
+ self.visible = True\r
+ self.x = []\r
+ self.y = []\r
+\r
+class Results:\r
+ def __init__(self):\r
+ self.columns = []\r
+ self.decimals = {}\r
+ self.has_multipliers = False\r
+ self.multipliers = {}\r
+ self.results = []\r
+ self.separator='\t'\r
+ self.units = {}\r
+\r
+ def get_pretty_value(self, column, value):\r
+ if self.has_multipliers and self.has_results():\r
+ multiplier = self.multipliers[column]\r
+ decimals = self.decimals[column]\r
+ return prettyformat.pretty_format(value, '', decimals, multiplier, True)\r
+ return str(value)\r
+\r
+ #def get_fit_result(self):\r
+ #if not(self.has_multipliers):\r
+ #self.set_multipliers()\r
+\r
+ #sResult = 'Contour length ['+prettyformat.get_prefix(self.multiplierContourLength) + 'm]' + self.separator\r
+ #sResult += prettyformat.pretty_format(self.contourLength[0], '', self.decimals, self.multiplierContourLength, True) + '\n'\r
+ #sResult += 'Persistence length ['+prettyformat.get_prefix(self.multiplierPersistenceLength) + 'm]' + self.separator\r
+ #sResult += prettyformat.pretty_format(self.persistenceLength[0], '', self.decimals, self.multiplierPersistenceLength, True) + '\n'\r
+ #sResult += 'Rupture force ['+prettyformat.get_prefix(self.multiplierRuptureForce) + 'N]' + self.separator\r
+ #sResult += prettyformat.pretty_format(self.ruptureForces[0], '', self.decimals, self.multiplierRuptureForce, True) + '\n'\r
+ #sResult += 'Loading rate ['+prettyformat.get_prefix(self.multiplierSlope) + 'N/m]' + self.separator\r
+ #sResult += prettyformat.pretty_format(self.slopes[0], '', self.decimals, self.multiplierSlope, True)+'\n'\r
+ #sResult += 'Sigma contour ['+prettyformat.get_prefix(self.multiplierContourLength) + 'm]' + self.separator\r
+ #sResult += prettyformat.pretty_format(self.contourLengthSigma[0], '', self.decimals, self.multiplierContourLength, True) + '\n'\r
+ #sResult += 'Sigma persistence ['+prettyformat.get_prefix(self.multiplierPersistenceLength) + 'm]' + self.separator\r
+ #sResult += prettyformat.pretty_format(self.persistenceLengthSigma[0], '', self.decimals, self.multiplierPersistenceLength, True)\r
+\r
+ #return sResult\r
+\r
+ #def get_fit_results(self, index):\r
+ #if index >= 0 and index < len(self.contourLength):\r
+ #if not(self.has_multipliers):\r
+ #self.set_multipliers()\r
+ #sLine = prettyformat.pretty_format(self.contourLength[index], '', self.decimals, self.multiplierContourLength, True) + self.separator\r
+ #sLine += prettyformat.pretty_format(self.persistenceLength[index], '', self.decimals, self.multiplierPersistenceLength, True) + self.separator\r
+ #sLine += prettyformat.pretty_format(self.ruptureForces[index], '', self.decimals, self.multiplierRuptureForce, True) + self.separator\r
+ #sLine += prettyformat.pretty_format(self.slopes[index], '', self.decimals, self.multiplierSlope, True) + self.separator\r
+ #sLine += prettyformat.pretty_format(self.contourLengthSigma[index], '', self.decimals, self.multiplierContourLength, True) + self.separator\r
+ #sLine += prettyformat.pretty_format(self.persistenceLengthSigma[index], '', self.decimals, self.multiplierPersistenceLength, True)\r
+\r
+ #return sLine\r
+ #else:\r
+ #return ''\r
+\r
+ def has_results(self):\r
+ return self.results\r
+\r
+ def header_as_list(self):\r
+ header = []\r
+ if self.has_results():\r
+ if not self.has_multipliers:\r
+ self.set_multipliers()\r
+ for column in self.columns:\r
+ #result will contain the results dictionary for 'column'\r
+ #result = self.results[0][0][column]\r
+ #result[1] contains the unit\r
+ unit_str = ''.join([prettyformat.get_prefix(self.multipliers[column]), self.units[column]])\r
+ header_str = ''.join([column, ' [', unit_str, ']'])\r
+ header.append(header_str)\r
+ return header\r
+\r
+ #def header_as_str(self):\r
+ #if self.has_results():\r
+ #if not self.has_multipliers:\r
+ #self.set_multipliers()\r
+ #header_str = ''\r
+ #for column in self.columns:\r
+ ##result will contain the results dictionary for 'column'\r
+ #result = self.results[0][0][column]\r
+ ##result[1] contains the unit\r
+ #unit_str = ''.join([prettyformat.get_prefix(self.multipliers[column]), result[1]])\r
+ #header_str = ''.join([header_str, result_str, ' [', unit_str, ']', self.separator])\r
+ #return header_str\r
+ #else:\r
+ #return None\r
+\r
+ def set_decimal(self, column, decimal=DEFAULT_DECIMAL):\r
+ if self.decimals.has_key(name):\r
+ self.decimals[name] = decimal\r
+\r
+ def set_decimals(self, decimals=DEFAULT_DECIMAL):\r
+ if decimals < 0:\r
+ #set default value if necessary\r
+ decimals = DEFAULT_DECIMAL\r
+ for column in self.columns:\r
+ self.decimals[column] = decimals\r
+\r
+ def set_multipliers(self, index=0):\r
+ if self.has_results():\r
+ if index >= 0 and index < len(self.results):\r
+ for column in self.columns:\r
+ #result will contain the results dictionary at 'index'\r
+ result = self.results[index][0]\r
+ #in position 0 of the result we find the value\r
+ self.multipliers[column] = prettyformat.get_multiplier(result[column][0])\r
+ self.has_multipliers = True\r
+ else:\r
+ self.has_multipliers = False\r
+\r
+\r
+class ResultsWLC(Results):\r
+ def __init__(self):\r
+ Results.__init__(self)\r
+ self.columns = ['Contour length', 'sigma contour length', 'Persistence length', 'sigma persistence length', 'Rupture force', 'Loading rate']\r
+ self.units['Contour length'] = 'm'\r
+ self.units['sigma contour length'] = 'm'\r
+ self.units['Persistence length'] = 'm'\r
+ self.units['sigma persistence length'] = 'm'\r
+ self.units['Rupture force'] = 'N'\r
+ self.units['Loading rate'] = 'N/m'\r
+ self.set_decimals(2)\r
+\r
+ def set_multipliers(self, index=0):\r
+ if self.has_results():\r
+ if index >= 0 and index < len(self.results):\r
+ for column in self.columns:\r
+ #result will contain the results dictionary at 'index'\r
+ result = self.results[index].result\r
+ #in position 0 of the result we find the value\r
+ if column == 'sigma contour length':\r
+ self.multipliers[column] = self.multipliers['Contour length']\r
+ elif column == 'sigma persistence length':\r
+ self.multipliers[column] = self.multipliers['Persistence length']\r
+ else:\r
+ self.multipliers[column] = prettyformat.get_multiplier(result[column])\r
+ self.has_multipliers = True\r
+ else:\r
+ self.has_multipliers = False\r